diff --git a/.github/agents/agentic-workflows.agent.md b/.github/agents/agentic-workflows.md similarity index 57% rename from .github/agents/agentic-workflows.agent.md rename to .github/agents/agentic-workflows.md index 7ed300e00c..08c6d9a24f 100644 --- a/.github/agents/agentic-workflows.agent.md +++ b/.github/agents/agentic-workflows.md @@ -1,5 +1,6 @@ --- -description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing +name: Agentic Workflows +description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing. disable-model-invocation: true --- @@ -7,18 +8,29 @@ disable-model-invocation: true This agent helps you work with **GitHub Agentic Workflows (gh-aw)**, a CLI extension for creating AI-powered workflows in natural language using markdown files. +## Repository Instructions Overlay + +If `.github/aw/instructions.md` exists, load it with: +@.github/aw/instructions.md + +Precedence: repository overlay instructions override defaults in this agent when they conflict. + ## What This Agent Does This is a **dispatcher agent** that routes your request to the appropriate specialized prompt based on your task: - **Creating new workflows**: Routes to `create` prompt - **Updating existing workflows**: Routes to `update` prompt -- **Debugging workflows**: Routes to `debug` prompt +- **Debugging workflows**: Routes to `debug` prompt - **Upgrading workflows**: Routes to `upgrade-agentic-workflows` prompt - **Creating report-generating workflows**: Routes to `report` prompt — consult this whenever the workflow posts status updates, audits, analyses, or any structured output as issues, discussions, or comments - **Creating shared components**: Routes to `create-shared-agentic-workflow` prompt - **Fixing Dependabot PRs**: Routes to `dependabot` prompt — use this when Dependabot opens PRs that modify generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`). Never merge those PRs directly; instead update the source `.md` files and rerun `gh aw compile --dependabot` to bundle all fixes - **Analyzing test coverage**: Routes to `test-coverage` prompt — consult this whenever the workflow reads, analyzes, or reports on test coverage data from PRs or CI runs +- **Rendering ASCII charts in markdown**: Routes to `asciicharts` guide — consult this whenever the workflow needs compact charts that render reliably in GitHub issues, comments, or discussions +- **CLI commands and triggering workflows**: Routes to `cli-commands` guide — consult this whenever the user asks how to run, compile, debug, or manage workflows from the command line, or when they need the MCP tool equivalent of a `gh aw` command +- **Reducing token consumption / cost optimization**: Routes to `token-optimization` guide — consult this whenever the user asks how to reduce token usage, lower costs, speed up workflows, or measure the impact of prompt changes with experiments +- **Choosing workflow architectures and design patterns**: Routes to `patterns` guide — consult this whenever the user asks for strategy, architecture, operating models, or pattern selection for agentic workflows Workflows may optionally include: @@ -30,7 +42,7 @@ Workflows may optionally include: - Workflow files: `.github/workflows/*.md` and `.github/workflows/**/*.md` - Workflow lock files: `.github/workflows/*.lock.yml` - Shared components: `.github/workflows/shared/*.md` -- Configuration: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/github-agentic-workflows.md +- Configuration: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md` ## Problems This Solves @@ -49,30 +61,32 @@ When you interact with this agent, it will: ## Available Prompts +> **Note**: The prompt and reference files listed below are located in the [`github/gh-aw`](https://github.com/github/gh-aw) repository and are **not available locally** in this repository. Load them from their public URLs. + ### Create New Workflow **Load when**: User wants to create a new workflow from scratch, add automation, or design a workflow that doesn't exist yet -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/create-agentic-workflow.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md` **Use cases**: - "Create a workflow that triages issues" - "I need a workflow to label pull requests" - "Design a weekly research automation" -### Update Existing Workflow +### Update Existing Workflow **Load when**: User wants to modify, improve, or refactor an existing workflow -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/update-agentic-workflow.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md` **Use cases**: - "Add web-fetch tool to the issue-classifier workflow" - "Update the PR reviewer to use discussions instead of issues" - "Improve the prompt for the weekly-research workflow" -### Debug Workflow +### Debug Workflow **Load when**: User needs to investigate, audit, debug, or understand a workflow, troubleshoot issues, analyze logs, or fix errors -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/debug-agentic-workflow.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md` **Use cases**: - "Why is this workflow failing?" @@ -82,7 +96,7 @@ When you interact with this agent, it will: ### Upgrade Agentic Workflows **Load when**: User wants to upgrade workflows to a new gh-aw version or fix deprecations -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/upgrade-agentic-workflows.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md` **Use cases**: - "Upgrade all workflows to the latest version" @@ -92,7 +106,7 @@ When you interact with this agent, it will: ### Create a Report-Generating Workflow **Load when**: The workflow being created or updated produces reports — recurring status updates, audit summaries, analyses, or any structured output posted as a GitHub issue, discussion, or comment -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/report.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md` **Use cases**: - "Create a weekly CI health report" @@ -102,7 +116,7 @@ When you interact with this agent, it will: ### Create Shared Agentic Workflow **Load when**: User wants to create a reusable workflow component or wrap an MCP server -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/create-shared-agentic-workflow.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md` **Use cases**: - "Create a shared component for Notion integration" @@ -112,7 +126,7 @@ When you interact with this agent, it will: ### Fix Dependabot PRs **Load when**: User needs to close or fix open Dependabot PRs that update dependencies in generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`) -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/dependabot.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md` **Use cases**: - "Fix the open Dependabot PRs for npm dependencies" @@ -122,19 +136,54 @@ When you interact with this agent, it will: ### Analyze Test Coverage **Load when**: The workflow reads, analyzes, or reports test coverage — whether triggered by a PR, a schedule, or a slash command. Always consult this prompt before designing the coverage data strategy. -**Prompt file**: https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/test-coverage.md +**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md` **Use cases**: - "Create a workflow that comments coverage on PRs" - "Analyze coverage trends over time" - "Add a coverage gate that blocks PRs below a threshold" +### CLI Commands Reference +**Load when**: The user asks how to run, compile, debug, or manage workflows from the command line; needs the MCP tool equivalent of a `gh aw` command; or is in a restricted environment (e.g., Copilot Cloud) without direct CLI access. + +**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md` + +**Use cases**: +- "How do I trigger workflow X on the main branch?" +- "What's the MCP equivalent of `gh aw logs`?" +- "I'm in Copilot Cloud — how do I compile a workflow?" +- "Show me all available gh aw commands" + +### Token Consumption Optimization +**Load when**: The user asks how to reduce token usage, lower workflow costs, make a workflow faster or cheaper, or measure the impact of prompt or configuration changes. + +**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md` + +**Use cases**: +- "How do I reduce the token cost of this workflow?" +- "My workflow is too expensive — how do I optimize it?" +- "How do I compare token usage between two runs?" +- "Should I use gh-proxy or the MCP server?" +- "How do I use sub-agents to reduce costs?" +- "How do I measure the impact of a prompt change?" + +### Workflow Pattern Selection +**Load when**: The user asks for architecture, strategy, operating model selection, or pattern recommendations for building agentic workflows. + +**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md` + +**Use cases**: +- "Which pattern should I use for multi-repo rollout?" +- "How should I structure this workflow architecture?" +- "What pattern fits slash-command triage?" +- "Should this be DispatchOps or DailyOps?" + ## Instructions When a user interacts with you: 1. **Identify the task type** from the user's request -2. **Load the appropriate prompt** from the GitHub repository URLs listed above +2. **Load the appropriate prompt** from the URLs listed above 3. **Follow the loaded prompt's instructions** exactly 4. **If uncertain**, ask clarifying questions to determine the right prompt @@ -147,6 +196,10 @@ gh aw init # Generate the lock file for a workflow gh aw compile [workflow-name] +# Trigger a workflow on demand (preferred over gh workflow run) +gh aw run # interactive input collection +gh aw run --ref main # run on a specific branch + # Debug workflow runs gh aw logs [workflow-name] gh aw audit @@ -169,10 +222,12 @@ gh aw compile --validate ## Important Notes -- Always reference the instructions file at https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/github-agentic-workflows.md for complete documentation +- Always reference the instructions file at `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md` for complete documentation - Use the MCP tool `agentic-workflows` when running in GitHub Copilot Cloud - Workflows must be compiled to `.lock.yml` files before running in GitHub Actions - **Bash tools are enabled by default** - Don't restrict bash commands unnecessarily since workflows are sandboxed by the AWF - Follow security best practices: minimal permissions, explicit network access, no template injection -- **Network configuration**: Use ecosystem identifiers (`node`, `python`, `go`, etc.) or explicit FQDNs in `network.allowed`. Bare shorthands like `npm` or `pypi` are **not** valid. See https://github.com/github/gh-aw/blob/v0.64.2/.github/aw/network.md for the full list of valid ecosystem identifiers and domain patterns. +- **Network configuration**: Use ecosystem identifiers (`node`, `python`, `go`, etc.) or explicit FQDNs in `network.allowed`. Bare shorthands like `npm` or `pypi` are **not** valid. See `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/network.md` for the full list of valid ecosystem identifiers and domain patterns. - **Single-file output**: When creating a workflow, produce exactly **one** workflow `.md` file. Do not create separate documentation files (architecture docs, runbooks, usage guides, etc.). If documentation is needed, add a brief `## Usage` section inside the workflow file itself. +- **Triggering runs**: Always use `gh aw run ` to trigger a workflow on demand — not `gh workflow run .lock.yml`. `gh aw run` handles workflow resolution by short name, input parsing and validation, and correct run-tracking for agentic workflows. Use `--ref ` to run on a specific branch. +- **CLI commands reference**: For a complete guide on all `gh aw` commands and their MCP tool equivalents (for restricted environments), see `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md` diff --git a/.github/aw/actions-lock.json b/.github/aw/actions-lock.json index 20f2503163..528dbe85c2 100644 --- a/.github/aw/actions-lock.json +++ b/.github/aw/actions-lock.json @@ -1,39 +1,34 @@ { "entries": { - "actions/checkout@v6.0.2": { + "actions/checkout@v7": { "repo": "actions/checkout", - "version": "v6.0.2", - "sha": "de0fac2e4500dabe0009e67214ff5f5447ce83dd" + "version": "v7", + "sha": "9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0" }, - "actions/download-artifact@v8.0.0": { + "actions/download-artifact@v8.0.1": { "repo": "actions/download-artifact", - "version": "v8.0.0", - "sha": "70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3" + "version": "v8.0.1", + "sha": "3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c" }, - "actions/github-script@v8": { + "actions/github-script@v9": { "repo": "actions/github-script", - "version": "v8", - "sha": "ed597411d8f924073f98dfc5c65a23a2325f34cd" + "version": "v9", + "sha": "373c709c69115d41ff229c7e5df9f8788daa9553" }, - "actions/github-script@v9.0.0": { - "repo": "actions/github-script", - "version": "v9.0.0", - "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" - }, - "actions/upload-artifact@v7.0.0": { + "actions/upload-artifact@v7.0.1": { "repo": "actions/upload-artifact", - "version": "v7.0.0", - "sha": "bbbca2ddaa5d8feaa63e36b76fdaad77386f024f" + "version": "v7.0.1", + "sha": "043fb46d1a93c77aae656e7c1c64a875d1fc6a0a" }, - "github/gh-aw-actions/setup@v0.77.5": { - "repo": "github/gh-aw-actions/setup", - "version": "v0.77.5", - "sha": "3ea13c02d765410340d533515cb31a7eef2baaf0" + "github/gh-aw-actions/setup-cli@v0.82.10": { + "repo": "github/gh-aw-actions/setup-cli", + "version": "v0.82.10", + "sha": "05205436a78512d71a2d842e46586ed05f4fa058" }, - "github/gh-aw/actions/setup@v0.52.1": { - "repo": "github/gh-aw/actions/setup", - "version": "v0.52.1", - "sha": "a86e657586e4ac5f549a790628971ec02f6a4a8f" + "github/gh-aw-actions/setup@v0.82.10": { + "repo": "github/gh-aw-actions/setup", + "version": "v0.82.10", + "sha": "05205436a78512d71a2d842e46586ed05f4fa058" } } } diff --git a/.github/badges/jacoco-generated.svg b/.github/badges/jacoco-generated.svg deleted file mode 100644 index bd7223a65f..0000000000 --- a/.github/badges/jacoco-generated.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - coverage generated - coverage generated - 72.7% - 72.7% - - diff --git a/.github/badges/jacoco-handwritten.svg b/.github/badges/jacoco-handwritten.svg deleted file mode 100644 index bfb6196f68..0000000000 --- a/.github/badges/jacoco-handwritten.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - coverage handwritten - coverage handwritten - 78.4% - 78.4% - - diff --git a/.github/instructions/dotnet-e2e.instructions.md b/.github/instructions/dotnet-e2e.instructions.md new file mode 100644 index 0000000000..8dcf7d5330 --- /dev/null +++ b/.github/instructions/dotnet-e2e.instructions.md @@ -0,0 +1,9 @@ +--- +applyTo: "dotnet/test/E2E/**/*.cs" +--- + +# .NET E2E test instructions + +- Create and resume sessions through `E2ETestContext` using `Ctx.CreateSessionAsync` and `Ctx.ResumeSessionAsync`. Do not call these methods directly on `CopilotClient`; the context applies the backend selected by the E2E matrix while preserving providers explicitly configured by the test. +- Create clients with `Ctx.CreateClient` so they receive the harness environment, CLI path, authentication defaults, transport handling, and lifecycle tracking. +- Instantiate `CopilotClient` directly only when client construction, startup, shutdown, or disposal is the behavior under test. Keep cleanup explicit in those tests, and still create any sessions through `Ctx` so they participate in backend coverage. diff --git a/.github/lsp.json b/.github/lsp.json index 7535212849..e58456ac43 100644 --- a/.github/lsp.json +++ b/.github/lsp.json @@ -21,24 +21,6 @@ ".go": "go" }, "rootUri": "go" - }, - "rust-analyzer": { - "command": "rust-analyzer", - "fileExtensions": { - ".rs": "rust" - }, - "initializationOptions": { - "cargo": { - "buildScripts": { - "enable": true - }, - "allFeatures": true - }, - "checkOnSave": true, - "check": { - "command": "clippy" - } - } } } } diff --git a/.github/scripts/generate-java-coverage-badge.sh b/.github/scripts/generate-java-coverage-badge.sh deleted file mode 100755 index 3c68d830d5..0000000000 --- a/.github/scripts/generate-java-coverage-badge.sh +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env bash -# Generates SVG coverage badges from a JaCoCo CSV report. -# -# Usage: generate-coverage-badge.sh [jacoco.csv] [output-dir] -# jacoco.csv - Path to JaCoCo CSV report (default: target/site/jacoco-coverage/jacoco.csv) -# output-dir - Directory for the badge SVG (default: .github/badges) -set -euo pipefail - -CSV="${1:-target/site/jacoco-coverage/jacoco.csv}" -BADGES_DIR="${2:-.github/badges}" -GENERATED_PREFIX="com.github.copilot.generated" - -if [ ! -f "$CSV" ]; then - echo "⚠️ No JaCoCo CSV report found at $CSV" - exit 0 -fi - -calc_totals() { - local scope=$1 - awk -F',' -v scope="$scope" -v generated_prefix="$GENERATED_PREFIX" ' - NR > 1 { - is_generated = index($2, generated_prefix) == 1 - if (scope == "overall" || - (scope == "generated" && is_generated) || - (scope == "handwritten" && !is_generated)) { - missed += $4 - covered += $5 - } - } - END { print missed + 0, covered + 0 } - ' "$CSV" -} - -format_pct() { - local missed=$1 - local covered=$2 - local total=$((missed + covered)) - if [ "$total" -eq 0 ]; then - echo "0" - else - awk "BEGIN { printf \"%.1f\", ($covered / $total) * 100 }" | sed 's/\.0$//' - fi -} - -pick_color() { - local pct=$1 - local color="#e05d44" # red <60 - if awk "BEGIN{exit!($pct>=100)}"; then color="#4c1" # bright green - elif awk "BEGIN{exit!($pct>=90)}"; then color="#97ca00" # green - elif awk "BEGIN{exit!($pct>=80)}"; then color="#a4a61d" # yellow-green - elif awk "BEGIN{exit!($pct>=70)}"; then color="#dfb317" # yellow - elif awk "BEGIN{exit!($pct>=60)}"; then color="#fe7d37" # orange - fi - echo "$color" -} - -generate_badge() { - local label=$1 - local value=$2 - local output=$3 - local pct=${value%\%} - local color - color=$(pick_color "$pct") - local lw=$(( ${#label} * 7 + 12 )) - local vw=$(( ${#value} * 7 + 16 )) - local tw=$((lw + vw)) - - cat > "$output" < - - - - - - - - - - - - ${label} - ${label} - ${value} - ${value} - - -EOF -} - -mkdir -p "$BADGES_DIR" - -read -r handwritten_missed handwritten_covered <<< "$(calc_totals handwritten)" -read -r generated_missed generated_covered <<< "$(calc_totals generated)" - -handwritten_pct=$(format_pct "$handwritten_missed" "$handwritten_covered") -generated_pct=$(format_pct "$generated_missed" "$generated_covered") - -echo "Handwritten coverage: ${handwritten_pct}%" -echo "Generated coverage: ${generated_pct}%" - -generate_badge "coverage handwritten" "${handwritten_pct}%" "${BADGES_DIR}/jacoco-handwritten.svg" -generate_badge "coverage generated" "${generated_pct}%" "${BADGES_DIR}/jacoco-generated.svg" - -echo "Badges generated in ${BADGES_DIR}" diff --git a/.github/skills/agentic-workflows/SKILL.md b/.github/skills/agentic-workflows/SKILL.md new file mode 100644 index 0000000000..acec3f146c --- /dev/null +++ b/.github/skills/agentic-workflows/SKILL.md @@ -0,0 +1,94 @@ +--- +name: agentic-workflows +description: Route gh-aw workflow design/create/debug/upgrade requests to the right prompts. +--- + +# Agentic Workflows Router + +Use this skill when a user asks to design, create, update, debug, or upgrade GitHub Agentic Workflows in this repository. + +This skill is a dispatcher: identify the task type, load the matching workflow prompt/skill file, and follow it directly. Keep responses concise and ask a clarifying question if the correct prompt is unclear. + +Repository overlay (optional): +- If `.github/aw/instructions.md` exists, load it with `@.github/aw/instructions.md` after loading the matched prompt/skill. +- Precedence: repository overlay instructions override upstream defaults when they conflict. + +Read only the files you need: +Load these files from `github/gh-aw` (they are not available locally). +- `.github/aw/agentic-chat.md` +- `.github/aw/agentic-workflows-mcp.md` +- `.github/aw/asciicharts.md` +- `.github/aw/campaign.md` +- `.github/aw/charts-trending.md` +- `.github/aw/charts.md` +- `.github/aw/cli-commands.md` +- `.github/aw/configure-agentic-engine.md` +- `.github/aw/context.md` +- `.github/aw/create-agentic-workflow-trigger-details.md` +- `.github/aw/create-agentic-workflow.md` +- `.github/aw/create-shared-agentic-workflow.md` +- `.github/aw/debug-agentic-workflow.md` +- `.github/aw/dependabot.md` +- `.github/aw/deployment-status.md` +- `.github/aw/designer.md` +- `.github/aw/evals.md` +- `.github/aw/experiments.md` +- `.github/aw/github-agentic-workflows.md` +- `.github/aw/github-mcp-server.md` +- `.github/aw/instructions.md` +- `.github/aw/llms.md` +- `.github/aw/loop.md` +- `.github/aw/lsp.md` +- `.github/aw/mcp-clis.md` +- `.github/aw/memory-stateful-patterns.md` +- `.github/aw/memory.md` +- `.github/aw/messages.md` +- `.github/aw/multi-agent-research.md` +- `.github/aw/network.md` +- `.github/aw/optimize-agentic-workflow.md` +- `.github/aw/patterns.md` +- `.github/aw/pr-reviewer.md` +- `.github/aw/report.md` +- `.github/aw/reuse.md` +- `.github/aw/safe-outputs-automation.md` +- `.github/aw/safe-outputs-content.md` +- `.github/aw/safe-outputs-management.md` +- `.github/aw/safe-outputs-runtime.md` +- `.github/aw/safe-outputs.md` +- `.github/aw/serena-tool.md` +- `.github/aw/shared-safe-jobs.md` +- `.github/aw/skills.md` +- `.github/aw/subagents.md` +- `.github/aw/syntax-agentic.md` +- `.github/aw/syntax-core.md` +- `.github/aw/syntax-tools-imports.md` +- `.github/aw/syntax.md` +- `.github/aw/test-coverage.md` +- `.github/aw/test-expression.md` +- `.github/aw/token-optimization.md` +- `.github/aw/triggers.md` +- `.github/aw/update-agentic-workflow.md` +- `.github/aw/upgrade-agentic-workflows.md` +- `.github/aw/visual-regression.md` +- `.github/aw/workflow-constraints.md` +- `.github/aw/workflow-editing.md` +- `.github/aw/workflow-patterns.md` + +After loading the matching workflow prompt or skill, follow it directly: +- Design workflows from scratch via interview: `.github/aw/designer.md` +- Create new workflows: `.github/aw/create-agentic-workflow.md` +- Configure or add declarative engines: `.github/aw/configure-agentic-engine.md` +- Update existing workflows: `.github/aw/update-agentic-workflow.md` +- Debug, audit, or investigate workflows: `.github/aw/debug-agentic-workflow.md` +- Upgrade workflows and fix deprecations: `.github/aw/upgrade-agentic-workflows.md` +- Create shared components or MCP wrappers: `.github/aw/create-shared-agentic-workflow.md` +- Create report-generating workflows: `.github/aw/report.md` +- Fix Dependabot manifest PRs: `.github/aw/dependabot.md` +- Analyze coverage workflows: `.github/aw/test-coverage.md` +- Render compact markdown charts: `.github/aw/asciicharts.md` +- Map CLI commands to MCP usage: `.github/aw/cli-commands.md` +- Choose workflow architecture and patterns: `.github/aw/patterns.md` +- Optimize token usage and cost: `.github/aw/token-optimization.md` +- Design long-running multi-agent research workflows: `.github/aw/multi-agent-research.md` + +When the task involves OTEL, OTLP, traces, observability backends, or telemetry-driven analysis, also read and follow `skills/otel-queries/SKILL.md` after loading the matching workflow prompt or skill. diff --git a/.github/workflows/agentics-maintenance.yml b/.github/workflows/agentics-maintenance.yml new file mode 100644 index 0000000000..45d836922f --- /dev/null +++ b/.github/workflows/agentics-maintenance.yml @@ -0,0 +1,633 @@ +# This file was automatically generated by pkg/workflow/maintenance_workflow.go (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ +# | _ |/ _` |/ _ \ '_ \| __| |/ __| +# | | | | (_| | __/ | | | |_| | (__ +# \_| |_/\__, |\___|_| |_|\__|_|\___| +# __/ | +# _ _ |___/ +# | | | | / _| | +# | | | | ___ _ __ _ __| |_| | _____ ____ +# | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| +# \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ +# \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ +# +# +# To regenerate this workflow, run: +# gh aw compile +# Not all edits will cause changes to this file. +# +# For more information: https://github.github.com/gh-aw/introduction/overview/ +# +# This file defines the generated agentic maintenance workflow for this repository. +# It runs scheduled cleanup for expiring safe outputs and supports manual maintenance operations. +# +# This workflow is generated automatically when workflows use expiring safe outputs +# or when repository maintenance features are enabled in .github/workflows/aw.json. +# +# To disable maintenance workflow generation, set in .github/workflows/aw.json: +# {"maintenance": false} +# +# Agentic maintenance docs: +# https://github.github.com/gh-aw/reference/ephemerals/#manual-maintenance-operations +# +name: Agentic Maintenance + +on: + schedule: + - cron: "37 0 * * *" # Daily (based on minimum expires: 30 days) + workflow_dispatch: + inputs: + operation: + description: 'Optional maintenance operation to run' + required: false + type: choice + default: '' + options: + - '' + - 'disable' + - 'enable' + - 'update' + - 'upgrade' + - 'safe_outputs' + - 'create_labels' + - 'activity_report' + - 'close_agentic_workflows_issues' + - 'clean_cache_memories' + - 'update_pull_request_branches' + - 'validate' + - 'forecast' + run_url: + description: 'Run URL or run ID to replay safe outputs from (e.g. https://github.com/owner/repo/actions/runs/12345 or 12345). Required when operation is safe_outputs.' + required: false + type: string + default: '' + workflow_call: + inputs: + operation: + description: 'Optional maintenance operation to run (disable, enable, update, upgrade, safe_outputs, create_labels, activity_report, close_agentic_workflows_issues, clean_cache_memories, update_pull_request_branches, validate, forecast)' + required: false + type: string + default: '' + run_url: + description: 'Run URL or run ID to replay safe outputs from (e.g. https://github.com/owner/repo/actions/runs/12345 or 12345). Required when operation is safe_outputs.' + required: false + type: string + default: '' + outputs: + operation_completed: + description: 'The maintenance operation that was completed (empty when none ran or a scheduled job ran)' + value: ${{ jobs.run_operation.outputs.operation || inputs.operation }} + applied_run_url: + description: 'The run URL that safe outputs were applied from' + value: ${{ jobs.apply_safe_outputs.outputs.run_url }} + +permissions: {} + +jobs: + close-expired-discussions: + if: ${{ (!(github.event.repository.fork)) && github.event_name != 'push' && (github.event_name != 'workflow_dispatch' && github.event_name != 'workflow_call' || inputs.operation == '') }} + runs-on: ubuntu-slim + permissions: + discussions: write + steps: + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Close expired discussions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/close_expired_discussions.cjs'); + await main(); + close-expired-issues: + if: ${{ (!(github.event.repository.fork)) && github.event_name != 'push' && (github.event_name != 'workflow_dispatch' && github.event_name != 'workflow_call' || inputs.operation == '') }} + runs-on: ubuntu-slim + permissions: + issues: write + steps: + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Close expired issues + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/close_expired_issues.cjs'); + await main(); + close-expired-pull-requests: + if: ${{ (!(github.event.repository.fork)) && github.event_name != 'push' && (github.event_name != 'workflow_dispatch' && github.event_name != 'workflow_call' || inputs.operation == '') }} + runs-on: ubuntu-slim + permissions: + pull-requests: write + steps: + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Close expired pull requests + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/close_expired_pull_requests.cjs'); + await main(); + + cleanup-cache-memory: + if: ${{ (!(github.event.repository.fork)) && github.event_name != 'push' && (github.event_name != 'workflow_dispatch' && github.event_name != 'workflow_call' || inputs.operation == '' || inputs.operation == 'clean_cache_memories') }} + runs-on: ubuntu-slim + permissions: + actions: write + steps: + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Cleanup outdated cache-memory entries + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/cleanup_cache_memory.cjs'); + await main(); + + run_operation: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation != '' && inputs.operation != 'safe_outputs' && inputs.operation != 'create_labels' && inputs.operation != 'activity_report' && inputs.operation != 'close_agentic_workflows_issues' && inputs.operation != 'clean_cache_memories' && inputs.operation != 'update_pull_request_branches' && inputs.operation != 'validate' && inputs.operation != 'forecast' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-slim + permissions: + actions: write + contents: write + pull-requests: write + outputs: + operation: ${{ steps.record.outputs.operation }} + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Install gh-aw + uses: github/gh-aw-actions/setup-cli@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + version: v0.82.10 + + - name: Run operation + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_OPERATION: ${{ inputs.operation }} + GH_AW_CMD_PREFIX: gh aw + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/run_operation_update_upgrade.cjs'); + await main(); + + - name: Record outputs + id: record + env: + GH_AW_OPERATION: ${{ inputs.operation }} + run: echo "operation=$GH_AW_OPERATION" >> "$GITHUB_OUTPUT" + + update_pull_request_branches: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation == 'update_pull_request_branches' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-slim + permissions: + contents: write + pull-requests: write + steps: + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Update pull request branches + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/update_pull_request_branches.cjs'); + await main(); + + apply_safe_outputs: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation == 'safe_outputs' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-slim + permissions: + actions: read + contents: write + discussions: write + issues: write + pull-requests: write + outputs: + run_url: ${{ steps.record.outputs.run_url }} + steps: + - name: Checkout actions folder + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + sparse-checkout: | + actions + clean: false + persist-credentials: false + + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Apply Safe Outputs + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_RUN_URL: ${{ inputs.run_url }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/apply_safe_outputs_replay.cjs'); + await main(); + + - name: Record outputs + id: record + env: + GH_AW_RUN_URL: ${{ inputs.run_url }} + run: echo "run_url=$GH_AW_RUN_URL" >> "$GITHUB_OUTPUT" + + create_labels: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation == 'create_labels' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-slim + permissions: + contents: read + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Install gh-aw + uses: github/gh-aw-actions/setup-cli@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + version: v0.82.10 + + - name: Create missing labels + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_CMD_PREFIX: gh aw + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/create_labels.cjs'); + await main(); + + activity_report: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation == 'activity_report' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-slim + timeout-minutes: 120 + permissions: + actions: read + contents: read + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Install gh-aw + uses: github/gh-aw-actions/setup-cli@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + version: v0.82.10 + + - name: Restore activity report logs cache + id: activity_report_logs_cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ./.cache/gh-aw/activity-report-logs + key: ${{ runner.os }}-activity-report-logs-${{ github.repository }}-${{ github.ref_name }}-${{ github.run_id }} + restore-keys: | + ${{ runner.os }}-activity-report-logs-${{ github.repository }}- + ${{ runner.os }}-activity-report-logs- + - name: Download activity report logs + timeout-minutes: 20 + shell: bash + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_CMD_PREFIX: gh aw + run: | + ${GH_AW_CMD_PREFIX} logs \ + --repo "$GITHUB_REPOSITORY" \ + --start-date -1w \ + --count 500 \ + --output ./.cache/gh-aw/activity-report-logs \ + --format markdown \ + --report-file ./.cache/gh-aw/activity-report-logs/report.md + + - name: Save activity report logs cache + if: ${{ always() }} + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ./.cache/gh-aw/activity-report-logs + key: ${{ steps.activity_report_logs_cache.outputs.cache-primary-key }} + + - name: Generate activity report issue + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fs = require('node:fs'); + const reportPath = './.cache/gh-aw/activity-report-logs/report.md'; + if (!fs.existsSync(reportPath)) { + core.warning('Activity report markdown not found at ' + reportPath + '; skipping issue creation.'); + return; + } + let reportBody = ''; + try { + reportBody = fs.readFileSync(reportPath, 'utf8').trim(); + } catch (error) { + core.warning('Failed to read activity report markdown at ' + reportPath + ': ' + error.message); + return; + } + if (!reportBody) { + core.warning('Activity report markdown is empty at ' + reportPath + '; skipping issue creation.'); + return; + } + const repoSlug = context.repo.owner + '/' + context.repo.repo; + const body = [ + '### Agentic workflow activity report', + '', + 'Repository: ' + repoSlug, + 'Generated at: ' + new Date().toISOString(), + '', + reportBody, + ].join('\n'); + const createdIssue = await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: '[aw] agentic status report', + body, + labels: ['agentic-workflows'], + }); + core.info('Created issue #' + createdIssue.data.number + ': ' + createdIssue.data.html_url); + + forecast_report: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation == 'forecast' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-slim + timeout-minutes: 60 + permissions: + actions: read + contents: read + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Install gh-aw + uses: github/gh-aw-actions/setup-cli@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + version: v0.82.10 + + - name: Restore forecast report logs cache + id: forecast_report_logs_cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ./.github/aw/logs + key: ${{ runner.os }}-forecast-report-logs-${{ github.repository }}-${{ github.ref_name }}-${{ github.run_id }} + restore-keys: | + ${{ runner.os }}-forecast-report-logs-${{ github.repository }}- + ${{ runner.os }}-forecast-report-logs- + + - name: Generate forecast report + id: generate_forecast_report + timeout-minutes: 30 + shell: bash + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DEBUG: "*" + GH_AW_CMD_PREFIX: gh aw + run: | + mkdir -p ./.cache/gh-aw/forecast + set +e + ${GH_AW_CMD_PREFIX} forecast --repo "$GITHUB_REPOSITORY" --timeout 30 --verbose --json > ./.cache/gh-aw/forecast/report.json + forecast_exit_code=$? + set -e + if [ "${forecast_exit_code}" -eq 124 ]; then + echo '{"outcome":"timeout","message":"Forecast computation timed out after 30 minutes."}' > ./.cache/gh-aw/forecast/error.json + echo "::error::Forecast computation timed out after 30 minutes." + exit 1 + fi + if [ "${forecast_exit_code}" -ne 0 ]; then + echo '{"outcome":"error","message":"Forecast computation failed before producing a report."}' > ./.cache/gh-aw/forecast/error.json + echo "::error::Forecast computation failed with exit code ${forecast_exit_code}." + exit 1 + fi + + - name: Debug forecast logs folder + if: ${{ always() }} + shell: bash + run: | + if [ ! -d ./.github/aw/logs ]; then + echo "Logs directory not found: ./.github/aw/logs" + exit 0 + fi + echo "Files under ./.github/aw/logs:" + find ./.github/aw/logs -type f | sort + + - name: Save forecast report logs cache + if: ${{ always() }} + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ./.github/aw/logs + key: ${{ runner.os }}-forecast-report-logs-${{ github.repository }}-${{ github.ref_name }}-${{ github.run_id }} + + - name: Generate forecast issue + if: ${{ always() }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + FORECAST_STEP_OUTCOME: ${{ steps.generate_forecast_report.outcome }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/create_forecast_issue.cjs'); + await main(); + + close_agentic_workflows_issues: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation == 'close_agentic_workflows_issues' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-slim + permissions: + issues: write + steps: + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Close no-repro agentic-workflows issues + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/close_agentic_workflows_issues.cjs'); + await main(); + + validate_workflows: + if: ${{ (github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') && inputs.operation == 'validate' && (!(github.event.repository.fork)) }} + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Setup Scripts + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + destination: ${{ runner.temp }}/gh-aw/actions + + - name: Check admin/maintainer permissions + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_team_member.cjs'); + await main(); + + - name: Install gh-aw + uses: github/gh-aw-actions/setup-cli@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 + with: + version: v0.82.10 + + - name: Validate workflows and file issue on findings + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_CMD_PREFIX: gh aw + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/run_validate_workflows.cjs'); + await main(); diff --git a/.github/workflows/block-remove-before-merge.yml b/.github/workflows/block-remove-before-merge.yml index f9df22ebe9..0b491ea817 100644 --- a/.github/workflows/block-remove-before-merge.yml +++ b/.github/workflows/block-remove-before-merge.yml @@ -11,7 +11,7 @@ permissions: jobs: check-paths: name: "No remove-before-merge directories" - if: github.event_name == 'pull_request' + if: github.event_name == 'pull_request' && github.base_ref == 'main' runs-on: ubuntu-latest steps: - name: Check for remove-before-merge paths in PR diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index 7b6d738671..d25689b3b9 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -76,9 +76,9 @@ jobs: # Install gh-aw extension for advanced GitHub CLI features - name: Install gh-aw extension - uses: github/gh-aw/actions/setup-cli@0feed75a980b06f247abbbf80127f8eb2c19e2c5 # v0.74.8 + uses: github/gh-aw-actions/setup-cli@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: - version: v0.74.4 + version: v0.82.10 # Enable repository pre-commit hooks (Spotless checks for Java source changes) - name: Enable pre-commit hooks diff --git a/.github/workflows/cross-repo-issue-analysis.lock.yml b/.github/workflows/cross-repo-issue-analysis.lock.yml index 697ecc0ee0..dc117400bf 100644 --- a/.github/workflows/cross-repo-issue-analysis.lock.yml +++ b/.github/workflows/cross-repo-issue-analysis.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"97b961391ad56ae223a93f2ff91267fed96ce49805bdd921de7549138893d637","body_hash":"653dfb46c89df98eca22ddfb802149d6ade32e9a7ad40dbdc51bfb6b0ba1c4a3","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN","RUNTIME_TRIAGE_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"16de319b1db6be0d409d3055ca8fa9f619f2c0120dad678248a45dce07b880b4","body_hash":"653dfb46c89df98eca22ddfb802149d6ade32e9a7ad40dbdc51bfb6b0ba1c4a3","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN","RUNTIME_TRIAGE_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -32,27 +33,30 @@ # - RUNTIME_TRIAGE_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "SDK Runtime Triage" on: issues: types: - - labeled + - labeled workflow_dispatch: inputs: aw_context: @@ -81,14 +85,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: body: ${{ steps.sanitized.outputs.body }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -98,17 +108,18 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} trace-id: ${{ needs.pre_activation.outputs.setup-trace-id }} parent-span-id: ${{ needs.pre_activation.outputs.setup-parent-span-id || needs.pre_activation.outputs.setup-span-id }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/cross-repo-issue-analysis.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info @@ -116,16 +127,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -136,13 +147,59 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-crossrepoissueanalysis-${{ github.run_id }} + restore-keys: agentic-workflow-usage-crossrepoissueanalysis- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "SDK Runtime Triage" + GH_AW_WORKFLOW_ID: "cross-repo-issue-analysis" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Checkout .github and .agents folders - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false sparse-checkout: | @@ -151,7 +208,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -159,8 +215,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -178,7 +234,7 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -196,6 +252,9 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/compute_text.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -215,20 +274,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_38cbf088966d11e6_EOF' + cat << 'GH_AW_PROMPT_41a978c1ce3777a8_EOF' - GH_AW_PROMPT_38cbf088966d11e6_EOF + GH_AW_PROMPT_41a978c1ce3777a8_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_38cbf088966d11e6_EOF' + cat << 'GH_AW_PROMPT_41a978c1ce3777a8_EOF' Tools: create_issue, add_labels(max:3), missing_tool, missing_data, noop - GH_AW_PROMPT_38cbf088966d11e6_EOF + GH_AW_PROMPT_41a978c1ce3777a8_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_38cbf088966d11e6_EOF' + cat << 'GH_AW_PROMPT_41a978c1ce3777a8_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -256,13 +315,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_38cbf088966d11e6_EOF + + GH_AW_PROMPT_41a978c1ce3777a8_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_38cbf088966d11e6_EOF' + cat << 'GH_AW_PROMPT_41a978c1ce3777a8_EOF' {{#runtime-import .github/workflows/cross-repo-issue-analysis.md}} - GH_AW_PROMPT_38cbf088966d11e6_EOF + GH_AW_PROMPT_41a978c1ce3777a8_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -300,9 +359,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -340,7 +399,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -353,9 +412,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read env: @@ -364,13 +425,17 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: crossrepoissueanalysis outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -380,10 +445,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -392,8 +458,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/cross-repo-issue-analysis.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths @@ -404,7 +470,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -413,6 +479,11 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw - env: GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} RUNTIME_TRIAGE_TOKEN: ${{ secrets.RUNTIME_TRIAGE_TOKEN }} @@ -421,21 +492,14 @@ jobs: - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.RUNTIME_TRIAGE_TOKEN }} @@ -447,14 +511,14 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless - name: Determine automatic lockdown mode for GitHub MCP Server id: determine-automatic-lockdown - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 env: GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} @@ -462,16 +526,11 @@ jobs: script: | const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); await determineAutomaticLockdown(github, context, core); - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -483,15 +542,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_873b138e05029386_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_f9dc8569c195ba44_EOF' {"add_labels":{"allowed":["runtime","sdk-fix-only","needs-investigation"],"max":3,"target":"triggering"},"create_issue":{"labels":["upstream-from-sdk","ai-triaged"],"max":1,"target-repo":"github/copilot-agent-runtime","title_prefix":"[copilot-sdk] "},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_873b138e05029386_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_f9dc8569c195ba44_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -513,10 +572,7 @@ jobs: }, "labels": { "required": true, - "type": "array", - "itemType": "string", - "itemSanitize": true, - "itemMaxLength": 128 + "type": "array" }, "repo": { "type": "string", @@ -531,7 +587,8 @@ jobs: "required": true, "type": "string", "sanitize": true, - "maxLength": 65000 + "maxLength": 65000, + "minLength": 20 }, "fields": { "type": "array" @@ -641,62 +698,24 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_GUARD_MIN_INTEGRITY: ${{ steps.determine-automatic-lockdown.outputs.min_integrity }} GITHUB_MCP_GUARD_REPOS: ${{ steps.determine-automatic-lockdown.outputs.repos }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.RUNTIME_TRIAGE_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -705,29 +724,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_fc7eecb5bcf8a5c8_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -739,16 +753,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -760,7 +793,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_fc7eecb5bcf8a5c8_EOF + GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -813,41 +846,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-tool github --allow-tool safeoutputs --allow-tool '\''shell(cat)'\'' --allow-tool '\''shell(cat:*)'\'' --allow-tool '\''shell(date)'\'' --allow-tool '\''shell(echo)'\'' --allow-tool '\''shell(find:*)'\'' --allow-tool '\''shell(grep)'\'' --allow-tool '\''shell(grep:*)'\'' --allow-tool '\''shell(head)'\'' --allow-tool '\''shell(head:*)'\'' --allow-tool '\''shell(ls)'\'' --allow-tool '\''shell(ls:*)'\'' --allow-tool '\''shell(printf)'\'' --allow-tool '\''shell(pwd)'\'' --allow-tool '\''shell(safeoutputs:*)'\'' --allow-tool '\''shell(sort)'\'' --allow-tool '\''shell(tail)'\'' --allow-tool '\''shell(tail:*)'\'' --allow-tool '\''shell(uniq)'\'' --allow-tool '\''shell(wc)'\'' --allow-tool '\''shell(wc:*)'\'' --allow-tool '\''shell(yq)'\'' --allow-tool write --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-tool github --allow-tool safeoutputs --allow-tool '\''shell(cat)'\'' --allow-tool '\''shell(cat:*)'\'' --allow-tool '\''shell(date)'\'' --allow-tool '\''shell(echo)'\'' --allow-tool '\''shell(find:*)'\'' --allow-tool '\''shell(grep)'\'' --allow-tool '\''shell(grep:*)'\'' --allow-tool '\''shell(head)'\'' --allow-tool '\''shell(head:*)'\'' --allow-tool '\''shell(ls)'\'' --allow-tool '\''shell(ls:*)'\'' --allow-tool '\''shell(printf)'\'' --allow-tool '\''shell(pwd)'\'' --allow-tool '\''shell(safeoutputs:*)'\'' --allow-tool '\''shell(sort)'\'' --allow-tool '\''shell(tail)'\'' --allow-tool '\''shell(tail:*)'\'' --allow-tool '\''shell(uniq)'\'' --allow-tool '\''shell(wc)'\'' --allow-tool '\''shell(wc:*)'\'' --allow-tool '\''shell(yq)'\'' --allow-tool write --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -862,7 +905,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -870,17 +914,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -904,10 +941,10 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,RUNTIME_TRIAGE_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN,RUNTIME_TRIAGE_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SECRET_RUNTIME_TRIAGE_TOKEN: ${{ secrets.RUNTIME_TRIAGE_TOKEN }} - name: Append agent step summary if: always() @@ -940,6 +977,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -961,16 +999,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1031,7 +1060,8 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read @@ -1041,6 +1071,8 @@ jobs: group: "gh-aw-conclusion-cross-repo-issue-analysis" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1049,7 +1081,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1058,8 +1090,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/cross-repo-issue-analysis.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1075,6 +1107,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-crossrepoissueanalysis-${{ github.run_id }} + restore-keys: agentic-workflow-usage-crossrepoissueanalysis- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-crossrepoissueanalysis-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1086,6 +1210,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "cross-repo-issue-analysis" with: github-token: ${{ secrets.RUNTIME_TRIAGE_TOKEN }} script: | @@ -1153,23 +1281,30 @@ jobs: GH_AW_WORKFLOW_ID: "cross-repo-issue-analysis" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "20" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.RUNTIME_TRIAGE_TOKEN }} script: | @@ -1182,19 +1317,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1203,8 +1341,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/cross-repo-issue-analysis.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1222,7 +1360,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1231,7 +1369,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1250,12 +1388,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1293,11 +1432,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1307,39 +1446,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1353,7 +1504,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1397,6 +1562,8 @@ jobs: pre_activation: if: github.event_name == 'workflow_dispatch' || github.event.label.name == 'runtime triage' runs-on: ubuntu-slim + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: activated: ${{ steps.check_membership.outputs.is_team_member == 'true' }} matched_command: '' @@ -1406,15 +1573,15 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/cross-repo-issue-analysis.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Check team membership for workflow id: check_membership @@ -1440,15 +1607,20 @@ jobs: contents: read issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/cross-repo-issue-analysis" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "cross-repo-issue-analysis" GH_AW_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/cross-repo-issue-analysis.md" @@ -1464,7 +1636,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1473,8 +1645,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Runtime Triage" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/cross-repo-issue-analysis.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1493,7 +1665,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1525,4 +1697,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/cross-repo-issue-analysis.md b/.github/workflows/cross-repo-issue-analysis.md index 1719949881..58e07156b6 100644 --- a/.github/workflows/cross-repo-issue-analysis.md +++ b/.github/workflows/cross-repo-issue-analysis.md @@ -14,6 +14,7 @@ permissions: contents: read issues: read pull-requests: read + copilot-requests: write steps: - name: Clone copilot-agent-runtime env: diff --git a/.github/workflows/dotnet-sdk-tests.yml b/.github/workflows/dotnet-sdk-tests.yml index d3b2ef162a..ecd5dcd09c 100644 --- a/.github/workflows/dotnet-sdk-tests.yml +++ b/.github/workflows/dotnet-sdk-tests.yml @@ -28,14 +28,35 @@ permissions: jobs: test: - name: ".NET SDK Tests" + name: ".NET SDK Tests (${{ matrix.os }}, ${{ matrix.transport }}, ${{ matrix.backend }})" if: github.event.repository.fork == false env: POWERSHELL_UPDATECHECK: Off + COPILOT_SDK_E2E_BACKEND: ${{ matrix.backend }} + DOTNET_TEST_FILTER: ${{ matrix.test-filter }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] + transport: ["default", "inprocess"] + backend: [capi] + # TODO: Re-enable after fixing in-process sqlite file locking on shutdown on Windows. + exclude: + - os: windows-latest + transport: "inprocess" + include: + - os: ubuntu-latest + transport: inprocess + backend: anthropic-messages + test-filter: "FullyQualifiedName~GitHub.Copilot.Test.E2E&E2EBackend!=SelfConfiguredBackend&E2EBackend!=CapiOnly" + - os: ubuntu-latest + transport: inprocess + backend: openai-responses + test-filter: "FullyQualifiedName~GitHub.Copilot.Test.E2E&E2EBackend!=SelfConfiguredBackend&E2EBackend!=CapiOnly" + - os: ubuntu-latest + transport: inprocess + backend: openai-completions + test-filter: "FullyQualifiedName~GitHub.Copilot.Test.E2E&E2EBackend!=SelfConfiguredBackend&E2EBackend!=CapiOnly" runs-on: ${{ matrix.os }} defaults: run: @@ -80,7 +101,16 @@ jobs: if: runner.os == 'Windows' run: pwsh.exe -Command "Write-Host 'PowerShell ready'" + - name: Select inprocess transport + if: matrix.transport == 'inprocess' + run: echo "COPILOT_SDK_DEFAULT_CONNECTION=inprocess" >> "$GITHUB_ENV" + - name: Run .NET SDK tests env: COPILOT_HMAC_KEY: ${{ secrets.COPILOT_DEVELOPER_CLI_INTEGRATION_HMAC_KEY }} - run: dotnet test --no-build -v n + run: | + args=(--no-build -v n) + if [[ -n "$DOTNET_TEST_FILTER" ]]; then + args+=(--filter "$DOTNET_TEST_FILTER") + fi + dotnet test "${args[@]}" diff --git a/.github/workflows/go-sdk-tests.yml b/.github/workflows/go-sdk-tests.yml index e262961096..365e60373f 100644 --- a/.github/workflows/go-sdk-tests.yml +++ b/.github/workflows/go-sdk-tests.yml @@ -29,7 +29,7 @@ permissions: jobs: test: - name: "Go SDK Tests" + name: "Go SDK Tests (${{ matrix.os }}, ${{ matrix.transport }})" if: github.event.repository.fork == false env: POWERSHELL_UPDATECHECK: Off @@ -37,6 +37,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] + transport: ["default", "inprocess"] runs-on: ${{ matrix.os }} defaults: run: @@ -78,6 +79,12 @@ jobs: if: runner.os == 'Windows' run: pwsh.exe -Command "Write-Host 'PowerShell ready'" + - name: Select inprocess transport + if: matrix.transport == 'inprocess' + run: | + echo "COPILOT_SDK_DEFAULT_CONNECTION=inprocess" >> "$GITHUB_ENV" + echo "GOFLAGS=-tags=copilot_inprocess" >> "$GITHUB_ENV" + - name: Run Go SDK tests env: COPILOT_HMAC_KEY: ${{ secrets.COPILOT_DEVELOPER_CLI_INTEGRATION_HMAC_KEY }} diff --git a/.github/workflows/handle-bug.lock.yml b/.github/workflows/handle-bug.lock.yml index 014ed4b689..4c8844361d 100644 --- a/.github/workflows/handle-bug.lock.yml +++ b/.github/workflows/handle-bug.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"a473a22cd67feb7f8f5225639fd989cf71705f78c9fe11c3fc757168e1672b0e","body_hash":"376c982b907760113954510ef1aff70d22dcb172c7bb851b2fa3d82121bdbc1c","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"df4e7ec5b346a28c7de5353cbfb15d329d03eb7092f2ded784ee6602108461e6","body_hash":"376c982b907760113954510ef1aff70d22dcb172c7bb851b2fa3d82121bdbc1c","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -31,20 +32,24 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Bug Handler" on: @@ -79,7 +84,7 @@ on: permissions: {} concurrency: - group: "gh-aw-${{ github.workflow }}" + group: "gh-aw-handle-bug-${{ github.run_id }}" run-name: "Bug Handler" @@ -89,14 +94,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: artifact_prefix: ${{ steps.artifact-prefix.outputs.prefix }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -108,15 +119,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Bug Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-bug.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Resolve host repo for activation checkout @@ -144,16 +156,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Bug Handler" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -165,11 +177,57 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handlebug-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handlebug- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Bug Handler" + GH_AW_WORKFLOW_ID: "handle-bug" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Print cross-repo setup guidance if: failure() && steps.resolve-host-repo.outputs.target_repo != github.repository run: | @@ -178,7 +236,7 @@ jobs: echo "::error::See: https://github.github.com/gh-aw/patterns/central-repo-ops/#cross-repo-setup" - name: Checkout .github and .agents folders if: steps.resolve-host-repo.outputs.target_repo == github.repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false repository: ${{ steps.resolve-host-repo.outputs.target_repo }} @@ -189,7 +247,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -197,8 +254,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -216,13 +273,16 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -240,20 +300,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_3df18ed0421fc8c1_EOF' + cat << 'GH_AW_PROMPT_04d69bd6df5739b0_EOF' - GH_AW_PROMPT_3df18ed0421fc8c1_EOF + GH_AW_PROMPT_04d69bd6df5739b0_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_3df18ed0421fc8c1_EOF' + cat << 'GH_AW_PROMPT_04d69bd6df5739b0_EOF' Tools: add_comment, add_labels, missing_tool, missing_data, noop - GH_AW_PROMPT_3df18ed0421fc8c1_EOF + GH_AW_PROMPT_04d69bd6df5739b0_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_3df18ed0421fc8c1_EOF' + cat << 'GH_AW_PROMPT_04d69bd6df5739b0_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -281,13 +341,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_3df18ed0421fc8c1_EOF + + GH_AW_PROMPT_04d69bd6df5739b0_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_3df18ed0421fc8c1_EOF' + cat << 'GH_AW_PROMPT_04d69bd6df5739b0_EOF' {{#runtime-import .github/workflows/handle-bug.md}} - GH_AW_PROMPT_3df18ed0421fc8c1_EOF + GH_AW_PROMPT_04d69bd6df5739b0_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -319,9 +379,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -356,7 +416,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -369,9 +429,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read concurrency: @@ -383,14 +445,18 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: handlebug outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} artifact_prefix: ${{ needs.activation.outputs.artifact_prefix }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -400,10 +466,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -412,8 +479,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Bug Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-bug.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Set runtime paths @@ -425,7 +492,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -434,23 +501,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -462,11 +527,22 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless + - name: Determine automatic lockdown mode for GitHub MCP Server + id: determine-automatic-lockdown + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + env: + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} + GH_AW_GITHUB_MIN_INTEGRITY: 'none' + with: + script: | + const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); + await determineAutomaticLockdown(github, context, core); - name: Parse integrity filter lists id: parse-guard-vars env: @@ -474,16 +550,11 @@ jobs: GH_AW_TRUSTED_USERS_VAR: ${{ vars.GH_AW_GITHUB_TRUSTED_USERS || '' }} GH_AW_APPROVAL_LABELS_VAR: ${{ vars.GH_AW_GITHUB_APPROVAL_LABELS || '' }} run: bash "${RUNNER_TEMP}/gh-aw/actions/parse_guard_list.sh" - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: ${{ needs.activation.outputs.artifact_prefix }}activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -495,15 +566,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_788bfbc2e8cbcb67_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_18a2d1564ec59c01_EOF' {"add_comment":{"max":1,"target":"*"},"add_labels":{"allowed":["bug","enhancement","question","documentation"],"max":1,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_788bfbc2e8cbcb67_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_18a2d1564ec59c01_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -547,10 +618,7 @@ jobs: }, "labels": { "required": true, - "type": "array", - "itemType": "string", - "itemSanitize": true, - "itemMaxLength": 128 + "type": "array" }, "repo": { "type": "string", @@ -639,60 +707,22 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -701,29 +731,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_5cf2254bdcfe4a71_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -738,16 +763,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -759,7 +803,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_5cf2254bdcfe4a71_EOF + GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -788,41 +832,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -837,7 +891,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -845,17 +900,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -879,8 +927,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -914,6 +961,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -935,16 +983,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1007,17 +1046,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-handle-bug-${{ inputs.issue_number }}" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1026,7 +1067,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1035,8 +1076,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Bug Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-bug.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1053,6 +1094,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handlebug-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handlebug- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handlebug-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1064,6 +1197,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "handle-bug" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1131,23 +1268,30 @@ jobs: GH_AW_WORKFLOW_ID: "handle-bug" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "20" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1160,19 +1304,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1181,8 +1328,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Bug Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-bug.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1201,7 +1348,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1210,7 +1357,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1229,12 +1376,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1272,11 +1420,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1286,39 +1434,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1332,7 +1492,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1382,18 +1556,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/handle-bug" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "handle-bug" GH_AW_WORKFLOW_NAME: "Bug Handler" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/handle-bug.md" @@ -1409,7 +1587,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1418,8 +1596,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Bug Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-bug.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1439,7 +1617,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1471,4 +1649,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/handle-bug.md b/.github/workflows/handle-bug.md index 7edb33a4fb..8d426ce5d6 100644 --- a/.github/workflows/handle-bug.md +++ b/.github/workflows/handle-bug.md @@ -16,6 +16,7 @@ permissions: contents: read issues: read pull-requests: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/handle-documentation.lock.yml b/.github/workflows/handle-documentation.lock.yml index 92a284669b..71d73c337c 100644 --- a/.github/workflows/handle-documentation.lock.yml +++ b/.github/workflows/handle-documentation.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"258058e9a5e3bb707bbcfc9157b7b69f64c06547642da2526a1ff441e3a358dd","body_hash":"81c8287f5691cdc10ae8f60c004bb671d9b4942740d73fcc9646e28fbcd8790e","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"6c3b9dc8d0f7b54d44175db209cda34e37ea8c635d01ee0a5cba13675053f6cd","body_hash":"81c8287f5691cdc10ae8f60c004bb671d9b4942740d73fcc9646e28fbcd8790e","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -31,20 +32,24 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Documentation Handler" on: @@ -79,7 +84,7 @@ on: permissions: {} concurrency: - group: "gh-aw-${{ github.workflow }}" + group: "gh-aw-handle-documentation-${{ github.run_id }}" run-name: "Documentation Handler" @@ -89,14 +94,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: artifact_prefix: ${{ steps.artifact-prefix.outputs.prefix }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -108,15 +119,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Documentation Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-documentation.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Resolve host repo for activation checkout @@ -144,16 +156,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Documentation Handler" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -165,11 +177,57 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handledocumentation-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handledocumentation- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Documentation Handler" + GH_AW_WORKFLOW_ID: "handle-documentation" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Print cross-repo setup guidance if: failure() && steps.resolve-host-repo.outputs.target_repo != github.repository run: | @@ -178,7 +236,7 @@ jobs: echo "::error::See: https://github.github.com/gh-aw/patterns/central-repo-ops/#cross-repo-setup" - name: Checkout .github and .agents folders if: steps.resolve-host-repo.outputs.target_repo == github.repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false repository: ${{ steps.resolve-host-repo.outputs.target_repo }} @@ -189,7 +247,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -197,8 +254,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -216,13 +273,16 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -240,20 +300,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_c1995fcb77e4eb7d_EOF' + cat << 'GH_AW_PROMPT_b3d8e6ce75517df8_EOF' - GH_AW_PROMPT_c1995fcb77e4eb7d_EOF + GH_AW_PROMPT_b3d8e6ce75517df8_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_c1995fcb77e4eb7d_EOF' + cat << 'GH_AW_PROMPT_b3d8e6ce75517df8_EOF' Tools: add_comment, add_labels, missing_tool, missing_data, noop - GH_AW_PROMPT_c1995fcb77e4eb7d_EOF + GH_AW_PROMPT_b3d8e6ce75517df8_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_c1995fcb77e4eb7d_EOF' + cat << 'GH_AW_PROMPT_b3d8e6ce75517df8_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -281,13 +341,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_c1995fcb77e4eb7d_EOF + + GH_AW_PROMPT_b3d8e6ce75517df8_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_c1995fcb77e4eb7d_EOF' + cat << 'GH_AW_PROMPT_b3d8e6ce75517df8_EOF' {{#runtime-import .github/workflows/handle-documentation.md}} - GH_AW_PROMPT_c1995fcb77e4eb7d_EOF + GH_AW_PROMPT_b3d8e6ce75517df8_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -319,9 +379,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -356,7 +416,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -369,9 +429,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read concurrency: @@ -383,14 +445,18 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: handledocumentation outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} artifact_prefix: ${{ needs.activation.outputs.artifact_prefix }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -400,10 +466,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -412,8 +479,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Documentation Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-documentation.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Set runtime paths @@ -425,7 +492,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -434,23 +501,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -462,11 +527,22 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless + - name: Determine automatic lockdown mode for GitHub MCP Server + id: determine-automatic-lockdown + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + env: + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} + GH_AW_GITHUB_MIN_INTEGRITY: 'none' + with: + script: | + const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); + await determineAutomaticLockdown(github, context, core); - name: Parse integrity filter lists id: parse-guard-vars env: @@ -474,16 +550,11 @@ jobs: GH_AW_TRUSTED_USERS_VAR: ${{ vars.GH_AW_GITHUB_TRUSTED_USERS || '' }} GH_AW_APPROVAL_LABELS_VAR: ${{ vars.GH_AW_GITHUB_APPROVAL_LABELS || '' }} run: bash "${RUNNER_TEMP}/gh-aw/actions/parse_guard_list.sh" - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: ${{ needs.activation.outputs.artifact_prefix }}activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -495,15 +566,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_f287fa0f078c345e_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_6c1b251bac7b1edb_EOF' {"add_comment":{"max":1,"target":"*"},"add_labels":{"allowed":["documentation"],"max":1,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_f287fa0f078c345e_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_6c1b251bac7b1edb_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -547,10 +618,7 @@ jobs: }, "labels": { "required": true, - "type": "array", - "itemType": "string", - "itemSanitize": true, - "itemMaxLength": 128 + "type": "array" }, "repo": { "type": "string", @@ -639,60 +707,22 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -701,29 +731,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_728828b4ea6e4249_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -738,16 +763,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -759,7 +803,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_728828b4ea6e4249_EOF + GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -788,41 +832,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 5 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -837,7 +891,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -845,17 +900,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -879,8 +927,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -914,6 +961,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -935,16 +983,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1007,17 +1046,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-handle-documentation-${{ inputs.issue_number }}" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1026,7 +1067,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1035,8 +1076,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Documentation Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-documentation.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1053,6 +1094,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handledocumentation-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handledocumentation- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handledocumentation-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1064,6 +1197,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "handle-documentation" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1131,23 +1268,30 @@ jobs: GH_AW_WORKFLOW_ID: "handle-documentation" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "5" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1160,19 +1304,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1181,8 +1328,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Documentation Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-documentation.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1201,7 +1348,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1210,7 +1357,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1229,12 +1376,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1272,11 +1420,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1286,39 +1434,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1332,7 +1492,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1382,18 +1556,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/handle-documentation" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "handle-documentation" GH_AW_WORKFLOW_NAME: "Documentation Handler" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/handle-documentation.md" @@ -1409,7 +1587,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1418,8 +1596,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Documentation Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-documentation.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1439,7 +1617,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1471,4 +1649,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/handle-documentation.md b/.github/workflows/handle-documentation.md index 45c21adb1b..12449a85ca 100644 --- a/.github/workflows/handle-documentation.md +++ b/.github/workflows/handle-documentation.md @@ -16,6 +16,7 @@ permissions: contents: read issues: read pull-requests: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/handle-enhancement.lock.yml b/.github/workflows/handle-enhancement.lock.yml index de163e4e3e..ac4b65a737 100644 --- a/.github/workflows/handle-enhancement.lock.yml +++ b/.github/workflows/handle-enhancement.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"0a1cd53da97b1be36f489e58d1153583dc96c9b436fab3392437a8d498d4d8fb","body_hash":"624219976b9b7078c6bb11c4177925478cfd8316fe8de535a581bdd176eda825","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"f194730258943dec72121a119dba066ff5fee588d79f69fddddd4ca29b56ffd4","body_hash":"624219976b9b7078c6bb11c4177925478cfd8316fe8de535a581bdd176eda825","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -31,20 +32,24 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Enhancement Handler" on: @@ -79,7 +84,7 @@ on: permissions: {} concurrency: - group: "gh-aw-${{ github.workflow }}" + group: "gh-aw-handle-enhancement-${{ github.run_id }}" run-name: "Enhancement Handler" @@ -89,14 +94,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: artifact_prefix: ${{ steps.artifact-prefix.outputs.prefix }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -108,15 +119,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Enhancement Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-enhancement.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Resolve host repo for activation checkout @@ -144,16 +156,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Enhancement Handler" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -165,11 +177,57 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handleenhancement-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handleenhancement- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Enhancement Handler" + GH_AW_WORKFLOW_ID: "handle-enhancement" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Print cross-repo setup guidance if: failure() && steps.resolve-host-repo.outputs.target_repo != github.repository run: | @@ -178,7 +236,7 @@ jobs: echo "::error::See: https://github.github.com/gh-aw/patterns/central-repo-ops/#cross-repo-setup" - name: Checkout .github and .agents folders if: steps.resolve-host-repo.outputs.target_repo == github.repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false repository: ${{ steps.resolve-host-repo.outputs.target_repo }} @@ -189,7 +247,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -197,8 +254,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -216,13 +273,16 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -240,20 +300,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_192f9f111edce454_EOF' + cat << 'GH_AW_PROMPT_e59da2f8e25b61b4_EOF' - GH_AW_PROMPT_192f9f111edce454_EOF + GH_AW_PROMPT_e59da2f8e25b61b4_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_192f9f111edce454_EOF' + cat << 'GH_AW_PROMPT_e59da2f8e25b61b4_EOF' Tools: add_comment, add_labels, missing_tool, missing_data, noop - GH_AW_PROMPT_192f9f111edce454_EOF + GH_AW_PROMPT_e59da2f8e25b61b4_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_192f9f111edce454_EOF' + cat << 'GH_AW_PROMPT_e59da2f8e25b61b4_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -281,13 +341,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_192f9f111edce454_EOF + + GH_AW_PROMPT_e59da2f8e25b61b4_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_192f9f111edce454_EOF' + cat << 'GH_AW_PROMPT_e59da2f8e25b61b4_EOF' {{#runtime-import .github/workflows/handle-enhancement.md}} - GH_AW_PROMPT_192f9f111edce454_EOF + GH_AW_PROMPT_e59da2f8e25b61b4_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -319,9 +379,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -356,7 +416,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -369,9 +429,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read concurrency: @@ -383,14 +445,18 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: handleenhancement outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} artifact_prefix: ${{ needs.activation.outputs.artifact_prefix }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -400,10 +466,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -412,8 +479,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Enhancement Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-enhancement.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Set runtime paths @@ -425,7 +492,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -434,23 +501,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -462,11 +527,22 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless + - name: Determine automatic lockdown mode for GitHub MCP Server + id: determine-automatic-lockdown + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + env: + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} + GH_AW_GITHUB_MIN_INTEGRITY: 'none' + with: + script: | + const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); + await determineAutomaticLockdown(github, context, core); - name: Parse integrity filter lists id: parse-guard-vars env: @@ -474,16 +550,11 @@ jobs: GH_AW_TRUSTED_USERS_VAR: ${{ vars.GH_AW_GITHUB_TRUSTED_USERS || '' }} GH_AW_APPROVAL_LABELS_VAR: ${{ vars.GH_AW_GITHUB_APPROVAL_LABELS || '' }} run: bash "${RUNNER_TEMP}/gh-aw/actions/parse_guard_list.sh" - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: ${{ needs.activation.outputs.artifact_prefix }}activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -495,15 +566,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_7a0b9826ce5c2de6_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_a36bb21781ffc2fb_EOF' {"add_comment":{"max":1,"target":"*"},"add_labels":{"allowed":["enhancement"],"max":1,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_7a0b9826ce5c2de6_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_a36bb21781ffc2fb_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -547,10 +618,7 @@ jobs: }, "labels": { "required": true, - "type": "array", - "itemType": "string", - "itemSanitize": true, - "itemMaxLength": 128 + "type": "array" }, "repo": { "type": "string", @@ -639,60 +707,22 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -701,29 +731,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_fc710c56a8354bbf_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -738,16 +763,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -759,7 +803,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_fc710c56a8354bbf_EOF + GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -788,41 +832,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 5 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -837,7 +891,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -845,17 +900,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -879,8 +927,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -914,6 +961,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -935,16 +983,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1007,17 +1046,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-handle-enhancement-${{ inputs.issue_number }}" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1026,7 +1067,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1035,8 +1076,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Enhancement Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-enhancement.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1053,6 +1094,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handleenhancement-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handleenhancement- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handleenhancement-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1064,6 +1197,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "handle-enhancement" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1131,23 +1268,30 @@ jobs: GH_AW_WORKFLOW_ID: "handle-enhancement" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "5" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1160,19 +1304,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1181,8 +1328,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Enhancement Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-enhancement.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1201,7 +1348,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1210,7 +1357,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1229,12 +1376,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1272,11 +1420,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1286,39 +1434,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1332,7 +1492,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1382,18 +1556,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/handle-enhancement" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "handle-enhancement" GH_AW_WORKFLOW_NAME: "Enhancement Handler" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/handle-enhancement.md" @@ -1409,7 +1587,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1418,8 +1596,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Enhancement Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-enhancement.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1439,7 +1617,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1471,4 +1649,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/handle-enhancement.md b/.github/workflows/handle-enhancement.md index 6dcb2aa0fd..9043c181c1 100644 --- a/.github/workflows/handle-enhancement.md +++ b/.github/workflows/handle-enhancement.md @@ -16,6 +16,7 @@ permissions: contents: read issues: read pull-requests: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/handle-question.lock.yml b/.github/workflows/handle-question.lock.yml index 14f7fe1995..5c2a4b849b 100644 --- a/.github/workflows/handle-question.lock.yml +++ b/.github/workflows/handle-question.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"fb6cc48845814496ea0da474d3030f9e02e7d38b5bb346b70ca525c06c271cb1","body_hash":"1bdd19aae2095beb6e3fcf7af755cd102d424de3a8727ef6e4674815950c7e8b","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"92158ba4f7e373cb65457b060c7645569b32c756c13c025837491f6809cf694f","body_hash":"1bdd19aae2095beb6e3fcf7af755cd102d424de3a8727ef6e4674815950c7e8b","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -31,20 +32,24 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Question Handler" on: @@ -79,7 +84,7 @@ on: permissions: {} concurrency: - group: "gh-aw-${{ github.workflow }}" + group: "gh-aw-handle-question-${{ github.run_id }}" run-name: "Question Handler" @@ -89,14 +94,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: artifact_prefix: ${{ steps.artifact-prefix.outputs.prefix }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -108,15 +119,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Question Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-question.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Resolve host repo for activation checkout @@ -144,16 +156,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Question Handler" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -165,11 +177,57 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handlequestion-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handlequestion- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Question Handler" + GH_AW_WORKFLOW_ID: "handle-question" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Print cross-repo setup guidance if: failure() && steps.resolve-host-repo.outputs.target_repo != github.repository run: | @@ -178,7 +236,7 @@ jobs: echo "::error::See: https://github.github.com/gh-aw/patterns/central-repo-ops/#cross-repo-setup" - name: Checkout .github and .agents folders if: steps.resolve-host-repo.outputs.target_repo == github.repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false repository: ${{ steps.resolve-host-repo.outputs.target_repo }} @@ -189,7 +247,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -197,8 +254,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -216,13 +273,16 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -240,20 +300,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_0e4131663d1691aa_EOF' + cat << 'GH_AW_PROMPT_a6cfd5b92b97c528_EOF' - GH_AW_PROMPT_0e4131663d1691aa_EOF + GH_AW_PROMPT_a6cfd5b92b97c528_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_0e4131663d1691aa_EOF' + cat << 'GH_AW_PROMPT_a6cfd5b92b97c528_EOF' Tools: add_comment, add_labels, missing_tool, missing_data, noop - GH_AW_PROMPT_0e4131663d1691aa_EOF + GH_AW_PROMPT_a6cfd5b92b97c528_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_0e4131663d1691aa_EOF' + cat << 'GH_AW_PROMPT_a6cfd5b92b97c528_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -281,13 +341,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_0e4131663d1691aa_EOF + + GH_AW_PROMPT_a6cfd5b92b97c528_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_0e4131663d1691aa_EOF' + cat << 'GH_AW_PROMPT_a6cfd5b92b97c528_EOF' {{#runtime-import .github/workflows/handle-question.md}} - GH_AW_PROMPT_0e4131663d1691aa_EOF + GH_AW_PROMPT_a6cfd5b92b97c528_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -319,9 +379,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -356,7 +416,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -369,9 +429,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read concurrency: @@ -383,14 +445,18 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: handlequestion outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} artifact_prefix: ${{ needs.activation.outputs.artifact_prefix }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -400,10 +466,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -412,8 +479,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Question Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-question.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Set runtime paths @@ -425,7 +492,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -434,23 +501,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -462,11 +527,22 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless + - name: Determine automatic lockdown mode for GitHub MCP Server + id: determine-automatic-lockdown + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + env: + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} + GH_AW_GITHUB_MIN_INTEGRITY: 'none' + with: + script: | + const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); + await determineAutomaticLockdown(github, context, core); - name: Parse integrity filter lists id: parse-guard-vars env: @@ -474,16 +550,11 @@ jobs: GH_AW_TRUSTED_USERS_VAR: ${{ vars.GH_AW_GITHUB_TRUSTED_USERS || '' }} GH_AW_APPROVAL_LABELS_VAR: ${{ vars.GH_AW_GITHUB_APPROVAL_LABELS || '' }} run: bash "${RUNNER_TEMP}/gh-aw/actions/parse_guard_list.sh" - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: ${{ needs.activation.outputs.artifact_prefix }}activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -495,15 +566,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_f18ff0beb4e2bc07_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_564a988b74c338ef_EOF' {"add_comment":{"max":1,"target":"*"},"add_labels":{"allowed":["question"],"max":1,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_f18ff0beb4e2bc07_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_564a988b74c338ef_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -547,10 +618,7 @@ jobs: }, "labels": { "required": true, - "type": "array", - "itemType": "string", - "itemSanitize": true, - "itemMaxLength": 128 + "type": "array" }, "repo": { "type": "string", @@ -639,60 +707,22 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -701,29 +731,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_878c9f46d6eeb406_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -738,16 +763,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -759,7 +803,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_878c9f46d6eeb406_EOF + GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -788,41 +832,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 5 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -837,7 +891,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -845,17 +900,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -879,8 +927,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -914,6 +961,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -935,16 +983,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1007,17 +1046,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-handle-question-${{ inputs.issue_number }}" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1026,7 +1067,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1035,8 +1076,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Question Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-question.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1053,6 +1094,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ${{ needs.activation.outputs.artifact_prefix }}usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handlequestion-${{ github.run_id }} + restore-keys: agentic-workflow-usage-handlequestion- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-handlequestion-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1064,6 +1197,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "handle-question" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1131,23 +1268,30 @@ jobs: GH_AW_WORKFLOW_ID: "handle-question" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "5" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1160,19 +1304,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1181,8 +1328,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Question Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-question.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1201,7 +1348,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1210,7 +1357,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1229,12 +1376,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1272,11 +1420,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1286,39 +1434,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1332,7 +1492,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1382,18 +1556,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/handle-question" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "handle-question" GH_AW_WORKFLOW_NAME: "Question Handler" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/handle-question.md" @@ -1409,7 +1587,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1418,8 +1596,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Question Handler" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/handle-question.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }} - name: Download agent output artifact @@ -1439,7 +1617,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1471,4 +1649,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/handle-question.md b/.github/workflows/handle-question.md index 2bf3a65235..21a10d468a 100644 --- a/.github/workflows/handle-question.md +++ b/.github/workflows/handle-question.md @@ -16,6 +16,7 @@ permissions: contents: read issues: read pull-requests: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/issue-classification.lock.yml b/.github/workflows/issue-classification.lock.yml index 0fd6359144..e06af36319 100644 --- a/.github/workflows/issue-classification.lock.yml +++ b/.github/workflows/issue-classification.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"1c9f9a62a510a7796b96187fbe0537fd05da1c082d8fab86cd7b99bf001aee01","body_hash":"8e7ac9b7bb6ab07630a10a4a016108ba59f70feadf82a7391ca0ba5504e14bff","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"797f7487a67c2fa4465cb3fd31e17c9f0620bb232b2a4fb693c62cb76d5d5a36","body_hash":"8e7ac9b7bb6ab07630a10a4a016108ba59f70feadf82a7391ca0ba5504e14bff","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -31,26 +32,30 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Issue Classification Agent" on: issues: types: - - opened + - opened # roles: all # Roles processed as role check in pre-activation job workflow_dispatch: inputs: @@ -77,14 +82,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: body: ${{ steps.sanitized.outputs.body }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -94,15 +105,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Classification Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-classification.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info @@ -110,16 +122,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Issue Classification Agent" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -130,13 +142,59 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-issueclassification-${{ github.run_id }} + restore-keys: agentic-workflow-usage-issueclassification- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Issue Classification Agent" + GH_AW_WORKFLOW_ID: "issue-classification" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Checkout .github and .agents folders - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false sparse-checkout: | @@ -145,7 +203,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -153,8 +210,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -172,7 +229,7 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -190,6 +247,9 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/compute_text.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -209,20 +269,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF' + cat << 'GH_AW_PROMPT_2b9644ded951c90e_EOF' - GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF + GH_AW_PROMPT_2b9644ded951c90e_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF' + cat << 'GH_AW_PROMPT_2b9644ded951c90e_EOF' Tools: add_comment, call_workflow, missing_tool, missing_data, noop - GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF + GH_AW_PROMPT_2b9644ded951c90e_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF' + cat << 'GH_AW_PROMPT_2b9644ded951c90e_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -250,13 +310,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF + + GH_AW_PROMPT_2b9644ded951c90e_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF' + cat << 'GH_AW_PROMPT_2b9644ded951c90e_EOF' {{#runtime-import .github/workflows/issue-classification.md}} - GH_AW_PROMPT_0e5e0cb2acba7dc0_EOF + GH_AW_PROMPT_2b9644ded951c90e_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -293,9 +353,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -332,7 +392,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -345,9 +405,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read env: @@ -356,13 +418,17 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: issueclassification outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -372,10 +438,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -384,8 +451,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Classification Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-classification.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths @@ -396,7 +463,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -405,23 +472,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -433,11 +498,22 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless + - name: Determine automatic lockdown mode for GitHub MCP Server + id: determine-automatic-lockdown + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + env: + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} + GH_AW_GITHUB_MIN_INTEGRITY: 'none' + with: + script: | + const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); + await determineAutomaticLockdown(github, context, core); - name: Parse integrity filter lists id: parse-guard-vars env: @@ -445,16 +521,11 @@ jobs: GH_AW_TRUSTED_USERS_VAR: ${{ vars.GH_AW_GITHUB_TRUSTED_USERS || '' }} GH_AW_APPROVAL_LABELS_VAR: ${{ vars.GH_AW_GITHUB_APPROVAL_LABELS || '' }} run: bash "${RUNNER_TEMP}/gh-aw/actions/parse_guard_list.sh" - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -466,15 +537,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_0e1d49da13fc6a56_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_3e3303377640f8c6_EOF' {"add_comment":{"max":1,"target":"triggering"},"call_workflow":{"max":1,"workflow_files":{"handle-bug":"./.github/workflows/handle-bug.lock.yml","handle-documentation":"./.github/workflows/handle-documentation.lock.yml","handle-enhancement":"./.github/workflows/handle-enhancement.lock.yml","handle-question":"./.github/workflows/handle-question.lock.yml"},"workflows":["handle-bug","handle-enhancement","handle-question","handle-documentation"]},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_0e1d49da13fc6a56_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_3e3303377640f8c6_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -699,60 +770,22 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -761,29 +794,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_5ad084c2b5bc2d53_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -798,16 +826,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -819,7 +866,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_5ad084c2b5bc2d53_EOF + GH_AW_MCP_CONFIG_e85305aae15b8db5_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -848,41 +895,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 10 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -897,7 +954,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -905,17 +963,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -939,8 +990,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -974,6 +1024,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -995,16 +1046,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1062,10 +1104,12 @@ jobs: call-handle-bug: needs: safe_outputs if: needs.safe_outputs.outputs.call_workflow_name == 'handle-bug' + # Imported from called workflow "handle-bug" because GitHub requires the caller job to grant permissions requested by reusable workflow jobs. + # Review the called workflow's job-level permissions in ./.github/workflows/handle-bug.lock.yml. permissions: actions: read contents: read - discussions: write + copilot-requests: write issues: write pull-requests: write uses: ./.github/workflows/handle-bug.lock.yml @@ -1081,10 +1125,12 @@ jobs: call-handle-documentation: needs: safe_outputs if: needs.safe_outputs.outputs.call_workflow_name == 'handle-documentation' + # Imported from called workflow "handle-documentation" because GitHub requires the caller job to grant permissions requested by reusable workflow jobs. + # Review the called workflow's job-level permissions in ./.github/workflows/handle-documentation.lock.yml. permissions: actions: read contents: read - discussions: write + copilot-requests: write issues: write pull-requests: write uses: ./.github/workflows/handle-documentation.lock.yml @@ -1100,10 +1146,12 @@ jobs: call-handle-enhancement: needs: safe_outputs if: needs.safe_outputs.outputs.call_workflow_name == 'handle-enhancement' + # Imported from called workflow "handle-enhancement" because GitHub requires the caller job to grant permissions requested by reusable workflow jobs. + # Review the called workflow's job-level permissions in ./.github/workflows/handle-enhancement.lock.yml. permissions: actions: read contents: read - discussions: write + copilot-requests: write issues: write pull-requests: write uses: ./.github/workflows/handle-enhancement.lock.yml @@ -1119,10 +1167,12 @@ jobs: call-handle-question: needs: safe_outputs if: needs.safe_outputs.outputs.call_workflow_name == 'handle-question' + # Imported from called workflow "handle-question" because GitHub requires the caller job to grant permissions requested by reusable workflow jobs. + # Review the called workflow's job-level permissions in ./.github/workflows/handle-question.lock.yml. permissions: actions: read contents: read - discussions: write + copilot-requests: write issues: write pull-requests: write uses: ./.github/workflows/handle-question.lock.yml @@ -1147,17 +1197,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-issue-classification" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1166,7 +1218,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1175,8 +1227,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Classification Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-classification.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1192,6 +1244,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-issueclassification-${{ github.run_id }} + restore-keys: agentic-workflow-usage-issueclassification- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-issueclassification-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1203,6 +1347,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "issue-classification" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1270,23 +1418,30 @@ jobs: GH_AW_WORKFLOW_ID: "issue-classification" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "10" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1299,19 +1454,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1320,8 +1478,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Classification Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-classification.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1339,7 +1497,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1348,7 +1506,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1367,12 +1525,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1410,11 +1569,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1424,39 +1583,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1470,7 +1641,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1520,18 +1705,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/issue-classification" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "issue-classification" GH_AW_WORKFLOW_NAME: "Issue Classification Agent" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/issue-classification.md" @@ -1549,7 +1738,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1558,8 +1747,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Classification Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-classification.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1578,7 +1767,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1610,4 +1799,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/issue-classification.md b/.github/workflows/issue-classification.md index af682461f5..b1e3345f91 100644 --- a/.github/workflows/issue-classification.md +++ b/.github/workflows/issue-classification.md @@ -14,6 +14,7 @@ permissions: contents: read issues: read pull-requests: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/issue-triage.lock.yml b/.github/workflows/issue-triage.lock.yml index dce3e9171d..4f4ef28f1a 100644 --- a/.github/workflows/issue-triage.lock.yml +++ b/.github/workflows/issue-triage.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4472ef96371b3dbbd8e7b52b2612d552047d519ba61344a9b2a92e663fee87ed","body_hash":"30994be7c5c23b102c12a56a325ac313e413a2507dff11d0dc695899379bfbd0","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"596392856be0229eb9fd3a16e2de146d2c9f5f8484809a28e50c861f386652af","body_hash":"30994be7c5c23b102c12a56a325ac313e413a2507dff11d0dc695899379bfbd0","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -31,27 +32,30 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Issue Triage Agent" on: issues: types: - - opened + - opened # roles: all # Roles processed as role check in pre-activation job workflow_dispatch: inputs: @@ -78,14 +82,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: body: ${{ steps.sanitized.outputs.body }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -95,15 +105,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Triage Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-triage.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info @@ -111,16 +122,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Issue Triage Agent" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -131,13 +142,59 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-issuetriage-${{ github.run_id }} + restore-keys: agentic-workflow-usage-issuetriage- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Issue Triage Agent" + GH_AW_WORKFLOW_ID: "issue-triage" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Checkout .github and .agents folders - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false sparse-checkout: | @@ -146,7 +203,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -154,8 +210,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -173,7 +229,7 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -191,6 +247,9 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/compute_text.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -210,20 +269,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_294c35176923eb24_EOF' + cat << 'GH_AW_PROMPT_39930e94844c6d8f_EOF' - GH_AW_PROMPT_294c35176923eb24_EOF + GH_AW_PROMPT_39930e94844c6d8f_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_294c35176923eb24_EOF' + cat << 'GH_AW_PROMPT_39930e94844c6d8f_EOF' Tools: add_comment(max:2), close_issue, update_issue, add_labels(max:10), missing_tool, missing_data, noop - GH_AW_PROMPT_294c35176923eb24_EOF + GH_AW_PROMPT_39930e94844c6d8f_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_294c35176923eb24_EOF' + cat << 'GH_AW_PROMPT_39930e94844c6d8f_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -251,13 +310,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_294c35176923eb24_EOF + + GH_AW_PROMPT_39930e94844c6d8f_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_294c35176923eb24_EOF' + cat << 'GH_AW_PROMPT_39930e94844c6d8f_EOF' {{#runtime-import .github/workflows/issue-triage.md}} - GH_AW_PROMPT_294c35176923eb24_EOF + GH_AW_PROMPT_39930e94844c6d8f_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -294,9 +353,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -333,7 +392,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -346,9 +405,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read env: @@ -357,13 +418,17 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: issuetriage outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -373,10 +438,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -385,8 +451,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Triage Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-triage.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths @@ -397,7 +463,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -406,23 +472,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -434,14 +498,14 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless - name: Determine automatic lockdown mode for GitHub MCP Server id: determine-automatic-lockdown - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 env: GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} @@ -449,16 +513,11 @@ jobs: script: | const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); await determineAutomaticLockdown(github, context, core); - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -470,15 +529,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_90ffae57d01667f3_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_bd9befd4ae64abbb_EOF' {"add_comment":{"max":2},"add_labels":{"allowed":["bug","enhancement","question","documentation","sdk/dotnet","sdk/go","sdk/java","sdk/nodejs","sdk/python","priority/high","priority/low","testing","security","needs-info","duplicate"],"max":10,"target":"triggering"},"close_issue":{"max":1,"target":"triggering"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{},"update_issue":{"allow_body":true,"max":1,"target":"triggering"}} - GH_AW_SAFE_OUTPUTS_CONFIG_90ffae57d01667f3_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_bd9befd4ae64abbb_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -524,10 +583,7 @@ jobs: }, "labels": { "required": true, - "type": "array", - "itemType": "string", - "itemSanitize": true, - "itemMaxLength": 128 + "type": "array" }, "repo": { "type": "string", @@ -643,10 +699,7 @@ jobs: "issueOrPRNumber": true }, "labels": { - "type": "array", - "itemType": "string", - "itemSanitize": true, - "itemMaxLength": 128 + "type": "array" }, "milestone": { "optionalPositiveInteger": true @@ -677,7 +730,7 @@ jobs: "maxLength": 128 } }, - "customValidation": "requiresOneOf:status,title,body" + "customValidation": "requiresOneOf:status,title,body,labels,assignees,milestone" } } uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -687,62 +740,24 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_GUARD_MIN_INTEGRITY: ${{ steps.determine-automatic-lockdown.outputs.min_integrity }} GITHUB_MCP_GUARD_REPOS: ${{ steps.determine-automatic-lockdown.outputs.repos }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -751,29 +766,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_90b7530930d86f98_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -785,16 +795,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -806,7 +835,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_90b7530930d86f98_EOF + GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -835,41 +864,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 10 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -884,7 +923,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -892,17 +932,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -926,8 +959,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -961,6 +993,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -982,16 +1015,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1052,17 +1076,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-issue-triage" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1071,7 +1097,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1080,8 +1106,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Triage Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-triage.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1097,6 +1123,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-issuetriage-${{ github.run_id }} + restore-keys: agentic-workflow-usage-issuetriage- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-issuetriage-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1108,6 +1226,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "issue-triage" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1175,23 +1297,30 @@ jobs: GH_AW_WORKFLOW_ID: "issue-triage" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "10" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1204,19 +1333,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1225,8 +1357,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Triage Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-triage.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1244,7 +1376,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1253,7 +1385,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1272,12 +1404,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1315,11 +1448,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1329,39 +1462,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1375,7 +1520,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1425,18 +1584,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/issue-triage" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "issue-triage" GH_AW_WORKFLOW_NAME: "Issue Triage Agent" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/issue-triage.md" @@ -1452,7 +1615,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1461,8 +1624,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Issue Triage Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/issue-triage.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1481,7 +1644,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1513,4 +1676,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/issue-triage.md b/.github/workflows/issue-triage.md index 72f2042dc9..c4f774c0db 100644 --- a/.github/workflows/issue-triage.md +++ b/.github/workflows/issue-triage.md @@ -14,6 +14,7 @@ permissions: contents: read issues: read pull-requests: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml b/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml index f099dd9da4..3a7335922b 100644 --- a/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml +++ b/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e539700f2389ba9b056bf59e91a04578013218d4a37bbeee4e1db3e88e39af45","body_hash":"41bc10df4ac9179064417476fbb39fef7423d0998dc0beb7bad42e9eb7ab0494","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"a5f19a89f89b0693f86ca89ea90e3a633fe19c17bf4d27214fa9124429cdc156","body_hash":"41bc10df4ac9179064417476fbb39fef7423d0998dc0beb7bad42e9eb7ab0494","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -34,21 +35,24 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Java Handwritten Code Adaptation After CLI Upgrade" on: @@ -81,13 +85,19 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -95,15 +105,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info @@ -111,16 +122,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults","github"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -131,13 +142,59 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-javaadapthandwrittencodetoacceptupgradechanges-${{ github.run_id }} + restore-keys: agentic-workflow-usage-javaadapthandwrittencodetoacceptupgradechanges- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" + GH_AW_WORKFLOW_ID: "java-adapt-handwritten-code-to-accept-upgrade-changes" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Checkout .github and .agents folders - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false sparse-checkout: | @@ -146,7 +203,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -154,8 +210,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -173,13 +229,16 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -198,23 +257,23 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_c4f6bd591c056d39_EOF' + cat << 'GH_AW_PROMPT_67432b380d9d8ebb_EOF' - GH_AW_PROMPT_c4f6bd591c056d39_EOF + GH_AW_PROMPT_67432b380d9d8ebb_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_c4f6bd591c056d39_EOF' + cat << 'GH_AW_PROMPT_67432b380d9d8ebb_EOF' Tools: add_comment(max:10), push_to_pull_request_branch, missing_tool, missing_data, noop - GH_AW_PROMPT_c4f6bd591c056d39_EOF + GH_AW_PROMPT_67432b380d9d8ebb_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_push_to_pr_branch.md" - cat << 'GH_AW_PROMPT_c4f6bd591c056d39_EOF' + cat << 'GH_AW_PROMPT_67432b380d9d8ebb_EOF' - GH_AW_PROMPT_c4f6bd591c056d39_EOF + GH_AW_PROMPT_67432b380d9d8ebb_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_c4f6bd591c056d39_EOF' + cat << 'GH_AW_PROMPT_67432b380d9d8ebb_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -242,13 +301,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_c4f6bd591c056d39_EOF + + GH_AW_PROMPT_67432b380d9d8ebb_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_c4f6bd591c056d39_EOF' + cat << 'GH_AW_PROMPT_67432b380d9d8ebb_EOF' {{#runtime-import .github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.md}} - GH_AW_PROMPT_c4f6bd591c056d39_EOF + GH_AW_PROMPT_67432b380d9d8ebb_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -282,9 +341,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -320,7 +379,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -333,23 +392,29 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: actions: read contents: read + copilot-requests: write env: DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} GH_AW_ASSETS_ALLOWED_EXTS: "" GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: javaadapthandwrittencodetoacceptupgradechanges outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -359,10 +424,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -371,8 +437,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths @@ -383,7 +449,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -392,23 +458,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -420,14 +484,14 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless - name: Determine automatic lockdown mode for GitHub MCP Server id: determine-automatic-lockdown - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 env: GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} @@ -435,16 +499,11 @@ jobs: script: | const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); await determineAutomaticLockdown(github, context, core); - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -456,15 +515,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_aebcb23c2a00f40b_EOF' - {"add_comment":{"max":10,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"false"},"push_to_pull_request_branch":{"if_no_changes":"warn","max_patch_size":1024,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"required_labels":["dependencies","sdk/java"],"target":"*"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_aebcb23c2a00f40b_EOF + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_fcd407b1cd819e9a_EOF' + {"add_comment":{"max":10,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"false"},"push_to_pull_request_branch":{"if_no_changes":"warn","max_patch_size":4096,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"required_labels":["dependencies","sdk/java"],"target":"*"},"report_incomplete":{}} + GH_AW_SAFE_OUTPUTS_CONFIG_fcd407b1cd819e9a_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -560,7 +619,6 @@ jobs: "defaultMax": 1, "fields": { "branch": { - "required": true, "type": "string", "sanitize": true, "maxLength": 256 @@ -600,62 +658,24 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_GUARD_MIN_INTEGRITY: ${{ steps.determine-automatic-lockdown.outputs.min_integrity }} GITHUB_MCP_GUARD_REPOS: ${{ steps.determine-automatic-lockdown.outputs.repos }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -664,29 +684,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_8710e02016d3ca0b_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_89bf9ba8e0ab7f74_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos" }, @@ -698,16 +713,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -719,7 +753,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_8710e02016d3ca0b_EOF + GH_AW_MCP_CONFIG_89bf9ba8e0ab7f74_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -748,41 +782,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["*.githubusercontent.com","api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","codeload.github.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","docs.github.com","github-cloud.githubusercontent.com","github-cloud.s3.amazonaws.com","github.blog","github.com","github.githubassets.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","lfs.github.com","objects.githubusercontent.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","patch-diff.githubusercontent.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"*.githubusercontent.com\",\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"codeload.github.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"docs.github.com\",\"github-cloud.githubusercontent.com\",\"github-cloud.s3.amazonaws.com\",\"github.blog\",\"github.com\",\"github.githubassets.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"lfs.github.com\",\"objects.githubusercontent.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"patch-diff.githubusercontent.com\",\"patchdiff.githubusercontent.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 60 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -797,7 +841,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -805,17 +850,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -839,8 +877,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -860,7 +897,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,patchdiff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} with: @@ -874,6 +911,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -895,16 +933,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -965,17 +994,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: write - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-java-adapt-handwritten-code-to-accept-upgrade-changes" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -984,7 +1015,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -993,8 +1024,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1010,6 +1041,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-javaadapthandwrittencodetoacceptupgradechanges-${{ github.run_id }} + restore-keys: agentic-workflow-usage-javaadapthandwrittencodetoacceptupgradechanges- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-javaadapthandwrittencodetoacceptupgradechanges-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1021,6 +1144,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "false" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "java-adapt-handwritten-code-to-accept-upgrade-changes" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1088,25 +1215,32 @@ jobs: GH_AW_WORKFLOW_ID: "java-adapt-handwritten-code-to-accept-upgrade-changes" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_CODE_PUSH_FAILURE_ERRORS: ${{ needs.safe_outputs.outputs.code_push_failure_errors }} GH_AW_CODE_PUSH_FAILURE_COUNT: ${{ needs.safe_outputs.outputs.code_push_failure_count }} GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "60" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1119,19 +1253,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1140,8 +1277,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1159,7 +1296,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1168,7 +1305,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1187,12 +1324,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1230,11 +1368,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1244,39 +1382,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1290,7 +1440,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1340,18 +1504,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: write - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/java-adapt-handwritten-code-to-accept-upgrade-changes" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "java-adapt-handwritten-code-to-accept-upgrade-changes" GH_AW_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.md" @@ -1369,7 +1537,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1378,8 +1546,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Handwritten Code Adaptation After CLI Upgrade" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1401,50 +1569,23 @@ jobs: with: name: agent path: /tmp/gh-aw/ - - name: Extract base branch from agent output - id: extract-base-branch - if: steps.download-agent-output.outcome == 'success' - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require('${{ runner.temp }}/gh-aw/actions/extract_base_branch_from_agent_output.cjs'); - await main(); - - name: Checkout repository (trusted default branch for comment events) - if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment') - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - ref: ${{ github.event.repository.default_branch }} - token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - persist-credentials: false - fetch-depth: 1 - name: Checkout repository - if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: - ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }} + persist-credentials: true token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - persist-credentials: false - fetch-depth: 1 - name: Configure Git credentials if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GIT_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GIT_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1456,10 +1597,10 @@ jobs: env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_COMMENT_ID: ${{ needs.activation.outputs.comment_id }} - GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,patchdiff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} - GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":10,\"target\":\"*\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"push_to_pull_request_branch\":{\"if_no_changes\":\"warn\",\"max_patch_size\":1024,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"required_labels\":[\"dependencies\",\"sdk/java\"],\"target\":\"*\"},\"report_incomplete\":{}}" + GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":10,\"target\":\"*\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"push_to_pull_request_branch\":{\"if_no_changes\":\"warn\",\"max_patch_size\":4096,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"required_labels\":[\"dependencies\",\"sdk/java\"],\"target\":\"*\"},\"report_incomplete\":{}}" GH_AW_CI_TRIGGER_TOKEN: ${{ secrets.GH_AW_CI_TRIGGER_TOKEN }} with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -1477,4 +1618,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.md b/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.md index e3661607f6..b1623ff78a 100644 --- a/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.md +++ b/.github/workflows/java-adapt-handwritten-code-to-accept-upgrade-changes.md @@ -20,6 +20,7 @@ permissions: contents: read actions: read + copilot-requests: write timeout-minutes: 60 network: @@ -34,7 +35,7 @@ tools: safe-outputs: push-to-pull-request-branch: target: "*" - labels: [dependencies, sdk/java] + required-labels: [dependencies, sdk/java] add-comment: target: "*" max: 10 @@ -155,4 +156,4 @@ git push origin "${{ inputs.branch }}" Then add a comment to PR #${{ inputs.pr_number }} summarizing what was fixed. -If after 3 full fix-compile-test cycles the build still fails, add a comment to the PR describing the remaining failures and stop. +If after 3 full fix-compile-test cycles the build still fails, add a comment to the PR describing the remaining failures and stop. \ No newline at end of file diff --git a/.github/workflows/java-codegen-fix.lock.yml b/.github/workflows/java-codegen-fix.lock.yml index 79d9505ec3..11e1b91842 100644 --- a/.github/workflows/java-codegen-fix.lock.yml +++ b/.github/workflows/java-codegen-fix.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"af13eefc935af6393de806a9a4307707d3b51a8c0d96992a84383cd9be790d52","body_hash":"fe41f8fe1c12cb585cfaefdd755f58d2a84410d9d819cd706a3192ce052e2545","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"b0390c9ab9beb0d7e106314299e89e486269ab7f64d8489d5021132d79aa6b9b","body_hash":"fe41f8fe1c12cb585cfaefdd755f58d2a84410d9d819cd706a3192ce052e2545","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -33,21 +34,24 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Java Codegen Agentic Fix" on: @@ -84,13 +88,19 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -98,15 +108,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Java Codegen Agentic Fix" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-codegen-fix.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info @@ -114,16 +125,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Java Codegen Agentic Fix" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults","github"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -134,13 +145,59 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-javacodegenfix-${{ github.run_id }} + restore-keys: agentic-workflow-usage-javacodegenfix- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Java Codegen Agentic Fix" + GH_AW_WORKFLOW_ID: "java-codegen-fix" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Checkout .github and .agents folders - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false sparse-checkout: | @@ -149,7 +206,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -157,8 +213,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -176,13 +232,16 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -202,23 +261,23 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_1b89baae00b47687_EOF' + cat << 'GH_AW_PROMPT_7834a0b5f08e9149_EOF' - GH_AW_PROMPT_1b89baae00b47687_EOF + GH_AW_PROMPT_7834a0b5f08e9149_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_1b89baae00b47687_EOF' + cat << 'GH_AW_PROMPT_7834a0b5f08e9149_EOF' Tools: add_comment(max:5), push_to_pull_request_branch, missing_tool, missing_data, noop - GH_AW_PROMPT_1b89baae00b47687_EOF + GH_AW_PROMPT_7834a0b5f08e9149_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_push_to_pr_branch.md" - cat << 'GH_AW_PROMPT_1b89baae00b47687_EOF' + cat << 'GH_AW_PROMPT_7834a0b5f08e9149_EOF' - GH_AW_PROMPT_1b89baae00b47687_EOF + GH_AW_PROMPT_7834a0b5f08e9149_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_1b89baae00b47687_EOF' + cat << 'GH_AW_PROMPT_7834a0b5f08e9149_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -246,13 +305,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_1b89baae00b47687_EOF + + GH_AW_PROMPT_7834a0b5f08e9149_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_1b89baae00b47687_EOF' + cat << 'GH_AW_PROMPT_7834a0b5f08e9149_EOF' {{#runtime-import .github/workflows/java-codegen-fix.md}} - GH_AW_PROMPT_1b89baae00b47687_EOF + GH_AW_PROMPT_7834a0b5f08e9149_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -288,9 +347,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -327,7 +386,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -340,23 +399,29 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: actions: read contents: read + copilot-requests: write env: DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} GH_AW_ASSETS_ALLOWED_EXTS: "" GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: javacodegenfix outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -366,10 +431,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -378,8 +444,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Codegen Agentic Fix" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-codegen-fix.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths @@ -390,7 +456,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -399,23 +465,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -427,14 +491,14 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless - name: Determine automatic lockdown mode for GitHub MCP Server id: determine-automatic-lockdown - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 env: GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} @@ -442,16 +506,11 @@ jobs: script: | const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); await determineAutomaticLockdown(github, context, core); - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -463,15 +522,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_9547b36a6c2ad8b6_EOF' - {"add_comment":{"max":5,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"false"},"push_to_pull_request_branch":{"if_no_changes":"warn","max_patch_size":1024,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"required_labels":["dependencies"],"target":"*"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_9547b36a6c2ad8b6_EOF + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_cf285131e299ca5f_EOF' + {"add_comment":{"max":5,"target":"*"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"false"},"push_to_pull_request_branch":{"if_no_changes":"warn","max_patch_size":4096,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"required_labels":["dependencies"],"target":"*"},"report_incomplete":{}} + GH_AW_SAFE_OUTPUTS_CONFIG_cf285131e299ca5f_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -567,7 +626,6 @@ jobs: "defaultMax": 1, "fields": { "branch": { - "required": true, "type": "string", "sanitize": true, "maxLength": 256 @@ -607,62 +665,24 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_GUARD_MIN_INTEGRITY: ${{ steps.determine-automatic-lockdown.outputs.min_integrity }} GITHUB_MCP_GUARD_REPOS: ${{ steps.determine-automatic-lockdown.outputs.repos }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -671,29 +691,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_209c8aba9155ceb2_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_89bf9ba8e0ab7f74_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos" }, @@ -705,16 +720,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -726,7 +760,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_209c8aba9155ceb2_EOF + GH_AW_MCP_CONFIG_89bf9ba8e0ab7f74_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -755,41 +789,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["*.githubusercontent.com","api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","codeload.github.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","docs.github.com","github-cloud.githubusercontent.com","github-cloud.s3.amazonaws.com","github.blog","github.com","github.githubassets.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","lfs.github.com","objects.githubusercontent.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","patch-diff.githubusercontent.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"*.githubusercontent.com\",\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"codeload.github.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"docs.github.com\",\"github-cloud.githubusercontent.com\",\"github-cloud.s3.amazonaws.com\",\"github.blog\",\"github.com\",\"github.githubassets.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"lfs.github.com\",\"objects.githubusercontent.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"patch-diff.githubusercontent.com\",\"patchdiff.githubusercontent.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 60 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -804,7 +848,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -812,17 +857,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -846,8 +884,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -867,7 +904,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,patchdiff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} with: @@ -881,6 +918,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -902,16 +940,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -972,17 +1001,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: write - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-java-codegen-fix" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -991,7 +1022,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1000,8 +1031,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Codegen Agentic Fix" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-codegen-fix.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1017,6 +1048,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-javacodegenfix-${{ github.run_id }} + restore-keys: agentic-workflow-usage-javacodegenfix- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-javacodegenfix-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1028,6 +1151,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "false" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "java-codegen-fix" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1095,25 +1222,32 @@ jobs: GH_AW_WORKFLOW_ID: "java-codegen-fix" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_CODE_PUSH_FAILURE_ERRORS: ${{ needs.safe_outputs.outputs.code_push_failure_errors }} GH_AW_CODE_PUSH_FAILURE_COUNT: ${{ needs.safe_outputs.outputs.code_push_failure_count }} GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "60" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1126,19 +1260,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1147,8 +1284,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Codegen Agentic Fix" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-codegen-fix.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1166,7 +1303,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1175,7 +1312,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1194,12 +1331,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1237,11 +1375,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1251,39 +1389,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1297,7 +1447,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1347,18 +1511,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: write - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/java-codegen-fix" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "java-codegen-fix" GH_AW_WORKFLOW_NAME: "Java Codegen Agentic Fix" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/java-codegen-fix.md" @@ -1376,7 +1544,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1385,8 +1553,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Java Codegen Agentic Fix" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/java-codegen-fix.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1408,50 +1576,23 @@ jobs: with: name: agent path: /tmp/gh-aw/ - - name: Extract base branch from agent output - id: extract-base-branch - if: steps.download-agent-output.outcome == 'success' - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require('${{ runner.temp }}/gh-aw/actions/extract_base_branch_from_agent_output.cjs'); - await main(); - - name: Checkout repository (trusted default branch for comment events) - if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment') - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - ref: ${{ github.event.repository.default_branch }} - token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - persist-credentials: false - fetch-depth: 1 - name: Checkout repository - if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: - ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }} + persist-credentials: true token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - persist-credentials: false - fetch-depth: 1 - name: Configure Git credentials if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GIT_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GIT_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1463,10 +1604,10 @@ jobs: env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_COMMENT_ID: ${{ needs.activation.outputs.comment_id }} - GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,patchdiff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} - GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":5,\"target\":\"*\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"push_to_pull_request_branch\":{\"if_no_changes\":\"warn\",\"max_patch_size\":1024,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"required_labels\":[\"dependencies\"],\"target\":\"*\"},\"report_incomplete\":{}}" + GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":5,\"target\":\"*\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"push_to_pull_request_branch\":{\"if_no_changes\":\"warn\",\"max_patch_size\":4096,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"required_labels\":[\"dependencies\"],\"target\":\"*\"},\"report_incomplete\":{}}" GH_AW_CI_TRIGGER_TOKEN: ${{ secrets.GH_AW_CI_TRIGGER_TOKEN }} with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -1484,4 +1625,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/java-codegen-fix.md b/.github/workflows/java-codegen-fix.md index 882df1d4a7..1fe465f4c5 100644 --- a/.github/workflows/java-codegen-fix.md +++ b/.github/workflows/java-codegen-fix.md @@ -23,6 +23,7 @@ permissions: contents: read actions: read + copilot-requests: write timeout-minutes: 60 network: @@ -37,13 +38,14 @@ tools: safe-outputs: push-to-pull-request-branch: target: "*" - labels: [dependencies] + required-labels: [dependencies] add-comment: target: "*" max: 5 noop: report-as-issue: false --- + # Java Codegen Agentic Fix You are an automation agent that fixes Java compilation and test failures caused by code generation changes in the `copilot-sdk` monorepo. @@ -242,4 +244,4 @@ Do **NOT** push broken code. - You **MAY** modify files under `java/src/main/java/` and `java/src/test/java/` to fix handwritten code - Always run `cd java && mvn spotless:apply` before committing to ensure code formatting - Maximum 3 fix attempts before reporting failure via `noop` -- Only push if `mvn verify` passes +- Only push if `mvn verify` passes \ No newline at end of file diff --git a/.github/workflows/java-publish-maven.yml b/.github/workflows/java-publish-maven.yml index e22cd05a5b..944a0ee38e 100644 --- a/.github/workflows/java-publish-maven.yml +++ b/.github/workflows/java-publish-maven.yml @@ -22,6 +22,34 @@ on: type: boolean required: false default: false + workflow_call: + inputs: + releaseVersion: + description: "Release version (e.g., 1.0.0). If empty, derives from pom.xml by removing -SNAPSHOT" + required: false + type: string + developmentVersion: + description: "Next development version (e.g., 1.0.1-SNAPSHOT). If empty, increments patch version" + required: false + type: string + prerelease: + description: "Is this a prerelease?" + type: boolean + required: false + default: false + secrets: + JAVA_RELEASE_TOKEN: + required: true + JAVA_RELEASE_GITHUB_TOKEN: + required: true + JAVA_MAVEN_CENTRAL_USERNAME: + required: true + JAVA_MAVEN_CENTRAL_PASSWORD: + required: true + JAVA_GPG_SECRET_KEY: + required: true + JAVA_GPG_PASSPHRASE: + required: true permissions: contents: write @@ -144,10 +172,10 @@ jobs: exit 1 fi else - # Split version: supports "0.1.32", "0.1.32-java.0", and "0.1.32-java-preview.0" formats + # Split version: supports "0.1.32", "0.1.32-preview.0", "0.1.32-java.0", and "0.1.32-java-preview.0" formats # Validate RELEASE_VERSION format explicitly to provide clear errors - if ! echo "$RELEASE_VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+(-(beta-)?java(-preview)?\.[0-9]+)?$'; then - echo "Error: RELEASE_VERSION '$RELEASE_VERSION' is invalid. Expected format: M.M.P, M.M.P-java.N, M.M.P-java-preview.N, M.M.P-beta-java.N, or M.M.P-beta-java-preview.N (e.g., 1.2.3, 1.2.3-java.0, 1.2.3-java-preview.0, 1.2.3-beta-java.0, or 1.2.3-beta-java-preview.0)." >&2 + if ! echo "$RELEASE_VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+(-(preview|(beta-)?java(-preview)?)\.[0-9]+)?$'; then + echo "Error: RELEASE_VERSION '$RELEASE_VERSION' is invalid. Expected format: M.M.P, M.M.P-preview.N, M.M.P-java.N, M.M.P-java-preview.N, M.M.P-beta-java.N, or M.M.P-beta-java-preview.N (e.g., 1.2.3, 1.2.3-preview.0, 1.2.3-java.0, 1.2.3-java-preview.0, 1.2.3-beta-java.0, or 1.2.3-beta-java-preview.0)." >&2 exit 1 fi # Extract the base M.M.P portion (before any qualifier) diff --git a/.github/workflows/java-sdk-tests.yml b/.github/workflows/java-sdk-tests.yml index e310fa8ba1..948a986e5a 100644 --- a/.github/workflows/java-sdk-tests.yml +++ b/.github/workflows/java-sdk-tests.yml @@ -31,9 +31,7 @@ on: merge_group: permissions: - contents: write - checks: write - pull-requests: write + contents: read jobs: java-sdk: @@ -77,12 +75,19 @@ jobs: - name: Run spotless check if: matrix.test-jdk == '25' run: | - mvn spotless:check - if [ $? -ne 0 ]; then - echo "❌ spotless:check failed. Please run 'mvn spotless:apply' in java" - exit 1 - fi - echo "✅ spotless:check passed" + max_attempts=3 + for ((attempt=1; attempt<=max_attempts; attempt++)); do + if mvn spotless:check; then + echo "✅ spotless:check passed" + exit 0 + fi + if [ "$attempt" -lt "$max_attempts" ]; then + echo "⚠️ spotless:check failed (attempt $attempt/$max_attempts), retrying in 10s..." + sleep 10 + fi + done + echo "❌ spotless:check failed after $max_attempts attempts. Please run 'mvn spotless:apply' in java/" + exit 1 - name: Run Java SDK tests (JDK 25) if: matrix.test-jdk == '25' @@ -117,22 +122,6 @@ jobs: java/target/surefire-reports-isolated/ retention-days: 1 - - name: Generate JaCoCo badge - if: success() && github.ref == 'refs/heads/main' && matrix.test-jdk == '25' - working-directory: . - run: bash .github/scripts/generate-java-coverage-badge.sh java/target/site/jacoco-coverage/jacoco.csv .github/badges - - - name: Create PR for JaCoCo badge update - if: success() && github.ref == 'refs/heads/main' && matrix.test-jdk == '25' - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v7 - with: - commit-message: "Update Java JaCoCo coverage badge" - title: "Update Java JaCoCo coverage badge" - body: "Automated Java JaCoCo coverage badge update from CI." - branch: auto/update-java-jacoco-badge - add-paths: .github/badges/ - delete-branch: true - - name: Generate Test Report Summary if: always() uses: ./.github/actions/java-test-report diff --git a/.github/workflows/nodejs-sdk-tests.yml b/.github/workflows/nodejs-sdk-tests.yml index 8880cadfa3..647345e0ea 100644 --- a/.github/workflows/nodejs-sdk-tests.yml +++ b/.github/workflows/nodejs-sdk-tests.yml @@ -31,7 +31,7 @@ permissions: jobs: test: - name: "Node.js SDK Tests" + name: "Node.js SDK Tests (${{ matrix.os }}, ${{ matrix.transport }})" if: github.event.repository.fork == false env: POWERSHELL_UPDATECHECK: Off @@ -39,6 +39,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] + transport: ["default", "inprocess"] runs-on: ${{ matrix.os }} defaults: run: @@ -75,6 +76,11 @@ jobs: if: runner.os == 'Windows' run: pwsh.exe -Command "Write-Host 'PowerShell ready'" + - name: Select inprocess transport + if: matrix.transport == 'inprocess' + run: | + echo "COPILOT_SDK_DEFAULT_CONNECTION=inprocess" >> "$GITHUB_ENV" + - name: Run Node.js SDK tests env: COPILOT_HMAC_KEY: ${{ secrets.COPILOT_DEVELOPER_CLI_INTEGRATION_HMAC_KEY }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e5b23a5816..cd96dd0fa9 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -171,13 +171,17 @@ jobs: - name: Set version run: sed -i -E 's/^version = ".*"$/version = "${{ needs.version.outputs.version }}"/' Cargo.toml - name: Snapshot CLI version + hashes for build.rs - run: bash scripts/snapshot-bundled-cli-version.sh - - name: Verify cli-version.txt exists run: | - if [[ ! -f cli-version.txt ]]; then - echo "::error::cli-version.txt was not generated. The Snapshot step must run before packaging." - exit 1 - fi + bash scripts/snapshot-bundled-cli-version.sh + bash scripts/snapshot-bundled-in-process-version.sh + - name: Verify CLI version snapshots exist + run: | + for snapshot in cli-version.txt cli-version-in-process.txt; do + if [[ ! -f "${snapshot}" ]]; then + echo "::error::${snapshot} was not generated. The Snapshot step must run before packaging." + exit 1 + fi + done - name: Package (dry run) run: cargo publish --dry-run --allow-dirty - name: Upload artifact @@ -229,10 +233,28 @@ jobs: with: packages-dir: python/dist/ + publish-java: + name: Publish Java SDK + if: github.event.inputs.dist-tag != 'unstable' && github.ref == 'refs/heads/main' + needs: version + uses: ./.github/workflows/java-publish-maven.yml + with: + releaseVersion: ${{ needs.version.outputs.version }} + prerelease: ${{ github.event.inputs.dist-tag == 'prerelease' }} + secrets: inherit + github-release: name: Create GitHub Release - needs: [version, publish-nodejs, publish-dotnet, publish-python, publish-rust] - if: github.ref == 'refs/heads/main' && github.event.inputs.dist-tag != 'unstable' + needs: [version, publish-nodejs, publish-dotnet, publish-python, publish-rust, publish-java] + if: | + always() && + github.ref == 'refs/heads/main' && + github.event.inputs.dist-tag != 'unstable' && + needs.version.result == 'success' && + needs.publish-nodejs.result == 'success' && + needs.publish-dotnet.result == 'success' && + needs.publish-python.result == 'success' && + needs.publish-rust.result == 'success' runs-on: ubuntu-latest steps: - uses: actions/checkout@v6.0.2 diff --git a/.github/workflows/python-sdk-tests.yml b/.github/workflows/python-sdk-tests.yml index e6260dd0b2..8d3ea07154 100644 --- a/.github/workflows/python-sdk-tests.yml +++ b/.github/workflows/python-sdk-tests.yml @@ -31,7 +31,7 @@ permissions: jobs: test: - name: "Python SDK Tests" + name: "Python SDK Tests (${{ matrix.os }}, ${{ matrix.transport }})" if: github.event.repository.fork == false env: POWERSHELL_UPDATECHECK: Off @@ -41,6 +41,7 @@ jobs: os: [ubuntu-latest, macos-latest, windows-latest] # Test the oldest supported Python version to make sure compatibility is maintained. python-version: ["3.11"] + transport: ["default", "inprocess"] runs-on: ${{ matrix.os }} defaults: run: @@ -86,6 +87,11 @@ jobs: if: runner.os == 'Windows' run: pwsh.exe -Command "Write-Host 'PowerShell ready'" + - name: Select inprocess transport + if: matrix.transport == 'inprocess' + run: | + echo "COPILOT_SDK_DEFAULT_CONNECTION=inprocess" >> "$GITHUB_ENV" + - name: Run Python SDK tests env: COPILOT_HMAC_KEY: ${{ secrets.COPILOT_DEVELOPER_CLI_INTEGRATION_HMAC_KEY }} diff --git a/.github/workflows/release-changelog.lock.yml b/.github/workflows/release-changelog.lock.yml index 4e8adbc0c2..f6ea436049 100644 --- a/.github/workflows/release-changelog.lock.yml +++ b/.github/workflows/release-changelog.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"f56148e477b1349cf894dd5ee148dae8af3a90ab64cf708a41697d2c13b2da4b","body_hash":"89e26ed929f440bd6af57d1da92b06dbf1739b4a1d34b9923286919d00f272d1","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"9342b428009e6a3b47258c08b78735a89fc72714b73a44b72c4714e310d60006","body_hash":"89e26ed929f440bd6af57d1da92b06dbf1739b4a1d34b9923286919d00f272d1","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}]} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -32,21 +33,24 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "Release Changelog Generator" on: @@ -75,13 +79,19 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -89,15 +99,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "Release Changelog Generator" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/release-changelog.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info @@ -105,16 +116,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "Release Changelog Generator" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -125,13 +136,59 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-releasechangelog-${{ github.run_id }} + restore-keys: agentic-workflow-usage-releasechangelog- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "Release Changelog Generator" + GH_AW_WORKFLOW_ID: "release-changelog" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Checkout .github and .agents folders - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false sparse-checkout: | @@ -140,7 +197,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -148,8 +204,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -167,13 +223,16 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -191,23 +250,23 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF' + cat << 'GH_AW_PROMPT_c642707f673b9ac4_EOF' - GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF + GH_AW_PROMPT_c642707f673b9ac4_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF' + cat << 'GH_AW_PROMPT_c642707f673b9ac4_EOF' Tools: create_pull_request, update_release, missing_tool, missing_data, noop - GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF + GH_AW_PROMPT_c642707f673b9ac4_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_create_pull_request.md" - cat << 'GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF' + cat << 'GH_AW_PROMPT_c642707f673b9ac4_EOF' - GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF + GH_AW_PROMPT_c642707f673b9ac4_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF' + cat << 'GH_AW_PROMPT_c642707f673b9ac4_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -235,13 +294,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF + + GH_AW_PROMPT_c642707f673b9ac4_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF' + cat << 'GH_AW_PROMPT_c642707f673b9ac4_EOF' {{#runtime-import .github/workflows/release-changelog.md}} - GH_AW_PROMPT_8ca4e2fb6c3e0923_EOF + GH_AW_PROMPT_c642707f673b9ac4_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -274,9 +333,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -311,7 +370,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -324,10 +383,12 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: actions: read contents: read + copilot-requests: write issues: read pull-requests: read env: @@ -336,13 +397,17 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: releasechangelog outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -352,10 +417,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -364,8 +430,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Release Changelog Generator" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/release-changelog.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths @@ -376,7 +442,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -385,23 +451,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -413,14 +477,14 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless - name: Determine automatic lockdown mode for GitHub MCP Server id: determine-automatic-lockdown - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 env: GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} @@ -428,16 +492,11 @@ jobs: script: | const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); await determineAutomaticLockdown(github, context, core); - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -449,15 +508,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_6e92a7a47fdc567f_EOF' - {"create_pull_request":{"draft":false,"labels":["automation","changelog"],"max":1,"max_patch_files":100,"max_patch_size":1024,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"protected_files_policy":"request_review","title_prefix":"[changelog] "},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{},"update_release":{"max":1}} - GH_AW_SAFE_OUTPUTS_CONFIG_6e92a7a47fdc567f_EOF + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_269226b895ff9733_EOF' + {"create_pull_request":{"draft":false,"labels":["automation","changelog"],"max":1,"max_patch_files":100,"max_patch_size":4096,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"protected_files_policy":"request_review","title_prefix":"[changelog] "},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{},"update_release":{"max":1}} + GH_AW_SAFE_OUTPUTS_CONFIG_269226b895ff9733_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -592,7 +651,8 @@ jobs: "required": true, "type": "string", "sanitize": true, - "maxLength": 65000 + "maxLength": 65000, + "minLength": 20 }, "operation": { "required": true, @@ -618,62 +678,24 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_GUARD_MIN_INTEGRITY: ${{ steps.determine-automatic-lockdown.outputs.min_integrity }} GITHUB_MCP_GUARD_REPOS: ${{ steps.determine-automatic-lockdown.outputs.repos }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -682,29 +704,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_432de5cac6e63f96_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -716,16 +733,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -737,7 +773,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_432de5cac6e63f96_EOF + GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -766,41 +802,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 15 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -815,7 +861,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -823,17 +870,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -857,8 +897,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -892,6 +931,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -913,16 +953,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -983,7 +1014,8 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: write @@ -993,6 +1025,8 @@ jobs: group: "gh-aw-conclusion-release-changelog" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1001,7 +1035,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1010,8 +1044,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Release Changelog Generator" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/release-changelog.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1027,6 +1061,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-releasechangelog-${{ github.run_id }} + restore-keys: agentic-workflow-usage-releasechangelog- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-releasechangelog-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1038,6 +1164,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "release-changelog" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1105,25 +1235,32 @@ jobs: GH_AW_WORKFLOW_ID: "release-changelog" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_CODE_PUSH_FAILURE_ERRORS: ${{ needs.safe_outputs.outputs.code_push_failure_errors }} GH_AW_CODE_PUSH_FAILURE_COUNT: ${{ needs.safe_outputs.outputs.code_push_failure_count }} GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "15" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1136,19 +1273,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1157,8 +1297,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Release Changelog Generator" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/release-changelog.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1176,7 +1316,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1185,7 +1325,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1204,12 +1344,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1247,11 +1388,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1261,39 +1402,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1307,7 +1460,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1359,15 +1526,20 @@ jobs: contents: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/release-changelog" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_WORKFLOW_ID: "release-changelog" GH_AW_WORKFLOW_NAME: "Release Changelog Generator" GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/release-changelog.md" @@ -1383,7 +1555,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1392,8 +1564,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "Release Changelog Generator" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/release-changelog.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1415,50 +1587,23 @@ jobs: with: name: agent path: /tmp/gh-aw/ - - name: Extract base branch from agent output - id: extract-base-branch - if: steps.download-agent-output.outcome == 'success' - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require('${{ runner.temp }}/gh-aw/actions/extract_base_branch_from_agent_output.cjs'); - await main(); - - name: Checkout repository (trusted default branch for comment events) - if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment') - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - ref: ${{ github.event.repository.default_branch }} - token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - persist-credentials: false - fetch-depth: 1 - name: Checkout repository - if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: - ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }} + persist-credentials: true token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - persist-credentials: false - fetch-depth: 1 - name: Configure Git credentials if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GIT_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GIT_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1473,7 +1618,7 @@ jobs: GH_AW_ALLOWED_DOMAINS: "api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,github.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} - GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"create_pull_request\":{\"draft\":false,\"labels\":[\"automation\",\"changelog\"],\"max\":1,\"max_patch_files\":100,\"max_patch_size\":1024,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"protected_files_policy\":\"request_review\",\"title_prefix\":\"[changelog] \"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"true\"},\"report_incomplete\":{},\"update_release\":{\"max\":1}}" + GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"create_pull_request\":{\"draft\":false,\"labels\":[\"automation\",\"changelog\"],\"max\":1,\"max_patch_files\":100,\"max_patch_size\":4096,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"protected_files_policy\":\"request_review\",\"title_prefix\":\"[changelog] \"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"true\"},\"report_incomplete\":{},\"update_release\":{\"max\":1}}" GH_AW_CI_TRIGGER_TOKEN: ${{ secrets.GH_AW_CI_TRIGGER_TOKEN }} with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -1491,4 +1636,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/release-changelog.md b/.github/workflows/release-changelog.md index 52af777cd8..7a682c56dd 100644 --- a/.github/workflows/release-changelog.md +++ b/.github/workflows/release-changelog.md @@ -12,6 +12,7 @@ permissions: actions: read issues: read pull-requests: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/rust-sdk-tests.yml b/.github/workflows/rust-sdk-tests.yml index f75a5d6a29..8e13e16b23 100644 --- a/.github/workflows/rust-sdk-tests.yml +++ b/.github/workflows/rust-sdk-tests.yml @@ -29,7 +29,7 @@ permissions: jobs: test: - name: "Rust SDK Tests" + name: "Rust SDK Tests (${{ matrix.os }}, default)" if: github.event.repository.fork == false env: POWERSHELL_UPDATECHECK: Off @@ -84,7 +84,7 @@ jobs: # Share the bundled-CLI archive cache with the `bundle` job: build.rs # now downloads in both modes (embed for `bundle`, extract-to-cache # for this `test` job's `--no-default-features` build). - - name: Cache bundled CLI tarball + - name: Cache bundled CLI archives uses: actions/cache@v4 with: path: ./rust/.bundled-cli-cache @@ -98,7 +98,7 @@ jobs: if: runner.os == 'Linux' env: BUNDLED_CLI_CACHE_DIR: ${{ github.workspace }}/rust/.bundled-cli-cache - run: cargo clippy --all-targets --features test-support -- --no-deps -D warnings -D clippy::unwrap_used -D clippy::disallowed_macros -D clippy::await_holding_invalid_type + run: cargo clippy --all-targets --features test-support,bundled-in-process -- --no-deps -D warnings -D clippy::unwrap_used -D clippy::disallowed_macros -D clippy::await_holding_invalid_type - name: cargo doc if: runner.os == 'Linux' @@ -129,6 +129,84 @@ jobs: # The dedicated `bundle` job below exercises the embed pipeline. run: cargo test --no-default-features --features test-support -- --test-threads=4 --nocapture + # Exercises the in-process FFI transport (`Transport::InProcess`, the Rust + # analogue of the .NET `RuntimeConnection.ForInProcess()`), mirroring the + # `inprocess` transport cell in dotnet-sdk-tests.yml. Sets + # COPILOT_SDK_DEFAULT_CONNECTION=inprocess so the client hosts the runtime + # cdylib in-process instead of spawning a stdio child, then runs the whole + # E2E suite over the in-process transport. The suite runs serially in-process + # (the harness forces concurrency to 1) because it mirrors each test's + # environment onto the shared process environment the in-process worker inherits. + # Runs the whole E2E suite over the in-process transport on supported hosts. + test-inprocess: + name: "Rust SDK Tests (${{ matrix.os }}, inprocess)" + if: github.event.repository.fork == false + env: + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + strategy: + fail-fast: false + matrix: + # TODO: Re-enable Windows after fixing the napi-oop peer shutdown crash. + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + working-directory: ./rust + steps: + - uses: actions/checkout@v6.0.2 + + - uses: ./.github/actions/setup-copilot + id: setup-copilot + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@4be7066ada62dd38de10e7b70166bc74ed198c30 # stable + with: + toolchain: "1.94.0" + + - uses: Swatinem/rust-cache@42dc69e1aa15d09112580998cf2ef0119e2e91ae # v2 + with: + workspaces: "rust" + prefix-key: v1-rust-no-bin + cache-bin: false + + - name: Read pinned @github/copilot CLI version + id: cli-version + working-directory: ./nodejs + run: | + version=$(node -p "require('./package-lock.json').packages['node_modules/@github/copilot'].version") + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "Pinned CLI version: $version" + + - name: Cache bundled CLI archives + uses: actions/cache@v4 + with: + path: ./rust/.bundled-cli-cache + key: bundled-cli-${{ matrix.os }}-${{ steps.cli-version.outputs.version }} + + - name: Install test harness dependencies + working-directory: ./test/harness + run: npm ci --ignore-scripts + + - name: Warm up PowerShell + if: runner.os == 'Windows' + run: pwsh.exe -Command "Write-Host 'PowerShell ready'" + + - name: Select in-process transport + run: echo "COPILOT_SDK_DEFAULT_CONNECTION=inprocess" >> "$GITHUB_ENV" + + - name: cargo test (in-process transport, full E2E suite) + timeout-minutes: 60 + env: + COPILOT_HMAC_KEY: ${{ secrets.COPILOT_DEVELOPER_CLI_INTEGRATION_HMAC_KEY }} + COPILOT_CLI_PATH: ${{ steps.setup-copilot.outputs.cli-path }} + BUNDLED_CLI_CACHE_DIR: ${{ github.workspace }}/rust/.bundled-cli-cache + # The harness forces serial execution in-process (both the async semaphore and + # libtest via --test-threads=1) because it mirrors each test's environment onto + # the shared process environment, so RUST_E2E_CONCURRENCY is not set here. + run: cargo test --no-default-features --features test-support,bundled-in-process --test e2e -- --test-threads=1 --nocapture + # Validates the bundled-CLI build path on all three supported # platforms. While the regular `cargo test` job above also exercises # build.rs (bundling is on by default now), this matrix job is the @@ -136,7 +214,7 @@ jobs: # extract / embed pipeline. Catches regressions before they ship to # crates.io and before bundling consumers hit them downstream. bundle: - name: "Rust SDK Bundled CLI Build" + name: "Rust SDK Bundled CLI Build (${{ matrix.os }})" if: github.event.repository.fork == false env: CARGO_TERM_COLOR: always @@ -180,13 +258,15 @@ jobs: # ~130 MB on every CI invocation. Keyed by OS + CLI version so old # archives drop out when the pinned version bumps, keeping the # cache bounded. - - name: Cache bundled CLI tarball + - name: Cache bundled CLI archives uses: actions/cache@v4 with: path: ./rust/.bundled-cli-cache key: bundled-cli-${{ matrix.os }}-${{ steps.cli-version.outputs.version }} - - name: cargo build (bundled-cli is the default feature) + - name: Test bundled CLI build paths env: BUNDLED_CLI_CACHE_DIR: ${{ github.workspace }}/rust/.bundled-cli-cache - run: cargo build + run: | + cargo build + cargo test --features bundled-in-process --lib embedded_archive_contains_only_expected_files diff --git a/.github/workflows/sdk-canary.yml b/.github/workflows/sdk-canary.yml new file mode 100644 index 0000000000..95f8b1c926 --- /dev/null +++ b/.github/workflows/sdk-canary.yml @@ -0,0 +1,391 @@ +name: "SDK Canary Test/Publish" + +# Nightly-style canary pipeline. First installs an explicit version of the +# @github/copilot runtime, builds the Node SDK, and runs the Node e2e suite +# against it to prove runtime <-> SDK compatibility. When that gate passes (and +# mode allows), publishes an SDK canary pinned to the tested runtime to the +# internal Azure Artifacts feed only (never public npm). + +env: + HUSKY: 0 + # Internal org-scoped Azure Artifacts feed — single source of truth so the + # feed name isn't repeated across steps. The SDK canary publishes here and + # (when runtime_source=internal) installs the runtime from here; it must NEVER + # reach public npm (@github/copilot-sdk is a live public package). + FEED_URL: https://pkgs.dev.azure.com/devdiv/_packaging/copilot-canary/npm/registry/ + # Azure DevOps resource ID used to mint an ADO access token for the feed. + ADO_RESOURCE: 499b84ac-1321-427f-aa17-267ca6975798 + +on: + workflow_dispatch: + inputs: + runtime_version: + description: "Exact @github/copilot version to test (e.g. 1.0.69 or 1.0.70-canary.)" + required: true + type: string + runtime_source: + description: "Where to install the runtime from" + required: true + type: choice + options: + - public + - internal + default: public + mode: + description: "publish (tests must pass), publish-force (publish even if tests fail), or tests-only (run gate, never publish)" + required: false + type: choice + default: publish + options: + - publish + - publish-force + - tests-only + repository_dispatch: + types: [runtime-canary] + +permissions: + contents: read + id-token: write + +# Serialize runs per ref so two overlapping canary runs can't race the feed +# publish. cancel-in-progress: false — never kill an in-flight publish. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + resolve: + name: "Resolve runtime inputs" + if: github.event.repository.fork == false + runs-on: ubuntu-latest + permissions: {} + outputs: + RUNTIME_VERSION: ${{ steps.normalize.outputs.RUNTIME_VERSION }} + RUNTIME_SOURCE: ${{ steps.normalize.outputs.RUNTIME_SOURCE }} + PUBLISH_MODE: ${{ steps.normalize.outputs.PUBLISH_MODE }} + steps: + # Normalize whichever trigger fired into a single (RUNTIME_VERSION, + # RUNTIME_SOURCE, PUBLISH_MODE) triple that every downstream step + # references. workflow_dispatch reads the human-supplied inputs; + # repository_dispatch reads client_payload and forces source=internal + # (a runtime canary only exists on the feed), defaulting mode to publish. + - name: Normalize inputs + id: normalize + env: + EVENT_NAME: ${{ github.event_name }} + INPUT_VERSION: ${{ inputs.runtime_version }} + INPUT_SOURCE: ${{ inputs.runtime_source }} + INPUT_MODE: ${{ inputs.mode }} + PAYLOAD_VERSION: ${{ github.event.client_payload.runtime_version }} + PAYLOAD_SOURCE: ${{ github.event.client_payload.runtime_source }} + PAYLOAD_MODE: ${{ github.event.client_payload.mode }} + run: | + set -euo pipefail + case "$EVENT_NAME" in + workflow_dispatch) + VERSION="$INPUT_VERSION" + SOURCE="$INPUT_SOURCE" + MODE="$INPUT_MODE" + ;; + repository_dispatch) + VERSION="$PAYLOAD_VERSION" + # A runtime canary only ever exists on the internal feed. + SOURCE="${PAYLOAD_SOURCE:-internal}" + MODE="${PAYLOAD_MODE:-publish}" + ;; + *) + echo "::error::Unsupported event '$EVENT_NAME'." + exit 1 + ;; + esac + if [ -z "$VERSION" ]; then echo "::error::Could not determine runtime version."; exit 1; fi + if [ -z "$SOURCE" ]; then SOURCE="public"; fi + case "$SOURCE" in + public|internal) ;; + *) echo "::error::Invalid runtime source '$SOURCE'. Expected one of: public, internal."; exit 1 ;; + esac + if [ -z "$MODE" ]; then MODE="publish"; fi + case "$MODE" in + publish|publish-force|tests-only) ;; + *) echo "::error::Invalid publish mode '$MODE'. Expected one of: publish, publish-force, tests-only."; exit 1 ;; + esac + echo "Resolved RUNTIME_VERSION=$VERSION RUNTIME_SOURCE=$SOURCE PUBLISH_MODE=$MODE" + echo "RUNTIME_VERSION=$VERSION" >> "$GITHUB_OUTPUT" + echo "RUNTIME_SOURCE=$SOURCE" >> "$GITHUB_OUTPUT" + echo "PUBLISH_MODE=$MODE" >> "$GITHUB_OUTPUT" + + - name: Validate runtime version (semver) + env: + RUNTIME_VERSION: ${{ steps.normalize.outputs.RUNTIME_VERSION }} + run: | + if [[ ! "$RUNTIME_VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then + echo "::error::Invalid runtime version '$RUNTIME_VERSION'. Expected semver (e.g. 1.0.69 or 1.0.70-canary.abc123)." + exit 1 + fi + + test: + name: "E2E tests (${{ matrix.os }})" + needs: resolve + if: github.event.repository.fork == false + environment: cicd + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + env: + POWERSHELL_UPDATECHECK: Off + RUNTIME_VERSION: ${{ needs.resolve.outputs.RUNTIME_VERSION }} + RUNTIME_SOURCE: ${{ needs.resolve.outputs.RUNTIME_SOURCE }} + defaults: + run: + shell: bash + working-directory: ./nodejs + steps: + - uses: actions/checkout@v6.0.2 + + - uses: actions/setup-node@v6 + with: + cache: "npm" + cache-dependency-path: "./nodejs/package-lock.json" + node-version: 22 + + - name: Install SDK dependencies + run: npm ci --ignore-scripts + + - name: Install test harness dependencies + working-directory: ./test/harness + run: npm ci --ignore-scripts + + - name: Azure Login (OIDC -> id-cpd-ci) + if: env.RUNTIME_SOURCE == 'internal' + uses: azure/login@532459ea530d8321f2fb9bb10d1e0bcf23869a43 # v3.0.0 + with: + client-id: "${{ vars.CPD_ID_CLIENT_ID }}" # id-cpd-ci + tenant-id: "${{ vars.CPD_ID_TENANT_ID }}" + allow-no-subscriptions: true + + # Route ONLY @github/* (the runtime + its 8 platform packages) to the + # internal feed via a scoped registry. All other deps (e.g. detect-libc) + # still resolve from public npm. A global --registry would break because + # detect-libc is not on the feed. + - name: Configure canary feed (.npmrc) + if: env.RUNTIME_SOURCE == 'internal' + run: | + set -euo pipefail + TOKEN="$(az account get-access-token --resource "$ADO_RESOURCE" --query accessToken -o tsv)" + echo "::add-mask::$TOKEN" + # Derive the protocol-relative auth scopes from FEED_URL so the feed + # name lives in exactly one place (the workflow-level env). + FEED_AUTH_REGISTRY="${FEED_URL#https:}" + FEED_AUTH_BASE="${FEED_AUTH_REGISTRY%registry/}" + NPMRC="$(printf '%s\n' \ + "@github:registry=${FEED_URL}" \ + "${FEED_AUTH_REGISTRY}:_authToken=${TOKEN}" \ + "${FEED_AUTH_BASE}:_authToken=${TOKEN}")" + printf '%s\n' "$NPMRC" > .npmrc + echo "Wrote scoped @github registry .npmrc to ./nodejs" + + - name: Override runtime version + run: | + set -euo pipefail + echo "Installing @github/copilot@${RUNTIME_VERSION} (source: ${RUNTIME_SOURCE})" + npm install "@github/copilot@${RUNTIME_VERSION}" --save-exact --ignore-scripts + + - name: Verify installed runtime + run: | + set -euo pipefail + node -e ' + const fs = require("fs"); + const expected = process.env.RUNTIME_VERSION; + const pkg = require("./node_modules/@github/copilot/package.json"); + if (pkg.version !== expected) { + console.error(`::error::Installed @github/copilot version ${pkg.version} does not match requested ${expected}`); + process.exit(1); + } + const dir = "./node_modules/@github"; + const entries = fs.readdirSync(dir).filter((d) => d.startsWith("copilot-")); + const plat = process.platform === "win32" ? "win32" : process.platform === "darwin" ? "darwin" : "linux"; + const arch = process.arch; + const match = entries.find((d) => d.includes(plat) && d.includes(arch)); + if (!match) { + console.error(`::error::No @github/copilot platform optional dep for ${plat}-${arch}. Present: ${entries.join(", ") || "(none)"}`); + process.exit(1); + } + const platPkg = require(`${dir}/${match}/package.json`); + if (platPkg.version !== expected) { + console.error(`::error::Platform package @github/${match} version ${platPkg.version} does not match requested ${expected}`); + process.exit(1); + } + console.log(`Verified @github/copilot@${pkg.version} with platform package @github/${match}@${platPkg.version}`); + ' + + - name: Build SDK + run: npm run build + + - name: Warm up PowerShell + if: runner.os == 'Windows' + run: pwsh.exe -Command "Write-Host 'PowerShell ready'" + + - name: Run Node.js SDK e2e tests + env: + COPILOT_HMAC_KEY: ${{ secrets.COPILOT_DEVELOPER_CLI_INTEGRATION_HMAC_KEY }} + run: npm test + + publish: + name: "Publish SDK canary (internal feed)" + needs: [resolve, test] + # Publish runs only when the gate permits it. Mode governs behavior: + # - tests-only: never publish (skips this job entirely). + # - publish: publish only when the e2e gate is green (the default for both + # the human and automated triggers). + # - publish-force: publish even on a non-green gate — a human-acknowledged + # flake override, audited via the ::warning:: step below and the run actor. + # publish-force only skips the e2e *signal* — the publish job still runs the + # build (so a broken build can't publish) and enforces the feed-only guards. + if: > + !cancelled() && + github.event.repository.fork == false && + needs.resolve.result == 'success' && + needs.resolve.outputs.PUBLISH_MODE != 'tests-only' && + (needs.test.result == 'success' || + needs.resolve.outputs.PUBLISH_MODE == 'publish-force') + environment: cicd + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + RUNTIME_VERSION: ${{ needs.resolve.outputs.RUNTIME_VERSION }} + defaults: + run: + shell: bash + working-directory: ./nodejs + steps: + - name: Warn — publishing despite failed e2e gate (publish-force) + # always() so this audit is never skipped by prior-step status; it fires + # specifically when publish proceeded on a non-green gate via publish-force. + # Runs at the workspace root because it executes before checkout, so the + # job's default working-directory (./nodejs) does not exist yet. + if: always() && needs.test.result != 'success' && needs.resolve.outputs.PUBLISH_MODE == 'publish-force' + working-directory: ${{ github.workspace }} + run: | + echo "::warning title=e2e gate bypassed::Publishing SDK canary despite a non-passing e2e gate (test job result: ${{ needs.test.result }}) via publish-force. Triggered by '${{ github.actor }}' through '${{ github.event_name }}'. The e2e signal was bypassed; build + feed-only guards still apply." + + - uses: actions/checkout@v6.0.2 + + - uses: actions/setup-node@v6 + with: + node-version: 22 + + # Default public registry: installs build deps and the currently pinned + # runtime. Do NOT write any feed .npmrc or scoped @github:registry line + # here, or npm ci would try to fetch the runtime from the upstream-less + # feed and 404. + - name: Install SDK dependencies + run: npm ci --ignore-scripts + + - name: Compute SDK canary version + id: sdkver + env: + RUN_NUMBER: ${{ github.run_number }} + SHA: ${{ github.sha }} + run: | + set -euo pipefail + SHORT_SHA="${SHA:0:7}" + # Base the canary on the NEXT patch of the public SDK latest so canaries + # correlate with public releases: they sort ABOVE the current public + # latest and BELOW the eventual real release of that next patch (a + # prerelease of X.Y.Z always sorts below X.Y.Z), so a canary can never + # shadow the real release when it ships. + # Reuse the repo's own version helper (scripts/get-version.js) so this + # stays consistent with publish.yml: `current` returns the latest public + # dist-tag version, read-only from public npm (never the feed), then + # we bump the patch ourselves to keep strict patch+1 semantics. + PUBLIC_LATEST="$(node scripts/get-version.js current || true)" + BASE="${PUBLIC_LATEST%%-*}"; BASE="${BASE%%+*}" + if [[ "$BASE" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then + NEXT="${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.$(( BASH_REMATCH[3] + 1 ))" + else + echo "::error::Could not resolve public SDK latest version (got '$PUBLIC_LATEST'); refusing to publish a canary with an unknown base." + exit 1 + fi + SDK_VERSION="${NEXT}-canary.${RUN_NUMBER}.g${SHORT_SHA}" + if [[ ! "$SDK_VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then + echo "::error::Computed SDK canary version '$SDK_VERSION' is not valid semver." + exit 1 + fi + echo "SDK canary version: $SDK_VERSION" + echo "SDK_VERSION=$SDK_VERSION" >> "$GITHUB_OUTPUT" + + - name: Set package version and pin runtime dependency + env: + SDK_VERSION: ${{ steps.sdkver.outputs.SDK_VERSION }} + run: | + set -euo pipefail + npm version "$SDK_VERSION" --no-git-tag-version --allow-same-version + # Exact pin (no caret) so the published SDK canary depends on precisely + # the runtime version that was just tested by the e2e gate. + npm pkg set "dependencies.@github/copilot=$RUNTIME_VERSION" + echo "Pinned @github/copilot to $(npm pkg get dependencies.@github/copilot)" + + - name: Build SDK + run: npm run build + + - name: Azure Login (OIDC -> id-cpd-ci) + uses: azure/login@532459ea530d8321f2fb9bb10d1e0bcf23869a43 # v3.0.0 + with: + client-id: "${{ vars.CPD_ID_CLIENT_ID }}" # id-cpd-ci + tenant-id: "${{ vars.CPD_ID_TENANT_ID }}" + allow-no-subscriptions: true + + # Auth-only .npmrc: just the two token lines, NO scoped registry line. + # The publish target is supplied explicitly via publishConfig + --registry. + - name: Configure feed auth (.npmrc) + run: | + set -euo pipefail + TOKEN="$(az account get-access-token --resource "$ADO_RESOURCE" --query accessToken -o tsv)" + echo "::add-mask::$TOKEN" + # Derive the protocol-relative auth scopes from FEED_URL (single source + # of truth). NO scoped @github:registry line here — publish target is + # supplied explicitly via publishConfig + --registry. + FEED_AUTH_REGISTRY="${FEED_URL#https:}" + FEED_AUTH_BASE="${FEED_AUTH_REGISTRY%registry/}" + printf '%s\n' \ + "${FEED_AUTH_REGISTRY}:_authToken=${TOKEN}" \ + "${FEED_AUTH_BASE}:_authToken=${TOKEN}" > .npmrc + echo "Wrote auth-only .npmrc to ./nodejs" + + # Belt and suspenders (2 of 3): pin the publish target in the package too. + - name: Set publishConfig registry + run: npm pkg set "publishConfig.registry=$FEED_URL" + + # Belt and suspenders (3 of 3): fail loudly unless the effective publish + # target is the internal feed. Guards against ever reaching public npm. + - name: Assert publish target is the internal feed + run: | + set -euo pipefail + EFFECTIVE="$(npm pkg get publishConfig.registry | tr -d '"')" + echo "Effective publishConfig.registry: $EFFECTIVE" + if [ "$EFFECTIVE" != "$FEED_URL" ]; then + echo "::error::publishConfig.registry ('$EFFECTIVE') is not the internal feed ('$FEED_URL'). Refusing to publish." + exit 1 + fi + + - name: Publish SDK canary to internal feed + run: npm publish --registry "$FEED_URL" + + - name: Summarize published canary + env: + SDK_VERSION: ${{ steps.sdkver.outputs.SDK_VERSION }} + run: | + set -euo pipefail + { + echo "## SDK canary published" + echo "" + echo "| | |" + echo "| --- | --- |" + echo "| Runtime consumed | \`@github/copilot@${RUNTIME_VERSION}\` |" + echo "| Canary SDK produced | \`@github/copilot-sdk@${SDK_VERSION}\` |" + echo "| Feed | ${FEED_URL} |" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/sdk-consistency-review.lock.yml b/.github/workflows/sdk-consistency-review.lock.yml index 3cffd9d387..f3dabb7ebb 100644 --- a/.github/workflows/sdk-consistency-review.lock.yml +++ b/.github/workflows/sdk-consistency-review.lock.yml @@ -1,20 +1,21 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"7705f1f36359046432427c7379dff5ce45f49f1d69e23433af41c1234042e51b","body_hash":"97333b6724b46fcc7c9d59c1eec7c424d3a2005fab0e52e2520c97a02021426b","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"fb73d13f101fc375308576a64180f63934cc9e8306cb6ef6303f1b9788d9df28","body_hash":"97333b6724b46fcc7c9d59c1eec7c424d3a2005fab0e52e2520c97a02021426b","compiler_version":"v0.82.10","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.70"}} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0","version":"v7"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"05205436a78512d71a2d842e46586ed05f4fa058","version":"v0.82.10"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35","digest":"sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35","digest":"sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35","digest":"sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.1","digest":"sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b","pinned_image":"ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b"},{"image":"ghcr.io/github/github-mcp-server:v1.5.0","digest":"sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4","pinned_image":"ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4"}],"has_pull_request":true} +# This file was automatically generated by gh-aw (v0.82.10). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md +# +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ # | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ +# | | | | (_| | __/ | | | |_| | (__ # \_| |_/\__, |\___|_| |_|\__|_|\___| # __/ | -# _ _ |___/ +# _ _ |___/ # | | | | / _| | # | | | | ___ _ __ _ __| |_| | _____ ____ # | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -31,38 +32,41 @@ # - GITHUB_TOKEN # # Custom actions used: -# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 +# - actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 # - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# - github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 -# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 -# - ghcr.io/github/gh-aw-mcpg:v0.3.22 -# - ghcr.io/github/github-mcp-server:v1.1.0 -# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 +# - ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 +# - ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 +# - ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 +# - ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b +# - ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 name: "SDK Consistency Review Agent" on: pull_request: paths: - - nodejs/** - - python/** - - go/** - - dotnet/** - - java/** - - "!java/docs/**" - - "!java/*.txt" - - "!java/*.md" + - nodejs/** + - python/** + - go/** + - dotnet/** + - java/** + - "!java/docs/**" + - "!java/*.txt" + - "!java/*.md" types: - - opened - - synchronize - - reopened + - opened + - synchronize + - reopened # roles: all # Roles processed as role check in pre-activation job workflow_dispatch: inputs: @@ -91,14 +95,20 @@ jobs: permissions: actions: read contents: read + env: + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: body: ${{ steps.sanitized.outputs.body }} comment_id: "" comment_repo: "" + daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} + daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} + daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} - secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} @@ -108,15 +118,16 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info @@ -124,16 +135,16 @@ jobs: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AGENT_VERSION: "1.0.55" - GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AGENT_VERSION: "1.0.70" + GH_AW_INFO_CLI_VERSION: "v0.82.10" GH_AW_INFO_WORKFLOW_NAME: "SDK Consistency Review Agent" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" @@ -144,13 +155,59 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); await main(core, context); - - name: Validate COPILOT_GITHUB_TOKEN secret - id: validate-secret - run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-sdkconsistencyreview-${{ github.run_id }} + restore-keys: agentic-workflow-usage-sdkconsistencyreview- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Restore daily AIC usage cache (artifact fallback) + id: restore-daily-aic-cache-fallback + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} + GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/restore_aic_usage_cache_fallback.cjs'); + await main(); + - name: Check daily workflow token guardrail + id: daily-effective-workflow-guardrail + if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" + GH_AW_WORKFLOW_ID: "sdk-consistency-review" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} + GH_AW_HAS_SLASH_COMMAND: "false" + GH_AW_HAS_LABEL_COMMAND: "false" + GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_daily_aic_workflow_guardrail.cjs'); + await main(); + - name: Check for OAuth tokens + id: check-oauth-tokens + run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" env: COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - name: Checkout .github and .agents folders - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false sparse-checkout: | @@ -159,7 +216,6 @@ jobs: .antigravity .claude .codex - .crush .gemini .opencode .pi @@ -167,8 +223,8 @@ jobs: fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file @@ -186,7 +242,7 @@ jobs: - name: Check compile-agentic version uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.77.5" + GH_AW_COMPILED_VERSION: "v0.82.10" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -204,6 +260,9 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/compute_text.cjs'); await main(); + - name: Log runtime features + if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - name: Create prompt with built-in context env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt @@ -222,20 +281,20 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_cf79d4d226819b37_EOF' + cat << 'GH_AW_PROMPT_96d45caa4ffc7593_EOF' - GH_AW_PROMPT_cf79d4d226819b37_EOF + GH_AW_PROMPT_96d45caa4ffc7593_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_cf79d4d226819b37_EOF' + cat << 'GH_AW_PROMPT_96d45caa4ffc7593_EOF' Tools: add_comment, create_pull_request_review_comment(max:10), missing_tool, missing_data, noop - GH_AW_PROMPT_cf79d4d226819b37_EOF + GH_AW_PROMPT_96d45caa4ffc7593_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" - cat << 'GH_AW_PROMPT_cf79d4d226819b37_EOF' + cat << 'GH_AW_PROMPT_96d45caa4ffc7593_EOF' The following GitHub context information is available for this workflow: {{#if github.actor}} @@ -263,13 +322,13 @@ jobs: - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - - GH_AW_PROMPT_cf79d4d226819b37_EOF + + GH_AW_PROMPT_96d45caa4ffc7593_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" - cat << 'GH_AW_PROMPT_cf79d4d226819b37_EOF' + cat << 'GH_AW_PROMPT_96d45caa4ffc7593_EOF' {{#runtime-import .github/workflows/sdk-consistency-review.md}} - GH_AW_PROMPT_cf79d4d226819b37_EOF + GH_AW_PROMPT_96d45caa4ffc7593_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -304,9 +363,9 @@ jobs: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); - + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); - + // Call the substitution function return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, @@ -342,7 +401,7 @@ jobs: include-hidden-files: true path: | /tmp/gh-aw/aw_info.json - /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/models.json /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/aw-prompts/prompt-template.txt /tmp/gh-aw/aw-prompts/prompt-import-tree.json @@ -355,9 +414,11 @@ jobs: agent: needs: activation + if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write issues: read pull-requests: read env: @@ -366,13 +427,17 @@ jobs: GH_AW_ASSETS_BRANCH: "" GH_AW_ASSETS_MAX_SIZE_KB: 0 GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} GH_AW_WORKFLOW_ID_SANITIZED: sdkconsistencyreview outputs: agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} + aic: ${{ steps.parse-mcp-gateway.outputs.aic }} + ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} + http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} @@ -382,10 +447,11 @@ jobs: setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} + unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -394,8 +460,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths @@ -406,7 +472,7 @@ jobs: echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" } >> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: persist-credentials: false - name: Create gh-aw temp directory @@ -415,23 +481,21 @@ jobs: run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" env: GH_TOKEN: ${{ github.token }} + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Checkout PR branch id: checkout-pr if: | - github.event.pull_request || github.event.issue.pull_request + github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} @@ -443,14 +507,14 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 --rootless - name: Determine automatic lockdown mode for GitHub MCP Server id: determine-automatic-lockdown - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 (source v9) + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 env: GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} @@ -458,16 +522,11 @@ jobs: script: | const determineAutomaticLockdown = require('${{ runner.temp }}/gh-aw/actions/determine_automatic_lockdown.cjs'); await determineAutomaticLockdown(github, context, core); - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: "AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - name: Restore inline sub-agents from activation artifact env: @@ -479,15 +538,15 @@ jobs: GH_AW_SKILL_DIR: ".github/skills" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 ghcr.io/github/gh-aw-mcpg:v0.4.1@sha256:ad2a979c2cd8b50098e84938ca9c9c1580eb8e91526f101a90adfba7859b2c32 ghcr.io/github/gh-aw-node@sha256:529d02eb970b1161aa25c593a9c3df57fdfad5a8add328cb3b6eccef66f3183b ghcr.io/github/github-mcp-server:v1.5.0@sha256:e25564dccc9110a70a77b9df560cbde11aa392fcb5f08b9abe5c4ebc6d146ea4 - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_ee26456e9d33cb21_EOF' + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_05b64a640c1d5c26_EOF' {"add_comment":{"hide_older_comments":true,"max":1},"create_pull_request_review_comment":{"max":10,"side":"RIGHT"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{}} - GH_AW_SAFE_OUTPUTS_CONFIG_ee26456e9d33cb21_EOF + GH_AW_SAFE_OUTPUTS_CONFIG_05b64a640c1d5c26_EOF - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | @@ -641,62 +700,24 @@ jobs: setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); await main(); - - name: Generate Safe Outputs MCP Server Config - id: safe-outputs-config - run: | - # Generate a secure random API key (360 bits of entropy, 40+ chars) - # Mask immediately to prevent timing vulnerabilities - API_KEY=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${API_KEY}" - - PORT=3001 - - # Set outputs for next steps - { - echo "safe_outputs_api_key=${API_KEY}" - echo "safe_outputs_port=${PORT}" - } >> "$GITHUB_OUTPUT" - - echo "Safe Outputs MCP server will run on port ${PORT}" - - - name: Start Safe Outputs MCP HTTP Server - id: safe-outputs-start - env: - DEBUG: '*' - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - run: | - # Environment variables are set above to prevent template injection - export DEBUG - export GH_AW_SAFE_OUTPUTS - export GH_AW_SAFE_OUTPUTS_PORT - export GH_AW_SAFE_OUTPUTS_API_KEY - export GH_AW_SAFE_OUTPUTS_TOOLS_PATH - export GH_AW_SAFE_OUTPUTS_CONFIG_PATH - export GH_AW_MCP_LOG_DIR - - bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" - - name: Start MCP Gateway id: start-mcp-gateway env: + GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} - GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} GITHUB_MCP_GUARD_MIN_INTEGRITY: ${{ steps.determine-automatic-lockdown.outputs.min_integrity }} GITHUB_MCP_GUARD_REPOS: ${{ steps.determine-automatic-lockdown.outputs.repos }} GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -eo pipefail mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - + # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_DOMAIN="awmg-mcpg" export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" @@ -705,29 +726,24 @@ jobs: mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" export DEBUG="*" - + export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - case "${DOCKER_HOST:-}" in - unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; - /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; - * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; - esac - DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' - - mkdir -p /home/runner/.copilot + source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.1' + + mkdir -p "$HOME/.copilot" GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_f1f5e8d8750acfbe_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "container": "ghcr.io/github/github-mcp-server:v1.5.0", "env": { - "GITHUB_HOST": "\${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_HOST": "${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", "GITHUB_READ_ONLY": "1", "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" }, @@ -739,16 +755,35 @@ jobs: } }, "safeoutputs": { - "type": "http", - "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", - "headers": { - "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + "type": "stdio", + "container": "ghcr.io/github/gh-aw-node", + "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], + "args": ["-w", "\${GITHUB_WORKSPACE}"], + "entrypoint": "sh", + "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], + "env": { + "DEBUG": "*", + "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", + "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", + "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", + "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", + "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", + "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", + "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", + "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", + "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", + "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", + "GITHUB_SHA": "\${GITHUB_SHA}", + "GITHUB_TOKEN": "\${GITHUB_TOKEN}", + "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", + "RUNNER_TEMP": "\${RUNNER_TEMP}" }, "guard-policies": { "write-sink": { "accept": [ "*" - ] + ], + "sink-visibility": ${{ toJSON(steps.determine-automatic-lockdown.outputs.visibility) }} } } } @@ -760,7 +795,7 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_f1f5e8d8750acfbe_EOF + GH_AW_MCP_CONFIG_d97c92af15acf38e_EOF - name: Mount MCP servers as CLIs id: mount-mcp-clis continue-on-error: true @@ -789,41 +824,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" + export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","github.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"github.com\",\"host.docker.internal\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"raw.githubusercontent.com\",\"registry.npmjs.org\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"telemetry.enterprise.githubcopilot.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} - GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 15 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -838,7 +883,8 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - name: Detect agent errors if: always() id: detect-agent-errors @@ -846,17 +892,10 @@ jobs: run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: - REPO_NAME: ${{ github.repository }} - SERVER_URL: ${{ github.server_url }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_TOKEN: ${{ github.token }} - run: | - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git config --global am.keepcr true - # Re-authenticate git with GitHub token - SERVER_URL_STRIPPED="${SERVER_URL#https://}" - git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" - echo "Git configured with standard GitHub Actions identity" + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - name: Copy Copilot session state files to logs if: always() continue-on-error: true @@ -880,8 +919,7 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); await main(); env: - GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -915,6 +953,7 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -936,16 +975,7 @@ jobs: continue-on-error: true env: AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: | - # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts - # AWF runs with sudo, creating files owned by root - sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true - # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) - if command -v awf &> /dev/null; then - awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" - else - echo 'AWF binary not installed, skipping firewall log summary' - fi + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - name: Parse token usage for step summary if: always() continue-on-error: true @@ -1006,17 +1036,19 @@ jobs: - safe_outputs if: > always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.stale_lock_file_failed == 'true') + needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || + needs.activation.outputs.secret_verification_result == 'failed' || needs.activation.outputs.daily_ai_credits_exceeded == 'true') runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write concurrency: group: "gh-aw-conclusion-sdk-consistency-review" cancel-in-progress: false queue: max + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -1025,7 +1057,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1034,8 +1066,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1051,6 +1083,98 @@ jobs: mkdir -p /tmp/gh-aw/ find "/tmp/gh-aw/" -type f -print echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download safe outputs items manifest + id: download-safe-outputs-manifest + if: always() + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: safe-outputs-items + path: /tmp/gh-aw/ + - name: Collect usage artifact files + if: always() + continue-on-error: true + run: | + mkdir -p /tmp/gh-aw/usage/agent /tmp/gh-aw/usage/detection + echo "Usage artifact source file status:" + for file in /tmp/gh-aw/aw_info.json /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl; do + [ -f "$file" ] && echo "FOUND: $file" || echo "MISSING: $file" + done + [ -f /tmp/gh-aw/aw_info.json ] && cp /tmp/gh-aw/aw_info.json /tmp/gh-aw/usage/aw_info.json || true + [ -f /tmp/gh-aw/aw-info.jsonl ] && cp /tmp/gh-aw/aw-info.jsonl /tmp/gh-aw/usage/aw-info.jsonl || true + [ -f /tmp/gh-aw/agent_usage.json ] && cp /tmp/gh-aw/agent_usage.json /tmp/gh-aw/usage/agent_usage.json || true + [ -f /tmp/gh-aw/agent_usage.jsonl ] && cp /tmp/gh-aw/agent_usage.jsonl /tmp/gh-aw/usage/agent_usage.jsonl || true + [ -f /tmp/gh-aw/detection_usage.jsonl ] && cp /tmp/gh-aw/detection_usage.jsonl /tmp/gh-aw/usage/detection_usage.jsonl || true + [ -f /tmp/gh-aw/evals/evals.jsonl ] && cp /tmp/gh-aw/evals/evals.jsonl /tmp/gh-aw/usage/evals.jsonl || true + [ -f /tmp/gh-aw/github_rate_limits.jsonl ] && cp /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/usage/github_rate_limits.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/agent/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall-audit-logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/audit/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -s /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl ] && cp /tmp/gh-aw/threat-detection/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl /tmp/gh-aw/usage/detection/token_usage.jsonl || true + [ -f /tmp/gh-aw/usage/agent/token_usage.jsonl ] || : > /tmp/gh-aw/usage/agent/token_usage.jsonl + [ -f /tmp/gh-aw/usage/detection/token_usage.jsonl ] || : > /tmp/gh-aw/usage/detection/token_usage.jsonl + mkdir -p /tmp/gh-aw/usage/activity + node "${RUNNER_TEMP}/gh-aw/actions/generate_usage_activity_summary.cjs" + find /tmp/gh-aw/usage -type f -print | sort + - name: Upload usage artifact + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: usage + path: | + /tmp/gh-aw/usage/aw_info.json + /tmp/gh-aw/usage/aw-info.jsonl + /tmp/gh-aw/usage/agent_usage.json + /tmp/gh-aw/usage/agent_usage.jsonl + /tmp/gh-aw/usage/detection_usage.jsonl + /tmp/gh-aw/usage/evals.jsonl + /tmp/gh-aw/usage/github_rate_limits.jsonl + /tmp/gh-aw/usage/agent/token_usage.jsonl + /tmp/gh-aw/usage/detection/token_usage.jsonl + /tmp/gh-aw/usage/activity/summary.json + if-no-files-found: ignore + - name: Restore daily AIC usage cache + id: restore-daily-aic-cache-conclusion + if: always() + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-sdkconsistencyreview-${{ github.run_id }} + restore-keys: agentic-workflow-usage-sdkconsistencyreview- + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Write daily AIC usage cache entry + id: write-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 + with: + github-token: ${{ github.token }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context); + const { main } = require('${{ runner.temp }}/gh-aw/actions/write_daily_aic_usage_cache.cjs'); + await main(); + - name: Save daily AIC usage cache + id: save-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + key: agentic-workflow-usage-sdkconsistencyreview-${{ github.run_id }} + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + - name: Upload daily AIC usage cache artifact + id: upload-daily-aic-cache + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: aic-usage-cache + path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl + if-no-files-found: ignore + retention-days: 7 - name: Process no-op messages id: noop uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -1063,6 +1187,10 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} + GH_AW_WORKFLOW_ID: "sdk-consistency-review" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1134,23 +1262,30 @@ jobs: GH_AW_WORKFLOW_ID: "sdk-consistency-review" GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" GH_AW_ENGINE_ID: "copilot" - GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} + GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} + GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} + GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "15" - GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1163,19 +1298,22 @@ jobs: needs: - activation - agent - if: > - always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + if: always() && needs.agent.result != 'skipped' runs-on: ubuntu-latest permissions: contents: read + copilot-requests: write + env: + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} outputs: + aic: ${{ steps.parse_detection_token_usage.outputs.aic }} detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} detection_reason: ${{ steps.detection_conclusion.outputs.reason }} detection_success: ${{ steps.detection_conclusion.outputs.success }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1184,8 +1322,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1203,7 +1341,7 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Checkout repository for patch context if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # --- Threat Detection --- @@ -1212,7 +1350,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.27.35@sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed ghcr.io/github/gh-aw-firewall/api-proxy:0.27.35@sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04 ghcr.io/github/gh-aw-firewall/squid:0.27.35@sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3 - name: Check if detection needed id: detection_guard if: always() @@ -1231,12 +1369,13 @@ jobs: if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f /home/runner/.copilot/mcp-config.json + rm -f "$HOME/.copilot/mcp-config.json" rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - name: Prepare threat detection files if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + rm -f /tmp/gh-aw/agent_usage.json cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." @@ -1274,11 +1413,11 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.70 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.27.35 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' continue-on-error: true @@ -1288,39 +1427,51 @@ jobs: run: | set -o pipefail printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + trap 'rm -f "$HOME/.copilot/settings.json"' EXIT + mkdir -p "$HOME/.copilot" + printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" + export XDG_CONFIG_HOME="$HOME" touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" - GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" + printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.27.35/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.business.githubcopilot.com\",\"api.enterprise.githubcopilot.com\",\"api.github.com\",\"api.githubcopilot.com\",\"api.individual.githubcopilot.com\",\"github.com\",\"host.docker.internal\",\"registry.npmjs.org\",\"telemetry.enterprise.githubcopilot.com\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"fable\",\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.27.35,squid=sha256:f69282ec7b1326ba53891c399cf5b10475c0d3ccf4e1519b33d234a5427b57d3,agent=sha256:2202f63e8650b2b8b0d38033b44a05387b2b71ad3e690c4d23a34786f5462aed,agent-act=sha256:b00340a7b09c917c522cb806af6da1d12f2146e25a4a6198f1589b0116aee992,api-proxy=sha256:755b79d0dfda82bd6b43a208d68666721e504110c5d342a4eeb199802644ff04,cli-proxy=sha256:fe83cd274636efa9de3f456e2b078fae137328b9bb6ee4986ae510acaef0cec5\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" + GH_AW_DOCKER_HOST="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST="${DOCKER_HOST}" + fi if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" + printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" fi GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" if [ -d "$GH_AW_TOOL_CACHE" ]; then if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" fi - elif [ -d "/home/runner/work/_tool" ]; then - GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" fi - # shellcheck disable=SC1003 - sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ - -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + # shellcheck disable=SC1003,SC2016,SC2086 + awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --skip-pull \ + -- /bin/bash -c 'set +o histexpand; : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_GITHUB_TOKEN: ${{ github.token }} COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-4.6' }} + GH_AW_LLM_PROVIDER: github + GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} + GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.77.5 + GH_AW_TIMEOUT_MINUTES: 20 + GH_AW_VERSION: v0.82.10 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1334,7 +1485,21 @@ jobs: GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] RUNNER_TEMP: ${{ runner.temp }} - XDG_CONFIG_HOME: /home/runner + S2STOKENS: true + TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} + - name: Parse threat detection token usage for step summary + id: parse_detection_token_usage + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -1384,18 +1549,22 @@ jobs: runs-on: ubuntu-slim permissions: contents: read - discussions: write issues: write pull-requests: write - timeout-minutes: 15 + timeout-minutes: 45 env: + GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AIC: ${{ needs.agent.outputs.aic }} + GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/sdk-consistency-review" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: ${{ needs.agent.outputs.model }} - GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_ENGINE_VERSION: "1.0.70" + GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} + GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} GH_AW_TRACKER_ID: "sdk-consistency-review" GH_AW_WORKFLOW_ID: "sdk-consistency-review" GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" @@ -1412,7 +1581,7 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + uses: github/gh-aw-actions/setup@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} @@ -1421,8 +1590,8 @@ jobs: env: GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.55" - GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_VERSION: "1.0.70" + GH_AW_INFO_AWF_VERSION: "v0.27.35" GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output @@ -1441,7 +1610,7 @@ jobs: - name: Configure GH_HOST for enterprise compatibility id: ghes-host-config shell: bash - run: | + run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. GH_HOST="${GITHUB_SERVER_URL#https://}" @@ -1473,4 +1642,3 @@ jobs: /tmp/gh-aw/safe-output-items.jsonl /tmp/gh-aw/temporary-id-map.json if-no-files-found: ignore - diff --git a/.github/workflows/sdk-consistency-review.md b/.github/workflows/sdk-consistency-review.md index 4111015ba5..28c0015228 100644 --- a/.github/workflows/sdk-consistency-review.md +++ b/.github/workflows/sdk-consistency-review.md @@ -24,6 +24,7 @@ permissions: contents: read pull-requests: read issues: read + copilot-requests: write tools: github: toolsets: [default] diff --git a/.github/workflows/verify-compiled.yml b/.github/workflows/verify-compiled.yml index 2e3eee554c..946f6f903f 100644 --- a/.github/workflows/verify-compiled.yml +++ b/.github/workflows/verify-compiled.yml @@ -17,9 +17,9 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install gh-aw CLI - uses: github/gh-aw/actions/setup-cli@main + uses: github/gh-aw-actions/setup-cli@05205436a78512d71a2d842e46586ed05f4fa058 # v0.82.10 with: - version: v0.77.5 + version: v0.82.10 - name: Recompile workflows run: gh aw compile - name: Check for uncommitted changes diff --git a/.gitignore b/.gitignore index 1485d3a9c4..4aff9be11d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,9 @@ docs/.validation/ # Visual Studio .vs/ +# Intellij IDEA +.idea/ + # C# Dev Kit *.csproj.lscache diff --git a/CHANGELOG.md b/CHANGELOG.md index 82cfa98399..41bf05e171 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,215 @@ All notable changes to the Copilot SDK are documented in this file. This changelog is automatically generated by an AI agent when stable releases are published. See [GitHub Releases](https://github.com/github/copilot-sdk/releases) for the full list. +## [v1.0.7](https://github.com/github/copilot-sdk/releases/tag/v1.0.7) (2026-07-16) + +### Feature: in-process (FFI) transport + +The SDK can now host the Copilot runtime in-process by loading the native runtime library via its C ABI (FFI), eliminating the overhead of spawning a child process. This experimental transport is available for Node.js, Rust, Python, and Go. ([#1953](https://github.com/github/copilot-sdk/pull/1953), [#1915](https://github.com/github/copilot-sdk/pull/1915), [#1975](https://github.com/github/copilot-sdk/pull/1975), [#1976](https://github.com/github/copilot-sdk/pull/1976)) + +```ts +const client = new CopilotClient({ connection: RuntimeConnection.forInProcess() }); +``` + +```cs +var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForInProcess() }); +``` + +### Feature: tool search configuration + +A new `toolSearch` session option controls how the SDK defers tools when the total tool count exceeds a threshold. When enabled (the default), excess MCP and external tools are surfaced on demand through the built-in `tool_search_tool` rather than pre-loaded into every prompt. Tool results can also include `toolReferences` to link cited sources back to the tool that produced them. ([#1933](https://github.com/github/copilot-sdk/pull/1933)) + +```ts +const session = await client.createSession({ + toolSearch: { defer: "auto" }, +}); +``` + +```cs +var session = await client.CreateSessionAsync(new SessionConfig +{ + ToolSearch = new ToolSearchConfig { Defer = "auto" }, +}); +``` + +### Feature: opaque metadata passthrough on tool definitions + +Tool definitions now accept an optional `metadata` bag that is forwarded verbatim in `session.create` and `session.resume` RPC calls. This lets hosts attach namespaced, implementation-specific metadata to tools without expanding the typed public contract; unknown keys are preserved and round-tripped untouched. ([#1864](https://github.com/github/copilot-sdk/pull/1864)) + +```ts +session.defineTool("my-tool", { metadata: { "myapp:priority": 1 } }, handler); +``` + +```cs +session.DefineTool("my-tool", new ToolOptions { Metadata = new() { ["myapp:priority"] = 1 } }, handler); +``` + +### Other changes + +- feature: **[All SDKs]** add `canvasProvider` field to session create/resume config so hosts can supply a stable canvas-provider identity that survives cold resume ([#1847](https://github.com/github/copilot-sdk/pull/1847)) +- feature: **[All SDKs]** forward `enableManagedSettings` flag in session create/resume for enterprise managed-settings enforcement ([#1925](https://github.com/github/copilot-sdk/pull/1925)) +- feature: **[All SDKs]** propagate `agentId`, `parentAgentId`, and `interactionType` from LLM inference start frames into request-handler contexts ([#1949](https://github.com/github/copilot-sdk/pull/1949)) +- improvement: **[Rust]** make tool schema and MCP server serialization deterministic by replacing `HashMap` with `IndexMap` ([#1931](https://github.com/github/copilot-sdk/pull/1931)) +- improvement: **[Rust]** use `native-tls` for the build-time CLI download ([#1964](https://github.com/github/copilot-sdk/pull/1964)) +- bugfix: **[.NET]** avoid Windows in-process test teardown deadlock ([#1997](https://github.com/github/copilot-sdk/pull/1997)) + +### New contributors + +- @agoncal made their first contribution in [#1951](https://github.com/github/copilot-sdk/pull/1951) +- @Shivam60 made their first contribution in [#1964](https://github.com/github/copilot-sdk/pull/1964) +- @rinceyuan made their first contribution in [#1978](https://github.com/github/copilot-sdk/pull/1978) +- @belaltaher8 made their first contribution in [#1864](https://github.com/github/copilot-sdk/pull/1864) + +## [java/v1.0.6](https://github.com/github/copilot-sdk/releases/tag/java/v1.0.6) (2026-07-08) + +### Feature: inline lambda tool definitions + +Developers can now define tools directly at the call site using `ToolDefinition.from(...)` with typed lambda handlers and `Param.of(...)` parameter metadata — no separate annotated class required. Async variants (`fromAsync`) and `ToolInvocation` context injection (`fromWithToolInvocation`) are also available. ([#1895](https://github.com/github/copilot-sdk/pull/1895)) + +```java +ToolDefinition greet = ToolDefinition.from( + "greet", "Greets a user by name", + Param.of(String.class, "name", "The user's name"), + name -> "Hello, " + name + "!"); +``` + +### Other changes + +- bugfix: **[Java]** preserve explicit null map values in JSON-RPC params so user setting clears reach the CLI ([#1906](https://github.com/github/copilot-sdk/pull/1906)) +- feature: **[Java]** add experimental `onGitHubTelemetry` callback on `CopilotClientOptions` for receiving forwarded GitHub telemetry events ([#1835](https://github.com/github/copilot-sdk/pull/1835)) + +## [java/v1.0.5-01](https://github.com/github/copilot-sdk/releases/tag/java/v1.0.5-01) (2026-07-01) + +### Feature: new session options — citations, agent exclusions, and credit limits + +Three new options are available on `SessionConfig` and `ResumeSessionConfig`. `enableCitations` (experimental) enables native model citations for supported providers; `excludedBuiltInAgents` hides named built-in agents from discovery; and `sessionLimits` sets a per-session AI-credit budget. ([#1865](https://github.com/github/copilot-sdk/pull/1865)) + +```java +SessionConfig config = new SessionConfig() + .setEnableCitations(true) + .setExcludedBuiltInAgents(List.of("copilot")) + .setSessionLimits(new SessionLimitsConfig(100.0)); +``` + +### New contributors + +- @coleflennikenmsft made their first contribution in [#1854](https://github.com/github/copilot-sdk/pull/1854) +- @szabta89 made their first contribution in [#1856](https://github.com/github/copilot-sdk/pull/1856) + +## [v1.0.5](https://github.com/github/copilot-sdk/releases/tag/v1.0.5) (2026-07-01) + +### Feature: MCP OAuth host token handlers + +SDK applications can now handle OAuth challenges from MCP servers that require host-provided authentication. Register an `onMcpAuthRequest` callback on the session config and the SDK will invoke it whenever an MCP server responds with a `401 WWW-Authenticate` challenge; return an access token (or cancel the request). Supports initial auth, refresh, reauth, and upscope flows across all SDKs. ([#1669](https://github.com/github/copilot-sdk/pull/1669)) + +```ts +const session = await client.createSession({ + onMcpAuthRequest: async (request) => ({ + accessToken: await myIdentityProvider.getToken(request.serverUrl), + }), +}); +``` + +```cs +var session = await client.CreateSessionAsync(new SessionConfig +{ + OnMcpAuthRequest = async ctx => + McpAuthResult.FromToken(new McpAuthToken + { + AccessToken = await myIdentityProvider.GetTokenAsync(ctx.ServerUrl) + }), +}); +``` + +### Feature: session options for citations, excluded agents, and spending limits + +Three additional session configuration options are now available across all SDKs. ([#1865](https://github.com/github/copilot-sdk/pull/1865)) + +```ts +const session = await client.createSession({ + enableCitations: true, + excludedBuiltinAgents: ["github-search"], + sessionLimits: { maxAiCredits: 10 }, +}); +``` + +```cs +var session = await client.CreateSessionAsync(new SessionConfig +{ + EnableCitations = true, + ExcludedBuiltInAgents = ["github-search"], + SessionLimits = new SessionLimitsConfig { MaxAiCredits = 10 }, +}); +``` + +### Other changes + +- improvement: **[All SDKs]** rename BYOK callback field `getBearerToken` → `bearerTokenProvider`; add `sessionId` to `ProviderTokenArgs` for per-session token scoping ([#1796](https://github.com/github/copilot-sdk/pull/1796)) +- bugfix: **[Node]** fix MCP OAuth `registerInterest` sent before `session.resume`, causing "Session not found" errors when resuming a session with `onMcpAuthRequest` ([#1861](https://github.com/github/copilot-sdk/pull/1861)) +- feature: **[Java]** `@CopilotTool` and `@CopilotToolParam` annotations with compile-time annotation processor for ergonomic tool registration via `ToolDefinition.fromObject()` ([#1792](https://github.com/github/copilot-sdk/pull/1792), [#1838](https://github.com/github/copilot-sdk/pull/1838)) +- feature: **[Java]** `ToolInvocation` parameter injection in `@CopilotTool` methods for accessing session context without exposing it to the LLM schema ([#1832](https://github.com/github/copilot-sdk/pull/1832)) +- feature: **[Rust]** add 9 GitHub-anchored variants to `Attachment` enum (`GitHubCommit`, `GitHubRelease`, `GitHubActionsJob`, `GitHubRepository`, `GitHubFileDiff`, `GitHubTreeComparison`, `GitHubUrl`, `GitHubFile`, `GitHubSnippet`) ([#1823](https://github.com/github/copilot-sdk/pull/1823)) + +### New contributors + +- @pallaviraiturkar0 made their first contribution in [#1823](https://github.com/github/copilot-sdk/pull/1823) +- @roji made their first contribution in [#1827](https://github.com/github/copilot-sdk/pull/1827) +## [java/v1.0.4](https://github.com/github/copilot-sdk/releases/tag/java/v1.0.4) (2026-06-25) + +### Feature: HTTP request callback support + +Register a `CopilotRequestHandler` on the client to intercept every outbound LLM inference HTTP or WebSocket request — for both BYOK and CAPI — and mutate, replace, or fully forward it. Useful for logging, header injection, model substitution, or custom routing. ([#1689](https://github.com/github/copilot-sdk/pull/1689), [#1775](https://github.com/github/copilot-sdk/pull/1775), [#1784](https://github.com/github/copilot-sdk/pull/1784)) + +```java +final class MyHandler extends CopilotRequestHandler { + @Override + protected HttpResponse sendRequest(HttpRequest request, CopilotRequestContext ctx) throws Exception { + HttpRequest mutated = HttpRequest.newBuilder(request, (n, v) -> true) + .header("X-Debug-Session", ctx.sessionId() == null ? "none" : ctx.sessionId()) + .build(); + return super.sendRequest(mutated, ctx); + } +} + +CopilotClient client = new CopilotClient( + new CopilotClientOptions().setRequestHandler(new MyHandler())); +``` + +### Feature: `getBearerToken` callback for BYOK providers (Managed Identity) + +BYOK provider configs now accept a `getBearerToken` callback so the SDK consumer can resolve bearer tokens (e.g. Azure Managed Identity) on demand. The SDK takes zero Azure SDK dependency — the consumer supplies the callback using any identity library. ([#1748](https://github.com/github/copilot-sdk/pull/1748)) + +```java +var provider = new ProviderConfig() + .setType("openai") + .setBaseUrl(baseUrl) + .setGetBearerToken(args -> cred.getToken(ctx).map(AccessToken::getToken).toFuture()); +``` + +### Feature: experimental multi-provider BYOK registry + +Register multiple named providers and models on a single session via `NamedProviderConfig` and `ProviderModelConfig`. Custom agents can reference provider-qualified model IDs such as `"alpha/sonnet"`. This feature is experimental. ([#1718](https://github.com/github/copilot-sdk/pull/1718)) + +### Feature: `preamble` system message section and `preserve` action + +Two new customization options for system message sections. `SystemMessageSections.PREAMBLE` targets only the identity preamble without affecting its sibling sub-sections (`identity` and `tool_instructions` are now documented as section groups). The new `preserve` action protects an individually-addressable section from a group-level `remove`. ([#1713](https://github.com/github/copilot-sdk/pull/1713)) + +### Other changes + +- feature: add optional `memory` configuration (`MemoryConfiguration`) to session create and resume ([#1617](https://github.com/github/copilot-sdk/pull/1617)) +- feature: `defer` parameter on tool definitions controls eager vs. lazy tool loading (`"auto"` or `"never"`) ([#1632](https://github.com/github/copilot-sdk/pull/1632)) +- feature: `otlpProtocol` telemetry option for configuring OTLP export transport (`"http/json"` or `"http/protobuf"`) ([#1648](https://github.com/github/copilot-sdk/pull/1648)) +- feature: `ModelBilling.tokenPrices` surfaced on public SDK types, exposing per-tier pricing and context window limits ([#1633](https://github.com/github/copilot-sdk/pull/1633)) +- feature: `CapiSessionOptions.enableWebSocketResponses` and `ProviderConfig.transport` for WebSocket transport control on session create/resume ([#1711](https://github.com/github/copilot-sdk/pull/1711)) +- improvement: call `runtime.shutdown` during client stop for deterministic OTEL telemetry flush before process cleanup ([#1667](https://github.com/github/copilot-sdk/pull/1667)) +- improvement: rename `SystemPromptSections` → `SystemMessageSections` for cross-SDK consistency; old class deprecated with `forRemoval=true` ([#1683](https://github.com/github/copilot-sdk/pull/1683)) + +### New contributors + +- @almaleksia made their first contribution in [#1632](https://github.com/github/copilot-sdk/pull/1632) +- @dereklegenzoff made their first contribution in [#1711](https://github.com/github/copilot-sdk/pull/1711) +- @ellismg made their first contribution in [#1750](https://github.com/github/copilot-sdk/pull/1750) + ## [v1.0.2](https://github.com/github/copilot-sdk/releases/tag/v1.0.2) (2026-06-18) ### Feature: opt-in memory for sessions diff --git a/README.md b/README.md index f80b5ecdc2..43ff70debd 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Yes, a GitHub Copilot subscription is required to use the GitHub Copilot SDK, ** ### How does billing work for SDK usage? -Billing for the GitHub Copilot SDK is based on the same model as the Copilot CLI, with each prompt being counted towards your premium request quota. For more information on premium requests, see [Requests in GitHub Copilot](https://docs.github.com/en/copilot/concepts/billing/copilot-requests). +Billing for the GitHub Copilot SDK is based on the same model as the Copilot CLI, with each prompt being counted towards your usage allowance. For more information on Copilot usage billing, see [Usage in GitHub Copilot](https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing). ### Does it support BYOK (Bring Your Own Key)? diff --git a/docs/README.md b/docs/README.md index 3d46fe9abf..9e0d8fddff 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,4 +1,4 @@ -# Copilot SDK +# Copilot SDK Welcome to the GitHub Copilot SDK docs. Whether you're building your first Copilot-powered app or deploying to production, you'll find what you need here. @@ -46,6 +46,7 @@ Guides for building with the SDK's capabilities. * [MCP Servers](./features/mcp.md): integrate Model Context Protocol servers * [Skills](./features/skills.md): load reusable prompt modules * [Plugin Directories](./features/plugin-directories.md): bundle skills, hooks, MCP servers, and agents as a single loadable plugin +* [Session limits](./features/session-limits.md): set an AI Credits budget for a session * [Image Input](./features/image-input.md): send images as attachments * [Streaming Events](./features/streaming-events.md): real-time event reference * [Steering & Queueing](./features/steering-and-queueing.md): message delivery modes diff --git a/docs/auth/README.md b/docs/auth/README.md index b09646d5d7..282bcb0192 100644 --- a/docs/auth/README.md +++ b/docs/auth/README.md @@ -7,6 +7,6 @@ Choose the authentication method that best fits your deployment scenario for the ## Authentication priority -When multiple credentials are configured, an explicit SDK token takes priority, followed by HMAC or direct Copilot API environment authentication, environment variable GitHub tokens, stored Copilot CLI credentials, and then GitHub CLI credentials. See [Authenticate Copilot SDK](authenticate.md#authentication-priority) for details. +When multiple credentials are configured, an explicit SDK token takes priority, followed by direct Copilot API environment authentication, environment variable GitHub tokens, stored Copilot CLI credentials, and then GitHub CLI credentials. See [Authenticate Copilot SDK](authenticate.md#authentication-priority) for details. For multi-user server mode, pass a per-session `gitHubToken` so each session runs with the correct GitHub identity; see [Multi-user and server deployments](../setup/multi-tenancy.md). diff --git a/docs/auth/authenticate.md b/docs/auth/authenticate.md index 0c4d706992..1a01901863 100644 --- a/docs/auth/authenticate.md +++ b/docs/auth/authenticate.md @@ -9,7 +9,7 @@ The GitHub Copilot SDK supports multiple authentication methods to fit different | [GitHub Signed-in User](#github-signed-in-user) | Interactive apps where users sign in with GitHub | Yes | | [OAuth GitHub App](#oauth-github-app) | Apps acting on behalf of users via OAuth | Yes | | [Environment Variables](#environment-variables) | CI/CD, automation, server-to-server | Yes | -| [BYOK (Bring Your Own Key)](./byok.md) | Using your own API keys (Azure AI Foundry, OpenAI, etc.) | No | +| [BYOK (Bring Your Own Key)](./byok.md) | Using your own API keys (Azure AI Foundry, OpenAI, and more) | No | ## GitHub signed-in user @@ -221,7 +221,7 @@ client.start().get(); **Supported token types:** * `gho_` - OAuth user access tokens -* `ghu_` - GitHub App user access tokens +* `ghu_` - GitHub App user access tokens * `github_pat_` - Fine-grained personal access tokens **Not supported:** @@ -275,7 +275,7 @@ await client.start() **When to use:** -* CI/CD pipelines (GitHub Actions, Jenkins, etc.) +* CI/CD pipelines (GitHub Actions, Jenkins, and more) * Automated testing * Server-side applications with service accounts * Development when you don't want to use interactive login @@ -301,7 +301,6 @@ BYOK allows you to use your own API keys from model providers like Azure AI Foun When multiple authentication methods are available, the SDK uses them in this priority order: 1. **Explicit `gitHubToken`** - Token passed directly to the SDK client or session configuration -1. **HMAC key** - `CAPI_HMAC_KEY` or `COPILOT_HMAC_KEY` environment variables 1. **Direct API token** - `GITHUB_COPILOT_API_TOKEN` with `COPILOT_API_URL` 1. **Environment variable tokens** - `COPILOT_GITHUB_TOKEN` → `GH_TOKEN` → `GITHUB_TOKEN` 1. **Stored OAuth credentials** - From previous `copilot` CLI login diff --git a/docs/auth/byok.md b/docs/auth/byok.md index 1bf3646640..01d954a40b 100644 --- a/docs/auth/byok.md +++ b/docs/auth/byok.md @@ -529,7 +529,7 @@ import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", provider: { type: "azure", baseUrl: "https://my-resource.openai.azure.com", @@ -560,7 +560,7 @@ import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", provider: { type: "openai", baseUrl: "https://your-resource.openai.azure.com/openai/v1/", diff --git a/docs/features/README.md b/docs/features/README.md index fe2a98c2ea..b695fea6d4 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -15,6 +15,7 @@ These guides cover the capabilities you can add to your Copilot SDK application. | [MCP Servers](./mcp.md) | Integrate Model Context Protocol servers for external tool access | | [Skills](./skills.md) | Load reusable prompt modules from directories | | [Plugin Directories](./plugin-directories.md) | Bundle skills, hooks, MCP servers, and agents as a single loadable plugin | +| [Session limits](./session-limits.md) | Set an AI Credits budget for a session and observe budget events | | [Image Input](./image-input.md) | Send images to sessions as attachments | | [Streaming Events](./streaming-events.md) | Subscribe to real-time session events (40+ event types) | | [Steering & Queueing](./steering-and-queueing.md) | Control message delivery—immediate steering vs. sequential queueing | diff --git a/docs/features/cloud-sessions.md b/docs/features/cloud-sessions.md index 0d670b996f..863f9456b9 100644 --- a/docs/features/cloud-sessions.md +++ b/docs/features/cloud-sessions.md @@ -235,7 +235,7 @@ Capture the URL by subscribing to `session.info` and filtering by `infoType: "re session.on("session.info", (event) => { if (event.data?.infoType === "remote" && event.data.url) { console.log("Open from web or mobile:", event.data.url); - // e.g. surface in your UI as a shareable link or QR code. + // For example, surface in your UI as a shareable link or QR code. } }); ``` diff --git a/docs/features/custom-agents.md b/docs/features/custom-agents.md index fb2f81fd1c..3cab77474e 100644 --- a/docs/features/custom-agents.md +++ b/docs/features/custom-agents.md @@ -37,7 +37,7 @@ const client = new CopilotClient(); await client.start(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", customAgents: [ { name: "researcher", @@ -71,7 +71,7 @@ await client.start() session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), - model="gpt-4.1", + model="gpt-5.4", custom_agents=[ { "name": "researcher", @@ -112,7 +112,7 @@ func main() { client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", CustomAgents: []copilot.CustomAgentConfig{ { Name: "researcher", @@ -144,7 +144,7 @@ client := copilot.NewClient(nil) client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", CustomAgents: []copilot.CustomAgentConfig{ { Name: "researcher", @@ -179,7 +179,7 @@ using GitHub.Copilot.Rpc; await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "gpt-5.4", CustomAgents = new List { new() @@ -219,7 +219,7 @@ try (var client = new CopilotClient()) { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setCustomAgents(List.of( new CustomAgentConfig() .setName("researcher") @@ -253,10 +253,14 @@ try (var client = new CopilotClient()) { | `mcpServers` | `object` | | MCP server configurations specific to this agent | | `infer` | `boolean` | | Whether the runtime can auto-select this agent (default: `true`) | | `skills` | `string[]` | | Skill names to preload into the agent's context at startup | +| `model` | `string` | | Model identifier to use while this agent runs | +| `reasoningEffort` | `string` | | Reasoning effort to use while this agent runs. When omitted, no override is sent and the backend chooses its default | > [!TIP] > A good `description` helps the runtime match user intent to the right agent. Be specific about the agent's expertise and capabilities. +Set `model` and `reasoningEffort` to override the parent session's model settings while a custom agent runs. When `reasoningEffort` is omitted, the SDK sends no per-agent override and the backend chooses its default. The parent session effort is not inherited, and the SDK does not add a per-agent default. Python uses `reasoning_effort`, .NET uses `ReasoningEffort`, Go uses `ReasoningEffort`, Java uses `setReasoningEffort`, and Rust uses `with_reasoning_effort`. + In addition to per-agent configuration above, you can set `agent` on the **session config** itself to pre-select which custom agent is active when the session starts. See [Selecting an Agent at Session Creation](#selecting-an-agent-at-session-creation) below. | Session Config Property | Type | Description | @@ -529,7 +533,7 @@ func main() { client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, diff --git a/docs/features/fleet-mode.md b/docs/features/fleet-mode.md index a830f4931d..cbb737b78d 100644 --- a/docs/features/fleet-mode.md +++ b/docs/features/fleet-mode.md @@ -8,18 +8,18 @@ Fleet mode is useful when the work can be decomposed before execution and each u Good fits include: -- Multi-file refactors where each worker owns a file, package, or language SDK. -- Batch reviews where each worker checks a separate diff, module, or alert group. -- Parallel research across independent repositories, services, or feature areas. -- Documentation refreshes where each worker owns a page or topic. -- Migration tasks where each worker can validate its own slice and report back. +* Multi-file refactors where each worker owns a file, package, or language SDK. +* Batch reviews where each worker checks a separate diff, module, or alert group. +* Parallel research across independent repositories, services, or feature areas. +* Documentation refreshes where each worker owns a page or topic. +* Migration tasks where each worker can validate its own slice and report back. Avoid fleet mode for: -- Sequential tasks where step 2 needs the concrete output from step 1. -- Tightly coupled edits where workers would contend for the same files. -- Small tasks that one synchronous sub-agent or the parent agent can finish quickly. -- Tasks that require continuous shared reasoning rather than clear ownership. +* Sequential tasks where step 2 needs the concrete output from step 1. +* Tightly coupled edits where workers would contend for the same files. +* Small tasks that one synchronous sub-agent or the parent agent can finish quickly. +* Tasks that require continuous shared reasoning rather than clear ownership. Fleet mode works best when the parent session can create clear units of work, assign one owner per unit, and define what each worker must return. @@ -321,29 +321,29 @@ Keep plugin-provided sub-agent types narrow and descriptive so the orchestrator ## Best practices -- Decompose the work into independent units before starting fleet mode. -- Minimize dependencies between todos; dependencies reduce parallelism. -- Give each todo a durable ID, a clear title, and a complete description. -- Make each sub-agent own exactly one todo at a time. -- Use background sub-agents for truly parallel work. -- Use synchronous sub-agent calls for serialized steps or validation gates. -- Provide each sub-agent with complete context; sub-agents are stateless across calls. -- Include file paths, commands, expected outputs, and constraints in each worker prompt. -- Do not dispatch a single background sub-agent; prefer a synchronous call or batch multiple workers in parallel. -- Avoid assigning overlapping files to different workers unless the parent agent will reconcile conflicts explicitly. -- Require every worker to report what it changed, how it validated the change, and what remains blocked. -- Have the parent agent verify the combined result after workers finish. +* Decompose the work into independent units before starting fleet mode. +* Minimize dependencies between todos; dependencies reduce parallelism. +* Give each todo a durable ID, a clear title, and a complete description. +* Make each sub-agent own exactly one todo at a time. +* Use background sub-agents for truly parallel work. +* Use synchronous sub-agent calls for serialized steps or validation gates. +* Provide each sub-agent with complete context; sub-agents are stateless across calls. +* Include file paths, commands, expected outputs, and constraints in each worker prompt. +* Do not dispatch a single background sub-agent; prefer a synchronous call or batch multiple workers in parallel. +* Avoid assigning overlapping files to different workers unless the parent agent will reconcile conflicts explicitly. +* Require every worker to report what it changed, how it validated the change, and what remains blocked. +* Have the parent agent verify the combined result after workers finish. ## Limitations and open questions -- Fleet mode is exposed through generated session RPC bindings and is marked experimental in several SDKs. -- The SQL todos pattern is the canonical coordination model in the runtime guidance, but whether it is a stable extensibility contract for SDK consumers is still an open question. -- `subagentStart` and `subagentStop` are runtime hook names; this branch exposes sub-agent lifecycle to SDK consumers through the generic session event stream, not dedicated hook callbacks. -- Plugin sub-agent registration is configured at the runtime layer through `--plugin-dir`; no SDK-level plugin registration helper was verified on this branch. -- Java native typed bindings for `session.fleet.start` were not found in the Java SDK source on this branch. -- Fleet mode does not remove the need for parent-agent review. Parallel workers can produce inconsistent assumptions that the orchestrator must reconcile. +* Fleet mode is exposed through generated session RPC bindings and is marked experimental in several SDKs. +* The SQL todos pattern is the canonical coordination model in the runtime guidance, but whether it is a stable extensibility contract for SDK consumers is still an open question. +* `subagentStart` and `subagentStop` are runtime hook names; this branch exposes sub-agent lifecycle to SDK consumers through the generic session event stream, not dedicated hook callbacks. +* Plugin sub-agent registration is configured at the runtime layer through `--plugin-dir`; no SDK-level plugin registration helper was verified on this branch. +* Java native typed bindings for `session.fleet.start` were not found in the Java SDK source on this branch. +* Fleet mode does not remove the need for parent-agent review. Parallel workers can produce inconsistent assumptions that the orchestrator must reconcile. ## See also -- [Custom agents and sub-agent orchestration](custom-agents.md) -- [Hooks](hooks.md) +* [Custom agents and sub-agent orchestration](custom-agents.md) +* [Hooks](hooks.md) diff --git a/docs/features/hooks.md b/docs/features/hooks.md index 6af5232a68..feee55546d 100644 --- a/docs/features/hooks.md +++ b/docs/features/hooks.md @@ -1051,16 +1051,16 @@ const session = await client.createSession({ For full type definitions, input/output field tables, and additional examples for every hook, see the API reference: -- [Hooks Overview](../hooks/hooks-overview.md) -- [Pre-Tool Use](../hooks/pre-tool-use.md) -- [Post-Tool Use](../hooks/post-tool-use.md) -- [User Prompt Submitted](../hooks/user-prompt-submitted.md) -- [Session Lifecycle](../hooks/session-lifecycle.md) -- [Error Handling](../hooks/error-handling.md) +* [Hooks Overview](../hooks/hooks-overview.md) +* [Pre-Tool Use](../hooks/pre-tool-use.md) +* [Post-Tool Use](../hooks/post-tool-use.md) +* [User Prompt Submitted](../hooks/user-prompt-submitted.md) +* [Session Lifecycle](../hooks/session-lifecycle.md) +* [Error Handling](../hooks/error-handling.md) ## See also -- [Getting Started](../getting-started.md) -- [Custom Agents & Sub-Agent Orchestration](./custom-agents.md) -- [Streaming Session Events](./streaming-events.md) -- [Debugging Guide](../troubleshooting/debugging.md) \ No newline at end of file +* [Getting Started](../getting-started.md) +* [Custom Agents & Sub-Agent Orchestration](./custom-agents.md) +* [Streaming Session Events](./streaming-events.md) +* [Debugging Guide](../troubleshooting/debugging.md) \ No newline at end of file diff --git a/docs/features/image-input.md b/docs/features/image-input.md index c63a80c11d..321e5d2fc6 100644 --- a/docs/features/image-input.md +++ b/docs/features/image-input.md @@ -47,7 +47,7 @@ const client = new CopilotClient(); await client.start(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", onPermissionRequest: async () => ({ kind: "approve-once" }), }); @@ -75,7 +75,7 @@ await client.start() session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), - model="gpt-4.1", + model="gpt-5.4", ) await session.send( @@ -110,7 +110,7 @@ func main() { client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, @@ -136,7 +136,7 @@ client := copilot.NewClient(nil) client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, @@ -171,7 +171,7 @@ public static class ImageInputExample await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "gpt-5.4", OnPermissionRequest = (req, inv) => Task.FromResult(PermissionDecision.ApproveOnce()), }); @@ -200,7 +200,7 @@ using GitHub.Copilot.Rpc; await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "gpt-5.4", OnPermissionRequest = (req, inv) => Task.FromResult(PermissionDecision.ApproveOnce()), }); @@ -234,7 +234,7 @@ try (var client = new CopilotClient()) { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -263,7 +263,7 @@ const client = new CopilotClient(); await client.start(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", onPermissionRequest: async () => ({ kind: "approve-once" }), }); @@ -294,7 +294,7 @@ await client.start() session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), - model="gpt-4.1", + model="gpt-5.4", ) base64_image_data = "..." # your base64-encoded image @@ -332,7 +332,7 @@ func main() { client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, @@ -387,7 +387,7 @@ public static class BlobAttachmentExample await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "gpt-5.4", OnPermissionRequest = (req, inv) => Task.FromResult(PermissionDecision.ApproveOnce()), }); @@ -442,7 +442,7 @@ try (var client = new CopilotClient()) { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); diff --git a/docs/features/session-limits.md b/docs/features/session-limits.md new file mode 100644 index 0000000000..b2e4cfe479 --- /dev/null +++ b/docs/features/session-limits.md @@ -0,0 +1,174 @@ +# Session limits + +Session limits let an application set an AI Credits budget for a Copilot session. Use `sessionLimits` when creating or resuming a session to set a soft cap for the current accounting window. + +## Configure a session limit + +Set `maxAiCredits` to the AI Credits soft cap for the session's current accounting window. Usage is checked after model calls return, so one response can exceed the configured value before the runtime blocks the next model call. The SDK forwards this value to the Copilot CLI when it creates or resumes the session. + +
+TypeScript + + + +```typescript +const session = await client.createSession({ + onPermissionRequest: approveAll, + sessionLimits: { + maxAiCredits: 30, + }, +}); + +const resumed = await client.resumeSession(session.sessionId, { + onPermissionRequest: approveAll, + sessionLimits: { + maxAiCredits: 30, + }, +}); +``` + +
+
+Python + + + +```python +session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + session_limits={ + "max_ai_credits": 30, + }, +) + +resumed = await client.resume_session( + session.session_id, + on_permission_request=PermissionHandler.approve_all, + session_limits={ + "max_ai_credits": 30, + }, +) +``` + +
+
+Go + + + +```go +session, err := client.CreateSession(ctx, &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + SessionLimits: &rpc.SessionLimitsConfig{ + MaxAiCredits: copilot.Float64(30), + }, +}) + +resumed, err := client.ResumeSession(ctx, session.SessionID, &copilot.ResumeSessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + SessionLimits: &rpc.SessionLimitsConfig{ + MaxAiCredits: copilot.Float64(30), + }, +}) +``` + +
+
+.NET + + + +```csharp +var session = await client.CreateSessionAsync(new SessionConfig +{ + OnPermissionRequest = PermissionHandler.ApproveAll, + SessionLimits = new SessionLimitsConfig + { + MaxAiCredits = 30, + }, +}); + +var resumed = await client.ResumeSessionAsync(session.SessionId, new ResumeSessionConfig +{ + OnPermissionRequest = PermissionHandler.ApproveAll, + SessionLimits = new SessionLimitsConfig + { + MaxAiCredits = 30, + }, +}); +``` + +
+
+Java + + + +```java +CopilotSession session = client + .createSession(new SessionConfig() + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setSessionLimits(new SessionLimitsConfig(30.0))) + .get(); + +CopilotSession resumed = client + .resumeSession(session.getSessionId(), new ResumeSessionConfig() + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setSessionLimits(new SessionLimitsConfig(30.0))) + .get(); +``` + +
+
+Rust + + + +```rust +let limits = SessionLimitsConfig { + max_ai_credits: Some(30.0), +}; + +let session = client + .create_session( + SessionConfig::new() + .approve_all_permissions() + .with_session_limits(limits.clone()), + ) + .await?; + +let resumed = client + .resume_session( + ResumeSessionConfig::new(session.id().clone()) + .approve_all_permissions() + .with_session_limits(limits), + ) + .await?; +``` + +
+ +## Observe budget events + +Applications can subscribe to session events to update UI when the soft cap changes or the session reaches the exhausted-budget flow. + +| Event type | When it is emitted | Important fields | +|---|---|---| +| `session.session_limits_changed` | Active session limits changed. A `null` `sessionLimits` value means no limits are active. | `sessionLimits.maxAiCredits?` | +| `session.usage_checkpoint` | The runtime records durable aggregate usage for resume and accounting. | `totalNanoAiu`, `totalPremiumRequests?` | +| `session_limits_exhausted.requested` | The session reached the exhausted-budget flow and needs a user decision before continuing. | `requestId`, `maxAiCredits`, `usedAiCredits` | +| `session_limits_exhausted.completed` | The exhausted-limit prompt was resolved. | `requestId`, `response.action`, `response.additionalAiCredits?`, `response.maxAiCredits?` | + +Use the generated event types for the SDK language you are using. For example, TypeScript narrows by `event.type`: + +```typescript +session.on((event) => { + if (event.type === "session_limits_exhausted.requested") { + showBudgetDialog({ + requestId: event.data.requestId, + maxAiCredits: event.data.maxAiCredits, + usedAiCredits: event.data.usedAiCredits, + }); + } +}); +``` diff --git a/docs/features/skills.md b/docs/features/skills.md index 6db955e743..5b8388162a 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -24,7 +24,7 @@ import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", skillDirectories: [ "./skills/code-review", "./skills/documentation", @@ -50,7 +50,7 @@ async def main(): session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), - model="gpt-4.1", + model="gpt-5.4", skill_directories=[ "./skills/code-review", "./skills/documentation", @@ -87,7 +87,7 @@ func main() { defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", SkillDirectories: []string{ "./skills/code-review", "./skills/documentation", @@ -122,7 +122,7 @@ using GitHub.Copilot.Rpc; await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "gpt-5.4", SkillDirectories = new List { "./skills/code-review", @@ -154,7 +154,7 @@ try (var client = new CopilotClient()) { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setSkillDirectories(List.of( "./skills/code-review", "./skills/documentation" diff --git a/docs/features/steering-and-queueing.md b/docs/features/steering-and-queueing.md index 7dbdc17b7c..7bfffc433d 100644 --- a/docs/features/steering-and-queueing.md +++ b/docs/features/steering-and-queueing.md @@ -47,7 +47,7 @@ const client = new CopilotClient(); await client.start(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", onPermissionRequest: async () => ({ kind: "approve-once" }), }); @@ -77,7 +77,7 @@ async def main(): session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), - model="gpt-4.1", + model="gpt-5.4", ) # Start a long-running task @@ -118,7 +118,7 @@ func main() { defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, @@ -158,7 +158,7 @@ using GitHub.Copilot.Rpc; await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "gpt-5.4", OnPermissionRequest = (req, inv) => Task.FromResult(PermissionDecision.ApproveOnce()), }); @@ -191,7 +191,7 @@ try (var client = new CopilotClient()) { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -234,7 +234,7 @@ const client = new CopilotClient(); await client.start(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", onPermissionRequest: async () => ({ kind: "approve-once" }), }); @@ -269,7 +269,7 @@ async def main(): session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), - model="gpt-4.1", + model="gpt-5.4", ) # Send an initial task @@ -311,7 +311,7 @@ func main() { client.Start(ctx) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, @@ -371,7 +371,7 @@ public static class QueueingExample await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "gpt-5.4", OnPermissionRequest = (req, inv) => Task.FromResult(PermissionDecision.ApproveOnce()), }); @@ -434,7 +434,7 @@ try (var client = new CopilotClient()) { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -475,7 +475,7 @@ You can use both patterns together in a single session. Steering affects the cur ```typescript const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", onPermissionRequest: async () => ({ kind: "approve-once" }), }); @@ -503,7 +503,7 @@ await session.send({ ```python session = await client.create_session( on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(), - model="gpt-4.1", + model="gpt-5.4", ) # Start a task diff --git a/docs/features/streaming-events.md b/docs/features/streaming-events.md index 423aa9e34b..0c2dafdefb 100644 --- a/docs/features/streaming-events.md +++ b/docs/features/streaming-events.md @@ -130,7 +130,7 @@ func main() { client := copilot.NewClient(nil) session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "gpt-5.4", Streaming: copilot.Bool(true), OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil @@ -306,7 +306,7 @@ Ephemeral. Token usage and cost information for an individual API call. | Data Field | Type | Required | Description | |------------|------|----------|-------------| -| `model` | `string` | ✅ | Model identifier (e.g., `"gpt-4.1"`) | +| `model` | `string` | ✅ | Model identifier (e.g., `"gpt-5.4"`) | | `inputTokens` | `number` | | Input tokens consumed | | `outputTokens` | `number` | | Output tokens produced | | `cacheReadTokens` | `number` | | Tokens read from prompt cache | @@ -472,6 +472,24 @@ Ephemeral. Context window utilization snapshot. | `currentTokens` | `number` | ✅ | Current tokens in the context window | | `messagesLength` | `number` | ✅ | Current message count in the conversation | +### `session.session_limits_changed` + +Session limits changed for the current accounting window. A `null` `sessionLimits` value means no limits are active. + +| Data Field | Type | Required | Description | +|------------|------|----------|-------------| +| `sessionLimits` | `SessionLimitsConfig \| null` | ✅ | Current session limits, or `null` when no limits are active | +| `sessionLimits.maxAiCredits` | `number` | | Maximum AI Credits allowed across the session's current accounting window | + +### `session.usage_checkpoint` + +Durable aggregate usage checkpoint used to reconstruct accounting when a session is resumed. + +| Data Field | Type | Required | Description | +|------------|------|----------|-------------| +| `totalNanoAiu` | `number` | ✅ | Session-wide accumulated nano-AI units cost at checkpoint time | +| `totalPremiumRequests` | `number` | | Total number of premium API requests used at checkpoint time | + ### `session.task_complete` The agent has completed its assigned task. @@ -721,6 +739,27 @@ Ephemeral. A queued command was resolved. |------------|------|----------|-------------| | `requestId` | `string` | ✅ | Matches the corresponding `command.queued` | +### `session_limits_exhausted.requested` + +Ephemeral. The current session budget was exhausted and the runtime needs a user decision before continuing. + +| Data Field | Type | Required | Description | +|------------|------|----------|-------------| +| `requestId` | `string` | ✅ | Use this ID when responding to the pending exhausted-limit request | +| `maxAiCredits` | `number` | ✅ | Configured max AI Credits for the current accounting window | +| `usedAiCredits` | `number` | ✅ | AI Credits already consumed in the current accounting window | + +### `session_limits_exhausted.completed` + +Ephemeral. A pending exhausted-limit request was resolved. + +| Data Field | Type | Required | Description | +|------------|------|----------|-------------| +| `requestId` | `string` | ✅ | Matches the corresponding `session_limits_exhausted.requested` event | +| `response.action` | `"add" \| "set" \| "unset" \| "cancel"` | ✅ | Action selected for the exhausted-limit request | +| `response.additionalAiCredits` | `number` | | AI Credits to add to the current max when `response.action` is `"add"` | +| `response.maxAiCredits` | `number` | | New absolute max AI Credits when `response.action` is `"set"` | + ## Quick reference: agentic turn flow A typical agentic turn emits events in this order: @@ -773,6 +812,8 @@ session.idle → Ready for next message (ephemeral) | `session.title_changed` | ✅ | Session | `title` | | `session.context_changed` | | Session | `cwd`, `gitRoot?`, `repository?`, `branch?` | | `session.usage_info` | ✅ | Session | `tokenLimit`, `currentTokens`, `messagesLength` | +| `session.session_limits_changed` | | Session | `sessionLimits` | +| `session.usage_checkpoint` | | Session | `totalNanoAiu`, `totalPremiumRequests?` | | `session.task_complete` | | Session | `summary?` | | `session.shutdown` | | Session | `shutdownType`, `codeChanges`, `modelMetrics` | | `permission.requested` | ✅ | Permission | `requestId`, `permissionRequest` | @@ -794,5 +835,7 @@ session.idle → Ready for next message (ephemeral) | `external_tool.completed` | ✅ | External Tool | `requestId` | | `command.queued` | ✅ | Command | `requestId`, `command` | | `command.completed` | ✅ | Command | `requestId` | +| `session_limits_exhausted.requested` | ✅ | Session | `requestId`, `maxAiCredits`, `usedAiCredits` | +| `session_limits_exhausted.completed` | ✅ | Session | `requestId`, `response.action` | | `exit_plan_mode.requested` | ✅ | Plan Mode | `requestId`, `summary`, `planContent`, `actions` | | `exit_plan_mode.completed` | ✅ | Plan Mode | `requestId` | \ No newline at end of file diff --git a/docs/getting-started.md b/docs/getting-started.md index c258c50e9c..b14fb73e52 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -150,7 +150,7 @@ Create `index.ts`: import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); -const session = await client.createSession({ model: "gpt-4.1" }); +const session = await client.createSession({ model: "auto" }); const response = await session.sendAndWait({ prompt: "What is 2 + 2?" }); console.log(response?.data.content); @@ -181,7 +181,7 @@ async def main(): client = CopilotClient() await client.start() - session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1") + session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="auto") response = await session.send_and_wait("What is 2 + 2?") print(response.data.content) @@ -223,7 +223,7 @@ func main() { } defer client.Stop() - session, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"}) + session, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "auto"}) if err != nil { log.Fatal(err) } @@ -304,7 +304,7 @@ using GitHub.Copilot; await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "auto", OnPermissionRequest = PermissionHandler.ApproveAll }); @@ -337,7 +337,7 @@ public class HelloCopilot { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("auto") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -383,7 +383,7 @@ import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "auto", streaming: true, }); @@ -419,7 +419,7 @@ async def main(): client = CopilotClient() await client.start() - session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1", streaming=True) + session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="auto", streaming=True) # Listen for response chunks def handle_event(event): @@ -466,7 +466,7 @@ func main() { defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "auto", Streaming: copilot.Bool(true), }) if err != nil { @@ -562,7 +562,7 @@ using GitHub.Copilot; await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "auto", OnPermissionRequest = PermissionHandler.ApproveAll, Streaming = true, }); @@ -602,7 +602,7 @@ public class HelloCopilot { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("auto") .setStreaming(true) .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -912,7 +912,7 @@ const getWeather = defineTool("get_weather", { const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "auto", streaming: true, tools: [getWeather], }); @@ -968,7 +968,7 @@ async def main(): client = CopilotClient() await client.start() - session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1", streaming=True, tools=[get_weather]) + session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="auto", streaming=True, tools=[get_weather]) def handle_event(event): if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA: @@ -1045,7 +1045,7 @@ func main() { defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "auto", Streaming: copilot.Bool(true), Tools: []copilot.Tool{getWeather}, }) @@ -1185,7 +1185,7 @@ var getWeather = CopilotTool.DefineTool( await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "auto", OnPermissionRequest = PermissionHandler.ApproveAll, Streaming = true, Tools = [getWeather], @@ -1259,7 +1259,7 @@ public class HelloCopilot { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("auto") .setStreaming(true) .setTools(List.of(getWeather)) .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) @@ -1316,7 +1316,7 @@ const getWeather = defineTool("get_weather", { const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "auto", streaming: true, tools: [getWeather], }); @@ -1389,7 +1389,7 @@ async def main(): client = CopilotClient() await client.start() - session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1", streaming=True, tools=[get_weather]) + session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="auto", streaming=True, tools=[get_weather]) def handle_event(event): if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA: @@ -1482,7 +1482,7 @@ func main() { defer client.Stop() session, err := client.CreateSession(ctx, &copilot.SessionConfig{ - Model: "gpt-4.1", + Model: "auto", Streaming: copilot.Bool(true), Tools: []copilot.Tool{getWeather}, }) @@ -1671,7 +1671,7 @@ var getWeather = CopilotTool.DefineTool( await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync(new SessionConfig { - Model = "gpt-4.1", + Model = "auto", OnPermissionRequest = PermissionHandler.ApproveAll, Streaming = true, Tools = [getWeather] @@ -1765,7 +1765,7 @@ public class WeatherAssistant { var session = client.createSession( new SessionConfig() - .setModel("gpt-4.1") + .setModel("auto") .setStreaming(true) .setOnPermissionRequest(request -> CompletableFuture.completedFuture(PermissionDecision.allow()) diff --git a/docs/hooks/post-tool-use.md b/docs/hooks/post-tool-use.md index 45964b0344..b7ef3af1c4 100644 --- a/docs/hooks/post-tool-use.md +++ b/docs/hooks/post-tool-use.md @@ -2,10 +2,10 @@ The `onPostToolUse` hook is called **after** a tool executes **successfully**. Use it to: -- Transform or filter tool results -- Log tool execution for auditing -- Add context based on results -- Suppress results from the conversation +* Transform or filter tool results +* Log tool execution for auditing +* Add context based on results +* Suppress results from the conversation > **Failure variant** — `onPostToolUse` only fires for successful tool executions. To observe **failed** tool calls, register `onPostToolUseFailure` (`on_post_tool_use_failure` in Python, `OnPostToolUseFailure` in Go/.NET, `on_post_tool_use_failure` in Rust). The handler receives `{ sessionId, toolName, toolArgs, error, timestamp, workingDirectory }` — the `error` field is a string extracted from the tool's failure result — and may return `{ additionalContext: string }` to inject extra guidance for the model (e.g. retry hints). See the [hooks overview](./hooks-overview.md) for the full list. > @@ -507,6 +507,6 @@ const session = await client.createSession({ ## See also -- [Hooks Overview](./README.md) -- [Pre-Tool Use Hook](./pre-tool-use.md) -- [Error Handling Hook](./error-handling.md) \ No newline at end of file +* [Hooks Overview](./README.md) +* [Pre-Tool Use Hook](./pre-tool-use.md) +* [Error Handling Hook](./error-handling.md) \ No newline at end of file diff --git a/docs/integrations/microsoft-agent-framework.md b/docs/integrations/microsoft-agent-framework.md index 3d6d990860..663a20a799 100644 --- a/docs/integrations/microsoft-agent-framework.md +++ b/docs/integrations/microsoft-agent-framework.md @@ -123,7 +123,7 @@ var client = new CopilotClient(); client.start().get(); var session = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -217,7 +217,7 @@ const getWeather = DefineTool({ const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", tools: [getWeather], onPermissionRequest: async () => ({ kind: "approve-once" }), }); @@ -255,7 +255,7 @@ try (var client = new CopilotClient()) { client.start().get(); var session = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setTools(List.of(getWeather)) .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -296,7 +296,7 @@ AIAgent reviewer = copilotClient.AsAIAgent(new AIAgentOptions // Azure OpenAI agent for generating documentation AIAgent documentor = AIAgent.FromOpenAI(new OpenAIAgentOptions { - Model = "gpt-4.1", + Model = "gpt-5.4", Instructions = "You write clear, concise documentation for code changes.", }); @@ -330,7 +330,7 @@ async def main(): # OpenAI agent for documentation documentor = OpenAIAgent( - model="gpt-4.1", + model="gpt-5.4", instructions="You write clear, concise documentation for code changes.", ) @@ -360,7 +360,7 @@ client.start().get(); // Step 1: Code review session var reviewer = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -370,7 +370,7 @@ var review = reviewer.sendAndWait(new MessageOptions() // Step 2: Documentation session using review output var documentor = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -434,12 +434,12 @@ var client = new CopilotClient(); client.start().get(); var securitySession = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); var perfSession = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -518,7 +518,7 @@ import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", streaming: true, onPermissionRequest: async () => ({ kind: "approve-once" }), }); @@ -544,7 +544,7 @@ var client = new CopilotClient(); client.start().get(); var session = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setStreaming(true) .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -598,7 +598,7 @@ import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", onPermissionRequest: async () => ({ kind: "approve-once" }), }); const response = await session.sendAndWait({ prompt: "Explain this code" }); diff --git a/docs/setup/azure-managed-identity.md b/docs/setup/azure-managed-identity.md index 51ca0dc0be..8afac6e1d3 100644 --- a/docs/setup/azure-managed-identity.md +++ b/docs/setup/azure-managed-identity.md @@ -240,7 +240,7 @@ class ManagedIdentityCopilotAgent: | Variable | Description | Example | |----------|-------------|---------| -| `AZURE_TOKEN_CREDENTIALS` | When running in **Azure**, set it to `ManagedIdentityCredential`. When running **locally**, set it to either `dev` or a developer tool credential name, such as `AzureCliCredential`. | | +| `AZURE_TOKEN_CREDENTIALS` | When running in **Azure**, set it to `ManagedIdentityCredential`. When running **locally**, set it to either `dev` or a developer tool credential name, such as `AzureCliCredential`. | `ManagedIdentityCredential` | | `FOUNDRY_RESOURCE_URL` | Your Microsoft Foundry resource URL | `https://.openai.azure.com` | No API key environment variable is needed—authentication is handled by `DefaultAzureCredential`, which automatically supports: diff --git a/docs/setup/backend-services.md b/docs/setup/backend-services.md index ca4a310b6f..7f1da36e82 100644 --- a/docs/setup/backend-services.md +++ b/docs/setup/backend-services.md @@ -134,7 +134,7 @@ const client = new CopilotClient({ const session = await client.createSession({ sessionId: `user-${userId}-${Date.now()}`, - model: "gpt-4.1", + model: "gpt-5.4", availableTools: ["custom:*"], gitHubToken: user.githubToken, }); @@ -157,7 +157,7 @@ client = CopilotClient( ) await client.start() -session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1", session_id=f"user-{user_id}-{int(time.time())}") +session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-5.4", session_id=f"user-{user_id}-{int(time.time())}") response = await session.send_and_wait(message) ``` @@ -191,7 +191,7 @@ func main() { session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-%d", userID, time.Now().Unix()), - Model: "gpt-4.1", + Model: "gpt-5.4", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: message}) @@ -209,7 +209,7 @@ defer client.Stop() session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-%d", userID, time.Now().Unix()), - Model: "gpt-4.1", + Model: "gpt-5.4", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: message}) @@ -235,7 +235,7 @@ var client = new CopilotClient(new CopilotClientOptions await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{userId}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}", - Model = "gpt-4.1", + Model = "gpt-5.4", }); var response = await session.SendAndWaitAsync( @@ -252,7 +252,7 @@ var client = new CopilotClient(new CopilotClientOptions await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{userId}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}", - Model = "gpt-4.1", + Model = "gpt-5.4", }); var response = await session.SendAndWaitAsync( @@ -280,7 +280,7 @@ try { var session = client.createSession(new SessionConfig() .setSessionId(String.format("user-%s-%d", userId, System.currentTimeMillis() / 1000)) - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -332,7 +332,7 @@ const client = new CopilotClient({ app.post("/chat", authMiddleware, async (req, res) => { const session = await client.createSession({ sessionId: `user-${req.user.id}-chat`, - model: "gpt-4.1", + model: "gpt-5.4", availableTools: ["custom:*"], gitHubToken: req.user.githubToken, }); @@ -355,7 +355,7 @@ const client = new CopilotClient({ }); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", provider: { type: "openai", baseUrl: "https://api.openai.com/v1", @@ -407,7 +407,7 @@ app.post("/api/chat", async (req, res) => { } catch { session = await client.createSession({ sessionId, - model: "gpt-4.1", + model: "gpt-5.4", availableTools: ["custom:*"], gitHubToken: req.user.githubToken, }); @@ -436,7 +436,7 @@ const client = new CopilotClient({ async function processJob(job: Job) { const session = await client.createSession({ sessionId: `job-${job.id}`, - model: "gpt-4.1", + model: "gpt-5.4", }); const response = await session.sendAndWait({ diff --git a/docs/setup/bundled-cli.md b/docs/setup/bundled-cli.md index 26eb62c3f4..7c7d2fbbc4 100644 --- a/docs/setup/bundled-cli.md +++ b/docs/setup/bundled-cli.md @@ -47,7 +47,7 @@ import { CopilotClient } from "@github/copilot-sdk"; const client = new CopilotClient(); -const session = await client.createSession({ model: "gpt-4.1" }); +const session = await client.createSession({ model: "gpt-5.4" }); const response = await session.sendAndWait({ prompt: "Hello!" }); console.log(response?.data.content); @@ -66,7 +66,7 @@ from copilot.session import PermissionHandler client = CopilotClient() await client.start() -session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1") +session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-5.4") response = await session.send_and_wait("Hello!") print(response.data.content) @@ -101,7 +101,7 @@ func main() { } defer client.Stop() - session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"}) + session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5.4"}) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) if d, ok := response.Data.(*copilot.AssistantMessageData); ok { fmt.Println(d.Content) @@ -117,7 +117,7 @@ if err := client.Start(ctx); err != nil { } defer client.Stop() -session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"}) +session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5.4"}) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) if d, ok := response.Data.(*copilot.AssistantMessageData); ok { fmt.Println(d.Content) @@ -132,7 +132,7 @@ if d, ok := response.Data.(*copilot.AssistantMessageData); ok { ```csharp await using var client = new CopilotClient(); await using var session = await client.CreateSessionAsync( - new SessionConfig { Model = "gpt-4.1" }); + new SessionConfig { Model = "gpt-5.4" }); var response = await session.SendAndWaitAsync( new MessageOptions { Prompt = "Hello!" }); @@ -158,7 +158,7 @@ var client = new CopilotClient(new CopilotClientOptions() client.start().get(); var session = client.createSession(new SessionConfig() - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); @@ -219,7 +219,7 @@ If you manage your own model provider keys, users don't need GitHub accounts at const client = new CopilotClient(); const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", provider: { type: "openai", baseUrl: "https://api.openai.com/v1", @@ -241,7 +241,7 @@ const client = new CopilotClient(); const sessionId = `project-${projectName}`; const session = await client.createSession({ sessionId, - model: "gpt-4.1", + model: "gpt-5.4", }); // User closes app... diff --git a/docs/setup/choosing-a-setup-path.md b/docs/setup/choosing-a-setup-path.md index 7fe28be8d4..17c971e657 100644 --- a/docs/setup/choosing-a-setup-path.md +++ b/docs/setup/choosing-a-setup-path.md @@ -88,7 +88,7 @@ Use this table to find the right guides based on what you need to do: | Getting started quickly | [Default Setup (Bundled CLI)](./bundled-cli.md) | | Use your own CLI binary or server | [Local CLI](./local-cli.md) | | Users sign in with GitHub | [GitHub OAuth](./github-oauth.md) | -| Use your own model keys (OpenAI, Azure, etc.) | [BYOK](../auth/byok.md) | +| Use your own model keys (OpenAI, Azure, and more) | [BYOK](../auth/byok.md) | | Azure BYOK with Managed Identity (no API keys) | [Azure Managed Identity](./azure-managed-identity.md) | | Run the SDK on a server | [Backend Services](./backend-services.md) | | Configure SDK options for concurrent users | [Multi-tenancy and server deployments](./multi-tenancy.md) | diff --git a/docs/setup/github-oauth.md b/docs/setup/github-oauth.md index 25b6aa80e3..5b44024b14 100644 --- a/docs/setup/github-oauth.md +++ b/docs/setup/github-oauth.md @@ -133,7 +133,7 @@ function createClientForUser(userToken: string): CopilotClient { const client = createClientForUser("gho_user_access_token"); const session = await client.createSession({ sessionId: `user-${userId}-session`, - model: "gpt-4.1", + model: "gpt-5.4", }); const response = await session.sendAndWait({ prompt: "Hello!" }); @@ -158,7 +158,7 @@ def create_client_for_user(user_token: str) -> CopilotClient: client = create_client_for_user("gho_user_access_token") await client.start() -session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1", session_id=f"user-{user_id}-session") +session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-5.4", session_id=f"user-{user_id}-session") response = await session.send_and_wait("Hello!") ``` @@ -195,7 +195,7 @@ func main() { session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-session", userID), - Model: "gpt-4.1", + Model: "gpt-5.4", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) _ = response @@ -218,7 +218,7 @@ defer client.Stop() session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-session", userID), - Model: "gpt-4.1", + Model: "gpt-5.4", }) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) ``` @@ -245,7 +245,7 @@ await using var client = CreateClientForUser("gho_user_access_token"); await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{userId}-session", - Model = "gpt-4.1", + Model = "gpt-5.4", }); var response = await session.SendAndWaitAsync( @@ -266,7 +266,7 @@ await using var client = CreateClientForUser("gho_user_access_token"); await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{userId}-session", - Model = "gpt-4.1", + Model = "gpt-5.4", }); var response = await session.SendAndWaitAsync( @@ -297,7 +297,7 @@ var userId = "user1"; try (var client = createClientForUser("gho_user_access_token")) { var session = client.createSession(new SessionConfig() .setSessionId(String.format("user-%s-session", userId)) - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) ).get(); diff --git a/docs/setup/local-cli.md b/docs/setup/local-cli.md index b8dd735b38..72394b3481 100644 --- a/docs/setup/local-cli.md +++ b/docs/setup/local-cli.md @@ -40,7 +40,7 @@ const client = new CopilotClient({ cliPath: "/usr/local/bin/copilot", }); -const session = await client.createSession({ model: "gpt-4.1" }); +const session = await client.createSession({ model: "gpt-5.4" }); const response = await session.sendAndWait({ prompt: "Hello!" }); console.log(response?.data.content); @@ -62,7 +62,7 @@ client = CopilotClient({ }) await client.start() -session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1") +session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-5.4") response = await session.send_and_wait("Hello!") if response: match response.data: @@ -102,7 +102,7 @@ func main() { } defer client.Stop() - session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"}) + session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5.4"}) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) if response != nil { if d, ok := response.Data.(*copilot.AssistantMessageData); ok { @@ -122,7 +122,7 @@ if err := client.Start(ctx); err != nil { } defer client.Stop() -session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"}) +session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5.4"}) response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"}) if response != nil { if d, ok := response.Data.(*copilot.AssistantMessageData); ok { @@ -143,7 +143,7 @@ var client = new CopilotClient(new CopilotClientOptions }); await using var session = await client.CreateSessionAsync( - new SessionConfig { Model = "gpt-4.1" }); + new SessionConfig { Model = "gpt-5.4" }); var response = await session.SendAndWaitAsync( new MessageOptions { Prompt = "Hello!" }); @@ -190,7 +190,7 @@ Sessions default to ephemeral. To create resumable sessions, provide your own se // Create a named session const session = await client.createSession({ sessionId: "my-project-analysis", - model: "gpt-4.1", + model: "gpt-5.4", }); // Later, resume it diff --git a/docs/setup/multi-tenancy.md b/docs/setup/multi-tenancy.md index def44746e6..2f82dde0bf 100644 --- a/docs/setup/multi-tenancy.md +++ b/docs/setup/multi-tenancy.md @@ -48,7 +48,7 @@ const client = new CopilotClient({ const session = await client.createSession({ sessionId: `user-${user.id}-${crypto.randomUUID()}`, - model: "gpt-4.1", + model: "gpt-5.4", availableTools: ["custom:lookupOrder", "custom:createTicket"], gitHubToken: user.githubToken, }); @@ -73,7 +73,7 @@ await client.start() session = await client.create_session( session_id=f"user-{user.id}-{request_id}", - model="gpt-4.1", + model="gpt-5.4", available_tools=["custom:lookupOrder", "custom:createTicket"], github_token=user.github_token, on_permission_request=PermissionHandler.approve_all, @@ -117,7 +117,7 @@ func main() { session, err := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-%s", user.ID, requestID), - Model: "gpt-4.1", + Model: "gpt-5.4", AvailableTools: []string{"custom:lookupOrder", "custom:createTicket"}, GitHubToken: user.GitHubToken, }) @@ -137,7 +137,7 @@ client := copilot.NewClient(&copilot.ClientOptions{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{ SessionID: fmt.Sprintf("user-%s-%s", user.ID, requestID), - Model: "gpt-4.1", + Model: "gpt-5.4", AvailableTools: []string{"custom:lookupOrder", "custom:createTicket"}, GitHubToken: user.GitHubToken, }) @@ -168,7 +168,7 @@ var client = new CopilotClient(new CopilotClientOptions await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{user.Id}-{requestId}", - Model = "gpt-4.1", + Model = "gpt-5.4", AvailableTools = ["custom:lookupOrder", "custom:createTicket"], GitHubToken = user.GitHubToken, }); @@ -187,7 +187,7 @@ var client = new CopilotClient(new CopilotClientOptions await using var session = await client.CreateSessionAsync(new SessionConfig { SessionId = $"user-{user.Id}-{requestId}", - Model = "gpt-4.1", + Model = "gpt-5.4", AvailableTools = ["custom:lookupOrder", "custom:createTicket"], GitHubToken = user.GitHubToken, }); @@ -223,7 +223,7 @@ public class MultiTenancyExample { var session = client.createSession(new SessionConfig() .setSessionId("user-" + user.id() + "-" + requestId) - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setAvailableTools(List.of("custom:lookupOrder", "custom:createTicket")) .setGitHubToken(user.gitHubToken()) ).get(); @@ -242,7 +242,7 @@ var client = new CopilotClient(new CopilotClientOptions() var session = client.createSession(new SessionConfig() .setSessionId("user-" + user.id() + "-" + requestId) - .setModel("gpt-4.1") + .setModel("gpt-5.4") .setAvailableTools(List.of("custom:lookupOrder", "custom:createTicket")) .setGitHubToken(user.gitHubToken()) ).get(); @@ -276,7 +276,7 @@ let client = Client::start( let session = client.create_session( SessionConfig::default() .with_session_id(format!("user-{}-{request_id}", user.id)) - .with_model("gpt-4.1") + .with_model("gpt-5.4") .with_available_tools(["custom:lookupOrder", "custom:createTicket"]) .with_github_token(user.github_token), ).await?; @@ -366,7 +366,7 @@ Set `gitHubToken` on each session to scope GitHub auth to the requesting user. T ```typescript const session = await client.createSession({ sessionId: `user-${user.id}-support`, - model: "gpt-4.1", + model: "gpt-5.4", availableTools: ["custom:*"], gitHubToken: user.githubToken, }); diff --git a/docs/setup/scaling.md b/docs/setup/scaling.md index d960eb94ea..c4a7a0953f 100644 --- a/docs/setup/scaling.md +++ b/docs/setup/scaling.md @@ -324,7 +324,7 @@ app.post("/chat", async (req, res) => { const session = await client.createSession({ sessionId: `user-${req.user.id}-chat`, - model: "gpt-4.1", + model: "gpt-5.4", }); const response = await session.sendAndWait({ prompt: req.body.message }); @@ -404,7 +404,7 @@ class SessionManager { // Create or resume const session = await client.createSession({ sessionId, - model: "gpt-4.1", + model: "gpt-5.4", }); this.activeSessions.set(sessionId, session); @@ -450,7 +450,7 @@ For stateless API endpoints where each request is independent: ```typescript app.post("/api/analyze", async (req, res) => { const session = await client.createSession({ - model: "gpt-4.1", + model: "gpt-5.4", }); try { @@ -475,7 +475,7 @@ app.post("/api/chat/start", async (req, res) => { const session = await client.createSession({ sessionId, - model: "gpt-4.1", + model: "gpt-5.4", infiniteSessions: { enabled: true, backgroundCompactionThreshold: 0.80, diff --git a/docs/troubleshooting/mcp-debugging.md b/docs/troubleshooting/mcp-debugging.md index 3447ed9210..f93f7acae2 100644 --- a/docs/troubleshooting/mcp-debugging.md +++ b/docs/troubleshooting/mcp-debugging.md @@ -446,10 +446,10 @@ When opening an issue or asking for help, collect: * [ ] SDK language and version * [ ] CLI version (`copilot --version`) -* [ ] MCP server type (Node.js, Python, .NET, Go, Rust, etc.) +* [ ] MCP server type (Node.js, Python, .NET, Go, Rust, and more) * [ ] Full MCP server configuration (redact secrets) * [ ] Result of manual `initialize` test -* [ ] Result of manual `tools/list` test +* [ ] Result of manual `tools/list` test * [ ] Debug logs from SDK * [ ] Any error messages diff --git a/dotnet/src/Canvas.cs b/dotnet/src/Canvas.cs index b4e63f1b31..6bf8be984e 100644 --- a/dotnet/src/Canvas.cs +++ b/dotnet/src/Canvas.cs @@ -57,6 +57,32 @@ public sealed class ExtensionInfo public string Name { get; set; } = string.Empty; } +/// +/// Stable identity for a host/SDK connection that supplies built-in canvases. +/// +/// +/// When set on session create or resume, the runtime uses +/// verbatim as the agent-facing canvas extension id, so canvases declared on a +/// control connection survive stdio reconnect and CLI process restart instead +/// of being re-keyed to a per-connection id. The id is opaque to the runtime; a +/// per-window-stable value such as app:builtin:<windowId> is +/// recommended. An id beginning with connection: is reserved and ignored +/// by the runtime. +/// +[Experimental(Diagnostics.Experimental)] +public sealed class CanvasProviderIdentity +{ + /// + /// Opaque, stable provider id used verbatim as the canvas extension id. + /// + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Optional display name surfaced as the canvas extension name. + [JsonPropertyName("name")] + public string? Name { get; set; } +} + /// Structured exception returned from canvas handlers. /// /// Throw this from implementations to surface a diff --git a/dotnet/src/Client.cs b/dotnet/src/Client.cs index a67eb96817..a512978225 100644 --- a/dotnet/src/Client.cs +++ b/dotnet/src/Client.cs @@ -8,12 +8,14 @@ using Microsoft.Extensions.Logging.Abstractions; using System.Collections.Concurrent; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net.Sockets; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Text.RegularExpressions; @@ -78,6 +80,7 @@ public sealed partial class CopilotClient : IDisposable, IAsyncDisposable private readonly List _lifecycleHandlers = []; private Task? _connectionTask; + private FfiRuntimeHost? _ffiHost; private bool _disposed; private int? _actualPort; private int? _negotiatedProtocolVersion; @@ -134,13 +137,16 @@ private sealed record LifecycleSubscription(Type EventType, Action + /// Validates environment-variable options against the resolved transport. + /// Per-client environment is only representable for child-process transports + /// (each client owns its own OS process). The in-process (FFI) transport + /// loads the native runtime into the shared host process, whose single + /// environment block cannot carry per-client values, so environment and + /// telemetry options that lower to environment variables are rejected there. + /// + private static void ValidateEnvironmentOptions(CopilotClientOptions options, RuntimeConnection connection) + { + if (connection is InProcessRuntimeConnection) + { + if (options.Environment is not null) + { + throw new ArgumentException( + $"{nameof(CopilotClientOptions)}.{nameof(CopilotClientOptions.Environment)} is not supported with " + + $"{nameof(RuntimeConnection)}.{nameof(RuntimeConnection.ForInProcess)}(): the in-process transport " + + "loads the native runtime into the shared host process, whose single environment block cannot carry " + + "per-client values. Set the variables on the host process environment instead.", + nameof(options)); + } + + if (options.Telemetry is not null) + { + throw new ArgumentException( + $"{nameof(CopilotClientOptions)}.{nameof(CopilotClientOptions.Telemetry)} is not supported with " + + $"{nameof(RuntimeConnection)}.{nameof(RuntimeConnection.ForInProcess)}(): telemetry configuration is " + + "lowered to environment variables read by native runtime code running in the shared host process, so " + + "per-client telemetry cannot be honored in-process. Configure telemetry via the host process " + + "environment, or use a child-process transport.", + nameof(options)); + } + + if (options.WorkingDirectory is not null) + { + throw new ArgumentException( + $"{nameof(CopilotClientOptions)}.{nameof(CopilotClientOptions.WorkingDirectory)} is not supported with " + + $"{nameof(RuntimeConnection)}.{nameof(RuntimeConnection.ForInProcess)}(): the in-process transport hosts " + + "the native runtime in the shared host process and spawns the worker without a working-directory " + + "parameter, so a per-client working directory cannot be honored in-process. Use a child-process " + + "transport, or set the process working directory before creating the client.", + nameof(options)); + } + + return; + } + + if (connection is ChildProcessRuntimeConnection { Environment: not null } && options.Environment is not null) + { + throw new ArgumentException( + $"Set environment variables via either {nameof(CopilotClientOptions)}.{nameof(CopilotClientOptions.Environment)} " + + $"or {nameof(ChildProcessRuntimeConnection)}.{nameof(ChildProcessRuntimeConnection.Environment)}, not both. " + + $"Prefer {nameof(ChildProcessRuntimeConnection)}.{nameof(ChildProcessRuntimeConnection.Environment)} for " + + "child-process transports.", + nameof(options)); + } + } + + /// + /// Environment variable that overrides the transport used when the caller does not + /// specify . Accepts "inprocess" + /// or "stdio" (case-insensitive); unset preserves the default stdio transport. + /// Any other value is an error. Ignored when a is set + /// explicitly. + /// + internal const string DefaultConnectionEnvVar = "COPILOT_SDK_DEFAULT_CONNECTION"; + + /// + /// Resolves the default for the no-Connection case, + /// honoring . + /// + private static RuntimeConnection ResolveDefaultConnection(CopilotClientOptions options) + { + var value = options.Environment is not null + && options.Environment.TryGetValue(DefaultConnectionEnvVar, out var fromOptions) + ? fromOptions + : Environment.GetEnvironmentVariable(DefaultConnectionEnvVar); + + if (string.IsNullOrEmpty(value) || string.Equals(value, "stdio", StringComparison.OrdinalIgnoreCase)) + { + return RuntimeConnection.ForStdio(); + } + if (string.Equals(value, "inprocess", StringComparison.OrdinalIgnoreCase)) + { + return RuntimeConnection.ForInProcess(); + } + throw new ArgumentException( + $"Invalid {DefaultConnectionEnvVar} value '{value}'. Expected 'inprocess', 'stdio', or unset."); + } + /// /// Parses a runtime URL into a URI with host and port. /// @@ -250,7 +348,56 @@ async Task StartCoreAsync(CancellationToken ct) try { - if (_connection is UriRuntimeConnection) + if (_connection is InProcessRuntimeConnection) + { + var ffiEnvironment = new Dictionary(); + if (!string.IsNullOrEmpty(_options.GitHubToken)) + { + ffiEnvironment["COPILOT_SDK_AUTH_TOKEN"] = _options.GitHubToken!; + } + if (!string.IsNullOrEmpty(_options.BaseDirectory)) + { + ffiEnvironment["COPILOT_HOME"] = _options.BaseDirectory!; + } + if (_options.Mode == CopilotClientMode.Empty) + { + ffiEnvironment["COPILOT_DISABLE_KEYTAR"] = "1"; + } + + var ffiArgs = new List(); + if (_options.LogLevel is { } logLevel && !string.IsNullOrEmpty(logLevel.Value)) + { + ffiArgs.AddRange(["--log-level", logLevel.Value]); + } + if (!string.IsNullOrEmpty(_options.GitHubToken)) + { + ffiArgs.AddRange(["--auth-token-env", "COPILOT_SDK_AUTH_TOKEN"]); + } + var useLoggedInUser = _options.UseLoggedInUser ?? string.IsNullOrEmpty(_options.GitHubToken); + if (!useLoggedInUser) + { + ffiArgs.Add("--no-auto-login"); + } + if (_options.SessionIdleTimeoutSeconds is > 0) + { + ffiArgs.AddRange(["--session-idle-timeout", _options.SessionIdleTimeoutSeconds.Value.ToString(CultureInfo.InvariantCulture)]); + } + if (_options.EnableRemoteSessions) + { + ffiArgs.Add("--remote"); + } + + var ffiHost = FfiRuntimeHost.Create( + ResolveCliPathForFfi(), + GetNapiPrebuildsFolderOrThrow(), + ffiEnvironment, + ffiArgs, + _logger); + _ffiHost = ffiHost; + await ffiHost.StartAsync(ct); + connection = await ConnectToServerAsync(null, null, null, null, ct, ffiHost); + } + else if (_connection is UriRuntimeConnection) { // External runtime _actualPort = _optionsPort; @@ -437,7 +584,7 @@ private async Task CleanupConnectionAsync(List? errors, bool graceful private async Task CleanupConnectionAsync(Connection ctx, List? errors, bool gracefulRuntimeShutdown) { - if (gracefulRuntimeShutdown && ctx.CliProcess is not null) + if (gracefulRuntimeShutdown && (ctx.CliProcess is not null || ctx.FfiHost is not null)) { var runtimeShutdownTimestamp = Stopwatch.GetTimestamp(); try @@ -477,6 +624,13 @@ or IOException { await CleanupCliProcessAsync(childProcess, ctx.StderrPump, errors, _logger); } + + if (ctx.FfiHost is { } ffiHost) + { + try { ffiHost.Dispose(); } + catch (Exception ex) { AddCleanupError(errors, ex, _logger); } + _ffiHost = null; + } } private static async Task CleanupCliProcessAsync(Process childProcess, ProcessStderrPump? stderrPump, List? errors, ILogger? logger) @@ -630,6 +784,7 @@ private CopilotSession InitializeSession( this); session.RegisterTools(config.Tools ?? []); session.RegisterPermissionHandler(config.OnPermissionRequest); + session.RegisterMcpAuthHandler(config.OnMcpAuthRequest); session.RegisterCommands(config.Commands); session.RegisterElicitationHandler(config.OnElicitationRequest); session.RegisterExitPlanModeHandler(config.OnExitPlanModeRequest); @@ -979,9 +1134,11 @@ public async Task CreateSessionAsync(SessionConfig config, Cance config.ReasoningSummary, config.ContextTier, config.Tools?.Select(ToolDefinition.FromAIFunction).ToList(), + config.EnableCitations, wireSystemMessage, toolFilter.AvailableTools, toolFilter.ExcludedTools, + config.ExcludedBuiltInAgents, config.Provider, config.Capi, config.EnableSessionTelemetry, @@ -1012,6 +1169,7 @@ public async Task CreateSessionAsync(SessionConfig config, Cance config.SkillDirectories, config.DisabledSkills, config.InfiniteSessions, + config.SessionLimits, Commands: config.Commands?.Select(c => new CommandWireDefinition(c.Name, c.Description)).ToList(), RequestElicitation: config.OnElicitationRequest != null, RequestMcpApps: config.EnableMcpApps ? true : null, @@ -1024,16 +1182,20 @@ public async Task CreateSessionAsync(SessionConfig config, Cance InstructionDirectories: config.InstructionDirectories, PluginDirectories: config.PluginDirectories, LargeOutput: config.LargeOutput, + ToolSearch: config.ToolSearch, Memory: config.Memory, Canvases: config.Canvases, RequestCanvasRenderer: config.RequestCanvasRenderer, RequestExtensions: config.RequestExtensions, ExtensionSdkPath: config.ExtensionSdkPath, ExtensionInfo: config.ExtensionInfo, + CanvasProvider: config.CanvasProvider, Providers: config.Providers, Models: config.Models, ToolFilterPrecedence: toolFilter.ToolFilterPrecedence, - ExpAssignments: config.ExpAssignments); + ExpAssignments: config.ExpAssignments, + EnableManagedSettings: config.EnableManagedSettings, + EnableGitHubTelemetryForwarding: _options.OnGitHubTelemetry != null ? true : null); var rpcTimestamp = Stopwatch.GetTimestamp(); @@ -1080,6 +1242,11 @@ public async Task CreateSessionAsync(SessionConfig config, Cance $"session.create returned sessionId {response.SessionId} but the caller requested {localSessionId}."); } + if (config.OnMcpAuthRequest is not null) + { + await session.Rpc.EventLog.RegisterInterestAsync("mcp.oauth_required", cancellationToken); + } + session.WorkspacePath = response.WorkspacePath; session.SetCapabilities(response.Capabilities); session.SetOpenCanvases(response.OpenCanvases); @@ -1166,7 +1333,6 @@ public async Task ResumeSessionAsync(string sessionId, ResumeSes transformCallbacks, hasHooks, "CopilotClient.ResumeSessionAsync"); - try { var (traceparent, tracestate) = TelemetryHelpers.GetTraceContext(); @@ -1179,9 +1345,11 @@ public async Task ResumeSessionAsync(string sessionId, ResumeSes config.ReasoningSummary, config.ContextTier, config.Tools?.Select(ToolDefinition.FromAIFunction).ToList(), + config.EnableCitations, wireSystemMessage, toolFilter.AvailableTools, toolFilter.ExcludedTools, + config.ExcludedBuiltInAgents, config.Provider, config.Capi, config.EnableSessionTelemetry, @@ -1213,6 +1381,7 @@ public async Task ResumeSessionAsync(string sessionId, ResumeSes config.SkillDirectories, config.DisabledSkills, config.InfiniteSessions, + config.SessionLimits, Commands: config.Commands?.Select(c => new CommandWireDefinition(c.Name, c.Description)).ToList(), RequestElicitation: config.OnElicitationRequest != null, RequestMcpApps: config.EnableMcpApps ? true : null, @@ -1225,17 +1394,21 @@ public async Task ResumeSessionAsync(string sessionId, ResumeSes InstructionDirectories: config.InstructionDirectories, PluginDirectories: config.PluginDirectories, LargeOutput: config.LargeOutput, + ToolSearch: config.ToolSearch, Memory: config.Memory, Canvases: config.Canvases, RequestCanvasRenderer: config.RequestCanvasRenderer, RequestExtensions: config.RequestExtensions, ExtensionSdkPath: config.ExtensionSdkPath, ExtensionInfo: config.ExtensionInfo, + CanvasProvider: config.CanvasProvider, OpenCanvases: config.OpenCanvases, Providers: config.Providers, Models: config.Models, ToolFilterPrecedence: toolFilter.ToolFilterPrecedence, - ExpAssignments: config.ExpAssignments); + ExpAssignments: config.ExpAssignments, + EnableManagedSettings: config.EnableManagedSettings, + EnableGitHubTelemetryForwarding: _options.OnGitHubTelemetry != null ? true : null); var rpcTimestamp = Stopwatch.GetTimestamp(); var response = await InvokeRpcAsync( @@ -1249,6 +1422,11 @@ public async Task ResumeSessionAsync(string sessionId, ResumeSes session.SetCapabilities(response.Capabilities); session.SetOpenCanvases(response.OpenCanvases); + if (config.OnMcpAuthRequest is not null) + { + await session.Rpc.EventLog.RegisterInterestAsync("mcp.oauth_required", cancellationToken); + } + await UpdateSessionOptionsForModeAsync(session, config, cancellationToken).ConfigureAwait(false); } catch (Exception ex) @@ -1708,21 +1886,24 @@ await Rpc.SessionFs.SetProviderAsync( } /// - /// Builds the client-global RPC handler bag at construction time. Currently - /// only the LLM inference provider adapter is registered; returns null when no + /// Builds the client-global RPC handler bag at construction time. Registers + /// the LLM inference provider adapter and/or the GitHub telemetry adapter + /// depending on which options are configured; returns null when no /// client-global API is configured so the registration is skipped entirely. /// private ClientGlobalApiHandlers? BuildClientGlobalApis() { var handler = _options.RequestHandler; - if (handler is null) + var onGitHubTelemetry = _options.OnGitHubTelemetry; + if (handler is null && onGitHubTelemetry is null) { return null; } return new ClientGlobalApiHandlers { - LlmInference = new LlmInferenceAdapter(handler, () => _serverRpc), + LlmInference = handler is null ? null : new LlmInferenceAdapter(handler, () => _serverRpc), + GitHubTelemetry = onGitHubTelemetry is null ? null : new GitHubTelemetryAdapter(onGitHubTelemetry, _logger), }; } @@ -1773,14 +1954,26 @@ private async Task VerifyProtocolVersionAsync(Connection connection, Cancellatio int? serverVersion; try { - var token = _connection switch - { - TcpRuntimeConnection tcp => tcp.ConnectionToken, - UriRuntimeConnection uri => uri.ConnectionToken, - _ => null, - }; + var token = _ffiHost is not null + ? null // FFI hosting is an ungated in-process connection; no token. + : _connection switch + { + TcpRuntimeConnection tcp => tcp.ConnectionToken, + UriRuntimeConnection uri => uri.ConnectionToken, + _ => null, + }; var connectResponse = await InvokeRpcAsync( - connection.Rpc, "connect", [new ConnectRequest { Token = token }], connection.StderrBuffer, cancellationToken); + connection.Rpc, + "connect", + [new ConnectHandshakeRequest( + token, + // Opt in to GitHub telemetry forwarding at the connection level when a + // handler is registered (mirrors the runtime, which reads this flag on the + // `connect` handshake so the first session's un-replayable `session.start` + // event is forwarded). Also sent on session.create/resume for older CLIs. + _options.OnGitHubTelemetry != null ? true : null)], + connection.StderrBuffer, + cancellationToken); serverVersion = (int)connectResponse.ProtocolVersion; } catch (IOException ex) when (ex.InnerException is RemoteRpcException remoteEx && IsUnsupportedConnectMethod(remoteEx)) @@ -1823,6 +2016,25 @@ private static bool IsUnsupportedConnectMethod(RemoteRpcException ex) || string.Equals(ex.Message, "Unhandled method connect", StringComparison.Ordinal); } + // Applies the telemetry-derived environment variables the runtime reads to + // enable OTLP export. Shared by the stdio/tcp child-process path and the + // in-process FFI path so telemetry behaves identically across transports. + private static void ApplyTelemetryEnvironment(IDictionary environment, TelemetryConfig? telemetry) + { + if (telemetry is null) + { + return; + } + + environment["COPILOT_OTEL_ENABLED"] = "true"; + if (telemetry.OtlpEndpoint is not null) environment["OTEL_EXPORTER_OTLP_ENDPOINT"] = telemetry.OtlpEndpoint; + if (telemetry.OtlpProtocol is not null) environment["OTEL_EXPORTER_OTLP_PROTOCOL"] = telemetry.OtlpProtocol; + if (telemetry.FilePath is not null) environment["COPILOT_OTEL_FILE_EXPORTER_PATH"] = telemetry.FilePath; + if (telemetry.ExporterType is not null) environment["COPILOT_OTEL_EXPORTER_TYPE"] = telemetry.ExporterType; + if (telemetry.SourceName is not null) environment["COPILOT_OTEL_SOURCE_NAME"] = telemetry.SourceName; + if (telemetry.CaptureContent is { } capture) environment["OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"] = capture ? "true" : "false"; + } + private async Task<(Process Process, int? DetectedLocalhostTcpPort, ProcessStderrPump StderrPump)> StartCliServerAsync(CancellationToken cancellationToken) { var options = _options; @@ -1831,9 +2043,12 @@ private static bool IsUnsupportedConnectMethod(RemoteRpcException ex) var tcpConnection = _connection as TcpRuntimeConnection; var useStdio = _connection is StdioRuntimeConnection; - // Use explicit path, COPILOT_CLI_PATH env var (from options.Environment or process env), or bundled runtime - no PATH fallback - var envCliPath = options.Environment is not null && options.Environment.TryGetValue("COPILOT_CLI_PATH", out var envValue) ? envValue - : System.Environment.GetEnvironmentVariable("COPILOT_CLI_PATH"); + // Use explicit path, COPILOT_CLI_PATH env var (from the connection's + // Environment, options.Environment, or process env), or bundled runtime - no PATH fallback + var envCliPath = + (childProcessConnection.Environment is not null && childProcessConnection.Environment.TryGetValue("COPILOT_CLI_PATH", out var connEnvValue) ? connEnvValue : null) + ?? (options.Environment is not null && options.Environment.TryGetValue("COPILOT_CLI_PATH", out var envValue) ? envValue : null) + ?? System.Environment.GetEnvironmentVariable("COPILOT_CLI_PATH"); var cliPath = childProcessConnection.Path ?? envCliPath ?? GetBundledCliPath(out var searchedPath) @@ -1900,10 +2115,11 @@ private static bool IsUnsupportedConnectMethod(RemoteRpcException ex) CreateNoWindow = true }; - if (options.Environment != null) + var childEnvironment = options.Environment ?? childProcessConnection.Environment; + if (childEnvironment != null) { startInfo.Environment.Clear(); - foreach (var (key, value) in options.Environment) + foreach (var (key, value) in childEnvironment) { startInfo.Environment[key] = value; } @@ -1937,16 +2153,7 @@ private static bool IsUnsupportedConnectMethod(RemoteRpcException ex) } // Set telemetry environment variables if configured - if (options.Telemetry is { } telemetry) - { - startInfo.Environment["COPILOT_OTEL_ENABLED"] = "true"; - if (telemetry.OtlpEndpoint is not null) startInfo.Environment["OTEL_EXPORTER_OTLP_ENDPOINT"] = telemetry.OtlpEndpoint; - if (telemetry.OtlpProtocol is not null) startInfo.Environment["OTEL_EXPORTER_OTLP_PROTOCOL"] = telemetry.OtlpProtocol; - if (telemetry.FilePath is not null) startInfo.Environment["COPILOT_OTEL_FILE_EXPORTER_PATH"] = telemetry.FilePath; - if (telemetry.ExporterType is not null) startInfo.Environment["COPILOT_OTEL_EXPORTER_TYPE"] = telemetry.ExporterType; - if (telemetry.SourceName is not null) startInfo.Environment["COPILOT_OTEL_SOURCE_NAME"] = telemetry.SourceName; - if (telemetry.CaptureContent is { } capture) startInfo.Environment["OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"] = capture ? "true" : "false"; - } + ApplyTelemetryEnvironment(startInfo.Environment, options.Telemetry); var cliProcess = new Process { StartInfo = startInfo }; try @@ -2041,7 +2248,12 @@ private static bool IsUnsupportedConnectMethod(RemoteRpcException ex) { string os; if (OperatingSystem.IsWindows()) os = "win"; - else if (OperatingSystem.IsLinux()) os = "linux"; + else if (OperatingSystem.IsLinux()) + { + os = RuntimeInformation.RuntimeIdentifier.StartsWith("linux-musl-", StringComparison.Ordinal) + ? "linux-musl" + : "linux"; + } else if (OperatingSystem.IsMacOS()) os = "osx"; else return null; @@ -2055,6 +2267,62 @@ private static bool IsUnsupportedConnectMethod(RemoteRpcException ex) return arch != null ? $"{os}-{arch}" : null; } + private string ResolveCliPathForFfi() + { + var envCliPath = _options.Environment is not null && _options.Environment.TryGetValue("COPILOT_CLI_PATH", out var envValue) + ? envValue + : System.Environment.GetEnvironmentVariable("COPILOT_CLI_PATH"); + if (!string.IsNullOrEmpty(envCliPath)) + { + return envCliPath; + } + + // Fall back to the bundled single-file CLI the same way stdio discovers it. + // It embeds its own Node and is spawned directly as `copilot --embedded-host`, + // with the sibling cdylib loaded in-process (FfiRuntimeHost.Create prefers the + // flat `libcopilot_runtime.so`/`copilot_runtime.dll` next to the CLI, falling + // back to the dev `prebuilds//runtime.node` layout). + var bundled = GetBundledCliPath(out var searchedPath); + return bundled + ?? throw new InvalidOperationException( + "In-process FFI hosting requires the Copilot CLI. Set the COPILOT_CLI_PATH " + + $"environment variable, or ensure the bundled CLI is present (looked in '{searchedPath}')."); + } + + /// + /// Returns the napi-rs prebuilds folder name for the current host — the + /// <node-platform>-<arch> convention (e.g. win32-x64, + /// darwin-arm64, linux-x64) under which the runtime ships + /// prebuilds/<folder>/runtime.node. This differs from the .NET RID + /// (win-x64/osx-x64) for Windows and macOS. + /// + private static string? GetNapiPrebuildsFolder() + { + string platform; + if (OperatingSystem.IsWindows()) platform = "win32"; + else if (OperatingSystem.IsLinux()) + { + platform = RuntimeInformation.RuntimeIdentifier.StartsWith("linux-musl-", StringComparison.Ordinal) + ? "linuxmusl" + : "linux"; + } + else if (OperatingSystem.IsMacOS()) platform = "darwin"; + else return null; + + var arch = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch + { + System.Runtime.InteropServices.Architecture.X64 => "x64", + System.Runtime.InteropServices.Architecture.Arm64 => "arm64", + _ => null, + }; + + return arch != null ? $"{platform}-{arch}" : null; + } + + private static string GetNapiPrebuildsFolderOrThrow() => + GetNapiPrebuildsFolder() + ?? throw new InvalidOperationException("Could not determine a napi-rs prebuilds folder for FFI hosting."); + private static (string FileName, IEnumerable Args) ResolveCliCommand(string cliPath, IEnumerable args) { var isJsFile = cliPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase); @@ -2067,7 +2335,7 @@ private static (string FileName, IEnumerable Args) ResolveCliCommand(str return (cliPath, args); } - private async Task ConnectToServerAsync(Process? cliProcess, string? tcpHost, int? tcpPort, ProcessStderrPump? stderrPump, CancellationToken cancellationToken) + private async Task ConnectToServerAsync(Process? cliProcess, string? tcpHost, int? tcpPort, ProcessStderrPump? stderrPump, CancellationToken cancellationToken, FfiRuntimeHost? ffiHost = null) { var setupTimestamp = Stopwatch.GetTimestamp(); NetworkStream? networkStream = null; @@ -2077,7 +2345,12 @@ private async Task ConnectToServerAsync(Process? cliProcess, string? { Stream inputStream, outputStream; - if (_connection is StdioRuntimeConnection) + if (ffiHost is not null) + { + inputStream = ffiHost.ReceiveStream; + outputStream = ffiHost.SendStream; + } + else if (_connection is StdioRuntimeConnection) { if (cliProcess == null) { @@ -2143,7 +2416,7 @@ private async Task ConnectToServerAsync(Process? cliProcess, string? "CopilotClient.ConnectToServerAsync transport setup complete. Elapsed={Elapsed}", setupTimestamp); - var connection = new Connection(rpc, cliProcess, networkStream, stderrPump); + var connection = new Connection(rpc, cliProcess, networkStream, stderrPump, ffiHost); _serverRpc = connection.Server; return connection; @@ -2232,13 +2505,15 @@ public void Dispose() /// /// A representing the asynchronous dispose operation. /// - /// This method calls to immediately release all resources. + /// This method calls to gracefully shut down the runtime and + /// release all resources. Use for an immediate hard stop + /// that skips graceful runtime shutdown. /// public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; - await ForceStopAsync(); + await StopAsync(); } private class RpcHandler(CopilotClient client) @@ -2346,7 +2621,8 @@ private class Connection( JsonRpc rpc, Process? cliProcess, // Set if we created the child process NetworkStream? networkStream, // Set if using TCP - ProcessStderrPump? stderrPump = null) // Captures stderr for error messages + ProcessStderrPump? stderrPump = null, // Captures stderr for error messages + FfiRuntimeHost? ffiHost = null) // Set if using in-process FFI hosting { public Process? CliProcess => cliProcess; public JsonRpc Rpc => rpc; @@ -2354,6 +2630,7 @@ private class Connection( public NetworkStream? NetworkStream => networkStream; public ProcessStderrPump? StderrPump => stderrPump; public StringBuilder? StderrBuffer => stderrPump?.Buffer; + public FfiRuntimeHost? FfiHost => ffiHost; } private sealed class ProcessStderrPump @@ -2421,9 +2698,11 @@ internal record CreateSessionRequest( ReasoningSummary? ReasoningSummary, ContextTier? ContextTier, IList? Tools, + bool? EnableCitations, SystemMessageConfig? SystemMessage, IList? AvailableTools, IList? ExcludedTools, + [property: JsonPropertyName("excludedBuiltinAgents")] IList? ExcludedBuiltInAgents, ProviderConfig? Provider, CapiSessionOptions? Capi, bool? EnableSessionTelemetry, @@ -2454,6 +2733,7 @@ internal record CreateSessionRequest( IList? SkillDirectories, IList? DisabledSkills, InfiniteSessionConfig? InfiniteSessions, + SessionLimitsConfig? SessionLimits, IList? Commands = null, bool? RequestElicitation = null, bool? RequestMcpApps = null, @@ -2466,6 +2746,7 @@ internal record CreateSessionRequest( IList? InstructionDirectories = null, IList? PluginDirectories = null, LargeToolOutputConfig? LargeOutput = null, + ToolSearchConfig? ToolSearch = null, MemoryConfiguration? Memory = null, #pragma warning disable GHCP001 IList? Canvases = null, @@ -2473,10 +2754,13 @@ internal record CreateSessionRequest( bool? RequestExtensions = null, string? ExtensionSdkPath = null, ExtensionInfo? ExtensionInfo = null, + CanvasProviderIdentity? CanvasProvider = null, IList? Providers = null, IList? Models = null, OptionsUpdateToolFilterPrecedence? ToolFilterPrecedence = null, - [property: JsonPropertyName("expAssignments")] JsonElement? ExpAssignments = null); + [property: JsonPropertyName("expAssignments")] JsonElement? ExpAssignments = null, + [property: JsonPropertyName("enableManagedSettings")] bool? EnableManagedSettings = null, + bool? EnableGitHubTelemetryForwarding = null); #pragma warning restore GHCP001 internal record ToolDefinition( @@ -2485,17 +2769,20 @@ internal record ToolDefinition( JsonElement Parameters, /* JSON schema */ bool? OverridesBuiltInTool = null, bool? SkipPermission = null, - CopilotToolDefer? Defer = null) + CopilotToolDefer? Defer = null, + IDictionary? Metadata = null) { public static ToolDefinition FromAIFunction(AIFunctionDeclaration function) { var overrides = function.AdditionalProperties.TryGetValue(CopilotTool.OverridesBuiltInToolKey, out var val) && val is true; var skipPerm = function.AdditionalProperties.TryGetValue(CopilotTool.SkipPermissionKey, out var skipVal) && skipVal is true; var defer = function.AdditionalProperties.TryGetValue(CopilotTool.DeferKey, out var deferVal) && deferVal is CopilotToolDefer d ? d : (CopilotToolDefer?)null; + var metadata = function.AdditionalProperties.TryGetValue(CopilotTool.MetadataKey, out var metaVal) && metaVal is IDictionary m ? m : null; return new ToolDefinition(function.Name, function.Description, function.JsonSchema, overrides ? true : null, skipPerm ? true : null, - defer); + defer, + metadata); } } @@ -2515,9 +2802,11 @@ internal record ResumeSessionRequest( ReasoningSummary? ReasoningSummary, ContextTier? ContextTier, IList? Tools, + bool? EnableCitations, SystemMessageConfig? SystemMessage, IList? AvailableTools, IList? ExcludedTools, + [property: JsonPropertyName("excludedBuiltinAgents")] IList? ExcludedBuiltInAgents, ProviderConfig? Provider, CapiSessionOptions? Capi, bool? EnableSessionTelemetry, @@ -2549,6 +2838,7 @@ internal record ResumeSessionRequest( IList? SkillDirectories, IList? DisabledSkills, InfiniteSessionConfig? InfiniteSessions, + SessionLimitsConfig? SessionLimits, IList? Commands = null, bool? RequestElicitation = null, bool? RequestMcpApps = null, @@ -2561,6 +2851,7 @@ internal record ResumeSessionRequest( IList? InstructionDirectories = null, IList? PluginDirectories = null, LargeToolOutputConfig? LargeOutput = null, + ToolSearchConfig? ToolSearch = null, MemoryConfiguration? Memory = null, #pragma warning disable GHCP001 IList? Canvases = null, @@ -2568,11 +2859,14 @@ internal record ResumeSessionRequest( bool? RequestExtensions = null, string? ExtensionSdkPath = null, ExtensionInfo? ExtensionInfo = null, + CanvasProviderIdentity? CanvasProvider = null, IList? OpenCanvases = null, IList? Providers = null, IList? Models = null, OptionsUpdateToolFilterPrecedence? ToolFilterPrecedence = null, - [property: JsonPropertyName("expAssignments")] JsonElement? ExpAssignments = null); + [property: JsonPropertyName("expAssignments")] JsonElement? ExpAssignments = null, + [property: JsonPropertyName("enableManagedSettings")] bool? EnableManagedSettings = null, + bool? EnableGitHubTelemetryForwarding = null); #pragma warning restore GHCP001 internal record ResumeSessionResponse( @@ -2609,6 +2903,10 @@ internal record GetSessionMetadataRequest( internal record GetSessionMetadataResponse( SessionMetadata? Session); + internal record ConnectHandshakeRequest( + string? Token, + [property: JsonPropertyName("enableGitHubTelemetryForwarding")] bool? EnableGitHubTelemetryForwarding = null); + internal record SetForegroundSessionRequest( string SessionId); @@ -2643,6 +2941,7 @@ internal record HooksInvokeResponse( [JsonSerializable(typeof(ListSessionsResponse))] [JsonSerializable(typeof(GetSessionMetadataRequest))] [JsonSerializable(typeof(GetSessionMetadataResponse))] + [JsonSerializable(typeof(ConnectHandshakeRequest))] [JsonSerializable(typeof(McpOAuthTokenStorageMode))] [JsonSerializable(typeof(EmbeddingCacheStorageMode))] [JsonSerializable(typeof(ModelCapabilitiesOverride))] @@ -2650,6 +2949,7 @@ internal record HooksInvokeResponse( [JsonSerializable(typeof(CapiSessionOptions))] [JsonSerializable(typeof(NamedProviderConfig))] [JsonSerializable(typeof(ProviderModelConfig))] + [JsonSerializable(typeof(SessionLimitsConfig))] [JsonSerializable(typeof(ResumeSessionRequest))] [JsonSerializable(typeof(ResumeSessionResponse))] [JsonSerializable(typeof(SessionCapabilities))] @@ -2690,3 +2990,28 @@ public sealed class ToolResultAIContent(ToolResultObject toolResult) : AIContent /// public ToolResultObject Result => toolResult; } + +/// +/// Bridges the generated client-global handler to +/// the public OnGitHubTelemetry callback, forwarding the generated +/// payload unchanged. +/// +[Experimental(Diagnostics.Experimental)] +internal sealed class GitHubTelemetryAdapter(Func callback, ILogger logger) : Rpc.IGitHubTelemetryHandler +{ + private readonly Func _callback = callback ?? throw new ArgumentNullException(nameof(callback)); + private readonly ILogger _logger = logger ?? NullLogger.Instance; + + public async Task EventAsync(Rpc.GitHubTelemetryNotification request, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + try + { + await _callback(request).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Error handling gitHubTelemetry.event notification"); + } + } +} diff --git a/dotnet/src/CopilotRequestHandler.cs b/dotnet/src/CopilotRequestHandler.cs index f26fc70e0a..514d77da6f 100644 --- a/dotnet/src/CopilotRequestHandler.cs +++ b/dotnet/src/CopilotRequestHandler.cs @@ -49,6 +49,9 @@ public CopilotRequestContext(CopilotRequestContext original) : this(original.RequestId, original.Url, original.Headers) { SessionId = original.SessionId; + AgentId = original.AgentId; + ParentAgentId = original.ParentAgentId; + InteractionType = original.InteractionType; Transport = original.Transport; CancellationToken = original.CancellationToken; WebSocketResponse = original.WebSocketResponse; @@ -67,6 +70,15 @@ internal CopilotRequestContext(string requestId, string url, IReadOnlyDictionary /// Runtime session id that triggered the request, if any. public string? SessionId { get; init; } + /// Stable per-agent-instance id for the agent trajectory that issued this request. + public string? AgentId { get; init; } + + /// Id of the parent agent when this request was issued by a subagent. + public string? ParentAgentId { get; init; } + + /// Runtime classification for the interaction that produced this request. + public string? InteractionType { get; init; } + /// Transport the runtime would otherwise use. public CopilotRequestTransport Transport { get; init; } @@ -526,6 +538,12 @@ private static async Task BuildHttpRequestAsync(LlmInference if (!message.Headers.TryAddWithoutValidation(name, values)) { +#if NETSTANDARD2_0 + if (!hasBody) + { + continue; + } +#endif message.Content ??= new ByteArrayContent([]); message.Content.Headers.TryAddWithoutValidation(name, values); } @@ -870,6 +888,9 @@ public Task HttpRequestStartAsync(LlmInferen exchange.Context = new CopilotRequestContext(request.RequestId, request.Url, ToReadOnlyHeaders(request.Headers)) { SessionId = request.SessionId, + AgentId = request.AgentId, + ParentAgentId = request.ParentAgentId, + InteractionType = request.InteractionType, Transport = transport, CancellationToken = exchange.Abort.Token, }; diff --git a/dotnet/src/CopilotTool.cs b/dotnet/src/CopilotTool.cs index d6dc0351e4..e22296bccd 100644 --- a/dotnet/src/CopilotTool.cs +++ b/dotnet/src/CopilotTool.cs @@ -3,6 +3,7 @@ *--------------------------------------------------------------------------------------------*/ using Microsoft.Extensions.AI; +using System.Text.Json.Nodes; namespace GitHub.Copilot; @@ -20,6 +21,9 @@ public static class CopilotTool /// The key used in to carry the tool's deferral mode. internal const string DeferKey = "defer"; + /// The key used in to carry the tool's opaque host-defined metadata. + internal const string MetadataKey = "metadata"; + /// /// Defines a tool for use in a . /// @@ -87,7 +91,7 @@ static void ApplyToolInvocationBinding(AIFunctionFactoryOptions factoryOptions) static void ApplyToolOptions(AIFunctionFactoryOptions factoryOptions, CopilotToolOptions? toolOptions) { - if (toolOptions is not null && (toolOptions.OverridesBuiltInTool || toolOptions.SkipPermission || toolOptions.Defer is not null)) + if (toolOptions is not null && (toolOptions.OverridesBuiltInTool || toolOptions.SkipPermission || toolOptions.Defer is not null || toolOptions.Metadata is not null)) { Dictionary additionalProperties = new(StringComparer.Ordinal); if (factoryOptions.AdditionalProperties is not null) @@ -113,6 +117,11 @@ static void ApplyToolOptions(AIFunctionFactoryOptions factoryOptions, CopilotToo additionalProperties[DeferKey] = defer; } + if (toolOptions.Metadata is { } metadata) + { + additionalProperties[MetadataKey] = metadata; + } + factoryOptions.AdditionalProperties = additionalProperties; } } @@ -151,6 +160,11 @@ public sealed class CopilotToolOptions /// SDK forwards it to the CLI as the tool's defer mode. Defaults to "auto". /// public CopilotToolDefer? Defer { get; set; } + + /// + /// Gets or sets opaque, host-defined metadata associated with the tool definition. + /// + public IDictionary? Metadata { get; set; } } /// diff --git a/dotnet/src/FfiRuntimeHost.cs b/dotnet/src/FfiRuntimeHost.cs new file mode 100644 index 0000000000..a838b9fd17 --- /dev/null +++ b/dotnet/src/FfiRuntimeHost.cs @@ -0,0 +1,683 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Extensions.Logging; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Threading.Channels; + +namespace GitHub.Copilot; + +/// +/// Hosts the Copilot runtime in-process by loading the Rust cdylib (runtime.node) +/// and speaking JSON-RPC over its C ABI (FFI) instead of spawning a CLI child process +/// and communicating over stdio/TCP. +/// +/// +/// The Rust host_start export spawns the residual TypeScript worker itself — +/// typically the packaged single-file CLI (copilot --embedded-host, which embeds +/// its own Node) or, for dev, node dist-cli/index.js --embedded-host — so the .NET +/// host never launches Node directly. JSON-RPC frames are pumped across the ABI: writes go +/// to connection_write; inbound frames arrive on a native callback that feeds +/// . +/// +/// The native interop layer has two implementations selected by target framework. On +/// modern .NET it uses source-generated LibraryImport P/Invoke with an +/// UnmanagedCallersOnly function-pointer callback, which is trim- and +/// NativeAOT-compatible. On netstandard2.0 (which has neither LibraryImport +/// nor NativeLibrary) it falls back to classic delegate-based P/Invoke over a +/// hand-rolled dlopen/LoadLibrary loader. Because the library lives at a +/// runtime-resolved absolute path, the modern path maps the logical +/// via a resolver and the legacy path loads the absolute path +/// directly. +/// +/// +internal sealed partial class FfiRuntimeHost : IDisposable +{ + /// Logical name the native interop layer binds the cdylib to. + private const string LibraryName = "copilot_runtime"; + + private readonly ILogger _logger; + private readonly string _cliEntrypoint; + private readonly string _libraryPath; + private readonly IReadOnlyDictionary? _environment; + private readonly IReadOnlyList _args; + + private readonly CallbackReceiveStream _receiveStream = new(); + private CallbackSendStream? _sendStream; + + private uint _serverId; + private uint _connectionId; + private bool _disposed; + + private FfiRuntimeHost(string libraryPath, string cliEntrypoint, IReadOnlyDictionary? environment, IReadOnlyList args, ILogger logger) + { + _libraryPath = libraryPath; + _cliEntrypoint = cliEntrypoint; + _environment = environment; + _args = args; + _logger = logger; + } + + /// The stream JSON-RPC reads server→client frames from. + public Stream ReceiveStream => _receiveStream; + + /// The stream JSON-RPC writes client→server frames to. + public Stream SendStream => _sendStream + ?? throw new InvalidOperationException("FfiRuntimeHost has not been started."); + + /// + /// Loads the cdylib next to the given CLI entrypoint and prepares the FFI host. + /// The entrypoint is either the packaged single-file CLI binary (e.g. + /// runtimes/<rid>/native/copilot) or, for dev, a .js file (e.g. + /// dist-cli/index.js) launched via node. The cdylib is resolved + /// relative to the entrypoint directory, preferring the flat, natural + /// shared-library name the .NET build emits (e.g. libcopilot_runtime.so) + /// and falling back to the dev tarball layout + /// prebuilds/<prebuildsFolder>/runtime.node, where + /// is the napi-rs + /// <node-platform>-<arch> folder name (e.g. win32-x64). + /// + public static FfiRuntimeHost Create(string cliEntrypoint, string prebuildsFolder, IReadOnlyDictionary? environment, IReadOnlyList args, ILogger logger) + { + var fullEntrypoint = Path.GetFullPath(cliEntrypoint); + var distDir = Path.GetDirectoryName(fullEntrypoint) + ?? throw new InvalidOperationException($"Could not determine directory for '{cliEntrypoint}'."); + + // Bundled .NET layout: flat, natural shared-library name next to the CLI. + var flatLibraryPath = Path.Combine(distDir, GetRuntimeLibraryFileName()); + // Dev/tarball layout: dist-cli/prebuilds/-/runtime.node. + var prebuildsLibraryPath = Path.Combine(distDir, "prebuilds", prebuildsFolder, "runtime.node"); + + var libraryPath = File.Exists(flatLibraryPath) ? flatLibraryPath + : File.Exists(prebuildsLibraryPath) ? prebuildsLibraryPath + : throw new InvalidOperationException( + $"FFI runtime library not found. Looked for '{flatLibraryPath}' and '{prebuildsLibraryPath}'."); + + PrepareNativeLibrary(libraryPath); + return new FfiRuntimeHost(libraryPath, fullEntrypoint, environment, args, logger); + } + + /// + /// The natural platform shared-library file name for the runtime cdylib, as + /// emitted by the .NET build (the .node file renamed to what the Rust cdylib + /// would be called on this OS). + /// + private static string GetRuntimeLibraryFileName() + { + if (OperatingSystem.IsWindows()) return "copilot_runtime.dll"; + if (OperatingSystem.IsMacOS()) return "libcopilot_runtime.dylib"; + return "libcopilot_runtime.so"; + } + + /// + /// Starts the in-process runtime: spawns the CLI worker via the Rust host, + /// waits for readiness, and opens the FFI JSON-RPC connection. + /// + public async Task StartAsync(CancellationToken cancellationToken) + { + // host_start blocks until the worker connects back and signals readiness + // (up to ~30s), and connection_open must run outside any async runtime, so + // perform the blocking FFI handshake on a background thread. + await Task.Run(() => + { + var argvJson = BuildArgvJson(_cliEntrypoint, _args); + var envJson = BuildEnvJson(_environment); + + _serverId = NativeHostStart(argvJson, envJson); + if (_serverId == 0) + { + throw new InvalidOperationException( + $"copilot_runtime_host_start failed (library '{_libraryPath}', entrypoint '{_cliEntrypoint}')."); + } + + _connectionId = NativeOpenConnection(_serverId); + if (_connectionId == 0) + { + DisposeNativeCallback(); + NativeHostShutdown(_serverId); + _serverId = 0; + throw new InvalidOperationException("copilot_runtime_connection_open failed."); + } + + _sendStream = new CallbackSendStream(SendFrame); + }, cancellationToken).ConfigureAwait(false); + + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug( + "FfiRuntimeHost started. Library={Library}, ServerId={ServerId}, ConnectionId={ConnectionId}", + _libraryPath, _serverId, _connectionId); + } + } + + private static byte[] BuildArgvJson(string cliEntrypoint, IReadOnlyList args) + { + // A .js entrypoint (dev / dist-cli) is launched via node; the packaged + // single-file CLI binary embeds its own Node and is invoked directly. + var isJsFile = cliEntrypoint.EndsWith(".js", StringComparison.OrdinalIgnoreCase); + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream)) + { + writer.WriteStartArray(); + if (isJsFile) + { + writer.WriteStringValue("node"); + } + writer.WriteStringValue(cliEntrypoint); + writer.WriteStringValue("--embedded-host"); + // Pin the worker to the bundled pkg matching the loaded cdylib, instead of + // drifting to a newer version under the user's ~/.copilot/pkg (ABI skew). + writer.WriteStringValue("--no-auto-update"); + foreach (var arg in args) + { + writer.WriteStringValue(arg); + } + writer.WriteEndArray(); + } + return stream.ToArray(); + } + + private static byte[]? BuildEnvJson(IReadOnlyDictionary? environment) + { + if (environment is null || environment.Count == 0) + { + return null; + } + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream)) + { + writer.WriteStartObject(); + foreach (var kvp in environment) + { + writer.WriteString(kvp.Key, kvp.Value); + } + writer.WriteEndObject(); + } + return stream.ToArray(); + } + + /// + /// Writes one framed message to the native connection. The bytes are read + /// synchronously by the native side (it copies before returning), so the + /// span does not need to outlive the call — no allocation or copy on our side. + /// + private delegate bool FrameWriter(ReadOnlySpan frame); + + private bool SendFrame(ReadOnlySpan frame) + { + if (_disposed || _connectionId == 0) + { + return false; + } + return NativeConnectionWrite(_connectionId, frame); + } + + private void FeedInbound(IntPtr bytesPtr, UIntPtr bytesLen) + { + var length = checked((int)bytesLen.ToUInt64()); + var buffer = new byte[length]; + Marshal.Copy(bytesPtr, buffer, 0, length); + _receiveStream.Feed(buffer); + } + + public void Dispose() + { + if (_disposed) + { + return; + } + _disposed = true; + + try + { + if (_connectionId != 0) + { + NativeConnectionClose(_connectionId); + _connectionId = 0; + } + } + catch (Exception ex) + { + _logger.LogDebug(ex, "FfiRuntimeHost: connection_close failed"); + } + + try + { + if (_serverId != 0) + { + NativeHostShutdown(_serverId); + _serverId = 0; + } + } + catch (Exception ex) + { + _logger.LogDebug(ex, "FfiRuntimeHost: host_shutdown failed"); + } + + _receiveStream.Complete(); + DisposeNativeCallback(); + } + + /// Length as the native pointer-sized unsigned integer the ABI expects. + private static UIntPtr Len(int value) => new((uint)value); + +#if NET + // ---- Modern interop: source-generated LibraryImport P/Invoke (trim/AOT-safe) ---- + + private static readonly object ResolverLock = new(); + private static bool s_resolverRegistered; + private static string? s_resolvedLibraryPath; + + // A normal (non-pinned) handle to this instance, passed to the native side as + // the callback's user_data so the static outbound callback can route back here. + private GCHandle _selfHandle; + + /// + /// Registers (once) a process-wide + /// that maps to the absolute runtime.node path so the + /// stubs resolve. The resolved handle is cached by + /// the runtime after first use, so all in-process hosts share a single loaded library. + /// + private static void PrepareNativeLibrary(string libraryPath) + { + lock (ResolverLock) + { + if (s_resolvedLibraryPath is not null && s_resolvedLibraryPath != libraryPath) + { + throw new InvalidOperationException( + $"An in-process FFI runtime library is already loaded from '{s_resolvedLibraryPath}'; " + + $"loading a different library from '{libraryPath}' in the same process is not supported."); + } + s_resolvedLibraryPath = libraryPath; + if (!s_resolverRegistered) + { + NativeLibrary.SetDllImportResolver(typeof(FfiRuntimeHost).Assembly, Resolve); + s_resolverRegistered = true; + } + } + } + + private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + { + if (libraryName == LibraryName && s_resolvedLibraryPath is not null) + { + return NativeLibrary.Load(s_resolvedLibraryPath); + } + return IntPtr.Zero; + } + + private static uint NativeHostStart(byte[] argvJson, byte[]? env) => + HostStart(argvJson, Len(argvJson.Length), env, env is null ? UIntPtr.Zero : Len(env.Length)); + + private uint NativeOpenConnection(uint serverId) + { + _selfHandle = GCHandle.Alloc(this); + unsafe + { + return ConnectionOpen( + serverId, + &OnOutboundStatic, + GCHandle.ToIntPtr(_selfHandle), + null, UIntPtr.Zero, + null, UIntPtr.Zero, + null, UIntPtr.Zero); + } + } + + private static bool NativeHostShutdown(uint serverId) => HostShutdown(serverId); + + private static bool NativeConnectionWrite(uint connectionId, ReadOnlySpan frame) => ConnectionWrite(connectionId, frame, Len(frame.Length)); + + private static bool NativeConnectionClose(uint connectionId) => ConnectionClose(connectionId); + + private void DisposeNativeCallback() + { + if (_selfHandle.IsAllocated) + { + _selfHandle.Free(); + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void OnOutboundStatic(IntPtr userData, IntPtr bytesPtr, nuint bytesLen) + { + if (userData == IntPtr.Zero || bytesPtr == IntPtr.Zero || bytesLen == 0) + { + return; + } + if (GCHandle.FromIntPtr(userData).Target is FfiRuntimeHost self) + { + self.FeedInbound(bytesPtr, bytesLen); + } + } + + [LibraryImport(LibraryName, EntryPoint = "copilot_runtime_host_start")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + private static partial uint HostStart( + byte[] argvJson, nuint argvJsonLen, + byte[]? env, nuint envLen); + + [LibraryImport(LibraryName, EntryPoint = "copilot_runtime_host_shutdown")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + [return: MarshalAs(UnmanagedType.U1)] + private static partial bool HostShutdown(uint serverId); + + [LibraryImport(LibraryName, EntryPoint = "copilot_runtime_connection_open")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + private static unsafe partial uint ConnectionOpen( + uint serverId, + delegate* unmanaged[Cdecl] onOutbound, + IntPtr userData, + byte[]? extSource, nuint extSourceLen, + byte[]? extName, nuint extNameLen, + byte[]? connToken, nuint connTokenLen); + + [LibraryImport(LibraryName, EntryPoint = "copilot_runtime_connection_write")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + [return: MarshalAs(UnmanagedType.U1)] + private static partial bool ConnectionWrite(uint connectionId, ReadOnlySpan bytes, nuint bytesLen); + + [LibraryImport(LibraryName, EntryPoint = "copilot_runtime_connection_close")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + [return: MarshalAs(UnmanagedType.U1)] + private static partial bool ConnectionClose(uint connectionId); +#else + // ---- Legacy interop: delegate-based P/Invoke for netstandard2.0 ---- + // netstandard2.0 has neither LibraryImport, NativeLibrary, nor UnmanagedCallersOnly, + // so the cdylib is loaded through a hand-rolled dlopen/LoadLibrary shim and each + // export is bound to a [UnmanagedFunctionPointer] delegate. The outbound callback is + // an instance delegate kept alive in a field for the connection's lifetime. + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate uint HostStartDelegate( + byte[] argvJson, UIntPtr argvJsonLen, + byte[]? env, UIntPtr envLen); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.U1)] + private delegate bool HostShutdownDelegate(uint serverId); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate uint ConnectionOpenDelegate( + uint serverId, + OutboundCallbackDelegate onOutbound, + IntPtr userData, + byte[]? extSource, UIntPtr extSourceLen, + byte[]? extName, UIntPtr extNameLen, + byte[]? connToken, UIntPtr connTokenLen); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.U1)] + private delegate bool ConnectionWriteDelegate(uint connectionId, IntPtr bytes, UIntPtr bytesLen); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.U1)] + private delegate bool ConnectionCloseDelegate(uint connectionId); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void OutboundCallbackDelegate(IntPtr userData, IntPtr bytesPtr, UIntPtr bytesLen); + + private static readonly object NativeLock = new(); + private static bool s_loaded; + private static string? s_loadedPath; + private static HostStartDelegate? s_hostStart; + private static HostShutdownDelegate? s_hostShutdown; + private static ConnectionOpenDelegate? s_connectionOpen; + private static ConnectionWriteDelegate? s_connectionWrite; + private static ConnectionCloseDelegate? s_connectionClose; + + // Held for the connection's lifetime so the marshaled function pointer handed to the + // native side is not collected while Rust may still invoke it. + private OutboundCallbackDelegate? _outboundDelegate; + + private static void PrepareNativeLibrary(string libraryPath) + { + lock (NativeLock) + { + if (s_loaded) + { + if (s_loadedPath != libraryPath) + { + throw new InvalidOperationException( + $"An in-process FFI runtime library is already loaded from '{s_loadedPath}'; " + + $"loading a different library from '{libraryPath}' in the same process is not supported."); + } + return; + } + + var handle = NativeLoader.Load(libraryPath); + if (handle == IntPtr.Zero) + { + throw new InvalidOperationException($"Failed to load FFI runtime library '{libraryPath}'."); + } + + s_hostStart = Bind(handle, "copilot_runtime_host_start"); + s_hostShutdown = Bind(handle, "copilot_runtime_host_shutdown"); + s_connectionOpen = Bind(handle, "copilot_runtime_connection_open"); + s_connectionWrite = Bind(handle, "copilot_runtime_connection_write"); + s_connectionClose = Bind(handle, "copilot_runtime_connection_close"); + s_loaded = true; + s_loadedPath = libraryPath; + } + } + + private static T Bind(IntPtr handle, string export) where T : Delegate + { + var symbol = NativeLoader.GetSymbol(handle, export); + if (symbol == IntPtr.Zero) + { + throw new InvalidOperationException($"FFI runtime library is missing the '{export}' export."); + } + return Marshal.GetDelegateForFunctionPointer(symbol); + } + + private static uint NativeHostStart(byte[] argvJson, byte[]? env) => + s_hostStart!(argvJson, Len(argvJson.Length), env, env is null ? UIntPtr.Zero : Len(env.Length)); + + private uint NativeOpenConnection(uint serverId) + { + _outboundDelegate = OnOutbound; + return s_connectionOpen!( + serverId, + _outboundDelegate, + IntPtr.Zero, + null, UIntPtr.Zero, + null, UIntPtr.Zero, + null, UIntPtr.Zero); + } + + private static bool NativeHostShutdown(uint serverId) => s_hostShutdown!(serverId); + + private static unsafe bool NativeConnectionWrite(uint connectionId, ReadOnlySpan frame) + { + fixed (byte* ptr = frame) + { + return s_connectionWrite!(connectionId, (IntPtr)ptr, Len(frame.Length)); + } + } + + private static bool NativeConnectionClose(uint connectionId) => s_connectionClose!(connectionId); + + private void DisposeNativeCallback() => _outboundDelegate = null; + + private void OnOutbound(IntPtr userData, IntPtr bytesPtr, UIntPtr bytesLen) + { + if (bytesPtr == IntPtr.Zero || bytesLen == UIntPtr.Zero) + { + return; + } + FeedInbound(bytesPtr, bytesLen); + } + + /// + /// Minimal cross-platform native library loader for netstandard2.0, which lacks + /// NativeLibrary. Uses LoadLibrary/GetProcAddress on Windows + /// and dlopen/dlsym elsewhere (trying libdl.so.2 first, then + /// libdl for older Linux and macOS). + /// + private static class NativeLoader + { + public static IntPtr Load(string path) => + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Windows.LoadLibrary(path) : Unix.Open(path); + + public static IntPtr GetSymbol(IntPtr handle, string name) => + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Windows.GetProcAddress(handle, name) : Unix.Sym(handle, name); + + private static class Windows + { + [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPWStr)] string path); + + [DllImport("kernel32", SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr GetProcAddress(IntPtr module, [MarshalAs(UnmanagedType.LPStr)] string name); + } + + private static class Unix + { + private const int RtldNow = 2; + + public static IntPtr Open(string path) + { + try { return Libdl2.dlopen(path, RtldNow); } + catch (DllNotFoundException) { return Libdl1.dlopen(path, RtldNow); } + } + + public static IntPtr Sym(IntPtr handle, string name) + { + try { return Libdl2.dlsym(handle, name); } + catch (DllNotFoundException) { return Libdl1.dlsym(handle, name); } + } + + private static class Libdl2 + { + [DllImport("libdl.so.2", EntryPoint = "dlopen", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dlopen([MarshalAs(UnmanagedType.LPStr)] string fileName, int flags); + + [DllImport("libdl.so.2", EntryPoint = "dlsym", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dlsym(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string symbol); + } + + private static class Libdl1 + { + [DllImport("libdl", EntryPoint = "dlopen", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dlopen([MarshalAs(UnmanagedType.LPStr)] string fileName, int flags); + + [DllImport("libdl", EntryPoint = "dlsym", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dlsym(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string symbol); + } + } + } +#endif + + /// + /// A read-only stream fed by the native outbound callback. Chunks are queued on + /// an unbounded channel and drained in order by the JSON-RPC read loop. + /// + private sealed class CallbackReceiveStream : Stream + { + private readonly Channel _channel = Channel.CreateUnbounded( + new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }); + private ReadOnlyMemory _leftover; + + public void Feed(byte[] data) => _channel.Writer.TryWrite(data); + + public void Complete() => _channel.Writer.TryComplete(); + +#if !NETSTANDARD2_0 + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + return await ReadCoreAsync(buffer, cancellationToken).ConfigureAwait(false); + } +#endif + + private async ValueTask ReadCoreAsync(Memory buffer, CancellationToken cancellationToken) + { + if (_leftover.IsEmpty) + { + while (true) + { + if (!await _channel.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) + { + return 0; // EOF: channel completed. + } + if (_channel.Reader.TryRead(out var chunk)) + { + _leftover = chunk; + break; + } + // Data was signalled but lost a race for it; wait again rather + // than reporting a spurious EOF. + } + } + + var n = Math.Min(buffer.Length, _leftover.Length); + _leftover.Span.Slice(0, n).CopyTo(buffer.Span); + _leftover = _leftover.Slice(n); + return n; + } + + public override int Read(byte[] buffer, int offset, int count) => + ReadCoreAsync(buffer.AsMemory(offset, count), CancellationToken.None).AsTask().GetAwaiter().GetResult(); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadCoreAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + /// + /// A write-only stream that forwards each frame to the native + /// connection_write export. + /// + private sealed class CallbackSendStream(FrameWriter write) : Stream + { + private void WriteFrame(ReadOnlySpan frame) + { + if (!write(frame)) + { + throw new IOException("Failed to write a frame to the in-process runtime connection."); + } + } + + public override void Write(byte[] buffer, int offset, int count) => WriteFrame(buffer.AsSpan(offset, count)); + +#if !NETSTANDARD2_0 + public override void Write(ReadOnlySpan buffer) => WriteFrame(buffer); + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + WriteFrame(buffer.Span); + return ValueTask.CompletedTask; + } +#endif + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + WriteFrame(buffer.AsSpan(offset, count)); + return Task.CompletedTask; + } + + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } +} diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index 3a9fcf9cde..bf73bdfaf7 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -19,6 +19,7 @@ namespace GitHub.Copilot.Rpc; /// Server liveness response, including the echoed message, current server timestamp, and protocol version. +[Experimental(Diagnostics.Experimental)] public sealed class PingResult { /// Echoed message (or default greeting). @@ -35,6 +36,7 @@ public sealed class PingResult } /// Optional message to echo back to the caller. +[Experimental(Diagnostics.Experimental)] internal sealed class PingRequest { /// Optional message to echo back. @@ -43,6 +45,7 @@ internal sealed class PingRequest } /// Handshake result reporting the server's protocol version and package version on success. +[Experimental(Diagnostics.Experimental)] internal sealed class ConnectResult { /// Always true on success. @@ -58,20 +61,49 @@ internal sealed class ConnectResult public string Version { get; set; } = string.Empty; } -/// Optional connection token presented by the SDK client during the handshake. +/// Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). +[Experimental(Diagnostics.Experimental)] internal sealed class ConnectRequest { + /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. + [JsonPropertyName("enableGitHubTelemetryForwarding")] + public bool? EnableGitHubTelemetryForwarding { get; set; } + /// Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN. [JsonPropertyName("token")] public string? Token { get; set; } } +/// Active server-driven promotion for a model, including its discount and expiry. +[Experimental(Diagnostics.Experimental)] +public sealed class ModelBillingPromo +{ + /// Percentage discount (0-100) applied while the promotion is active. May be fractional. + [JsonPropertyName("discountPercent")] + public double? DiscountPercent { get; set; } + + /// UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. + [JsonPropertyName("endsAt")] + public string EndsAt { get; set; } = string.Empty; + + /// Stable identifier for the promotion campaign. + [JsonPropertyName("id")] + public string? Id { get; set; } + + /// Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. + [JsonPropertyName("message")] + public string? Message { get; set; } +} + /// Long context tier pricing (available for models with extended context windows). +[Experimental(Diagnostics.Experimental)] public sealed class ModelBillingTokenPricesLongContext { /// Use cacheReadPrice instead. AI Credits cost per billing batch of cached tokens. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonPropertyName("cachePrice")] public double? CachePrice { get; set; } @@ -85,7 +117,9 @@ public sealed class ModelBillingTokenPricesLongContext /// Use maxPromptTokens instead. Prompt token budget for the long context tier. The total context window is this value plus the model's max_output_tokens. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonPropertyName("contextMax")] public long? ContextMax { get; set; } @@ -103,6 +137,7 @@ public sealed class ModelBillingTokenPricesLongContext } /// Token-level pricing information for this model. +[Experimental(Diagnostics.Experimental)] public sealed class ModelBillingTokenPrices { /// Number of tokens per standard billing batch. @@ -111,7 +146,9 @@ public sealed class ModelBillingTokenPrices /// Use cacheReadPrice instead. AI Credits cost per billing batch of cached tokens. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonPropertyName("cachePrice")] public double? CachePrice { get; set; } @@ -125,7 +162,9 @@ public sealed class ModelBillingTokenPrices /// Use maxPromptTokens instead. Prompt token budget for the default tier. The total context window is this value plus the model's max_output_tokens. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonPropertyName("contextMax")] public long? ContextMax { get; set; } @@ -147,18 +186,28 @@ public sealed class ModelBillingTokenPrices } /// Billing information. +[Experimental(Diagnostics.Experimental)] public sealed class ModelBilling { + /// Whole-number percentage discount (0-100) applied to usage billed through this model. Populated for the synthetic `auto` model, where requests routed by auto-mode are billed at a reduced rate; absent for concrete models. + [JsonPropertyName("discountPercent")] + public int? DiscountPercent { get; set; } + /// Billing cost multiplier relative to the base rate. [JsonPropertyName("multiplier")] public double? Multiplier { get; set; } + /// Active server-driven promotion for this model, if any. Present when the model is being promoted with a time-boxed discount. + [JsonPropertyName("promo")] + public ModelBillingPromo? Promo { get; set; } + /// Token-level pricing information for this model. [JsonPropertyName("tokenPrices")] public ModelBillingTokenPrices? TokenPrices { get; set; } } /// Vision-specific limits. +[Experimental(Diagnostics.Experimental)] public sealed class ModelCapabilitiesLimitsVision { /// Maximum image size in bytes. @@ -175,6 +224,7 @@ public sealed class ModelCapabilitiesLimitsVision } /// Token limits for prompts, outputs, and context window. +[Experimental(Diagnostics.Experimental)] public sealed class ModelCapabilitiesLimits { /// Maximum total context window size in tokens. @@ -195,8 +245,13 @@ public sealed class ModelCapabilitiesLimits } /// Feature flags indicating what the model supports. +[Experimental(Diagnostics.Experimental)] public sealed class ModelCapabilitiesSupports { + /// Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + [JsonPropertyName("adaptive_thinking")] + public AdaptiveThinkingSupport? AdaptiveThinking { get; set; } + /// Whether this model supports reasoning effort configuration. [JsonPropertyName("reasoningEffort")] public bool? ReasoningEffort { get; set; } @@ -207,6 +262,7 @@ public sealed class ModelCapabilitiesSupports } /// Model capabilities and limits. +[Experimental(Diagnostics.Experimental)] public sealed class ModelCapabilities { /// Token limits for prompts, outputs, and context window. @@ -219,6 +275,7 @@ public sealed class ModelCapabilities } /// Policy state (if applicable). +[Experimental(Diagnostics.Experimental)] public sealed class ModelPolicy { /// Current policy state for this model. @@ -230,7 +287,8 @@ public sealed class ModelPolicy public string? Terms { get; set; } } -/// Schema for the `Model` type. +/// Copilot model metadata, including identifier, display name, capabilities, policy, billing, reasoning efforts, and picker categories. +[Experimental(Diagnostics.Experimental)] public sealed class Model { /// Billing information. @@ -271,6 +329,7 @@ public sealed class Model } /// List of Copilot models available to the resolved user, including capabilities and billing metadata. +[Experimental(Diagnostics.Experimental)] public sealed class ModelList { /// List of available models with full metadata. @@ -279,6 +338,7 @@ public sealed class ModelList } /// RPC data type for ModelsList operations. +[Experimental(Diagnostics.Experimental)] internal sealed class ModelsListRequest { /// GitHub token for per-user model listing. When provided, resolves this token to determine the user's Copilot plan and available models instead of using the global auth. @@ -286,7 +346,8 @@ internal sealed class ModelsListRequest public string? GitHubToken { get; set; } } -/// Schema for the `Tool` type. +/// Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. +[Experimental(Diagnostics.Experimental)] public sealed class Tool { /// Description of what the tool does. @@ -311,6 +372,7 @@ public sealed class Tool } /// Built-in tools available for the requested model, with their parameters and instructions. +[Experimental(Diagnostics.Experimental)] public sealed class ToolList { /// List of available built-in tools with metadata. @@ -319,6 +381,7 @@ public sealed class ToolList } /// Optional model identifier whose tool overrides should be applied to the listing. +[Experimental(Diagnostics.Experimental)] internal sealed class ToolsListRequest { /// Optional model ID — when provided, the returned tool list reflects model-specific overrides. @@ -326,7 +389,8 @@ internal sealed class ToolsListRequest public string? Model { get; set; } } -/// Schema for the `AccountQuotaSnapshot` type. +/// Quota usage snapshot for a Copilot quota type, including entitlement, used requests, overage, reset date, and remaining percentage. +[Experimental(Diagnostics.Experimental)] public sealed class AccountQuotaSnapshot { /// Number of requests included in the entitlement, or -1 for unlimited entitlements. @@ -363,6 +427,7 @@ public sealed class AccountQuotaSnapshot } /// Quota usage snapshots for the resolved user, keyed by quota type. +[Experimental(Diagnostics.Experimental)] public sealed class AccountGetQuotaResult { /// Quota snapshots keyed by type (e.g., chat, completions, premium_interactions). @@ -371,6 +436,7 @@ public sealed class AccountGetQuotaResult } /// RPC data type for AccountGetQuota operations. +[Experimental(Diagnostics.Experimental)] internal sealed class AccountGetQuotaRequest { /// GitHub token for per-user quota lookup. When provided, resolves this token to determine the user's quota instead of using the global auth. @@ -380,6 +446,7 @@ internal sealed class AccountGetQuotaRequest /// Initial authentication info for the session. /// Polymorphic base type discriminated by type. +[Experimental(Diagnostics.Experimental)] [JsonPolymorphic( TypeDiscriminatorPropertyName = "type", UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] @@ -398,7 +465,8 @@ public partial class AuthInfo } -/// Schema for the `CopilotUserResponseEndpoints` type. +/// Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. +[Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponseEndpoints { /// Gets or sets the api value. @@ -430,284 +498,294 @@ public sealed class CopilotUserResponseOrganizationListItem public string? Name { get; set; } } -/// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. +/// Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. +[Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponseQuotaSnapshotsChat { - /// Gets or sets the entitlement value. + /// Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. [JsonPropertyName("entitlement")] public double? Entitlement { get; set; } - /// Gets or sets the has_quota value. + /// Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. [JsonPropertyName("has_quota")] public bool? HasQuota { get; set; } - /// Gets or sets the overage_count value. + /// Count of additional pay-per-request usage consumed this period beyond the entitlement. [JsonPropertyName("overage_count")] public double? OverageCount { get; set; } - /// Gets or sets the overage_permitted value. + /// Whether usage may continue at pay-per-request rates once the entitlement is exhausted. [JsonPropertyName("overage_permitted")] public bool? OveragePermitted { get; set; } - /// Gets or sets the percent_remaining value. + /// Percentage of the entitlement remaining at the snapshot timestamp. [JsonPropertyName("percent_remaining")] public double? PercentRemaining { get; set; } - /// Gets or sets the quota_id value. + /// Identifier of the quota bucket this snapshot describes. [JsonPropertyName("quota_id")] public string? QuotaId { get; set; } - /// Gets or sets the quota_remaining value. + /// Amount of quota remaining at the snapshot timestamp. [JsonPropertyName("quota_remaining")] public double? QuotaRemaining { get; set; } - /// Gets or sets the quota_reset_at value. + /// Unix epoch time, in seconds, when this quota next resets. [JsonPropertyName("quota_reset_at")] public double? QuotaResetAt { get; set; } - /// Gets or sets the remaining value. + /// Remaining entitlement/quota amount at the snapshot timestamp. [JsonPropertyName("remaining")] public double? Remaining { get; set; } - /// Gets or sets the timestamp_utc value. + /// UTC timestamp when this snapshot was captured. [JsonPropertyName("timestamp_utc")] public string? TimestampUtc { get; set; } - /// Gets or sets the token_based_billing value. + /// Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. [JsonPropertyName("token_based_billing")] public bool? TokenBasedBilling { get; set; } - /// Gets or sets the unlimited value. + /// Whether the entitlement for this category is unlimited. [JsonPropertyName("unlimited")] public bool? Unlimited { get; set; } } -/// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. +/// Completions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. +[Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponseQuotaSnapshotsCompletions { - /// Gets or sets the entitlement value. + /// Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. [JsonPropertyName("entitlement")] public double? Entitlement { get; set; } - /// Gets or sets the has_quota value. + /// Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. [JsonPropertyName("has_quota")] public bool? HasQuota { get; set; } - /// Gets or sets the overage_count value. + /// Count of additional pay-per-request usage consumed this period beyond the entitlement. [JsonPropertyName("overage_count")] public double? OverageCount { get; set; } - /// Gets or sets the overage_permitted value. + /// Whether usage may continue at pay-per-request rates once the entitlement is exhausted. [JsonPropertyName("overage_permitted")] public bool? OveragePermitted { get; set; } - /// Gets or sets the percent_remaining value. + /// Percentage of the entitlement remaining at the snapshot timestamp. [JsonPropertyName("percent_remaining")] public double? PercentRemaining { get; set; } - /// Gets or sets the quota_id value. + /// Identifier of the quota bucket this snapshot describes. [JsonPropertyName("quota_id")] public string? QuotaId { get; set; } - /// Gets or sets the quota_remaining value. + /// Amount of quota remaining at the snapshot timestamp. [JsonPropertyName("quota_remaining")] public double? QuotaRemaining { get; set; } - /// Gets or sets the quota_reset_at value. + /// Unix epoch time, in seconds, when this quota next resets. [JsonPropertyName("quota_reset_at")] public double? QuotaResetAt { get; set; } - /// Gets or sets the remaining value. + /// Remaining entitlement/quota amount at the snapshot timestamp. [JsonPropertyName("remaining")] public double? Remaining { get; set; } - /// Gets or sets the timestamp_utc value. + /// UTC timestamp when this snapshot was captured. [JsonPropertyName("timestamp_utc")] public string? TimestampUtc { get; set; } - /// Gets or sets the token_based_billing value. + /// Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. [JsonPropertyName("token_based_billing")] public bool? TokenBasedBilling { get; set; } - /// Gets or sets the unlimited value. + /// Whether the entitlement for this category is unlimited. [JsonPropertyName("unlimited")] public bool? Unlimited { get; set; } } -/// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. +/// Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. +[Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponseQuotaSnapshotsPremiumInteractions { - /// Gets or sets the entitlement value. + /// Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. [JsonPropertyName("entitlement")] public double? Entitlement { get; set; } - /// Gets or sets the has_quota value. + /// Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. [JsonPropertyName("has_quota")] public bool? HasQuota { get; set; } - /// Gets or sets the overage_count value. + /// Count of additional pay-per-request usage consumed this period beyond the entitlement. [JsonPropertyName("overage_count")] public double? OverageCount { get; set; } - /// Gets or sets the overage_permitted value. + /// Whether usage may continue at pay-per-request rates once the entitlement is exhausted. [JsonPropertyName("overage_permitted")] public bool? OveragePermitted { get; set; } - /// Gets or sets the percent_remaining value. + /// Percentage of the entitlement remaining at the snapshot timestamp. [JsonPropertyName("percent_remaining")] public double? PercentRemaining { get; set; } - /// Gets or sets the quota_id value. + /// Identifier of the quota bucket this snapshot describes. [JsonPropertyName("quota_id")] public string? QuotaId { get; set; } - /// Gets or sets the quota_remaining value. + /// Amount of quota remaining at the snapshot timestamp. [JsonPropertyName("quota_remaining")] public double? QuotaRemaining { get; set; } - /// Gets or sets the quota_reset_at value. + /// Unix epoch time, in seconds, when this quota next resets. [JsonPropertyName("quota_reset_at")] public double? QuotaResetAt { get; set; } - /// Gets or sets the remaining value. + /// Remaining entitlement/quota amount at the snapshot timestamp. [JsonPropertyName("remaining")] public double? Remaining { get; set; } - /// Gets or sets the timestamp_utc value. + /// UTC timestamp when this snapshot was captured. [JsonPropertyName("timestamp_utc")] public string? TimestampUtc { get; set; } - /// Gets or sets the token_based_billing value. + /// Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. [JsonPropertyName("token_based_billing")] public bool? TokenBasedBilling { get; set; } - /// Gets or sets the unlimited value. + /// Whether the entitlement for this category is unlimited. [JsonPropertyName("unlimited")] public bool? Unlimited { get; set; } } -/// Schema for the `CopilotUserResponseQuotaSnapshots` type. +/// Quota snapshot map from the raw Copilot user-response passthrough, with chat, completions, premium-interactions, and other entries. +[Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponseQuotaSnapshots { - /// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + /// Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. [JsonPropertyName("chat")] public CopilotUserResponseQuotaSnapshotsChat? Chat { get; set; } - /// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + /// Completions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. [JsonPropertyName("completions")] public CopilotUserResponseQuotaSnapshotsCompletions? Completions { get; set; } - /// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + /// Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. [JsonPropertyName("premium_interactions")] public CopilotUserResponseQuotaSnapshotsPremiumInteractions? PremiumInteractions { get; set; } } /// Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. +[Experimental(Diagnostics.Experimental)] public sealed class CopilotUserResponse { - /// Gets or sets the access_type_sku value. + /// Copilot access SKU identifier (e.g. `free_limited_copilot`, `copilot_for_business_seat_quota`) used to gate model and feature access. [JsonPropertyName("access_type_sku")] public string? AccessTypeSku { get; set; } - /// Gets or sets the analytics_tracking_id value. + /// Opaque analytics tracking identifier for the user, forwarded from the Copilot API. [JsonPropertyName("analytics_tracking_id")] public string? AnalyticsTrackingId { get; set; } - /// Gets or sets the assigned_date value. + /// Date the Copilot seat was assigned to the user, if applicable. [JsonPropertyName("assigned_date")] public string? AssignedDate { get; set; } - /// Gets or sets the can_signup_for_limited value. + /// Whether the user is eligible to sign up for the free/limited Copilot tier. [JsonPropertyName("can_signup_for_limited")] public bool? CanSignupForLimited { get; set; } - /// Gets or sets the can_upgrade_plan value. + /// Whether the user is able to upgrade their Copilot plan. [JsonPropertyName("can_upgrade_plan")] public bool? CanUpgradePlan { get; set; } - /// Gets or sets the chat_enabled value. + /// Whether Copilot chat is enabled for the user. [JsonPropertyName("chat_enabled")] public bool? ChatEnabled { get; set; } - /// Gets or sets the cli_remote_control_enabled value. + /// Whether CLI remote control is enabled for the user. [JsonPropertyName("cli_remote_control_enabled")] public bool? CliRemoteControlEnabled { get; set; } - /// Gets or sets the cloud_session_storage_enabled value. + /// Whether cloud session storage is enabled for the user. [JsonPropertyName("cloud_session_storage_enabled")] public bool? CloudSessionStorageEnabled { get; set; } - /// Gets or sets the codex_agent_enabled value. + /// Whether the Codex agent is enabled for the user. [JsonPropertyName("codex_agent_enabled")] public bool? CodexAgentEnabled { get; set; } - /// Gets or sets the copilot_plan value. + /// Copilot plan name for the user (e.g. `individual`, `business`, `enterprise`). [JsonPropertyName("copilot_plan")] public string? CopilotPlan { get; set; } - /// Gets or sets the copilotignore_enabled value. + /// Whether `.copilotignore` content-exclusion support is enabled for the user. [JsonPropertyName("copilotignore_enabled")] public bool? CopilotignoreEnabled { get; set; } - /// Schema for the `CopilotUserResponseEndpoints` type. + /// Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. [JsonPropertyName("endpoints")] public CopilotUserResponseEndpoints? Endpoints { get; set; } - /// Gets or sets the is_mcp_enabled value. + /// Whether MCP (Model Context Protocol) support is enabled for the user. [JsonPropertyName("is_mcp_enabled")] public bool? IsMcpEnabled { get; set; } - /// Gets or sets the is_staff value. + /// Whether the user is a GitHub/Microsoft staff member. [JsonPropertyName("is_staff")] public bool? IsStaff { get; set; } - /// Gets or sets the limited_user_quotas value. + /// Per-category quota allotments for free/limited-tier users, keyed by quota category. [JsonPropertyName("limited_user_quotas")] public IDictionary? LimitedUserQuotas { get; set; } - /// Gets or sets the limited_user_reset_date value. + /// Date the free/limited-tier user's quotas next reset, as a raw string from the Copilot API. [JsonPropertyName("limited_user_reset_date")] public string? LimitedUserResetDate { get; set; } - /// Gets or sets the login value. + /// GitHub login of the authenticated user. [JsonPropertyName("login")] public string? Login { get; set; } - /// Gets or sets the monthly_quotas value. + /// Per-category monthly quota allotments, keyed by quota category. [JsonPropertyName("monthly_quotas")] public IDictionary? MonthlyQuotas { get; set; } - /// Gets or sets the organization_list value. + /// Organizations the user belongs to, each with an optional login and display name. [JsonPropertyName("organization_list")] public IList? OrganizationList { get; set; } - /// Gets or sets the organization_login_list value. + /// Logins of the organizations the user belongs to. [JsonPropertyName("organization_login_list")] public IList? OrganizationLoginList { get; set; } - /// Gets or sets the quota_reset_date value. + /// Date the user's usage quota next resets, as a raw string from the Copilot API; see `quota_reset_date_utc` for the UTC-normalized value. [JsonPropertyName("quota_reset_date")] public string? QuotaResetDate { get; set; } - /// Gets or sets the quota_reset_date_utc value. + /// UTC-normalized form of `quota_reset_date` (the date the user's usage quota next resets). [JsonPropertyName("quota_reset_date_utc")] public string? QuotaResetDateUtc { get; set; } - /// Schema for the `CopilotUserResponseQuotaSnapshots` type. + /// Quota snapshot map from the raw Copilot user-response passthrough, with chat, completions, premium-interactions, and other entries. [JsonPropertyName("quota_snapshots")] public CopilotUserResponseQuotaSnapshots? QuotaSnapshots { get; set; } - /// Gets or sets the restricted_telemetry value. + /// Whether the user's telemetry is subject to restricted-data handling. [JsonPropertyName("restricted_telemetry")] public bool? RestrictedTelemetry { get; set; } - /// Gets or sets the token_based_billing value. + /// Raw passthrough of the Copilot API `te` flag for the user (an opaque server-side eligibility signal surfaced in telemetry); not otherwise interpreted by the runtime. + [JsonPropertyName("te")] + public bool? Te { get; set; } + + /// Whether the account is on usage-based (token/AI-credit) billing rather than a fixed premium-request quota. [JsonPropertyName("token_based_billing")] public bool? TokenBasedBilling { get; set; } } -/// Schema for the `HMACAuthInfo` type. +/// Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub host and HMAC secret. /// The hmac variant of . +[Experimental(Diagnostics.Experimental)] public partial class AuthInfoHmac : AuthInfo { /// @@ -728,8 +806,9 @@ public partial class AuthInfoHmac : AuthInfo public required string Host { get; set; } } -/// Schema for the `EnvAuthInfo` type. +/// Authentication-info variant for a token sourced from an environment variable, with host, optional login, token, and env var name. /// The env variant of . +[Experimental(Diagnostics.Experimental)] public partial class AuthInfoEnv : AuthInfo { /// @@ -759,8 +838,9 @@ public partial class AuthInfoEnv : AuthInfo public required string Token { get; set; } } -/// Schema for the `TokenAuthInfo` type. +/// Authentication-info variant for SDK-configured token authentication, carrying host and the secret token value. /// The token variant of . +[Experimental(Diagnostics.Experimental)] public partial class AuthInfoToken : AuthInfo { /// @@ -781,8 +861,9 @@ public partial class AuthInfoToken : AuthInfo public required string Token { get; set; } } -/// Schema for the `CopilotApiTokenAuthInfo` type. +/// Authentication-info variant for direct Copilot API token auth sourced from environment variables, with public GitHub host. /// The copilot-api-token variant of . +[Experimental(Diagnostics.Experimental)] public partial class AuthInfoCopilotApiToken : AuthInfo { /// @@ -799,8 +880,9 @@ public partial class AuthInfoCopilotApiToken : AuthInfo public required string Host { get; set; } } -/// Schema for the `UserAuthInfo` type. +/// Authentication-info variant for OAuth user auth, with host and login; the token remains in the runtime secret store. /// The user variant of . +[Experimental(Diagnostics.Experimental)] public partial class AuthInfoUser : AuthInfo { /// @@ -821,8 +903,9 @@ public partial class AuthInfoUser : AuthInfo public required string Login { get; set; } } -/// Schema for the `GhCliAuthInfo` type. +/// Authentication-info variant for GitHub CLI credentials, carrying host, login, and the `gh auth token` value. /// The gh-cli variant of . +[Experimental(Diagnostics.Experimental)] public partial class AuthInfoGhCli : AuthInfo { /// @@ -847,8 +930,9 @@ public partial class AuthInfoGhCli : AuthInfo public required string Token { get; set; } } -/// Schema for the `ApiKeyAuthInfo` type. +/// Authentication-info variant for API-key authentication to a non-GitHub LLM provider, carrying the secret `apiKey` and host. /// The api-key variant of . +[Experimental(Diagnostics.Experimental)] public partial class AuthInfoApiKey : AuthInfo { /// @@ -870,6 +954,7 @@ public partial class AuthInfoApiKey : AuthInfo } /// Current authentication state. +[Experimental(Diagnostics.Experimental)] public sealed class AccountGetCurrentAuthResult { /// Authentication errors from the last auth attempt, if any. @@ -881,7 +966,8 @@ public sealed class AccountGetCurrentAuthResult public AuthInfo? AuthInfo { get; set; } } -/// Schema for the `AccountAllUsers` type. +/// Authenticated account entry returned by `account.getAllUsers`, with auth info and an optional associated token. +[Experimental(Diagnostics.Experimental)] public sealed class AccountAllUsers { /// Authentication information for this user. @@ -894,6 +980,7 @@ public sealed class AccountAllUsers } /// Result of a successful login; throws on failure. +[Experimental(Diagnostics.Experimental)] public sealed class AccountLoginResult { /// Whether the credential was persisted to a secure store (system keychain, or the config file when plaintext storage is enabled). False when no secure store was available and the token was not saved, so the consumer can decide how to proceed. @@ -902,6 +989,7 @@ public sealed class AccountLoginResult } /// Credentials to store after successful authentication. +[Experimental(Diagnostics.Experimental)] internal sealed class AccountLoginRequest { /// GitHub host URL. @@ -918,6 +1006,7 @@ internal sealed class AccountLoginRequest } /// Logout result indicating if more users remain. +[Experimental(Diagnostics.Experimental)] public sealed class AccountLogoutResult { /// Whether other authenticated users remain after logout. @@ -926,6 +1015,7 @@ public sealed class AccountLogoutResult } /// User to log out. +[Experimental(Diagnostics.Experimental)] internal sealed class AccountLogoutRequest { /// Authentication information for the user to log out. @@ -934,6 +1024,7 @@ internal sealed class AccountLogoutRequest } /// Confirmation that the secret values were registered. +[Experimental(Diagnostics.Experimental)] public sealed class SecretsAddFilterValuesResult { /// Whether the values were successfully registered. @@ -942,6 +1033,7 @@ public sealed class SecretsAddFilterValuesResult } /// Secret values to add to the redaction filter. +[Experimental(Diagnostics.Experimental)] internal sealed class SecretsAddFilterValuesRequest { /// Raw secret values to register for redaction. @@ -949,7 +1041,8 @@ internal sealed class SecretsAddFilterValuesRequest public IList Values { get => field ??= []; set; } } -/// Schema for the `DiscoveredMcpServer` type. +/// MCP server discovered by `mcp.discover`, with config source, optional plugin source, transport type, and enabled state. +[Experimental(Diagnostics.Experimental)] public sealed class DiscoveredMcpServer { /// Whether the server is enabled (not in the disabled list). @@ -981,6 +1074,7 @@ public sealed class DiscoveredMcpServer } /// MCP servers discovered from user, workspace, plugin, and built-in sources. +[Experimental(Diagnostics.Experimental)] public sealed class McpDiscoverResult { /// MCP servers discovered from all sources. @@ -989,6 +1083,7 @@ public sealed class McpDiscoverResult } /// Optional working directory used as context for MCP server discovery. +[Experimental(Diagnostics.Experimental)] internal sealed class McpDiscoverRequest { /// Working directory used as context for discovery (e.g., plugin resolution). @@ -997,6 +1092,7 @@ internal sealed class McpDiscoverRequest } /// User-configured MCP servers, keyed by server name. +[Experimental(Diagnostics.Experimental)] public sealed class McpConfigList { /// All MCP servers from user config, keyed by name. @@ -1005,6 +1101,7 @@ public sealed class McpConfigList } /// MCP server name and configuration to add to user configuration. +[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigAddRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). @@ -1020,6 +1117,7 @@ internal sealed class McpConfigAddRequest } /// MCP server name and replacement configuration to write to user configuration. +[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigUpdateRequest { /// MCP server configuration (stdio process or remote HTTP/SSE). @@ -1035,6 +1133,7 @@ internal sealed class McpConfigUpdateRequest } /// MCP server name to remove from user configuration. +[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigRemoveRequest { /// Name of the MCP server to remove. @@ -1046,6 +1145,7 @@ internal sealed class McpConfigRemoveRequest } /// MCP server names to enable for new sessions. +[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigEnableRequest { /// Names of MCP servers to enable. Each server is removed from the persisted disabled list so new sessions spawn it. Unknown or already-enabled names are ignored. @@ -1054,6 +1154,7 @@ internal sealed class McpConfigEnableRequest } /// MCP server names to disable for new sessions. +[Experimental(Diagnostics.Experimental)] internal sealed class McpConfigDisableRequest { /// Names of MCP servers to disable. Each server is added to the persisted disabled list so new sessions skip it. Already-disabled names are ignored. Active sessions keep their current connections until they end. @@ -1065,6 +1166,10 @@ internal sealed class McpConfigDisableRequest [Experimental(Diagnostics.Experimental)] public sealed class InstalledPluginInfo { + /// Opaque, stable hash identifying a direct (non-marketplace) install source. Present only for direct repo / URL / local installs; absent for marketplace plugins. Same source yields the same id; distinct sources never collide. + [JsonPropertyName("directSourceId")] + public string? DirectSourceId { get; set; } + /// Whether the plugin is currently enabled for new sessions. [JsonPropertyName("enabled")] public bool Enabled { get; set; } @@ -1129,6 +1234,10 @@ internal sealed class PluginsInstallRequest [Experimental(Diagnostics.Experimental)] internal sealed class PluginsUninstallRequest { + /// Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall when multiple installed plugins share the same name. + [JsonPropertyName("directSourceId")] + public string? DirectSourceId { get; set; } + /// Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the fully-qualified spec. [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; @@ -1160,7 +1269,7 @@ internal sealed class PluginsUpdateRequest public string Name { get; set; } = string.Empty; } -/// Schema for the `PluginUpdateAllEntry` type. +/// Per-plugin result from updating all plugins, with versions, skills installed, success flag, and optional error. [Experimental(Diagnostics.Experimental)] public sealed class PluginUpdateAllEntry { @@ -1255,13 +1364,17 @@ public sealed class MarketplaceAddResult public string Name { get; set; } = string.Empty; } -/// Marketplace source to register. +/// Marketplace source and optional working directory for relative-path resolution. [Experimental(Diagnostics.Experimental)] internal sealed class PluginsMarketplacesAddRequest { /// Marketplace source. Accepts the same forms as the CLI: "owner/repo" or "owner/repo#ref" (GitHub), an http/https/ssh URL (optionally with #ref), a git scp-style URL (user@host:path), or a local path. The marketplace's own name (from its manifest) is used as the registration key. [JsonPropertyName("source")] public string Source { get; set; } = string.Empty; + + /// Working directory used to resolve relative local paths in `source`. Defaults to the server's current working directory. + [JsonPropertyName("workingDirectory")] + public string? WorkingDirectory { get; set; } } /// Outcome of the remove attempt, including dependent-plugin info when applicable. @@ -1321,7 +1434,7 @@ internal sealed class PluginsMarketplacesBrowseRequest public string Name { get; set; } = string.Empty; } -/// Schema for the `MarketplaceRefreshEntry` type. +/// Per-marketplace refresh result, including marketplace name, success flag, and optional failure error. [Experimental(Diagnostics.Experimental)] public sealed class MarketplaceRefreshEntry { @@ -1356,7 +1469,8 @@ internal sealed class PluginsMarketplacesRefreshRequest public string? Name { get; set; } } -/// Schema for the `ServerSkill` type. +/// Server-side skill metadata, including name, description, source, enabled/invocable state, path, project path, and argument hint. +[Experimental(Diagnostics.Experimental)] public sealed class ServerSkill { /// Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field. @@ -1393,6 +1507,7 @@ public sealed class ServerSkill } /// Skills discovered across global and project sources. +[Experimental(Diagnostics.Experimental)] public sealed class ServerSkillList { /// All discovered skills across all sources. @@ -1401,6 +1516,7 @@ public sealed class ServerSkillList } /// Optional project paths and additional skill directories to include in discovery. +[Experimental(Diagnostics.Experimental)] internal sealed class SkillsDiscoverRequest { /// When true, omit skills from the host's global sources (personal, custom, plugin, and built-in), returning only project-scoped skills. For multitenant deployments. @@ -1416,7 +1532,7 @@ internal sealed class SkillsDiscoverRequest public IList? SkillDirectories { get; set; } } -/// Schema for the `SkillDiscoveryPath` type. +/// Canonical directory where skills can be discovered or created, with scope, preference, and optional project path. [Experimental(Diagnostics.Experimental)] public sealed class SkillDiscoveryPath { @@ -1460,6 +1576,7 @@ internal sealed class SkillsGetDiscoveryPathsRequest } /// Skill names to mark as disabled in global configuration, replacing any previous list. +[Experimental(Diagnostics.Experimental)] internal sealed class SkillsConfigSetDisabledSkillsRequest { /// List of skill names to disable. @@ -1467,7 +1584,7 @@ internal sealed class SkillsConfigSetDisabledSkillsRequest public IList DisabledSkills { get => field ??= []; set; } } -/// Schema for the `AgentInfo` type. +/// Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. [Experimental(Diagnostics.Experimental)] public sealed class AgentInfo { @@ -1539,7 +1656,7 @@ internal sealed class AgentsDiscoverRequest public IList? ProjectPaths { get; set; } } -/// Schema for the `AgentDiscoveryPath` type. +/// Canonical directory where custom agents can be discovered or created, with scope, preference, and optional project path. [Experimental(Diagnostics.Experimental)] public sealed class AgentDiscoveryPath { @@ -1582,7 +1699,7 @@ internal sealed class AgentsGetDiscoveryPathsRequest public IList? ProjectPaths { get; set; } } -/// Schema for the `InstructionSource` type. +/// Loaded instruction source for a session, including path, content, category, location, applicability, and optional description. [Experimental(Diagnostics.Experimental)] public sealed class InstructionSource { @@ -1649,7 +1766,7 @@ internal sealed class InstructionsDiscoverRequest public IList? ProjectPaths { get; set; } } -/// Schema for the `InstructionDiscoveryPath` type. +/// Canonical file or directory where custom instructions can be discovered or created, with location, kind, preference, and project path. [Experimental(Diagnostics.Experimental)] public sealed class InstructionDiscoveryPath { @@ -1696,7 +1813,136 @@ internal sealed class InstructionsGetDiscoveryPathsRequest public IList? ProjectPaths { get; set; } } +/// A literal choice the command input accepts, with a human-facing description. +[Experimental(Diagnostics.Experimental)] +public sealed class SlashCommandInputChoice +{ + /// Human-readable description shown alongside the choice. + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; + + /// The literal choice value (e.g. 'on', 'off', 'show'). + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; +} + +/// Optional unstructured input hint. +[Experimental(Diagnostics.Experimental)] +public sealed class SlashCommandInput +{ + /// Optional literal choices the input accepts, each with a human-facing description; clients may render these as selectable options. + [JsonPropertyName("choices")] + public IList? Choices { get; set; } + + /// Optional completion hint for the input (e.g. 'directory' for filesystem path completion). + [JsonPropertyName("completion")] + public SlashCommandInputCompletion? Completion { get; set; } + + /// Hint to display when command input has not been provided. + [JsonPropertyName("hint")] + public string Hint { get; set; } = string.Empty; + + /// When true, clients should pass the full text after the command name as a single argument rather than splitting on whitespace. + [JsonPropertyName("preserveMultilineInput")] + public bool? PreserveMultilineInput { get; set; } + + /// When true, the command requires non-empty input; clients should render the input hint as required. + [JsonPropertyName("required")] + public bool? Required { get; set; } +} + +/// Slash-command metadata with name, aliases, description, kind, input hint, execution allowance, and schedulability. +[Experimental(Diagnostics.Experimental)] +public sealed class SlashCommandInfo +{ + /// Canonical aliases without leading slashes. + [JsonPropertyName("aliases")] + public IList? Aliases { get; set; } + + /// Whether the command may run while an agent turn is active. + [JsonPropertyName("allowDuringAgentExecution")] + public bool AllowDuringAgentExecution { get; set; } + + /// Human-readable command description. + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; + + /// Whether the command is experimental. + [JsonPropertyName("experimental")] + public bool? Experimental { get; set; } + + /// Optional unstructured input hint. + [JsonPropertyName("input")] + public SlashCommandInput? Input { get; set; } + + /// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command. + [JsonPropertyName("kind")] + public SlashCommandKind Kind { get; set; } + + /// Canonical command name without a leading slash. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Whether the command may be the target of `/every` / `/after` schedules. Resolution happens at every tick, so only set this when the command is safe to re-invoke and produces an agent prompt. + [JsonPropertyName("schedulable")] + public bool? Schedulable { get; set; } +} + +/// Slash commands available in the session, after applying any include/exclude filters. +[Experimental(Diagnostics.Experimental)] +public sealed class CommandList +{ + /// Commands available in this session. + [JsonPropertyName("commands")] + public IList Commands { get => field ??= []; set; } +} + +/// A single user setting's effective value alongside its default, so consumers can render settings left at their default. +[Experimental(Diagnostics.Experimental)] +public sealed class UserSettingMetadata +{ + /// The centrally-known default for this setting (null when no default is registered). + [JsonPropertyName("default")] + public JsonElement Default { get; set; } + + /// True when the user has not set an explicit value for this setting (i.e. it is left at its default). Reflects whether the user has overridden the key, not whether the effective value happens to equal the default — a key explicitly set to a value identical to the default still reports false. + [JsonPropertyName("isDefault")] + public bool IsDefault { get; set; } + + /// The effective value: the user's value if set, otherwise the default. + [JsonPropertyName("value")] + public JsonElement Value { get; set; } +} + +/// Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. +[Experimental(Diagnostics.Experimental)] +public sealed class UserSettingsGetResult +{ + /// Every known user setting keyed by setting name, each with its effective value, default, and whether it is at the default. + [JsonPropertyName("settings")] + public IDictionary Settings { get => field ??= new Dictionary(); set; } +} + +/// Outcome of writing user settings. +[Experimental(Diagnostics.Experimental)] +public sealed class UserSettingsSetResult +{ + /// Top-level keys whose write landed in settings.json but is shadowed by a value still present in the legacy config.json (config.json wins on read). The write does not take effect until the legacy value is removed. + [JsonPropertyName("shadowedKeys")] + public IList ShadowedKeys { get => field ??= []; set; } +} + +/// Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. +[Experimental(Diagnostics.Experimental)] +internal sealed class UserSettingsSetRequest +{ + /// Partial user settings to write, as a free-form object keyed by setting name. + [JsonPropertyName("settings")] + public JsonElement Settings { get; set; } +} + /// Indicates whether the calling client was registered as the session filesystem provider. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsSetProviderResult { /// Whether the provider was set successfully. @@ -1705,6 +1951,7 @@ public sealed class SessionFsSetProviderResult } /// Optional capabilities declared by the provider. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsSetProviderCapabilities { /// Whether the provider supports SQLite query/exists operations. @@ -1713,6 +1960,7 @@ public sealed class SessionFsSetProviderCapabilities } /// Initial working directory, session-state path layout, and path conventions used to register the calling SDK client as the session filesystem provider. +[Experimental(Diagnostics.Experimental)] internal sealed class SessionFsSetProviderRequest { /// Optional capabilities declared by the provider. @@ -1921,7 +2169,7 @@ public sealed class RemoteSessionMetadataValue public RemoteSessionMetadataTaskType? TaskType { get; set; } } -/// Schema for the `SessionsOpenProgress` type. +/// `sessions.open` handoff progress update with step, status, and optional message. [Experimental(Diagnostics.Experimental)] public sealed class SessionsOpenProgress { @@ -2458,7 +2706,7 @@ internal sealed class SessionsReleaseLockRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `LocalSessionMetadataValue` type. +/// Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. [Experimental(Diagnostics.Experimental)] public sealed class LocalSessionMetadataValue { @@ -2568,7 +2816,7 @@ public sealed class SessionsSetAdditionalPluginsResult { } -/// Schema for the `InstalledPlugin` type. +/// Installed plugin record from global state, with marketplace, version, install time, enabled state, cache path, and source. [Experimental(Diagnostics.Experimental)] public sealed class InstalledPlugin { @@ -2683,6 +2931,12 @@ public partial class RemoteControlStatusActive : RemoteControlStatus [JsonPropertyName("attachedSessionId")] public required string AttachedSessionId { get; set; } + /// True while a read-only/session-sync export is deferred, awaiting the first `user.message` before its MC session exists. Marked internal: this field is excluded from the public SDK surface and is populated only on the CLI in-process path. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] + [JsonPropertyName("awaitingFirstMessage")] + internal bool? AwaitingFirstMessage { get; set; } + /// MC frontend URL for this session, when known. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("frontendUrl")] @@ -2843,42 +3097,6 @@ internal sealed class SessionsStopRemoteControlRequest public bool? Force { get; set; } } -/// Schema for the `SessionsPollSpawnedSessionsEvent` type. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionsPollSpawnedSessionsEvent -{ - /// Session id of the newly-spawned session. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} - -/// Batch of spawn events plus a cursor for follow-up polls. -[Experimental(Diagnostics.Experimental)] -internal sealed class PollSpawnedSessionsResult -{ - /// Opaque cursor to pass back to receive only events after this batch. - [JsonPropertyName("cursor")] - public string Cursor { get; set; } = string.Empty; - - /// Spawn events emitted since the supplied cursor. - [JsonPropertyName("events")] - public IList Events { get => field ??= []; set; } -} - -/// RPC data type for SessionsPollSpawnedSessions operations. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionsPollSpawnedSessionsRequest -{ - /// Opaque cursor returned by a previous poll. Omit on the first call to receive any spawn events buffered since the runtime started. - [JsonPropertyName("cursor")] - public string? Cursor { get; set; } - - /// Milliseconds to wait for new spawn events when the cursor is at the tail. 0 (default) returns immediately even if no events are buffered. Capped at 60000ms. - [JsonConverter(typeof(MillisecondsTimeSpanConverter))] - [JsonPropertyName("waitMs")] - public TimeSpan? Wait { get; set; } -} - /// Handle for releasing the extension tool registration. [Experimental(Diagnostics.Experimental)] internal sealed class RegisterExtensionToolsResult @@ -3248,50 +3466,132 @@ internal sealed class SendRequest public bool? Wait { get; set; } } -/// Result of aborting the current turn. +/// Result of sending zero or more user messages. [Experimental(Diagnostics.Experimental)] -public sealed class AbortResult +public sealed class SendMessagesResult { - /// Error message if the abort failed. - [JsonPropertyName("error")] - public string? Error { get; set; } - - /// Whether the abort completed successfully. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. + [JsonPropertyName("messageIds")] + public IList MessageIds { get => field ??= []; set; } } -/// Parameters for aborting the current turn. +/// A single user message to append to the session as part of a `session.sendMessages` turn. [Experimental(Diagnostics.Experimental)] -internal sealed class AbortRequest +public sealed class SendMessageItem { - /// Finite reason code describing why the current turn was aborted. - [JsonPropertyName("reason")] - public AbortReason? Reason { get; set; } + /// Optional attachments (files, directories, selections, blobs, GitHub references) to include with this message. + [JsonPropertyName("attachments")] + public IList? Attachments { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. + [JsonInclude] + [JsonPropertyName("billable")] + internal bool? Billable { get; set; } -/// Parameters for shutting down the session. -[Experimental(Diagnostics.Experimental)] -internal sealed class ShutdownRequest -{ - /// Optional human-readable reason. Typically the message of the error that triggered shutdown when type is 'error'. - [JsonPropertyName("reason")] - public string? Reason { get; set; } + /// If provided, this is shown in the timeline instead of `prompt`. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// The user message text. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; - /// Why the session is being shut down. Defaults to "routine" when omitted. - [JsonPropertyName("type")] - public ShutdownType? Type { get; set; } + /// If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange. + [JsonPropertyName("requiredTool")] + public string? RequiredTool { get; set; } + + /// Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-<command-id>` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-<numeric-id>` for messages originating from a scheduled job. + [RegularExpression("^(system|command-.*|schedule-\\d+)$")] + [JsonInclude] + [JsonPropertyName("source")] + internal string? Source { get; set; } } -/// Identifier of the session event that was emitted for the log message. +/// Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. +[Experimental(Diagnostics.Experimental)] +internal sealed class SendMessagesRequest +{ + /// The UI mode the agent was in when these messages were sent. Defaults to the session's current mode. + [JsonPropertyName("agentMode")] + public SendAgentMode? AgentMode { get; set; } + + /// The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. + [JsonPropertyName("messages")] + public IList Messages { get => field ??= []; set; } + + /// How to deliver the messages. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. + [JsonPropertyName("mode")] + public SendMode? Mode { get; set; } + + /// If true, adds the messages to the front of the queue instead of the end. + [JsonPropertyName("prepend")] + public bool? Prepend { get; set; } + + /// Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. + [JsonPropertyName("requestHeaders")] + public IDictionary? RequestHeaders { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// W3C Trace Context traceparent header for distributed tracing of this agent turn. + [JsonPropertyName("traceparent")] + public string? Traceparent { get; set; } + + /// W3C Trace Context tracestate header for distributed tracing. + [JsonPropertyName("tracestate")] + public string? Tracestate { get; set; } + + /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. + [JsonPropertyName("wait")] + public bool? Wait { get; set; } +} + +/// Result of aborting the current turn. +[Experimental(Diagnostics.Experimental)] +public sealed class AbortResult +{ + /// Error message if the abort failed. + [JsonPropertyName("error")] + public string? Error { get; set; } + + /// Whether the abort completed successfully. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Parameters for aborting the current turn. +[Experimental(Diagnostics.Experimental)] +internal sealed class AbortRequest +{ + /// Finite reason code describing why the current turn was aborted. + [JsonPropertyName("reason")] + public AbortReason? Reason { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Parameters for shutting down the session. +[Experimental(Diagnostics.Experimental)] +internal sealed class ShutdownRequest +{ + /// Optional human-readable reason. Typically the message of the error that triggered shutdown when type is 'error'. + [JsonPropertyName("reason")] + public string? Reason { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Why the session is being shut down. Defaults to "routine" when omitted. + [JsonPropertyName("type")] + public ShutdownType? Type { get; set; } +} + +/// Identifier of the session event that was emitted for the log message. [Experimental(Diagnostics.Experimental)] public sealed class LogResult { @@ -3368,7 +3668,7 @@ public sealed class SessionAuthStatus /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionAuthGetStatusRequest +internal sealed class SessionGitHubAuthGetStatusRequest { /// Target session identifier. [JsonPropertyName("sessionId")] @@ -3379,6 +3679,10 @@ internal sealed class SessionAuthGetStatusRequest [Experimental(Diagnostics.Experimental)] public sealed class SessionSetCredentialsResult { + /// Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). + [JsonPropertyName("copilotUserResolved")] + public bool? CopilotUserResolved { get; set; } + /// Whether the operation succeeded. [JsonPropertyName("success")] public bool Success { get; set; } @@ -3388,7 +3692,7 @@ public sealed class SessionSetCredentialsResult [Experimental(Diagnostics.Experimental)] internal sealed class SessionSetCredentialsParams { - /// The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime stores the value verbatim and uses it for outbound model/API requests; it does NOT re-validate or re-fetch the associated Copilot user response. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. + /// The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime installs the supplied value immediately for outbound model/API requests. When the credential carries a raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous install) so plan/quota/billing metadata regains fidelity; on resolution failure the verbatim credential remains installed. It does NOT otherwise validate the credential. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. [JsonPropertyName("credentials")] public AuthInfo? Credentials { get; set; } @@ -3397,6 +3701,187 @@ internal sealed class SessionSetCredentialsParams public string SessionId { get; set; } = string.Empty; } +/// A file included in the redacted debug bundle. +[Experimental(Diagnostics.Experimental)] +public sealed class DebugCollectLogsCollectedEntry +{ + /// Relative path of the file in the staged bundle/archive. + [JsonPropertyName("bundlePath")] + public string BundlePath { get; set; } = string.Empty; + + /// Redacted output size in bytes. + [JsonPropertyName("sizeBytes")] + public long SizeBytes { get; set; } + + /// Source category for this entry. + [JsonPropertyName("source")] + public DebugCollectLogsSource Source { get; set; } +} + +/// An optional debug bundle entry that could not be included. +[Experimental(Diagnostics.Experimental)] +public sealed class DebugCollectLogsSkippedEntry +{ + /// Relative path requested for this bundle entry. + [JsonPropertyName("bundlePath")] + public string BundlePath { get; set; } = string.Empty; + + /// Server-local source path that could not be read. + [JsonPropertyName("path")] + public string? Path { get; set; } + + /// Reason the entry was skipped. + [JsonPropertyName("reason")] + public string Reason { get; set; } = string.Empty; +} + +/// Result of collecting a redacted debug bundle. +[Experimental(Diagnostics.Experimental)] +public sealed class DebugCollectLogsResult +{ + /// Files included in the redacted bundle. + [JsonPropertyName("entries")] + public IList Entries { get => field ??= []; set; } + + /// Destination kind that was written. + [JsonPropertyName("kind")] + public DebugCollectLogsResultKind Kind { get; set; } + + /// Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; + + /// Optional files or directories that could not be included. + [JsonPropertyName("skippedEntries")] + public IList? SkippedEntries { get; set; } +} + +/// A caller-provided server-local file or directory to include in the debug bundle. +[Experimental(Diagnostics.Experimental)] +public sealed class DebugCollectLogsEntry +{ + /// Relative path to use inside the staged bundle/archive. + [JsonPropertyName("bundlePath")] + public string BundlePath { get; set; } = string.Empty; + + /// Kind of source path to include. + [JsonPropertyName("kind")] + public DebugCollectLogsEntryKind Kind { get; set; } + + /// Server-local source path to read. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; + + /// How text content from this entry should be redacted. Defaults to plain-text. + [JsonPropertyName("redaction")] + public DebugCollectLogsRedaction? Redaction { get; set; } + + /// When true, collection fails if this entry cannot be read. Defaults to false, which records the entry in `skippedEntries`. + [JsonPropertyName("required")] + public bool? Required { get; set; } +} + +/// Destination for the redacted debug bundle. +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(DebugCollectLogsDestinationArchive), "archive")] +[JsonDerivedType(typeof(DebugCollectLogsDestinationDirectory), "directory")] +public partial class DebugCollectLogsDestination +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} + + +/// The archive variant of . +[Experimental(Diagnostics.Experimental)] +public partial class DebugCollectLogsDestinationArchive : DebugCollectLogsDestination +{ + /// + [JsonIgnore] + public override string Kind => "archive"; + + /// When true, create the archive atomically without overwriting an existing file by appending ` (N)` before the extension as needed. Defaults to false. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("noOverwrite")] + public bool? NoOverwrite { get; set; } + + /// Absolute or server-relative path for the .tgz archive to create. + [JsonPropertyName("outputPath")] + public required string OutputPath { get; set; } +} + +/// The directory variant of . +[Experimental(Diagnostics.Experimental)] +public partial class DebugCollectLogsDestinationDirectory : DebugCollectLogsDestination +{ + /// + [JsonIgnore] + public override string Kind => "directory"; + + /// Directory where redacted files should be staged. The directory is created if needed. + [JsonPropertyName("outputDirectory")] + public required string OutputDirectory { get; set; } +} + +/// Built-in session diagnostics to include in the bundle. Omitted fields default to true. +[Experimental(Diagnostics.Experimental)] +public sealed class DebugCollectLogsInclude +{ + /// Server-local path to the current process log. When set, it is included as `process.log` and its directory is searched for prior logs from the same session. + [JsonPropertyName("currentProcessLogPath")] + public string? CurrentProcessLogPath { get; set; } + + /// Include the session event log (`events.jsonl`). Defaults to true. + [JsonPropertyName("events")] + public bool? Events { get; set; } + + /// Server-local path to the session's events.jsonl file. Internal callers normally omit this and let the runtime derive it from the session. + [JsonPropertyName("eventsPath")] + public string? EventsPath { get; set; } + + /// Maximum number of previous process logs to include. Defaults to 5. + [JsonPropertyName("previousProcessLogLimit")] + public long? PreviousProcessLogLimit { get; set; } + + /// Server-local process log directory to search when `currentProcessLogPath` is unavailable, useful for collecting logs for inactive sessions. + [JsonPropertyName("processLogDirectory")] + public string? ProcessLogDirectory { get; set; } + + /// Include process logs for the session. Defaults to true. + [JsonPropertyName("processLogs")] + public bool? ProcessLogs { get; set; } + + /// Include interactive shell logs written under the session's `shell-logs` directory. Defaults to true. + [JsonPropertyName("shellLogs")] + public bool? ShellLogs { get; set; } +} + +/// Options for collecting a redacted session debug bundle. +[Experimental(Diagnostics.Experimental)] +internal sealed class DebugCollectLogsRequest +{ + /// Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. + [JsonPropertyName("additionalEntries")] + public IList? AdditionalEntries { get; set; } + + /// Where the redacted bundle should be written. Use `archive` to produce a .tgz, or `directory` to stage redacted files for caller-managed upload/post-processing. + [JsonPropertyName("destination")] + public DebugCollectLogsDestination Destination { get => field ??= new(); set; } + + /// Which built-in session diagnostics to include. Omitted fields default to true. + [JsonPropertyName("include")] + public DebugCollectLogsInclude? Include { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + /// Canvas action that the agent or host can invoke. To discover the input schema for a particular action, call the list_canvas_capabilities tool. [Experimental(Diagnostics.Experimental)] public sealed class CanvasAction @@ -3444,6 +3929,10 @@ public sealed class DiscoveredCanvas [JsonPropertyName("extensionName")] public string? ExtensionName { get; set; } + /// Host-local PNG path for the canvas icon, when supplied. + [JsonPropertyName("icon")] + public string? Icon { get; set; } + /// JSON Schema for canvas open input. [JsonPropertyName("inputSchema")] public JsonElement? InputSchema { get; set; } @@ -3483,6 +3972,10 @@ public sealed class OpenCanvasInstance [JsonPropertyName("extensionName")] public string? ExtensionName { get; set; } + /// Host-local PNG path for the canvas icon, when supplied. + [JsonPropertyName("icon")] + public string? Icon { get; set; } + /// Input supplied when the instance was opened. [JsonPropertyName("input")] public JsonElement? Input { get; set; } @@ -3667,6 +4160,10 @@ public sealed class ModelCapabilitiesOverrideLimits [Experimental(Diagnostics.Experimental)] public sealed class ModelCapabilitiesOverrideSupports { + /// Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + [JsonPropertyName("adaptive_thinking")] + public AdaptiveThinkingSupport? AdaptiveThinking { get; set; } + /// Whether this model supports reasoning effort configuration. [JsonPropertyName("reasoningEffort")] public bool? ReasoningEffort { get; set; } @@ -3716,6 +4213,10 @@ internal sealed class ModelSwitchToRequest /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// Output verbosity level to request for supported models. + [JsonPropertyName("verbosity")] + public Verbosity? Verbosity { get; set; } } /// Update the session's reasoning effort without changing the selected model. Use `switchTo` instead when you also need to change the model. The runtime stores the effort on the session and applies it to subsequent turns. @@ -3740,6 +4241,19 @@ internal sealed class ModelSetReasoningEffortRequest public string SessionId { get; set; } = string.Empty; } +/// Cost-category metadata for a CAPI model. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionModelPriceCategory +{ + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Gets or sets the priceCategory value. + [JsonPropertyName("priceCategory")] + public ModelPickerPriceCategory PriceCategory { get; set; } +} + /// The list of models available to this session. [Experimental(Diagnostics.Experimental)] public sealed class SessionModelList @@ -3748,6 +4262,10 @@ public sealed class SessionModelList [JsonPropertyName("list")] public IList List { get => field ??= []; set; } + /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. + [JsonPropertyName("modelPriceCategories")] + public IList? ModelPriceCategories { get; set; } + /// Per-quota snapshots returned alongside the model list, keyed by quota type. [JsonPropertyName("quotaSnapshots")] public IDictionary? QuotaSnapshots { get; set; } @@ -4128,7 +4646,7 @@ internal sealed class WorkspacesCreateFileRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `WorkspacesCheckpoints` type. +/// Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. [Experimental(Diagnostics.Experimental)] public sealed class WorkspacesCheckpoints { @@ -4290,6 +4808,75 @@ internal sealed class WorkspacesDiffRequest public string SessionId { get; set; } = string.Empty; } +/// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). +[Experimental(Diagnostics.Experimental)] +public sealed class CompletionsGetTriggerCharactersResult +{ + /// Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. + [JsonPropertyName("triggerCharacters")] + public IList TriggerCharacters { get => field ??= []; set; } +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionCompletionsGetTriggerCharactersRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` (UTF-16 code units) in the composer with `insertText`; when the range is absent, the active token around the cursor is replaced. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionCompletionItem +{ + /// Text spliced into the composer when the item is accepted. + [JsonPropertyName("insertText")] + public string InsertText { get; set; } = string.Empty; + + /// Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the host's display kind. + [JsonPropertyName("kind")] + public string? Kind { get; set; } + + /// Primary display label for the picker row. Falls back to `insertText` when absent. + [JsonPropertyName("label")] + public string? Label { get; set; } + + /// End (exclusive) of the replacement range in `text`, in UTF-16 code units. + [JsonPropertyName("rangeEnd")] + public long? RangeEnd { get; set; } + + /// Start of the replacement range in `text`, in UTF-16 code units. + [JsonPropertyName("rangeStart")] + public long? RangeStart { get; set; } +} + +/// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. +[Experimental(Diagnostics.Experimental)] +public sealed class CompletionsRequestResult +{ + /// Completion items in host-ranked order. + [JsonPropertyName("items")] + public IList Items { get => field ??= []; set; } +} + +/// Request host-driven completions for the current composer input. +[Experimental(Diagnostics.Experimental)] +internal sealed class CompletionsRequestRequest +{ + /// Cursor offset within `text`, in UTF-16 code units. + [JsonPropertyName("offset")] + public long Offset { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// The full composed composer input. + [JsonPropertyName("text")] + public string Text { get; set; } = string.Empty; +} + /// Instruction sources loaded for the session, in merge order. [Experimental(Diagnostics.Experimental)] public sealed class InstructionsGetSourcesResult @@ -4453,7 +5040,7 @@ internal sealed class TasksStartAgentRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `TaskInfo` type. +/// Tracked task union returned by task APIs, containing either an agent task or a shell task. /// Polymorphic base type discriminated by type. [Experimental(Diagnostics.Experimental)] [JsonPolymorphic( @@ -4469,7 +5056,7 @@ public partial class TaskInfo } -/// Schema for the `TaskAgentInfo` type. +/// Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. /// The agent variant of . [Experimental(Diagnostics.Experimental)] public partial class TaskInfoAgent : TaskInfo @@ -4563,7 +5150,7 @@ public partial class TaskInfoAgent : TaskInfo public required string ToolCallId { get; set; } } -/// Schema for the `TaskShellInfo` type. +/// Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. /// The shell variant of . [Experimental(Diagnostics.Experimental)] public partial class TaskInfoShell : TaskInfo @@ -4684,7 +5271,7 @@ public partial class TasksGetProgressResultProgress } -/// Schema for the `TaskProgressLine` type. +/// Timestamped display line for task progress output or recent agent activity. [Experimental(Diagnostics.Experimental)] public sealed class TaskProgressLine { @@ -4697,7 +5284,7 @@ public sealed class TaskProgressLine public DateTimeOffset Timestamp { get; set; } } -/// Schema for the `TaskAgentProgress` type. +/// Progress snapshot for an agent task, with recent activity lines and optional latest intent. /// The agent variant of . public partial class TasksGetProgressResultProgressAgent : TasksGetProgressResultProgress { @@ -4715,7 +5302,7 @@ public partial class TasksGetProgressResultProgressAgent : TasksGetProgressResul public required IList RecentActivity { get; set; } } -/// Schema for the `TaskShellProgress` type. +/// Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. /// The shell variant of . public partial class TasksGetProgressResultProgressShell : TasksGetProgressResultProgress { @@ -4891,7 +5478,7 @@ internal sealed class TasksSendMessageRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `Skill` type. +/// Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. [Experimental(Diagnostics.Experimental)] public sealed class Skill { @@ -4946,7 +5533,7 @@ internal sealed class SessionSkillsListRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `SkillsInvokedSkill` type. +/// Skill invocation record with name, path, content, allowed tools, and turn number. [Experimental(Diagnostics.Experimental)] public sealed class SkillsInvokedSkill { @@ -5101,7 +5688,7 @@ public sealed class McpHostState public IList PendingConnections { get => field ??= []; set; } } -/// Schema for the `McpServer` type. +/// MCP server status entry, including config source/plugin source and any connection error. [Experimental(Diagnostics.Experimental)] public sealed class McpServer { @@ -5155,7 +5742,20 @@ internal sealed class SessionMcpListRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `McpTools` type. +/// Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. +[Experimental(Diagnostics.Experimental)] +public sealed class McpToolUi +{ + /// URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use `session.mcp.resources.read` to fetch its HTML and resource metadata. + [JsonPropertyName("resourceUri")] + public string? ResourceUri { get; set; } + + /// Tool visibility advertised by the server. When absent, MCP Apps defaults apply. + [JsonPropertyName("visibility")] + public IList? Visibility { get; set; } +} + +/// MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery metadata. [Experimental(Diagnostics.Experimental)] public sealed class McpTools { @@ -5166,6 +5766,10 @@ public sealed class McpTools /// Tool name. [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; + + /// Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` block was present without recognized fields. + [JsonPropertyName("ui")] + public McpToolUi? Ui { get; set; } } /// Tools exposed by the connected MCP server. Throws when the server is not connected. @@ -5234,7 +5838,7 @@ internal sealed class SessionMcpReloadRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `McpAllowedServer` type. +/// MCP server allowed by policy, with server name and optional PII-free explanatory note. [Experimental(Diagnostics.Experimental)] public sealed class McpAllowedServer { @@ -5247,7 +5851,7 @@ public sealed class McpAllowedServer public string? RedactedNote { get; set; } } -/// Schema for the `McpFilteredServer` type. +/// MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. [Experimental(Diagnostics.Experimental)] public sealed class McpFilteredServer { @@ -5434,14 +6038,13 @@ internal sealed class McpConfigureGitHubRequest public string SessionId { get; set; } = string.Empty; } -/// Server name and opaque configuration for an individual MCP server start. +/// Server name and configuration for an individual MCP server start. [Experimental(Diagnostics.Experimental)] internal sealed class McpStartServerRequest { - /// Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. - [JsonInclude] + /// MCP server configuration (stdio process or remote HTTP/SSE). [JsonPropertyName("config")] - internal JsonElement Config { get; set; } + public JsonElement Config { get; set; } /// Name of the MCP server to start. [JsonPropertyName("serverName")] @@ -5452,14 +6055,13 @@ internal sealed class McpStartServerRequest public string SessionId { get; set; } = string.Empty; } -/// Server name and opaque configuration for an individual MCP server restart. +/// Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. [Experimental(Diagnostics.Experimental)] internal sealed class McpRestartServerRequest { - /// Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. - [JsonInclude] + /// Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). [JsonPropertyName("config")] - internal JsonElement Config { get; set; } + public JsonElement? Config { get; set; } /// Name of the MCP server to restart. [JsonPropertyName("serverName")] @@ -5546,30 +6148,6 @@ internal sealed class McpIsServerRunningRequest public string SessionId { get; set; } = string.Empty; } -/// Empty result after recording the MCP OAuth response. -[Experimental(Diagnostics.Experimental)] -internal sealed class McpOauthRespondResult -{ -} - -/// MCP OAuth request id and optional provider response. -[Experimental(Diagnostics.Experimental)] -internal sealed class McpOauthRespondRequest -{ - /// In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be serialized across the JSON-RPC boundary. - [JsonInclude] - [JsonPropertyName("provider")] - internal JsonElement? Provider { get; set; } - - /// OAuth request identifier from mcp.oauth_required. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} - /// Indicates whether the pending MCP OAuth response was accepted. [Experimental(Diagnostics.Experimental)] public sealed class McpOauthHandlePendingResult @@ -5612,11 +6190,6 @@ public partial class McpOauthPendingRequestResponseToken : McpOauthPendingReques [JsonPropertyName("expiresIn")] public long? ExpiresIn { get; set; } - /// Refresh token supplied by the host, if available. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("refreshToken")] - public string? RefreshToken { get; set; } - /// OAuth token type. Defaults to Bearer when omitted. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("tokenType")] @@ -5704,16 +6277,80 @@ internal sealed class McpOauthLoginRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `McpAppsResourceContent` type. +/// Indicates whether the pending MCP headers refresh response was accepted. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsResourceContent +public sealed class McpHeadersHandlePendingHeadersRefreshRequestResult { - /// Resource-level metadata (CSP, permissions, etc.). - [JsonPropertyName("_meta")] - public IDictionary? _meta { get; set; } - - /// Base64-encoded binary content. - [JsonPropertyName("blob")] + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Host response: supply dynamic headers or decline this refresh. +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(McpHeadersHandlePendingHeadersRefreshRequestHeaders), "headers")] +[JsonDerivedType(typeof(McpHeadersHandlePendingHeadersRefreshRequestNone), "none")] +public partial class McpHeadersHandlePendingHeadersRefreshRequest +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} + + +/// The headers variant of . +[Experimental(Diagnostics.Experimental)] +public partial class McpHeadersHandlePendingHeadersRefreshRequestHeaders : McpHeadersHandlePendingHeadersRefreshRequest +{ + /// + [JsonIgnore] + public override string Kind => "headers"; + + /// Headers to overlay onto the MCP request. Dynamic headers override static config headers but do not replace SDK-managed request headers. + [JsonPropertyName("headers")] + public required IDictionary Headers { get; set; } +} + +/// The none variant of . +[Experimental(Diagnostics.Experimental)] +public partial class McpHeadersHandlePendingHeadersRefreshRequestNone : McpHeadersHandlePendingHeadersRefreshRequest +{ + /// + [JsonIgnore] + public override string Kind => "none"; +} + +/// MCP headers refresh request id and the host response. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpHeadersHandlePendingHeadersRefreshRequestRequest +{ + /// Headers refresh request identifier from mcp.headers_refresh_required. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Host response: supply dynamic headers or decline this refresh. + [JsonPropertyName("result")] + public McpHeadersHandlePendingHeadersRefreshRequest Result { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource metadata. +[Experimental(Diagnostics.Experimental)] +public sealed class McpAppsResourceContent +{ + /// Resource-level metadata (CSP, permissions, etc.). + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } + + /// Base64-encoded binary content. + [JsonPropertyName("blob")] public string? Blob { get; set; } /// MIME type of the content. @@ -5985,7 +6622,259 @@ internal sealed class McpAppsDiagnoseRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `Plugin` type. +/// MCP resource content with URI, optional MIME type, text or base64 blob, and resource metadata. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourceContent +{ + /// Resource-level metadata (CSP, permissions, etc.). + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } + + /// Base64-encoded binary content. + [JsonPropertyName("blob")] + public string? Blob { get; set; } + + /// MIME type of the content. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } + + /// Text content (e.g. HTML). + [JsonPropertyName("text")] + public string? Text { get; set; } + + /// The resource URI. + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; +} + +/// Resource contents returned by the MCP server. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourcesReadResult +{ + /// Resource contents returned by the server. + [JsonPropertyName("contents")] + public IList Contents { get => field ??= []; set; } +} + +/// MCP server and resource URI to fetch. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpResourcesReadRequest +{ + /// Name of the MCP server hosting the resource. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Resource URI. + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; +} + +/// Standard MCP resource annotations plus preserved non-standard annotation fields. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourceAnnotations +{ + /// Server-provided non-standard annotation fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } + + /// Intended audience roles for this resource. + [JsonPropertyName("audience")] + public IList? Audience { get; set; } + + /// Last-modified timestamp hint. + [JsonPropertyName("lastModified")] + public string? LastModified { get; set; } + + /// Priority hint for model/client use. + [JsonPropertyName("priority")] + public double? Priority { get; set; } +} + +/// A resource icon descriptor plus preserved non-standard icon fields. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourceIcon +{ + /// Server-provided non-standard icon fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } + + /// Icon MIME type, when known. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } + + /// Icon sizes hint. + [JsonPropertyName("sizes")] + public string? Sizes { get; set; } + + /// Icon URI. + [JsonPropertyName("src")] + public string Src { get; set; } = string.Empty; + + /// Theme hint for this icon. + [JsonPropertyName("theme")] + public string? Theme { get; set; } +} + +/// An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, MIME type, size, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResource +{ + /// Resource-level metadata. + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } + + /// Server-provided non-standard descriptor fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } + + /// Model/client annotations associated with this resource. + [JsonPropertyName("annotations")] + public McpResourceAnnotations? Annotations { get; set; } + + /// Optional description of what this resource represents. + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// Icons associated with this resource. + [JsonPropertyName("icons")] + public IList? Icons { get; set; } + + /// MIME type of the resource, if known. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } + + /// The programmatic name of the resource. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Resource size in bytes, when known. + [JsonPropertyName("size")] + public long? Size { get; set; } + + /// Optional human-readable display title. + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// The resource URI (e.g. ui://... or file:///...). + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; +} + +/// One page of resources advertised by the named MCP server. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourcesListResult +{ + /// Opaque cursor for the next page, if the server has more resources. + [JsonPropertyName("nextCursor")] + public string? NextCursor { get; set; } + + /// Resources advertised by the server (proxied MCP `resources/list`). + [JsonPropertyName("resources")] + public IList Resources { get => field ??= []; set; } +} + +/// MCP server whose resources to enumerate. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpResourcesListRequest +{ + /// Opaque MCP pagination cursor from a prior `nextCursor` value. + [JsonPropertyName("cursor")] + public string? Cursor { get; set; } + + /// Name of the MCP server whose resources to enumerate. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, name, and optional title, description, MIME type, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourceTemplate +{ + /// Resource-template-level metadata. + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } + + /// Server-provided non-standard descriptor fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } + + /// Model/client annotations associated with this template. + [JsonPropertyName("annotations")] + public McpResourceAnnotations? Annotations { get; set; } + + /// Optional description of what this template is for. + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// Icons associated with resources matching this template. + [JsonPropertyName("icons")] + public IList? Icons { get; set; } + + /// MIME type for resources matching this template, if uniform. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } + + /// The programmatic name of the resource template. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Optional human-readable display title. + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// An RFC 6570 URI template for constructing resource URIs. + [JsonPropertyName("uriTemplate")] + public string UriTemplate { get; set; } = string.Empty; +} + +/// One page of resource templates advertised by the named MCP server. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourcesListTemplatesResult +{ + /// Opaque cursor for the next page, if the server has more resource templates. + [JsonPropertyName("nextCursor")] + public string? NextCursor { get; set; } + + /// Resource templates advertised by the server (proxied MCP `resources/templates/list`). + [JsonPropertyName("resourceTemplates")] + public IList ResourceTemplates { get => field ??= []; set; } +} + +/// MCP server whose resource templates to enumerate. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpResourcesListTemplatesRequest +{ + /// Opaque MCP pagination cursor from a prior `nextCursor` value. + [JsonPropertyName("cursor")] + public string? Cursor { get; set; } + + /// Name of the MCP server whose resource templates to enumerate. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Session plugin metadata, with name, marketplace, optional version, and enabled state. [Experimental(Diagnostics.Experimental)] public sealed class Plugin { @@ -6036,6 +6925,10 @@ public sealed class PluginsReloadRequest [JsonPropertyName("reloadCustomAgents")] public bool? ReloadCustomAgents { get; set; } + /// Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + [JsonPropertyName("reloadExtensions")] + public bool? ReloadExtensions { get; set; } + /// Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). [JsonPropertyName("reloadHooks")] public bool? ReloadHooks { get; set; } @@ -6057,6 +6950,10 @@ internal sealed class PluginsReloadRequestWithSession [JsonPropertyName("reloadCustomAgents")] public bool? ReloadCustomAgents { get; set; } + /// Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + [JsonPropertyName("reloadExtensions")] + public bool? ReloadExtensions { get; set; } + /// Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). [JsonPropertyName("reloadHooks")] public bool? ReloadHooks { get; set; } @@ -6273,12 +7170,16 @@ internal sealed class ProviderAddRequest [Experimental(Diagnostics.Experimental)] public sealed class SessionUpdateOptionsResult { + /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated. + [JsonPropertyName("pluginHookCount")] + public long? PluginHookCount { get; set; } + /// Whether the operation succeeded. [JsonPropertyName("success")] public bool Success { get; set; } } -/// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. +/// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. [Experimental(Diagnostics.Experimental)] public sealed class OptionsUpdateAdditionalContentExclusionPolicyRuleSource { @@ -6291,7 +7192,7 @@ public sealed class OptionsUpdateAdditionalContentExclusionPolicyRuleSource public string Type { get; set; } = string.Empty; } -/// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRule` type. +/// Single content-exclusion rule supplied to `session.options.update`, with paths, match conditions, and source. [Experimental(Diagnostics.Experimental)] public sealed class OptionsUpdateAdditionalContentExclusionPolicyRule { @@ -6307,12 +7208,12 @@ public sealed class OptionsUpdateAdditionalContentExclusionPolicyRule [JsonPropertyName("paths")] public IList Paths { get => field ??= []; set; } - /// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. + /// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. [JsonPropertyName("source")] public OptionsUpdateAdditionalContentExclusionPolicyRuleSource Source { get => field ??= new(); set; } } -/// Schema for the `OptionsUpdateAdditionalContentExclusionPolicy` type. +/// Content-exclusion policy supplied to `session.options.update`, with rules, last-updated data, and scope. [Experimental(Diagnostics.Experimental)] public sealed class OptionsUpdateAdditionalContentExclusionPolicy { @@ -6338,7 +7239,7 @@ public sealed class CapiSessionOptions public bool? EnableWebSocketResponses { get; set; } } -/// Schema for the `SessionInstalledPlugin` type. +/// Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. [Experimental(Diagnostics.Experimental)] public sealed class SessionInstalledPlugin { @@ -6475,10 +7376,6 @@ public sealed class SandboxConfigUserPolicyFilesystem [Experimental(Diagnostics.Experimental)] public sealed class SandboxConfigUserPolicyNetwork { - /// Hosts allowed in addition to the base policy. - [JsonPropertyName("allowedHosts")] - public IList? AllowedHosts { get; set; } - /// Whether traffic to local/loopback addresses is allowed. [JsonPropertyName("allowLocalNetwork")] public bool? AllowLocalNetwork { get; set; } @@ -6486,10 +7383,6 @@ public sealed class SandboxConfigUserPolicyNetwork /// Whether outbound network traffic is allowed at all. [JsonPropertyName("allowOutbound")] public bool? AllowOutbound { get; set; } - - /// Hosts explicitly blocked. - [JsonPropertyName("blockedHosts")] - public IList? BlockedHosts { get; set; } } /// macOS seatbelt-specific options. @@ -6552,6 +7445,10 @@ internal sealed class SessionUpdateOptionsParams [JsonPropertyName("agentContext")] public string? AgentContext { get; set; } + /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. + [JsonPropertyName("allowAllMcpServerInstructions")] + public bool? AllowAllMcpServerInstructions { get; set; } + /// Whether to disable the `ask_user` tool (encourages autonomous behavior). [JsonPropertyName("askUserDisabled")] public bool? AskUserDisabled { get; set; } @@ -6636,6 +7533,10 @@ internal sealed class SessionUpdateOptionsParams [JsonPropertyName("eventsLogDirectory")] public string? EventsLogDirectory { get; set; } + /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. + [JsonPropertyName("excludedBuiltinAgents")] + public IList? ExcludedBuiltinAgents { get; set; } + /// Denylist of tool names for this session. [JsonPropertyName("excludedTools")] public IList? ExcludedTools { get; set; } @@ -6644,6 +7545,10 @@ internal sealed class SessionUpdateOptionsParams [JsonPropertyName("featureFlags")] public IDictionary? FeatureFlags { get; set; } + /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. + [JsonPropertyName("includedBuiltinAgents")] + public IList? IncludedBuiltinAgents { get; set; } + /// Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. [JsonPropertyName("installedPlugins")] public IList? InstalledPlugins { get; set; } @@ -6712,6 +7617,10 @@ internal sealed class SessionUpdateOptionsParams [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + /// Optional session limits. Pass null to clear the session limits. + [JsonPropertyName("sessionLimits")] + public SessionLimitsConfig? SessionLimits { get; set; } + /// Shell init profile (`None` or `NonInteractive`). [JsonPropertyName("shellInitProfile")] public string? ShellInitProfile { get; set; } @@ -6744,6 +7653,10 @@ internal sealed class SessionUpdateOptionsParams [JsonPropertyName("trajectoryFile")] public string? TrajectoryFile { get; set; } + /// Output verbosity level for supported models. + [JsonPropertyName("verbosity")] + public Verbosity? Verbosity { get; set; } + /// Absolute working-directory path for shell tools. [JsonPropertyName("workingDirectory")] public string? WorkingDirectory { get; set; } @@ -6770,7 +7683,7 @@ internal sealed class LspInitializeRequest public string? WorkingDirectory { get; set; } } -/// Schema for the `Extension` type. +/// Discovered extension metadata, including source-qualified ID, name, discovery source, status, and optional process ID. [Experimental(Diagnostics.Experimental)] public sealed class Extension { @@ -6848,7 +7761,7 @@ internal sealed class SessionExtensionsReloadRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `PushAttachment` type. +/// Attachment union accepted by push input, covering files, directories, GitHub objects, blobs, snippets, and extension context. /// Polymorphic base type discriminated by type. [Experimental(Diagnostics.Experimental)] [JsonPolymorphic( @@ -6858,6 +7771,15 @@ internal sealed class SessionExtensionsReloadRequest [JsonDerivedType(typeof(PushAttachmentDirectory), "directory")] [JsonDerivedType(typeof(PushAttachmentSelection), "selection")] [JsonDerivedType(typeof(PushAttachmentGitHubReference), "github_reference")] +[JsonDerivedType(typeof(PushAttachmentGitHubCommit), "github_commit")] +[JsonDerivedType(typeof(PushAttachmentGitHubRelease), "github_release")] +[JsonDerivedType(typeof(PushAttachmentGitHubActionsJob), "github_actions_job")] +[JsonDerivedType(typeof(PushAttachmentGitHubRepository), "github_repository")] +[JsonDerivedType(typeof(PushAttachmentGitHubFileDiff), "github_file_diff")] +[JsonDerivedType(typeof(PushAttachmentGitHubTreeComparison), "github_tree_comparison")] +[JsonDerivedType(typeof(PushAttachmentGitHubUrl), "github_url")] +[JsonDerivedType(typeof(PushAttachmentGitHubFile), "github_file")] +[JsonDerivedType(typeof(PushAttachmentGitHubSnippet), "github_snippet")] [JsonDerivedType(typeof(PushAttachmentBlob), "blob")] [JsonDerivedType(typeof(PushAttachmentExtensionContext), "extension_context")] public partial class PushAttachment @@ -7017,44 +7939,322 @@ public partial class PushAttachmentGitHubReference : PushAttachment public required string Url { get; set; } } -/// Blob attachment with inline base64-encoded data. -/// The blob variant of . +/// Pointer to a GitHub repository. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentBlob : PushAttachment +public sealed class PushGitHubRepoRef +{ + /// Numeric GitHub repository id. + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// Repository name (without owner). + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Repository owner login (user or organization). + [JsonPropertyName("owner")] + public string Owner { get; set; } = string.Empty; +} + +/// Pointer to a GitHub commit. +/// The github_commit variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubCommit : PushAttachment { /// [JsonIgnore] - public override string Type => "blob"; + public override string Type => "github_commit"; - /// Base64-encoded content. - [Base64String] - [JsonPropertyName("data")] - public required string Data { get; set; } + /// First line of the commit message. + [JsonPropertyName("message")] + public required string Message { get; set; } - /// User-facing display name for the attachment. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("displayName")] - public string? DisplayName { get; set; } + /// Full commit SHA. + [JsonPropertyName("oid")] + public required string Oid { get; set; } - /// MIME type of the inline data. - [JsonPropertyName("mimeType")] - public required string MimeType { get; set; } + /// Repository the commit belongs to. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the commit on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } } -/// Slim input shape for extension_context attachments; identity fields are runtime-derived. -/// The extension_context variant of . +/// Pointer to a GitHub release. +/// The github_release variant of . [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentExtensionContext : PushAttachment +public partial class PushAttachmentGitHubRelease : PushAttachment { /// [JsonIgnore] - public override string Type => "extension_context"; + public override string Type => "github_release"; - /// Caller-supplied JSON payload (required, may be null but not undefined). - [JsonPropertyName("payload")] - public required JsonElement Payload { get; set; } + /// Human-readable release name. + [JsonPropertyName("name")] + public required string Name { get; set; } - /// Human-readable composer pill label. + /// Repository the release belongs to. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// Git tag the release is anchored to. + [JsonPropertyName("tagName")] + public required string TagName { get; set; } + + /// URL to the release on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a GitHub Actions job. +/// The github_actions_job variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubActionsJob : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_actions_job"; + + /// Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("conclusion")] + public string? Conclusion { get; set; } + + /// Job id within the workflow run. + [JsonPropertyName("jobId")] + public required long JobId { get; set; } + + /// Display name of the job. + [JsonPropertyName("jobName")] + public required string JobName { get; set; } + + /// Repository the workflow run belongs to. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the job on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } + + /// Display name of the workflow the job ran in. + [JsonPropertyName("workflowName")] + public required string WorkflowName { get; set; } +} + +/// Pointer to a GitHub repository. +/// The github_repository variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubRepository : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_repository"; + + /// Short description of the repository. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("ref")] + public string? Ref { get; set; } + + /// Repository pointer. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the repository on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// One side of a file diff (head or base). +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentGitHubFileDiffSide +{ + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; + + /// Git ref (branch, tag, or commit SHA) the file is read at. + [JsonPropertyName("ref")] + public string Ref { get; set; } = string.Empty; + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public PushGitHubRepoRef Repo { get => field ??= new(); set; } +} + +/// Pointer to a single-file diff. At least one of `head` and `base` must be present. +/// The github_file_diff variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubFileDiff : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_file_diff"; + + /// File location on the base side of the diff. Absent for additions. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("base")] + public PushAttachmentGitHubFileDiffSide? Base { get; set; } + + /// File location on the head side of the diff. Absent for deletions. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("head")] + public PushAttachmentGitHubFileDiffSide? Head { get; set; } + + /// URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL). + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// One side of a tree comparison (head or base). +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentGitHubTreeComparisonSide +{ + /// Repository the revision belongs to. + [JsonPropertyName("repo")] + public PushGitHubRepoRef Repo { get => field ??= new(); set; } + + /// Git revision (branch, tag, or commit SHA). + [JsonPropertyName("revision")] + public string Revision { get; set; } = string.Empty; +} + +/// Pointer to a comparison between two git revisions. +/// The github_tree_comparison variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubTreeComparison : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_tree_comparison"; + + /// Base side of the comparison. + [JsonPropertyName("base")] + public required PushAttachmentGitHubTreeComparisonSide Base { get; set; } + + /// Head side of the comparison. + [JsonPropertyName("head")] + public required PushAttachmentGitHubTreeComparisonSide Head { get; set; } + + /// URL to the comparison on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Generic GitHub URL reference. +/// The github_url variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubUrl : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_url"; + + /// URL to the GitHub resource. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a file in a GitHub repository at a specific ref. +/// The github_file variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubFile : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_file"; + + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public required string Path { get; set; } + + /// Git ref the file is read at (branch, tag, or commit SHA). + [JsonPropertyName("ref")] + public required string Ref { get; set; } + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the file on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a line range inside a file in a GitHub repository. +/// The github_snippet variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubSnippet : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_snippet"; + + /// Line range the snippet covers. + [JsonPropertyName("lineRange")] + public required PushAttachmentFileLineRange LineRange { get; set; } + + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public required string Path { get; set; } + + /// Git ref the file is read at (branch, tag, or commit SHA). + [JsonPropertyName("ref")] + public required string Ref { get; set; } + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the snippet on GitHub (with line anchor). + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Blob attachment with inline base64-encoded data. +/// The blob variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentBlob : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "blob"; + + /// Base64-encoded content. + [Base64String] + [JsonPropertyName("data")] + public required string Data { get; set; } + + /// User-facing display name for the attachment. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("displayName")] + public string? DisplayName { get; set; } + + /// MIME type of the inline data. + [JsonPropertyName("mimeType")] + public required string MimeType { get; set; } +} + +/// Slim input shape for extension_context attachments; identity fields are runtime-derived. +/// The extension_context variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentExtensionContext : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "extension_context"; + + /// Caller-supplied JSON payload (required, may be null but not undefined). + [JsonPropertyName("payload")] + public required JsonElement Payload { get; set; } + + /// Human-readable composer pill label. [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] [MinLength(1)] [JsonPropertyName("title")] @@ -7207,6 +8407,14 @@ public sealed class UpdateSubagentSettingsRequestSubagents /// Names of subagents the user has turned off; they cannot be dispatched. [JsonPropertyName("disabledSubagents")] public IList? DisabledSubagents { get; set; } + + /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only. + [JsonPropertyName("maxConcurrency")] + public int? MaxConcurrency { get; set; } + + /// Maximum subagent nesting depth; applies to usage-based billing users only. + [JsonPropertyName("maxDepth")] + public int? MaxDepth { get; set; } } /// Subagent settings to apply to the current session. @@ -7222,73 +8430,6 @@ internal sealed class UpdateSubagentSettingsRequest public UpdateSubagentSettingsRequestSubagents? Subagents { get; set; } } -/// Optional unstructured input hint. -[Experimental(Diagnostics.Experimental)] -public sealed class SlashCommandInput -{ - /// Optional completion hint for the input (e.g. 'directory' for filesystem path completion). - [JsonPropertyName("completion")] - public SlashCommandInputCompletion? Completion { get; set; } - - /// Hint to display when command input has not been provided. - [JsonPropertyName("hint")] - public string Hint { get; set; } = string.Empty; - - /// When true, clients should pass the full text after the command name as a single argument rather than splitting on whitespace. - [JsonPropertyName("preserveMultilineInput")] - public bool? PreserveMultilineInput { get; set; } - - /// When true, the command requires non-empty input; clients should render the input hint as required. - [JsonPropertyName("required")] - public bool? Required { get; set; } -} - -/// Schema for the `SlashCommandInfo` type. -[Experimental(Diagnostics.Experimental)] -public sealed class SlashCommandInfo -{ - /// Canonical aliases without leading slashes. - [JsonPropertyName("aliases")] - public IList? Aliases { get; set; } - - /// Whether the command may run while an agent turn is active. - [JsonPropertyName("allowDuringAgentExecution")] - public bool AllowDuringAgentExecution { get; set; } - - /// Human-readable command description. - [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; - - /// Whether the command is experimental. - [JsonPropertyName("experimental")] - public bool? Experimental { get; set; } - - /// Optional unstructured input hint. - [JsonPropertyName("input")] - public SlashCommandInput? Input { get; set; } - - /// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command. - [JsonPropertyName("kind")] - public SlashCommandKind Kind { get; set; } - - /// Canonical command name without a leading slash. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - - /// Whether the command may be the target of `/every` / `/after` schedules. Resolution happens at every tick, so only set this when the command is safe to re-invoke and produces an agent prompt. - [JsonPropertyName("schedulable")] - public bool? Schedulable { get; set; } -} - -/// Slash commands available in the session, after applying any include/exclude filters. -[Experimental(Diagnostics.Experimental)] -public sealed class CommandList -{ - /// Commands available in this session. - [JsonPropertyName("commands")] - public IList Commands { get => field ??= []; set; } -} - /// Optional filters controlling which command sources to include in the listing. [Experimental(Diagnostics.Experimental)] public sealed class CommandsListRequest @@ -7327,7 +8468,7 @@ internal sealed class CommandsListRequestWithSession public string SessionId { get; set; } = string.Empty; } -/// Result of invoking the slash command (text output, prompt to send to the agent, or completion). +/// Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). /// Polymorphic base type discriminated by kind. [Experimental(Diagnostics.Experimental)] [JsonPolymorphic( @@ -7345,7 +8486,7 @@ public partial class SlashCommandInvocationResult } -/// Schema for the `SlashCommandTextResult` type. +/// Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. /// The text variant of . [Experimental(Diagnostics.Experimental)] public partial class SlashCommandInvocationResultText : SlashCommandInvocationResult @@ -7374,7 +8515,7 @@ public partial class SlashCommandInvocationResultText : SlashCommandInvocationRe public required string Text { get; set; } } -/// Schema for the `SlashCommandAgentPromptResult` type. +/// Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. /// The agent-prompt variant of . [Experimental(Diagnostics.Experimental)] public partial class SlashCommandInvocationResultAgentPrompt : SlashCommandInvocationResult @@ -7392,6 +8533,11 @@ public partial class SlashCommandInvocationResultAgentPrompt : SlashCommandInvoc [JsonPropertyName("mode")] public SessionMode? Mode { get; set; } + /// Optional user-facing notice to show before the prompt is submitted. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("notice")] + public string? Notice { get; set; } + /// Prompt to submit to the agent. [JsonPropertyName("prompt")] public required string Prompt { get; set; } @@ -7402,7 +8548,7 @@ public partial class SlashCommandInvocationResultAgentPrompt : SlashCommandInvoc public bool? RuntimeSettingsChanged { get; set; } } -/// Schema for the `SlashCommandCompletedResult` type. +/// Slash-command invocation result indicating completion, with optional message and settings-change flag. /// The completed variant of . [Experimental(Diagnostics.Experimental)] public partial class SlashCommandInvocationResultCompleted : SlashCommandInvocationResult @@ -7422,7 +8568,7 @@ public partial class SlashCommandInvocationResultCompleted : SlashCommandInvocat public bool? RuntimeSettingsChanged { get; set; } } -/// Schema for the `SlashCommandSelectSubcommandOption` type. +/// Selectable slash-command subcommand option with name, description, and optional group label. [Experimental(Diagnostics.Experimental)] public sealed class SlashCommandSelectSubcommandOption { @@ -7439,7 +8585,7 @@ public sealed class SlashCommandSelectSubcommandOption public string Name { get; set; } = string.Empty; } -/// Schema for the `SlashCommandSelectSubcommandResult` type. +/// Slash-command invocation result asking the client to present subcommand options for a parent command. /// The select-subcommand variant of . [Experimental(Diagnostics.Experimental)] public partial class SlashCommandInvocationResultSelectSubcommand : SlashCommandInvocationResult @@ -7743,7 +8889,7 @@ public sealed class UIHandlePendingResult public bool Success { get; set; } } -/// Schema for the `UIUserInputResponse` type. +/// User response for a pending user-input request, with answer text and whether it was typed freeform. [Experimental(Diagnostics.Experimental)] public sealed class UIUserInputResponse { @@ -7764,7 +8910,7 @@ internal sealed class UIHandlePendingUserInputRequest [JsonPropertyName("requestId")] public string RequestId { get; set; } = string.Empty; - /// Schema for the `UIUserInputResponse` type. + /// User response for a pending user-input request, with answer text and whether it was typed freeform. [JsonPropertyName("response")] public UIUserInputResponse Response { get => field ??= new(); set; } @@ -7813,7 +8959,41 @@ internal sealed class UIHandlePendingAutoModeSwitchRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `UIExitPlanModeResponse` type. +/// The user's selected action for an exhausted session limit. +[Experimental(Diagnostics.Experimental)] +public sealed class UISessionLimitsExhaustedResponse +{ + /// Action selected by the user. + [JsonPropertyName("action")] + public UISessionLimitsExhaustedResponseAction Action { get; set; } + + /// AI Credits to add to the current max when action is 'add'. + [JsonPropertyName("additionalAiCredits")] + public double? AdditionalAiCredits { get; set; } + + /// New absolute max AI Credits when action is 'set'. + [JsonPropertyName("maxAiCredits")] + public double? MaxAiCredits { get; set; } +} + +/// Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIHandlePendingSessionLimitsExhaustedRequest +{ + /// The unique request ID from the session_limits_exhausted.requested event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// The selected session-limit action. + [JsonPropertyName("response")] + public UISessionLimitsExhaustedResponse Response { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. [Experimental(Diagnostics.Experimental)] public sealed class UIExitPlanModeResponse { @@ -7842,7 +9022,7 @@ internal sealed class UIHandlePendingExitPlanModeRequest [JsonPropertyName("requestId")] public string RequestId { get; set; } = string.Empty; - /// Schema for the `UIExitPlanModeResponse` type. + /// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. [JsonPropertyName("response")] public UIExitPlanModeResponse Response { get => field ??= new(); set; } @@ -7900,7 +9080,7 @@ public sealed class PermissionsConfigureResult public bool Success { get; set; } } -/// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. +/// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. [Experimental(Diagnostics.Experimental)] public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRuleSource { @@ -7913,7 +9093,7 @@ public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRuleSour public string Type { get; set; } = string.Empty; } -/// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRule` type. +/// Single content-exclusion rule supplied to `session.permissions.configure`, with paths, match conditions, and source. [Experimental(Diagnostics.Experimental)] public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRule { @@ -7929,12 +9109,12 @@ public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRule [JsonPropertyName("paths")] public IList Paths { get => field ??= []; set; } - /// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. + /// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. [JsonPropertyName("source")] public PermissionsConfigureAdditionalContentExclusionPolicyRuleSource Source { get => field ??= new(); set; } } -/// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. +/// Content-exclusion policy supplied to `session.permissions.configure`, with rules, last-updated data, and scope. [Experimental(Diagnostics.Experimental)] public sealed class PermissionsConfigureAdditionalContentExclusionPolicy { @@ -8069,7 +9249,7 @@ public partial class PermissionDecision } -/// Schema for the `PermissionDecisionApproveOnce` type. +/// Permission-decision request variant to approve only the current permission request. /// The approve-once variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveOnce : PermissionDecision @@ -8102,7 +9282,7 @@ public partial class PermissionDecisionApproveForSessionApproval } -/// Schema for the `PermissionDecisionApproveForSessionApprovalCommands` type. +/// Session-scoped approval details for specific command identifiers. /// The commands variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalCommands : PermissionDecisionApproveForSessionApproval @@ -8116,7 +9296,7 @@ public partial class PermissionDecisionApproveForSessionApprovalCommands : Permi public required IList CommandIdentifiers { get; set; } } -/// Schema for the `PermissionDecisionApproveForSessionApprovalRead` type. +/// Session-scoped approval details for read-only filesystem operations. /// The read variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalRead : PermissionDecisionApproveForSessionApproval @@ -8126,7 +9306,7 @@ public partial class PermissionDecisionApproveForSessionApprovalRead : Permissio public override string Kind => "read"; } -/// Schema for the `PermissionDecisionApproveForSessionApprovalWrite` type. +/// Session-scoped approval details for filesystem write operations. /// The write variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalWrite : PermissionDecisionApproveForSessionApproval @@ -8136,7 +9316,7 @@ public partial class PermissionDecisionApproveForSessionApprovalWrite : Permissi public override string Kind => "write"; } -/// Schema for the `PermissionDecisionApproveForSessionApprovalMcp` type. +/// Session-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. /// The mcp variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalMcp : PermissionDecisionApproveForSessionApproval @@ -8154,7 +9334,7 @@ public partial class PermissionDecisionApproveForSessionApprovalMcp : Permission public string? ToolName { get; set; } } -/// Schema for the `PermissionDecisionApproveForSessionApprovalMcpSampling` type. +/// Session-scoped approval details for MCP sampling requests from a server. /// The mcp-sampling variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalMcpSampling : PermissionDecisionApproveForSessionApproval @@ -8168,7 +9348,7 @@ public partial class PermissionDecisionApproveForSessionApprovalMcpSampling : Pe public required string ServerName { get; set; } } -/// Schema for the `PermissionDecisionApproveForSessionApprovalMemory` type. +/// Session-scoped approval details for writes to long-term memory. /// The memory variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalMemory : PermissionDecisionApproveForSessionApproval @@ -8178,7 +9358,7 @@ public partial class PermissionDecisionApproveForSessionApprovalMemory : Permiss public override string Kind => "memory"; } -/// Schema for the `PermissionDecisionApproveForSessionApprovalCustomTool` type. +/// Session-scoped approval details for a custom tool, keyed by tool name. /// The custom-tool variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalCustomTool : PermissionDecisionApproveForSessionApproval @@ -8192,7 +9372,7 @@ public partial class PermissionDecisionApproveForSessionApprovalCustomTool : Per public required string ToolName { get; set; } } -/// Schema for the `PermissionDecisionApproveForSessionApprovalExtensionManagement` type. +/// Session-scoped approval details for extension-management operations, optionally narrowed by operation. /// The extension-management variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalExtensionManagement : PermissionDecisionApproveForSessionApproval @@ -8207,7 +9387,7 @@ public partial class PermissionDecisionApproveForSessionApprovalExtensionManagem public string? Operation { get; set; } } -/// Schema for the `PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess` type. +/// Session-scoped approval details for an extension's permission-gated capability access, keyed by extension name. /// The extension-permission-access variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess : PermissionDecisionApproveForSessionApproval @@ -8221,7 +9401,7 @@ public partial class PermissionDecisionApproveForSessionApprovalExtensionPermiss public required string ExtensionName { get; set; } } -/// Schema for the `PermissionDecisionApproveForSession` type. +/// Permission-decision request variant to approve for the rest of the session, with optional tool approval or URL domain. /// The approve-for-session variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForSession : PermissionDecision @@ -8264,7 +9444,7 @@ public partial class PermissionDecisionApproveForLocationApproval } -/// Schema for the `PermissionDecisionApproveForLocationApprovalCommands` type. +/// Location-scoped approval details for specific command identifiers. /// The commands variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalCommands : PermissionDecisionApproveForLocationApproval @@ -8278,7 +9458,7 @@ public partial class PermissionDecisionApproveForLocationApprovalCommands : Perm public required IList CommandIdentifiers { get; set; } } -/// Schema for the `PermissionDecisionApproveForLocationApprovalRead` type. +/// Location-scoped approval details for read-only filesystem operations. /// The read variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalRead : PermissionDecisionApproveForLocationApproval @@ -8288,7 +9468,7 @@ public partial class PermissionDecisionApproveForLocationApprovalRead : Permissi public override string Kind => "read"; } -/// Schema for the `PermissionDecisionApproveForLocationApprovalWrite` type. +/// Location-scoped approval details for filesystem write operations. /// The write variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalWrite : PermissionDecisionApproveForLocationApproval @@ -8298,7 +9478,7 @@ public partial class PermissionDecisionApproveForLocationApprovalWrite : Permiss public override string Kind => "write"; } -/// Schema for the `PermissionDecisionApproveForLocationApprovalMcp` type. +/// Location-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. /// The mcp variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalMcp : PermissionDecisionApproveForLocationApproval @@ -8316,7 +9496,7 @@ public partial class PermissionDecisionApproveForLocationApprovalMcp : Permissio public string? ToolName { get; set; } } -/// Schema for the `PermissionDecisionApproveForLocationApprovalMcpSampling` type. +/// Location-scoped approval details for MCP sampling requests from a server. /// The mcp-sampling variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalMcpSampling : PermissionDecisionApproveForLocationApproval @@ -8330,7 +9510,7 @@ public partial class PermissionDecisionApproveForLocationApprovalMcpSampling : P public required string ServerName { get; set; } } -/// Schema for the `PermissionDecisionApproveForLocationApprovalMemory` type. +/// Location-scoped approval details for writes to long-term memory. /// The memory variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalMemory : PermissionDecisionApproveForLocationApproval @@ -8340,7 +9520,7 @@ public partial class PermissionDecisionApproveForLocationApprovalMemory : Permis public override string Kind => "memory"; } -/// Schema for the `PermissionDecisionApproveForLocationApprovalCustomTool` type. +/// Location-scoped approval details for a custom tool, keyed by tool name. /// The custom-tool variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalCustomTool : PermissionDecisionApproveForLocationApproval @@ -8354,7 +9534,7 @@ public partial class PermissionDecisionApproveForLocationApprovalCustomTool : Pe public required string ToolName { get; set; } } -/// Schema for the `PermissionDecisionApproveForLocationApprovalExtensionManagement` type. +/// Location-scoped approval details for extension-management operations, optionally narrowed by operation. /// The extension-management variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalExtensionManagement : PermissionDecisionApproveForLocationApproval @@ -8369,7 +9549,7 @@ public partial class PermissionDecisionApproveForLocationApprovalExtensionManage public string? Operation { get; set; } } -/// Schema for the `PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess` type. +/// Location-scoped approval details for an extension's permission-gated capability access, keyed by extension name. /// The extension-permission-access variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess : PermissionDecisionApproveForLocationApproval @@ -8383,7 +9563,7 @@ public partial class PermissionDecisionApproveForLocationApprovalExtensionPermis public required string ExtensionName { get; set; } } -/// Schema for the `PermissionDecisionApproveForLocation` type. +/// Permission-decision request variant to approve and persist a permission for a project location, with approval details and location key. /// The approve-for-location variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproveForLocation : PermissionDecision @@ -8401,7 +9581,7 @@ public partial class PermissionDecisionApproveForLocation : PermissionDecision public required string LocationKey { get; set; } } -/// Schema for the `PermissionDecisionApprovePermanently` type. +/// Permission-decision request variant to permanently approve a URL domain across sessions. /// The approve-permanently variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApprovePermanently : PermissionDecision @@ -8415,7 +9595,7 @@ public partial class PermissionDecisionApprovePermanently : PermissionDecision public required string Domain { get; set; } } -/// Schema for the `PermissionDecisionReject` type. +/// Permission-decision request variant to reject a pending permission request, with optional feedback. /// The reject variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionReject : PermissionDecision @@ -8430,7 +9610,7 @@ public partial class PermissionDecisionReject : PermissionDecision public string? Feedback { get; set; } } -/// Schema for the `PermissionDecisionUserNotAvailable` type. +/// Permission-decision variant indicating no user was available to confirm the request. /// The user-not-available variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionUserNotAvailable : PermissionDecision @@ -8440,7 +9620,7 @@ public partial class PermissionDecisionUserNotAvailable : PermissionDecision public override string Kind => "user-not-available"; } -/// Schema for the `PermissionDecisionApproved` type. +/// Permission-decision variant indicating the request was approved. /// The approved variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApproved : PermissionDecision @@ -8450,7 +9630,7 @@ public partial class PermissionDecisionApproved : PermissionDecision public override string Kind => "approved"; } -/// Schema for the `PermissionDecisionApprovedForSession` type. +/// Permission-decision variant indicating approval was remembered for the session, with approval details. /// The approved-for-session variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApprovedForSession : PermissionDecision @@ -8464,7 +9644,7 @@ public partial class PermissionDecisionApprovedForSession : PermissionDecision public required UserToolSessionApproval Approval { get; set; } } -/// Schema for the `PermissionDecisionApprovedForLocation` type. +/// Permission-decision variant indicating approval was persisted for a project location, with approval details and location key. /// The approved-for-location variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionApprovedForLocation : PermissionDecision @@ -8482,7 +9662,7 @@ public partial class PermissionDecisionApprovedForLocation : PermissionDecision public required string LocationKey { get; set; } } -/// Schema for the `PermissionDecisionCancelled` type. +/// Permission-decision variant indicating the request was cancelled before use, with an optional reason. /// The cancelled variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionCancelled : PermissionDecision @@ -8497,7 +9677,7 @@ public partial class PermissionDecisionCancelled : PermissionDecision public string? Reason { get; set; } } -/// Schema for the `PermissionDecisionDeniedByRules` type. +/// Permission-decision variant indicating explicit denial by permission rules, with the matching rules. /// The denied-by-rules variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionDeniedByRules : PermissionDecision @@ -8511,7 +9691,7 @@ public partial class PermissionDecisionDeniedByRules : PermissionDecision public required IList Rules { get; set; } } -/// Schema for the `PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. +/// Permission-decision variant indicating no approval rule matched and user confirmation was unavailable. /// The denied-no-approval-rule-and-could-not-request-from-user variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser : PermissionDecision @@ -8521,7 +9701,7 @@ public partial class PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFro public override string Kind => "denied-no-approval-rule-and-could-not-request-from-user"; } -/// Schema for the `PermissionDecisionDeniedInteractivelyByUser` type. +/// Permission-decision variant indicating the user denied an interactive prompt, with optional feedback and force-reject flag. /// The denied-interactively-by-user variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionDeniedInteractivelyByUser : PermissionDecision @@ -8541,7 +9721,7 @@ public partial class PermissionDecisionDeniedInteractivelyByUser : PermissionDec public bool? ForceReject { get; set; } } -/// Schema for the `PermissionDecisionDeniedByContentExclusionPolicy` type. +/// Permission-decision variant indicating denial by content-exclusion policy, with path and message. /// The denied-by-content-exclusion-policy variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionDeniedByContentExclusionPolicy : PermissionDecision @@ -8559,7 +9739,7 @@ public partial class PermissionDecisionDeniedByContentExclusionPolicy : Permissi public required string Path { get; set; } } -/// Schema for the `PermissionDecisionDeniedByPermissionRequestHook` type. +/// Permission-decision variant indicating denial by a permission request hook, with optional message and interrupt flag. /// The denied-by-permission-request-hook variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionDecisionDeniedByPermissionRequestHook : PermissionDecision @@ -8596,7 +9776,7 @@ internal sealed class PermissionDecisionRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `PendingPermissionRequest` type. +/// Pending permission prompt reconstructed from event history, with request ID and user-facing prompt details. [Experimental(Diagnostics.Experimental)] public sealed class PendingPermissionRequest { @@ -8657,22 +9837,34 @@ internal sealed class PermissionsSetApproveAllRequest [Experimental(Diagnostics.Experimental)] public sealed class AllowAllPermissionSetResult { - /// Authoritative allow-all state after the mutation. + /// Authoritative full allow-all state after the mutation. [JsonPropertyName("enabled")] public bool Enabled { get; set; } + /// Authoritative allow-all mode after the mutation. + [JsonPropertyName("mode")] + public PermissionsAllowAllMode? Mode { get; set; } + /// Whether the operation succeeded. [JsonPropertyName("success")] public bool Success { get; set; } } -/// Whether to enable full allow-all permissions for the session. +/// Allow-all mode to apply for the session. [Experimental(Diagnostics.Experimental)] internal sealed class PermissionsSetAllowAllRequest { - /// Whether to enable full allow-all permissions. + /// Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + public bool? Enabled { get; set; } + + /// Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM auto-approval; `off` disables both. + [JsonPropertyName("mode")] + public PermissionsAllowAllMode? Mode { get; set; } + + /// Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. + [JsonPropertyName("model")] + public string? Model { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] @@ -8683,13 +9875,17 @@ internal sealed class PermissionsSetAllowAllRequest public PermissionsSetAllowAllSource? Source { get; set; } } -/// Current full allow-all permission state. +/// Current allow-all permission mode. [Experimental(Diagnostics.Experimental)] public sealed class AllowAllPermissionState { /// Whether full allow-all permissions are currently active. [JsonPropertyName("enabled")] public bool Enabled { get; set; } + + /// Current allow-all mode. + [JsonPropertyName("mode")] + public PermissionsAllowAllMode? Mode { get; set; } } /// No parameters. @@ -9007,7 +10203,7 @@ public partial class PermissionsLocationsAddToolApprovalDetails } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsCommands` type. +/// Location-persisted tool approval details for specific command identifiers. /// The commands variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsCommands : PermissionsLocationsAddToolApprovalDetails @@ -9021,7 +10217,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsCommands : Permis public required IList CommandIdentifiers { get; set; } } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsRead` type. +/// Location-persisted tool approval details for read-only filesystem operations. /// The read variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsRead : PermissionsLocationsAddToolApprovalDetails @@ -9031,7 +10227,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsRead : Permission public override string Kind => "read"; } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsWrite` type. +/// Location-persisted tool approval details for filesystem write operations. /// The write variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsWrite : PermissionsLocationsAddToolApprovalDetails @@ -9041,7 +10237,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsWrite : Permissio public override string Kind => "write"; } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsMcp` type. +/// Location-persisted tool approval details for an MCP server tool, or all tools when `toolName` is null. /// The mcp variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsMcp : PermissionsLocationsAddToolApprovalDetails @@ -9059,7 +10255,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsMcp : Permissions public string? ToolName { get; set; } } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsMcpSampling` type. +/// Location-persisted tool approval details for MCP sampling requests from a server. /// The mcp-sampling variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsMcpSampling : PermissionsLocationsAddToolApprovalDetails @@ -9073,7 +10269,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsMcpSampling : Per public required string ServerName { get; set; } } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsMemory` type. +/// Location-persisted tool approval details for writes to long-term memory. /// The memory variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsMemory : PermissionsLocationsAddToolApprovalDetails @@ -9083,7 +10279,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsMemory : Permissi public override string Kind => "memory"; } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsCustomTool` type. +/// Location-persisted tool approval details for a custom tool, keyed by tool name. /// The custom-tool variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsCustomTool : PermissionsLocationsAddToolApprovalDetails @@ -9097,7 +10293,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsCustomTool : Perm public required string ToolName { get; set; } } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionManagement` type. +/// Location-persisted tool approval details for extension-management operations, optionally narrowed by operation. /// The extension-management variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsExtensionManagement : PermissionsLocationsAddToolApprovalDetails @@ -9112,7 +10308,7 @@ public partial class PermissionsLocationsAddToolApprovalDetailsExtensionManageme public string? Operation { get; set; } } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess` type. +/// Location-persisted tool approval details for an extension's permission-gated capability access, keyed by extension name. /// The extension-permission-access variant of . [Experimental(Diagnostics.Experimental)] public partial class PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess : PermissionsLocationsAddToolApprovalDetails @@ -9333,6 +10529,10 @@ public sealed class SessionMetadataSnapshot [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + /// Current session limits, or null when no limits are active. + [JsonPropertyName("sessionLimits")] + public SessionLimitsConfig? SessionLimits { get; set; } + /// ISO 8601 timestamp of when the session started. [JsonPropertyName("startTime")] public DateTimeOffset StartTime { get; set; } @@ -9477,9 +10677,126 @@ internal sealed class MetadataContextInfoRequest public string SessionId { get; set; } = string.Empty; } -/// Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). -[Experimental(Diagnostics.Experimental)] -public sealed class MetadataRecordContextChangeResult +/// Successful compaction history for the session. +public sealed class MetadataContextAttributionResultContextAttributionCompactions +{ + /// Number of successful compactions in this session. + [JsonPropertyName("count")] + public long Count { get; set; } +} + +/// RPC data type for MetadataContextAttributionResultContextAttributionEntry operations. +public sealed class MetadataContextAttributionResultContextAttributionEntry +{ + /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + [JsonPropertyName("attributes")] + public IDictionary? Attributes { get; set; } + + /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + [JsonPropertyName("kind")] + public string Kind { get; set; } = string.Empty; + + /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + [JsonPropertyName("label")] + public string Label { get; set; } = string.Empty; + + /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + [JsonPropertyName("parentId")] + public string? ParentId { get; set; } + + /// Token count currently in context attributable to this entry. + [JsonPropertyName("tokens")] + public long Tokens { get; set; } +} + +/// Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. +public sealed class MetadataContextAttributionResultContextAttribution +{ + /// Successful compaction history for the session. + [JsonPropertyName("compactions")] + public MetadataContextAttributionResultContextAttributionCompactions Compactions { get => field ??= new(); set; } + + /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + [JsonPropertyName("entries")] + public IList Entries { get => field ??= []; set; } + + /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + [JsonPropertyName("totalTokens")] + public long TotalTokens { get; set; } +} + +/// Per-source attribution breakdown for the session's current context window, or null if uninitialized. +[Experimental(Diagnostics.Experimental)] +public sealed class MetadataContextAttributionResult +{ + /// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + [JsonPropertyName("contextAttribution")] + public MetadataContextAttributionResultContextAttribution? ContextAttribution { get; set; } +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionMetadataGetContextAttributionRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// A single large message currently in context. +[Experimental(Diagnostics.Experimental)] +public sealed class ContextHeaviestMessage +{ + /// Stable identifier for this message within the snapshot. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. + [JsonPropertyName("label")] + public string Label { get; set; } = string.Empty; + + /// Role of the chat message (`user`, `assistant`, or `tool`). + [JsonPropertyName("role")] + public string Role { get; set; } = string.Empty; + + /// Token count currently in context for this individual message. + [JsonPropertyName("tokens")] + public long Tokens { get; set; } +} + +/// The heaviest individual messages in the session's context window, most-expensive first. +[Experimental(Diagnostics.Experimental)] +public sealed class MetadataContextHeaviestMessagesResult +{ + /// Heaviest messages, most-expensive first. + [JsonPropertyName("messages")] + public IList Messages { get => field ??= []; set; } + + /// Total token count of the current context window, so callers can compute each message's share without a second call. + [JsonPropertyName("totalTokens")] + public long TotalTokens { get; set; } +} + +/// Parameters for the heaviest-messages query. +[Experimental(Diagnostics.Experimental)] +internal sealed class MetadataContextHeaviestMessagesRequest +{ + /// Maximum number of messages to return, most-expensive first. Omit for the server default. + [JsonPropertyName("limit")] + public long? Limit { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). +[Experimental(Diagnostics.Experimental)] +public sealed class MetadataRecordContextChangeResult { } @@ -9533,7 +10850,7 @@ internal sealed class MetadataRecordContextChangeRequest public string SessionId { get; set; } = string.Empty; } -/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. +/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. [Experimental(Diagnostics.Experimental)] public sealed class MetadataSetWorkingDirectoryResult { @@ -9542,7 +10859,7 @@ public sealed class MetadataSetWorkingDirectoryResult public string WorkingDirectory { get; set; } = string.Empty; } -/// Absolute path to set as the session's new working directory. +/// Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. [Experimental(Diagnostics.Experimental)] internal sealed class MetadataSetWorkingDirectoryRequest { @@ -9585,6 +10902,240 @@ internal sealed class MetadataRecomputeContextTokensRequest public string SessionId { get; set; } = string.Empty; } +/// Availability of built-in job tools surfaced to boundary consumers. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionSettingsBuiltInToolAvailabilitySnapshot +{ + /// Gets or sets the createPullRequest value. + [JsonPropertyName("createPullRequest")] + public bool? CreatePullRequest { get; set; } + + /// Gets or sets the reportProgress value. + [JsonPropertyName("reportProgress")] + public bool? ReportProgress { get; set; } +} + +/// Redacted job settings for a session. The job nonce is excluded. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionSettingsJobSnapshot +{ + /// Gets or sets the builtInToolAvailability value. + [JsonPropertyName("builtInToolAvailability")] + public SessionSettingsBuiltInToolAvailabilitySnapshot? BuiltInToolAvailability { get; set; } + + /// Gets or sets the eventType value. + [JsonPropertyName("eventType")] + public string? EventType { get; set; } + + /// Gets or sets the isTriggerJob value. + [JsonPropertyName("isTriggerJob")] + public bool? IsTriggerJob { get; set; } +} + +/// Redacted model routing settings for a session. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionSettingsModelSnapshot +{ + /// Gets or sets the callbackUrl value. + [JsonPropertyName("callbackUrl")] + public string? CallbackUrl { get; set; } + + /// Gets or sets the defaultReasoningEffort value. + [JsonPropertyName("defaultReasoningEffort")] + public string? DefaultReasoningEffort { get; set; } + + /// Gets or sets the instanceId value. + [JsonPropertyName("instanceId")] + public string? InstanceId { get; set; } + + /// Gets or sets the model value. + [JsonPropertyName("model")] + public string? Model { get; set; } +} + +/// Online-evaluation settings safe to expose across the SDK boundary. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionSettingsOnlineEvaluationSnapshot +{ + /// Gets or sets the disableOnlineEvaluation value. + [JsonPropertyName("disableOnlineEvaluation")] + public bool? DisableOnlineEvaluation { get; set; } + + /// Gets or sets the enableOnlineEvaluationOutputFile value. + [JsonPropertyName("enableOnlineEvaluationOutputFile")] + public bool? EnableOnlineEvaluationOutputFile { get; set; } +} + +/// Redacted repository and GitHub host settings for a session. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionSettingsRepoSnapshot +{ + /// Gets or sets the branch value. + [JsonPropertyName("branch")] + public string? Branch { get; set; } + + /// Gets or sets the commit value. + [JsonPropertyName("commit")] + public string? Commit { get; set; } + + /// Gets or sets the host value. + [JsonPropertyName("host")] + public string? Host { get; set; } + + /// Gets or sets the hostProtocol value. + [JsonPropertyName("hostProtocol")] + public string? HostProtocol { get; set; } + + /// Gets or sets the id value. + [JsonPropertyName("id")] + public double? Id { get; set; } + + /// Gets or sets the name value. + [JsonPropertyName("name")] + public string? Name { get; set; } + + /// Gets or sets the ownerId value. + [JsonPropertyName("ownerId")] + public double? OwnerId { get; set; } + + /// Gets or sets the ownerName value. + [JsonPropertyName("ownerName")] + public string? OwnerName { get; set; } + + /// Gets or sets the prCommitCount value. + [JsonPropertyName("prCommitCount")] + public double? PrCommitCount { get; set; } + + /// Gets or sets the readWrite value. + [JsonPropertyName("readWrite")] + public bool? ReadWrite { get; set; } + + /// Gets or sets the secretScanningUrl value. + [JsonPropertyName("secretScanningUrl")] + public string? SecretScanningUrl { get; set; } + + /// Gets or sets the serverUrl value. + [JsonPropertyName("serverUrl")] + public string? ServerUrl { get; set; } +} + +/// Redacted validation and memory-tool settings for a session. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionSettingsValidationSnapshot +{ + /// Gets or sets the advisoryEnabled value. + [JsonPropertyName("advisoryEnabled")] + public bool? AdvisoryEnabled { get; set; } + + /// Gets or sets the codeqlEnabled value. + [JsonPropertyName("codeqlEnabled")] + public bool? CodeqlEnabled { get; set; } + + /// Gets or sets the codeReviewEnabled value. + [JsonPropertyName("codeReviewEnabled")] + public bool? CodeReviewEnabled { get; set; } + + /// Gets or sets the codeReviewModel value. + [JsonPropertyName("codeReviewModel")] + public string? CodeReviewModel { get; set; } + + /// Gets or sets the dependabotTimeout value. + [JsonPropertyName("dependabotTimeout")] + public double? DependabotTimeout { get; set; } + + /// Gets or sets the memoryStoreEnabled value. + [JsonPropertyName("memoryStoreEnabled")] + public bool? MemoryStoreEnabled { get; set; } + + /// Gets or sets the memoryVoteEnabled value. + [JsonPropertyName("memoryVoteEnabled")] + public bool? MemoryVoteEnabled { get; set; } + + /// Gets or sets the secretScanningEnabled value. + [JsonPropertyName("secretScanningEnabled")] + public bool? SecretScanningEnabled { get; set; } + + /// Gets or sets the timeout value. + [JsonPropertyName("timeout")] + public double? Timeout { get; set; } +} + +/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionSettingsSnapshot +{ + /// Gets or sets the clientName value. + [JsonPropertyName("clientName")] + public string? ClientName { get; set; } + + /// Gets or sets the job value. + [JsonPropertyName("job")] + public SessionSettingsJobSnapshot Job { get => field ??= new(); set; } + + /// Gets or sets the model value. + [JsonPropertyName("model")] + public SessionSettingsModelSnapshot Model { get => field ??= new(); set; } + + /// Gets or sets the onlineEvaluation value. + [JsonPropertyName("onlineEvaluation")] + public SessionSettingsOnlineEvaluationSnapshot OnlineEvaluation { get => field ??= new(); set; } + + /// Gets or sets the repo value. + [JsonPropertyName("repo")] + public SessionSettingsRepoSnapshot Repo { get => field ??= new(); set; } + + /// Gets or sets the startTimeMs value. + [JsonPropertyName("startTimeMs")] + public double? StartTimeMs { get; set; } + + /// Gets or sets the timeoutMs value. + [JsonPropertyName("timeoutMs")] + public double? TimeoutMs { get; set; } + + /// Gets or sets the validation value. + [JsonPropertyName("validation")] + public SessionSettingsValidationSnapshot Validation { get => field ??= new(); set; } + + /// Gets or sets the version value. + [JsonPropertyName("version")] + public string? Version { get; set; } +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionSettingsSnapshotRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Result of evaluating a Rust-owned settings predicate. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionSettingsEvaluatePredicateResult +{ + /// Gets or sets the enabled value. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } +} + +/// Named Rust-owned settings predicate to evaluate for this session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionSettingsEvaluatePredicateRequest +{ + /// Predicate name. The runtime owns the raw feature-flag names and composition logic. + [JsonPropertyName("name")] + public SessionSettingsPredicateName Name { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Tool name for tool-scoped predicates such as trivial-change handling. + [JsonPropertyName("toolName")] + public string? ToolName { get; set; } +} + /// Identifier of the spawned process, used to correlate streamed output and exit notifications. [Experimental(Diagnostics.Experimental)] public sealed class ShellExecResult @@ -9862,7 +11413,7 @@ internal sealed class SessionHistorySummarizeForHandoffRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `QueuePendingItems` type. +/// User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. [Experimental(Diagnostics.Experimental)] public sealed class QueuePendingItems { @@ -10006,7 +11557,7 @@ public sealed class RegisterEventInterestResult [Experimental(Diagnostics.Experimental)] internal sealed class RegisterEventInterestParams { - /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates the full interactive OAuth flow to the consumer; when no interest is registered the runtime installs a browserless fallback that silently reuses cached tokens). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. + /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. [JsonPropertyName("eventType")] public string EventType { get; set; } = string.Empty; @@ -10071,7 +11622,7 @@ public sealed class UsageMetricsModelMetricRequests public long Count { get; set; } } -/// Schema for the `UsageMetricsModelMetricTokenDetail` type. +/// Per-model token-detail entry containing the accumulated token count for one token type. [Experimental(Diagnostics.Experimental)] public sealed class UsageMetricsModelMetricTokenDetail { @@ -10105,7 +11656,7 @@ public sealed class UsageMetricsModelMetricUsage public long? ReasoningTokens { get; set; } } -/// Schema for the `UsageMetricsModelMetric` type. +/// Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. [Experimental(Diagnostics.Experimental)] public sealed class UsageMetricsModelMetric { @@ -10126,7 +11677,7 @@ public sealed class UsageMetricsModelMetric public UsageMetricsModelMetricUsage Usage { get => field ??= new(); set; } } -/// Schema for the `UsageMetricsTokenDetail` type. +/// Session-wide token-detail entry containing the accumulated token count for one token type. [Experimental(Diagnostics.Experimental)] public sealed class UsageMetricsTokenDetail { @@ -10250,7 +11801,67 @@ internal sealed class RemoteNotifySteerableChangedRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `ScheduleEntry` type. +/// Current sharing status and shareable GitHub URL for a session. +[Experimental(Diagnostics.Experimental)] +public sealed class VisibilityGetResult +{ + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("shareUrl")] + public string? ShareUrl { get; set; } + + /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). + [JsonPropertyName("status")] + public SessionVisibilityStatus? Status { get; set; } + + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. + [JsonPropertyName("synced")] + public bool Synced { get; set; } +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionVisibilityGetRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Effective sharing status and shareable GitHub URL after updating session visibility. +[Experimental(Diagnostics.Experimental)] +public sealed class VisibilitySetResult +{ + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("shareUrl")] + public string? ShareUrl { get; set; } + + /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). + [JsonPropertyName("status")] + public SessionVisibilityStatus? Status { get; set; } + + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. + [JsonPropertyName("synced")] + public bool Synced { get; set; } +} + +/// Desired sharing status for the session. +[Experimental(Diagnostics.Experimental)] +internal sealed class VisibilitySetRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. + [JsonPropertyName("status")] + public SessionVisibilityStatus Status { get; set; } +} + +/// Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. [Experimental(Diagnostics.Experimental)] public sealed class ScheduleEntry { @@ -10346,6 +11957,7 @@ public sealed class ProviderTokenAcquireResult } /// Asks the SDK client to acquire a bearer token for a BYOK provider whose config set `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; the runtime does no caching, so this is sent once per request. +[Experimental(Diagnostics.Experimental)] public sealed class ProviderTokenAcquireRequest { /// Name of the BYOK provider needing a token. For the legacy whole-session `provider` this is the implicit provider name; for named providers it is `NamedProviderConfig.name`. @@ -10384,6 +11996,7 @@ public sealed class SessionFsReadFileResult } /// Path of the file to read from the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsReadFileRequest { /// Path using SessionFs conventions. @@ -10396,6 +12009,7 @@ public sealed class SessionFsReadFileRequest } /// File path, content to write, and optional mode for the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsWriteFileRequest { /// Content to write. @@ -10416,6 +12030,7 @@ public sealed class SessionFsWriteFileRequest } /// File path, content to append, and optional mode for the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsAppendFileRequest { /// Content to append. @@ -10445,6 +12060,7 @@ public sealed class SessionFsExistsResult } /// Path to test for existence in the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsExistsRequest { /// Path using SessionFs conventions. @@ -10486,6 +12102,7 @@ public sealed class SessionFsStatResult } /// Path whose metadata should be returned from the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsStatRequest { /// Path using SessionFs conventions. @@ -10498,6 +12115,7 @@ public sealed class SessionFsStatRequest } /// Directory path to create in the client-provided session filesystem, with options for recursive creation and POSIX mode. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsMkdirRequest { /// Optional POSIX-style mode for newly created directories. @@ -10531,6 +12149,7 @@ public sealed class SessionFsReaddirResult } /// Directory path whose entries should be listed from the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsReaddirRequest { /// Path using SessionFs conventions. @@ -10542,7 +12161,7 @@ public sealed class SessionFsReaddirRequest public string SessionId { get; set; } = string.Empty; } -/// Schema for the `SessionFsReaddirWithTypesEntry` type. +/// Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. [Experimental(Diagnostics.Experimental)] public sealed class SessionFsReaddirWithTypesEntry { @@ -10569,6 +12188,7 @@ public sealed class SessionFsReaddirWithTypesResult } /// Directory path whose entries (with type information) should be listed from the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsReaddirWithTypesRequest { /// Path using SessionFs conventions. @@ -10581,6 +12201,7 @@ public sealed class SessionFsReaddirWithTypesRequest } /// Path to remove from the client-provided session filesystem, with options for recursive removal and force. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsRmRequest { /// Ignore errors if the path does not exist. @@ -10601,6 +12222,7 @@ public sealed class SessionFsRmRequest } /// Source and destination paths for renaming or moving an entry in the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsRenameRequest { /// Destination path using SessionFs conventions. @@ -10642,6 +12264,7 @@ public sealed class SessionFsSqliteQueryResult } /// SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. +[Experimental(Diagnostics.Experimental)] public sealed class SessionFsSqliteQueryRequest { /// Optional named bind parameters. @@ -10831,14 +12454,26 @@ public sealed class LlmInferenceHttpRequestStartResult [Experimental(Diagnostics.Experimental)] public sealed class LlmInferenceHttpRequestStartRequest { + /// Stable per-agent-instance id attributing this request to a specific agent trajectory. Present when the request originates from an agent turn; absent for requests issued outside any agent context (e.g. some SDK callers). A request with an `agentId` but no `parentAgentId` is a root-agent request; one carrying both is a subagent request. Sourced from the runtime's per-request agent context and surfaced on the envelope independently of transport, so it is available for both first-party (CAPI) and BYOK/custom-provider requests; on the CAPI transport the runtime derives the upstream `X-Agent-Task-Id` header from this same context. Consumers routing each provider call to a training trajectory should key on this rather than on lifecycle events, since it is available on the request path before sampling. + [JsonPropertyName("agentId")] + public string? AgentId { get; set; } + /// Gets or sets the headers value. [JsonPropertyName("headers")] public IDictionary> Headers { get => field ??= new Dictionary>(); set; } + /// Coarse classification of the interaction that produced this request. Open string for forward-compatibility; known values include `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, and `conversation-user`. Absent when the runtime did not classify the request. Comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` header from this same context. + [JsonPropertyName("interactionType")] + public string? InteractionType { get; set; } + /// HTTP method, e.g. GET, POST. [JsonPropertyName("method")] public string Method { get; set; } = string.Empty; + /// Id of the parent agent that spawned the agent issuing this request. Present only for subagent requests; absent for root-agent requests and non-agent requests. Combined with `agentId`, this lets consumers attribute a call to a child trajectory versus the root. Like `agentId`, it comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Parent-Agent-Id` header from this same context. + [JsonPropertyName("parentAgentId")] + public string? ParentAgentId { get; set; } + /// Opaque runtime-minted id, unique per in-flight request. The SDK uses this to correlate httpRequestChunk frames and to address its httpResponseStart / httpResponseChunk replies back to the runtime. [JsonPropertyName("requestId")] public string RequestId { get; set; } = string.Empty; @@ -10891,33 +12526,207 @@ public sealed class LlmInferenceHttpRequestChunkRequest public string RequestId { get; set; } = string.Empty; } -/// Model capability category for grouping in the model picker. -[JsonConverter(typeof(Converter))] -[DebuggerDisplay("{Value,nq}")] -public readonly struct ModelPickerCategory : IEquatable +/// Client environment metadata describing the process that produced a telemetry event. +[Experimental(Diagnostics.Experimental)] +public sealed class GitHubTelemetryClientInfo { - private readonly string? _value; + /// Copilot CLI version string. + [JsonPropertyName("cli_version")] + public string CliVersion { get; set; } = string.Empty; - /// Initializes a new instance of the struct. - /// The value to associate with this . - [JsonConstructor] - public ModelPickerCategory(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - _value = value; - } + /// Name of the client application. + [JsonPropertyName("client_name")] + public string? ClientName { get; set; } - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; + /// Type of client. + [JsonPropertyName("client_type")] + public string? ClientType { get; set; } - /// Lightweight model category optimized for faster, lower-cost interactions. - public static ModelPickerCategory Lightweight { get; } = new("lightweight"); + /// Copilot subscription plan, when known. + [JsonPropertyName("copilot_plan")] + public string? CopilotPlan { get; set; } - /// Versatile model category suitable for a broad range of tasks. - public static ModelPickerCategory Versatile { get; } = new("versatile"); + /// Stable machine identifier for the device. + [JsonPropertyName("dev_device_id")] + public string? DevDeviceId { get; set; } - /// Powerful model category optimized for complex tasks. - public static ModelPickerCategory Powerful { get; } = new("powerful"); + /// Whether the user is a GitHub/Microsoft staff member. + [JsonPropertyName("is_staff")] + public bool? IsStaff { get; set; } + + /// Node.js runtime version string. + [JsonPropertyName("node_version")] + public string NodeVersion { get; set; } = string.Empty; + + /// Operating system architecture (e.g. arm64, x64). + [JsonPropertyName("os_arch")] + public string OsArch { get; set; } = string.Empty; + + /// Operating system platform (e.g. darwin, linux, win32). + [JsonPropertyName("os_platform")] + public string OsPlatform { get; set; } = string.Empty; + + /// Operating system version string. + [JsonPropertyName("os_version")] + public string OsVersion { get; set; } = string.Empty; +} + +/// A single telemetry event in the runtime's native GitHub-shaped telemetry format, forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing GitHubTelemetryNotification distinguishes standard from restricted events; the payload shape is identical for both. +[Experimental(Diagnostics.Experimental)] +public sealed class GitHubTelemetryEvent +{ + /// Client environment metadata. + [JsonPropertyName("client")] + public GitHubTelemetryClientInfo? Client { get; set; } + + /// Copilot tracking ID for user-level attribution. + [JsonPropertyName("copilot_tracking_id")] + public string? CopilotTrackingId { get; set; } + + /// Timestamp when the event was created (ISO 8601 format). + [JsonPropertyName("created_at")] + public string? CreatedAt { get; set; } + + /// Experiment assignment context. + [JsonPropertyName("exp_assignment_context")] + public string? ExpAssignmentContext { get; set; } + + /// Feature flags enabled for this session, as a map from flag to value. + [JsonPropertyName("features")] + public IDictionary? Features { get; set; } + + /// Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed). + [JsonPropertyName("kind")] + public string Kind { get; set; } = string.Empty; + + /// Numeric metrics as a map from key to value. + [JsonPropertyName("metrics")] + public IDictionary Metrics { get => field ??= new Dictionary(); set; } + + /// Reference to the model call that produced this event. + [JsonPropertyName("model_call_id")] + public string? ModelCallId { get; set; } + + /// String-valued properties as a map from key to value. + [JsonPropertyName("properties")] + public IDictionary Properties { get => field ??= new Dictionary(); set; } + + /// Session identifier the event belongs to. + [JsonPropertyName("session_id")] + public string? SessionId { get; set; } +} + +/// Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. +[Experimental(Diagnostics.Experimental)] +public sealed class GitHubTelemetryNotification +{ + /// The telemetry event, in the runtime's native GitHub-shaped telemetry format. + [JsonPropertyName("event")] + public GitHubTelemetryEvent Event { get => field ??= new(); set; } + + /// Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route restricted events to first-party Microsoft stores only. + [JsonPropertyName("restricted")] + public bool Restricted { get; set; } + + /// Session the telemetry event belongs to, when it is session-scoped. Omitted for sessionless events (for example, `server.sendTelemetry` calls with no session id), which are still forwarded to opted-in connections. + [JsonPropertyName("sessionId")] + public string? SessionId { get; set; } +} + +/// Resolved Anthropic adaptive-thinking capability for a model. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct AdaptiveThinkingSupport : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public AdaptiveThinkingSupport(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The model does not accept thinking.type='adaptive'. + public static AdaptiveThinkingSupport Unsupported { get; } = new("unsupported"); + + /// The model accepts adaptive thinking but also accepts thinking.type='enabled'. + public static AdaptiveThinkingSupport Optional { get; } = new("optional"); + + /// The model only accepts adaptive thinking and rejects thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + public static AdaptiveThinkingSupport Required { get; } = new("required"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AdaptiveThinkingSupport left, AdaptiveThinkingSupport right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AdaptiveThinkingSupport left, AdaptiveThinkingSupport right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is AdaptiveThinkingSupport other && Equals(other); + + /// + public bool Equals(AdaptiveThinkingSupport other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override AdaptiveThinkingSupport Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, AdaptiveThinkingSupport value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AdaptiveThinkingSupport)); + } + } +} + + +/// Model capability category for grouping in the model picker. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct ModelPickerCategory : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public ModelPickerCategory(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Lightweight model category optimized for faster, lower-cost interactions. + public static ModelPickerCategory Lightweight { get; } = new("lightweight"); + + /// Versatile model category suitable for a broad range of tasks. + public static ModelPickerCategory Versatile { get; } = new("versatile"); + + /// Powerful model category optimized for complex tasks. + public static ModelPickerCategory Powerful { get; } = new("powerful"); /// Returns a value indicating whether two instances are equivalent. public static bool operator ==(ModelPickerCategory left, ModelPickerCategory right) => left.Equals(right); @@ -10957,6 +12766,7 @@ public override void Write(Utf8JsonWriter writer, ModelPickerCategory value, Jso /// Relative cost tier for token-based billing users. +[Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] public readonly struct ModelPickerPriceCategory : IEquatable @@ -11025,6 +12835,7 @@ public override void Write(Utf8JsonWriter writer, ModelPickerPriceCategory value /// Current policy state for this model. +[Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] public readonly struct ModelPolicyState : IEquatable @@ -11090,6 +12901,7 @@ public override void Write(Utf8JsonWriter writer, ModelPolicyState value, JsonSe /// Server transport type: stdio, http, sse (deprecated), or memory. +[Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] public readonly struct DiscoveredMcpServerType : IEquatable @@ -11643,7 +13455,134 @@ public override void Write(Utf8JsonWriter writer, InstructionDiscoveryPathLocati } +/// Optional completion hint for the input (e.g. 'directory' for filesystem path completion). +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SlashCommandInputCompletion : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SlashCommandInputCompletion(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Input should complete filesystem directories. + public static SlashCommandInputCompletion Directory { get; } = new("directory"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is SlashCommandInputCompletion other && Equals(other); + + /// + public bool Equals(SlashCommandInputCompletion other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SlashCommandInputCompletion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SlashCommandInputCompletion value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); + } + } +} + + +/// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SlashCommandKind : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SlashCommandKind(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Command implemented by the runtime. + public static SlashCommandKind Builtin { get; } = new("builtin"); + + /// Command backed by a skill. + public static SlashCommandKind Skill { get; } = new("skill"); + + /// Command registered by an SDK client or extension. + public static SlashCommandKind Client { get; } = new("client"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SlashCommandKind left, SlashCommandKind right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SlashCommandKind left, SlashCommandKind right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is SlashCommandKind other && Equals(other); + + /// + public bool Equals(SlashCommandKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SlashCommandKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SlashCommandKind value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); + } + } +} + + /// Path conventions used by this filesystem. +[Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] public readonly struct SessionFsSetProviderConventions : IEquatable @@ -12989,43 +14928,49 @@ public override void Write(Utf8JsonWriter writer, AuthInfoType value, JsonSerial } -/// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. +/// Source category for a collected debug bundle entry. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct WorkspacesWorkspaceDetailsHostType : IEquatable +public readonly struct DebugCollectLogsSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public WorkspacesWorkspaceDetailsHostType(string value) + public DebugCollectLogsSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Workspace repository is hosted on GitHub. - public static WorkspacesWorkspaceDetailsHostType GitHub { get; } = new("github"); + /// Session event log. + public static DebugCollectLogsSource Events { get; } = new("events"); - /// Workspace repository is hosted on Azure DevOps. - public static WorkspacesWorkspaceDetailsHostType Ado { get; } = new("ado"); + /// Process log for the session. + public static DebugCollectLogsSource ProcessLog { get; } = new("process-log"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => left.Equals(right); + /// Interactive shell log for the session. + public static DebugCollectLogsSource ShellLog { get; } = new("shell-log"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => !(left == right); + /// Caller-provided diagnostic entry. + public static DebugCollectLogsSource Additional { get; } = new("additional"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsSource left, DebugCollectLogsSource right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsSource left, DebugCollectLogsSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is WorkspacesWorkspaceDetailsHostType other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsSource other && Equals(other); /// - public bool Equals(WorkspacesWorkspaceDetailsHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13033,18 +14978,270 @@ public WorkspacesWorkspaceDetailsHostType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override WorkspacesWorkspaceDetailsHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, WorkspacesWorkspaceDetailsHostType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsSource value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsSource)); + } + } +} + + +/// Destination kind that was written. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct DebugCollectLogsResultKind : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public DebugCollectLogsResultKind(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// A .tgz archive was written. + public static DebugCollectLogsResultKind Archive { get; } = new("archive"); + + /// A directory containing redacted files was written. + public static DebugCollectLogsResultKind Directory { get; } = new("directory"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is DebugCollectLogsResultKind other && Equals(other); + + /// + public bool Equals(DebugCollectLogsResultKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override DebugCollectLogsResultKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, DebugCollectLogsResultKind value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsResultKind)); + } + } +} + + +/// Kind of caller-provided debug log entry. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct DebugCollectLogsEntryKind : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public DebugCollectLogsEntryKind(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Include a single server-local file. + public static DebugCollectLogsEntryKind File { get; } = new("file"); + + /// Include files from a server-local directory recursively. + public static DebugCollectLogsEntryKind Directory { get; } = new("directory"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is DebugCollectLogsEntryKind other && Equals(other); + + /// + public bool Equals(DebugCollectLogsEntryKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override DebugCollectLogsEntryKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, DebugCollectLogsEntryKind value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsEntryKind)); + } + } +} + + +/// How a collected debug entry should be redacted before being staged. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct DebugCollectLogsRedaction : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public DebugCollectLogsRedaction(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Redact the file as plain UTF-8 log text. + public static DebugCollectLogsRedaction PlainText { get; } = new("plain-text"); + + /// Redact each non-empty line as a session event JSON object, falling back to plain-text redaction for malformed lines. + public static DebugCollectLogsRedaction EventsJsonl { get; } = new("events-jsonl"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is DebugCollectLogsRedaction other && Equals(other); + + /// + public bool Equals(DebugCollectLogsRedaction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override DebugCollectLogsRedaction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, DebugCollectLogsRedaction value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsRedaction)); + } + } +} + + +/// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct WorkspacesWorkspaceDetailsHostType : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public WorkspacesWorkspaceDetailsHostType(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Workspace repository is hosted on GitHub. + public static WorkspacesWorkspaceDetailsHostType GitHub { get; } = new("github"); + + /// Workspace repository is hosted on Azure DevOps. + public static WorkspacesWorkspaceDetailsHostType Ado { get; } = new("ado"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is WorkspacesWorkspaceDetailsHostType other && Equals(other); + + /// + public bool Equals(WorkspacesWorkspaceDetailsHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override WorkspacesWorkspaceDetailsHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, WorkspacesWorkspaceDetailsHostType value, JsonSerializerOptions options) { GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspacesWorkspaceDetailsHostType)); } @@ -13385,6 +15582,69 @@ public override void Write(Utf8JsonWriter writer, TaskShellInfoAttachmentMode va } +/// Consumer allowed to call an MCP tool. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct McpToolUiVisibility : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public McpToolUiVisibility(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The model may call the tool. + public static McpToolUiVisibility Model { get; } = new("model"); + + /// An MCP App view may call the tool. + public static McpToolUiVisibility App { get; } = new("app"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpToolUiVisibility left, McpToolUiVisibility right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpToolUiVisibility left, McpToolUiVisibility right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is McpToolUiVisibility other && Equals(other); + + /// + public bool Equals(McpToolUiVisibility other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override McpToolUiVisibility Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, McpToolUiVisibility value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpToolUiVisibility)); + } + } +} + + /// Outcome of the sampling inference. 'success' produced a response; 'failure' encountered an error (including agent-side rejection by content filter or criteria); 'cancelled' the caller cancelled this execution via cancelSamplingExecution. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] @@ -15161,106 +17421,46 @@ public override void Write(Utf8JsonWriter writer, SubagentSettingsEntryContextTi } -/// Optional completion hint for the input (e.g. 'directory' for filesystem path completion). +/// The user's response: accept (submitted), decline (rejected), or cancel (dismissed). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SlashCommandInputCompletion : IEquatable +public readonly struct UIElicitationResponseAction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SlashCommandInputCompletion(string value) + public UIElicitationResponseAction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Input should complete filesystem directories. - public static SlashCommandInputCompletion Directory { get; } = new("directory"); + /// The user submitted the requested form values. + public static UIElicitationResponseAction Accept { get; } = new("accept"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => left.Equals(right); + /// The user explicitly declined to provide the requested input. + public static UIElicitationResponseAction Decline { get; } = new("decline"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => !(left == right); + /// The user dismissed the elicitation request. + public static UIElicitationResponseAction Cancel { get; } = new("cancel"); - /// - public override bool Equals(object? obj) => obj is SlashCommandInputCompletion other && Equals(other); - - /// - public bool Equals(SlashCommandInputCompletion other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - - /// - public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - - /// - public override string ToString() => Value; - - /// Provides a for serializing instances. - [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter - { - /// - public override SlashCommandInputCompletion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); - } - - /// - public override void Write(Utf8JsonWriter writer, SlashCommandInputCompletion value, JsonSerializerOptions options) - { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); - } - } -} - - -/// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command. -[Experimental(Diagnostics.Experimental)] -[JsonConverter(typeof(Converter))] -[DebuggerDisplay("{Value,nq}")] -public readonly struct SlashCommandKind : IEquatable -{ - private readonly string? _value; - - /// Initializes a new instance of the struct. - /// The value to associate with this . - [JsonConstructor] - public SlashCommandKind(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - _value = value; - } - - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; - - /// Command implemented by the runtime. - public static SlashCommandKind Builtin { get; } = new("builtin"); - - /// Command backed by a skill. - public static SlashCommandKind Skill { get; } = new("skill"); - - /// Command registered by an SDK client or extension. - public static SlashCommandKind Client { get; } = new("client"); - - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SlashCommandKind left, SlashCommandKind right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UIElicitationResponseAction left, UIElicitationResponseAction right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SlashCommandKind left, SlashCommandKind right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UIElicitationResponseAction left, UIElicitationResponseAction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SlashCommandKind other && Equals(other); + public override bool Equals(object? obj) => obj is UIElicitationResponseAction other && Equals(other); /// - public bool Equals(SlashCommandKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UIElicitationResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15268,65 +17468,65 @@ public SlashCommandKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SlashCommandKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UIElicitationResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SlashCommandKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UIElicitationResponseAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); } } } -/// The user's response: accept (submitted), decline (rejected), or cancel (dismissed). +/// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct UIElicitationResponseAction : IEquatable +public readonly struct UIAutoModeSwitchResponse : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public UIElicitationResponseAction(string value) + public UIAutoModeSwitchResponse(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The user submitted the requested form values. - public static UIElicitationResponseAction Accept { get; } = new("accept"); + /// Allow the automatic mode switch for this turn. + public static UIAutoModeSwitchResponse Yes { get; } = new("yes"); - /// The user explicitly declined to provide the requested input. - public static UIElicitationResponseAction Decline { get; } = new("decline"); + /// Allow this mode switch and persist the preference. + public static UIAutoModeSwitchResponse YesAlways { get; } = new("yes_always"); - /// The user dismissed the elicitation request. - public static UIElicitationResponseAction Cancel { get; } = new("cancel"); + /// Decline the automatic mode switch. + public static UIAutoModeSwitchResponse No { get; } = new("no"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(UIElicitationResponseAction left, UIElicitationResponseAction right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(UIElicitationResponseAction left, UIElicitationResponseAction right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => !(left == right); /// - public override bool Equals(object? obj) => obj is UIElicitationResponseAction other && Equals(other); + public override bool Equals(object? obj) => obj is UIAutoModeSwitchResponse other && Equals(other); /// - public bool Equals(UIElicitationResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UIAutoModeSwitchResponse other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15334,65 +17534,68 @@ public UIElicitationResponseAction(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override UIElicitationResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UIAutoModeSwitchResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, UIElicitationResponseAction value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UIAutoModeSwitchResponse value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); } } } -/// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). +/// User action selected for an exhausted session limit. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct UIAutoModeSwitchResponse : IEquatable +public readonly struct UISessionLimitsExhaustedResponseAction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public UIAutoModeSwitchResponse(string value) + public UISessionLimitsExhaustedResponseAction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Allow the automatic mode switch for this turn. - public static UIAutoModeSwitchResponse Yes { get; } = new("yes"); + /// Increase the current max by an exact AI Credits amount. + public static UISessionLimitsExhaustedResponseAction Add { get; } = new("add"); - /// Allow this mode switch and persist the preference. - public static UIAutoModeSwitchResponse YesAlways { get; } = new("yes_always"); + /// Set a new absolute max AI Credits value. + public static UISessionLimitsExhaustedResponseAction Set { get; } = new("set"); - /// Decline the automatic mode switch. - public static UIAutoModeSwitchResponse No { get; } = new("no"); + /// Remove the current session limit. + public static UISessionLimitsExhaustedResponseAction Unset { get; } = new("unset"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => left.Equals(right); + /// Leave the limit unchanged and cancel the blocked model request. + public static UISessionLimitsExhaustedResponseAction Cancel { get; } = new("cancel"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UISessionLimitsExhaustedResponseAction left, UISessionLimitsExhaustedResponseAction right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UISessionLimitsExhaustedResponseAction left, UISessionLimitsExhaustedResponseAction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is UIAutoModeSwitchResponse other && Equals(other); + public override bool Equals(object? obj) => obj is UISessionLimitsExhaustedResponseAction other && Equals(other); /// - public bool Equals(UIAutoModeSwitchResponse other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UISessionLimitsExhaustedResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15400,20 +17603,20 @@ public UIAutoModeSwitchResponse(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override UIAutoModeSwitchResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UISessionLimitsExhaustedResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, UIAutoModeSwitchResponse value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UISessionLimitsExhaustedResponseAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UISessionLimitsExhaustedResponseAction)); } } } @@ -15620,6 +17823,72 @@ public override void Write(Utf8JsonWriter writer, PermissionsSetApproveAllSource } +/// Current or requested allow-all mode. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct PermissionsAllowAllMode : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public PermissionsAllowAllMode(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Permission requests follow the normal approval flow. + public static PermissionsAllowAllMode Off { get; } = new("off"); + + /// Tool, path, and URL permission requests are automatically approved. + public static PermissionsAllowAllMode On { get; } = new("on"); + + /// Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + public static PermissionsAllowAllMode Auto { get; } = new("auto"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionsAllowAllMode left, PermissionsAllowAllMode right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionsAllowAllMode left, PermissionsAllowAllMode right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is PermissionsAllowAllMode other && Equals(other); + + /// + public bool Equals(PermissionsAllowAllMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override PermissionsAllowAllMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, PermissionsAllowAllMode value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsAllowAllMode)); + } + } +} + + /// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] @@ -16070,6 +18339,120 @@ public override void Write(Utf8JsonWriter writer, SessionWorkingDirectoryContext } +/// Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names are intentionally not part of the contract. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SessionSettingsPredicateName : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SessionSettingsPredicateName(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Whether the security-tools feature flag enables security tool wiring. + public static SessionSettingsPredicateName SecurityToolsEnabled { get; } = new("securityToolsEnabled"); + + /// Whether third-party security tools should receive the security prompt. + public static SessionSettingsPredicateName ThirdPartySecurityPromptEnabled { get; } = new("thirdPartySecurityPromptEnabled"); + + /// Whether validation may run in parallel. + public static SessionSettingsPredicateName ParallelValidationEnabled { get; } = new("parallelValidationEnabled"); + + /// Whether runtime timing telemetry is enabled. + public static SessionSettingsPredicateName RuntimeTimingTelemetryEnabled { get; } = new("runtimeTimingTelemetryEnabled"); + + /// Whether the co-author hook is enabled. + public static SessionSettingsPredicateName CoAuthorHookEnabled { get; } = new("coAuthorHookEnabled"); + + /// Whether Chronicle integration is enabled. + public static SessionSettingsPredicateName ChronicleEnabled { get; } = new("chronicleEnabled"); + + /// Whether content-exclusion policy may self-fetch data. + public static SessionSettingsPredicateName ContentExclusionSelfFetchEnabled { get; } = new("contentExclusionSelfFetchEnabled"); + + /// Whether Claude Opus token-limit caps should be applied. + public static SessionSettingsPredicateName CapClaudeOpusTokenLimitsEnabled { get; } = new("capClaudeOpusTokenLimitsEnabled"); + + /// Whether code-review behavior is enabled. + public static SessionSettingsPredicateName CodeReviewFeatureEnabled { get; } = new("codeReviewFeatureEnabled"); + + /// Whether CCA should use the TypeScript autofind behavior. + public static SessionSettingsPredicateName CcaUseTsAutofindEnabled { get; } = new("ccaUseTsAutofindEnabled"); + + /// Whether the dependency checker is enabled. + public static SessionSettingsPredicateName DependencyCheckerEnabled { get; } = new("dependencyCheckerEnabled"); + + /// Whether the Dependabot checker is enabled. + public static SessionSettingsPredicateName DependabotCheckerEnabled { get; } = new("dependabotCheckerEnabled"); + + /// Whether the CodeQL checker is enabled. + public static SessionSettingsPredicateName CodeqlCheckerEnabled { get; } = new("codeqlCheckerEnabled"); + + /// Whether trivial-change handling is enabled. + public static SessionSettingsPredicateName TrivialChangeEnabled { get; } = new("trivialChangeEnabled"); + + /// Whether trivial-change skip behavior is enabled. + public static SessionSettingsPredicateName TrivialChangeSkipEnabled { get; } = new("trivialChangeSkipEnabled"); + + /// Whether trivial-change handling is enabled for code review. + public static SessionSettingsPredicateName TrivialChangeEnabledForCodeReview { get; } = new("trivialChangeEnabledForCodeReview"); + + /// Whether trivial-change skip behavior is enabled for code review. + public static SessionSettingsPredicateName TrivialChangeSkipEnabledForCodeReview { get; } = new("trivialChangeSkipEnabledForCodeReview"); + + /// Whether trivial-change handling is enabled for a specific tool. + public static SessionSettingsPredicateName TrivialChangeEnabledForTool { get; } = new("trivialChangeEnabledForTool"); + + /// Whether trivial-change skip behavior is enabled for a specific tool. + public static SessionSettingsPredicateName TrivialChangeSkipEnabledForTool { get; } = new("trivialChangeSkipEnabledForTool"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionSettingsPredicateName left, SessionSettingsPredicateName right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionSettingsPredicateName left, SessionSettingsPredicateName right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is SessionSettingsPredicateName other && Equals(other); + + /// + public bool Equals(SessionSettingsPredicateName other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SessionSettingsPredicateName Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SessionSettingsPredicateName value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionSettingsPredicateName)); + } + } +} + + /// Signal to send (default: SIGTERM). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] @@ -16361,10 +18744,73 @@ public RemoteSessionMode(string value) public static bool operator !=(RemoteSessionMode left, RemoteSessionMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is RemoteSessionMode other && Equals(other); + public override bool Equals(object? obj) => obj is RemoteSessionMode other && Equals(other); + + /// + public bool Equals(RemoteSessionMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override RemoteSessionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, RemoteSessionMode value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMode)); + } + } +} + + +/// Sharing status for a synced session. "repo" makes the session visible to anyone with read access to the repository; "unshared" restricts it to the creator and collaborators. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SessionVisibilityStatus : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SessionVisibilityStatus(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The session is visible to repository readers. + public static SessionVisibilityStatus Repo { get; } = new("repo"); + + /// The session is restricted to its creator and collaborators. + public static SessionVisibilityStatus Unshared { get; } = new("unshared"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionVisibilityStatus left, SessionVisibilityStatus right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionVisibilityStatus left, SessionVisibilityStatus right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is SessionVisibilityStatus other && Equals(other); /// - public bool Equals(RemoteSessionMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionVisibilityStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16372,20 +18818,20 @@ public RemoteSessionMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override RemoteSessionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionVisibilityStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, RemoteSessionMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionVisibilityStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionVisibilityStatus)); } } } @@ -16660,6 +19106,7 @@ internal ServerRpc(JsonRpc rpc) /// Optional message to echo back. /// The to monitor for cancellation requests. The default is . /// Server liveness response, including the echoed message, current server timestamp, and protocol version. + [Experimental(Diagnostics.Experimental)] public async Task PingAsync(string? message = null, CancellationToken cancellationToken = default) { var request = new PingRequest { Message = message }; @@ -16668,11 +19115,13 @@ public async Task PingAsync(string? message = null, CancellationToke /// Performs the SDK server connection handshake and validates the optional connection token. Marked internal because this is JSON-RPC transport plumbing invoked automatically by an SDK client's own `connect()` wrapper, not a user-facing method. Stays internal as long as the SDK client owns the handshake; would only become public if the SDK ever exposed the raw schema surface to consumers without a connection wrapper. /// Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN. + /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. /// The to monitor for cancellation requests. The default is . /// Handshake result reporting the server's protocol version and package version on success. - internal async Task ConnectAsync(string? token = null, CancellationToken cancellationToken = default) + [Experimental(Diagnostics.Experimental)] + internal async Task ConnectAsync(string? token = null, bool? enableGitHubTelemetryForwarding = null, CancellationToken cancellationToken = default) { - var request = new ConnectRequest { Token = token }; + var request = new ConnectRequest { Token = token, EnableGitHubTelemetryForwarding = enableGitHubTelemetryForwarding }; return await CopilotClient.InvokeRpcAsync(_rpc, "connect", [request], cancellationToken); } @@ -16730,6 +19179,12 @@ internal async Task ConnectAsync(string? token = null, Cancellati Interlocked.CompareExchange(ref field, new(_rpc), null) ?? field; + /// Commands APIs. + public ServerCommandsApi Commands => + field ?? + Interlocked.CompareExchange(ref field, new(_rpc), null) ?? + field; + /// User APIs. public ServerUserApi User => field ?? @@ -16768,6 +19223,7 @@ internal async Task ConnectAsync(string? token = null, Cancellati } /// Provides server-scoped Models APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerModelsApi { private readonly JsonRpc _rpc; @@ -16789,6 +19245,7 @@ public async Task ListAsync(string? gitHubToken = null, CancellationT } /// Provides server-scoped Tools APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerToolsApi { private readonly JsonRpc _rpc; @@ -16810,6 +19267,7 @@ public async Task ListAsync(string? model = null, CancellationToken ca } /// Provides server-scoped Account APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerAccountApi { private readonly JsonRpc _rpc; @@ -16875,6 +19333,7 @@ public async Task LogoutAsync(AuthInfo authInfo, Cancellati } /// Provides server-scoped Secrets APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerSecretsApi { private readonly JsonRpc _rpc; @@ -16898,6 +19357,7 @@ public async Task AddFilterValuesAsync(IListProvides server-scoped Mcp APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerMcpApi { private readonly JsonRpc _rpc; @@ -16925,6 +19385,7 @@ public async Task DiscoverAsync(string? workingDirectory = nu } /// Provides server-scoped McpConfig APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerMcpConfigApi { private readonly JsonRpc _rpc; @@ -17043,12 +19504,13 @@ public async Task InstallAsync(string source, string? worki /// Uninstalls an installed plugin. /// Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the fully-qualified spec. + /// Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall when multiple installed plugins share the same name. /// The to monitor for cancellation requests. The default is . - public async Task UninstallAsync(string name, CancellationToken cancellationToken = default) + public async Task UninstallAsync(string name, string? directSourceId = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); - var request = new PluginsUninstallRequest { Name = name }; + var request = new PluginsUninstallRequest { Name = name, DirectSourceId = directSourceId }; await CopilotClient.InvokeRpcAsync(_rpc, "plugins.uninstall", [request], cancellationToken); } @@ -17122,13 +19584,14 @@ public async Task ListAsync(CancellationToken cancellatio /// Registers a new marketplace from a source (owner/repo, URL, or local path). /// Marketplace source. Accepts the same forms as the CLI: "owner/repo" or "owner/repo#ref" (GitHub), an http/https/ssh URL (optionally with #ref), a git scp-style URL (user@host:path), or a local path. The marketplace's own name (from its manifest) is used as the registration key. + /// Working directory used to resolve relative local paths in `source`. Defaults to the server's current working directory. /// The to monitor for cancellation requests. The default is . /// Result of registering a new marketplace. - public async Task AddAsync(string source, CancellationToken cancellationToken = default) + public async Task AddAsync(string source, string? workingDirectory = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(source); - var request = new PluginsMarketplacesAddRequest { Source = source }; + var request = new PluginsMarketplacesAddRequest { Source = source, WorkingDirectory = workingDirectory }; return await CopilotClient.InvokeRpcAsync(_rpc, "plugins.marketplaces.add", [request], cancellationToken); } @@ -17169,6 +19632,7 @@ public async Task RefreshAsync(string? name = null, Ca } /// Provides server-scoped Skills APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerSkillsApi { private readonly JsonRpc _rpc; @@ -17195,7 +19659,6 @@ public async Task DiscoverAsync(IList? projectPaths = n /// When true, omit the host's personal and custom skill directories, leaving only project directories. For multitenant deployments. /// The to monitor for cancellation requests. The default is . /// Canonical locations where skills can be created so the runtime will recognize them. - [Experimental(Diagnostics.Experimental)] public async Task GetDiscoveryPathsAsync(IList? projectPaths = null, bool? excludeHostSkills = null, CancellationToken cancellationToken = default) { var request = new SkillsGetDiscoveryPathsRequest { ProjectPaths = projectPaths, ExcludeHostSkills = excludeHostSkills }; @@ -17210,6 +19673,7 @@ public async Task GetDiscoveryPathsAsync(IList? } /// Provides server-scoped SkillsConfig APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerSkillsConfigApi { private readonly JsonRpc _rpc; @@ -17299,7 +19763,28 @@ public async Task GetDiscoveryPathsAsync(IListProvides server-scoped Commands APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class ServerCommandsApi +{ + private readonly JsonRpc _rpc; + + internal ServerCommandsApi(JsonRpc rpc) + { + _rpc = rpc; + } + + /// Lists the well-known built-in slash commands that work as the first message in a new session (e.g. /plan, /env), without requiring an active session. Commands that depend on session state, authentication, or a synced session are omitted. + /// The to monitor for cancellation requests. The default is . + /// Slash commands available in the session, after applying any include/exclude filters. + public async Task ListAsync(CancellationToken cancellationToken = default) + { + return await CopilotClient.InvokeRpcAsync(_rpc, "commands.list", [], cancellationToken); + } +} + /// Provides server-scoped User APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerUserApi { private readonly JsonRpc _rpc; @@ -17317,6 +19802,7 @@ internal ServerUserApi(JsonRpc rpc) } /// Provides server-scoped UserSettings APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerUserSettingsApi { private readonly JsonRpc _rpc; @@ -17332,9 +19818,30 @@ public async Task ReloadAsync(CancellationToken cancellationToken = default) { await CopilotClient.InvokeRpcAsync(_rpc, "user.settings.reload", [], cancellationToken); } + + /// Lists every known user setting (settings.json overlaid with the legacy config.json, config.json wins), each with its effective value, its default, and whether it is at the default — so settings the user has never set still appear with their default value. Does not include repository- or enterprise-managed overrides that the runtime layers on top at session time. + /// The to monitor for cancellation requests. The default is . + /// Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. + public async Task GetAsync(CancellationToken cancellationToken = default) + { + return await CopilotClient.InvokeRpcAsync(_rpc, "user.settings.get", [], cancellationToken); + } + + /// Writes one or more user settings to settings.json, replacing each provided top-level key. A key whose value is null is removed. Returns the keys whose new value is shadowed by a legacy config.json entry (config.json wins on read), which the runtime leaves in place — such writes do not take effect until the legacy value is removed. + /// Partial user settings to write, as a free-form object keyed by setting name. + /// The to monitor for cancellation requests. The default is . + /// Outcome of writing user settings. + public async Task SetAsync(object settings, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + + var request = new UserSettingsSetRequest { Settings = CopilotClient.ToJsonElementForWire(settings)!.Value }; + return await CopilotClient.InvokeRpcAsync(_rpc, "user.settings.set", [request], cancellationToken); + } } /// Provides server-scoped Runtime APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerRuntimeApi { private readonly JsonRpc _rpc; @@ -17353,6 +19860,7 @@ public async Task ShutdownAsync(CancellationToken cancellationToken = default) } /// Provides server-scoped SessionFs APIs. +[Experimental(Diagnostics.Experimental)] public sealed class ServerSessionFsApi { private readonly JsonRpc _rpc; @@ -17747,17 +20255,6 @@ public async Task GetRemoteControlStatusAsync(Cancell return await CopilotClient.InvokeRpcAsync(_rpc, "sessions.getRemoteControlStatus", [], cancellationToken); } - /// Cursor-based long-poll for sessions spawned by the runtime (e.g. in response to a Mission Control `start_session` command). The cursor is an opaque token; pass it back to receive only spawn events that occurred AFTER the cursor was issued. Omit the cursor on the first call to receive any events buffered since the runtime started. Internal: this is a CLI background-daemon plumbing primitive. SDK consumers that need to react to runtime-spawned sessions should subscribe to a higher-level event stream rather than driving a long-poll loop. - /// Opaque cursor returned by a previous poll. Omit on the first call to receive any spawn events buffered since the runtime started. - /// Milliseconds to wait for new spawn events when the cursor is at the tail. 0 (default) returns immediately even if no events are buffered. Capped at 60000ms. - /// The to monitor for cancellation requests. The default is . - /// Batch of spawn events plus a cursor for follow-up polls. - internal async Task PollSpawnedSessionsAsync(string? cursor = null, TimeSpan? waitMs = null, CancellationToken cancellationToken = default) - { - var request = new SessionsPollSpawnedSessionsRequest { Cursor = cursor, Wait = waitMs }; - return await CopilotClient.InvokeRpcAsync(_rpc, "sessions.pollSpawnedSessions", [request], cancellationToken); - } - /// Registers extension-provided tools on the given session, gated by an optional `enabled` callback. Returns an opaque unsubscribe function the caller must invoke to deregister the tools when the extension is torn down. Marked internal because `loader`, `enabled`, and the returned `unsubscribe` are in-process handles that cannot cross the JSON-RPC boundary. Disappears once extension discovery / launch / tool registration are owned by the runtime: SDK consumers will pass pure config (search paths, disabled ids) via `SessionOptions` and the runtime will resolve, launch, register, and tear down extensions itself. /// Session to register extension tools on. /// In-process ExtensionLoader handle (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, extension discovery/launch moves entirely into the runtime — the CLI passes pure config (search paths, disabled ids) via SessionOptions instead. @@ -17827,8 +20324,14 @@ internal SessionRpc(CopilotSession session) internal CopilotSession Session => _session; - /// Auth APIs. - public AuthApi Auth => + /// GitHubAuth APIs. + public GitHubAuthApi GitHubAuth => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; + + /// Debug APIs. + public DebugApi Debug => field ?? Interlocked.CompareExchange(ref field, new(_session), null) ?? field; @@ -17869,6 +20372,12 @@ internal SessionRpc(CopilotSession session) Interlocked.CompareExchange(ref field, new(_session), null) ?? field; + /// Completions APIs. + public CompletionsApi Completions => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; + /// Instructions APIs. public InstructionsApi Instructions => field ?? @@ -17971,6 +20480,12 @@ internal SessionRpc(CopilotSession session) Interlocked.CompareExchange(ref field, new(_session), null) ?? field; + /// Settings APIs. + public SettingsApi Settings => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; + /// Shell APIs. public ShellApi Shell => field ?? @@ -18007,6 +20522,12 @@ internal SessionRpc(CopilotSession session) Interlocked.CompareExchange(ref field, new(_session), null) ?? field; + /// Visibility APIs. + public VisibilityApi Visibility => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; + /// Schedule APIs. public ScheduleApi Schedule => field ?? @@ -18050,6 +20571,27 @@ public async Task SendAsync(string prompt, string? displayPrompt = n return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.send", [request], cancellationToken); } + /// Sends zero or more user messages to the session in a single turn and returns their message IDs. All provided messages are appended to the conversation in order, then exactly one agent turn runs over the resulting history. When the list is empty, one turn runs over the existing history with no new user message. Remote-backed (Mission Control) sessions do not support this method and will return an error. + /// The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. + /// How to deliver the messages. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. + /// If true, adds the messages to the front of the queue instead of the end. + /// The UI mode the agent was in when these messages were sent. Defaults to the session's current mode. + /// Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. + /// W3C Trace Context traceparent header for distributed tracing of this agent turn. + /// W3C Trace Context tracestate header for distributed tracing. + /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. + /// The to monitor for cancellation requests. The default is . + /// Result of sending zero or more user messages. + [Experimental(Diagnostics.Experimental)] + public async Task SendMessagesAsync(IList messages, SendMode? mode = null, bool? prepend = null, SendAgentMode? agentMode = null, IDictionary? requestHeaders = null, string? traceparent = null, string? tracestate = null, bool? wait = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(messages); + _session.ThrowIfDisposed(); + + var request = new SendMessagesRequest { SessionId = _session.SessionId, Messages = messages, Mode = mode, Prepend = prepend, AgentMode = agentMode, RequestHeaders = requestHeaders, Traceparent = traceparent, Tracestate = tracestate, Wait = wait }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.sendMessages", [request], cancellationToken); + } + /// Aborts the current agent turn. /// Finite reason code describing why the current turn was aborted. /// The to monitor for cancellation requests. The default is . @@ -18096,13 +20638,13 @@ public async Task LogAsync(string message, SessionLogLevel? level = n } } -/// Provides session-scoped Auth APIs. +/// Provides session-scoped GitHubAuth APIs. [Experimental(Diagnostics.Experimental)] -public sealed class AuthApi +public sealed class GitHubAuthApi { private readonly CopilotSession _session; - internal AuthApi(CopilotSession session) + internal GitHubAuthApi(CopilotSession session) { _session = session; } @@ -18114,12 +20656,12 @@ public async Task GetStatusAsync(CancellationToken cancellati { _session.ThrowIfDisposed(); - var request = new SessionAuthGetStatusRequest { SessionId = _session.SessionId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.auth.getStatus", [request], cancellationToken); + var request = new SessionGitHubAuthGetStatusRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.gitHubAuth.getStatus", [request], cancellationToken); } /// Updates the session's auth credentials used for outbound model and API requests. - /// The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime stores the value verbatim and uses it for outbound model/API requests; it does NOT re-validate or re-fetch the associated Copilot user response. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. + /// The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime installs the supplied value immediately for outbound model/API requests. When the credential carries a raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous install) so plan/quota/billing metadata regains fidelity; on resolution failure the verbatim credential remains installed. It does NOT otherwise validate the credential. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. /// The to monitor for cancellation requests. The default is . /// Indicates whether the credential update succeeded. public async Task SetCredentialsAsync(AuthInfo? credentials = null, CancellationToken cancellationToken = default) @@ -18127,7 +20669,34 @@ public async Task SetCredentialsAsync(AuthInfo? cre _session.ThrowIfDisposed(); var request = new SessionSetCredentialsParams { SessionId = _session.SessionId, Credentials = credentials }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.auth.setCredentials", [request], cancellationToken); + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.gitHubAuth.setCredentials", [request], cancellationToken); + } +} + +/// Provides session-scoped Debug APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class DebugApi +{ + private readonly CopilotSession _session; + + internal DebugApi(CopilotSession session) + { + _session = session; + } + + /// Collects a redacted session debug log bundle into a local archive or staging directory. The runtime includes session-owned logs by default and accepts caller-provided diagnostic entries so host applications can add their own files without changing this API shape. + /// Where the redacted bundle should be written. Use `archive` to produce a .tgz, or `directory` to stage redacted files for caller-managed upload/post-processing. + /// Which built-in session diagnostics to include. Omitted fields default to true. + /// Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. + /// The to monitor for cancellation requests. The default is . + /// Result of collecting a redacted debug bundle. + public async Task CollectLogsAsync(DebugCollectLogsDestination destination, DebugCollectLogsInclude? include = null, IList? additionalEntries = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(destination); + _session.ThrowIfDisposed(); + + var request = new DebugCollectLogsRequest { SessionId = _session.SessionId, Destination = destination, Include = include, AdditionalEntries = additionalEntries }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.debug.collectLogs", [request], cancellationToken); } } @@ -18254,16 +20823,17 @@ public async Task GetCurrentAsync(CancellationToken cancellationTo /// Model selection id to switch to, as returned by `list`. A bare id (e.g. `claude-sonnet-4.6`) names a Copilot (CAPI) model; a provider-qualified id (`provider/id`, e.g. `acme/claude-sonnet`) targets a registry BYOK model. /// Reasoning effort level to use for the model. "none" disables reasoning. /// Reasoning summary mode to request for supported model clients. + /// Output verbosity level to request for supported models. /// Override individual model capabilities resolved by the runtime. /// Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. /// The to monitor for cancellation requests. The default is . /// The model identifier active on the session after the switch. - public async Task SwitchToAsync(string modelId, string? reasoningEffort = null, ReasoningSummary? reasoningSummary = null, ModelCapabilitiesOverride? modelCapabilities = null, ContextTier? contextTier = null, CancellationToken cancellationToken = default) + public async Task SwitchToAsync(string modelId, string? reasoningEffort = null, ReasoningSummary? reasoningSummary = null, Verbosity? verbosity = null, ModelCapabilitiesOverride? modelCapabilities = null, ContextTier? contextTier = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(modelId); _session.ThrowIfDisposed(); - var request = new ModelSwitchToRequest { SessionId = _session.SessionId, ModelId = modelId, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, ModelCapabilities = modelCapabilities, ContextTier = contextTier }; + var request = new ModelSwitchToRequest { SessionId = _session.SessionId, ModelId = modelId, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, Verbosity = verbosity, ModelCapabilities = modelCapabilities, ContextTier = contextTier }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.model.switchTo", [request], cancellationToken); } @@ -18552,6 +21122,43 @@ public async Task DiffAsync(WorkspaceDiffMode mode, bool? i } } +/// Provides session-scoped Completions APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class CompletionsApi +{ + private readonly CopilotSession _session; + + internal CompletionsApi(CopilotSession session) + { + _session = session; + } + + /// Gets the characters that should trigger host-driven completions for the session. Empty disables host-driven completions (e.g. local sessions, or a relay host that does not advertise them). + /// The to monitor for cancellation requests. The default is . + /// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). + public async Task GetTriggerCharactersAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionCompletionsGetTriggerCharactersRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.completions.getTriggerCharacters", [request], cancellationToken); + } + + /// Requests host-driven completion items for the current composer input. Returns an empty list when the host has no items or does not support completions. + /// The full composed composer input. + /// Cursor offset within `text`, in UTF-16 code units. + /// The to monitor for cancellation requests. The default is . + /// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. + public async Task RequestAsync(string text, long offset, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(text); + _session.ThrowIfDisposed(); + + var request = new CompletionsRequestRequest { SessionId = _session.SessionId, Text = text, Offset = offset }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.completions.request", [request], cancellationToken); + } +} + /// Provides session-scoped Instructions APIs. [Experimental(Diagnostics.Experimental)] public sealed class InstructionsApi @@ -18922,7 +21529,7 @@ public async Task ListAsync(CancellationToken cancellationToken = return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.list", [request], cancellationToken); } - /// Lists the tools exposed by a connected MCP server on this session's host. + /// Lists the tools exposed by a connected MCP server on this session's host. This performs a live `tools/list` request. Tool UI metadata is returned independently of whether MCP Apps rendering is enabled for the session. /// Name of the connected MCP server whose tools to list. /// The to monitor for cancellation requests. The default is . /// Tools exposed by the connected MCP server. Throws when the server is not connected. @@ -19050,11 +21657,11 @@ internal async Task ConfigureGitHubAsync(object authIn return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.configureGitHub", [request], cancellationToken); } - /// Starts an individual MCP server on the session's host. + /// Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. /// Name of the MCP server to start. - /// Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. + /// MCP server configuration (stdio process or remote HTTP/SSE). /// The to monitor for cancellation requests. The default is . - internal async Task StartServerAsync(string serverName, object config, CancellationToken cancellationToken = default) + public async Task StartServerAsync(string serverName, object config, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(serverName); ArgumentNullException.ThrowIfNull(config); @@ -19064,17 +21671,16 @@ internal async Task StartServerAsync(string serverName, object config, Cancellat await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.startServer", [request], cancellationToken); } - /// Restarts an individual MCP server on the session's host (stops then starts). + /// Restarts an individual MCP server on the live session (stops then starts). Omit `config` for a config-free restart-by-name of an already-configured server; supply `config` to restart with a replacement configuration. Session-scoped and ephemeral: does NOT modify persistent user configuration (`mcp.config.*`). /// Name of the MCP server to restart. - /// Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. + /// Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). /// The to monitor for cancellation requests. The default is . - internal async Task RestartServerAsync(string serverName, object config, CancellationToken cancellationToken = default) + public async Task RestartServerAsync(string serverName, object? config = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(serverName); - ArgumentNullException.ThrowIfNull(config); _session.ThrowIfDisposed(); - var request = new McpRestartServerRequest { SessionId = _session.SessionId, ServerName = serverName, Config = CopilotClient.ToJsonElementForWire(config)!.Value }; + var request = new McpRestartServerRequest { SessionId = _session.SessionId, ServerName = serverName, Config = CopilotClient.ToJsonElementForWire(config) }; await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.restartServer", [request], cancellationToken); } @@ -19139,11 +21745,23 @@ public async Task IsServerRunningAsync(string serverNa Interlocked.CompareExchange(ref field, new(_session), null) ?? field; + /// Headers APIs. + public McpHeadersApi Headers => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; + /// Apps APIs. public McpAppsApi Apps => field ?? Interlocked.CompareExchange(ref field, new(_session), null) ?? field; + + /// Resources APIs. + public McpResourcesApi Resources => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; } /// Provides session-scoped McpOauth APIs. @@ -19157,20 +21775,6 @@ internal McpOauthApi(CopilotSession session) _session = session; } - /// Responds to a pending MCP OAuth request with an in-process provider. This internal CLI-only API accepts a live OAuthClientProvider instance and cannot be used over the SDK JSON-RPC boundary. Use session.mcp.oauth.handlePendingRequest instead for the public SDK-safe response path. - /// OAuth request identifier from mcp.oauth_required. - /// In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be serialized across the JSON-RPC boundary. - /// The to monitor for cancellation requests. The default is . - /// Empty result after recording the MCP OAuth response. - internal async Task RespondAsync(string requestId, object? provider = null, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(requestId); - _session.ThrowIfDisposed(); - - var request = new McpOauthRespondRequest { SessionId = _session.SessionId, RequestId = requestId, Provider = CopilotClient.ToJsonElementForWire(provider) }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.oauth.respond", [request], cancellationToken); - } - /// Resolves a pending MCP OAuth request with a host-provided token or cancellation. The pending request is emitted as mcp.oauth_required with the data necessary to authorize the request. /// OAuth request identifier from the mcp.oauth_required event. /// Host response to the pending OAuth request. @@ -19207,6 +21811,33 @@ public async Task LoginAsync(string serverName, bool? force } } +/// Provides session-scoped McpHeaders APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class McpHeadersApi +{ + private readonly CopilotSession _session; + + internal McpHeadersApi(CopilotSession session) + { + _session = session; + } + + /// Responds to a pending MCP dynamic headers refresh request. Hosts that subscribe to `mcp.headers_refresh_required` use this to provide short-lived per-server headers or to indicate that no dynamic headers are available for this refresh. + /// Headers refresh request identifier from mcp.headers_refresh_required. + /// Host response: supply dynamic headers or decline this refresh. + /// The to monitor for cancellation requests. The default is . + /// Indicates whether the pending MCP headers refresh response was accepted. + public async Task HandlePendingHeadersRefreshRequestAsync(string requestId, McpHeadersHandlePendingHeadersRefreshRequest result, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(requestId); + ArgumentNullException.ThrowIfNull(result); + _session.ThrowIfDisposed(); + + var request = new McpHeadersHandlePendingHeadersRefreshRequestRequest { SessionId = _session.SessionId, RequestId = requestId, Result = result }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.headers.handlePendingHeadersRefreshRequest", [request], cancellationToken); + } +} + /// Provides session-scoped McpApps APIs. [Experimental(Diagnostics.Experimental)] public sealed class McpAppsApi @@ -19303,6 +21934,61 @@ public async Task DiagnoseAsync(string serverName, Cancel } } +/// Provides session-scoped McpResources APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourcesApi +{ + private readonly CopilotSession _session; + + internal McpResourcesApi(CopilotSession session) + { + _session = session; + } + + /// Fetch an MCP resource from a connected server by URI (proxies MCP `resources/read`). + /// Name of the MCP server hosting the resource. + /// Resource URI. + /// The to monitor for cancellation requests. The default is . + /// Resource contents returned by the MCP server. + public async Task ReadAsync(string serverName, string uri, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(serverName); + ArgumentNullException.ThrowIfNull(uri); + _session.ThrowIfDisposed(); + + var request = new McpResourcesReadRequest { SessionId = _session.SessionId, ServerName = serverName, Uri = uri }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.resources.read", [request], cancellationToken); + } + + /// Enumerate one page of resources a connected MCP server exposes (proxies MCP `resources/list`). Pass `cursor` to continue from a prior result's `nextCursor`. + /// Name of the MCP server whose resources to enumerate. + /// Opaque MCP pagination cursor from a prior `nextCursor` value. + /// The to monitor for cancellation requests. The default is . + /// One page of resources advertised by the named MCP server. + public async Task ListAsync(string serverName, string? cursor = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(serverName); + _session.ThrowIfDisposed(); + + var request = new McpResourcesListRequest { SessionId = _session.SessionId, ServerName = serverName, Cursor = cursor }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.resources.list", [request], cancellationToken); + } + + /// Enumerate one page of resource templates a connected MCP server exposes (proxies MCP `resources/templates/list`). Pass `cursor` to continue from a prior result's `nextCursor`. + /// Name of the MCP server whose resource templates to enumerate. + /// Opaque MCP pagination cursor from a prior `nextCursor` value. + /// The to monitor for cancellation requests. The default is . + /// One page of resource templates advertised by the named MCP server. + public async Task ListTemplatesAsync(string serverName, string? cursor = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(serverName); + _session.ThrowIfDisposed(); + + var request = new McpResourcesListTemplatesRequest { SessionId = _session.SessionId, ServerName = serverName, Cursor = cursor }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.resources.listTemplates", [request], cancellationToken); + } +} + /// Provides session-scoped Plugins APIs. [Experimental(Diagnostics.Experimental)] public sealed class PluginsApi @@ -19332,7 +22018,7 @@ public async Task ReloadAsync(PluginsReloadRequest? request = null, Cancellation { _session.ThrowIfDisposed(); - var rpcRequest = new PluginsReloadRequestWithSession { SessionId = _session.SessionId, ReloadMcp = request?.ReloadMcp, ReloadCustomAgents = request?.ReloadCustomAgents, ReloadHooks = request?.ReloadHooks, DeferRepoHooks = request?.DeferRepoHooks }; + var rpcRequest = new PluginsReloadRequestWithSession { SessionId = _session.SessionId, ReloadMcp = request?.ReloadMcp, ReloadCustomAgents = request?.ReloadCustomAgents, ReloadHooks = request?.ReloadHooks, ReloadExtensions = request?.ReloadExtensions, DeferRepoHooks = request?.DeferRepoHooks }; await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.plugins.reload", [rpcRequest], cancellationToken); } } @@ -19390,6 +22076,7 @@ internal OptionsApi(CopilotSession session) /// Per-property model capability overrides for the selected model. /// Reasoning effort for the selected model (model-defined enum). /// Reasoning summary mode for supported model clients. + /// Output verbosity level for supported models. /// Identifier of the client driving the session. /// Identifier sent to LSP-style integrations. /// Stable integration identifier used for analytics and rate-limit attribution. @@ -19400,6 +22087,8 @@ internal OptionsApi(CopilotSession session) /// Absolute working-directory path for shell tools. /// Allowlist of tool names available to this session. /// Denylist of tool names for this session. + /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. + /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. /// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. /// Whether shell-script safety heuristics are enabled. /// Shell init profile (`None` or `NonInteractive`). @@ -19407,6 +22096,7 @@ internal OptionsApi(CopilotSession session) /// Resolved sandbox configuration. /// Whether interactive shell sessions are logged. /// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). + /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. /// Additional directories to search for skills. /// Skill IDs that should be excluded from this session. /// Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. @@ -19436,13 +22126,14 @@ internal OptionsApi(CopilotSession session) /// Whether to enable cross-session store writes and reads. /// Whether to enable skill directory scanning and loading. Falls back to enableConfigDiscovery when unset. /// Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. + /// Optional session limits. Pass null to clear the session limits. /// The to monitor for cancellation requests. The default is . /// Indicates whether the session options patch was applied successfully. - public async Task UpdateAsync(string? model = null, ModelCapabilitiesOverride? modelCapabilitiesOverrides = null, string? reasoningEffort = null, OptionsUpdateReasoningSummary? reasoningSummary = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, ProviderConfig? provider = null, CapiSessionOptions? capi = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, OptionsUpdateToolFilterPrecedence? toolFilterPrecedence = null, bool? enableScriptSafety = null, string? shellInitProfile = null, IList? shellProcessFlags = null, SandboxConfig? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, long? maxInlineBinaryBytes = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? suppressCustomAgentPrompt = null, bool? skipCustomInstructions = null, IList? disabledInstructionSources = null, bool? coauthorEnabled = null, string? trajectoryFile = null, bool? enableStreaming = null, string? copilotUrl = null, bool? askUserDisabled = null, bool? continueOnAutoMode = null, bool? runningInInteractiveMode = null, bool? enableReasoningSummaries = null, string? agentContext = null, string? eventsLogDirectory = null, IList? additionalContentExclusionPolicies = null, bool? manageScheduleEnabled = null, IList? sessionCapabilities = null, bool? skipEmbeddingRetrieval = null, string? organizationCustomInstructions = null, bool? enableFileHooks = null, bool? enableHostGitOperations = null, bool? enableSessionStore = null, bool? enableSkills = null, OptionsUpdateContextTier? contextTier = null, CancellationToken cancellationToken = default) + public async Task UpdateAsync(string? model = null, ModelCapabilitiesOverride? modelCapabilitiesOverrides = null, string? reasoningEffort = null, OptionsUpdateReasoningSummary? reasoningSummary = null, Verbosity? verbosity = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, ProviderConfig? provider = null, CapiSessionOptions? capi = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, IList? includedBuiltinAgents = null, IList? excludedBuiltinAgents = null, OptionsUpdateToolFilterPrecedence? toolFilterPrecedence = null, bool? enableScriptSafety = null, string? shellInitProfile = null, IList? shellProcessFlags = null, SandboxConfig? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, bool? allowAllMcpServerInstructions = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, long? maxInlineBinaryBytes = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? suppressCustomAgentPrompt = null, bool? skipCustomInstructions = null, IList? disabledInstructionSources = null, bool? coauthorEnabled = null, string? trajectoryFile = null, bool? enableStreaming = null, string? copilotUrl = null, bool? askUserDisabled = null, bool? continueOnAutoMode = null, bool? runningInInteractiveMode = null, bool? enableReasoningSummaries = null, string? agentContext = null, string? eventsLogDirectory = null, IList? additionalContentExclusionPolicies = null, bool? manageScheduleEnabled = null, IList? sessionCapabilities = null, bool? skipEmbeddingRetrieval = null, string? organizationCustomInstructions = null, bool? enableFileHooks = null, bool? enableHostGitOperations = null, bool? enableSessionStore = null, bool? enableSkills = null, OptionsUpdateContextTier? contextTier = null, SessionLimitsConfig? sessionLimits = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new SessionUpdateOptionsParams { SessionId = _session.SessionId, Model = model, ModelCapabilitiesOverrides = modelCapabilitiesOverrides, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, ClientName = clientName, LspClientName = lspClientName, IntegrationId = integrationId, FeatureFlags = featureFlags, IsExperimentalMode = isExperimentalMode, Provider = provider, Capi = capi, WorkingDirectory = workingDirectory, AvailableTools = availableTools, ExcludedTools = excludedTools, ToolFilterPrecedence = toolFilterPrecedence, EnableScriptSafety = enableScriptSafety, ShellInitProfile = shellInitProfile, ShellProcessFlags = shellProcessFlags, SandboxConfig = sandboxConfig, LogInteractiveShells = logInteractiveShells, EnvValueMode = envValueMode, SkillDirectories = skillDirectories, DisabledSkills = disabledSkills, EnableOnDemandInstructionDiscovery = enableOnDemandInstructionDiscovery, MaxInlineBinaryBytes = maxInlineBinaryBytes, InstalledPlugins = installedPlugins, CustomAgentsLocalOnly = customAgentsLocalOnly, SuppressCustomAgentPrompt = suppressCustomAgentPrompt, SkipCustomInstructions = skipCustomInstructions, DisabledInstructionSources = disabledInstructionSources, CoauthorEnabled = coauthorEnabled, TrajectoryFile = trajectoryFile, EnableStreaming = enableStreaming, CopilotUrl = copilotUrl, AskUserDisabled = askUserDisabled, ContinueOnAutoMode = continueOnAutoMode, RunningInInteractiveMode = runningInInteractiveMode, EnableReasoningSummaries = enableReasoningSummaries, AgentContext = agentContext, EventsLogDirectory = eventsLogDirectory, AdditionalContentExclusionPolicies = additionalContentExclusionPolicies, ManageScheduleEnabled = manageScheduleEnabled, SessionCapabilities = sessionCapabilities, SkipEmbeddingRetrieval = skipEmbeddingRetrieval, OrganizationCustomInstructions = organizationCustomInstructions, EnableFileHooks = enableFileHooks, EnableHostGitOperations = enableHostGitOperations, EnableSessionStore = enableSessionStore, EnableSkills = enableSkills, ContextTier = contextTier }; + var request = new SessionUpdateOptionsParams { SessionId = _session.SessionId, Model = model, ModelCapabilitiesOverrides = modelCapabilitiesOverrides, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, Verbosity = verbosity, ClientName = clientName, LspClientName = lspClientName, IntegrationId = integrationId, FeatureFlags = featureFlags, IsExperimentalMode = isExperimentalMode, Provider = provider, Capi = capi, WorkingDirectory = workingDirectory, AvailableTools = availableTools, ExcludedTools = excludedTools, IncludedBuiltinAgents = includedBuiltinAgents, ExcludedBuiltinAgents = excludedBuiltinAgents, ToolFilterPrecedence = toolFilterPrecedence, EnableScriptSafety = enableScriptSafety, ShellInitProfile = shellInitProfile, ShellProcessFlags = shellProcessFlags, SandboxConfig = sandboxConfig, LogInteractiveShells = logInteractiveShells, EnvValueMode = envValueMode, AllowAllMcpServerInstructions = allowAllMcpServerInstructions, SkillDirectories = skillDirectories, DisabledSkills = disabledSkills, EnableOnDemandInstructionDiscovery = enableOnDemandInstructionDiscovery, MaxInlineBinaryBytes = maxInlineBinaryBytes, InstalledPlugins = installedPlugins, CustomAgentsLocalOnly = customAgentsLocalOnly, SuppressCustomAgentPrompt = suppressCustomAgentPrompt, SkipCustomInstructions = skipCustomInstructions, DisabledInstructionSources = disabledInstructionSources, CoauthorEnabled = coauthorEnabled, TrajectoryFile = trajectoryFile, EnableStreaming = enableStreaming, CopilotUrl = copilotUrl, AskUserDisabled = askUserDisabled, ContinueOnAutoMode = continueOnAutoMode, RunningInInteractiveMode = runningInInteractiveMode, EnableReasoningSummaries = enableReasoningSummaries, AgentContext = agentContext, EventsLogDirectory = eventsLogDirectory, AdditionalContentExclusionPolicies = additionalContentExclusionPolicies, ManageScheduleEnabled = manageScheduleEnabled, SessionCapabilities = sessionCapabilities, SkipEmbeddingRetrieval = skipEmbeddingRetrieval, OrganizationCustomInstructions = organizationCustomInstructions, EnableFileHooks = enableFileHooks, EnableHostGitOperations = enableHostGitOperations, EnableSessionStore = enableSessionStore, EnableSkills = enableSkills, ContextTier = contextTier, SessionLimits = sessionLimits }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.options.update", [request], cancellationToken); } } @@ -19630,7 +22321,7 @@ public async Task ListAsync(CommandsListRequest? request = null, Ca /// Command name. Leading slashes are stripped and the name is matched case-insensitively. /// Raw input after the command name. /// The to monitor for cancellation requests. The default is . - /// Result of invoking the slash command (text output, prompt to send to the agent, or completion). + /// Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). public async Task InvokeAsync(string name, string? input = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(name); @@ -19791,7 +22482,7 @@ public async Task HandlePendingElicitationAsync(string requ /// Resolves a pending `user_input.requested` event with the user's response. /// The unique request ID from the user_input.requested event. - /// Schema for the `UIUserInputResponse` type. + /// User response for a pending user-input request, with answer text and whether it was typed freeform. /// The to monitor for cancellation requests. The default is . /// Indicates whether the pending UI request was resolved by this call. public async Task HandlePendingUserInputAsync(string requestId, UIUserInputResponse response, CancellationToken cancellationToken = default) @@ -19832,9 +22523,24 @@ public async Task HandlePendingAutoModeSwitchAsync(string return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.ui.handlePendingAutoModeSwitch", [request], cancellationToken); } + /// Resolves a pending `session_limits_exhausted.requested` event with the user's selected limit action. + /// The unique request ID from the session_limits_exhausted.requested event. + /// The selected session-limit action. + /// The to monitor for cancellation requests. The default is . + /// Indicates whether the pending UI request was resolved by this call. + public async Task HandlePendingSessionLimitsExhaustedAsync(string requestId, UISessionLimitsExhaustedResponse response, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(requestId); + ArgumentNullException.ThrowIfNull(response); + _session.ThrowIfDisposed(); + + var request = new UIHandlePendingSessionLimitsExhaustedRequest { SessionId = _session.SessionId, RequestId = requestId, Response = response }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.ui.handlePendingSessionLimitsExhausted", [request], cancellationToken); + } + /// Resolves a pending `exit_plan_mode.requested` event with the user's response. /// The unique request ID from the exit_plan_mode.requested event. - /// Schema for the `UIExitPlanModeResponse` type. + /// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. /// The to monitor for cancellation requests. The default is . /// Indicates whether the pending UI request was resolved by this call. public async Task HandlePendingExitPlanModeAsync(string requestId, UIExitPlanModeResponse response, CancellationToken cancellationToken = default) @@ -19939,22 +22645,24 @@ public async Task SetApproveAllAsync(bool enable return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.permissions.setApproveAll", [request], cancellationToken); } - /// Enables or disables full allow-all permissions (tools, paths, and URLs) for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. Unlike `setApproveAll`, this swaps in the unrestricted path and URL managers and emits `session.permissions_changed` on transition. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire. - /// Whether to enable full allow-all permissions. + /// Sets the allow-all permission mode for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. The `on` mode swaps in unrestricted path and URL managers and emits `session.permissions_changed` on transition; the `auto` mode keeps normal prompt paths active while attaching LLM safety recommendations. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire. + /// Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM auto-approval; `off` disables both. + /// Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. + /// Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. /// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. /// The to monitor for cancellation requests. The default is . /// Indicates whether the operation succeeded and reports the post-mutation state. - public async Task SetAllowAllAsync(bool enabled, PermissionsSetAllowAllSource? source = null, CancellationToken cancellationToken = default) + public async Task SetAllowAllAsync(PermissionsAllowAllMode? mode = null, bool? enabled = null, string? model = null, PermissionsSetAllowAllSource? source = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new PermissionsSetAllowAllRequest { SessionId = _session.SessionId, Enabled = enabled, Source = source }; + var request = new PermissionsSetAllowAllRequest { SessionId = _session.SessionId, Mode = mode, Enabled = enabled, Model = model, Source = source }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.permissions.setAllowAll", [request], cancellationToken); } - /// Returns whether full allow-all permissions are currently active for the session. + /// Returns the current allow-all permission mode for the session. /// The to monitor for cancellation requests. The default is . - /// Current full allow-all permission state. + /// Current allow-all permission mode. public async Task GetAllowAllAsync(CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); @@ -20287,6 +22995,29 @@ public async Task ContextInfoAsync(long promptTokenLi return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.metadata.contextInfo", [request], cancellationToken); } + /// Returns the experimental per-source attribution breakdown of the session's current context window as a flat list of entries (skills, subagents, MCP servers, built-in tools, plugin rollups, system/tool-definition costs, with nesting via parentId), plus the successful compaction count. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. Returns null until the session has initialized its system prompt and tool metadata. + /// The to monitor for cancellation requests. The default is . + /// Per-source attribution breakdown for the session's current context window, or null if uninitialized. + public async Task GetContextAttributionAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionMetadataGetContextAttributionRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.metadata.getContextAttribution", [request], cancellationToken); + } + + /// Returns the largest individual messages currently in the session's context window, most-expensive first. Companion to `metadata.getContextAttribution`. Returns an empty list until the session has initialized. + /// Maximum number of messages to return, most-expensive first. Omit for the server default. + /// The to monitor for cancellation requests. The default is . + /// The heaviest individual messages in the session's context window, most-expensive first. + public async Task GetContextHeaviestMessagesAsync(long? limit = null, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new MetadataContextHeaviestMessagesRequest { SessionId = _session.SessionId, Limit = limit }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.metadata.getContextHeaviestMessages", [request], cancellationToken); + } + /// Records a working-directory/git context change and emits a `session.context_changed` event. /// Updated working directory and git context. Emitted as the new payload of `session.context_changed`. /// The to monitor for cancellation requests. The default is . @@ -20300,10 +23031,10 @@ public async Task RecordContextChangeAsync(Se return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.metadata.recordContextChange", [request], cancellationToken); } - /// Updates the session's recorded working directory. + /// Updates the session's working directory. For local sessions the target is validated first (an absolute path that exists on disk) and the permission primary directory is re-based; a rejected validation fails the call before any session state changes. /// Absolute path to set as the session's working directory. The runtime updates the session's recorded cwd so subsequent operations (shell tools, file lookups, telemetry) anchor to it. /// The to monitor for cancellation requests. The default is . - /// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. + /// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. public async Task SetWorkingDirectoryAsync(string workingDirectory, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(workingDirectory); @@ -20327,6 +23058,42 @@ public async Task RecomputeContextTokensAs } } +/// Provides session-scoped Settings APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class SettingsApi +{ + private readonly CopilotSession _session; + + internal SettingsApi(CopilotSession session) + { + _session = session; + } + + /// Returns a redacted snapshot of session runtime settings, with secrets and raw feature flags excluded. Internal: the runtime settings shape is a runtime-internal surface and is deliberately kept out of the public SDK, because consumers should not depend on the runtime's internal settings layout. It remains callable in-process and is expected to be reworked as the runtime internals are consolidated. + /// The to monitor for cancellation requests. The default is . + /// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. + internal async Task SnapshotAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionSettingsSnapshotRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.settings.snapshot", [request], cancellationToken); + } + + /// Evaluates a named Rust-owned settings predicate without exposing raw feature flags. Internal: the raw feature-flag names and composition are runtime-internal, so this predicate-evaluation helper is kept out of the public SDK surface and is callable in-process only. + /// Predicate name. The runtime owns the raw feature-flag names and composition logic. + /// Tool name for tool-scoped predicates such as trivial-change handling. + /// The to monitor for cancellation requests. The default is . + /// Result of evaluating a Rust-owned settings predicate. + internal async Task EvaluatePredicateAsync(SessionSettingsPredicateName name, string? toolName = null, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionSettingsEvaluatePredicateRequest { SessionId = _session.SessionId, Name = name, ToolName = toolName }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.settings.evaluatePredicate", [request], cancellationToken); + } +} + /// Provides session-scoped Shell APIs. [Experimental(Diagnostics.Experimental)] public sealed class ShellApi @@ -20549,7 +23316,7 @@ public async Task TailAsync(CancellationToken cancellationTo } /// Registers consumer interest in an event type for runtime gating purposes. - /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates the full interactive OAuth flow to the consumer; when no interest is registered the runtime installs a browserless fallback that silently reuses cached tokens). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. + /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. /// The to monitor for cancellation requests. The default is . /// Opaque handle representing an event-type interest registration. public async Task RegisterInterestAsync(string eventType, CancellationToken cancellationToken = default) @@ -20644,6 +23411,41 @@ public async Task NotifySteerableChangedAsyn } } +/// Provides session-scoped Visibility APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class VisibilityApi +{ + private readonly CopilotSession _session; + + internal VisibilityApi(CopilotSession session) + { + _session = session; + } + + /// Returns the session's current Mission Control sharing status and shareable GitHub URL. Reflects whether the synced session is visible to repository readers ("repo") or restricted to its creator and collaborators ("unshared"). + /// The to monitor for cancellation requests. The default is . + /// Current sharing status and shareable GitHub URL for a session. + public async Task GetAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionVisibilityGetRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.visibility.get", [request], cancellationToken); + } + + /// Sets the session's Mission Control sharing status, controlling whether the synced session is visible to repository readers. Returns the effective status and shareable GitHub URL after the change. + /// Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. + /// The to monitor for cancellation requests. The default is . + /// Effective sharing status and shareable GitHub URL after updating session visibility. + public async Task SetAsync(SessionVisibilityStatus status, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new VisibilitySetRequest { SessionId = _session.SessionId, Status = status }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.visibility.set", [request], cancellationToken); + } +} + /// Provides session-scoped Schedule APIs. [Experimental(Diagnostics.Experimental)] public sealed class ScheduleApi @@ -20914,11 +23716,24 @@ public interface ILlmInferenceHandler Task HttpRequestChunkAsync(LlmInferenceHttpRequestChunkRequest request, CancellationToken cancellationToken = default); } +/// Handles `gitHubTelemetry` client global API methods. +[Experimental(Diagnostics.Experimental)] +public interface IGitHubTelemetryHandler +{ + /// Forwards a single GitHub telemetry event to a host connection that opted into telemetry forwarding during the `server.connect` handshake. Opted-in connections receive every event the runtime emits after the handshake — across all sessions, plus sessionless events (for example, `server.sendTelemetry` calls with no session id). + /// Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. + /// The to monitor for cancellation requests. The default is . + Task EventAsync(GitHubTelemetryNotification request, CancellationToken cancellationToken = default); +} + /// Provides all client global API handler groups for a connection. public sealed class ClientGlobalApiHandlers { /// Optional handler for LlmInference client global API methods. public ILlmInferenceHandler? LlmInference { get; set; } + + /// Optional handler for GitHubTelemetry client global API methods. + public IGitHubTelemetryHandler? GitHubTelemetry { get; set; } } /// Registers client global API handlers on a JSON-RPC connection. @@ -20942,6 +23757,11 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH var handler = handlers.LlmInference ?? throw new InvalidOperationException("No llmInference client-global handler registered"); return await handler.HttpRequestChunkAsync(request, cancellationToken); }), singleObjectParam: true); + rpc.SetLocalRpcMethod("gitHubTelemetry.event", (Func)(async (request, cancellationToken) => + { + var handler = handlers.GitHubTelemetry ?? throw new InvalidOperationException("No gitHubTelemetry client-global handler registered"); + await handler.EventAsync(request, cancellationToken); + }), singleObjectParam: true); } } @@ -20957,6 +23777,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.AbortData), TypeInfoPropertyName = "SessionEventsAbortData")] [JsonSerializable(typeof(GitHub.Copilot.AbortEvent), TypeInfoPropertyName = "SessionEventsAbortEvent")] [JsonSerializable(typeof(GitHub.Copilot.AbortReason), TypeInfoPropertyName = "SessionEventsAbortReason")] +[JsonSerializable(typeof(GitHub.Copilot.AssistantIdleData), TypeInfoPropertyName = "SessionEventsAssistantIdleData")] +[JsonSerializable(typeof(GitHub.Copilot.AssistantIdleEvent), TypeInfoPropertyName = "SessionEventsAssistantIdleEvent")] [JsonSerializable(typeof(GitHub.Copilot.AssistantIntentData), TypeInfoPropertyName = "SessionEventsAssistantIntentData")] [JsonSerializable(typeof(GitHub.Copilot.AssistantIntentEvent), TypeInfoPropertyName = "SessionEventsAssistantIntentEvent")] [JsonSerializable(typeof(GitHub.Copilot.AssistantMessageData), TypeInfoPropertyName = "SessionEventsAssistantMessageData")] @@ -20972,8 +23794,12 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.AssistantReasoningDeltaData), TypeInfoPropertyName = "SessionEventsAssistantReasoningDeltaData")] [JsonSerializable(typeof(GitHub.Copilot.AssistantReasoningDeltaEvent), TypeInfoPropertyName = "SessionEventsAssistantReasoningDeltaEvent")] [JsonSerializable(typeof(GitHub.Copilot.AssistantReasoningEvent), TypeInfoPropertyName = "SessionEventsAssistantReasoningEvent")] +[JsonSerializable(typeof(GitHub.Copilot.AssistantServerToolProgressData), TypeInfoPropertyName = "SessionEventsAssistantServerToolProgressData")] +[JsonSerializable(typeof(GitHub.Copilot.AssistantServerToolProgressEvent), TypeInfoPropertyName = "SessionEventsAssistantServerToolProgressEvent")] [JsonSerializable(typeof(GitHub.Copilot.AssistantStreamingDeltaData), TypeInfoPropertyName = "SessionEventsAssistantStreamingDeltaData")] [JsonSerializable(typeof(GitHub.Copilot.AssistantStreamingDeltaEvent), TypeInfoPropertyName = "SessionEventsAssistantStreamingDeltaEvent")] +[JsonSerializable(typeof(GitHub.Copilot.AssistantToolCallDeltaData), TypeInfoPropertyName = "SessionEventsAssistantToolCallDeltaData")] +[JsonSerializable(typeof(GitHub.Copilot.AssistantToolCallDeltaEvent), TypeInfoPropertyName = "SessionEventsAssistantToolCallDeltaEvent")] [JsonSerializable(typeof(GitHub.Copilot.AssistantTurnEndData), TypeInfoPropertyName = "SessionEventsAssistantTurnEndData")] [JsonSerializable(typeof(GitHub.Copilot.AssistantTurnEndEvent), TypeInfoPropertyName = "SessionEventsAssistantTurnEndEvent")] [JsonSerializable(typeof(GitHub.Copilot.AssistantTurnStartData), TypeInfoPropertyName = "SessionEventsAssistantTurnStartData")] @@ -20989,12 +23815,25 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.AttachmentExtensionContext), TypeInfoPropertyName = "SessionEventsAttachmentExtensionContext")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentFile), TypeInfoPropertyName = "SessionEventsAttachmentFile")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentFileLineRange), TypeInfoPropertyName = "SessionEventsAttachmentFileLineRange")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubActionsJob), TypeInfoPropertyName = "SessionEventsAttachmentGitHubActionsJob")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubCommit), TypeInfoPropertyName = "SessionEventsAttachmentGitHubCommit")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubFile), TypeInfoPropertyName = "SessionEventsAttachmentGitHubFile")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubFileDiff), TypeInfoPropertyName = "SessionEventsAttachmentGitHubFileDiff")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubFileDiffSide), TypeInfoPropertyName = "SessionEventsAttachmentGitHubFileDiffSide")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubReference), TypeInfoPropertyName = "SessionEventsAttachmentGitHubReference")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubReferenceType), TypeInfoPropertyName = "SessionEventsAttachmentGitHubReferenceType")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubRelease), TypeInfoPropertyName = "SessionEventsAttachmentGitHubRelease")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubRepository), TypeInfoPropertyName = "SessionEventsAttachmentGitHubRepository")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubSnippet), TypeInfoPropertyName = "SessionEventsAttachmentGitHubSnippet")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubTreeComparison), TypeInfoPropertyName = "SessionEventsAttachmentGitHubTreeComparison")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubTreeComparisonSide), TypeInfoPropertyName = "SessionEventsAttachmentGitHubTreeComparisonSide")] +[JsonSerializable(typeof(GitHub.Copilot.AttachmentGitHubUrl), TypeInfoPropertyName = "SessionEventsAttachmentGitHubUrl")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentSelection), TypeInfoPropertyName = "SessionEventsAttachmentSelection")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentSelectionDetails), TypeInfoPropertyName = "SessionEventsAttachmentSelectionDetails")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentSelectionDetailsEnd), TypeInfoPropertyName = "SessionEventsAttachmentSelectionDetailsEnd")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentSelectionDetailsStart), TypeInfoPropertyName = "SessionEventsAttachmentSelectionDetailsStart")] +[JsonSerializable(typeof(GitHub.Copilot.AutoApprovalRecommendation), TypeInfoPropertyName = "SessionEventsAutoApprovalRecommendation")] +[JsonSerializable(typeof(GitHub.Copilot.AutoModeResolvedReasoningBucket), TypeInfoPropertyName = "SessionEventsAutoModeResolvedReasoningBucket")] [JsonSerializable(typeof(GitHub.Copilot.AutoModeSwitchCompletedData), TypeInfoPropertyName = "SessionEventsAutoModeSwitchCompletedData")] [JsonSerializable(typeof(GitHub.Copilot.AutoModeSwitchCompletedEvent), TypeInfoPropertyName = "SessionEventsAutoModeSwitchCompletedEvent")] [JsonSerializable(typeof(GitHub.Copilot.AutoModeSwitchRequestedData), TypeInfoPropertyName = "SessionEventsAutoModeSwitchRequestedData")] @@ -21054,8 +23893,10 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.ExternalToolCompletedEvent), TypeInfoPropertyName = "SessionEventsExternalToolCompletedEvent")] [JsonSerializable(typeof(GitHub.Copilot.ExternalToolRequestedData), TypeInfoPropertyName = "SessionEventsExternalToolRequestedData")] [JsonSerializable(typeof(GitHub.Copilot.ExternalToolRequestedEvent), TypeInfoPropertyName = "SessionEventsExternalToolRequestedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.GitHubRepoRef), TypeInfoPropertyName = "SessionEventsGitHubRepoRef")] [JsonSerializable(typeof(GitHub.Copilot.HandoffRepository), TypeInfoPropertyName = "SessionEventsHandoffRepository")] [JsonSerializable(typeof(GitHub.Copilot.HandoffSourceType), TypeInfoPropertyName = "SessionEventsHandoffSourceType")] +[JsonSerializable(typeof(GitHub.Copilot.HeaderEntry), TypeInfoPropertyName = "SessionEventsHeaderEntry")] [JsonSerializable(typeof(GitHub.Copilot.HookEndData), TypeInfoPropertyName = "SessionEventsHookEndData")] [JsonSerializable(typeof(GitHub.Copilot.HookEndError), TypeInfoPropertyName = "SessionEventsHookEndError")] [JsonSerializable(typeof(GitHub.Copilot.HookEndEvent), TypeInfoPropertyName = "SessionEventsHookEndEvent")] @@ -21063,22 +23904,34 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.HookProgressEvent), TypeInfoPropertyName = "SessionEventsHookProgressEvent")] [JsonSerializable(typeof(GitHub.Copilot.HookStartData), TypeInfoPropertyName = "SessionEventsHookStartData")] [JsonSerializable(typeof(GitHub.Copilot.HookStartEvent), TypeInfoPropertyName = "SessionEventsHookStartEvent")] +[JsonSerializable(typeof(GitHub.Copilot.ManagedSettingsResolvedSource), TypeInfoPropertyName = "SessionEventsManagedSettingsResolvedSource")] [JsonSerializable(typeof(GitHub.Copilot.McpAppToolCallCompleteData), TypeInfoPropertyName = "SessionEventsMcpAppToolCallCompleteData")] [JsonSerializable(typeof(GitHub.Copilot.McpAppToolCallCompleteError), TypeInfoPropertyName = "SessionEventsMcpAppToolCallCompleteError")] [JsonSerializable(typeof(GitHub.Copilot.McpAppToolCallCompleteEvent), TypeInfoPropertyName = "SessionEventsMcpAppToolCallCompleteEvent")] [JsonSerializable(typeof(GitHub.Copilot.McpAppToolCallCompleteToolMeta), TypeInfoPropertyName = "SessionEventsMcpAppToolCallCompleteToolMeta")] [JsonSerializable(typeof(GitHub.Copilot.McpAppToolCallCompleteToolMetaUI), TypeInfoPropertyName = "SessionEventsMcpAppToolCallCompleteToolMetaUI")] +[JsonSerializable(typeof(GitHub.Copilot.McpHeadersRefreshCompletedData), TypeInfoPropertyName = "SessionEventsMcpHeadersRefreshCompletedData")] +[JsonSerializable(typeof(GitHub.Copilot.McpHeadersRefreshCompletedEvent), TypeInfoPropertyName = "SessionEventsMcpHeadersRefreshCompletedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.McpHeadersRefreshCompletedOutcome), TypeInfoPropertyName = "SessionEventsMcpHeadersRefreshCompletedOutcome")] +[JsonSerializable(typeof(GitHub.Copilot.McpHeadersRefreshRequiredData), TypeInfoPropertyName = "SessionEventsMcpHeadersRefreshRequiredData")] +[JsonSerializable(typeof(GitHub.Copilot.McpHeadersRefreshRequiredEvent), TypeInfoPropertyName = "SessionEventsMcpHeadersRefreshRequiredEvent")] +[JsonSerializable(typeof(GitHub.Copilot.McpHeadersRefreshRequiredReason), TypeInfoPropertyName = "SessionEventsMcpHeadersRefreshRequiredReason")] [JsonSerializable(typeof(GitHub.Copilot.McpOauthCompletedData), TypeInfoPropertyName = "SessionEventsMcpOauthCompletedData")] [JsonSerializable(typeof(GitHub.Copilot.McpOauthCompletedEvent), TypeInfoPropertyName = "SessionEventsMcpOauthCompletedEvent")] [JsonSerializable(typeof(GitHub.Copilot.McpOauthCompletionOutcome), TypeInfoPropertyName = "SessionEventsMcpOauthCompletionOutcome")] +[JsonSerializable(typeof(GitHub.Copilot.McpOauthHttpResponse), TypeInfoPropertyName = "SessionEventsMcpOauthHttpResponse")] +[JsonSerializable(typeof(GitHub.Copilot.McpOauthRequestReason), TypeInfoPropertyName = "SessionEventsMcpOauthRequestReason")] [JsonSerializable(typeof(GitHub.Copilot.McpOauthRequiredData), TypeInfoPropertyName = "SessionEventsMcpOauthRequiredData")] [JsonSerializable(typeof(GitHub.Copilot.McpOauthRequiredEvent), TypeInfoPropertyName = "SessionEventsMcpOauthRequiredEvent")] [JsonSerializable(typeof(GitHub.Copilot.McpOauthRequiredStaticClientConfig), TypeInfoPropertyName = "SessionEventsMcpOauthRequiredStaticClientConfig")] [JsonSerializable(typeof(GitHub.Copilot.McpOauthWWWAuthenticateParams), TypeInfoPropertyName = "SessionEventsMcpOauthWWWAuthenticateParams")] +[JsonSerializable(typeof(GitHub.Copilot.McpPromptsListChangedEvent), TypeInfoPropertyName = "SessionEventsMcpPromptsListChangedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.McpResourcesListChangedEvent), TypeInfoPropertyName = "SessionEventsMcpResourcesListChangedEvent")] [JsonSerializable(typeof(GitHub.Copilot.McpServerSource), TypeInfoPropertyName = "SessionEventsMcpServerSource")] [JsonSerializable(typeof(GitHub.Copilot.McpServerStatus), TypeInfoPropertyName = "SessionEventsMcpServerStatus")] [JsonSerializable(typeof(GitHub.Copilot.McpServerTransport), TypeInfoPropertyName = "SessionEventsMcpServerTransport")] [JsonSerializable(typeof(GitHub.Copilot.McpServersLoadedServer), TypeInfoPropertyName = "SessionEventsMcpServersLoadedServer")] +[JsonSerializable(typeof(GitHub.Copilot.McpToolsListChangedEvent), TypeInfoPropertyName = "SessionEventsMcpToolsListChangedEvent")] [JsonSerializable(typeof(GitHub.Copilot.ModelCallFailureBadRequestKind), TypeInfoPropertyName = "SessionEventsModelCallFailureBadRequestKind")] [JsonSerializable(typeof(GitHub.Copilot.ModelCallFailureData), TypeInfoPropertyName = "SessionEventsModelCallFailureData")] [JsonSerializable(typeof(GitHub.Copilot.ModelCallFailureEvent), TypeInfoPropertyName = "SessionEventsModelCallFailureEvent")] @@ -21089,6 +23942,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.OmittedBinaryType), TypeInfoPropertyName = "SessionEventsOmittedBinaryType")] [JsonSerializable(typeof(GitHub.Copilot.PendingMessagesModifiedData), TypeInfoPropertyName = "SessionEventsPendingMessagesModifiedData")] [JsonSerializable(typeof(GitHub.Copilot.PendingMessagesModifiedEvent), TypeInfoPropertyName = "SessionEventsPendingMessagesModifiedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.PermissionAllowAllMode), TypeInfoPropertyName = "SessionEventsPermissionAllowAllMode")] +[JsonSerializable(typeof(GitHub.Copilot.PermissionAutoApproval), TypeInfoPropertyName = "SessionEventsPermissionAutoApproval")] [JsonSerializable(typeof(GitHub.Copilot.PermissionCompletedData), TypeInfoPropertyName = "SessionEventsPermissionCompletedData")] [JsonSerializable(typeof(GitHub.Copilot.PermissionCompletedEvent), TypeInfoPropertyName = "SessionEventsPermissionCompletedEvent")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequest), TypeInfoPropertyName = "SessionEventsPermissionPromptRequest")] @@ -21133,6 +23988,13 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.SamplingRequestedData), TypeInfoPropertyName = "SessionEventsSamplingRequestedData")] [JsonSerializable(typeof(GitHub.Copilot.SamplingRequestedEvent), TypeInfoPropertyName = "SessionEventsSamplingRequestedEvent")] [JsonSerializable(typeof(GitHub.Copilot.SessionEvent), TypeInfoPropertyName = "SessionEventsSessionEvent")] +[JsonSerializable(typeof(GitHub.Copilot.SessionLimitsConfig), TypeInfoPropertyName = "SessionEventsSessionLimitsConfig")] +[JsonSerializable(typeof(GitHub.Copilot.SessionLimitsExhaustedCompletedData), TypeInfoPropertyName = "SessionEventsSessionLimitsExhaustedCompletedData")] +[JsonSerializable(typeof(GitHub.Copilot.SessionLimitsExhaustedCompletedEvent), TypeInfoPropertyName = "SessionEventsSessionLimitsExhaustedCompletedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.SessionLimitsExhaustedRequestedData), TypeInfoPropertyName = "SessionEventsSessionLimitsExhaustedRequestedData")] +[JsonSerializable(typeof(GitHub.Copilot.SessionLimitsExhaustedRequestedEvent), TypeInfoPropertyName = "SessionEventsSessionLimitsExhaustedRequestedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.SessionLimitsExhaustedResponse), TypeInfoPropertyName = "SessionEventsSessionLimitsExhaustedResponse")] +[JsonSerializable(typeof(GitHub.Copilot.SessionLimitsExhaustedResponseAction), TypeInfoPropertyName = "SessionEventsSessionLimitsExhaustedResponseAction")] [JsonSerializable(typeof(GitHub.Copilot.SessionMode), TypeInfoPropertyName = "SessionEventsSessionMode")] [JsonSerializable(typeof(GitHub.Copilot.ShutdownCodeChanges), TypeInfoPropertyName = "SessionEventsShutdownCodeChanges")] [JsonSerializable(typeof(GitHub.Copilot.ShutdownModelMetric), TypeInfoPropertyName = "SessionEventsShutdownModelMetric")] @@ -21178,6 +24040,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentResourceLink), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentResourceLink")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentResourceLinkIcon), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentResourceLinkIcon")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentResourceLinkIconTheme), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentResourceLinkIconTheme")] +[JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentShellExit), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentShellExit")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentTerminal), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentTerminal")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentText), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentText")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteData), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteData")] @@ -21202,6 +24065,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionProgressEvent), TypeInfoPropertyName = "SessionEventsToolExecutionProgressEvent")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionStartData), TypeInfoPropertyName = "SessionEventsToolExecutionStartData")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionStartEvent), TypeInfoPropertyName = "SessionEventsToolExecutionStartEvent")] +[JsonSerializable(typeof(GitHub.Copilot.ToolExecutionStartShellToolInfo), TypeInfoPropertyName = "SessionEventsToolExecutionStartShellToolInfo")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionStartToolDescription), TypeInfoPropertyName = "SessionEventsToolExecutionStartToolDescription")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionStartToolDescriptionMeta), TypeInfoPropertyName = "SessionEventsToolExecutionStartToolDescriptionMeta")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionStartToolDescriptionMetaUI), TypeInfoPropertyName = "SessionEventsToolExecutionStartToolDescriptionMetaUI")] @@ -21214,6 +24078,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.UserInputRequestedEvent), TypeInfoPropertyName = "SessionEventsUserInputRequestedEvent")] [JsonSerializable(typeof(GitHub.Copilot.UserMessageAgentMode), TypeInfoPropertyName = "SessionEventsUserMessageAgentMode")] [JsonSerializable(typeof(GitHub.Copilot.UserMessageData), TypeInfoPropertyName = "SessionEventsUserMessageData")] +[JsonSerializable(typeof(GitHub.Copilot.UserMessageDelivery), TypeInfoPropertyName = "SessionEventsUserMessageDelivery")] [JsonSerializable(typeof(GitHub.Copilot.UserMessageEvent), TypeInfoPropertyName = "SessionEventsUserMessageEvent")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApproval), TypeInfoPropertyName = "SessionEventsUserToolSessionApproval")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalCommands), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalCommands")] @@ -21224,6 +24089,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalMemory), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalMemory")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalRead), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalRead")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalWrite), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalWrite")] +[JsonSerializable(typeof(GitHub.Copilot.Verbosity), TypeInfoPropertyName = "SessionEventsVerbosity")] [JsonSerializable(typeof(GitHub.Copilot.WorkingDirectoryContext), TypeInfoPropertyName = "SessionEventsWorkingDirectoryContext")] [JsonSerializable(typeof(GitHub.Copilot.WorkingDirectoryContextHostType), TypeInfoPropertyName = "SessionEventsWorkingDirectoryContextHostType")] [JsonSerializable(typeof(GitHub.Copilot.WorkspaceFileChangedOperation), TypeInfoPropertyName = "SessionEventsWorkspaceFileChangedOperation")] @@ -21279,12 +24145,16 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(CommandsListRequestWithSession))] [JsonSerializable(typeof(CommandsRespondToQueuedCommandRequest))] [JsonSerializable(typeof(CommandsRespondToQueuedCommandResult))] +[JsonSerializable(typeof(CompletionsGetTriggerCharactersResult))] +[JsonSerializable(typeof(CompletionsRequestRequest))] +[JsonSerializable(typeof(CompletionsRequestResult))] [JsonSerializable(typeof(ConfigureSessionExtensionsParams))] [JsonSerializable(typeof(ConnectRemoteSessionParams))] [JsonSerializable(typeof(ConnectRequest))] [JsonSerializable(typeof(ConnectResult))] [JsonSerializable(typeof(ConnectedRemoteSessionMetadata))] [JsonSerializable(typeof(ConnectedRemoteSessionMetadataRepository))] +[JsonSerializable(typeof(ContextHeaviestMessage))] [JsonSerializable(typeof(CopilotUserResponse))] [JsonSerializable(typeof(CopilotUserResponseEndpoints))] [JsonSerializable(typeof(CopilotUserResponseOrganizationListItem))] @@ -21294,6 +24164,13 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(CopilotUserResponseQuotaSnapshotsPremiumInteractions))] [JsonSerializable(typeof(CurrentModel))] [JsonSerializable(typeof(CurrentToolMetadata))] +[JsonSerializable(typeof(DebugCollectLogsCollectedEntry))] +[JsonSerializable(typeof(DebugCollectLogsDestination))] +[JsonSerializable(typeof(DebugCollectLogsEntry))] +[JsonSerializable(typeof(DebugCollectLogsInclude))] +[JsonSerializable(typeof(DebugCollectLogsRequest))] +[JsonSerializable(typeof(DebugCollectLogsResult))] +[JsonSerializable(typeof(DebugCollectLogsSkippedEntry))] [JsonSerializable(typeof(DiscoveredCanvas))] [JsonSerializable(typeof(DiscoveredMcpServer))] [JsonSerializable(typeof(EnqueueCommandParams))] @@ -21313,6 +24190,9 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(FolderTrustAddParams))] [JsonSerializable(typeof(FolderTrustCheckParams))] [JsonSerializable(typeof(FolderTrustCheckResult))] +[JsonSerializable(typeof(GitHubTelemetryClientInfo))] +[JsonSerializable(typeof(GitHubTelemetryEvent))] +[JsonSerializable(typeof(GitHubTelemetryNotification))] [JsonSerializable(typeof(HandlePendingToolCallRequest))] [JsonSerializable(typeof(HandlePendingToolCallResult))] [JsonSerializable(typeof(HistoryAbortManualCompactionResult))] @@ -21324,6 +24204,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(HistorySummarizeForHandoffResult))] [JsonSerializable(typeof(HistoryTruncateRequest))] [JsonSerializable(typeof(HistoryTruncateResult))] +[JsonSerializable(typeof(IDictionary))] +[JsonSerializable(typeof(IList))] [JsonSerializable(typeof(InstalledPlugin))] [JsonSerializable(typeof(InstalledPluginInfo))] [JsonSerializable(typeof(InstructionDiscoveryPath))] @@ -21387,6 +24269,9 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(McpExecuteSamplingRequest))] [JsonSerializable(typeof(McpExecuteSamplingResult))] [JsonSerializable(typeof(McpFilteredServer))] +[JsonSerializable(typeof(McpHeadersHandlePendingHeadersRefreshRequest))] +[JsonSerializable(typeof(McpHeadersHandlePendingHeadersRefreshRequestRequest))] +[JsonSerializable(typeof(McpHeadersHandlePendingHeadersRefreshRequestResult))] [JsonSerializable(typeof(McpHostState))] [JsonSerializable(typeof(McpIsServerRunningRequest))] [JsonSerializable(typeof(McpIsServerRunningResult))] @@ -21397,11 +24282,20 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(McpOauthLoginRequest))] [JsonSerializable(typeof(McpOauthLoginResult))] [JsonSerializable(typeof(McpOauthPendingRequestResponse))] -[JsonSerializable(typeof(McpOauthRespondRequest))] -[JsonSerializable(typeof(McpOauthRespondResult))] [JsonSerializable(typeof(McpRegisterExternalClientRequest))] [JsonSerializable(typeof(McpReloadWithConfigRequest))] [JsonSerializable(typeof(McpRemoveGitHubResult))] +[JsonSerializable(typeof(McpResource))] +[JsonSerializable(typeof(McpResourceAnnotations))] +[JsonSerializable(typeof(McpResourceContent))] +[JsonSerializable(typeof(McpResourceIcon))] +[JsonSerializable(typeof(McpResourceTemplate))] +[JsonSerializable(typeof(McpResourcesListRequest))] +[JsonSerializable(typeof(McpResourcesListResult))] +[JsonSerializable(typeof(McpResourcesListTemplatesRequest))] +[JsonSerializable(typeof(McpResourcesListTemplatesResult))] +[JsonSerializable(typeof(McpResourcesReadRequest))] +[JsonSerializable(typeof(McpResourcesReadResult))] [JsonSerializable(typeof(McpRestartServerRequest))] [JsonSerializable(typeof(McpSamplingExecutionResult))] [JsonSerializable(typeof(McpServer))] @@ -21413,8 +24307,15 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(McpStartServerRequest))] [JsonSerializable(typeof(McpStartServersResult))] [JsonSerializable(typeof(McpStopServerRequest))] +[JsonSerializable(typeof(McpToolUi))] [JsonSerializable(typeof(McpTools))] [JsonSerializable(typeof(McpUnregisterExternalClientRequest))] +[JsonSerializable(typeof(MetadataContextAttributionResult))] +[JsonSerializable(typeof(MetadataContextAttributionResultContextAttribution))] +[JsonSerializable(typeof(MetadataContextAttributionResultContextAttributionCompactions))] +[JsonSerializable(typeof(MetadataContextAttributionResultContextAttributionEntry))] +[JsonSerializable(typeof(MetadataContextHeaviestMessagesRequest))] +[JsonSerializable(typeof(MetadataContextHeaviestMessagesResult))] [JsonSerializable(typeof(MetadataContextInfoRequest))] [JsonSerializable(typeof(MetadataContextInfoResult))] [JsonSerializable(typeof(MetadataContextInfoResultContextInfo))] @@ -21430,6 +24331,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ModeSetRequest))] [JsonSerializable(typeof(Model))] [JsonSerializable(typeof(ModelBilling))] +[JsonSerializable(typeof(ModelBillingPromo))] [JsonSerializable(typeof(ModelBillingTokenPrices))] [JsonSerializable(typeof(ModelBillingTokenPricesLongContext))] [JsonSerializable(typeof(ModelCapabilities))] @@ -21532,7 +24434,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(PluginsReloadRequestWithSession))] [JsonSerializable(typeof(PluginsUninstallRequest))] [JsonSerializable(typeof(PluginsUpdateRequest))] -[JsonSerializable(typeof(PollSpawnedSessionsResult))] [JsonSerializable(typeof(ProviderAddRequest))] [JsonSerializable(typeof(ProviderAddResult))] [JsonSerializable(typeof(ProviderConfig))] @@ -21546,9 +24447,12 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ProviderTokenAcquireResult))] [JsonSerializable(typeof(PushAttachment))] [JsonSerializable(typeof(PushAttachmentFileLineRange))] +[JsonSerializable(typeof(PushAttachmentGitHubFileDiffSide))] +[JsonSerializable(typeof(PushAttachmentGitHubTreeComparisonSide))] [JsonSerializable(typeof(PushAttachmentSelectionDetails))] [JsonSerializable(typeof(PushAttachmentSelectionDetailsEnd))] [JsonSerializable(typeof(PushAttachmentSelectionDetailsStart))] +[JsonSerializable(typeof(PushGitHubRepoRef))] [JsonSerializable(typeof(QueuePendingItems))] [JsonSerializable(typeof(QueuePendingItemsResult))] [JsonSerializable(typeof(QueueRemoveMostRecentResult))] @@ -21585,6 +24489,9 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SecretsAddFilterValuesRequest))] [JsonSerializable(typeof(SecretsAddFilterValuesResult))] [JsonSerializable(typeof(SendAttachmentsToMessageParams))] +[JsonSerializable(typeof(SendMessageItem))] +[JsonSerializable(typeof(SendMessagesRequest))] +[JsonSerializable(typeof(SendMessagesResult))] [JsonSerializable(typeof(SendRequest))] [JsonSerializable(typeof(SendResult))] [JsonSerializable(typeof(ServerAgentList))] @@ -21596,11 +24503,12 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionAgentGetCurrentRequest))] [JsonSerializable(typeof(SessionAgentListRequest))] [JsonSerializable(typeof(SessionAgentReloadRequest))] -[JsonSerializable(typeof(SessionAuthGetStatusRequest))] [JsonSerializable(typeof(SessionAuthStatus))] [JsonSerializable(typeof(SessionBulkDeleteResult))] [JsonSerializable(typeof(SessionCanvasListOpenRequest))] [JsonSerializable(typeof(SessionCanvasListRequest))] +[JsonSerializable(typeof(SessionCompletionItem))] +[JsonSerializable(typeof(SessionCompletionsGetTriggerCharactersRequest))] [JsonSerializable(typeof(SessionContext))] [JsonSerializable(typeof(SessionEnrichMetadataResult))] [JsonSerializable(typeof(SessionEventLogTailRequest))] @@ -21630,6 +24538,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionFsStatRequest))] [JsonSerializable(typeof(SessionFsStatResult))] [JsonSerializable(typeof(SessionFsWriteFileRequest))] +[JsonSerializable(typeof(SessionGitHubAuthGetStatusRequest))] [JsonSerializable(typeof(SessionHistoryAbortManualCompactionRequest))] [JsonSerializable(typeof(SessionHistoryCancelBackgroundCompactionRequest))] [JsonSerializable(typeof(SessionHistorySummarizeForHandoffRequest))] @@ -21644,6 +24553,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionMcpReloadRequest))] [JsonSerializable(typeof(SessionMcpRemoveGitHubRequest))] [JsonSerializable(typeof(SessionMetadataActivityRequest))] +[JsonSerializable(typeof(SessionMetadataGetContextAttributionRequest))] [JsonSerializable(typeof(SessionMetadataIsProcessingRequest))] [JsonSerializable(typeof(SessionMetadataSnapshot))] [JsonSerializable(typeof(SessionMetadataSnapshotRequest))] @@ -21651,6 +24561,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionModeGetRequest))] [JsonSerializable(typeof(SessionModelGetCurrentRequest))] [JsonSerializable(typeof(SessionModelList))] +[JsonSerializable(typeof(SessionModelPriceCategory))] [JsonSerializable(typeof(SessionNameGetRequest))] [JsonSerializable(typeof(SessionOpenResult))] [JsonSerializable(typeof(SessionPlanDeleteRequest))] @@ -21666,6 +24577,16 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionScheduleListRequest))] [JsonSerializable(typeof(SessionSetCredentialsParams))] [JsonSerializable(typeof(SessionSetCredentialsResult))] +[JsonSerializable(typeof(SessionSettingsBuiltInToolAvailabilitySnapshot))] +[JsonSerializable(typeof(SessionSettingsEvaluatePredicateRequest))] +[JsonSerializable(typeof(SessionSettingsEvaluatePredicateResult))] +[JsonSerializable(typeof(SessionSettingsJobSnapshot))] +[JsonSerializable(typeof(SessionSettingsModelSnapshot))] +[JsonSerializable(typeof(SessionSettingsOnlineEvaluationSnapshot))] +[JsonSerializable(typeof(SessionSettingsRepoSnapshot))] +[JsonSerializable(typeof(SessionSettingsSnapshot))] +[JsonSerializable(typeof(SessionSettingsSnapshotRequest))] +[JsonSerializable(typeof(SessionSettingsValidationSnapshot))] [JsonSerializable(typeof(SessionSizes))] [JsonSerializable(typeof(SessionSkillsEnsureLoadedRequest))] [JsonSerializable(typeof(SessionSkillsGetInvokedRequest))] @@ -21685,6 +24606,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionUpdateOptionsParams))] [JsonSerializable(typeof(SessionUpdateOptionsResult))] [JsonSerializable(typeof(SessionUsageGetMetricsRequest))] +[JsonSerializable(typeof(SessionVisibilityGetRequest))] [JsonSerializable(typeof(SessionWorkingDirectoryContext))] [JsonSerializable(typeof(SessionWorkspacesGetWorkspaceRequest))] [JsonSerializable(typeof(SessionWorkspacesListCheckpointsRequest))] @@ -21712,8 +24634,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionsListRequest))] [JsonSerializable(typeof(SessionsLoadDeferredRepoHooksRequest))] [JsonSerializable(typeof(SessionsOpenProgress))] -[JsonSerializable(typeof(SessionsPollSpawnedSessionsEvent))] -[JsonSerializable(typeof(SessionsPollSpawnedSessionsRequest))] [JsonSerializable(typeof(SessionsPruneOldRequest))] [JsonSerializable(typeof(SessionsRegisterExtensionToolsOnSessionOptions))] [JsonSerializable(typeof(SessionsReleaseLockRequest))] @@ -21749,6 +24669,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SkillsLoadDiagnostics))] [JsonSerializable(typeof(SlashCommandInfo))] [JsonSerializable(typeof(SlashCommandInput))] +[JsonSerializable(typeof(SlashCommandInputChoice))] [JsonSerializable(typeof(SlashCommandInvocationResult))] [JsonSerializable(typeof(SlashCommandSelectSubcommandOption))] [JsonSerializable(typeof(SubagentSettingsEntry))] @@ -21792,8 +24713,10 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(UIHandlePendingResult))] [JsonSerializable(typeof(UIHandlePendingSamplingRequest))] [JsonSerializable(typeof(UIHandlePendingSamplingResponse))] +[JsonSerializable(typeof(UIHandlePendingSessionLimitsExhaustedRequest))] [JsonSerializable(typeof(UIHandlePendingUserInputRequest))] [JsonSerializable(typeof(UIRegisterDirectAutoModeSwitchHandlerResult))] +[JsonSerializable(typeof(UISessionLimitsExhaustedResponse))] [JsonSerializable(typeof(UIUnregisterDirectAutoModeSwitchHandlerRequest))] [JsonSerializable(typeof(UIUnregisterDirectAutoModeSwitchHandlerResult))] [JsonSerializable(typeof(UIUserInputResponse))] @@ -21807,6 +24730,13 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(UsageMetricsModelMetricUsage))] [JsonSerializable(typeof(UsageMetricsTokenDetail))] [JsonSerializable(typeof(UserRequestedShellCommandResult))] +[JsonSerializable(typeof(UserSettingMetadata))] +[JsonSerializable(typeof(UserSettingsGetResult))] +[JsonSerializable(typeof(UserSettingsSetRequest))] +[JsonSerializable(typeof(UserSettingsSetResult))] +[JsonSerializable(typeof(VisibilityGetResult))] +[JsonSerializable(typeof(VisibilitySetRequest))] +[JsonSerializable(typeof(VisibilitySetResult))] [JsonSerializable(typeof(WorkspaceDiffFileChange))] [JsonSerializable(typeof(WorkspaceDiffResult))] [JsonSerializable(typeof(WorkspacesCheckpoints))] diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index f1765e5c44..41b87d06ff 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -25,13 +25,16 @@ namespace GitHub.Copilot; TypeDiscriminatorPropertyName = "type", IgnoreUnrecognizedTypeDiscriminators = true)] [JsonDerivedType(typeof(AbortEvent), "abort")] +[JsonDerivedType(typeof(AssistantIdleEvent), "assistant.idle")] [JsonDerivedType(typeof(AssistantIntentEvent), "assistant.intent")] [JsonDerivedType(typeof(AssistantMessageEvent), "assistant.message")] [JsonDerivedType(typeof(AssistantMessageDeltaEvent), "assistant.message_delta")] [JsonDerivedType(typeof(AssistantMessageStartEvent), "assistant.message_start")] [JsonDerivedType(typeof(AssistantReasoningEvent), "assistant.reasoning")] [JsonDerivedType(typeof(AssistantReasoningDeltaEvent), "assistant.reasoning_delta")] +[JsonDerivedType(typeof(AssistantServerToolProgressEvent), "assistant.server_tool_progress")] [JsonDerivedType(typeof(AssistantStreamingDeltaEvent), "assistant.streaming_delta")] +[JsonDerivedType(typeof(AssistantToolCallDeltaEvent), "assistant.tool_call_delta")] [JsonDerivedType(typeof(AssistantTurnEndEvent), "assistant.turn_end")] [JsonDerivedType(typeof(AssistantTurnStartEvent), "assistant.turn_start")] [JsonDerivedType(typeof(AssistantUsageEvent), "assistant.usage")] @@ -52,14 +55,22 @@ namespace GitHub.Copilot; [JsonDerivedType(typeof(HookProgressEvent), "hook.progress")] [JsonDerivedType(typeof(HookStartEvent), "hook.start")] [JsonDerivedType(typeof(McpAppToolCallCompleteEvent), "mcp_app.tool_call_complete")] +[JsonDerivedType(typeof(McpHeadersRefreshCompletedEvent), "mcp.headers_refresh_completed")] +[JsonDerivedType(typeof(McpHeadersRefreshRequiredEvent), "mcp.headers_refresh_required")] [JsonDerivedType(typeof(McpOauthCompletedEvent), "mcp.oauth_completed")] [JsonDerivedType(typeof(McpOauthRequiredEvent), "mcp.oauth_required")] +[JsonDerivedType(typeof(McpPromptsListChangedEvent), "mcp.prompts.list_changed")] +[JsonDerivedType(typeof(McpResourcesListChangedEvent), "mcp.resources.list_changed")] +[JsonDerivedType(typeof(McpToolsListChangedEvent), "mcp.tools.list_changed")] [JsonDerivedType(typeof(ModelCallFailureEvent), "model.call_failure")] [JsonDerivedType(typeof(PendingMessagesModifiedEvent), "pending_messages.modified")] [JsonDerivedType(typeof(PermissionCompletedEvent), "permission.completed")] [JsonDerivedType(typeof(PermissionRequestedEvent), "permission.requested")] [JsonDerivedType(typeof(SamplingCompletedEvent), "sampling.completed")] [JsonDerivedType(typeof(SamplingRequestedEvent), "sampling.requested")] +[JsonDerivedType(typeof(SessionLimitsExhaustedCompletedEvent), "session_limits_exhausted.completed")] +[JsonDerivedType(typeof(SessionLimitsExhaustedRequestedEvent), "session_limits_exhausted.requested")] +[JsonDerivedType(typeof(SessionAutoModeResolvedEvent), "session.auto_mode_resolved")] [JsonDerivedType(typeof(SessionAutopilotObjectiveChangedEvent), "session.autopilot_objective_changed")] [JsonDerivedType(typeof(SessionBackgroundTasksChangedEvent), "session.background_tasks_changed")] [JsonDerivedType(typeof(SessionBinaryAssetEvent), "session.binary_asset")] @@ -80,6 +91,7 @@ namespace GitHub.Copilot; [JsonDerivedType(typeof(SessionHandoffEvent), "session.handoff")] [JsonDerivedType(typeof(SessionIdleEvent), "session.idle")] [JsonDerivedType(typeof(SessionInfoEvent), "session.info")] +[JsonDerivedType(typeof(SessionManagedSettingsResolvedEvent), "session.managed_settings_resolved")] [JsonDerivedType(typeof(SessionMcpServerStatusChangedEvent), "session.mcp_server_status_changed")] [JsonDerivedType(typeof(SessionMcpServersLoadedEvent), "session.mcp_servers_loaded")] [JsonDerivedType(typeof(SessionModeChangedEvent), "session.mode_changed")] @@ -91,6 +103,7 @@ namespace GitHub.Copilot; [JsonDerivedType(typeof(SessionScheduleCancelledEvent), "session.schedule_cancelled")] [JsonDerivedType(typeof(SessionScheduleCreatedEvent), "session.schedule_created")] [JsonDerivedType(typeof(SessionScheduleRearmedEvent), "session.schedule_rearmed")] +[JsonDerivedType(typeof(SessionSessionLimitsChangedEvent), "session.session_limits_changed")] [JsonDerivedType(typeof(SessionShutdownEvent), "session.shutdown")] [JsonDerivedType(typeof(SessionSkillsLoadedEvent), "session.skills_loaded")] [JsonDerivedType(typeof(SessionSnapshotRewindEvent), "session.snapshot_rewind")] @@ -100,6 +113,7 @@ namespace GitHub.Copilot; [JsonDerivedType(typeof(SessionTodosChangedEvent), "session.todos_changed")] [JsonDerivedType(typeof(SessionToolsUpdatedEvent), "session.tools_updated")] [JsonDerivedType(typeof(SessionTruncationEvent), "session.truncation")] +[JsonDerivedType(typeof(SessionUsageCheckpointEvent), "session.usage_checkpoint")] [JsonDerivedType(typeof(SessionUsageInfoEvent), "session.usage_info")] [JsonDerivedType(typeof(SessionWarningEvent), "session.warning")] [JsonDerivedType(typeof(SessionWorkspaceFileChangedEvent), "session.workspace_file_changed")] @@ -343,7 +357,20 @@ public sealed partial class SessionModeChangedEvent : SessionEvent public required SessionModeChangedData Data { get; set; } } -/// Permissions change details carrying the aggregate allow-all boolean transition. +/// Session limits update details. Null clears the limits. +/// Represents the session.session_limits_changed event. +public sealed partial class SessionSessionLimitsChangedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "session.session_limits_changed"; + + /// The session.session_limits_changed event payload. + [JsonPropertyName("data")] + public required SessionSessionLimitsChangedData Data { get; set; } +} + +/// Permissions change details carrying the aggregate allow-all transition. /// Represents the session.permissions_changed event. public sealed partial class SessionPermissionsChangedEvent : SessionEvent { @@ -447,6 +474,19 @@ public sealed partial class SessionShutdownEvent : SessionEvent public required SessionShutdownData Data { get; set; } } +/// Durable session usage checkpoint for reconstructing aggregate accounting on resume. +/// Represents the session.usage_checkpoint event. +public sealed partial class SessionUsageCheckpointEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "session.usage_checkpoint"; + + /// The session.usage_checkpoint event payload. + [JsonPropertyName("data")] + public required SessionUsageCheckpointData Data { get; set; } +} + /// Working directory and git context at session start. /// Represents the session.context_changed event. public sealed partial class SessionContextChangedEvent : SessionEvent @@ -512,7 +552,7 @@ public sealed partial class SessionTaskCompleteEvent : SessionEvent public required SessionTaskCompleteData Data { get; set; } } -/// Schema for the `UserMessageData` type. +/// Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. /// Represents the user.message event. public sealed partial class UserMessageEvent : SessionEvent { @@ -564,6 +604,19 @@ public sealed partial class AssistantIntentEvent : SessionEvent public required AssistantIntentData Data { get; set; } } +/// Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message. +/// Represents the assistant.server_tool_progress event. +public sealed partial class AssistantServerToolProgressEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "assistant.server_tool_progress"; + + /// The assistant.server_tool_progress event payload. + [JsonPropertyName("data")] + public required AssistantServerToolProgressData Data { get; set; } +} + /// Assistant reasoning content for timeline display with complete thinking text. /// Represents the assistant.reasoning event. public sealed partial class AssistantReasoningEvent : SessionEvent @@ -590,6 +643,19 @@ public sealed partial class AssistantReasoningDeltaEvent : SessionEvent public required AssistantReasoningDeltaData Data { get; set; } } +/// Streaming tool-call input delta for incremental tool-call updates. +/// Represents the assistant.tool_call_delta event. +public sealed partial class AssistantToolCallDeltaEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "assistant.tool_call_delta"; + + /// The assistant.tool_call_delta event payload. + [JsonPropertyName("data")] + public required AssistantToolCallDeltaData Data { get; set; } +} + /// Streaming response progress with cumulative byte count. /// Represents the assistant.streaming_delta event. public sealed partial class AssistantStreamingDeltaEvent : SessionEvent @@ -655,6 +721,19 @@ public sealed partial class AssistantTurnEndEvent : SessionEvent public required AssistantTurnEndData Data { get; set; } } +/// Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred. +/// Represents the assistant.idle event. +public sealed partial class AssistantIdleEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "assistant.idle"; + + /// The assistant.idle event payload. + [JsonPropertyName("data")] + public required AssistantIdleData Data { get; set; } +} + /// LLM API call usage metrics including tokens, costs, quotas, and billing information. /// Represents the assistant.usage event. public sealed partial class AssistantUsageEvent : SessionEvent @@ -1046,6 +1125,32 @@ public sealed partial class McpOauthCompletedEvent : SessionEvent public required McpOauthCompletedData Data { get; set; } } +/// Dynamic headers refresh request for a remote MCP server. +/// Represents the mcp.headers_refresh_required event. +public sealed partial class McpHeadersRefreshRequiredEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "mcp.headers_refresh_required"; + + /// The mcp.headers_refresh_required event payload. + [JsonPropertyName("data")] + public required McpHeadersRefreshRequiredData Data { get; set; } +} + +/// MCP headers refresh request completion notification. +/// Represents the mcp.headers_refresh_completed event. +public sealed partial class McpHeadersRefreshCompletedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "mcp.headers_refresh_completed"; + + /// The mcp.headers_refresh_completed event payload. + [JsonPropertyName("data")] + public required McpHeadersRefreshCompletedData Data { get; set; } +} + /// Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. /// Represents the session.custom_notification event. public sealed partial class SessionCustomNotificationEvent : SessionEvent @@ -1150,6 +1255,60 @@ public sealed partial class AutoModeSwitchCompletedEvent : SessionEvent public required AutoModeSwitchCompletedData Data { get; set; } } +/// Session limit exhaustion notification requiring user action. +/// Represents the session_limits_exhausted.requested event. +public sealed partial class SessionLimitsExhaustedRequestedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "session_limits_exhausted.requested"; + + /// The session_limits_exhausted.requested event payload. + [JsonPropertyName("data")] + public required SessionLimitsExhaustedRequestedData Data { get; set; } +} + +/// Session limit exhaustion prompt completion notification. +/// Represents the session_limits_exhausted.completed event. +public sealed partial class SessionLimitsExhaustedCompletedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "session_limits_exhausted.completed"; + + /// The session_limits_exhausted.completed event payload. + [JsonPropertyName("data")] + public required SessionLimitsExhaustedCompletedData Data { get; set; } +} + +/// Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. +/// Represents the session.auto_mode_resolved event. +[Experimental(Diagnostics.Experimental)] +public sealed partial class SessionAutoModeResolvedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "session.auto_mode_resolved"; + + /// The session.auto_mode_resolved event payload. + [JsonPropertyName("data")] + public required SessionAutoModeResolvedData Data { get; set; } +} + +/// Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. +/// Represents the session.managed_settings_resolved event. +[Experimental(Diagnostics.Experimental)] +public sealed partial class SessionManagedSettingsResolvedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "session.managed_settings_resolved"; + + /// The session.managed_settings_resolved event payload. + [JsonPropertyName("data")] + public required SessionManagedSettingsResolvedData Data { get; set; } +} + /// SDK command registration change notification. /// Represents the commands.changed event. public sealed partial class CommandsChangedEvent : SessionEvent @@ -1202,7 +1361,7 @@ public sealed partial class ExitPlanModeCompletedEvent : SessionEvent public required ExitPlanModeCompletedData Data { get; set; } } -/// Schema for the `ToolsUpdatedData` type. +/// Payload of `session.tools_updated` identifying the model whose resolved tools were updated. /// Represents the session.tools_updated event. public sealed partial class SessionToolsUpdatedEvent : SessionEvent { @@ -1215,7 +1374,7 @@ public sealed partial class SessionToolsUpdatedEvent : SessionEvent public required SessionToolsUpdatedData Data { get; set; } } -/// Schema for the `BackgroundTasksChangedData` type. +/// Empty payload for `session.background_tasks_changed`, indicating background task state changed. /// Represents the session.background_tasks_changed event. public sealed partial class SessionBackgroundTasksChangedEvent : SessionEvent { @@ -1228,7 +1387,7 @@ public sealed partial class SessionBackgroundTasksChangedEvent : SessionEvent public required SessionBackgroundTasksChangedData Data { get; set; } } -/// Schema for the `SkillsLoadedData` type. +/// Payload of `session.skills_loaded` listing resolved skill metadata. /// Represents the session.skills_loaded event. public sealed partial class SessionSkillsLoadedEvent : SessionEvent { @@ -1241,7 +1400,7 @@ public sealed partial class SessionSkillsLoadedEvent : SessionEvent public required SessionSkillsLoadedData Data { get; set; } } -/// Schema for the `CustomAgentsUpdatedData` type. +/// Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. /// Represents the session.custom_agents_updated event. public sealed partial class SessionCustomAgentsUpdatedEvent : SessionEvent { @@ -1254,7 +1413,7 @@ public sealed partial class SessionCustomAgentsUpdatedEvent : SessionEvent public required SessionCustomAgentsUpdatedData Data { get; set; } } -/// Schema for the `McpServersLoadedData` type. +/// Payload of `session.mcp_servers_loaded` listing MCP server status summaries. /// Represents the session.mcp_servers_loaded event. public sealed partial class SessionMcpServersLoadedEvent : SessionEvent { @@ -1267,7 +1426,7 @@ public sealed partial class SessionMcpServersLoadedEvent : SessionEvent public required SessionMcpServersLoadedData Data { get; set; } } -/// Schema for the `McpServerStatusChangedData` type. +/// Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. /// Represents the session.mcp_server_status_changed event. public sealed partial class SessionMcpServerStatusChangedEvent : SessionEvent { @@ -1280,7 +1439,46 @@ public sealed partial class SessionMcpServerStatusChangedEvent : SessionEvent public required SessionMcpServerStatusChangedData Data { get; set; } } -/// Schema for the `ExtensionsLoadedData` type. +/// Payload identifying the MCP server associated with a list change. +/// Represents the mcp.tools.list_changed event. +public sealed partial class McpToolsListChangedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "mcp.tools.list_changed"; + + /// The mcp.tools.list_changed event payload. + [JsonPropertyName("data")] + public required McpToolsListChangedData Data { get; set; } +} + +/// Payload identifying the MCP server associated with a list change. +/// Represents the mcp.resources.list_changed event. +public sealed partial class McpResourcesListChangedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "mcp.resources.list_changed"; + + /// The mcp.resources.list_changed event payload. + [JsonPropertyName("data")] + public required McpResourcesListChangedData Data { get; set; } +} + +/// Payload identifying the MCP server associated with a list change. +/// Represents the mcp.prompts.list_changed event. +public sealed partial class McpPromptsListChangedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "mcp.prompts.list_changed"; + + /// The mcp.prompts.list_changed event payload. + [JsonPropertyName("data")] + public required McpPromptsListChangedData Data { get; set; } +} + +/// Payload of `session.extensions_loaded` listing discovered extensions and their statuses. /// Represents the session.extensions_loaded event. public sealed partial class SessionExtensionsLoadedEvent : SessionEvent { @@ -1293,7 +1491,7 @@ public sealed partial class SessionExtensionsLoadedEvent : SessionEvent public required SessionExtensionsLoadedData Data { get; set; } } -/// Schema for the `CanvasOpenedData` type. +/// Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. /// Represents the session.canvas.opened event. [Experimental(Diagnostics.Experimental)] public sealed partial class SessionCanvasOpenedEvent : SessionEvent @@ -1307,7 +1505,7 @@ public sealed partial class SessionCanvasOpenedEvent : SessionEvent public required SessionCanvasOpenedData Data { get; set; } } -/// Schema for the `CanvasRegistryChangedData` type. +/// Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. /// Represents the session.canvas.registry_changed event. [Experimental(Diagnostics.Experimental)] public sealed partial class SessionCanvasRegistryChangedEvent : SessionEvent @@ -1321,7 +1519,7 @@ public sealed partial class SessionCanvasRegistryChangedEvent : SessionEvent public required SessionCanvasRegistryChangedData Data { get; set; } } -/// Schema for the `CanvasClosedData` type. +/// Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. /// Represents the session.canvas.closed event. [Experimental(Diagnostics.Experimental)] public sealed partial class SessionCanvasClosedEvent : SessionEvent @@ -1377,7 +1575,7 @@ public sealed partial class SessionCanvasRemovedEvent : SessionEvent public required SessionCanvasRemovedData Data { get; set; } } -/// Schema for the `ExtensionsAttachmentsPushedData` type. +/// Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. /// Represents the session.extensions.attachments_pushed event. public sealed partial class SessionExtensionsAttachmentsPushedEvent : SessionEvent { @@ -1458,10 +1656,20 @@ public sealed partial class SessionStartData [JsonPropertyName("sessionId")] public required string SessionId { get; set; } + /// Session limits configured at session creation time, if any. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("sessionLimits")] + public SessionLimitsConfig? SessionLimits { get; set; } + /// ISO 8601 timestamp when the session was created. [JsonPropertyName("startTime")] public required DateTimeOffset StartTime { get; set; } + /// Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high"). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("verbosity")] + public Verbosity? Verbosity { get; set; } + /// Schema version number for the session event format. [JsonPropertyName("version")] public required long Version { get; set; } @@ -1523,10 +1731,20 @@ public sealed partial class SessionResumeData [JsonPropertyName("selectedModel")] public string? SelectedModel { get; set; } + /// Session limits currently configured at resume time; null when no limits are active. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("sessionLimits")] + public SessionLimitsConfig? SessionLimits { get; set; } + /// True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("sessionWasActive")] public bool? SessionWasActive { get; set; } + + /// Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high"). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("verbosity")] + public Verbosity? Verbosity { get; set; } } /// Notifies that the session's remote steering capability has changed. @@ -1758,6 +1976,11 @@ public sealed partial class SessionModelChangeData [JsonPropertyName("previousReasoningSummary")] public ReasoningSummary? PreviousReasoningSummary { get; set; } + /// Output verbosity level before the model change, if applicable. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("previousVerbosity")] + public Verbosity? PreviousVerbosity { get; set; } + /// Reasoning effort level after the model change, if applicable. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("reasoningEffort")] @@ -1767,6 +1990,11 @@ public sealed partial class SessionModelChangeData [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("reasoningSummary")] public ReasoningSummary? ReasoningSummary { get; set; } + + /// Output verbosity level after the model change, if applicable. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("verbosity")] + public Verbosity? Verbosity { get; set; } } /// Agent mode change details including previous and new modes. @@ -1781,13 +2009,33 @@ public sealed partial class SessionModeChangedData public required SessionMode PreviousMode { get; set; } } -/// Permissions change details carrying the aggregate allow-all boolean transition. +/// Session limits update details. Null clears the limits. +public sealed partial class SessionSessionLimitsChangedData +{ + /// Current session limits, or null when no limits are active. + [JsonPropertyName("sessionLimits")] + public SessionLimitsConfig? SessionLimits { get; set; } +} + +/// Permissions change details carrying the aggregate allow-all transition. public sealed partial class SessionPermissionsChangedData { + /// Allow-all mode after the change. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("allowAllPermissionMode")] + public PermissionAllowAllMode? AllowAllPermissionMode { get; set; } + /// Aggregate allow-all flag after the change. [JsonPropertyName("allowAllPermissions")] public required bool AllowAllPermissions { get; set; } + /// Allow-all mode before the change. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("previousAllowAllPermissionMode")] + public PermissionAllowAllMode? PreviousAllowAllPermissionMode { get; set; } + /// Aggregate allow-all flag before the change. [JsonPropertyName("previousAllowAllPermissions")] public required bool PreviousAllowAllPermissions { get; set; } @@ -1980,6 +2228,20 @@ public sealed partial class SessionShutdownData internal double? TotalPremiumRequests { get; set; } } +/// Durable session usage checkpoint for reconstructing aggregate accounting on resume. +public sealed partial class SessionUsageCheckpointData +{ + /// Session-wide accumulated nano-AI units cost at checkpoint time. + [JsonPropertyName("totalNanoAiu")] + public required double TotalNanoAiu { get; set; } + + /// Total number of premium API requests used at checkpoint time. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] + [JsonPropertyName("totalPremiumRequests")] + internal double? TotalPremiumRequests { get; set; } +} + /// Working directory and git context at session start. public sealed partial class SessionContextChangedData { @@ -2067,6 +2329,11 @@ public sealed partial class SessionCompactionStartData [JsonPropertyName("conversationTokens")] public long? ConversationTokens { get; set; } + /// Model identifier used for compaction, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("model")] + public string? Model { get; set; } + /// Token count from system message(s) at compaction start. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("systemTokens")] @@ -2185,7 +2452,7 @@ public sealed partial class SessionTaskCompleteData public string? Summary { get; set; } } -/// Schema for the `UserMessageData` type. +/// Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. public sealed partial class UserMessageData { /// The agent mode that was active when this message was sent. @@ -2202,6 +2469,11 @@ public sealed partial class UserMessageData [JsonPropertyName("content")] public required string Content { get; set; } + /// How this message was delivered to the agentic loop relative to loop state (idle-start vs. steering/queued while busy). The timing axis; combine with `source` (origin) for the full picture. Used for telemetry attribution. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("delivery")] + public UserMessageDelivery? Delivery { get; set; } + /// CAPI interaction ID for correlating this user message with its turn. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("interactionId")] @@ -2251,6 +2523,11 @@ public sealed partial class AssistantTurnStartData [JsonPropertyName("interactionId")] public string? InteractionId { get; set; } + /// Model identifier used for this turn, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("model")] + public string? Model { get; set; } + /// Identifier for this turn within the agentic loop, typically a stringified turn number. [JsonPropertyName("turnId")] public required string TurnId { get; set; } @@ -2264,6 +2541,22 @@ public sealed partial class AssistantIntentData public required string Intent { get; set; } } +/// Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message. +public sealed partial class AssistantServerToolProgressData +{ + /// Kind of hosted server tool that is running. Only `web_search` is emitted today. + [JsonPropertyName("kind")] + public required string Kind { get; set; } + + /// Position of the hosted tool call in the response output. Stable across the call's lifecycle events (unlike the provider's per-event item id, which CAPI rotates), so the host keys the live in-progress row on it. + [JsonPropertyName("outputIndex")] + public required long OutputIndex { get; set; } + + /// Lifecycle status of the hosted call: `in_progress`, `searching`, or `completed`. + [JsonPropertyName("status")] + public required string Status { get; set; } +} + /// Assistant reasoning content for timeline display with complete thinking text. public sealed partial class AssistantReasoningData { @@ -2288,6 +2581,28 @@ public sealed partial class AssistantReasoningDeltaData public required string ReasoningId { get; set; } } +/// Streaming tool-call input delta for incremental tool-call updates. +public sealed partial class AssistantToolCallDeltaData +{ + /// Raw provider tool input fragment to append for this tool call. Function/tool-use providers stream serialized JSON argument text (so newlines inside JSON string values may appear as escaped `\n` until the accumulated JSON is parsed); custom tool calls stream raw custom input. + [JsonPropertyName("inputDelta")] + public required string InputDelta { get; set; } + + /// Tool call ID this delta belongs to, matching the corresponding assistant.message tool request. + [JsonPropertyName("toolCallId")] + public required string ToolCallId { get; set; } + + /// Name of the tool being invoked, when known from the stream. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("toolName")] + public string? ToolName { get; set; } + + /// Tool call type, when known from the stream. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("toolType")] + public AssistantMessageToolRequestType? ToolType { get; set; } +} + /// Streaming response progress with cumulative byte count. public sealed partial class AssistantStreamingDeltaData { @@ -2310,6 +2625,11 @@ public sealed partial class AssistantMessageData [JsonPropertyName("citations")] public Citations? Citations { get; set; } + /// Client-minted request id (x-request-id header) echoed by the server. Distinct from requestId (x-github-request-id) and serviceRequestId (x-copilot-service-request-id). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("clientRequestId")] + public string? ClientRequestId { get; set; } + /// The assistant's text response content. [JsonPropertyName("content")] public required string Content { get; set; } @@ -2340,7 +2660,9 @@ public sealed partial class AssistantMessageData /// Tool call ID of the parent tool invocation when this event originates from a sub-agent. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("parentToolCallId")] public string? ParentToolCallId { get; set; } @@ -2360,6 +2682,11 @@ public sealed partial class AssistantMessageData [JsonPropertyName("reasoningText")] public string? ReasoningText { get; set; } + /// OpenAI-compatible wire field the provider used for reasoning (e.g. reasoning_content/reasoning). Populated only when non-canonical, so the dialect round-trips across turns. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("reasoningWireField")] + public string? ReasoningWireField { get; set; } + /// GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("requestId")] @@ -2412,7 +2739,9 @@ public sealed partial class AssistantMessageDeltaData /// Tool call ID of the parent tool invocation when this event originates from a sub-agent. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("parentToolCallId")] public string? ParentToolCallId { get; set; } @@ -2421,11 +2750,25 @@ public sealed partial class AssistantMessageDeltaData /// Turn completion metadata including the turn identifier. public sealed partial class AssistantTurnEndData { + /// Model identifier used for this turn, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("model")] + public string? Model { get; set; } + /// Identifier of the turn that has ended, matching the corresponding assistant.turn_start event. [JsonPropertyName("turnId")] public required string TurnId { get; set; } } +/// Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred. +public sealed partial class AssistantIdleData +{ + /// True when the preceding agentic loop was cancelled via abort signal. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("aborted")] + public bool? Aborted { get; set; } +} + /// LLM API call usage metrics including tokens, costs, quotas, and billing information. public sealed partial class AssistantUsageData { @@ -2503,7 +2846,9 @@ public sealed partial class AssistantUsageData /// Parent tool call ID when this usage originates from a sub-agent. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("parentToolCallId")] public string? ParentToolCallId { get; set; } @@ -2671,11 +3016,18 @@ public sealed partial class ToolExecutionStartData /// Tool call ID of the parent tool invocation when this event originates from a sub-agent. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("parentToolCallId")] public string? ParentToolCallId { get; set; } + /// Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("shellToolInfo")] + public ToolExecutionStartShellToolInfo? ShellToolInfo { get; set; } + /// Unique identifier for this tool call. [JsonPropertyName("toolCallId")] public required string ToolCallId { get; set; } @@ -2737,6 +3089,12 @@ public sealed partial class ToolExecutionCompleteData [JsonPropertyName("isUserRequested")] public bool? IsUserRequested { get; set; } + /// FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels). Persisted as `{ ifc: ... }` so the label survives session resume, including model-visible failure results. Experimental. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("mcpMeta")] + public JsonElement? McpMeta { get; set; } + /// Model identifier that generated this tool call. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("model")] @@ -2744,7 +3102,9 @@ public sealed partial class ToolExecutionCompleteData /// Tool call ID of the parent tool invocation when this event originates from a sub-agent. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This member is deprecated and will be removed in a future version.")] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("parentToolCallId")] public string? ParentToolCallId { get; set; } @@ -2800,6 +3160,11 @@ public sealed partial class SkillInvokedData [JsonPropertyName("description")] public string? Description { get; set; } + /// Model identifier active when the skill was invoked, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("model")] + public string? Model { get; set; } + /// Name of the invoked skill. [JsonPropertyName("name")] public required string Name { get; set; } @@ -3244,6 +3609,15 @@ public sealed partial class SamplingCompletedData /// OAuth authentication request for an MCP server. public sealed partial class McpOauthRequiredData { + /// Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. Header order and casing are transport-dependent, and duplicate header names may appear multiple times. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("httpResponse")] + public McpOauthHttpResponse? HttpResponse { get; set; } + + /// Why the runtime is requesting host-provided OAuth credentials. + [JsonPropertyName("reason")] + public required McpOauthRequestReason Reason { get; set; } + /// Unique identifier for this OAuth request; used to respond via session.mcp.oauth.handlePendingRequest. [JsonPropertyName("requestId")] public required string RequestId { get; set; } @@ -3284,6 +3658,38 @@ public sealed partial class McpOauthCompletedData public required string RequestId { get; set; } } +/// Dynamic headers refresh request for a remote MCP server. +public sealed partial class McpHeadersRefreshRequiredData +{ + /// Why dynamic headers are being requested. + [JsonPropertyName("reason")] + public required McpHeadersRefreshRequiredReason Reason { get; set; } + + /// Unique identifier for this headers refresh request; used to respond via session.mcp.headers.handlePendingHeadersRefreshRequest(). + [JsonPropertyName("requestId")] + public required string RequestId { get; set; } + + /// Display name of the remote MCP server requesting headers. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } + + /// URL of the remote MCP server requesting headers. + [JsonPropertyName("serverUrl")] + public required string ServerUrl { get; set; } +} + +/// MCP headers refresh request completion notification. +public sealed partial class McpHeadersRefreshCompletedData +{ + /// How the pending MCP headers refresh request resolved. + [JsonPropertyName("outcome")] + public required McpHeadersRefreshCompletedOutcome Outcome { get; set; } + + /// Request ID of the resolved headers refresh request. + [JsonPropertyName("requestId")] + public required string RequestId { get; set; } +} + /// Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. public sealed partial class SessionCustomNotificationData { @@ -3432,6 +3838,102 @@ public sealed partial class AutoModeSwitchCompletedData public required AutoModeSwitchResponse Response { get; set; } } +/// Session limit exhaustion notification requiring user action. +public sealed partial class SessionLimitsExhaustedRequestedData +{ + /// Configured max AI Credits for the current accounting window. + [JsonPropertyName("maxAiCredits")] + public required double MaxAiCredits { get; set; } + + /// Unique identifier for this request; used to respond via session.ui.handlePendingSessionLimitsExhausted(). + [JsonPropertyName("requestId")] + public required string RequestId { get; set; } + + /// AI Credits already consumed in the current accounting window. + [JsonPropertyName("usedAiCredits")] + public required double UsedAiCredits { get; set; } +} + +/// Session limit exhaustion prompt completion notification. +public sealed partial class SessionLimitsExhaustedCompletedData +{ + /// Request ID of the resolved request; clients should dismiss any UI for this request. + [JsonPropertyName("requestId")] + public required string RequestId { get; set; } + + /// The user's selected session-limit action. + [JsonPropertyName("response")] + public required SessionLimitsExhaustedResponse Response { get; set; } +} + +/// Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. +[Experimental(Diagnostics.Experimental)] +public sealed partial class SessionAutoModeResolvedData +{ + /// Ordered candidate model list the router returned, when not a fallback. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("candidateModels")] + public string[]? CandidateModels { get; set; } + + /// Per-category classifier scores (0-1) behind the bucket: the granular HYDRA capability scores (reasoning, code_gen, debugging, tool_use), or the binary needs_reasoning/no_reasoning scores when HYDRA didn't run. Lets clients show a breakdown rather than just the bucket. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("categoryScores")] + public IDictionary? CategoryScores { get; set; } + + /// The concrete model the session will use after any intent refinement. + [JsonPropertyName("chosenModel")] + public required string ChosenModel { get; set; } + + /// Classifier confidence for the predicted label, when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("confidence")] + public double? Confidence { get; set; } + + /// The predicted classifier label (e.g. `needs_reasoning`), when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("predictedLabel")] + public string? PredictedLabel { get; set; } + + /// Coarse request-difficulty bucket, for explaining why a model was chosen ("picked X because this looks like high-reasoning work"). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("reasoningBucket")] + public AutoModeResolvedReasoningBucket? ReasoningBucket { get; set; } +} + +/// Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. +[Experimental(Diagnostics.Experimental)] +public sealed partial class SessionManagedSettingsResolvedData +{ + /// Whether enterprise policy disables bypass-permissions ("yolo") mode for this session. Deny-wins across layers, and forced on when `failClosed` is true. + [JsonPropertyName("bypassPermissionsDisabled")] + public required bool BypassPermissionsDisabled { get; set; } + + /// Whether the device (MDM/plist/registry/file) managed-settings layer was present. + [JsonPropertyName("deviceManaged")] + public required bool DeviceManaged { get; set; } + + /// Whether managed policy could not be determined (e.g. a failed server fetch) and the session fell back to the fail-closed restriction. When true, restrictions such as disabling bypass-permissions are enforced even though `settings` may be absent. + [JsonPropertyName("failClosed")] + public required bool FailClosed { get; set; } + + /// The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. + [JsonPropertyName("managedKeys")] + public required string[] ManagedKeys { get; set; } + + /// Whether the server (account/org) managed-settings layer was present. + [JsonPropertyName("serverManaged")] + public required bool ServerManaged { get; set; } + + /// The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("settings")] + public JsonElement? Settings { get; set; } + + /// Which channel supplied the effective managed settings (the winning layer), or `none` when no policy is in force. + [JsonPropertyName("source")] + public required ManagedSettingsResolvedSource Source { get; set; } +} + /// SDK command registration change notification. public sealed partial class CommandsChangedData { @@ -3501,7 +4003,7 @@ public sealed partial class ExitPlanModeCompletedData public ExitPlanModeAction? SelectedAction { get; set; } } -/// Schema for the `ToolsUpdatedData` type. +/// Payload of `session.tools_updated` identifying the model whose resolved tools were updated. public sealed partial class SessionToolsUpdatedData { /// Identifier of the model the resolved tools apply to. @@ -3509,12 +4011,12 @@ public sealed partial class SessionToolsUpdatedData public required string Model { get; set; } } -/// Schema for the `BackgroundTasksChangedData` type. +/// Empty payload for `session.background_tasks_changed`, indicating background task state changed. public sealed partial class SessionBackgroundTasksChangedData { } -/// Schema for the `SkillsLoadedData` type. +/// Payload of `session.skills_loaded` listing resolved skill metadata. public sealed partial class SessionSkillsLoadedData { /// Array of resolved skill metadata. @@ -3522,7 +4024,7 @@ public sealed partial class SessionSkillsLoadedData public required SkillsLoadedSkill[] Skills { get; set; } } -/// Schema for the `CustomAgentsUpdatedData` type. +/// Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. public sealed partial class SessionCustomAgentsUpdatedData { /// Array of loaded custom agent metadata. @@ -3538,7 +4040,7 @@ public sealed partial class SessionCustomAgentsUpdatedData public required string[] Warnings { get; set; } } -/// Schema for the `McpServersLoadedData` type. +/// Payload of `session.mcp_servers_loaded` listing MCP server status summaries. public sealed partial class SessionMcpServersLoadedData { /// Array of MCP server status summaries. @@ -3546,7 +4048,7 @@ public sealed partial class SessionMcpServersLoadedData public required McpServersLoadedServer[] Servers { get; set; } } -/// Schema for the `McpServerStatusChangedData` type. +/// Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. public sealed partial class SessionMcpServerStatusChangedData { /// Error message if the server entered a failed state. @@ -3563,15 +4065,39 @@ public sealed partial class SessionMcpServerStatusChangedData public required McpServerStatus Status { get; set; } } -/// Schema for the `ExtensionsLoadedData` type. -public sealed partial class SessionExtensionsLoadedData +/// Payload identifying the MCP server associated with a list change. +public sealed partial class McpToolsListChangedData { - /// Array of discovered extensions and their status. - [JsonPropertyName("extensions")] - public required ExtensionsLoadedExtension[] Extensions { get; set; } + /// Name of the MCP server whose list changed. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } } -/// Schema for the `CanvasOpenedData` type. +/// Payload identifying the MCP server associated with a list change. +public sealed partial class McpResourcesListChangedData +{ + /// Name of the MCP server whose list changed. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } +} + +/// Payload identifying the MCP server associated with a list change. +public sealed partial class McpPromptsListChangedData +{ + /// Name of the MCP server whose list changed. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } +} + +/// Payload of `session.extensions_loaded` listing discovered extensions and their statuses. +public sealed partial class SessionExtensionsLoadedData +{ + /// Array of discovered extensions and their status. + [JsonPropertyName("extensions")] + public required ExtensionsLoadedExtension[] Extensions { get; set; } +} + +/// Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. [Experimental(Diagnostics.Experimental)] public sealed partial class SessionCanvasOpenedData { @@ -3588,6 +4114,11 @@ public sealed partial class SessionCanvasOpenedData [JsonPropertyName("extensionName")] public string? ExtensionName { get; set; } + /// Host-local PNG path for the canvas icon, when supplied. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("icon")] + public string? Icon { get; set; } + /// Input supplied when the instance was opened. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("input")] @@ -3613,7 +4144,7 @@ public sealed partial class SessionCanvasOpenedData public string? Url { get; set; } } -/// Schema for the `CanvasRegistryChangedData` type. +/// Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. [Experimental(Diagnostics.Experimental)] public sealed partial class SessionCanvasRegistryChangedData { @@ -3622,7 +4153,7 @@ public sealed partial class SessionCanvasRegistryChangedData public required CanvasRegistryChangedCanvas[] Canvases { get; set; } } -/// Schema for the `CanvasClosedData` type. +/// Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. [Experimental(Diagnostics.Experimental)] public sealed partial class SessionCanvasClosedData { @@ -3708,7 +4239,7 @@ public sealed partial class SessionCanvasRemovedData public required string InstanceId { get; set; } } -/// Schema for the `ExtensionsAttachmentsPushedData` type. +/// Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. public sealed partial class SessionExtensionsAttachmentsPushedData { /// Attachments contributed by an extension; the host should surface these as composer pills and forward them via the next session.send call. @@ -3800,6 +4331,16 @@ public sealed partial class WorkingDirectoryContext public string? RepositoryHost { get; set; } } +/// Optional session limits. +/// Nested data type for SessionLimitsConfig. +public sealed partial class SessionLimitsConfig +{ + /// Maximum AI Credits allowed across the session's current accounting window. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("maxAiCredits")] + public double? MaxAiCredits { get; set; } +} + /// Repository context for the handed-off session. /// Nested data type for HandoffRepository. public sealed partial class HandoffRepository @@ -3852,7 +4393,7 @@ public sealed partial class ShutdownModelMetricRequests public long? Count { get; set; } } -/// Schema for the `ShutdownModelMetricTokenDetail` type. +/// A token-type entry in a shutdown model metric, storing the accumulated token count. /// Nested data type for ShutdownModelMetricTokenDetail. public sealed partial class ShutdownModelMetricTokenDetail { @@ -3887,7 +4428,7 @@ public sealed partial class ShutdownModelMetricUsage public long? ReasoningTokens { get; set; } } -/// Schema for the `ShutdownModelMetric` type. +/// Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details. /// Nested data type for ShutdownModelMetric. public sealed partial class ShutdownModelMetric { @@ -3911,7 +4452,7 @@ public sealed partial class ShutdownModelMetric public required ShutdownModelMetricUsage Usage { get; set; } } -/// Schema for the `ShutdownTokenDetail` type. +/// A session-wide shutdown token-type entry storing the accumulated token count. /// Nested data type for ShutdownTokenDetail. public sealed partial class ShutdownTokenDetail { @@ -4173,6 +4714,276 @@ public sealed partial class AttachmentGitHubReference : Attachment public required string Url { get; set; } } +/// Pointer to a GitHub repository. +/// Nested data type for GitHubRepoRef. +public sealed partial class GitHubRepoRef +{ + /// Numeric GitHub repository id. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// Repository name (without owner). + [JsonPropertyName("name")] + public required string Name { get; set; } + + /// Repository owner login (user or organization). + [JsonPropertyName("owner")] + public required string Owner { get; set; } +} + +/// Pointer to a GitHub commit. +/// The github_commit variant of . +public sealed partial class AttachmentGitHubCommit : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_commit"; + + /// First line of the commit message. + [JsonPropertyName("message")] + public required string Message { get; set; } + + /// Full commit SHA. + [JsonPropertyName("oid")] + public required string Oid { get; set; } + + /// Repository the commit belongs to. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } + + /// URL to the commit on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a GitHub release. +/// The github_release variant of . +public sealed partial class AttachmentGitHubRelease : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_release"; + + /// Human-readable release name. + [JsonPropertyName("name")] + public required string Name { get; set; } + + /// Repository the release belongs to. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } + + /// Git tag the release is anchored to. + [JsonPropertyName("tagName")] + public required string TagName { get; set; } + + /// URL to the release on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a GitHub Actions job. +/// The github_actions_job variant of . +public sealed partial class AttachmentGitHubActionsJob : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_actions_job"; + + /// Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("conclusion")] + public string? Conclusion { get; set; } + + /// Job id within the workflow run. + [JsonPropertyName("jobId")] + public required long JobId { get; set; } + + /// Display name of the job. + [JsonPropertyName("jobName")] + public required string JobName { get; set; } + + /// Repository the workflow run belongs to. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } + + /// URL to the job on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } + + /// Display name of the workflow the job ran in. + [JsonPropertyName("workflowName")] + public required string WorkflowName { get; set; } +} + +/// Pointer to a GitHub repository. +/// The github_repository variant of . +public sealed partial class AttachmentGitHubRepository : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_repository"; + + /// Short description of the repository. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("ref")] + public string? Ref { get; set; } + + /// Repository pointer. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } + + /// URL to the repository on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// One side of a file diff (head or base). +/// Nested data type for AttachmentGitHubFileDiffSide. +public sealed partial class AttachmentGitHubFileDiffSide +{ + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public required string Path { get; set; } + + /// Git ref (branch, tag, or commit SHA) the file is read at. + [JsonPropertyName("ref")] + public required string Ref { get; set; } + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } +} + +/// Pointer to a single-file diff. At least one of `head` and `base` must be present. +/// The github_file_diff variant of . +public sealed partial class AttachmentGitHubFileDiff : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_file_diff"; + + /// File location on the base side of the diff. Absent for additions. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("base")] + public AttachmentGitHubFileDiffSide? Base { get; set; } + + /// File location on the head side of the diff. Absent for deletions. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("head")] + public AttachmentGitHubFileDiffSide? Head { get; set; } + + /// URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL). + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// One side of a tree comparison (head or base). +/// Nested data type for AttachmentGitHubTreeComparisonSide. +public sealed partial class AttachmentGitHubTreeComparisonSide +{ + /// Repository the revision belongs to. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } + + /// Git revision (branch, tag, or commit SHA). + [JsonPropertyName("revision")] + public required string Revision { get; set; } +} + +/// Pointer to a comparison between two git revisions. +/// The github_tree_comparison variant of . +public sealed partial class AttachmentGitHubTreeComparison : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_tree_comparison"; + + /// Base side of the comparison. + [JsonPropertyName("base")] + public required AttachmentGitHubTreeComparisonSide Base { get; set; } + + /// Head side of the comparison. + [JsonPropertyName("head")] + public required AttachmentGitHubTreeComparisonSide Head { get; set; } + + /// URL to the comparison on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Generic GitHub URL reference. +/// The github_url variant of . +public sealed partial class AttachmentGitHubUrl : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_url"; + + /// URL to the GitHub resource. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a file in a GitHub repository at a specific ref. +/// The github_file variant of . +public sealed partial class AttachmentGitHubFile : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_file"; + + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public required string Path { get; set; } + + /// Git ref the file is read at (branch, tag, or commit SHA). + [JsonPropertyName("ref")] + public required string Ref { get; set; } + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } + + /// URL to the file on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a line range inside a file in a GitHub repository. +/// The github_snippet variant of . +public sealed partial class AttachmentGitHubSnippet : Attachment +{ + /// + [JsonIgnore] + public override string Type => "github_snippet"; + + /// Line range the snippet covers. + [JsonPropertyName("lineRange")] + public required AttachmentFileLineRange LineRange { get; set; } + + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public required string Path { get; set; } + + /// Git ref the file is read at (branch, tag, or commit SHA). + [JsonPropertyName("ref")] + public required string Ref { get; set; } + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public required GitHubRepoRef Repo { get; set; } + + /// URL to the snippet on GitHub (with line anchor). + [JsonPropertyName("url")] + public required string Url { get; set; } +} + /// Blob attachment with inline base64-encoded data. /// The blob variant of . public sealed partial class AttachmentBlob : Attachment @@ -4250,7 +5061,7 @@ public sealed partial class AttachmentExtensionContext : Attachment public required string Title { get; set; } } -/// A user message attachment — a file, directory, code selection, blob, GitHub reference, or extension-supplied context payload. +/// A user message attachment — a file, directory, code selection, blob, GitHub reference, GitHub-anchored pointer, or extension-supplied context payload. /// Polymorphic base type discriminated by type. [JsonPolymorphic( TypeDiscriminatorPropertyName = "type", @@ -4259,6 +5070,15 @@ public sealed partial class AttachmentExtensionContext : Attachment [JsonDerivedType(typeof(AttachmentDirectory), "directory")] [JsonDerivedType(typeof(AttachmentSelection), "selection")] [JsonDerivedType(typeof(AttachmentGitHubReference), "github_reference")] +[JsonDerivedType(typeof(AttachmentGitHubCommit), "github_commit")] +[JsonDerivedType(typeof(AttachmentGitHubRelease), "github_release")] +[JsonDerivedType(typeof(AttachmentGitHubActionsJob), "github_actions_job")] +[JsonDerivedType(typeof(AttachmentGitHubRepository), "github_repository")] +[JsonDerivedType(typeof(AttachmentGitHubFileDiff), "github_file_diff")] +[JsonDerivedType(typeof(AttachmentGitHubTreeComparison), "github_tree_comparison")] +[JsonDerivedType(typeof(AttachmentGitHubUrl), "github_url")] +[JsonDerivedType(typeof(AttachmentGitHubFile), "github_file")] +[JsonDerivedType(typeof(AttachmentGitHubSnippet), "github_snippet")] [JsonDerivedType(typeof(AttachmentBlob), "blob")] [JsonDerivedType(typeof(AttachmentExtensionContext), "extension_context")] public partial class Attachment @@ -4535,7 +5355,7 @@ public sealed partial class AssistantUsageCopilotUsage public required double TotalNanoAiu { get; set; } } -/// Schema for the `AssistantUsageQuotaSnapshot` type. +/// Internal per-quota snapshot for assistant usage, including entitlement, consumed requests, overage, reset date, and remaining quota. /// Nested data type for AssistantUsageQuotaSnapshot. internal sealed partial class AssistantUsageQuotaSnapshot { @@ -4633,7 +5453,20 @@ public sealed partial class ModelCallFailureRequestFingerprint public required long ToolResultMessageCount { get; set; } } -/// Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. +/// Shell-aware path hints for a shell tool's command, captured at start time so consumers can snapshot a file's pre-image before the tool runs. +/// Nested data type for ToolExecutionStartShellToolInfo. +public sealed partial class ToolExecutionStartShellToolInfo +{ + /// Whether the command includes a file write redirection (e.g., > or >>). + [JsonPropertyName("hasWriteFileRedirection")] + public required bool HasWriteFileRedirection { get; set; } + + /// File paths the command may read or write, derived from the command at start time. Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. + [JsonPropertyName("possiblePaths")] + public required string[] PossiblePaths { get; set; } +} + +/// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. /// Nested data type for ToolExecutionStartToolDescriptionMetaUI. public sealed partial class ToolExecutionStartToolDescriptionMetaUI { @@ -4652,7 +5485,7 @@ public sealed partial class ToolExecutionStartToolDescriptionMetaUI /// Nested data type for ToolExecutionStartToolDescriptionMeta. public sealed partial class ToolExecutionStartToolDescriptionMeta { - /// Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. + /// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("ui")] public ToolExecutionStartToolDescriptionMetaUI? Ui { get; set; } @@ -4665,7 +5498,7 @@ public sealed partial class ToolExecutionStartToolDescription /// MCP Apps metadata for UI resource association. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("_meta")] - public ToolExecutionStartToolDescriptionMeta? _meta { get; set; } + public ToolExecutionStartToolDescriptionMeta? Meta { get; set; } /// Tool description. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -4926,8 +5759,12 @@ public sealed partial class ToolExecutionCompleteContentText : ToolExecutionComp public required string Text { get; set; } } -/// Terminal/shell output content block with optional exit code and working directory. +/// Deprecated for shell command exit metadata. Use ToolExecutionCompleteContentShellExit instead. /// The terminal variant of . +[EditorBrowsable(EditorBrowsableState.Never)] +#if NET5_0_OR_GREATER +[Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif public sealed partial class ToolExecutionCompleteContentTerminal : ToolExecutionCompleteContent { /// @@ -4949,6 +5786,38 @@ public sealed partial class ToolExecutionCompleteContentTerminal : ToolExecution public required string Text { get; set; } } +/// Shell command exit metadata with optional output preview. +/// The shell_exit variant of . +public sealed partial class ToolExecutionCompleteContentShellExit : ToolExecutionCompleteContent +{ + /// + [JsonIgnore] + public override string Type => "shell_exit"; + + /// Working directory where the shell command was executed. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("cwd")] + public string? Cwd { get; set; } + + /// Exit code from the completed shell command. + [JsonPropertyName("exitCode")] + public required long ExitCode { get; set; } + + /// Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("outputPreview")] + public string? OutputPreview { get; set; } + + /// Whether outputPreview is known to be incomplete or truncated. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("outputTruncated")] + public bool? OutputTruncated { get; set; } + + /// Shell id, as assigned by Copilot runtime. + [JsonPropertyName("shellId")] + public required string ShellId { get; set; } +} + /// Image content block with base64-encoded data. /// The image variant of . public sealed partial class ToolExecutionCompleteContentImage : ToolExecutionCompleteContent @@ -5051,7 +5920,7 @@ public sealed partial class ToolExecutionCompleteContentResourceLink : ToolExecu public required string Uri { get; set; } } -/// Schema for the `EmbeddedTextResourceContents` type. +/// Embedded text resource contents identified by a URI, with an optional MIME type and a text payload. /// Nested data type for EmbeddedTextResourceContents. public sealed partial class EmbeddedTextResourceContents { @@ -5069,7 +5938,7 @@ public sealed partial class EmbeddedTextResourceContents public required string Uri { get; set; } } -/// Schema for the `EmbeddedBlobResourceContents` type. +/// Embedded binary resource contents identified by a URI, with an optional MIME type and a base64-encoded blob. /// Nested data type for EmbeddedBlobResourceContents. public sealed partial class EmbeddedBlobResourceContents { @@ -5186,6 +6055,7 @@ public sealed partial class ToolExecutionCompleteContentResource : ToolExecution UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] [JsonDerivedType(typeof(ToolExecutionCompleteContentText), "text")] [JsonDerivedType(typeof(ToolExecutionCompleteContentTerminal), "terminal")] +[JsonDerivedType(typeof(ToolExecutionCompleteContentShellExit), "shell_exit")] [JsonDerivedType(typeof(ToolExecutionCompleteContentImage), "image")] [JsonDerivedType(typeof(ToolExecutionCompleteContentAudio), "audio")] [JsonDerivedType(typeof(ToolExecutionCompleteContentResourceLink), "resource_link")] @@ -5198,7 +6068,7 @@ public partial class ToolExecutionCompleteContent } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. +/// CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. /// Nested data type for ToolExecutionCompleteUIResourceMetaUICsp. public sealed partial class ToolExecutionCompleteUIResourceMetaUICsp { @@ -5223,60 +6093,60 @@ public sealed partial class ToolExecutionCompleteUIResourceMetaUICsp public string[]? ResourceDomains { get; set; } } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. +/// Marker object for camera permission on an MCP Apps UI resource. /// Nested data type for ToolExecutionCompleteUIResourceMetaUIPermissionsCamera. public sealed partial class ToolExecutionCompleteUIResourceMetaUIPermissionsCamera { } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. +/// Marker object for clipboard-write permission on an MCP Apps UI resource. /// Nested data type for ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite. public sealed partial class ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite { } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. +/// Marker object for geolocation permission on an MCP Apps UI resource. /// Nested data type for ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation. public sealed partial class ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation { } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. +/// Marker object for microphone permission on an MCP Apps UI resource. /// Nested data type for ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone. public sealed partial class ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone { } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. +/// Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. /// Nested data type for ToolExecutionCompleteUIResourceMetaUIPermissions. public sealed partial class ToolExecutionCompleteUIResourceMetaUIPermissions { - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. + /// Marker object for camera permission on an MCP Apps UI resource. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("camera")] public ToolExecutionCompleteUIResourceMetaUIPermissionsCamera? Camera { get; set; } - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. + /// Marker object for clipboard-write permission on an MCP Apps UI resource. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("clipboardWrite")] public ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite? ClipboardWrite { get; set; } - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. + /// Marker object for geolocation permission on an MCP Apps UI resource. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("geolocation")] public ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation? Geolocation { get; set; } - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. + /// Marker object for microphone permission on an MCP Apps UI resource. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("microphone")] public ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone? Microphone { get; set; } } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. +/// MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. /// Nested data type for ToolExecutionCompleteUIResourceMetaUI. public sealed partial class ToolExecutionCompleteUIResourceMetaUI { - /// Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. + /// CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("csp")] public ToolExecutionCompleteUIResourceMetaUICsp? Csp { get; set; } @@ -5286,7 +6156,7 @@ public sealed partial class ToolExecutionCompleteUIResourceMetaUI [JsonPropertyName("domain")] public string? Domain { get; set; } - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. + /// Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("permissions")] public ToolExecutionCompleteUIResourceMetaUIPermissions? Permissions { get; set; } @@ -5301,7 +6171,7 @@ public sealed partial class ToolExecutionCompleteUIResourceMetaUI /// Nested data type for ToolExecutionCompleteUIResourceMeta. public sealed partial class ToolExecutionCompleteUIResourceMeta { - /// Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. + /// MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("ui")] public ToolExecutionCompleteUIResourceMetaUI? Ui { get; set; } @@ -5314,7 +6184,7 @@ public sealed partial class ToolExecutionCompleteUIResource /// Resource-level UI metadata (CSP, permissions, visual preferences). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("_meta")] - public ToolExecutionCompleteUIResourceMeta? _meta { get; set; } + public ToolExecutionCompleteUIResourceMeta? Meta { get; set; } /// Base64-encoded HTML content. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -5365,6 +6235,12 @@ public sealed partial class ToolExecutionCompleteResult [JsonPropertyName("detailedContent")] public string? DetailedContent { get; set; } + /// FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels) — persisted as `{ ifc: ... }` (only the `ifc` key, not the whole `_meta`). Persisted so the FIDES IFC label survives session resume: the engine rehydrates accumulated taint by replaying these on load. Populated for ingress sources when FIDES IFC is on. Experimental. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("mcpMeta")] + public JsonElement? McpMeta { get; set; } + /// Structured content (arbitrary JSON) returned verbatim by the MCP tool. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("structuredContent")] @@ -5376,7 +6252,7 @@ public sealed partial class ToolExecutionCompleteResult public ToolExecutionCompleteUIResource? UiResource { get; set; } } -/// Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. +/// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. /// Nested data type for ToolExecutionCompleteToolDescriptionMetaUI. public sealed partial class ToolExecutionCompleteToolDescriptionMetaUI { @@ -5395,7 +6271,7 @@ public sealed partial class ToolExecutionCompleteToolDescriptionMetaUI /// Nested data type for ToolExecutionCompleteToolDescriptionMeta. public sealed partial class ToolExecutionCompleteToolDescriptionMeta { - /// Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. + /// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("ui")] public ToolExecutionCompleteToolDescriptionMetaUI? Ui { get; set; } @@ -5408,7 +6284,7 @@ public sealed partial class ToolExecutionCompleteToolDescription /// MCP Apps metadata for UI resource association. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("_meta")] - public ToolExecutionCompleteToolDescriptionMeta? _meta { get; set; } + public ToolExecutionCompleteToolDescriptionMeta? Meta { get; set; } /// Tool description. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -5454,7 +6330,7 @@ public sealed partial class SystemMessageMetadata public IDictionary? Variables { get; set; } } -/// Schema for the `SystemNotificationAgentCompleted` type. +/// System notification metadata for a background agent that completed or failed, including agent ID, type, status, description, and prompt. /// The agent_completed variant of . public sealed partial class SystemNotificationAgentCompleted : SystemNotification { @@ -5485,7 +6361,7 @@ public sealed partial class SystemNotificationAgentCompleted : SystemNotificatio public required SystemNotificationAgentCompletedStatus Status { get; set; } } -/// Schema for the `SystemNotificationAgentIdle` type. +/// System notification metadata for a background agent that became idle, including agent ID, type, and description. /// The agent_idle variant of . public sealed partial class SystemNotificationAgentIdle : SystemNotification { @@ -5507,7 +6383,7 @@ public sealed partial class SystemNotificationAgentIdle : SystemNotification public string? Description { get; set; } } -/// Schema for the `SystemNotificationNewInboxMessage` type. +/// System notification metadata for a new inbox message, including entry ID, sender details, and summary. /// The new_inbox_message variant of . public sealed partial class SystemNotificationNewInboxMessage : SystemNotification { @@ -5532,7 +6408,7 @@ public sealed partial class SystemNotificationNewInboxMessage : SystemNotificati public required string Summary { get; set; } } -/// Schema for the `SystemNotificationShellCompleted` type. +/// System notification metadata for a shell session that completed, including shell ID, optional exit code, and description. /// The shell_completed variant of . public sealed partial class SystemNotificationShellCompleted : SystemNotification { @@ -5555,7 +6431,7 @@ public sealed partial class SystemNotificationShellCompleted : SystemNotificatio public required string ShellId { get; set; } } -/// Schema for the `SystemNotificationShellDetachedCompleted` type. +/// System notification metadata for a detached shell session that completed, including shell ID and description. /// The shell_detached_completed variant of . public sealed partial class SystemNotificationShellDetachedCompleted : SystemNotification { @@ -5573,7 +6449,7 @@ public sealed partial class SystemNotificationShellDetachedCompleted : SystemNot public required string ShellId { get; set; } } -/// Schema for the `SystemNotificationInstructionDiscovered` type. +/// System notification metadata for an instruction file discovered during tool access, including source, trigger file, and tool. /// The instruction_discovered variant of . public sealed partial class SystemNotificationInstructionDiscovered : SystemNotification { @@ -5618,7 +6494,7 @@ public partial class SystemNotification } -/// Schema for the `PermissionRequestShellCommand` type. +/// A parsed command identifier in a shell permission request, including whether it is read-only. /// Nested data type for PermissionRequestShellCommand. public sealed partial class PermissionRequestShellCommand { @@ -5631,7 +6507,7 @@ public sealed partial class PermissionRequestShellCommand public required bool ReadOnly { get; set; } } -/// Schema for the `PermissionRequestShellPossibleUrl` type. +/// A URL that may be accessed by a command in a shell permission request. /// Nested data type for PermissionRequestShellPossibleUrl. public sealed partial class PermissionRequestShellPossibleUrl { @@ -5726,6 +6602,16 @@ public sealed partial class PermissionRequestWrite : PermissionRequest [JsonPropertyName("newFileContents")] public string? NewFileContents { get; set; } + /// True when a built-in file tool (apply_patch / str_replace_editor) asked to write a path the sandbox filesystem policy would block, and the host opted in via sandbox.allowBypass. This is a request, not a grant: the write happens unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypass")] + public bool? RequestSandboxBypass { get; set; } + + /// Justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypassReason")] + public string? RequestSandboxBypassReason { get; set; } + /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolCallId")] @@ -5748,6 +6634,16 @@ public sealed partial class PermissionRequestRead : PermissionRequest [JsonPropertyName("path")] public required string Path { get; set; } + /// True when the model has requested to run this search outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the search runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypass")] + public bool? RequestSandboxBypass { get; set; } + + /// Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypassReason")] + public string? RequestSandboxBypassReason { get; set; } + /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolCallId")] @@ -5801,6 +6697,16 @@ public sealed partial class PermissionRequestUrl : PermissionRequest [JsonPropertyName("intention")] public required string Intention { get; set; } + /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypass")] + public bool? RequestSandboxBypass { get; set; } + + /// Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypassReason")] + public string? RequestSandboxBypassReason { get; set; } + /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolCallId")] @@ -5977,6 +6883,21 @@ public partial class PermissionRequest } +/// Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is "auto"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request. +/// Nested data type for PermissionAutoApproval. +[Experimental(Diagnostics.Experimental)] +public sealed partial class PermissionAutoApproval +{ + /// Human-readable reason for the judge's recommendation, when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("reason")] + public string? Reason { get; set; } + + /// The auto-approval safety judge's outcome for this request. + [JsonPropertyName("recommendation")] + public required AutoApprovalRecommendation Recommendation { get; set; } +} + /// Shell command permission prompt. /// The commands variant of . public sealed partial class PermissionPromptRequestCommands : PermissionPromptRequest @@ -5985,6 +6906,12 @@ public sealed partial class PermissionPromptRequestCommands : PermissionPromptRe [JsonIgnore] public override string Kind => "commands"; + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Whether the UI can offer session-wide approval for this command pattern. [JsonPropertyName("canOfferSessionApproval")] public required bool CanOfferSessionApproval { get; set; } @@ -6020,6 +6947,12 @@ public sealed partial class PermissionPromptRequestWrite : PermissionPromptReque [JsonIgnore] public override string Kind => "write"; + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Whether the UI can offer session-wide approval for file write operations. [JsonPropertyName("canOfferSessionApproval")] public required bool CanOfferSessionApproval { get; set; } @@ -6055,6 +6988,12 @@ public sealed partial class PermissionPromptRequestRead : PermissionPromptReques [JsonIgnore] public override string Kind => "read"; + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Human-readable description of why the file is being read. [JsonPropertyName("intention")] public required string Intention { get; set; } @@ -6082,6 +7021,12 @@ public sealed partial class PermissionPromptRequestMcp : PermissionPromptRequest [JsonPropertyName("args")] public JsonElement? Args { get; set; } + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Name of the MCP server providing the tool. [JsonPropertyName("serverName")] public required string ServerName { get; set; } @@ -6108,10 +7053,26 @@ public sealed partial class PermissionPromptRequestUrl : PermissionPromptRequest [JsonIgnore] public override string Kind => "url"; + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Human-readable description of why the URL is being accessed. [JsonPropertyName("intention")] public required string Intention { get; set; } + /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypass")] + public bool? RequestSandboxBypass { get; set; } + + /// Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("requestSandboxBypassReason")] + public string? RequestSandboxBypassReason { get; set; } + /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolCallId")] @@ -6135,6 +7096,12 @@ public sealed partial class PermissionPromptRequestMemory : PermissionPromptRequ [JsonPropertyName("action")] public PermissionRequestMemoryAction? Action { get; set; } + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Source references for the stored fact (store only). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("citations")] @@ -6178,6 +7145,12 @@ public sealed partial class PermissionPromptRequestCustomTool : PermissionPrompt [JsonPropertyName("args")] public JsonElement? Args { get; set; } + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolCallId")] @@ -6204,6 +7177,12 @@ public sealed partial class PermissionPromptRequestPath : PermissionPromptReques [JsonPropertyName("accessKind")] public required PermissionPromptRequestPathAccessKind AccessKind { get; set; } + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// File paths that require explicit approval. [JsonPropertyName("paths")] public required string[] Paths { get; set; } @@ -6222,6 +7201,12 @@ public sealed partial class PermissionPromptRequestHook : PermissionPromptReques [JsonIgnore] public override string Kind => "hook"; + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Optional message from the hook explaining why confirmation is needed. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("hookMessage")] @@ -6250,6 +7235,12 @@ public sealed partial class PermissionPromptRequestExtensionManagement : Permiss [JsonIgnore] public override string Kind => "extension-management"; + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Name of the extension being managed. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("extensionName")] @@ -6273,6 +7264,12 @@ public sealed partial class PermissionPromptRequestExtensionPermissionAccess : P [JsonIgnore] public override string Kind => "extension-permission-access"; + /// Auto-approval judge information for this request; present only when auto mode is enabled. + [Experimental(Diagnostics.Experimental)] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoApproval")] + public PermissionAutoApproval? AutoApproval { get; set; } + /// Capabilities the extension is requesting. [JsonPropertyName("capabilities")] public required string[] Capabilities { get; set; } @@ -6311,7 +7308,7 @@ public partial class PermissionPromptRequest } -/// Schema for the `PermissionApproved` type. +/// Permission response variant indicating the request was approved without persisting an approval rule. /// The approved variant of . public sealed partial class PermissionResultApproved : PermissionResult { @@ -6320,7 +7317,7 @@ public sealed partial class PermissionResultApproved : PermissionResult public override string Kind => "approved"; } -/// Schema for the `UserToolSessionApprovalCommands` type. +/// Session-scoped tool-approval rule for specific shell command identifiers. /// The commands variant of . public sealed partial class UserToolSessionApprovalCommands : UserToolSessionApproval { @@ -6333,7 +7330,7 @@ public sealed partial class UserToolSessionApprovalCommands : UserToolSessionApp public required string[] CommandIdentifiers { get; set; } } -/// Schema for the `UserToolSessionApprovalRead` type. +/// Session-scoped tool-approval rule for read-only filesystem operations. /// The read variant of . public sealed partial class UserToolSessionApprovalRead : UserToolSessionApproval { @@ -6342,7 +7339,7 @@ public sealed partial class UserToolSessionApprovalRead : UserToolSessionApprova public override string Kind => "read"; } -/// Schema for the `UserToolSessionApprovalWrite` type. +/// Session-scoped tool-approval rule for filesystem write operations. /// The write variant of . public sealed partial class UserToolSessionApprovalWrite : UserToolSessionApproval { @@ -6351,7 +7348,7 @@ public sealed partial class UserToolSessionApprovalWrite : UserToolSessionApprov public override string Kind => "write"; } -/// Schema for the `UserToolSessionApprovalMcp` type. +/// Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null. /// The mcp variant of . public sealed partial class UserToolSessionApprovalMcp : UserToolSessionApproval { @@ -6368,7 +7365,7 @@ public sealed partial class UserToolSessionApprovalMcp : UserToolSessionApproval public string? ToolName { get; set; } } -/// Schema for the `UserToolSessionApprovalMemory` type. +/// Session-scoped tool-approval rule for writes to long-term memory. /// The memory variant of . public sealed partial class UserToolSessionApprovalMemory : UserToolSessionApproval { @@ -6377,7 +7374,7 @@ public sealed partial class UserToolSessionApprovalMemory : UserToolSessionAppro public override string Kind => "memory"; } -/// Schema for the `UserToolSessionApprovalCustomTool` type. +/// Session-scoped tool-approval rule for a custom tool, keyed by tool name. /// The custom-tool variant of . public sealed partial class UserToolSessionApprovalCustomTool : UserToolSessionApproval { @@ -6390,7 +7387,7 @@ public sealed partial class UserToolSessionApprovalCustomTool : UserToolSessionA public required string ToolName { get; set; } } -/// Schema for the `UserToolSessionApprovalExtensionManagement` type. +/// Session-scoped tool-approval rule for extension-management operations, optionally narrowed by operation. /// The extension-management variant of . public sealed partial class UserToolSessionApprovalExtensionManagement : UserToolSessionApproval { @@ -6404,7 +7401,7 @@ public sealed partial class UserToolSessionApprovalExtensionManagement : UserToo public string? Operation { get; set; } } -/// Schema for the `UserToolSessionApprovalExtensionPermissionAccess` type. +/// Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name. /// The extension-permission-access variant of . public sealed partial class UserToolSessionApprovalExtensionPermissionAccess : UserToolSessionApproval { @@ -6438,7 +7435,7 @@ public partial class UserToolSessionApproval } -/// Schema for the `PermissionApprovedForSession` type. +/// Permission response variant that approves a request and remembers the provided approval for the rest of the session. /// The approved-for-session variant of . public sealed partial class PermissionResultApprovedForSession : PermissionResult { @@ -6451,7 +7448,7 @@ public sealed partial class PermissionResultApprovedForSession : PermissionResul public required UserToolSessionApproval Approval { get; set; } } -/// Schema for the `PermissionApprovedForLocation` type. +/// Permission response variant that approves a request and persists the provided approval to a project location key. /// The approved-for-location variant of . public sealed partial class PermissionResultApprovedForLocation : PermissionResult { @@ -6468,7 +7465,7 @@ public sealed partial class PermissionResultApprovedForLocation : PermissionResu public required string LocationKey { get; set; } } -/// Schema for the `PermissionCancelled` type. +/// Permission response variant indicating the request was cancelled before use, with an optional reason. /// The cancelled variant of . public sealed partial class PermissionResultCancelled : PermissionResult { @@ -6482,7 +7479,7 @@ public sealed partial class PermissionResultCancelled : PermissionResult public string? Reason { get; set; } } -/// Schema for the `PermissionRule` type. +/// A permission approval or denial rule matched against a tool request, identified by a rule kind with an optional argument value. /// Nested data type for PermissionRule. public sealed partial class PermissionRule { @@ -6495,7 +7492,7 @@ public sealed partial class PermissionRule public required string Kind { get; set; } } -/// Schema for the `PermissionDeniedByRules` type. +/// Permission response variant denied because matching approval rules explicitly blocked the request. /// The denied-by-rules variant of . public sealed partial class PermissionResultDeniedByRules : PermissionResult { @@ -6508,7 +7505,7 @@ public sealed partial class PermissionResultDeniedByRules : PermissionResult public required PermissionRule[] Rules { get; set; } } -/// Schema for the `PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. +/// Permission response variant denied because no approval rule matched and user confirmation was unavailable. /// The denied-no-approval-rule-and-could-not-request-from-user variant of . public sealed partial class PermissionResultDeniedNoApprovalRuleAndCouldNotRequestFromUser : PermissionResult { @@ -6517,7 +7514,7 @@ public sealed partial class PermissionResultDeniedNoApprovalRuleAndCouldNotReque public override string Kind => "denied-no-approval-rule-and-could-not-request-from-user"; } -/// Schema for the `PermissionDeniedInteractivelyByUser` type. +/// Permission response variant denied in an interactive user prompt, with optional feedback and force-reject flag. /// The denied-interactively-by-user variant of . public sealed partial class PermissionResultDeniedInteractivelyByUser : PermissionResult { @@ -6536,7 +7533,7 @@ public sealed partial class PermissionResultDeniedInteractivelyByUser : Permissi public bool? ForceReject { get; set; } } -/// Schema for the `PermissionDeniedByContentExclusionPolicy` type. +/// Permission response variant denying a path under content exclusion policy, with the path and message. /// The denied-by-content-exclusion-policy variant of . public sealed partial class PermissionResultDeniedByContentExclusionPolicy : PermissionResult { @@ -6553,7 +7550,7 @@ public sealed partial class PermissionResultDeniedByContentExclusionPolicy : Per public required string Path { get; set; } } -/// Schema for the `PermissionDeniedByPermissionRequestHook` type. +/// Permission response variant denied by a permission-request hook, with optional message and interrupt flag. /// The denied-by-permission-request-hook variant of . public sealed partial class PermissionResultDeniedByPermissionRequestHook : PermissionResult { @@ -6612,6 +7609,37 @@ public sealed partial class ElicitationRequestedSchema public required string Type { get; set; } } +/// Single HTTP header entry as a name/value pair. +/// Nested data type for HeaderEntry. +public sealed partial class HeaderEntry +{ + /// HTTP response header name as observed by the runtime. + [JsonPropertyName("name")] + public required string Name { get; set; } + + /// HTTP response header value as observed by the runtime. + [JsonPropertyName("value")] + public required string Value { get; set; } +} + +/// Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. +/// Nested data type for McpOauthHttpResponse. +public sealed partial class McpOauthHttpResponse +{ + /// Complete UTF-8 response body for host-specific challenge handling, including an empty string for an empty body. Omitted when the complete body is not valid UTF-8; body read failures fail the HTTP operation rather than exposing a partial response. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("body")] + public string? Body { get; set; } + + /// HTTP response headers as observed by the runtime. Order and casing are transport-dependent, and duplicate header names may appear multiple times. + [JsonPropertyName("headers")] + public required HeaderEntry[] Headers { get; set; } + + /// HTTP status code returned with the auth challenge. + [JsonPropertyName("statusCode")] + public required int StatusCode { get; set; } +} + /// Static OAuth client configuration, if the server specifies one. /// Nested data type for McpOauthRequiredStaticClientConfig. public sealed partial class McpOauthRequiredStaticClientConfig @@ -6620,6 +7648,11 @@ public sealed partial class McpOauthRequiredStaticClientConfig [JsonPropertyName("clientId")] public required string ClientId { get; set; } + /// Optional OAuth client secret for confidential static clients, when the runtime can resolve one. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("clientSecret")] + public string? ClientSecret { get; set; } + /// Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("grantType")] @@ -6640,9 +7673,10 @@ public sealed partial class McpOauthWWWAuthenticateParams [JsonPropertyName("error")] public string? Error { get; set; } - /// Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter. + /// Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter, if present. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("resourceMetadataUrl")] - public required string ResourceMetadataUrl { get; set; } + public string? ResourceMetadataUrl { get; set; } /// Requested OAuth scopes from the WWW-Authenticate scope parameter, if present. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -6650,7 +7684,26 @@ public sealed partial class McpOauthWWWAuthenticateParams public string? Scope { get; set; } } -/// Schema for the `CommandsChangedCommand` type. +/// The user's selected action for an exhausted session limit. +/// Nested data type for SessionLimitsExhaustedResponse. +public sealed partial class SessionLimitsExhaustedResponse +{ + /// Action selected by the user. + [JsonPropertyName("action")] + public required SessionLimitsExhaustedResponseAction Action { get; set; } + + /// AI Credits to add to the current max when action is 'add'. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("additionalAiCredits")] + public double? AdditionalAiCredits { get; set; } + + /// New absolute max AI Credits when action is 'set'. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("maxAiCredits")] + public double? MaxAiCredits { get; set; } +} + +/// A single slash command available in the session, as listed by the `commands.changed` event. /// Nested data type for CommandsChangedCommand. public sealed partial class CommandsChangedCommand { @@ -6684,7 +7737,7 @@ public sealed partial class CapabilitiesChangedUI public bool? McpApps { get; set; } } -/// Schema for the `SkillsLoadedSkill` type. +/// A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. /// Nested data type for SkillsLoadedSkill. public sealed partial class SkillsLoadedSkill { @@ -6719,7 +7772,7 @@ public sealed partial class SkillsLoadedSkill public required bool UserInvocable { get; set; } } -/// Schema for the `CustomAgentsUpdatedAgent` type. +/// A single loaded custom agent in `session.custom_agents_updated`, with identity, source, tools, invocability, and model override. /// Nested data type for CustomAgentsUpdatedAgent. public sealed partial class CustomAgentsUpdatedAgent { @@ -6757,7 +7810,7 @@ public sealed partial class CustomAgentsUpdatedAgent public required bool UserInvocable { get; set; } } -/// Schema for the `McpServersLoadedServer` type. +/// A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata. /// Nested data type for McpServersLoadedServer. public sealed partial class McpServersLoadedServer { @@ -6795,7 +7848,7 @@ public sealed partial class McpServersLoadedServer public McpServerTransport? Transport { get; set; } } -/// Schema for the `ExtensionsLoadedExtension` type. +/// A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status. /// Nested data type for ExtensionsLoadedExtension. public sealed partial class ExtensionsLoadedExtension { @@ -6816,7 +7869,7 @@ public sealed partial class ExtensionsLoadedExtension public required ExtensionsLoadedExtensionStatus Status { get; set; } } -/// Schema for the `CanvasRegistryChangedCanvasAction` type. +/// A single action within a canvas declaration, with its name, optional description, and optional input schema. /// Nested data type for CanvasRegistryChangedCanvasAction. [Experimental(Diagnostics.Experimental)] public sealed partial class CanvasRegistryChangedCanvasAction @@ -6836,7 +7889,7 @@ public sealed partial class CanvasRegistryChangedCanvasAction public required string Name { get; set; } } -/// Schema for the `CanvasRegistryChangedCanvas` type. +/// A single canvas declaration in `session.canvas.registry_changed`, including provider IDs, display metadata, input schema, and actions. /// Nested data type for CanvasRegistryChangedCanvas. [Experimental(Diagnostics.Experimental)] public sealed partial class CanvasRegistryChangedCanvas @@ -6869,6 +7922,11 @@ public sealed partial class CanvasRegistryChangedCanvas [JsonPropertyName("extensionName")] public string? ExtensionName { get; set; } + /// Host-local PNG path for the canvas icon, when supplied. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("icon")] + public string? Icon { get; set; } + /// JSON Schema for canvas open input. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("inputSchema")] @@ -6884,7 +7942,7 @@ public sealed partial class McpAppToolCallCompleteError public required string Message { get; set; } } -/// Schema for the `McpAppToolCallCompleteToolMetaUI` type. +/// MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. /// Nested data type for McpAppToolCallCompleteToolMetaUI. public sealed partial class McpAppToolCallCompleteToolMetaUI { @@ -6903,7 +7961,7 @@ public sealed partial class McpAppToolCallCompleteToolMetaUI /// Nested data type for McpAppToolCallCompleteToolMeta. public sealed partial class McpAppToolCallCompleteToolMeta { - /// Schema for the `McpAppToolCallCompleteToolMetaUI` type. + /// MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("ui")] public McpAppToolCallCompleteToolMetaUI? Ui { get; set; } @@ -7095,6 +8153,70 @@ public override void Write(Utf8JsonWriter writer, ReasoningSummary value, JsonSe } } +/// Output verbosity level used for supported model calls (e.g. "low", "medium", "high"). +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct Verbosity : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public Verbosity(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// A terse response was requested. + public static Verbosity Low { get; } = new("low"); + + /// A medium amount of response detail was requested. + public static Verbosity Medium { get; } = new("medium"); + + /// A more detailed response was requested. + public static Verbosity High { get; } = new("high"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(Verbosity left, Verbosity right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(Verbosity left, Verbosity right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is Verbosity other && Equals(other); + + /// + public bool Equals(Verbosity other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override Verbosity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, Verbosity value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(Verbosity)); + } + } +} + /// The type of operation performed on the autopilot objective state file. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -7290,6 +8412,71 @@ public override void Write(Utf8JsonWriter writer, SessionMode value, JsonSeriali } } +/// Allow-all mode for the session. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct PermissionAllowAllMode : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public PermissionAllowAllMode(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Permission requests follow the normal approval flow. + public static PermissionAllowAllMode Off { get; } = new("off"); + + /// Tool, path, and URL permission requests are automatically approved. + public static PermissionAllowAllMode On { get; } = new("on"); + + /// Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + public static PermissionAllowAllMode Auto { get; } = new("auto"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionAllowAllMode left, PermissionAllowAllMode right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionAllowAllMode left, PermissionAllowAllMode right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is PermissionAllowAllMode other && Equals(other); + + /// + public bool Equals(PermissionAllowAllMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override PermissionAllowAllMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, PermissionAllowAllMode value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionAllowAllMode)); + } + } +} + /// The type of operation performed on the plan file. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -7729,46 +8916,45 @@ public override void Write(Utf8JsonWriter writer, AttachmentGitHubReferenceType } } -/// The system that produced a citation. -[Experimental(Diagnostics.Experimental)] +/// How this user message was delivered to the agentic loop, relative to whether the loop was already running. This is the timing axis only; the message's origin (human vs. system/command/schedule/skill/etc.) is carried separately by `source`. A system-injected message has a delivery too — e.g. a background-task notification waking an idle agent is `idle`, the same mechanism as a human starting a fresh turn. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct CitationProvider : IEquatable +public readonly struct UserMessageDelivery : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public CitationProvider(string value) + public UserMessageDelivery(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Citation produced by an Anthropic (Claude) model response. - public static CitationProvider Anthropic { get; } = new("anthropic"); + /// Delivered while the loop was idle; starts its own run immediately (a human's fresh turn, or a system notification waking an idle agent). + public static UserMessageDelivery Idle { get; } = new("idle"); - /// Citation produced by an OpenAI model response. - public static CitationProvider Openai { get; } = new("openai"); + /// Injected into the current in-flight run while the agent was busy (immediate mode). + public static UserMessageDelivery Steering { get; } = new("steering"); - /// Citation synthesized client-side by the runtime from tool output. - public static CitationProvider Client { get; } = new("client"); + /// Enqueued while the agent was busy; processed as its own run afterward. + public static UserMessageDelivery Queued { get; } = new("queued"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(CitationProvider left, CitationProvider right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UserMessageDelivery left, UserMessageDelivery right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(CitationProvider left, CitationProvider right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UserMessageDelivery left, UserMessageDelivery right) => !(left == right); /// - public override bool Equals(object? obj) => obj is CitationProvider other && Equals(other); + public override bool Equals(object? obj) => obj is UserMessageDelivery other && Equals(other); /// - public bool Equals(CitationProvider other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UserMessageDelivery other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -7776,20 +8962,20 @@ public CitationProvider(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override CitationProvider Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UserMessageDelivery Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, CitationProvider value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UserMessageDelivery value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(CitationProvider)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UserMessageDelivery)); } } } @@ -7855,6 +9041,71 @@ public override void Write(Utf8JsonWriter writer, AssistantMessageToolRequestTyp } } +/// The system that produced a citation. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct CitationProvider : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public CitationProvider(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Citation produced by an Anthropic (Claude) model response. + public static CitationProvider Anthropic { get; } = new("anthropic"); + + /// Citation produced by an OpenAI model response. + public static CitationProvider Openai { get; } = new("openai"); + + /// Citation synthesized client-side by the runtime from tool output. + public static CitationProvider Client { get; } = new("client"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(CitationProvider left, CitationProvider right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(CitationProvider left, CitationProvider right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is CitationProvider other && Equals(other); + + /// + public bool Equals(CitationProvider other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override CitationProvider Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, CitationProvider value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(CitationProvider)); + } + } +} + /// API endpoint used for this model call, matching CAPI supported_endpoints vocabulary. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -8846,6 +10097,74 @@ public override void Write(Utf8JsonWriter writer, PermissionRequestMemoryDirecti } } +/// Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct AutoApprovalRecommendation : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public AutoApprovalRecommendation(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The judge evaluated the request and recommends automatically approving it. + public static AutoApprovalRecommendation Approve { get; } = new("approve"); + + /// The judge evaluated the request and does not recommend auto-approving it; explicit approval is required. Whether that means prompting, denying, or something else is the consumer's decision. + public static AutoApprovalRecommendation RequireApproval { get; } = new("requireApproval"); + + /// Auto mode is enabled, but this request category is never auto-approvable (for example, sandbox-bypass requests), so the judge was not consulted. + public static AutoApprovalRecommendation Excluded { get; } = new("excluded"); + + /// The judge was consulted but did not return a usable recommendation, so the request requires explicit approval. + public static AutoApprovalRecommendation Error { get; } = new("error"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AutoApprovalRecommendation left, AutoApprovalRecommendation right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AutoApprovalRecommendation left, AutoApprovalRecommendation right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is AutoApprovalRecommendation other && Equals(other); + + /// + public bool Equals(AutoApprovalRecommendation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override AutoApprovalRecommendation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, AutoApprovalRecommendation value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AutoApprovalRecommendation)); + } + } +} + /// Underlying permission kind that needs path approval. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -9035,6 +10354,73 @@ public override void Write(Utf8JsonWriter writer, ElicitationCompletedAction val } } +/// Reason the runtime is requesting host-provided MCP OAuth credentials. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct McpOauthRequestReason : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public McpOauthRequestReason(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Initial credentials are required before connecting to the MCP server. + public static McpOauthRequestReason Initial { get; } = new("initial"); + + /// The current host-provided credential was rejected and a replacement is requested. + public static McpOauthRequestReason Refresh { get; } = new("refresh"); + + /// The server requires a new host authorization flow before continuing. + public static McpOauthRequestReason Reauth { get; } = new("reauth"); + + /// The server requires a credential with additional scope or audience. + public static McpOauthRequestReason Upscope { get; } = new("upscope"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpOauthRequestReason left, McpOauthRequestReason right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpOauthRequestReason left, McpOauthRequestReason right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is McpOauthRequestReason other && Equals(other); + + /// + public bool Equals(McpOauthRequestReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override McpOauthRequestReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, McpOauthRequestReason value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpOauthRequestReason)); + } + } +} + /// How the pending MCP OAuth request was completed. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -9096,6 +10482,134 @@ public override void Write(Utf8JsonWriter writer, McpOauthCompletionOutcome valu } } +/// Why dynamic headers are being requested. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct McpHeadersRefreshRequiredReason : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public McpHeadersRefreshRequiredReason(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The transport is making its first dynamic header request for this server. + public static McpHeadersRefreshRequiredReason Startup { get; } = new("startup"); + + /// The previously cached dynamic headers expired. + public static McpHeadersRefreshRequiredReason TtlExpired { get; } = new("ttl-expired"); + + /// The server returned 401 and stale dynamic headers were invalidated. + public static McpHeadersRefreshRequiredReason AuthFailed { get; } = new("auth-failed"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpHeadersRefreshRequiredReason left, McpHeadersRefreshRequiredReason right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpHeadersRefreshRequiredReason left, McpHeadersRefreshRequiredReason right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is McpHeadersRefreshRequiredReason other && Equals(other); + + /// + public bool Equals(McpHeadersRefreshRequiredReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override McpHeadersRefreshRequiredReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, McpHeadersRefreshRequiredReason value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpHeadersRefreshRequiredReason)); + } + } +} + +/// How the pending MCP headers refresh request resolved. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct McpHeadersRefreshCompletedOutcome : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public McpHeadersRefreshCompletedOutcome(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The host supplied dynamic headers. + public static McpHeadersRefreshCompletedOutcome Headers { get; } = new("headers"); + + /// The host responded with no dynamic headers. + public static McpHeadersRefreshCompletedOutcome None { get; } = new("none"); + + /// No response arrived within the bounded window. + public static McpHeadersRefreshCompletedOutcome Timeout { get; } = new("timeout"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpHeadersRefreshCompletedOutcome left, McpHeadersRefreshCompletedOutcome right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpHeadersRefreshCompletedOutcome left, McpHeadersRefreshCompletedOutcome right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is McpHeadersRefreshCompletedOutcome other && Equals(other); + + /// + public bool Equals(McpHeadersRefreshCompletedOutcome other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override McpHeadersRefreshCompletedOutcome Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, McpHeadersRefreshCompletedOutcome value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpHeadersRefreshCompletedOutcome)); + } + } +} + /// The user's auto-mode-switch choice. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -9160,6 +10674,201 @@ public override void Write(Utf8JsonWriter writer, AutoModeSwitchResponse value, } } +/// User action selected for an exhausted session limit. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SessionLimitsExhaustedResponseAction : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SessionLimitsExhaustedResponseAction(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Increase the current max by an exact AI Credits amount. + public static SessionLimitsExhaustedResponseAction Add { get; } = new("add"); + + /// Set a new absolute max AI Credits value. + public static SessionLimitsExhaustedResponseAction Set { get; } = new("set"); + + /// Remove the current session limit. + public static SessionLimitsExhaustedResponseAction Unset { get; } = new("unset"); + + /// Leave the limit unchanged and cancel the blocked model request. + public static SessionLimitsExhaustedResponseAction Cancel { get; } = new("cancel"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionLimitsExhaustedResponseAction left, SessionLimitsExhaustedResponseAction right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionLimitsExhaustedResponseAction left, SessionLimitsExhaustedResponseAction right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is SessionLimitsExhaustedResponseAction other && Equals(other); + + /// + public bool Equals(SessionLimitsExhaustedResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SessionLimitsExhaustedResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SessionLimitsExhaustedResponseAction value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLimitsExhaustedResponseAction)); + } + } +} + +/// Coarse request-difficulty bucket for UX explainability. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct AutoModeResolvedReasoningBucket : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public AutoModeResolvedReasoningBucket(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The request looks low-reasoning; a lighter model is appropriate. + public static AutoModeResolvedReasoningBucket Low { get; } = new("low"); + + /// The request needs a moderate amount of reasoning. + public static AutoModeResolvedReasoningBucket Medium { get; } = new("medium"); + + /// The request looks high-reasoning; a stronger model is appropriate. + public static AutoModeResolvedReasoningBucket High { get; } = new("high"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AutoModeResolvedReasoningBucket left, AutoModeResolvedReasoningBucket right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AutoModeResolvedReasoningBucket left, AutoModeResolvedReasoningBucket right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is AutoModeResolvedReasoningBucket other && Equals(other); + + /// + public bool Equals(AutoModeResolvedReasoningBucket other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override AutoModeResolvedReasoningBucket Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, AutoModeResolvedReasoningBucket value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AutoModeResolvedReasoningBucket)); + } + } +} + +/// Which channel supplied the effective enterprise managed settings (highest-authority present layer wins wholesale). +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct ManagedSettingsResolvedSource : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public ManagedSettingsResolvedSource(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Account/org policy self-fetched from the GitHub managed-settings endpoint (higher authority). + public static ManagedSettingsResolvedSource Server { get; } = new("server"); + + /// Device-level MDM policy discovered from plist/registry/file (lower authority). + public static ManagedSettingsResolvedSource Device { get; } = new("device"); + + /// No managed policy is in force (no layer contributed). + public static ManagedSettingsResolvedSource None { get; } = new("none"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ManagedSettingsResolvedSource left, ManagedSettingsResolvedSource right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ManagedSettingsResolvedSource left, ManagedSettingsResolvedSource right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is ManagedSettingsResolvedSource other && Equals(other); + + /// + public bool Equals(ManagedSettingsResolvedSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override ManagedSettingsResolvedSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, ManagedSettingsResolvedSource value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ManagedSettingsResolvedSource)); + } + } +} + /// Exit plan mode action. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -9651,6 +11360,8 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(AbortData))] [JsonSerializable(typeof(AbortEvent))] +[JsonSerializable(typeof(AssistantIdleData))] +[JsonSerializable(typeof(AssistantIdleEvent))] [JsonSerializable(typeof(AssistantIntentData))] [JsonSerializable(typeof(AssistantIntentEvent))] [JsonSerializable(typeof(AssistantMessageData))] @@ -9665,8 +11376,12 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(AssistantReasoningDeltaData))] [JsonSerializable(typeof(AssistantReasoningDeltaEvent))] [JsonSerializable(typeof(AssistantReasoningEvent))] +[JsonSerializable(typeof(AssistantServerToolProgressData))] +[JsonSerializable(typeof(AssistantServerToolProgressEvent))] [JsonSerializable(typeof(AssistantStreamingDeltaData))] [JsonSerializable(typeof(AssistantStreamingDeltaEvent))] +[JsonSerializable(typeof(AssistantToolCallDeltaData))] +[JsonSerializable(typeof(AssistantToolCallDeltaEvent))] [JsonSerializable(typeof(AssistantTurnEndData))] [JsonSerializable(typeof(AssistantTurnEndEvent))] [JsonSerializable(typeof(AssistantTurnStartData))] @@ -9682,7 +11397,18 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(AttachmentExtensionContext))] [JsonSerializable(typeof(AttachmentFile))] [JsonSerializable(typeof(AttachmentFileLineRange))] +[JsonSerializable(typeof(AttachmentGitHubActionsJob))] +[JsonSerializable(typeof(AttachmentGitHubCommit))] +[JsonSerializable(typeof(AttachmentGitHubFile))] +[JsonSerializable(typeof(AttachmentGitHubFileDiff))] +[JsonSerializable(typeof(AttachmentGitHubFileDiffSide))] [JsonSerializable(typeof(AttachmentGitHubReference))] +[JsonSerializable(typeof(AttachmentGitHubRelease))] +[JsonSerializable(typeof(AttachmentGitHubRepository))] +[JsonSerializable(typeof(AttachmentGitHubSnippet))] +[JsonSerializable(typeof(AttachmentGitHubTreeComparison))] +[JsonSerializable(typeof(AttachmentGitHubTreeComparisonSide))] +[JsonSerializable(typeof(AttachmentGitHubUrl))] [JsonSerializable(typeof(AttachmentSelection))] [JsonSerializable(typeof(AttachmentSelectionDetails))] [JsonSerializable(typeof(AttachmentSelectionDetailsEnd))] @@ -9735,7 +11461,9 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(ExternalToolCompletedEvent))] [JsonSerializable(typeof(ExternalToolRequestedData))] [JsonSerializable(typeof(ExternalToolRequestedEvent))] +[JsonSerializable(typeof(GitHubRepoRef))] [JsonSerializable(typeof(HandoffRepository))] +[JsonSerializable(typeof(HeaderEntry))] [JsonSerializable(typeof(HookEndData))] [JsonSerializable(typeof(HookEndError))] [JsonSerializable(typeof(HookEndEvent))] @@ -9748,19 +11476,31 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(McpAppToolCallCompleteEvent))] [JsonSerializable(typeof(McpAppToolCallCompleteToolMeta))] [JsonSerializable(typeof(McpAppToolCallCompleteToolMetaUI))] +[JsonSerializable(typeof(McpHeadersRefreshCompletedData))] +[JsonSerializable(typeof(McpHeadersRefreshCompletedEvent))] +[JsonSerializable(typeof(McpHeadersRefreshRequiredData))] +[JsonSerializable(typeof(McpHeadersRefreshRequiredEvent))] [JsonSerializable(typeof(McpOauthCompletedData))] [JsonSerializable(typeof(McpOauthCompletedEvent))] +[JsonSerializable(typeof(McpOauthHttpResponse))] [JsonSerializable(typeof(McpOauthRequiredData))] [JsonSerializable(typeof(McpOauthRequiredEvent))] [JsonSerializable(typeof(McpOauthRequiredStaticClientConfig))] [JsonSerializable(typeof(McpOauthWWWAuthenticateParams))] +[JsonSerializable(typeof(McpPromptsListChangedData))] +[JsonSerializable(typeof(McpPromptsListChangedEvent))] +[JsonSerializable(typeof(McpResourcesListChangedData))] +[JsonSerializable(typeof(McpResourcesListChangedEvent))] [JsonSerializable(typeof(McpServersLoadedServer))] +[JsonSerializable(typeof(McpToolsListChangedData))] +[JsonSerializable(typeof(McpToolsListChangedEvent))] [JsonSerializable(typeof(ModelCallFailureData))] [JsonSerializable(typeof(ModelCallFailureEvent))] [JsonSerializable(typeof(ModelCallFailureRequestFingerprint))] [JsonSerializable(typeof(OmittedBinaryResult))] [JsonSerializable(typeof(PendingMessagesModifiedData))] [JsonSerializable(typeof(PendingMessagesModifiedEvent))] +[JsonSerializable(typeof(PermissionAutoApproval))] [JsonSerializable(typeof(PermissionCompletedData))] [JsonSerializable(typeof(PermissionCompletedEvent))] [JsonSerializable(typeof(PermissionPromptRequest))] @@ -9807,6 +11547,8 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(SamplingCompletedEvent))] [JsonSerializable(typeof(SamplingRequestedData))] [JsonSerializable(typeof(SamplingRequestedEvent))] +[JsonSerializable(typeof(SessionAutoModeResolvedData))] +[JsonSerializable(typeof(SessionAutoModeResolvedEvent))] [JsonSerializable(typeof(SessionAutopilotObjectiveChangedData))] [JsonSerializable(typeof(SessionAutopilotObjectiveChangedEvent))] [JsonSerializable(typeof(SessionBackgroundTasksChangedData))] @@ -9848,6 +11590,14 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(SessionIdleEvent))] [JsonSerializable(typeof(SessionInfoData))] [JsonSerializable(typeof(SessionInfoEvent))] +[JsonSerializable(typeof(SessionLimitsConfig))] +[JsonSerializable(typeof(SessionLimitsExhaustedCompletedData))] +[JsonSerializable(typeof(SessionLimitsExhaustedCompletedEvent))] +[JsonSerializable(typeof(SessionLimitsExhaustedRequestedData))] +[JsonSerializable(typeof(SessionLimitsExhaustedRequestedEvent))] +[JsonSerializable(typeof(SessionLimitsExhaustedResponse))] +[JsonSerializable(typeof(SessionManagedSettingsResolvedData))] +[JsonSerializable(typeof(SessionManagedSettingsResolvedEvent))] [JsonSerializable(typeof(SessionMcpServerStatusChangedData))] [JsonSerializable(typeof(SessionMcpServerStatusChangedEvent))] [JsonSerializable(typeof(SessionMcpServersLoadedData))] @@ -9870,6 +11620,8 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(SessionScheduleCreatedEvent))] [JsonSerializable(typeof(SessionScheduleRearmedData))] [JsonSerializable(typeof(SessionScheduleRearmedEvent))] +[JsonSerializable(typeof(SessionSessionLimitsChangedData))] +[JsonSerializable(typeof(SessionSessionLimitsChangedEvent))] [JsonSerializable(typeof(SessionShutdownData))] [JsonSerializable(typeof(SessionShutdownEvent))] [JsonSerializable(typeof(SessionSkillsLoadedData))] @@ -9888,6 +11640,8 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(SessionToolsUpdatedEvent))] [JsonSerializable(typeof(SessionTruncationData))] [JsonSerializable(typeof(SessionTruncationEvent))] +[JsonSerializable(typeof(SessionUsageCheckpointData))] +[JsonSerializable(typeof(SessionUsageCheckpointEvent))] [JsonSerializable(typeof(SessionUsageInfoData))] [JsonSerializable(typeof(SessionUsageInfoEvent))] [JsonSerializable(typeof(SessionWarningData))] @@ -9932,6 +11686,7 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(ToolExecutionCompleteContentResourceDetails))] [JsonSerializable(typeof(ToolExecutionCompleteContentResourceLink))] [JsonSerializable(typeof(ToolExecutionCompleteContentResourceLinkIcon))] +[JsonSerializable(typeof(ToolExecutionCompleteContentShellExit))] [JsonSerializable(typeof(ToolExecutionCompleteContentTerminal))] [JsonSerializable(typeof(ToolExecutionCompleteContentText))] [JsonSerializable(typeof(ToolExecutionCompleteData))] @@ -9956,6 +11711,7 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(ToolExecutionProgressEvent))] [JsonSerializable(typeof(ToolExecutionStartData))] [JsonSerializable(typeof(ToolExecutionStartEvent))] +[JsonSerializable(typeof(ToolExecutionStartShellToolInfo))] [JsonSerializable(typeof(ToolExecutionStartToolDescription))] [JsonSerializable(typeof(ToolExecutionStartToolDescriptionMeta))] [JsonSerializable(typeof(ToolExecutionStartToolDescriptionMetaUI))] diff --git a/dotnet/src/GitHub.Copilot.SDK.csproj b/dotnet/src/GitHub.Copilot.SDK.csproj index 7a9fa2bdca..f48fb802d7 100644 --- a/dotnet/src/GitHub.Copilot.SDK.csproj +++ b/dotnet/src/GitHub.Copilot.SDK.csproj @@ -16,6 +16,7 @@ copilot.png github;copilot;sdk;jsonrpc;agent true + true true snupkg true diff --git a/dotnet/src/JsonRpc.cs b/dotnet/src/JsonRpc.cs index edd0534ab8..bf1684f17b 100644 --- a/dotnet/src/JsonRpc.cs +++ b/dotnet/src/JsonRpc.cs @@ -206,14 +206,12 @@ public void Dispose() private async Task SendMessageAsync(T message, JsonTypeInfo typeInfo, CancellationToken cancellationToken) { - // "Content-Length: " (16) + max int digits (10) + "\r\n\r\n" (4) - const int MaxHeaderLength = 30; - var json = JsonSerializer.SerializeToUtf8Bytes(message, typeInfo); - var headerBuf = ArrayPool.Shared.Rent(MaxHeaderLength); - bool wrote = Utf8.TryWrite(headerBuf, $"Content-Length: {json.Length}\r\n\r\n", out int headerLen); - Debug.Assert(wrote && headerLen > 0); + // Format the LSP header and body into a single pooled buffer so the framed + // message is written in one call — over the FFI transport that is one native + // boundary crossing per message instead of two. + var frame = BuildFrame(json, out int frameLen); // Cancellation only applies to *waiting* for the write lock. Once we hold the lock // and start writing a framed message, we must finish it — cancelling between the @@ -223,15 +221,40 @@ private async Task SendMessageAsync(T message, JsonTypeInfo typeInfo, Canc await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); try { - await _sendStream.WriteAsync(headerBuf.AsMemory(0, headerLen), CancellationToken.None).ConfigureAwait(false); - await _sendStream.WriteAsync(json, CancellationToken.None).ConfigureAwait(false); + await _sendStream.WriteAsync(frame.AsMemory(0, frameLen), CancellationToken.None).ConfigureAwait(false); await _sendStream.FlushAsync(CancellationToken.None).ConfigureAwait(false); } finally { _writeLock.Release(); - ArrayPool.Shared.Return(headerBuf); + ArrayPool.Shared.Return(frame); + } + } + + /// + /// Writes Content-Length: N\r\n\r\n followed by into a + /// single buffer rented from . The caller owns the returned + /// buffer and must return it to the shared pool. + /// + private static byte[] BuildFrame(ReadOnlySpan json, out int frameLen) + { + // "Content-Length: " (16) + max int digits (10) + "\r\n\r\n" (4) + const int MaxHeaderLength = 30; + + // Over-rent by the (fixed, tiny) header bound so the header can be written + // straight into the frame — no scratch buffer or header copy. The JSON is + // already UTF-8, so the only copy is placing it after the header, which is + // unavoidable since Content-Length needs its length up front. + var frame = ArrayPool.Shared.Rent(MaxHeaderLength + json.Length); + if (!Utf8.TryWrite(frame, $"Content-Length: {json.Length}\r\n\r\n", out int headerLen)) + { + ArrayPool.Shared.Return(frame); + throw new InvalidOperationException("Failed to write JSON-RPC frame header."); } + + json.CopyTo(frame.AsSpan(headerLen)); + frameLen = headerLen + json.Length; + return frame; } private async Task ReadLoopAsync(CancellationToken cancellationToken) diff --git a/dotnet/src/Session.cs b/dotnet/src/Session.cs index 0985848e26..04306b7f62 100644 --- a/dotnet/src/Session.cs +++ b/dotnet/src/Session.cs @@ -63,6 +63,7 @@ public sealed partial class CopilotSession : IAsyncDisposable private readonly CopilotClient _parentClient; private volatile Func>? _permissionHandler; + private volatile Func>? _mcpAuthHandler; private volatile Func>? _userInputHandler; private volatile Func>? _elicitationHandler; private volatile Func>? _exitPlanModeHandler; @@ -89,6 +90,13 @@ private sealed record EventSubscription(Type EventType, Action Han private readonly Channel _eventChannel = Channel.CreateUnbounded( new() { SingleReader = true }); + /// + /// Fixed name of the runtime's built-in tool-search tool. A client can + /// replace its behavior by registering a tool with this exact name and + /// OverridesBuiltInTool set to true. + /// + private const string ToolSearchToolName = "tool_search_tool"; + /// /// Gets the unique identifier for this session. /// @@ -558,6 +566,11 @@ internal void RegisterPermissionHandler(Func>? handler) + { + _mcpAuthHandler = handler; + } + /// /// Handles a permission request from the Copilot CLI. /// @@ -633,6 +646,39 @@ private async Task HandleBroadcastEventAsync(SessionEvent sessionEvent) break; } + case McpOauthRequiredEvent authEvent: + { + var data = authEvent.Data; + if (string.IsNullOrEmpty(data.RequestId)) + return; + + var handler = _mcpAuthHandler; + if (handler is null) + { + if (_logger.IsEnabled(LogLevel.Warning)) + { + _logger.LogWarning( + "Received MCP OAuth request without a registered MCP auth handler. SessionId={SessionId}, RequestId={RequestId}", + SessionId, + data.RequestId); + } + return; + } + + await ExecuteMcpAuthAndRespondAsync(data.RequestId, new McpAuthContext + { + SessionId = SessionId, + RequestId = data.RequestId, + ServerName = data.ServerName, + ServerUrl = data.ServerUrl, + Reason = data.Reason, + WwwAuthenticateParams = data.WwwAuthenticateParams, + ResourceMetadata = data.ResourceMetadata, + StaticClientConfig = data.StaticClientConfig + }, handler); + break; + } + case CommandExecuteEvent cmdEvent: { var data = cmdEvent.Data; @@ -702,6 +748,91 @@ await HandleElicitationRequestAsync( } } + private async Task ExecuteMcpAuthAndRespondAsync( + string requestId, + McpAuthContext context, + Func> handler) + { + try + { + var result = await handler(context); + McpOauthPendingRequestResponse response = + result is { Cancelled: false, Token: { } token } + ? new McpOauthPendingRequestResponseToken + { + AccessToken = token.AccessToken, + TokenType = token.TokenType, + ExpiresIn = token.ExpiresIn + } + : new McpOauthPendingRequestResponseCancelled(); + + await Rpc.Mcp.Oauth.HandlePendingRequestAsync(requestId, response); + } + catch (OperationCanceledException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (ObjectDisposedException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (InvalidOperationException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (ArgumentException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (NotSupportedException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (JsonException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (RemoteRpcException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (IOException) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + catch (Exception ex) when (IsRecoverableMcpAuthFailure(ex)) + { + await TryCancelMcpAuthRequestAsync(requestId); + } + } + + private static bool IsRecoverableMcpAuthFailure(Exception exception) + => exception is not OperationCanceledException + and not OutOfMemoryException + and not StackOverflowException + and not AccessViolationException + and not AppDomainUnloadedException; + + private async Task TryCancelMcpAuthRequestAsync(string requestId) + { + try + { + await Rpc.Mcp.Oauth.HandlePendingRequestAsync(requestId, new McpOauthPendingRequestResponseCancelled()); + } + catch (IOException) + { + // Connection lost — nothing we can do. + } + catch (ObjectDisposedException) + { + // Connection already disposed — nothing we can do. + } + catch (RemoteRpcException) + { + // The pending request may already be gone — nothing we can do. + } + } + /// /// Executes a tool handler and sends the result back via the HandlePendingToolCall RPC. /// @@ -717,6 +848,26 @@ private async Task ExecuteToolAndRespondAsync(string requestId, string toolName, Arguments = arguments }; + // The built-in tool-search tool receives a snapshot of the session's + // currently initialized tools so an override can filter the live + // catalog without issuing its own RPC. Fetch it only for that tool + // to avoid a round-trip on every tool call; a failed fetch leaves + // the snapshot null rather than failing the tool. + if (toolName == ToolSearchToolName) + { + try + { + var metadata = await Rpc.Tools.GetCurrentMetadataAsync(); + invocation.AvailableTools = metadata.Tools; + } + catch (Exception ex) when (ex is RemoteRpcException or IOException or ObjectDisposedException or JsonException) + { + // A failed metadata fetch is non-fatal: leave AvailableTools + // null so the tool still runs without the snapshot. + LogToolMetadataFetchFailed(ex, toolName); + } + } + var aiFunctionArgs = new AIFunctionArguments { Context = new Dictionary @@ -967,6 +1118,7 @@ private void UpdateOpenCanvasesFromEvent(SessionEvent sessionEvent) InstanceId = data.InstanceId, Status = data.Status, Title = data.Title, + Icon = data.Icon, Url = data.Url, }); } @@ -1624,15 +1776,15 @@ public async Task AbortAsync(CancellationToken cancellationToken = default) /// Changes the model for this session. /// The new model takes effect for the next message. Conversation history is preserved. /// - /// Model ID to switch to (e.g., "gpt-4.1"). + /// Model ID to switch to (e.g., "gpt-5.4"). /// Reasoning effort level (e.g., "low", "medium", "high", "xhigh"). /// Per-property overrides for model capabilities, deep-merged over runtime defaults. /// Optional cancellation token. /// /// - /// await session.SetModelAsync("gpt-4.1"); + /// await session.SetModelAsync("gpt-5.4"); /// await session.SetModelAsync("claude-sonnet-4.6", "high"); - /// await session.SetModelAsync("gpt-4.1", new SetModelOptions { ContextTier = ContextTier.LongContext }); + /// await session.SetModelAsync("gpt-5.4", new SetModelOptions { ContextTier = ContextTier.LongContext }); /// /// public Task SetModelAsync(string model, string? reasoningEffort, ModelCapabilitiesOverride? modelCapabilities = null, CancellationToken cancellationToken = default) @@ -1651,7 +1803,7 @@ public Task SetModelAsync(string model, string? reasoningEffort, ModelCapabiliti /// Changes the model for this session. /// The new model takes effect for the next message. Conversation history is preserved. /// - /// Model ID to switch to (e.g., "gpt-4.1"). + /// Model ID to switch to (e.g., "gpt-5.4"). /// Settings for the new model. /// Optional cancellation token. public async Task SetModelAsync(string model, SetModelOptions options, CancellationToken cancellationToken = default) @@ -1663,6 +1815,7 @@ await Rpc.Model.SwitchToAsync( model, options.ReasoningEffort, options.ReasoningSummary, + null, options.ModelCapabilities, options.ContextTier, cancellationToken); @@ -1782,6 +1935,9 @@ await InvokeRpcAsync( [LoggerMessage(Level = LogLevel.Error, Message = "Unhandled exception in session event handler")] private partial void LogEventHandlerError(Exception exception); + [LoggerMessage(Level = LogLevel.Debug, Message = "Failed to fetch tool metadata for {toolName}")] + private partial void LogToolMetadataFetchFailed(Exception exception, string toolName); + internal record SendMessageRequest { public string SessionId { get; init; } = string.Empty; diff --git a/dotnet/src/Types.cs b/dotnet/src/Types.cs index 5ae9657813..2bb643c75b 100644 --- a/dotnet/src/Types.cs +++ b/dotnet/src/Types.cs @@ -145,6 +145,20 @@ public static TcpRuntimeConnection ForTcp(int port = 0, string? connectionToken /// Optional shared secret to authenticate the connection. public static UriRuntimeConnection ForUri(string url, string? connectionToken = null) => new() { Url = url, ConnectionToken = connectionToken }; + + /// + /// Host the runtime in-process by loading its native library and communicating + /// over the C ABI (FFI) — no child process is spawned by the SDK for JSON-RPC + /// transport. The bundled runtime is used; to point at a non-default runtime + /// entrypoint, set the COPILOT_CLI_PATH environment variable. + /// + /// + /// Works across the SDK's target frameworks: modern .NET uses NativeLibrary, + /// while netstandard2.0 consumers use a built-in fallback native loader. + /// + [Experimental(Diagnostics.Experimental)] + public static InProcessRuntimeConnection ForInProcess() + => new(); } /// @@ -159,6 +173,16 @@ internal ChildProcessRuntimeConnection() { } /// Extra command-line arguments to pass to the runtime process. public IList? Args { get; set; } + + /// + /// Gets or sets the environment variables passed to the spawned runtime process, + /// replacing the inherited environment. + /// + /// + /// Cannot be combined with ; setting both throws + /// an when the client is constructed. + /// + public IReadOnlyDictionary? Environment { get; set; } } /// @@ -170,6 +194,19 @@ public sealed class StdioRuntimeConnection : ChildProcessRuntimeConnection internal StdioRuntimeConnection() { } } +/// +/// Hosts the runtime in-process by loading its native library and communicating +/// over the C ABI (FFI). Construct via . +/// Works across the SDK's target frameworks (modern .NET and netstandard2.0). +/// To point at a non-default runtime entrypoint, set the COPILOT_CLI_PATH +/// environment variable. +/// +[Experimental(Diagnostics.Experimental)] +public sealed class InProcessRuntimeConnection : RuntimeConnection +{ + internal InProcessRuntimeConnection() { } +} + /// /// Spawns a runtime child process listening on a TCP socket. Construct via /// . @@ -281,6 +318,7 @@ private CopilotClientOptions(CopilotClientOptions? other) OnListModels = other.OnListModels; SessionFs = other.SessionFs; RequestHandler = other.RequestHandler; + OnGitHubTelemetry = other.OnGitHubTelemetry; SessionIdleTimeoutSeconds = other.SessionIdleTimeoutSeconds; EnableRemoteSessions = other.EnableRemoteSessions; Mode = other.Mode; @@ -330,7 +368,15 @@ private CopilotClientOptions(CopilotClientOptions? other) /// public CopilotLogLevel? LogLevel { get; set; } - /// Environment variables to pass to the runtime process. + /// + /// Gets or sets environment variables passed to the runtime process. + /// + /// + /// Not supported with the in-process transport (), + /// which runs the runtime in the host process; setting this option there throws an + /// . For child-process transports, prefer + /// ; setting both throws. + /// public IReadOnlyDictionary? Environment { get; set; } /// Logger instance for SDK diagnostic output. @@ -378,6 +424,15 @@ private CopilotClientOptions(CopilotClientOptions? other) [Experimental(Diagnostics.Experimental)] public CopilotRequestHandler? RequestHandler { get; set; } + /// + /// Experimental. Receives GitHub telemetry events the runtime forwards to this + /// connection; setting a handler opts created/resumed sessions into forwarding. + /// The SDK awaits the handler task so it may perform asynchronous work. + /// + [Experimental(Diagnostics.Experimental)] + [EditorBrowsable(EditorBrowsableState.Never)] + public Func? OnGitHubTelemetry { get; set; } + /// /// OpenTelemetry configuration for the runtime. /// When set to a non- instance, the runtime is started with OpenTelemetry instrumentation enabled. @@ -642,6 +697,12 @@ public sealed class ToolResultObject [JsonPropertyName("toolTelemetry")] public IDictionary? ToolTelemetry { get; set; } + /// + /// Names of tools returned by a tool-search tool. + /// + [JsonPropertyName("toolReferences")] + public IList? ToolReferences { get; set; } + /// /// Converts the result of an invocation into a /// . Handles , @@ -753,6 +814,14 @@ public sealed class ToolInvocation /// Arguments passed to the tool by the language model. /// public JsonElement? Arguments { get; set; } + /// + /// Snapshot of the session's currently initialized tools. The SDK populates + /// this only when the invocation targets the built-in tool-search tool + /// (tool_search_tool), so a tool-search override can rank/filter the + /// live catalog — including MCP tools configured in settings — without + /// issuing its own RPC. null for every other tool invocation. + /// + public IList? AvailableTools { get; set; } } /// @@ -1128,6 +1197,72 @@ public sealed class ElicitationContext public string? Url { get; set; } } +/// +/// Context for an MCP OAuth request callback. +/// +[Experimental(Diagnostics.Experimental)] +public sealed class McpAuthContext +{ + /// Identifier of the session that triggered the MCP OAuth request. + public string SessionId { get; set; } = string.Empty; + + /// Identifier of the pending MCP OAuth request. + public string RequestId { get; set; } = string.Empty; + + /// Display name of the MCP server that requires OAuth. + public string ServerName { get; set; } = string.Empty; + + /// URL of the MCP server that requires OAuth. + public string ServerUrl { get; set; } = string.Empty; + + /// Why the runtime is requesting host-provided OAuth credentials. + public McpOauthRequestReason Reason { get; set; } + + /// Parsed WWW-Authenticate parameters from the MCP server, if available. + public McpOauthWWWAuthenticateParams? WwwAuthenticateParams { get; set; } + + /// Raw RFC 9728 protected-resource metadata JSON fetched by the runtime, if available. + public string? ResourceMetadata { get; set; } + + /// Static OAuth client configuration, if the server specifies one. + public McpOauthRequiredStaticClientConfig? StaticClientConfig { get; set; } +} + +/// +/// Host-provided OAuth token data for a pending MCP OAuth request. +/// +[Experimental(Diagnostics.Experimental)] +public sealed class McpAuthToken +{ + /// Access token acquired by the SDK host. + public required string AccessToken { get; set; } + + /// OAuth token type. Defaults to Bearer when omitted. + public string? TokenType { get; set; } + + /// Token lifetime in seconds, if known. + public long? ExpiresIn { get; set; } +} + +/// +/// Result returned by an MCP auth request handler. +/// +[Experimental(Diagnostics.Experimental)] +public sealed class McpAuthResult +{ + /// Whether the request should be cancelled instead of resolved with a token. + public bool Cancelled { get; set; } + + /// Host-provided token data. Ignored when is true. + public McpAuthToken? Token { get; set; } + + /// Create a token result. + public static McpAuthResult FromToken(McpAuthToken token) => new() { Token = token }; + + /// Create a cancellation result. + public static McpAuthResult Cancel() => new() { Cancelled = true }; +} + // ============================================================================ // Session Capabilities // ============================================================================ @@ -2522,6 +2657,14 @@ public sealed class CustomAgentConfig /// [JsonPropertyName("model")] public string? Model { get; set; } + + /// + /// Reasoning effort level for this agent's model. + /// When omitted, no per-agent override is sent and the backend chooses its + /// default. The parent session effort is not inherited. + /// + [JsonPropertyName("reasoningEffort")] + public string? ReasoningEffort { get; set; } } /// @@ -2600,6 +2743,30 @@ public sealed class LargeToolOutputConfig public string? OutputDirectory { get; set; } } +/// +/// Overrides the runtime's built-in tool-search behavior. +/// Defers tools to keep the model's active tool set small. +/// To override the tool-search tool's implementation, register a tool +/// named "tool_search_tool" with OverridesBuiltInTool set to +/// . +/// +public sealed class ToolSearchConfig +{ + /// + /// Enable or disable tool search. + /// + [JsonPropertyName("enabled")] + public bool? Enabled { get; set; } + + /// + /// The tool count above which MCP and external tools are deferred behind + /// tool search. When , the runtime default (30) + /// applies. + /// + [JsonPropertyName("deferThreshold")] + public int? DeferThreshold { get; set; } +} + /// /// Configuration for session memory. /// @@ -2692,6 +2859,7 @@ protected SessionConfigBase(SessionConfigBase? other) DefaultAgent = other.DefaultAgent; Agent = other.Agent; DisabledSkills = other.DisabledSkills is not null ? [.. other.DisabledSkills] : null; + EnableCitations = other.EnableCitations; EnableConfigDiscovery = other.EnableConfigDiscovery; SkipEmbeddingRetrieval = other.SkipEmbeddingRetrieval; EmbeddingCacheStorage = other.EmbeddingCacheStorage; @@ -2702,10 +2870,12 @@ protected SessionConfigBase(SessionConfigBase? other) EnableSessionStore = other.EnableSessionStore; EnableSkills = other.EnableSkills; EnableMcpApps = other.EnableMcpApps; + ExcludedBuiltInAgents = other.ExcludedBuiltInAgents is not null ? [.. other.ExcludedBuiltInAgents] : null; ExcludedTools = other.ExcludedTools is not null ? [.. other.ExcludedTools] : null; Hooks = other.Hooks; InfiniteSessions = other.InfiniteSessions; LargeOutput = other.LargeOutput; + ToolSearch = other.ToolSearch; Memory = other.Memory; McpServers = other.McpServers is not null ? (other.McpServers is Dictionary dict @@ -2719,6 +2889,7 @@ protected SessionConfigBase(SessionConfigBase? other) OnElicitationRequest = other.OnElicitationRequest; OnEvent = other.OnEvent; OnExitPlanModeRequest = other.OnExitPlanModeRequest; + OnMcpAuthRequest = other.OnMcpAuthRequest; OnPermissionRequest = other.OnPermissionRequest; OnUserInputRequest = other.OnUserInputRequest; Provider = other.Provider; @@ -2737,17 +2908,20 @@ protected SessionConfigBase(SessionConfigBase? other) GitHubToken = other.GitHubToken; RemoteSession = other.RemoteSession; ExpAssignments = other.ExpAssignments; + EnableManagedSettings = other.EnableManagedSettings; #pragma warning disable GHCP001 Canvases = other.Canvases is not null ? [.. other.Canvases] : null; RequestCanvasRenderer = other.RequestCanvasRenderer; RequestExtensions = other.RequestExtensions; ExtensionSdkPath = other.ExtensionSdkPath; ExtensionInfo = other.ExtensionInfo; + CanvasProvider = other.CanvasProvider; CanvasHandler = other.CanvasHandler; #pragma warning restore GHCP001 SkillDirectories = other.SkillDirectories is not null ? [.. other.SkillDirectories] : null; PluginDirectories = other.PluginDirectories is not null ? [.. other.PluginDirectories] : null; InstructionDirectories = other.InstructionDirectories is not null ? [.. other.InstructionDirectories] : null; + SessionLimits = other.SessionLimits; Streaming = other.Streaming; IncludeSubAgentStreamingEvents = other.IncludeSubAgentStreamingEvents; SystemMessage = other.SystemMessage; @@ -2786,6 +2960,16 @@ protected SessionConfigBase(SessionConfigBase? other) /// Per-property overrides for model capabilities, deep-merged over runtime defaults. public ModelCapabilitiesOverride? ModelCapabilities { get; set; } + /// + /// Enables native model citations for models that support them. + /// + /// + /// Citations are experimental, off by default, and currently available for Anthropic models. + /// This option may change or be removed while citation support is experimental. + /// + [Experimental(Diagnostics.Experimental)] + public bool? EnableCitations { get; set; } + /// /// Override the default configuration directory location. /// When specified, the session will use this directory for storing config and state. @@ -2878,6 +3062,16 @@ protected SessionConfigBase(SessionConfigBase? other) /// List of tool names to exclude from the session. public IList? ExcludedTools { get; set; } + /// + /// Built-in subagent names to exclude from this session. + /// + /// + /// Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a + /// custom agent with the same name is available. + /// + [JsonPropertyName("excludedBuiltinAgents")] + public IList? ExcludedBuiltInAgents { get; set; } + /// Custom model provider configuration for the session. public ProviderConfig? Provider { get; set; } @@ -3070,6 +3264,16 @@ protected SessionConfigBase(SessionConfigBase? other) /// public InfiniteSessionConfig? InfiniteSessions { get; set; } + /// + /// Optional limits for the session's current accounting window. + /// + /// + /// These settings only model the caller's configured limits. Enforcement and + /// limit-exhaustion behavior are handled by the runtime. + /// + [Experimental(Diagnostics.Experimental)] + public SessionLimitsConfig? SessionLimits { get; set; } + /// /// Configuration for handling large tool outputs. When a tool produces /// output exceeding the configured size, the output is written to a temp @@ -3078,6 +3282,13 @@ protected SessionConfigBase(SessionConfigBase? other) /// public LargeToolOutputConfig? LargeOutput { get; set; } + /// + /// Overrides the runtime's built-in tool-search behavior. + /// Tool search defers tools to keep the model's active tool set small. When , + /// the runtime default applies. + /// + public ToolSearchConfig? ToolSearch { get; set; } + /// /// Configuration for session memory. When set, controls whether the /// session can read and write persistent memory. @@ -3130,6 +3341,16 @@ protected SessionConfigBase(SessionConfigBase? other) [EditorBrowsable(EditorBrowsableState.Never)] public JsonElement? ExpAssignments { get; set; } + /// + /// Opt-in: when true, the runtime self-fetches enterprise managed + /// settings (bypass-permissions policy) at session bootstrap using the + /// session's . Requires to + /// be set; if omitted, the runtime is expected to reject session creation + /// (fail-closed). When unset, behaves exactly as before. Serialized on the + /// wire as enableManagedSettings. + /// + public bool? EnableManagedSettings { get; set; } + #pragma warning disable GHCP001 /// /// Canvas declarations advertised by this connection. The runtime forwards @@ -3171,6 +3392,16 @@ protected SessionConfigBase(SessionConfigBase? other) [Experimental(Diagnostics.Experimental)] public ExtensionInfo? ExtensionInfo { get; set; } + /// + /// Stable identity for a host/SDK connection that supplies built-in + /// canvases. When set, the runtime uses + /// verbatim as the agent-facing canvas extension id, so canvases declared on + /// a control connection survive reconnect and CLI restart. Honored on + /// session create and resume. + /// + [Experimental(Diagnostics.Experimental)] + public CanvasProviderIdentity? CanvasProvider { get; set; } + /// /// Provider-side canvas lifecycle handler. The SDK routes inbound /// canvas.open / canvas.close / canvas.action.invoke @@ -3180,6 +3411,14 @@ protected SessionConfigBase(SessionConfigBase? other) [JsonIgnore] public ICanvasHandler? CanvasHandler { get; set; } #pragma warning restore GHCP001 + + /// + /// Optional handler for MCP OAuth requests from MCP servers. + /// When provided, the SDK can satisfy MCP server OAuth requests with host-provided token data or cancellation. + /// + [Experimental(Diagnostics.Experimental)] + [JsonIgnore] + public Func>? OnMcpAuthRequest { get; set; } } /// @@ -3847,5 +4086,6 @@ public sealed class SystemMessageTransformRpcResponse [JsonSerializable(typeof(CanvasProviderOpenResult))] [JsonSerializable(typeof(CanvasHostContext))] [JsonSerializable(typeof(ExtensionInfo))] +[JsonSerializable(typeof(CanvasProviderIdentity))] #pragma warning restore GHCP001 internal partial class TypesJsonContext : JsonSerializerContext; diff --git a/dotnet/src/UnixMillisecondsDateTimeOffsetConverter.cs b/dotnet/src/UnixMillisecondsDateTimeOffsetConverter.cs index 4b8fcc3616..8e176fbafa 100644 --- a/dotnet/src/UnixMillisecondsDateTimeOffsetConverter.cs +++ b/dotnet/src/UnixMillisecondsDateTimeOffsetConverter.cs @@ -13,8 +13,14 @@ namespace GitHub.Copilot; public sealed class UnixMillisecondsDateTimeOffsetConverter : JsonConverter { /// - public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => - DateTimeOffset.FromUnixTimeMilliseconds(reader.GetInt64()); + public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + // The CLI may serialize the epoch-millisecond timestamp as a JSON integer + // or as a floating-point number (e.g. 1700000000000.0). GetInt64 throws on a + // fractional token, so fall back to reading a double and truncating. + long milliseconds = reader.TryGetInt64(out long value) ? value : (long)reader.GetDouble(); + return DateTimeOffset.FromUnixTimeMilliseconds(milliseconds); + } /// public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) => diff --git a/dotnet/src/build/GitHub.Copilot.SDK.targets b/dotnet/src/build/GitHub.Copilot.SDK.targets index 94b6515ea7..5f7944b2c4 100644 --- a/dotnet/src/build/GitHub.Copilot.SDK.targets +++ b/dotnet/src/build/GitHub.Copilot.SDK.targets @@ -9,6 +9,7 @@ <_CopilotOs Condition="'$(RuntimeIdentifier)' != '' And $(RuntimeIdentifier.StartsWith('win'))">win <_CopilotOs Condition="'$(_CopilotOs)' == '' And '$(RuntimeIdentifier)' != '' And $(RuntimeIdentifier.StartsWith('osx'))">osx <_CopilotOs Condition="'$(_CopilotOs)' == '' And '$(RuntimeIdentifier)' != '' And $(RuntimeIdentifier.StartsWith('maccatalyst'))">osx + <_CopilotOs Condition="'$(_CopilotOs)' == '' And '$(RuntimeIdentifier)' != '' And $(RuntimeIdentifier.StartsWith('linux-musl'))">linux-musl <_CopilotOs Condition="'$(_CopilotOs)' == '' And '$(RuntimeIdentifier)' != ''">linux @@ -22,7 +23,7 @@ - + @@ -31,10 +32,19 @@ <_CopilotPlatform Condition="'$(_CopilotRid)' == 'win-arm64'">win32-arm64 <_CopilotPlatform Condition="'$(_CopilotRid)' == 'linux-x64'">linux-x64 <_CopilotPlatform Condition="'$(_CopilotRid)' == 'linux-arm64'">linux-arm64 + <_CopilotPlatform Condition="'$(_CopilotRid)' == 'linux-musl-x64'">linuxmusl-x64 + <_CopilotPlatform Condition="'$(_CopilotRid)' == 'linux-musl-arm64'">linuxmusl-arm64 <_CopilotPlatform Condition="'$(_CopilotRid)' == 'osx-x64'">darwin-x64 <_CopilotPlatform Condition="'$(_CopilotRid)' == 'osx-arm64'">darwin-arm64 <_CopilotBinary Condition="$(_CopilotRid.StartsWith('win-'))">copilot.exe <_CopilotBinary Condition="'$(_CopilotBinary)' == ''">copilot + + <_CopilotRuntimeLib Condition="$(_CopilotRid.StartsWith('win-'))">copilot_runtime.dll + <_CopilotRuntimeLib Condition="$(_CopilotRid.StartsWith('osx-'))">libcopilot_runtime.dylib + <_CopilotRuntimeLib Condition="'$(_CopilotRuntimeLib)' == ''">libcopilot_runtime.so + <_CopilotRuntimeNodePath>$(_CopilotCacheDir)\prebuilds\$(_CopilotPlatform)\runtime.node + + diff --git a/dotnet/test/AssemblyInfo.cs b/dotnet/test/AssemblyInfo.cs index e34f0e255b..6f5f258a91 100644 --- a/dotnet/test/AssemblyInfo.cs +++ b/dotnet/test/AssemblyInfo.cs @@ -3,8 +3,9 @@ *--------------------------------------------------------------------------------------------*/ using Xunit; +using GitHub.Copilot.Test.Harness; -// Each E2E test class fixture spins up its own Copilot CLI subprocess plus a CapiProxy +// Each E2E test class fixture spins up its own Copilot CLI subprocess plus a ReplayProxy // (replaying HTTP proxy) Node.js subprocess. With ~25 test classes, running them in parallel // would launch ~50 long-lived Node.js processes simultaneously and exhaust both file // descriptors and memory on developer machines and CI runners (especially Windows). Tests @@ -13,3 +14,5 @@ // (a) sharing a single CLI subprocess across classes, or (b) gating concurrency with a // semaphore that limits concurrent fixtures to a small number (e.g. 2-3). [assembly: CollectionBehavior(DisableTestParallelization = true)] + +[assembly: InProcessEnvIsolation] diff --git a/dotnet/test/ConnectionTokenTests.cs b/dotnet/test/ConnectionTokenTests.cs index 524ff25861..3192bada6b 100644 --- a/dotnet/test/ConnectionTokenTests.cs +++ b/dotnet/test/ConnectionTokenTests.cs @@ -113,7 +113,7 @@ public class ConnectionTokenAutoGeneratedTests : IAsyncLifetime public async Task InitializeAsync() { _ctx = await E2ETestContext.CreateAsync(); - _client = _ctx.CreateClient(useStdio: false); + _client = _ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForTcp() }); } public async Task DisposeAsync() diff --git a/dotnet/test/E2E/ByokBearerTokenProviderE2ETests.cs b/dotnet/test/E2E/ByokBearerTokenProviderE2ETests.cs index 5973dc61c6..4d2cb5e34d 100644 --- a/dotnet/test/E2E/ByokBearerTokenProviderE2ETests.cs +++ b/dotnet/test/E2E/ByokBearerTokenProviderE2ETests.cs @@ -36,6 +36,7 @@ namespace GitHub.Copilot.Test.E2E; /// and the resulting token reaches that provider's endpoint. /// /// +[Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public class ByokBearerTokenProviderE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "byok_bearer_token_provider", output) { diff --git a/dotnet/test/E2E/ClientE2ETests.cs b/dotnet/test/E2E/ClientE2ETests.cs index 9972e3b336..d166223d65 100644 --- a/dotnet/test/E2E/ClientE2ETests.cs +++ b/dotnet/test/E2E/ClientE2ETests.cs @@ -9,8 +9,10 @@ namespace GitHub.Copilot.Test.E2E; // These tests bypass E2ETestBase because they are about how the CLI subprocess is started // Other test classes should instead inherit from E2ETestBase -public class ClientE2ETests +public class ClientE2ETests(E2ETestFixture fixture) : IClassFixture { + private E2ETestContext Ctx => fixture.Ctx; + [Theory] [InlineData(true)] // stdio transport [InlineData(false)] // TCP transport @@ -33,6 +35,32 @@ public async Task Should_Start_And_Connect_To_Server(bool useStdio) } } + [Fact] + public async Task Should_Start_And_Connect_Over_InProcess_Ffi() + { + // In-process FFI hosting resolves the CLI entrypoint (COPILOT_CLI_PATH or the + // bundled CLI binary) and its sibling native runtime library itself; if neither + // is available, StartAsync throws and the test fails hard. + using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForInProcess(), + }); + + try + { + await client.StartAsync(); + var pong = await client.PingAsync("ffi message"); + Assert.Equal("pong: ffi message", pong.Message); + Assert.NotEqual(default, pong.Timestamp); + + await client.StopAsync(); + } + finally + { + await client.ForceStopAsync(); + } + } + [Theory] [InlineData(true)] // stdio transport [InlineData(false)] // TCP transport @@ -40,7 +68,7 @@ public async Task Should_Force_Stop_Without_Cleanup(bool useStdio) { using var client = new CopilotClient(new CopilotClientOptions { Connection = useStdio ? RuntimeConnection.ForStdio() : RuntimeConnection.ForTcp() }); - await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); + await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); await client.ForceStopAsync(); } @@ -139,7 +167,7 @@ public async Task Should_List_Models_When_Authenticated(bool useStdio) public async Task Should_Not_Throw_When_Disposing_Session_After_Stopping_Client(bool useStdio) { await using var client = new CopilotClient(new CopilotClientOptions { Connection = useStdio ? RuntimeConnection.ForStdio() : RuntimeConnection.ForTcp() }); - await using var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); await client.StopAsync(); } @@ -175,7 +203,7 @@ public async Task Should_Report_Error_With_Stderr_When_CLI_Fails_To_Start(bool u // Verify subsequent calls also fail (don't hang) var ex2 = await Assert.ThrowsAnyAsync(async () => { - var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); await session.SendAsync(new MessageOptions { Prompt = "test" }); }); Assert.True( @@ -193,7 +221,7 @@ public async Task Should_Report_Error_With_Stderr_When_CLI_Fails_To_Start(bool u public async Task Should_Allow_CreateSession_Called_Without_PermissionHandler(bool useStdio) { await using var client = new CopilotClient(new CopilotClientOptions { Connection = useStdio ? RuntimeConnection.ForStdio() : RuntimeConnection.ForTcp() }); - await using var session = await client.CreateSessionAsync(new SessionConfig()); + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig()); Assert.NotNull(session.SessionId); } @@ -208,7 +236,7 @@ public async Task Should_Allow_ResumeSession_Called_Without_PermissionHandler() { Connection = RuntimeConnection.ForTcp(connectionToken: connectionToken), }); - await using var originalSession = await client.CreateSessionAsync(new SessionConfig()); + await using var originalSession = await ctx.CreateSessionAsync(client, new SessionConfig()); var port = client.RuntimePort ?? throw new InvalidOperationException("Client must be using TCP transport to support multi-client resume."); @@ -217,7 +245,7 @@ public async Task Should_Allow_ResumeSession_Called_Without_PermissionHandler() { Connection = RuntimeConnection.ForUri($"localhost:{port}", connectionToken: connectionToken), }); - await using var resumedSession = await resumeClient.ResumeSessionAsync(originalSession.SessionId, new()); + await using var resumedSession = await ctx.ResumeSessionAsync(resumeClient, originalSession.SessionId, new()); Assert.Equal(originalSession.SessionId, resumedSession.SessionId); } diff --git a/dotnet/test/E2E/ClientOptionsE2ETests.cs b/dotnet/test/E2E/ClientOptionsE2ETests.cs index c2f16a042b..bf995563c4 100644 --- a/dotnet/test/E2E/ClientOptionsE2ETests.cs +++ b/dotnet/test/E2E/ClientOptionsE2ETests.cs @@ -7,6 +7,7 @@ using System.Net; using System.Net.Sockets; using System.Text.Json; +using GitHub.Copilot.Test.Harness; using Xunit; using Xunit.Abstractions; @@ -41,7 +42,7 @@ public async Task Should_Use_Client_Cwd_For_Default_WorkingDirectory() WorkingDirectory = clientCwd, }); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -71,7 +72,6 @@ public async Task Should_Propagate_Process_Options_To_Spawned_Cli() { Connection = RuntimeConnection.ForStdio(path: cliPath, args: ["--capture-file", capturePath]), BaseDirectory = copilotHomeFromOption, - Environment = clientEnv, GitHubToken = "process-option-token", LogLevel = CopilotLogLevel.Debug, SessionIdleTimeoutSeconds = 17, @@ -85,7 +85,7 @@ public async Task Should_Propagate_Process_Options_To_Spawned_Cli() CaptureContent = true, }, UseLoggedInUser = false, - }); + }, environment: clientEnv); await client.StartAsync(); @@ -111,7 +111,7 @@ public async Task Should_Propagate_Process_Options_To_Spawned_Cli() Assert.Equal("dotnet-sdk-e2e", capturedEnv.GetProperty("COPILOT_OTEL_SOURCE_NAME").GetString()); Assert.Equal("true", capturedEnv.GetProperty("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT").GetString()); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableConfigDiscovery = true, IncludeSubAgentStreamingEvents = false, @@ -140,7 +140,7 @@ public async Task Should_Forward_EnableSessionTelemetry_In_Wire_Request() await client.StartAsync(); // When explicitly set to false, it should appear in the wire request - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableSessionTelemetry = false, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -167,7 +167,7 @@ public async Task Should_Omit_EnableSessionTelemetry_When_Not_Set() await client.StartAsync(); // When omitted (null/default), the field should not be present in the wire request - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -192,7 +192,7 @@ public async Task Should_Forward_Granular_Multitenancy_Fields_In_Create_Wire_Req await client.StartAsync(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { SkipEmbeddingRetrieval = false, OrganizationCustomInstructions = "Follow org policy.", @@ -219,6 +219,207 @@ public async Task Should_Forward_Granular_Multitenancy_Fields_In_Create_Wire_Req await session.DisposeAsync(); } + [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] + public async Task Should_Forward_Advanced_Session_Options_In_Create_Wire_Request() + { + var (cliPath, capturePath) = await CreateFakeCliCaptureAsync(); + var outputDirectory = Path.Join(Ctx.WorkDir, "large-output-create"); + + await using var client = Ctx.CreateClient(options: new CopilotClientOptions + { + Connection = RuntimeConnection.ForStdio(path: cliPath, args: ["--capture-file", capturePath]), + UseLoggedInUser = false, + }); + + await client.StartAsync(); + + var session = await Ctx.CreateSessionAsync(client, new SessionConfig + { + ClientName = "advanced-create-client", + Model = "claude-sonnet-4.5", + ReasoningEffort = "medium", + ReasoningSummary = ReasoningSummary.Detailed, + ContextTier = ContextTier.LongContext, + EnableCitations = true, + Capi = new CapiSessionOptions { EnableWebSocketResponses = false }, + McpOAuthTokenStorage = McpOAuthTokenStorageMode.Persistent, + CustomAgents = + [ + new CustomAgentConfig + { + Name = "agent-one", + DisplayName = "Agent One", + Description = "Handles agent-one tasks.", + Prompt = "Be agent one.", + Tools = ["view"], + Infer = true, + Skills = ["create-skill"], + Model = "claude-haiku-4.5", + }, + ], + DefaultAgent = new DefaultAgentConfig { ExcludedTools = ["edit"] }, + Agent = "agent-one", + SkillDirectories = ["skills-create"], + DisabledSkills = ["disabled-create-skill"], + PluginDirectories = ["plugins-create"], + InfiniteSessions = new InfiniteSessionConfig + { + Enabled = false, + BackgroundCompactionThreshold = 0.5, + BufferExhaustionThreshold = 0.9, + }, + LargeOutput = new LargeToolOutputConfig + { + Enabled = true, + MaxSizeBytes = 4096, + OutputDirectory = outputDirectory, + }, + Memory = new MemoryConfiguration { Enabled = true }, + GitHubToken = "session-create-token", + RemoteSession = GitHub.Copilot.Rpc.RemoteSessionMode.Export, + Cloud = new CloudSessionOptions + { + Repository = new CloudSessionRepository + { + Owner = "github", + Name = "copilot-sdk", + Branch = "main", + }, + }, + EnableMcpApps = true, + RequestCanvasRenderer = true, + RequestExtensions = true, + ExtensionSdkPath = "custom-extension-sdk", + ExtensionInfo = new ExtensionInfo { Source = "dotnet-sdk-tests", Name = "advanced-create-extension" }, + Canvases = + [ + new CanvasDeclaration + { + Id = "advanced-create-canvas", + DisplayName = "Advanced Create Canvas", + Description = "Covers create-time canvas options.", + }, + ], + Providers = + [ + new NamedProviderConfig + { + Name = "create-provider", + Type = "openai", + WireApi = "responses", + BaseUrl = "https://create-provider.example.test/v1", + ApiKey = "create-provider-key", + Headers = new Dictionary { ["X-Create-Provider"] = "yes" }, + }, + ], + Models = + [ + new ProviderModelConfig + { + Provider = "create-provider", + Id = "create-model", + Name = "Create Model", + ModelId = "claude-sonnet-4.5", + WireModel = "create-wire-model", + MaxContextWindowTokens = 12_000, + MaxPromptTokens = 10_000, + MaxOutputTokens = 2_000, + }, + ], + OnPermissionRequest = PermissionHandler.ApproveAll, + }); + + using var capture = JsonDocument.Parse(await File.ReadAllTextAsync(capturePath)); + var createRequest = GetCapturedRequestParams(capture.RootElement, "session.create"); + Assert.Equal("advanced-create-client", createRequest.GetProperty("clientName").GetString()); + Assert.Equal("claude-sonnet-4.5", createRequest.GetProperty("model").GetString()); + Assert.Equal("medium", createRequest.GetProperty("reasoningEffort").GetString()); + Assert.Equal("detailed", createRequest.GetProperty("reasoningSummary").GetString()); + Assert.Equal("long_context", createRequest.GetProperty("contextTier").GetString()); + Assert.True(createRequest.GetProperty("enableCitations").GetBoolean()); + Assert.False(createRequest.GetProperty("capi").GetProperty("enableWebSocketResponses").GetBoolean()); + Assert.Equal("persistent", createRequest.GetProperty("mcpOAuthTokenStorage").GetString()); + Assert.Equal("agent-one", createRequest.GetProperty("agent").GetString()); + Assert.Equal("edit", createRequest.GetProperty("defaultAgent").GetProperty("excludedTools")[0].GetString()); + Assert.Equal("agent-one", createRequest.GetProperty("customAgents")[0].GetProperty("name").GetString()); + Assert.Equal("plugins-create", createRequest.GetProperty("pluginDirectories")[0].GetString()); + Assert.Equal("disabled-create-skill", createRequest.GetProperty("disabledSkills")[0].GetString()); + Assert.False(createRequest.GetProperty("infiniteSessions").GetProperty("enabled").GetBoolean()); + Assert.True(createRequest.GetProperty("largeOutput").GetProperty("enabled").GetBoolean()); + Assert.Equal(4096, createRequest.GetProperty("largeOutput").GetProperty("maxSizeBytes").GetInt64()); + Assert.Equal(outputDirectory, createRequest.GetProperty("largeOutput").GetProperty("outputDir").GetString()); + Assert.True(createRequest.GetProperty("memory").GetProperty("enabled").GetBoolean()); + Assert.Equal("session-create-token", createRequest.GetProperty("gitHubToken").GetString()); + Assert.Equal("export", createRequest.GetProperty("remoteSession").GetString()); + Assert.Equal("github", createRequest.GetProperty("cloud").GetProperty("repository").GetProperty("owner").GetString()); + Assert.True(createRequest.GetProperty("requestMcpApps").GetBoolean()); + Assert.True(createRequest.GetProperty("requestCanvasRenderer").GetBoolean()); + Assert.True(createRequest.GetProperty("requestExtensions").GetBoolean()); + Assert.Equal("custom-extension-sdk", createRequest.GetProperty("extensionSdkPath").GetString()); + Assert.Equal("advanced-create-extension", createRequest.GetProperty("extensionInfo").GetProperty("name").GetString()); + Assert.Equal("advanced-create-canvas", createRequest.GetProperty("canvases")[0].GetProperty("id").GetString()); + Assert.Equal("create-provider", createRequest.GetProperty("providers")[0].GetProperty("name").GetString()); + Assert.Equal("responses", createRequest.GetProperty("providers")[0].GetProperty("wireApi").GetString()); + Assert.Equal("create-model", createRequest.GetProperty("models")[0].GetProperty("id").GetString()); + Assert.Equal(12000, createRequest.GetProperty("models")[0].GetProperty("maxContextWindowTokens").GetInt32()); + + await session.DisposeAsync(); + } + + [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] + public async Task Should_Forward_Singular_Provider_Options_In_Create_Wire_Request() + { + var (cliPath, capturePath) = await CreateFakeCliCaptureAsync(); + + await using var client = Ctx.CreateClient(options: new CopilotClientOptions + { + Connection = RuntimeConnection.ForStdio(path: cliPath, args: ["--capture-file", capturePath]), + UseLoggedInUser = false, + }); + + await client.StartAsync(); + + var session = await Ctx.CreateSessionAsync(client, new SessionConfig + { + Model = "claude-sonnet-4.5", + Provider = new ProviderConfig + { + Type = "azure", + WireApi = "responses", + Transport = "http", + BaseUrl = "https://azure-provider.example.test/openai", + ApiKey = "provider-api-key", + BearerToken = "provider-bearer-token", + Azure = new AzureOptions { ApiVersion = "2024-02-15-preview" }, + Headers = new Dictionary { ["X-Provider-Wire"] = "yes" }, + ModelId = "claude-sonnet-4.5", + WireModel = "azure-deployment", + MaxPromptTokens = 8192, + MaxOutputTokens = 1024, + }, + OnPermissionRequest = PermissionHandler.ApproveAll, + }); + + using var capture = JsonDocument.Parse(await File.ReadAllTextAsync(capturePath)); + var provider = GetCapturedRequestParams(capture.RootElement, "session.create").GetProperty("provider"); + Assert.Equal("azure", provider.GetProperty("type").GetString()); + Assert.Equal("responses", provider.GetProperty("wireApi").GetString()); + Assert.Equal("http", provider.GetProperty("transport").GetString()); + Assert.Equal("https://azure-provider.example.test/openai", provider.GetProperty("baseUrl").GetString()); + Assert.Equal("provider-api-key", provider.GetProperty("apiKey").GetString()); + Assert.Equal("provider-bearer-token", provider.GetProperty("bearerToken").GetString()); + Assert.Equal("2024-02-15-preview", provider.GetProperty("azure").GetProperty("apiVersion").GetString()); + Assert.Equal("yes", provider.GetProperty("headers").GetProperty("X-Provider-Wire").GetString()); + Assert.Equal("claude-sonnet-4.5", provider.GetProperty("modelId").GetString()); + Assert.Equal("azure-deployment", provider.GetProperty("wireModel").GetString()); + Assert.Equal(8192, provider.GetProperty("maxPromptTokens").GetInt32()); + Assert.Equal(1024, provider.GetProperty("maxOutputTokens").GetInt32()); + + await session.DisposeAsync(); + } + [Fact] public async Task Should_Apply_Empty_Mode_Defaults_To_CreateSession_Wire_Request() { @@ -234,7 +435,7 @@ public async Task Should_Apply_Empty_Mode_Defaults_To_CreateSession_Wire_Request await client.StartAsync(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn(BuiltInTools.Isolated), @@ -273,7 +474,7 @@ public async Task Should_Propagate_Activity_TraceContext_To_Session_Create_And_S activity.TraceStateString = "vendor=create-send"; activity.Start(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -357,7 +558,7 @@ public async Task Should_Propagate_Activity_TraceContext_To_Session_Resume() activity.TraceStateString = "vendor=resume"; activity.Start(); - var session = await client.ResumeSessionAsync("trace-resume-session", new ResumeSessionConfig + var session = await Ctx.ResumeSessionAsync(client, "trace-resume-session", new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -384,7 +585,7 @@ public async Task Should_Forward_Granular_Multitenancy_Fields_In_Resume_Wire_Req await client.StartAsync(); - var session = await client.ResumeSessionAsync("resume-session", new ResumeSessionConfig + var session = await Ctx.ResumeSessionAsync(client, "resume-session", new ResumeSessionConfig { SkipEmbeddingRetrieval = false, OrganizationCustomInstructions = "Resume org policy.", @@ -411,6 +612,88 @@ public async Task Should_Forward_Granular_Multitenancy_Fields_In_Resume_Wire_Req await session.DisposeAsync(); } + [Fact] + public async Task Should_Forward_Advanced_Session_Options_In_Resume_Wire_Request() + { + var (cliPath, capturePath) = await CreateFakeCliCaptureAsync(); + var outputDirectory = Path.Join(Ctx.WorkDir, "large-output-resume"); + using var canvasInput = JsonDocument.Parse("{\"start\":41}"); + + await using var client = Ctx.CreateClient(options: new CopilotClientOptions + { + Connection = RuntimeConnection.ForStdio(path: cliPath, args: ["--capture-file", capturePath]), + UseLoggedInUser = false, + }); + + await client.StartAsync(); + + var session = await Ctx.ResumeSessionAsync(client, "advanced-resume-session", new ResumeSessionConfig + { + ClientName = "advanced-resume-client", + Model = "claude-haiku-4.5", + ReasoningEffort = "low", + ReasoningSummary = ReasoningSummary.None, + ContextTier = ContextTier.Default, + SuppressResumeEvent = true, + ContinuePendingWork = true, + McpOAuthTokenStorage = McpOAuthTokenStorageMode.Persistent, + PluginDirectories = ["plugins-resume"], + LargeOutput = new LargeToolOutputConfig + { + Enabled = false, + MaxSizeBytes = 2048, + OutputDirectory = outputDirectory, + }, + Memory = new MemoryConfiguration { Enabled = false }, + RemoteSession = GitHub.Copilot.Rpc.RemoteSessionMode.On, + OpenCanvases = + [ + new GitHub.Copilot.Rpc.OpenCanvasInstance + { + CanvasId = "resume-canvas", + ExtensionId = "dotnet-sdk-tests/resume-extension", + ExtensionName = "Resume Extension", + InstanceId = "resume-canvas-1", + Input = canvasInput.RootElement.Clone(), + Status = "ready", + Title = "Resume Canvas", + Url = "https://example.com/resume-canvas", + }, + ], + OnPermissionRequest = PermissionHandler.ApproveAll, + }); + + using var capture = JsonDocument.Parse(await File.ReadAllTextAsync(capturePath)); + var resumeRequest = GetCapturedRequestParams(capture.RootElement, "session.resume"); + Assert.Equal("advanced-resume-session", resumeRequest.GetProperty("sessionId").GetString()); + Assert.Equal("advanced-resume-client", resumeRequest.GetProperty("clientName").GetString()); + Assert.Equal("claude-haiku-4.5", resumeRequest.GetProperty("model").GetString()); + Assert.Equal("low", resumeRequest.GetProperty("reasoningEffort").GetString()); + Assert.Equal("none", resumeRequest.GetProperty("reasoningSummary").GetString()); + Assert.Equal("default", resumeRequest.GetProperty("contextTier").GetString()); + Assert.True(resumeRequest.GetProperty("disableResume").GetBoolean()); + Assert.True(resumeRequest.GetProperty("continuePendingWork").GetBoolean()); + Assert.Equal("persistent", resumeRequest.GetProperty("mcpOAuthTokenStorage").GetString()); + Assert.Equal("plugins-resume", resumeRequest.GetProperty("pluginDirectories")[0].GetString()); + Assert.False(resumeRequest.GetProperty("largeOutput").GetProperty("enabled").GetBoolean()); + Assert.Equal(2048, resumeRequest.GetProperty("largeOutput").GetProperty("maxSizeBytes").GetInt64()); + Assert.Equal(outputDirectory, resumeRequest.GetProperty("largeOutput").GetProperty("outputDir").GetString()); + Assert.False(resumeRequest.GetProperty("memory").GetProperty("enabled").GetBoolean()); + Assert.Equal("on", resumeRequest.GetProperty("remoteSession").GetString()); + + var openCanvas = resumeRequest.GetProperty("openCanvases")[0]; + Assert.Equal("resume-canvas", openCanvas.GetProperty("canvasId").GetString()); + Assert.Equal("dotnet-sdk-tests/resume-extension", openCanvas.GetProperty("extensionId").GetString()); + Assert.Equal("Resume Extension", openCanvas.GetProperty("extensionName").GetString()); + Assert.Equal("resume-canvas-1", openCanvas.GetProperty("instanceId").GetString()); + Assert.Equal(41, openCanvas.GetProperty("input").GetProperty("start").GetInt32()); + Assert.Equal("ready", openCanvas.GetProperty("status").GetString()); + Assert.Equal("Resume Canvas", openCanvas.GetProperty("title").GetString()); + Assert.Equal("https://example.com/resume-canvas", openCanvas.GetProperty("url").GetString()); + + await session.DisposeAsync(); + } + [Fact] public async Task Should_Apply_Empty_Mode_Defaults_To_ResumeSession_Wire_Request() { @@ -426,7 +709,7 @@ public async Task Should_Apply_Empty_Mode_Defaults_To_ResumeSession_Wire_Request await client.StartAsync(); - var session = await client.ResumeSessionAsync("resume-empty-session", new ResumeSessionConfig + var session = await Ctx.ResumeSessionAsync(client, "resume-empty-session", new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn(BuiltInTools.Isolated), diff --git a/dotnet/test/E2E/CopilotRequestCancelErrorE2ETests.cs b/dotnet/test/E2E/CopilotRequestCancelErrorE2ETests.cs index 99e9e2546e..a9b645d2ac 100644 --- a/dotnet/test/E2E/CopilotRequestCancelErrorE2ETests.cs +++ b/dotnet/test/E2E/CopilotRequestCancelErrorE2ETests.cs @@ -54,7 +54,7 @@ public async Task Reports_A_Thrown_Callback_Error_Instead_Of_Hanging() await using var client = CreateClientWith(handler); await client.StartAsync(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -81,7 +81,7 @@ public async Task Observes_Runtime_Cancellation_Of_An_In_Flight_Inference_Reques await using var client = CreateClientWith(handler); await client.StartAsync(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); diff --git a/dotnet/test/E2E/CopilotRequestE2EProvider.cs b/dotnet/test/E2E/CopilotRequestE2EProvider.cs index e92df5fae4..89826b4f84 100644 --- a/dotnet/test/E2E/CopilotRequestE2EProvider.cs +++ b/dotnet/test/E2E/CopilotRequestE2EProvider.cs @@ -49,8 +49,6 @@ internal sealed class RecordingRequestHandler : CopilotRequestHandler protected override async Task SendRequestAsync(HttpRequestMessage request, CopilotRequestContext ctx) { var url = request.RequestUri!.ToString(); - _records.Enqueue(new InterceptedRequest(url, ctx.SessionId)); - var bodyText = request.Content is null ? string.Empty #if NET8_0_OR_GREATER @@ -58,6 +56,13 @@ protected override async Task SendRequestAsync(HttpRequestM #else : await request.Content.ReadAsStringAsync().ConfigureAwait(false); #endif + _records.Enqueue(new InterceptedRequest( + url, + ctx.SessionId, + ctx.AgentId, + ctx.ParentAgentId, + ctx.InteractionType, + bodyText)); return IsInferenceUrl(url) ? BuildInferenceResponse(url, bodyText) @@ -95,6 +100,13 @@ private static HttpResponseMessage BuildInferenceResponse(string url, string bod return Sse(string.Concat(ChatCompletionStreamEvents)); } + if (u.EndsWith("/messages", StringComparison.Ordinal)) + { + return wantsStream + ? Sse(string.Concat(AnthropicStreamEvents)) + : Json(BufferedAnthropicMessageJson); + } + // /chat/completions non-streaming (and any other inference url) — buffered JSON. return Json(BufferedChatCompletionJson); } @@ -154,15 +166,38 @@ internal static HttpResponseMessage BuildNonInferenceResponse(string url) "data: [DONE]\n\n", ]; + // Anthropic Messages streaming (SSE) sequence. Emitted when the runtime issues a + // streaming /messages request (stream: true); the buffered JSON below is only valid + // for non-streaming requests, and returning it for a streaming request makes the + // runtime's Anthropic client fail with "stream ended without producing a Message". + private static readonly string[] AnthropicStreamEvents = + [ + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_stub_1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4.5\",\"content\":[],\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\n\n", + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n", + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"" + SyntheticText + "\"}}\n\n", + "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n", + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":7}}\n\n", + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ]; + private static readonly string BufferedResponseJson = "{\"id\":\"resp_stub_1\",\"object\":\"response\",\"status\":\"completed\",\"output\":[{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"" + SyntheticText + "\"}]}],\"usage\":{\"input_tokens\":5,\"output_tokens\":7,\"total_tokens\":12}}"; private static readonly string BufferedChatCompletionJson = "{\"id\":\"chatcmpl-stub-1\",\"object\":\"chat.completion\",\"created\":1,\"model\":\"claude-sonnet-4.5\",\"choices\":[{\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\"" + SyntheticText + "\"},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":7,\"total_tokens\":12}}"; + private static readonly string BufferedAnthropicMessageJson = + "{\"id\":\"msg_stub_1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4.5\",\"content\":[{\"type\":\"text\",\"text\":\"" + SyntheticText + "\"}],\"stop_reason\":\"end_turn\",\"stop_sequence\":null,\"usage\":{\"input_tokens\":5,\"output_tokens\":7}}"; + private const string ModelCatalogJson = "{\"data\":[{\"id\":\"claude-sonnet-4.5\",\"name\":\"Claude Sonnet 4.5\",\"object\":\"model\",\"vendor\":\"Anthropic\",\"version\":\"1\",\"preview\":false,\"model_picker_enabled\":true,\"capabilities\":{\"type\":\"chat\",\"family\":\"claude-sonnet-4.5\",\"tokenizer\":\"o200k_base\",\"limits\":{\"max_context_window_tokens\":200000,\"max_output_tokens\":8192},\"supports\":{\"streaming\":true,\"tool_calls\":true,\"parallel_tool_calls\":true,\"vision\":true}}}]}"; } /// A single request the callback intercepted. -internal sealed record InterceptedRequest(string Url, string? SessionId); +internal sealed record InterceptedRequest( + string Url, + string? SessionId, + string? AgentId, + string? ParentAgentId, + string? InteractionType, + string Body); diff --git a/dotnet/test/E2E/CopilotRequestSessionIdE2ETests.cs b/dotnet/test/E2E/CopilotRequestSessionIdE2ETests.cs index e09c72c46e..fd00cc9b99 100644 --- a/dotnet/test/E2E/CopilotRequestSessionIdE2ETests.cs +++ b/dotnet/test/E2E/CopilotRequestSessionIdE2ETests.cs @@ -28,13 +28,14 @@ private CopilotClient CreateClientWith(RecordingRequestHandler provider) => }); [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Threads_The_Session_Id_Into_A_Capi_Session_Inference_Request() { var provider = new RecordingRequestHandler(); await using var client = CreateClientWith(provider); await client.StartAsync(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -53,20 +54,25 @@ public async Task Threads_The_Session_Id_Into_A_Capi_Session_Inference_Request() var inference = provider.InferenceRequests; Assert.NotEmpty(inference); - Assert.All(inference, r => Assert.Equal(capiSessionId, r.SessionId)); + Assert.All(inference, r => + { + Assert.Equal(capiSessionId, r.SessionId); + AssertAgentMetadata(r); + }); // Validate the final assistant response arrived (guards against truncated captures) Assert.Contains("OK from the synthetic", content); } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Threads_The_Session_Id_Into_A_Byok_Session_Inference_Request() { var provider = new RecordingRequestHandler(); await using var client = CreateClientWith(provider); await client.StartAsync(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, // BYOK providers require an explicit model id. @@ -96,9 +102,19 @@ public async Task Threads_The_Session_Id_Into_A_Byok_Session_Inference_Request() var inference = provider.InferenceRequests; Assert.NotEmpty(inference); - Assert.All(inference, r => Assert.Equal(byokSessionId, r.SessionId)); + Assert.All(inference, r => + { + Assert.Equal(byokSessionId, r.SessionId); + AssertAgentMetadata(r); + }); // Validate the final assistant response arrived (guards against truncated captures) Assert.Contains("OK from the synthetic", content); } + + private static void AssertAgentMetadata(InterceptedRequest request) + { + Assert.False(string.IsNullOrEmpty(request.AgentId)); + Assert.False(string.IsNullOrEmpty(request.InteractionType)); + } } diff --git a/dotnet/test/E2E/CopilotRequestWebSocketE2ETests.cs b/dotnet/test/E2E/CopilotRequestWebSocketE2ETests.cs index 464aadb66a..80ccdb8c90 100644 --- a/dotnet/test/E2E/CopilotRequestWebSocketE2ETests.cs +++ b/dotnet/test/E2E/CopilotRequestWebSocketE2ETests.cs @@ -31,6 +31,7 @@ namespace GitHub.Copilot.Test.E2E; /// message. Without the eager start the turn never completes and this test /// times out. /// +[Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public class CopilotRequestWebSocketE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "copilot_request_websocket", output) { @@ -51,11 +52,10 @@ public async Task Services_A_WebSocket_Turn_End_To_End_Via_The_Request_Handler() { Connection = RuntimeConnection.ForStdio(), RequestHandler = handler, - Environment = env, - }); + }, environment: env); await client.StartAsync(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); diff --git a/dotnet/test/E2E/GitHubTelemetryForwardingE2ETests.cs b/dotnet/test/E2E/GitHubTelemetryForwardingE2ETests.cs new file mode 100644 index 0000000000..80d0ccb0b6 --- /dev/null +++ b/dotnet/test/E2E/GitHubTelemetryForwardingE2ETests.cs @@ -0,0 +1,66 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +using System.Collections.Concurrent; +using GitHub.Copilot.Rpc; +using GitHub.Copilot.Test.Harness; +using Xunit; +using Xunit.Abstractions; + +namespace GitHub.Copilot.Test.E2E; + +#pragma warning disable GHCP001 // GitHub telemetry forwarding is experimental. + +// TODO(BYOK): Anthropic Messages produced no GitHub telemetry notification. Determine whether +// provider-backed sessions should forward the same telemetry before keeping this CAPI-only. +[Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] +public class GitHubTelemetryForwardingE2ETests(E2ETestFixture fixture, ITestOutputHelper output) + : E2ETestBase(fixture, "github_telemetry", output) +{ + [Fact] + public async Task Should_Forward_GitHub_Telemetry_For_A_Live_Session() + { + var notifications = new ConcurrentQueue(); + + await using var client = Ctx.CreateClient(options: new CopilotClientOptions + { + OnGitHubTelemetry = notification => + { + notifications.Enqueue(notification); + return Task.CompletedTask; + }, + }); + + CopilotSession? session = null; + try + { + session = await Ctx.CreateSessionAsync(client, new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + }); + + await TestHelper.WaitForConditionAsync( + () => !notifications.IsEmpty, + timeout: TimeSpan.FromSeconds(30), + timeoutMessage: "Timed out waiting for GitHub telemetry notification."); + + Assert.True(notifications.TryPeek(out var notification)); + Assert.False(string.IsNullOrEmpty(notification.SessionId)); + Assert.NotNull(notification.Event); + Assert.NotEmpty(notification.Event.Kind); + Assert.IsType(notification.Restricted); + } + finally + { + if (session is not null) + { + await session.DisposeAsync(); + } + + await client.StopAsync(); + } + } +} + +#pragma warning restore GHCP001 diff --git a/dotnet/test/E2E/HooksE2ETests.cs b/dotnet/test/E2E/HooksE2ETests.cs index ab971c26e6..0d9155fbc7 100644 --- a/dotnet/test/E2E/HooksE2ETests.cs +++ b/dotnet/test/E2E/HooksE2ETests.cs @@ -30,7 +30,7 @@ public async Task Should_Invoke_PreToolUse_Hook_When_Model_Runs_A_Tool() }); // Create a file for the model to read - await File.WriteAllTextAsync(Path.Combine(Ctx.WorkDir, "hello.txt"), "Hello from the test!"); + await File.WriteAllTextAsync(Path.Join(Ctx.WorkDir, "hello.txt"), "Hello from the test!"); await session.SendAsync(new MessageOptions { @@ -66,7 +66,7 @@ public async Task Should_Invoke_PostToolUse_Hook_After_Model_Runs_A_Tool() }); // Create a file for the model to read - await File.WriteAllTextAsync(Path.Combine(Ctx.WorkDir, "world.txt"), "World from the test!"); + await File.WriteAllTextAsync(Path.Join(Ctx.WorkDir, "world.txt"), "World from the test!"); await session.SendAsync(new MessageOptions { @@ -107,7 +107,7 @@ public async Task Should_Invoke_Both_PreToolUse_And_PostToolUse_Hooks_For_Single } }); - await File.WriteAllTextAsync(Path.Combine(Ctx.WorkDir, "both.txt"), "Testing both hooks!"); + await File.WriteAllTextAsync(Path.Join(Ctx.WorkDir, "both.txt"), "Testing both hooks!"); await session.SendAsync(new MessageOptions { @@ -147,7 +147,7 @@ public async Task Should_Deny_Tool_Execution_When_PreToolUse_Returns_Deny() // Create a file var originalContent = "Original content that should not be modified"; - await File.WriteAllTextAsync(Path.Combine(Ctx.WorkDir, "protected.txt"), originalContent); + await File.WriteAllTextAsync(Path.Join(Ctx.WorkDir, "protected.txt"), originalContent); await session.SendAsync(new MessageOptions { diff --git a/dotnet/test/E2E/McpOAuthE2ETests.cs b/dotnet/test/E2E/McpOAuthE2ETests.cs new file mode 100644 index 0000000000..1085aba040 --- /dev/null +++ b/dotnet/test/E2E/McpOAuthE2ETests.cs @@ -0,0 +1,360 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +using GitHub.Copilot.Rpc; +using GitHub.Copilot.Test.Harness; +using System.Diagnostics; +using System.Net.Http; +using System.Text.Json; +using Xunit; +using Xunit.Abstractions; + +namespace GitHub.Copilot.Test.E2E; + +public class McpOAuthE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "mcp_oauth", output) +{ + private const string ExpectedToken = "sdk-host-token"; + private const string RefreshToken = ExpectedToken + "-refresh"; + private const string UpscopeToken = ExpectedToken + "-upscope"; + private const string ReauthToken = ExpectedToken + "-reauth"; + + [Fact] + public async Task Should_Satisfy_MCP_OAuth_Using_Host_Provided_Token() + { + await using var oauthServer = await OAuthMcpServer.StartAsync(ExpectedToken); + var serverName = "oauth-protected-mcp"; + McpAuthContext? observedRequest = null; + + await using var session = await CreateSessionAsync(new SessionConfig + { + OnMcpAuthRequest = request => + { + observedRequest = request; + return Task.FromResult(McpAuthResult.FromToken(new McpAuthToken + { + AccessToken = ExpectedToken, + TokenType = "Bearer", + ExpiresIn = 3600 + })); + }, + McpServers = new Dictionary + { + [serverName] = new McpHttpServerConfig + { + Url = $"{oauthServer.Url}/mcp", + Tools = ["*"] + } + } + }); + + await WaitForMcpServerStatusAsync(session, serverName, McpServerStatus.Connected); + var tools = await session.Rpc.Mcp.ListToolsAsync(serverName); + Assert.Contains(tools.Tools, tool => tool.Name == "whoami"); + + Assert.NotNull(observedRequest); + Assert.NotEmpty(observedRequest!.RequestId); + Assert.Equal(serverName, observedRequest!.ServerName); + Assert.Equal($"{oauthServer.Url}/mcp", observedRequest.ServerUrl); + Assert.Equal(McpOauthRequestReason.Initial, observedRequest.Reason); + Assert.NotNull(observedRequest.WwwAuthenticateParams); + Assert.Equal($"{oauthServer.Url}/.well-known/oauth-protected-resource", observedRequest.WwwAuthenticateParams!.ResourceMetadataUrl); + Assert.Equal("mcp.read", observedRequest.WwwAuthenticateParams.Scope); + Assert.Equal("invalid_token", observedRequest.WwwAuthenticateParams.Error); + + using var metadata = JsonDocument.Parse(observedRequest.ResourceMetadata!); + Assert.Equal($"{oauthServer.Url}/mcp", metadata.RootElement.GetProperty("resource").GetString()); + + var requests = await oauthServer.GetRequestsAsync(); + Assert.Contains(requests, request => request.Authorization is null); + Assert.Contains(requests, request => request.Authorization == $"Bearer {ExpectedToken}"); + } + + [Fact] + public async Task Should_Resolve_Pending_MCP_OAuth_Request_With_Direct_Rpc() + { + await using var oauthServer = await OAuthMcpServer.StartAsync(ExpectedToken); + var serverName = "oauth-direct-rpc-mcp"; + var authRequest = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseHandler = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await using var session = await CreateSessionAsync(new SessionConfig + { + OnMcpAuthRequest = request => + { + authRequest.TrySetResult(request); + return releaseHandler.Task; + }, + McpServers = new Dictionary + { + [serverName] = new McpHttpServerConfig + { + Url = $"{oauthServer.Url}/mcp", + Tools = ["*"], + }, + }, + }); + + var connected = WaitForMcpServerStatusAsync(session, serverName, McpServerStatus.Connected); + var request = await authRequest.Task.WaitAsync(TimeSpan.FromSeconds(30)); + Assert.NotEmpty(request.RequestId); + Assert.Equal(serverName, request.ServerName); + Assert.Equal($"{oauthServer.Url}/mcp", request.ServerUrl); + Assert.Equal(McpOauthRequestReason.Initial, request.Reason); + Assert.NotNull(request.WwwAuthenticateParams); + Assert.Equal("mcp.read", request.WwwAuthenticateParams!.Scope); + + var handled = await session.Rpc.Mcp.Oauth.HandlePendingRequestAsync( + request.RequestId, + new McpOauthPendingRequestResponseToken + { + AccessToken = ExpectedToken, + TokenType = "Bearer", + ExpiresIn = 3600, + }); + Assert.True(handled.Success); + + await connected; + var tools = await session.Rpc.Mcp.ListToolsAsync(serverName); + Assert.Contains(tools.Tools, tool => tool.Name == "whoami"); + + releaseHandler.SetResult(McpAuthResult.FromToken(new McpAuthToken { AccessToken = ExpectedToken })); + } + + [Fact] + public async Task Should_Request_Replacement_Tokens_Across_MCP_OAuth_Lifecycle() + { + await using var oauthServer = await OAuthMcpServer.StartAsync(ExpectedToken); + var serverName = "oauth-lifecycle-mcp"; + List observedReasons = []; + var refreshCount = 0; + + await using var session = await CreateSessionAsync(new SessionConfig + { + EnableMcpApps = true, + OnMcpAuthRequest = request => + { + observedReasons.Add(request.Reason); + if (request.Reason == McpOauthRequestReason.Refresh) + { + refreshCount++; + Assert.NotNull(request.WwwAuthenticateParams); + Assert.Null(request.WwwAuthenticateParams!.ResourceMetadataUrl); + Assert.Equal("invalid_token", request.WwwAuthenticateParams.Error); + if (refreshCount > 1) + { + return Task.FromResult(McpAuthResult.Cancel()); + } + } + + if (request.Reason == McpOauthRequestReason.Upscope) + { + Assert.NotNull(request.WwwAuthenticateParams); + Assert.Equal($"{oauthServer.Url}/.well-known/oauth-protected-resource", request.WwwAuthenticateParams!.ResourceMetadataUrl); + Assert.Equal("mcp.write", request.WwwAuthenticateParams.Scope); + Assert.Equal("insufficient_scope", request.WwwAuthenticateParams.Error); + } + + var token = request.Reason == McpOauthRequestReason.Refresh + ? RefreshToken + : request.Reason == McpOauthRequestReason.Upscope + ? UpscopeToken + : request.Reason == McpOauthRequestReason.Reauth + ? ReauthToken + : ExpectedToken; + + return Task.FromResult(McpAuthResult.FromToken(new McpAuthToken + { + AccessToken = token + })); + }, + McpServers = new Dictionary + { + [serverName] = new McpHttpServerConfig + { + Url = $"{oauthServer.Url}/mcp", + Tools = ["*"] + } + } + }); + + await WaitForMcpServerStatusAsync(session, serverName, McpServerStatus.Connected); + await CallWhoamiAsync(session, serverName, "refresh"); + await CallWhoamiAsync(session, serverName, "upscope"); + await CallWhoamiAsync(session, serverName, "reauth"); + + Assert.Equal( + [ + McpOauthRequestReason.Initial, + McpOauthRequestReason.Refresh, + McpOauthRequestReason.Upscope, + McpOauthRequestReason.Refresh, + McpOauthRequestReason.Reauth + ], + observedReasons); + + var requests = await oauthServer.GetRequestsAsync(); + Assert.Contains(requests, request => request.Authorization == $"Bearer {RefreshToken}"); + Assert.Contains(requests, request => request.Authorization == $"Bearer {UpscopeToken}"); + Assert.Contains(requests, request => request.Authorization == $"Bearer {ReauthToken}"); + } + + [Fact] + public async Task Should_Cancel_Pending_MCP_OAuth_Request() + { + await using var oauthServer = await OAuthMcpServer.StartAsync(ExpectedToken); + var serverName = "oauth-cancelled-mcp"; + var authRequest = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await using var session = await CreateSessionAsync(new SessionConfig + { + OnMcpAuthRequest = request => + { + authRequest.TrySetResult(request); + return Task.FromResult(McpAuthResult.Cancel()); + }, + McpServers = new Dictionary + { + [serverName] = new McpHttpServerConfig + { + Url = $"{oauthServer.Url}/mcp", + Tools = ["*"] + } + } + }); + + await WaitForMcpServerStatusAsync(session, serverName, McpServerStatus.NeedsAuth); + + // The MCP connection is kicked off by session.create, but the SDK only registers its + // `mcp.oauth_required` event interest once create returns. If the server's initial 401 + // wins that race, the runtime records `needs-auth` WITHOUT invoking the host callback, + // so the callback fires only on a later auth retry (now that interest is registered), + // with the same `Initial` reason. Await the callback rather than sampling it the instant + // `needs-auth` first appears, which is what made this test flaky. + var observedRequest = await authRequest.Task.WaitAsync(TimeSpan.FromSeconds(60)); + + Assert.NotEmpty(observedRequest.RequestId); + Assert.Equal(serverName, observedRequest.ServerName); + Assert.Equal(McpOauthRequestReason.Initial, observedRequest.Reason); + } + + private static async Task CallWhoamiAsync(CopilotSession session, string serverName, string scenario) + { + using var argumentDocument = JsonDocument.Parse($"{{\"scenario\":\"{scenario}\"}}"); + var result = await session.Rpc.Mcp.Apps.CallToolAsync( + serverName, + "whoami", + serverName, + new Dictionary + { + ["scenario"] = argumentDocument.RootElement.GetProperty("scenario").Clone() + }); + + var content = result["content"].EnumerateArray().ToList(); + Assert.Single(content); + Assert.Equal("oauth-test-user", content[0].GetProperty("text").GetString()); + } + + private sealed class OAuthMcpServer : IAsyncDisposable + { + private readonly Process _process; + private readonly HttpClient _http = new(); + + private OAuthMcpServer(Process process, string url) + { + _process = process; + Url = url; + } + + public string Url { get; } + + public static async Task StartAsync(string expectedToken) + { + var repoRoot = FindRepoRoot(); + var script = GetRepoRelativePath(repoRoot, "test", "harness", "test-mcp-oauth-server.mjs"); + var startInfo = new ProcessStartInfo + { + FileName = "node", + Arguments = QuoteProcessArgument(script), + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + startInfo.Environment["EXPECTED_TOKEN"] = expectedToken; + + var process = Process.Start(startInfo) + ?? throw new InvalidOperationException("Failed to start OAuth MCP server."); + var stderrTask = process.StandardError.ReadToEndAsync(); + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + while (!cts.IsCancellationRequested) + { + var line = await process.StandardOutput.ReadLineAsync(cts.Token); + if (line is null) + { + throw new InvalidOperationException($"OAuth MCP server exited before listening: {await stderrTask}"); + } + if (line.StartsWith("Listening: ", StringComparison.Ordinal)) + { + return new OAuthMcpServer(process, line["Listening: ".Length..]); + } + } + + throw new TimeoutException($"Timed out waiting for OAuth MCP server: {await stderrTask}"); + } + + public async Task> GetRequestsAsync() + { + var json = await _http.GetStringAsync($"{Url}/__requests"); + using var document = JsonDocument.Parse(json); + return document.RootElement.EnumerateArray() + .Select(element => new OAuthMcpRequest( + element.TryGetProperty("authorization", out var authorization) + && authorization.ValueKind is JsonValueKind.String + ? authorization.GetString() + : null)) + .ToList(); + } + + public async ValueTask DisposeAsync() + { + _http.Dispose(); + if (!_process.HasExited) + { + _process.Kill(entireProcessTree: true); + await _process.WaitForExitAsync(); + } + _process.Dispose(); + } + + private static string FindRepoRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null) + { + var candidate = GetRepoRelativePath(dir.FullName, "test", "harness", "test-mcp-oauth-server.mjs"); + if (File.Exists(candidate)) + return dir.FullName; + dir = dir.Parent; + } + throw new InvalidOperationException("Could not find repository root."); + } + + private static string GetRepoRelativePath(string repoRoot, params string[] relativeSegments) + { + var path = repoRoot; + foreach (var segment in relativeSegments) + { + if (Path.IsPathRooted(segment)) + throw new ArgumentException("Repository-relative path segments must not be rooted.", nameof(relativeSegments)); + path = Path.Join(path, segment); + } + return Path.GetFullPath(path); + } + + private static string QuoteProcessArgument(string argument) + => "\"" + argument.Replace("\"", "\\\"") + "\""; + } + + private sealed record OAuthMcpRequest(string? Authorization); +} diff --git a/dotnet/test/E2E/ModeEmptyE2ETests.cs b/dotnet/test/E2E/ModeEmptyE2ETests.cs index df1bbc857d..433e6a745c 100644 --- a/dotnet/test/E2E/ModeEmptyE2ETests.cs +++ b/dotnet/test/E2E/ModeEmptyE2ETests.cs @@ -21,7 +21,7 @@ public class ModeEmptyE2ETests(E2ETestFixture fixture, ITestOutputHelper output) public async Task Empty_Mode_Isolated_Set_Shell_Tool_Is_Not_Exposed() { await using var client = Ctx.CreateClient(options: EmptyModeOptions(Ctx)); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn(BuiltInTools.Isolated), @@ -45,7 +45,7 @@ public async Task Empty_Mode_Isolated_Set_Shell_Tool_Is_Not_Exposed() public async Task Empty_Mode_Builtin_Star_Exposes_All_Built_In_Tools() { await using var client = Ctx.CreateClient(options: EmptyModeOptions(Ctx)); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn("*"), @@ -65,7 +65,7 @@ public async Task Empty_Mode_Excluded_Tools_Subtracts_From_Available_Tools() { var shellToolName = OperatingSystem.IsWindows() ? "powershell" : "bash"; await using var client = Ctx.CreateClient(options: EmptyModeOptions(Ctx)); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn("*"), @@ -85,7 +85,7 @@ public async Task Empty_Mode_Excluded_Tools_Subtracts_From_Available_Tools() public async Task Empty_Mode_Strips_Environment_Context_From_The_System_Message_By_Default() { await using var client = Ctx.CreateClient(options: EmptyModeOptions(Ctx)); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn(BuiltInTools.Isolated), @@ -109,7 +109,7 @@ public async Task Empty_Mode_Strips_Environment_Context_From_The_System_Message_ public async Task Empty_Mode_System_Message_Replace_Llm_Follows_Caller_Content_Verbatim() { await using var client = Ctx.CreateClient(options: EmptyModeOptions(Ctx)); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn(BuiltInTools.Isolated), @@ -128,7 +128,7 @@ public async Task Empty_Mode_System_Message_Replace_Llm_Follows_Caller_Content_V public async Task Empty_Mode_Append_Caller_Instruction_Takes_Effect_And_Env_Context_Stripped() { await using var client = Ctx.CreateClient(options: EmptyModeOptions(Ctx)); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, AvailableTools = new ToolSet().AddBuiltIn(BuiltInTools.Isolated), diff --git a/dotnet/test/E2E/ModeHandlersE2ETests.cs b/dotnet/test/E2E/ModeHandlersE2ETests.cs index 40552fa9f7..b9f0e69b22 100644 --- a/dotnet/test/E2E/ModeHandlersE2ETests.cs +++ b/dotnet/test/E2E/ModeHandlersE2ETests.cs @@ -8,6 +8,7 @@ namespace GitHub.Copilot.Test.E2E; +[Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public class ModeHandlersE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "mode_handlers", output) { @@ -24,7 +25,7 @@ public async Task Should_Invoke_Exit_Plan_Mode_Handler_When_Model_Uses_Tool() TaskCreationOptions.RunContinuationsAsynchronously); await using var client = CreateAuthenticatedClient(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { GitHubToken = Token, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -60,7 +61,7 @@ public async Task Should_Invoke_Exit_Plan_Mode_Handler_When_Model_Uses_Tool() var (request, invocation) = await handlerTask.Task.WaitAsync(TimeSpan.FromSeconds(30)); Assert.Equal(session.SessionId, invocation.SessionId); Assert.Equal(summary, request.Summary); - Assert.Equal(["interactive", "autopilot", "exit_only"], request.Actions); + Assert.Equal(["autopilot", "interactive", "exit_only"], request.Actions); Assert.Equal("interactive", request.RecommendedAction); Assert.NotNull(request.PlanContent); @@ -92,7 +93,7 @@ public async Task Should_Invoke_Auto_Mode_Switch_Handler_When_Rate_Limited() TaskCreationOptions.RunContinuationsAsynchronously); await using var client = CreateAuthenticatedClient(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { GitHubToken = Token, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -155,7 +156,7 @@ private CopilotClient CreateAuthenticatedClient() ["COPILOT_DEBUG_GITHUB_API_URL"] = Ctx.ProxyUrl, }; - return Ctx.CreateClient(options: new CopilotClientOptions { Environment = env }); + return Ctx.CreateClient(environment: env); } private Task ConfigureAuthenticatedUserAsync() diff --git a/dotnet/test/E2E/MultiClientCommandsElicitationE2ETests.cs b/dotnet/test/E2E/MultiClientCommandsElicitationE2ETests.cs index d60c21709c..d869dc8164 100644 --- a/dotnet/test/E2E/MultiClientCommandsElicitationE2ETests.cs +++ b/dotnet/test/E2E/MultiClientCommandsElicitationE2ETests.cs @@ -59,7 +59,7 @@ public async Task InitializeAsync() await Ctx.ConfigureForTestAsync("multi_client", _testName); // Trigger connection so we can read the port - var initSession = await Client1.CreateSessionAsync(new SessionConfig + var initSession = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -102,7 +102,7 @@ public async Task DisposeAsync() [Fact] public async Task Client_Receives_Commands_Changed_When_Another_Client_Joins_With_Commands() { - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -120,7 +120,7 @@ public async Task Client_Receives_Commands_Changed_When_Another_Client_Joins_Wit }); // Client2 joins with commands - var session2 = await Client2.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client2, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Commands = @@ -148,7 +148,7 @@ public async Task Client_Receives_Commands_Changed_When_Another_Client_Joins_Wit public async Task Capabilities_Changed_Fires_When_Second_Client_Joins_With_Elicitation_Handler() { // Client1 creates session without elicitation - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -168,7 +168,7 @@ public async Task Capabilities_Changed_Fires_When_Second_Client_Joins_With_Elici }); // Client2 joins WITH elicitation handler — triggers capabilities.changed - var session2 = await Client2.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client2, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, OnElicitationRequest = _ => Task.FromResult(new ElicitationResult @@ -194,7 +194,7 @@ public async Task Capabilities_Changed_Fires_When_Second_Client_Joins_With_Elici public async Task Capabilities_Changed_Fires_When_Elicitation_Provider_Disconnects() { // Client1 creates session without elicitation - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -222,7 +222,7 @@ public async Task Capabilities_Changed_Fires_When_Elicitation_Provider_Disconnec }); // Client3 joins WITH elicitation handler - await _client3.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + await Ctx.ResumeSessionAsync(_client3, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, OnElicitationRequest = _ => Task.FromResult(new ElicitationResult diff --git a/dotnet/test/E2E/MultiClientE2ETests.cs b/dotnet/test/E2E/MultiClientE2ETests.cs index faaf383935..4dbe7190ad 100644 --- a/dotnet/test/E2E/MultiClientE2ETests.cs +++ b/dotnet/test/E2E/MultiClientE2ETests.cs @@ -58,7 +58,7 @@ public async Task InitializeAsync() await Ctx.ConfigureForTestAsync("multi_client", _testName); // Trigger connection so we can read the port - var initSession = await Client1.CreateSessionAsync(new SessionConfig + var initSession = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -96,13 +96,13 @@ public async Task Both_Clients_See_Tool_Request_And_Completion_Events() { var tool = AIFunctionFactory.Create(MagicNumber, "magic_number"); - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Tools = [tool], }); - var session2 = await Client2.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client2, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -148,7 +148,7 @@ public async Task One_Client_Approves_Permission_And_Both_See_The_Result() { var client1PermissionRequests = new List(); - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = (request, _) => { @@ -158,7 +158,7 @@ public async Task One_Client_Approves_Permission_And_Both_See_The_Result() }); // Client 2 resumes — its handler never completes, so only client 1's approval takes effect - var session2 = await Client2.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client2, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = (_, _) => new TaskCompletionSource().Task, }); @@ -200,13 +200,13 @@ await session1.SendAsync(new MessageOptions [Fact] public async Task One_Client_Rejects_Permission_And_Both_See_The_Result() { - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = (_, _) => Task.FromResult(PermissionDecision.Reject()), }); // Client 2 resumes — its handler never completes - var session2 = await Client2.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client2, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = (_, _) => new TaskCompletionSource().Task, }); @@ -252,13 +252,13 @@ public async Task Two_Clients_Register_Different_Tools_And_Agent_Uses_Both() var toolA = AIFunctionFactory.Create(CityLookup, "city_lookup"); var toolB = AIFunctionFactory.Create(CurrencyLookup, "currency_lookup"); - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Tools = [toolA], }); - var session2 = await Client2.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client2, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Tools = [toolB], @@ -294,13 +294,13 @@ public async Task Disconnecting_Client_Removes_Its_Tools() var toolA = AIFunctionFactory.Create(StableTool, "stable_tool"); var toolB = AIFunctionFactory.Create(EphemeralTool, "ephemeral_tool"); - var session1 = await Client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(Client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Tools = [toolA], }); - await Client2.ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + await Ctx.ResumeSessionAsync(Client2, session1.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Tools = [toolB], diff --git a/dotnet/test/E2E/MultiProviderRegistryE2ETests.cs b/dotnet/test/E2E/MultiProviderRegistryE2ETests.cs index 8a75cc3c1a..80827cc867 100644 --- a/dotnet/test/E2E/MultiProviderRegistryE2ETests.cs +++ b/dotnet/test/E2E/MultiProviderRegistryE2ETests.cs @@ -18,6 +18,7 @@ namespace GitHub.Copilot.Test.E2E; /// session, be launched, and route inference to the configured provider with /// the configured wire model and headers. /// +[Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public class MultiProviderRegistryE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "multi_provider_registry", output) { diff --git a/dotnet/test/E2E/PendingWorkResumeE2ETests.cs b/dotnet/test/E2E/PendingWorkResumeE2ETests.cs index b330795905..b3ca218190 100644 --- a/dotnet/test/E2E/PendingWorkResumeE2ETests.cs +++ b/dotnet/test/E2E/PendingWorkResumeE2ETests.cs @@ -30,7 +30,7 @@ public async Task Should_Continue_Pending_Permission_Request_After_Resume() var cliUrl = GetCliUrl(server); using var suspendedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var session1 = await suspendedClient.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(suspendedClient, new SessionConfig { Tools = [AIFunctionFactory.Create(ResumePermissionTool, "resume_permission_tool")], OnPermissionRequest = (request, _) => @@ -57,7 +57,7 @@ await session1.SendAsync(new MessageOptions await suspendedClient.ForceStopAsync(); await using var resumedTcpClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var session2 = await resumedTcpClient.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(resumedTcpClient, sessionId, new ResumeSessionConfig { ContinuePendingWork = true, OnPermissionRequest = (_, _) => Task.FromResult(PermissionDecision.NoResult()), @@ -99,7 +99,7 @@ public async Task Should_Continue_Pending_External_Tool_Request_After_Resume() var cliUrl = GetCliUrl(server); using var suspendedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var session1 = await suspendedClient.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(suspendedClient, new SessionConfig { Tools = [AIFunctionFactory.Create(BlockingExternalTool, "resume_external_tool")], OnPermissionRequest = PermissionHandler.ApproveAll, @@ -120,7 +120,7 @@ await session1.SendAsync(new MessageOptions await suspendedClient.ForceStopAsync(); await using var resumedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var session2 = await resumedClient.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(resumedClient, sessionId, new ResumeSessionConfig { ContinuePendingWork = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -175,7 +175,7 @@ private async Task AssertPendingExternalToolHandleableOnResumeAsync( var cliUrl = GetCliUrl(server); using var suspendedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var session1 = await suspendedClient.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(suspendedClient, new SessionConfig { Tools = [AIFunctionFactory.Create(BlockingExternalTool, "resume_external_tool")], OnPermissionRequest = PermissionHandler.ApproveAll, @@ -216,7 +216,7 @@ await session1.SendAsync(new MessageOptions resumeConfig.Tools = [AIFunctionFactory.Create(ResumedExternalTool, "resume_external_tool")]; } - var session2 = await resumedClient.ResumeSessionAsync(sessionId, resumeConfig); + var session2 = await Ctx.ResumeSessionAsync(resumedClient, sessionId, resumeConfig); var resumeEvent = await GetSingleResumeEventAsync(session2); Assert.Equal(false, resumeEvent.Data.ContinuePendingWork); @@ -276,7 +276,7 @@ public async Task Should_Continue_Parallel_Pending_External_Tool_Requests_After_ var cliUrl = GetCliUrl(server); using var suspendedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var session1 = await suspendedClient.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(suspendedClient, new SessionConfig { Tools = [ @@ -306,7 +306,7 @@ await Task.WhenAll( await suspendedClient.ForceStopAsync(); await using var resumedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var session2 = await resumedClient.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(resumedClient, sessionId, new ResumeSessionConfig { ContinuePendingWork = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -357,7 +357,7 @@ public async Task Should_Resume_Successfully_When_No_Pending_Work_Exists() string sessionId; await using (var firstClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) })) { - var firstSession = await firstClient.CreateSessionAsync(new SessionConfig + var firstSession = await Ctx.CreateSessionAsync(firstClient, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -370,7 +370,7 @@ public async Task Should_Resume_Successfully_When_No_Pending_Work_Exists() } await using var resumedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var resumedSession = await resumedClient.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var resumedSession = await Ctx.ResumeSessionAsync(resumedClient, sessionId, new ResumeSessionConfig { ContinuePendingWork = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -395,7 +395,7 @@ public async Task Should_Report_ContinuePendingWork_True_In_Resume_Event() string sessionId; await using (var firstClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) })) { - var firstSession = await firstClient.CreateSessionAsync(new SessionConfig + var firstSession = await Ctx.CreateSessionAsync(firstClient, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -411,7 +411,7 @@ public async Task Should_Report_ContinuePendingWork_True_In_Resume_Event() } await using var resumedClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: SharedToken) }); - var resumedSession = await resumedClient.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var resumedSession = await Ctx.ResumeSessionAsync(resumedClient, sessionId, new ResumeSessionConfig { ContinuePendingWork = true, OnPermissionRequest = PermissionHandler.ApproveAll, diff --git a/dotnet/test/E2E/PerSessionAuthE2ETests.cs b/dotnet/test/E2E/PerSessionAuthE2ETests.cs index 6bc92f08d2..4b370768a1 100644 --- a/dotnet/test/E2E/PerSessionAuthE2ETests.cs +++ b/dotnet/test/E2E/PerSessionAuthE2ETests.cs @@ -8,6 +8,7 @@ namespace GitHub.Copilot.Test.E2E; +[Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public class PerSessionAuthE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "per-session-auth", output) { /// @@ -22,7 +23,7 @@ private CopilotClient CreateAuthTestClient() }; // Disable the harness's auto-injected client token so the per-session // auth tests validate only session-scoped tokens. - return Ctx.CreateClient(options: new CopilotClientOptions { Environment = env }, autoInjectGitHubToken: false); + return Ctx.CreateClient(environment: env, autoInjectGitHubToken: false); } private CopilotClient CreateNoAuthTestClient() @@ -32,9 +33,8 @@ private CopilotClient CreateNoAuthTestClient() return Ctx.CreateClient(options: new CopilotClientOptions { - Environment = env, UseLoggedInUser = false, - }, autoInjectGitHubToken: false); + }, autoInjectGitHubToken: false, environment: env); } private static Dictionary WithoutAuthEnv(Dictionary env) @@ -75,13 +75,13 @@ public async Task ShouldAuthenticateWithGitHubToken() { await SetupCopilotUsersAsync(); - await using var session = await AuthClient.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(AuthClient, new SessionConfig { GitHubToken = "token-alice", OnPermissionRequest = PermissionHandler.ApproveAll, }); - var status = await session.Rpc.Auth.GetStatusAsync(); + var status = await session.Rpc.GitHubAuth.GetStatusAsync(); Assert.True(status.IsAuthenticated); Assert.Equal("alice", status.Login); } @@ -91,23 +91,23 @@ public async Task ShouldIsolateAuthBetweenSessions() { await SetupCopilotUsersAsync(); - await using var sessionA = await AuthClient.CreateSessionAsync(new SessionConfig + await using var sessionA = await Ctx.CreateSessionAsync(AuthClient, new SessionConfig { GitHubToken = "token-alice", OnPermissionRequest = PermissionHandler.ApproveAll, }); - await using var sessionB = await AuthClient.CreateSessionAsync(new SessionConfig + await using var sessionB = await Ctx.CreateSessionAsync(AuthClient, new SessionConfig { GitHubToken = "token-bob", OnPermissionRequest = PermissionHandler.ApproveAll, }); - var statusA = await sessionA.Rpc.Auth.GetStatusAsync(); + var statusA = await sessionA.Rpc.GitHubAuth.GetStatusAsync(); Assert.True(statusA.IsAuthenticated); Assert.Equal("alice", statusA.Login); - var statusB = await sessionB.Rpc.Auth.GetStatusAsync(); + var statusB = await sessionB.Rpc.GitHubAuth.GetStatusAsync(); Assert.True(statusB.IsAuthenticated); Assert.Equal("bob", statusB.Login); } @@ -117,12 +117,12 @@ public async Task ShouldBeUnauthenticatedWithoutToken() { var noAuthClient = CreateNoAuthTestClient(); - await using var session = await noAuthClient.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(noAuthClient, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); - var status = await session.Rpc.Auth.GetStatusAsync(); + var status = await session.Rpc.GitHubAuth.GetStatusAsync(); // Without a per-session GitHub token, there is no per-session identity. Assert.True(string.IsNullOrEmpty(status.Login), $"Expected no per-session login without token, got {status.Login}"); } @@ -132,7 +132,7 @@ public async Task ShouldFailWithInvalidToken() { await SetupCopilotUsersAsync(); - var ex = await Assert.ThrowsAnyAsync(() => AuthClient.CreateSessionAsync(new SessionConfig + var ex = await Assert.ThrowsAnyAsync(() => Ctx.CreateSessionAsync(AuthClient, new SessionConfig { GitHubToken = "invalid-token", OnPermissionRequest = PermissionHandler.ApproveAll, diff --git a/dotnet/test/E2E/PermissionE2ETests.cs b/dotnet/test/E2E/PermissionE2ETests.cs index c4f3f108b8..2225dcba89 100644 --- a/dotnet/test/E2E/PermissionE2ETests.cs +++ b/dotnet/test/E2E/PermissionE2ETests.cs @@ -205,7 +205,7 @@ public async Task Should_Resume_Session_With_Permission_Handler() await session1.DisposeAsync(); // Resume with permission handler - var session2 = await Client.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client, sessionId, new ResumeSessionConfig { OnPermissionRequest = (request, invocation) => { @@ -279,7 +279,7 @@ public async Task Should_Deny_Tool_Operations_When_Handler_Explicitly_Denies_Aft await session1.SendAndWaitAsync(new MessageOptions { Prompt = "What is 1+1?" }); await session1.DisposeAsync(); - var session2 = await Client.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(Client, sessionId, new ResumeSessionConfig { OnPermissionRequest = (_, _) => Task.FromResult(PermissionDecision.UserNotAvailable()) @@ -377,7 +377,7 @@ void AddLifecycleEvent(string phase, string? toolCallId) } }); - await session.SendAsync(new MessageOptions + var sendTask = session.SendAndWaitAsync(new MessageOptions { Prompt = "Run 'echo slow_handler_test'" }); @@ -391,7 +391,13 @@ await session.SendAsync(new MessageOptions releaseHandler.SetResult(); - var message = await TestHelper.GetFinalAssistantMessageAsync(session); + var message = await sendTask; + var persistedEvents = await WaitForPersistedEventsAsync( + session, + events => + events.OfType().Any(evt => evt.Data.ToolCallId == targetToolId) && + events.OfType().Any(evt => evt.Data.ToolCallId == targetToolId), + $"Timed out waiting for persisted tool lifecycle for tool call '{targetToolId}'."); List<(string Phase, string? ToolCallId)> orderedLifecycle; lock (lifecycleLock) @@ -401,20 +407,23 @@ await session.SendAsync(new MessageOptions var permissionStartIndex = orderedLifecycle.FindIndex(evt => evt.Phase == "permission-start" && evt.ToolCallId == targetToolId); var permissionCompleteIndex = orderedLifecycle.FindIndex(evt => evt.Phase == "permission-complete" && evt.ToolCallId == targetToolId); - var toolStartIndex = orderedLifecycle.FindIndex(evt => evt.Phase == "tool-start" && evt.ToolCallId == targetToolId); - var toolCompleteIndex = orderedLifecycle.FindIndex(evt => evt.Phase == "tool-complete" && evt.ToolCallId == targetToolId); var observedLifecycle = string.Join(", ", orderedLifecycle.Select(evt => $"{evt.Phase}:{evt.ToolCallId}")); + var toolStartIndex = persistedEvents.FindIndex(evt => + evt is ToolExecutionStartEvent started && started.Data.ToolCallId == targetToolId); + var toolCompleteIndex = persistedEvents.FindIndex(evt => + evt is ToolExecutionCompleteEvent completed && completed.Data.ToolCallId == targetToolId); + var observedPersistedEvents = string.Join(", ", persistedEvents.Select(DescribeEvent)); Assert.InRange(permissionStartIndex, 0, orderedLifecycle.Count - 1); Assert.InRange(permissionCompleteIndex, 0, orderedLifecycle.Count - 1); - Assert.InRange(toolStartIndex, 0, orderedLifecycle.Count - 1); - Assert.InRange(toolCompleteIndex, 0, orderedLifecycle.Count - 1); Assert.True( - permissionCompleteIndex < toolCompleteIndex, - $"Expected permission completion before target tool completion. Observed: {observedLifecycle}"); + permissionStartIndex < permissionCompleteIndex, + $"Expected permission handler to complete after it started. Observed: {observedLifecycle}"); + Assert.InRange(toolStartIndex, 0, persistedEvents.Count - 1); + Assert.InRange(toolCompleteIndex, 0, persistedEvents.Count - 1); Assert.True( toolStartIndex < toolCompleteIndex, - $"Expected target tool start before target tool completion. Observed: {observedLifecycle}"); + $"Expected target tool start before target tool completion. Observed: {observedPersistedEvents}"); // The tool should have actually run after permission was granted Assert.Contains("slow_handler_test", message?.Data.Content ?? string.Empty); @@ -573,24 +582,21 @@ public async Task Should_Short_Circuit_Permission_Handler_When_Set_Approve_All_E try { - var toolCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using var subscription = session.On(evt => - { - if (evt is ToolExecutionCompleteEvent done && done.Data.Success) - { - toolCompleted.TrySetResult(done); - } - }); - await session.SendAndWaitAsync(new MessageOptions { Prompt = "Run 'echo test' and tell me what happens", }); - // A real shell tool must have completed successfully under the runtime-level approval. - await toolCompleted.Task.WaitAsync(TimeSpan.FromSeconds(30)); + var persistedEvents = await WaitForPersistedEventsAsync( + session, + events => events.OfType().Any(evt => + evt.Data.Success && ToolCompleteContains(evt, "test")), + "Timed out waiting for persisted successful shell tool completion."); Assert.Equal(0, Volatile.Read(ref handlerCallCount)); + Assert.Contains( + persistedEvents.OfType(), + evt => evt.Data.Success && ToolCompleteContains(evt, "test")); } finally { @@ -758,6 +764,40 @@ private static bool PathsEqual(string expected, string actual) OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } + private static async Task> WaitForPersistedEventsAsync( + CopilotSession session, + Func, bool> condition, + string timeoutMessage) + { + List events = []; + await TestHelper.WaitForConditionAsync( + async () => + { + events = (await session.GetEventsAsync()).ToList(); + return condition(events); + }, + timeoutMessage: timeoutMessage); + return events; + } + + private static string DescribeEvent(SessionEvent evt) + => evt switch + { + ToolExecutionStartEvent started => $"{evt.Type}:{started.Data.ToolCallId}", + ToolExecutionCompleteEvent completed => $"{evt.Type}:{completed.Data.ToolCallId}:{completed.Data.Success}", + _ => evt.Type, + }; + + private static bool ToolCompleteContains(ToolExecutionCompleteEvent evt, string expected) + => evt.Data.Result?.Content.Contains(expected, StringComparison.OrdinalIgnoreCase) == true || + evt.Data.Result?.DetailedContent?.Contains(expected, StringComparison.OrdinalIgnoreCase) == true || + evt.Data.Result?.Contents?.Any(content => content switch + { + ToolExecutionCompleteContentText text => text.Text.Contains(expected, StringComparison.OrdinalIgnoreCase), + ToolExecutionCompleteContentTerminal terminal => terminal.Text.Contains(expected, StringComparison.OrdinalIgnoreCase), + _ => false, + }) == true; + private static string NormalizePath(string path) { var fullPath = Path.GetFullPath(path); diff --git a/dotnet/test/E2E/PreMcpToolCallHookE2ETests.cs b/dotnet/test/E2E/PreMcpToolCallHookE2ETests.cs index 8e5240a9a8..02f8606148 100644 --- a/dotnet/test/E2E/PreMcpToolCallHookE2ETests.cs +++ b/dotnet/test/E2E/PreMcpToolCallHookE2ETests.cs @@ -20,7 +20,7 @@ private static string FindMetaEchoTestHarnessDir() var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir != null) { - var candidate = Path.Combine(dir.FullName, "test", "harness", "test-mcp-meta-echo-server.mjs"); + var candidate = Path.Join(dir.FullName, "test", "harness", "test-mcp-meta-echo-server.mjs"); if (File.Exists(candidate)) return Path.GetDirectoryName(candidate)!; dir = dir.Parent; @@ -33,7 +33,7 @@ private static string FindMetaEchoTestHarnessDir() ["meta-echo"] = new McpStdioServerConfig { Command = "node", - Args = [Path.Combine(testHarnessDir, "test-mcp-meta-echo-server.mjs")], + Args = [Path.Join(testHarnessDir, "test-mcp-meta-echo-server.mjs")], WorkingDirectory = testHarnessDir, Tools = ["*"] } diff --git a/dotnet/test/E2E/ProviderEndpointE2ETests.cs b/dotnet/test/E2E/ProviderEndpointE2ETests.cs index f7e9a78856..d2bf06982f 100644 --- a/dotnet/test/E2E/ProviderEndpointE2ETests.cs +++ b/dotnet/test/E2E/ProviderEndpointE2ETests.cs @@ -23,15 +23,16 @@ private CopilotClient CreateProviderEndpointClient() { ["COPILOT_ALLOW_GET_PROVIDER_ENDPOINT"] = "true", }; - return Ctx.CreateClient(options: new CopilotClientOptions { Environment = env }); + return Ctx.CreateClient(environment: env); } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task ShouldReturnByokProviderEndpointWhenCustomProviderIsConfigured() { var client = CreateProviderEndpointClient(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Provider = new ProviderConfig @@ -64,11 +65,12 @@ public async Task ShouldReturnByokProviderEndpointWhenCustomProviderIsConfigured } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task ShouldReturnCapiProviderEndpointForOAuthAuthenticatedSession() { var client = CreateProviderEndpointClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); diff --git a/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs b/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs index c1e43b09ec..0a3513e4b5 100644 --- a/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs +++ b/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs @@ -58,8 +58,7 @@ private CopilotClient CreateExtensionsClient() return Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForStdio(args: ["--yolo"]), - Environment = ExtensionsEnabledEnvironment(), - }); + }, environment: ExtensionsEnabledEnvironment()); } /// @@ -190,7 +189,7 @@ public async Task Discovers_Loads_And_Reports_Running_Extension(string sourceVal await using var client = CreateExtensionsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableConfigDiscovery = true, WorkingDirectory = workingDirectory, @@ -215,7 +214,7 @@ public async Task Disable_Then_Enable_Cycles_Extension_Status() await using var client = CreateExtensionsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableConfigDiscovery = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -241,7 +240,7 @@ public async Task Reload_Picks_Up_Extension_Added_After_Session_Create() // Start the session BEFORE writing the extension so the initial discovery sees nothing. await using var client = CreateExtensionsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableConfigDiscovery = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -286,7 +285,7 @@ public async Task Failed_Extension_Reports_Failed_Status() await using var client = CreateExtensionsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableConfigDiscovery = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -307,7 +306,7 @@ public async Task Multiple_Extensions_Are_Discovered_Independently() await using var client = CreateExtensionsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableConfigDiscovery = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -329,7 +328,7 @@ public async Task Reload_Preserves_Disabled_State_Across_Calls() await using var client = CreateExtensionsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { EnableConfigDiscovery = true, OnPermissionRequest = PermissionHandler.ApproveAll, diff --git a/dotnet/test/E2E/RpcMcpAndSkillsE2ETests.cs b/dotnet/test/E2E/RpcMcpAndSkillsE2ETests.cs index d53f93c9a1..0d2942d4bf 100644 --- a/dotnet/test/E2E/RpcMcpAndSkillsE2ETests.cs +++ b/dotnet/test/E2E/RpcMcpAndSkillsE2ETests.cs @@ -189,7 +189,7 @@ public async Task Should_List_Extensions() { Connection = RuntimeConnection.ForStdio(args: ["--yolo"]), }); - await using var session = await yoloClient.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(yoloClient, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -208,7 +208,7 @@ public async Task Should_List_Extensions() public async Task Should_Round_Trip_Mcp_App_Host_Context() { await using var client = CreateMcpAppsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -253,7 +253,7 @@ public async Task Should_Diagnose_And_Report_Mcp_App_Capability_Errors() new Dictionary { ["MCP_APP_RPC_VALUE"] = "from-app-rpc" }; await using var client = CreateMcpAppsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { McpServers = mcpServers, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -292,7 +292,7 @@ public async Task Should_Report_Error_When_Mcp_App_Resource_Is_Not_Available() { const string serverName = "rpc-apps-resource-server"; await using var client = CreateMcpAppsClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { McpServers = CreateTestMcpServers(serverName), OnPermissionRequest = PermissionHandler.ApproveAll, @@ -368,7 +368,7 @@ public async Task Should_Report_Error_When_Extensions_Are_Not_Available() { Connection = RuntimeConnection.ForStdio(args: ["--yolo"]), }); - await using var session = await yoloClient.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(yoloClient, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -398,10 +398,7 @@ private CopilotClient CreateMcpAppsClient() environment["COPILOT_MCP_APPS"] = "true"; environment["MCP_APPS"] = "true"; - return Ctx.CreateClient(options: new CopilotClientOptions - { - Environment = environment, - }); + return Ctx.CreateClient(environment: environment); } private static void CreateSkill(string skillsDir, string skillName, string description) diff --git a/dotnet/test/E2E/RpcServerE2ETests.cs b/dotnet/test/E2E/RpcServerE2ETests.cs index da4a360ddc..2df8593cc4 100644 --- a/dotnet/test/E2E/RpcServerE2ETests.cs +++ b/dotnet/test/E2E/RpcServerE2ETests.cs @@ -37,9 +37,8 @@ private CopilotClient CreateAuthenticatedClient(string token) return Ctx.CreateClient(options: new CopilotClientOptions { - Environment = env, GitHubToken = token, - }); + }, environment: env); } private async Task ConfigureAuthenticatedUserAsync( @@ -127,6 +126,41 @@ public async Task Should_Call_Rpc_Ping_With_Typed_Params_And_Result() } [Fact] + public async Task Should_Reject_Llm_Inference_Response_Frames_For_Missing_Request() + { + await Client.StartAsync(); + + var start = await Client.Rpc.LlmInference.HttpResponseStartAsync( + requestId: "missing-llm-inference-request", + status: 200, + headers: new Dictionary> + { + ["content-type"] = ["text/event-stream"], + }, + statusText: "OK"); + Assert.False(start.Accepted); + + var chunk = await Client.Rpc.LlmInference.HttpResponseChunkAsync( + requestId: "missing-llm-inference-request", + data: "data: {}\n\n", + binary: false, + end: false); + Assert.False(chunk.Accepted); + + var error = await Client.Rpc.LlmInference.HttpResponseChunkAsync( + requestId: "missing-llm-inference-request", + data: string.Empty, + end: true, + error: new GitHub.Copilot.Rpc.LlmInferenceHttpResponseChunkError + { + Code = "missing_request", + Message = "No pending LLM inference request.", + }); + Assert.False(error.Accepted); + } + + [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Call_Rpc_Models_List_With_Typed_Result() { const string token = "rpc-models-token"; @@ -142,6 +176,7 @@ public async Task Should_Call_Rpc_Models_List_With_Typed_Result() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Call_Rpc_Account_GetQuota_When_Authenticated() { const string token = "rpc-quota-token"; @@ -203,10 +238,7 @@ public async Task Should_Add_Secret_Filter_Values() { var environment = Ctx.GetEnvironment(); environment["COPILOT_ENABLE_SECRET_FILTERING"] = "true"; - await using var client = Ctx.CreateClient(options: new CopilotClientOptions - { - Environment = environment, - }); + await using var client = Ctx.CreateClient(environment: environment); await client.StartAsync(); var secret = $"rpc-secret-{Guid.NewGuid():N}"; @@ -226,7 +258,7 @@ public async Task Should_List_Find_And_Inspect_Persisted_Session_State() var missingTaskId = $"missing-task-{Guid.NewGuid():N}"; var missingSessionId = Guid.NewGuid().ToString(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { SessionId = sessionId, WorkingDirectory = workingDirectory, @@ -278,7 +310,7 @@ public async Task Should_Enrich_Basic_Session_Metadata() var sessionId = Guid.NewGuid().ToString(); var workingDirectory = CreateUniqueWorkDirectory("server-rpc-enrich"); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { SessionId = sessionId, WorkingDirectory = workingDirectory, @@ -323,7 +355,7 @@ public async Task Should_Close_Active_Session_And_Release_Lock() await using var client = CreateAuthenticatedClient(token); var sessionId = Guid.NewGuid().ToString(); var workingDirectory = CreateUniqueWorkDirectory("server-rpc-close"); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { SessionId = sessionId, WorkingDirectory = workingDirectory, @@ -347,8 +379,8 @@ public async Task Should_Check_In_Use_Session_From_Another_Runtime_And_Release_L { var sessionId = Guid.NewGuid().ToString(); var workingDirectory = CreateUniqueWorkDirectory("server-rpc-in-use"); - await using var otherClient = Ctx.CreateClient(useStdio: true); - await using var otherSession = await otherClient.CreateSessionAsync(new SessionConfig + await using var otherClient = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForStdio() }); + await using var otherSession = await Ctx.CreateSessionAsync(otherClient, new SessionConfig { SessionId = sessionId, WorkingDirectory = workingDirectory, @@ -389,7 +421,7 @@ public async Task Should_Prune_DryRun_And_BulkDelete_Persisted_Session() var missingSessionId = Guid.NewGuid().ToString(); var workingDirectory = CreateUniqueWorkDirectory("server-rpc-delete"); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { SessionId = sessionId, WorkingDirectory = workingDirectory, @@ -493,6 +525,44 @@ public async Task Should_Discover_Server_Mcp_And_Skills() Assert.True(discoveredSkill.Enabled); Assert.EndsWith(Path.Join(skillName, "SKILL.md"), discoveredSkill.Path); + var skillPaths = await Client.Rpc.Skills.GetDiscoveryPathsAsync( + projectPaths: [Ctx.WorkDir], + excludeHostSkills: true); + var projectSkillPath = Assert.Single(skillPaths.Paths, path => + PathEquals(Ctx.WorkDir, path.ProjectPath) && path.PreferredForCreation); + Assert.False(string.IsNullOrWhiteSpace(projectSkillPath.Path)); + + var agents = await Client.Rpc.Agents.DiscoverAsync( + projectPaths: [Ctx.WorkDir], + excludeHostAgents: true); + Assert.NotNull(agents.Agents); + Assert.All(agents.Agents, agent => Assert.False(string.IsNullOrWhiteSpace(agent.Name))); + + var agentPaths = await Client.Rpc.Agents.GetDiscoveryPathsAsync( + projectPaths: [Ctx.WorkDir], + excludeHostAgents: true); + var projectAgentPath = Assert.Single(agentPaths.Paths, path => + PathEquals(Ctx.WorkDir, path.ProjectPath) && path.PreferredForCreation); + Assert.False(string.IsNullOrWhiteSpace(projectAgentPath.Path)); + + var instructions = await Client.Rpc.Instructions.DiscoverAsync( + projectPaths: [Ctx.WorkDir], + excludeHostInstructions: true); + Assert.NotNull(instructions.Sources); + Assert.All(instructions.Sources, source => + { + Assert.False(string.IsNullOrWhiteSpace(source.Id)); + Assert.False(string.IsNullOrWhiteSpace(source.Label)); + Assert.False(string.IsNullOrWhiteSpace(source.SourcePath)); + }); + + var instructionPaths = await Client.Rpc.Instructions.GetDiscoveryPathsAsync( + projectPaths: [Ctx.WorkDir], + excludeHostInstructions: true); + Assert.NotEmpty(instructionPaths.Paths); + Assert.Contains(instructionPaths.Paths, path => PathEquals(Ctx.WorkDir, path.ProjectPath)); + Assert.All(instructionPaths.Paths, path => Assert.False(string.IsNullOrWhiteSpace(path.Path))); + try { await Client.Rpc.Skills.Config.SetDisabledSkillsAsync([skillName]); diff --git a/dotnet/test/E2E/RpcServerMiscE2ETests.cs b/dotnet/test/E2E/RpcServerMiscE2ETests.cs index 6d04a35f84..29e560100e 100644 --- a/dotnet/test/E2E/RpcServerMiscE2ETests.cs +++ b/dotnet/test/E2E/RpcServerMiscE2ETests.cs @@ -4,14 +4,15 @@ using GitHub.Copilot; using GitHub.Copilot.Rpc; +using GitHub.Copilot.Test.Harness; using Xunit; using Xunit.Abstractions; namespace GitHub.Copilot.Test.E2E; /// -/// E2E coverage for the remaining miscellaneous server-scoped RPC methods that were previously -/// untested: user.settings.reload, agentRegistry.spawn, runtime.shutdown, sessions.open, and the +/// E2E coverage for miscellaneous server-scoped RPC methods, including account auth state, +/// user.settings get/set/reload, agentRegistry.spawn, runtime.shutdown, sessions.open, and the /// session-scoped session.extensions.sendAttachmentsToMessage. /// /// Several of these are intentionally exercised at the wiring/guard boundary because the meaningful @@ -32,6 +33,97 @@ public async Task Should_Reload_User_Settings() await Client.Rpc.User.Settings.ReloadAsync(); } + [Fact] + public async Task Should_Get_Set_And_Clear_User_Settings() + { + await Client.StartAsync(); + + var before = await Client.Rpc.User.Settings.GetAsync(); + Assert.NotNull(before.Settings); + Assert.NotEmpty(before.Settings); + Assert.All(before.Settings, setting => + { + Assert.False(string.IsNullOrWhiteSpace(setting.Key)); + Assert.True( + setting.Value.Value.ValueKind != System.Text.Json.JsonValueKind.Undefined + || setting.Value.Default.ValueKind != System.Text.Json.JsonValueKind.Undefined, + $"Setting '{setting.Key}' should expose either a value or a default."); + }); + + var settingToToggle = before.Settings.First(setting => + setting.Value.Value.ValueKind is System.Text.Json.JsonValueKind.True or System.Text.Json.JsonValueKind.False); + var settingKey = settingToToggle.Key; + var toggledValue = settingToToggle.Value.Value.ValueKind != System.Text.Json.JsonValueKind.True; + + var set = await Client.Rpc.User.Settings.SetAsync(ParseSettingJson(settingKey, toggledValue ? "true" : "false")); + Assert.NotNull(set.ShadowedKeys); + Assert.DoesNotContain(settingKey, set.ShadowedKeys); + + await Client.Rpc.User.Settings.ReloadAsync(); + var afterSet = await Client.Rpc.User.Settings.GetAsync(); + var updatedSetting = Assert.Contains(settingKey, afterSet.Settings); + Assert.False(updatedSetting.IsDefault); + Assert.Equal(toggledValue, updatedSetting.Value.GetBoolean()); + + var clear = await Client.Rpc.User.Settings.SetAsync(ParseSettingJson(settingKey, "null")); + Assert.NotNull(clear.ShadowedKeys); + + await Client.Rpc.User.Settings.ReloadAsync(); + var afterClear = await Client.Rpc.User.Settings.GetAsync(); + var clearedSetting = Assert.Contains(settingKey, afterClear.Settings); + Assert.True(clearedSetting.IsDefault); + } + + [Fact] + public async Task Should_Login_List_GetCurrentAuth_And_Logout_Account() + { + var (client, home) = await CreateIsolatedClientAsync(autoInjectGitHubToken: false); + var login = $"rpc-account-{Guid.NewGuid():N}"; + var token = $"rpc-account-token-{Guid.NewGuid():N}"; + + try + { + await Ctx.SetCopilotUserByTokenAsync(token, new CopilotUserConfig( + Login: login, + CopilotPlan: "individual_pro", + Endpoints: new CopilotUserEndpoints(Api: Ctx.ProxyUrl, Telemetry: "https://localhost:1/telemetry"), + AnalyticsTrackingId: "rpc-account-tracking-id")); + + var initial = await client.Rpc.Account.GetCurrentAuthAsync(); + Assert.Null(initial.AuthInfo); + + var loginResult = await client.Rpc.Account.LoginAsync("https://github.com", login, token); + Assert.NotNull(loginResult); + + var current = await client.Rpc.Account.GetCurrentAuthAsync(); + Assert.Null(current.AuthErrors); + var authInfo = Assert.IsType(current.AuthInfo); + Assert.Equal("https://github.com", authInfo.Host); + Assert.Equal(login, authInfo.Login); + + var users = await client.Rpc.Account.GetAllUsersAsync(); + Assert.All(users, user => Assert.False(string.IsNullOrWhiteSpace(user.AuthInfo.Type))); + var account = users.FirstOrDefault(user => + user.AuthInfo is AuthInfoUser userAuth + && string.Equals(userAuth.Login, login, StringComparison.Ordinal)); + if (account is not null) + { + Assert.Equal(token, account.Token); + } + + var logout = await client.Rpc.Account.LogoutAsync(authInfo); + Assert.False(logout.HasMoreUsers); + + var afterLogout = await client.Rpc.Account.GetCurrentAuthAsync(); + Assert.Null(afterLogout.AuthInfo); + } + finally + { + await client.DisposeAsync(); + TryDeleteDirectory(home); + } + } + [Fact] public async Task Should_Report_Agent_Registry_Spawn_Gate_Closed() { @@ -74,7 +166,7 @@ await Harness.TestHelper.WaitForConditionAsync( async () => { try { await client.Rpc.User.Settings.ReloadAsync(); return false; } - catch { return true; } + catch (Exception ex) when (IsExpectedShutdownException(ex)) { return true; } }, timeout: TimeSpan.FromSeconds(15), pollInterval: TimeSpan.FromMilliseconds(100), @@ -82,8 +174,7 @@ await Harness.TestHelper.WaitForConditionAsync( } finally { - try { await client.DisposeAsync(); } - catch { /* process is already gone after shutdown */ } + await DisposeStoppedRuntimeClientAsync(client); } } @@ -103,7 +194,7 @@ public async Task Should_Report_Not_Found_When_Opening_Session_Without_Context() } finally { - try { await client.DisposeAsync(); } catch { /* best-effort */ } + await client.DisposeAsync(); TryDeleteDirectory(home); } } @@ -127,7 +218,8 @@ public async Task Should_Reject_Send_Attachments_From_Non_Extension_Connection() /// Creates a started client backed by a throwaway COPILOT_HOME so its session store is empty and /// independent of every other test and of the shared fixture client. /// - private async Task<(CopilotClient Client, string Home)> CreateIsolatedClientAsync() + private async Task<(CopilotClient Client, string Home)> CreateIsolatedClientAsync( + bool autoInjectGitHubToken = true) { var home = Path.Combine(Path.GetTempPath(), "copilot-e2e-misc-home-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(home); @@ -137,8 +229,22 @@ public async Task Should_Reject_Send_Attachments_From_Non_Extension_Connection() env["GH_CONFIG_DIR"] = home; env["XDG_CONFIG_HOME"] = home; env["XDG_STATE_HOME"] = home; + if (!autoInjectGitHubToken) + { + env["GH_TOKEN"] = ""; + env["GITHUB_TOKEN"] = ""; + } + + var options = new CopilotClientOptions(); + if (!autoInjectGitHubToken) + { + options.UseLoggedInUser = false; + } - var client = Ctx.CreateClient(options: new CopilotClientOptions { Environment = env }); + var client = Ctx.CreateClient( + options: options, + autoInjectGitHubToken: autoInjectGitHubToken, + environment: env); await client.StartAsync(); return (client, home); } @@ -152,9 +258,36 @@ private static void TryDeleteDirectory(string path) Directory.Delete(path, recursive: true); } } - catch + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // Temp directories are reclaimed by the OS; ignore transient locks on cleanup. } } + + private static async Task DisposeStoppedRuntimeClientAsync(CopilotClient client) + { + try + { + await client.DisposeAsync(); + } + catch (Exception ex) when (IsExpectedShutdownException(ex)) + { + // The runtime.shutdown test intentionally stops the process before disposal. + } + } + + private static bool IsExpectedShutdownException(Exception ex) => + ex is OperationCanceledException + or InvalidOperationException + or ObjectDisposedException + or IOException; + + private static System.Text.Json.JsonElement ParseJsonElement(string json) + { + using var document = System.Text.Json.JsonDocument.Parse(json); + return document.RootElement.Clone(); + } + + private static System.Text.Json.JsonElement ParseSettingJson(string key, string valueLiteral) + => ParseJsonElement("{\"" + System.Text.Json.JsonEncodedText.Encode(key) + "\":" + valueLiteral + "}"); } diff --git a/dotnet/test/E2E/RpcServerPluginsE2ETests.cs b/dotnet/test/E2E/RpcServerPluginsE2ETests.cs index 58d2cb5258..64a0f1c261 100644 --- a/dotnet/test/E2E/RpcServerPluginsE2ETests.cs +++ b/dotnet/test/E2E/RpcServerPluginsE2ETests.cs @@ -29,7 +29,7 @@ public class RpcServerPluginsE2ETests(E2ETestFixture fixture, ITestOutputHelper private const string DirectPluginName = "csharp-e2e-direct"; [Fact] - public async Task Should_Install_List_And_Uninstall_Plugin_From_Local_Marketplace() + public async Task Should_Install_And_List_Plugin_From_Local_Marketplace() { var marketplaceDir = CreateLocalMarketplaceFixture(); var (client, home) = await CreateIsolatedClientAsync(); @@ -53,10 +53,6 @@ public async Task Should_Install_List_And_Uninstall_Plugin_From_Local_Marketplac p => p.Name == PluginName && p.Marketplace == MarketplaceName); Assert.True(listed.Enabled); - await client.Rpc.Plugins.UninstallAsync(spec); - - var afterUninstall = await client.Rpc.Plugins.ListAsync(); - Assert.DoesNotContain(afterUninstall.Plugins, p => p.Name == PluginName && p.Marketplace == MarketplaceName); } finally { @@ -157,8 +153,9 @@ public async Task Should_Install_Direct_Local_Plugin_With_Deprecation_Warning() var afterInstall = await client.Rpc.Plugins.ListAsync(); Assert.Single(afterInstall.Plugins, p => p.Name == DirectPluginName); + Assert.False(string.IsNullOrEmpty(install.Plugin.DirectSourceId)); - await client.Rpc.Plugins.UninstallAsync(DirectPluginName); + await client.Rpc.Plugins.UninstallAsync(DirectPluginName, install.Plugin.DirectSourceId); var afterUninstall = await client.Rpc.Plugins.ListAsync(); Assert.DoesNotContain(afterUninstall.Plugins, p => p.Name == DirectPluginName); @@ -305,7 +302,7 @@ This skill exists so the plugin reports at least one installed skill. env["XDG_CONFIG_HOME"] = home; env["XDG_STATE_HOME"] = home; - var client = Ctx.CreateClient(options: new CopilotClientOptions { Environment = env }); + var client = Ctx.CreateClient(environment: env); await client.StartAsync(); return (client, home); } diff --git a/dotnet/test/E2E/RpcSessionStateE2ETests.cs b/dotnet/test/E2E/RpcSessionStateE2ETests.cs index 9701c5ea29..dfd76fb34f 100644 --- a/dotnet/test/E2E/RpcSessionStateE2ETests.cs +++ b/dotnet/test/E2E/RpcSessionStateE2ETests.cs @@ -46,7 +46,7 @@ public async Task Should_Call_Session_Rpc_Model_SwitchTo() await isolatedCtx.ConfigureForTestAsync("rpc_session_state", nameof(Should_Call_Session_Rpc_Model_SwitchTo)); var isolatedClient = isolatedCtx.CreateClient(); - await using var session = await isolatedClient.CreateSessionAsync(new SessionConfig + await using var session = await isolatedCtx.CreateSessionAsync(isolatedClient, new SessionConfig { Model = "claude-sonnet-4.5", OnPermissionRequest = PermissionHandler.ApproveAll, @@ -443,13 +443,13 @@ public async Task Should_Set_ReasoningEffort_And_Auto_Name() public async Task Should_Set_Auth_Credentials() { await using var client = Ctx.CreateClient(); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); var login = $"sdk-rpc-{Guid.NewGuid():N}"; - var setCredentials = await session.Rpc.Auth.SetCredentialsAsync(new AuthInfoUser + var setCredentials = await session.Rpc.GitHubAuth.SetCredentialsAsync(new AuthInfoUser { CopilotUser = new CopilotUserResponse { @@ -468,7 +468,7 @@ public async Task Should_Set_Auth_Credentials() }); Assert.True(setCredentials.Success); - var status = await session.Rpc.Auth.GetStatusAsync(); + var status = await session.Rpc.GitHubAuth.GetStatusAsync(); Assert.True(status.IsAuthenticated); Assert.Equal(AuthInfoType.User, status.AuthType); Assert.Equal("https://github.com", status.Host); diff --git a/dotnet/test/E2E/RpcSessionStateExtrasE2ETests.cs b/dotnet/test/E2E/RpcSessionStateExtrasE2ETests.cs index 5b1ce14843..28ec9b7cfe 100644 --- a/dotnet/test/E2E/RpcSessionStateExtrasE2ETests.cs +++ b/dotnet/test/E2E/RpcSessionStateExtrasE2ETests.cs @@ -11,13 +11,16 @@ namespace GitHub.Copilot.Test.E2E; /// /// E2E coverage for session-scoped RPC methods that were previously untested: -/// model.list, metadata.activity, permissions.getAllowAll/setAllowAll, plan.readSqlTodos, -/// telemetry.getEngagementId, tools.getCurrentMetadata, and the session-scoped plugins.reload. +/// completions, model.list, metadata.activity/context attribution/heaviest messages, +/// permissions.getAllowAll/setAllowAll, plan.readSqlTodos, provider.add, +/// telemetry.getEngagementId, tools.getCurrentMetadata/updateSubagentSettings, +/// session visibility, and the session-scoped plugins.reload. /// public class RpcSessionStateExtrasE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "rpc_session_state_extras", output) { [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_List_Models_For_Session() { // model.list resolves models through the session's own auth context, which requires the @@ -27,7 +30,7 @@ public async Task Should_List_Models_For_Session() const string token = "rpc-session-model-list-token"; await ConfigureAuthenticatedUserAsync(token); await using var client = CreateAuthenticatedClient(token); - await using var session = await client.CreateSessionAsync(new SessionConfig + await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig { Model = "claude-sonnet-4.5", OnPermissionRequest = PermissionHandler.ApproveAll, @@ -41,6 +44,70 @@ public async Task Should_List_Models_For_Session() Assert.Contains(result.List, model => model.GetRawText().Contains("claude-sonnet-4.5", StringComparison.Ordinal)); } + [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] + public async Task Should_Add_Byok_Provider_And_Model_At_Runtime() + { + await using var session = await CreateSessionAsync(); + var providerName = $"sdk-runtime-provider-{Guid.NewGuid():N}"; + var modelId = "sdk-runtime-model"; + var selectionId = $"{providerName}/{modelId}"; + + var added = await session.Rpc.Provider.AddAsync( + providers: + [ + new GitHub.Copilot.Rpc.NamedProviderConfig + { + Name = providerName, + Type = ProviderConfigType.Openai, + WireApi = ProviderConfigWireApi.Completions, + BaseUrl = "https://api.example.test/v1", + ApiKey = "runtime-provider-secret", + Headers = new Dictionary { ["X-SDK-Provider"] = "runtime" }, + }, + ], + models: + [ + new GitHub.Copilot.Rpc.ProviderModelConfig + { + Provider = providerName, + Id = modelId, + Name = "SDK Runtime Model", + ModelId = "claude-sonnet-4.5", + WireModel = "wire-sdk-runtime-model", + MaxContextWindowTokens = 4_096, + MaxPromptTokens = 3_072, + MaxOutputTokens = 1_024, + Capabilities = new GitHub.Copilot.Rpc.ModelCapabilitiesOverride + { + Limits = new GitHub.Copilot.Rpc.ModelCapabilitiesOverrideLimits + { + MaxContextWindowTokens = 4_096, + MaxPromptTokens = 3_072, + MaxOutputTokens = 1_024, + }, + Supports = new GitHub.Copilot.Rpc.ModelCapabilitiesOverrideSupports + { + ReasoningEffort = false, + Vision = false, + }, + }, + }, + ]); + + var addedModel = Assert.Single(added.Models); + var addedModelJson = addedModel.GetRawText(); + Assert.Contains(selectionId, addedModelJson, StringComparison.Ordinal); + Assert.Contains("SDK Runtime Model", addedModelJson, StringComparison.Ordinal); + + var listed = await session.Rpc.Model.ListAsync(); + Assert.Contains(listed.List, model => model.GetRawText().Contains(selectionId, StringComparison.Ordinal)); + + var switched = await session.Rpc.Model.SwitchToAsync(selectionId); + Assert.Equal(selectionId, switched.ModelId); + Assert.Equal(selectionId, (await session.Rpc.Model.GetCurrentAsync()).ModelId); + } + [Fact] public async Task Should_Report_Session_Activity_When_Idle() { @@ -54,6 +121,36 @@ public async Task Should_Report_Session_Activity_When_Idle() Assert.False(activity.Abortable, "Expected a freshly created session to have nothing abortable."); } + [Fact] + public async Task Should_Return_Empty_Completions_When_Host_Does_Not_Provide_Them() + { + await using var session = await CreateSessionAsync(); + + var triggers = await session.Rpc.Completions.GetTriggerCharactersAsync(); + Assert.NotNull(triggers.TriggerCharacters); + Assert.Empty(triggers.TriggerCharacters); + + var completions = await session.Rpc.Completions.RequestAsync("Use @", offset: 5); + Assert.NotNull(completions.Items); + Assert.Empty(completions.Items); + } + + [Fact] + public async Task Should_Report_Visibility_As_Unsynced_For_Local_Session() + { + await using var session = await CreateSessionAsync(); + + var initial = await session.Rpc.Visibility.GetAsync(); + Assert.False(initial.Synced); + Assert.Null(initial.Status); + Assert.Null(initial.ShareUrl); + + var set = await session.Rpc.Visibility.SetAsync(SessionVisibilityStatus.Repo); + Assert.False(set.Synced); + Assert.Null(set.Status); + Assert.Null(set.ShareUrl); + } + [Fact] public async Task Should_Get_And_Set_AllowAll_Permissions() { @@ -64,19 +161,19 @@ public async Task Should_Get_And_Set_AllowAll_Permissions() var initial = await session.Rpc.Permissions.GetAllowAllAsync(); Assert.False(initial.Enabled, "Allow-all should be disabled on a fresh session."); - var enable = await session.Rpc.Permissions.SetAllowAllAsync(true); + var enable = await session.Rpc.Permissions.SetAllowAllAsync(enabled: true); Assert.True(enable.Success); Assert.True(enable.Enabled); Assert.True((await session.Rpc.Permissions.GetAllowAllAsync()).Enabled); - var disable = await session.Rpc.Permissions.SetAllowAllAsync(false); + var disable = await session.Rpc.Permissions.SetAllowAllAsync(enabled: false); Assert.True(disable.Success); Assert.False(disable.Enabled); Assert.False((await session.Rpc.Permissions.GetAllowAllAsync()).Enabled); } finally { - await session.Rpc.Permissions.SetAllowAllAsync(false); + await session.Rpc.Permissions.SetAllowAllAsync(enabled: false); } } @@ -127,6 +224,74 @@ public async Task Should_Get_Current_Tool_Metadata_After_Initialization() }); } + [Fact] + public async Task Should_Get_Context_Attribution_And_Heaviest_Messages_After_Turn() + { + await using var session = await CreateSessionAsync(); + + var answer = await session.SendAndWaitAsync(new MessageOptions + { + Prompt = "Say CONTEXT_METADATA_OK exactly.", + }); + Assert.Contains("CONTEXT_METADATA_OK", answer?.Data.Content ?? string.Empty, StringComparison.Ordinal); + + var attribution = await session.Rpc.Metadata.GetContextAttributionAsync(); + var contextAttribution = Assert.IsType( + attribution.ContextAttribution); + Assert.True(contextAttribution.TotalTokens > 0); + Assert.True(contextAttribution.Compactions.Count >= 0); + Assert.NotEmpty(contextAttribution.Entries); + Assert.All(contextAttribution.Entries, entry => + { + Assert.False(string.IsNullOrWhiteSpace(entry.Id)); + Assert.False(string.IsNullOrWhiteSpace(entry.Kind)); + Assert.False(string.IsNullOrWhiteSpace(entry.Label)); + Assert.True(entry.Tokens >= 0); + if (entry.Attributes is not null) + { + Assert.All(entry.Attributes, attribute => Assert.False(string.IsNullOrWhiteSpace(attribute.Key))); + } + }); + + var heaviest = await session.Rpc.Metadata.GetContextHeaviestMessagesAsync(limit: 2); + Assert.True(heaviest.TotalTokens > 0); + Assert.NotNull(heaviest.Messages); + Assert.True(heaviest.Messages.Count <= 2); + Assert.All(heaviest.Messages, message => + { + Assert.False(string.IsNullOrWhiteSpace(message.Id)); + Assert.False(string.IsNullOrWhiteSpace(message.Label)); + Assert.False(string.IsNullOrWhiteSpace(message.Role)); + Assert.True(message.Tokens > 0); + }); + } + + [Fact] + public async Task Should_Update_And_Clear_Live_Subagent_Settings() + { + await using var session = await CreateSessionAsync(); + + var update = await session.Rpc.Tools.UpdateSubagentSettingsAsync(new UpdateSubagentSettingsRequestSubagents + { + Agents = new Dictionary + { + ["general-purpose"] = new() + { + Model = "claude-sonnet-4.5", + EffortLevel = "high", + ContextTier = SubagentSettingsEntryContextTier.Default, + }, + }, + DisabledSubagents = ["explore"], + MaxConcurrency = 2, + MaxDepth = 1, + }); + Assert.NotNull(update); + + var clear = await session.Rpc.Tools.UpdateSubagentSettingsAsync(); + Assert.NotNull(clear); + } + [Fact] public async Task Should_Reload_Session_Plugins() { @@ -150,9 +315,8 @@ private CopilotClient CreateAuthenticatedClient(string token) return Ctx.CreateClient(options: new CopilotClientOptions { - Environment = env, GitHubToken = token, - }); + }, environment: env); } private async Task ConfigureAuthenticatedUserAsync(string token) diff --git a/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs b/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs index fbb2892974..989fef7c55 100644 --- a/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs +++ b/dotnet/test/E2E/RpcTasksAndHandlersE2ETests.cs @@ -72,6 +72,9 @@ await AssertImplementedFailureAsync( } [Fact] + // TODO(BYOK): Provider-backed task agents handled an invalid model differently. Verify that + // BYOK model validation should reject it consistently before keeping this CAPI-only. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Report_Implemented_Error_For_Invalid_Task_Agent_Model() { var session = await CreateSessionAsync(); @@ -209,6 +212,14 @@ public async Task Should_Return_Expected_Results_For_Missing_Pending_Handler_Req response: UIAutoModeSwitchResponse.No); Assert.False(autoModeSwitch.Success); + var sessionLimits = await session.Rpc.Ui.HandlePendingSessionLimitsExhaustedAsync( + requestId: "missing-session-limits-exhausted-request", + response: new UISessionLimitsExhaustedResponse + { + Action = UISessionLimitsExhaustedResponseAction.Cancel, + }); + Assert.False(sessionLimits.Success); + var exitPlanMode = await session.Rpc.Ui.HandlePendingExitPlanModeAsync( requestId: "missing-exit-plan-mode-request", response: new UIExitPlanModeResponse @@ -251,6 +262,19 @@ public async Task Should_Return_Expected_Results_For_Missing_Pending_Handler_Req LocationKey = "missing-location", }); Assert.False(locationApproval.Success); + + var missingHeaders = await session.Rpc.Mcp.Headers.HandlePendingHeadersRefreshRequestAsync( + requestId: "missing-headers-refresh-request", + result: new McpHeadersHandlePendingHeadersRefreshRequestHeaders + { + Headers = new Dictionary { ["X-SDK-Test"] = "missing" }, + }); + Assert.False(missingHeaders.Success); + + var missingNoHeaders = await session.Rpc.Mcp.Headers.HandlePendingHeadersRefreshRequestAsync( + requestId: "missing-headers-refresh-none-request", + result: new McpHeadersHandlePendingHeadersRefreshRequestNone()); + Assert.False(missingNoHeaders.Success); } [Fact] diff --git a/dotnet/test/E2E/SessionConfigE2ETests.cs b/dotnet/test/E2E/SessionConfigE2ETests.cs index 30c7ce5007..ad313b116d 100644 --- a/dotnet/test/E2E/SessionConfigE2ETests.cs +++ b/dotnet/test/E2E/SessionConfigE2ETests.cs @@ -4,6 +4,7 @@ using GitHub.Copilot.Rpc; using GitHub.Copilot.Test.Harness; +using System.Text; using System.Text.Json; using Xunit; using Xunit.Abstractions; @@ -21,6 +22,9 @@ public class SessionConfigE2ETests(E2ETestFixture fixture, ITestOutputHelper out "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="); [Fact] + // TODO(BYOK): Anthropic Messages history diverged after enabling vision via SetModel. Verify + // that model capability overrides work for provider-backed sessions before keeping this CAPI-only. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Vision_Disabled_Then_Enabled_Via_SetModel() { await File.WriteAllBytesAsync(Path.Join(Ctx.WorkDir, "test.png"), Png1X1); @@ -61,6 +65,9 @@ await session.SetModelAsync( } [Fact] + // TODO(BYOK): Anthropic Messages history diverged after disabling vision via SetModel. Verify + // that model capability overrides work for provider-backed sessions before keeping this CAPI-only. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Vision_Enabled_Then_Disabled_Via_SetModel() { await File.WriteAllBytesAsync(Path.Join(Ctx.WorkDir, "test.png"), Png1X1); @@ -120,6 +127,7 @@ public async Task Should_Use_Custom_SessionId() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Apply_ReasoningEffort_On_Session_Create() { const string reasoningModelId = "custom-reasoning-model"; @@ -139,6 +147,7 @@ public async Task Should_Apply_ReasoningEffort_On_Session_Create() } [Theory] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] [InlineData("low")] [InlineData("medium")] [InlineData("high")] @@ -161,6 +170,7 @@ public async Task Should_Apply_All_ReasoningEffort_Values_On_Session_Create(stri } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Apply_ReasoningEffort_On_Session_Resume() { var originalSession = await CreateSessionAsync(); @@ -181,6 +191,9 @@ public async Task Should_Apply_ReasoningEffort_On_Session_Resume() } [Fact] + // TODO(BYOK): The Anthropic user-agent omitted ClientName and contained only its provider SDK + // identifier. Determine the expected propagation for custom providers before keeping this CAPI-only. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Forward_ClientName_In_UserAgent() { var session = await CreateSessionAsync(new SessionConfig @@ -197,6 +210,7 @@ public async Task Should_Forward_ClientName_In_UserAgent() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Forward_Custom_Provider_Headers_On_Create() { var session = await CreateSessionAsync(new SessionConfig @@ -216,6 +230,7 @@ public async Task Should_Forward_Custom_Provider_Headers_On_Create() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Forward_Custom_Provider_Headers_On_Resume() { var session1 = await CreateSessionAsync(); @@ -238,6 +253,7 @@ public async Task Should_Forward_Custom_Provider_Headers_On_Resume() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Forward_Provider_Wire_Model() { // Verifies that ProviderConfig.WireModel overrides the model name sent to @@ -269,6 +285,7 @@ public async Task Should_Forward_Provider_Wire_Model() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Use_Provider_Model_Id_As_Wire_Model() { // ProviderConfig.ModelId drives both the runtime resolved model AND the wire model @@ -449,6 +466,201 @@ public async Task Should_Apply_AvailableTools_On_Session_Resume() } [Fact] + public async Task Should_Apply_Session_Limits_On_Create() + { + var session = await CreateSessionAsync(new SessionConfig + { + SessionLimits = new SessionLimitsConfig + { + MaxAiCredits = 30, + }, + }); + + try + { + var exchange = await SendAndGetNextExchangeAsync( + session, + "Acknowledge the current session limits."); + + AssertSessionLimitsStatus(exchange, "30 AI credits"); + } + finally + { + await session.DisposeAsync(); + } + } + + [Fact] + public async Task Should_Apply_Session_Limits_On_Resume() + { + var session1 = await CreateSessionAsync(); + var session2 = await ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + { + SessionLimits = new SessionLimitsConfig + { + MaxAiCredits = 30, + }, + }); + + try + { + var exchange = await SendAndGetNextExchangeAsync( + session2, + "Acknowledge the current session limits."); + + AssertSessionLimitsStatus(exchange, "30 AI credits"); + } + finally + { + await session2.DisposeAsync(); + await session1.DisposeAsync(); + } + } + + [Fact] + public async Task Should_Apply_Excluded_Built_In_Agents_On_Create() + { + const string excludedAgent = "explore"; + const string prompt = "What is 1+1?"; + + var baselineSession = await CreateSessionAsync(); + try + { + var baselineExchange = await SendAndGetNextExchangeAsync(baselineSession, prompt); + Assert.Contains(excludedAgent, GetTaskAgentTypes(baselineExchange)); + } + finally + { + await baselineSession.DisposeAsync(); + } + + var excludedSession = await CreateSessionAsync(new SessionConfig + { + ExcludedBuiltInAgents = [excludedAgent], + }); + + try + { + var excludedExchange = await SendAndGetNextExchangeAsync(excludedSession, prompt); + var agentTypes = GetTaskAgentTypes(excludedExchange); + + Assert.NotEmpty(agentTypes); + Assert.DoesNotContain(excludedAgent, agentTypes); + } + finally + { + await excludedSession.DisposeAsync(); + } + } + + [Fact] + public async Task Should_Apply_Excluded_Built_In_Agents_On_Resume() + { + const string excludedAgent = "explore"; + + var session1 = await CreateSessionAsync(); + var session2 = await ResumeSessionAsync(session1.SessionId, new ResumeSessionConfig + { + ExcludedBuiltInAgents = [excludedAgent], + }); + + try + { + var exchange = await SendAndGetNextExchangeAsync(session2, "What is 1+1?"); + var agentTypes = GetTaskAgentTypes(exchange); + + Assert.NotEmpty(agentTypes); + Assert.DoesNotContain(excludedAgent, agentTypes); + } + finally + { + await session2.DisposeAsync(); + await session1.DisposeAsync(); + } + } + + [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] + public async Task Should_Enable_Citations_For_Anthropic_File_Attachments_On_Create() + { + var handler = new RecordingRequestHandler(); + await using var client = CreateClientWithRequestHandler(handler); + await client.StartAsync(); + + var session = await Ctx.CreateSessionAsync(client, new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + Model = "claude-sonnet-4.5", + EnableCitations = true, + Provider = CreateAnthropicProvider(), + }); + + try + { + await session.SendAndWaitAsync(new MessageOptions + { + Prompt = "Summarize the attached PDF with citations enabled.", + Attachments = [CreatePdfAttachment()], + }); + + AssertAnthropicDocumentCitationsEnabled(Assert.Single(handler.InferenceRequests).Body); + } + finally + { + await session.DisposeAsync(); + } + } + + [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] + public async Task Should_Enable_Citations_For_Anthropic_File_Attachments_On_Resume() + { + const string connectionToken = "citation-resume-token"; + var handler = new RecordingRequestHandler(); + await using var client = CreateClientWithRequestHandler( + handler, + RuntimeConnection.ForTcp(connectionToken: connectionToken)); + await client.StartAsync(); + + var session1 = await Ctx.CreateSessionAsync(client, new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + }); + var sessionId = session1.SessionId; + var port = client.RuntimePort + ?? throw new InvalidOperationException("The handler-backed E2E client must use TCP transport to support multi-client resume."); + await using var resumeClient = Ctx.CreateClient(options: new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri($"localhost:{port}", connectionToken: connectionToken), + }); + + var session2 = await Ctx.ResumeSessionAsync(resumeClient, sessionId, new ResumeSessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + Model = "claude-sonnet-4.5", + EnableCitations = true, + Provider = CreateAnthropicProvider(), + }); + + try + { + await session2.SendAndWaitAsync(new MessageOptions + { + Prompt = "Summarize the attached PDF with citations enabled.", + Attachments = [CreatePdfAttachment()], + }); + + AssertAnthropicDocumentCitationsEnabled(Assert.Single(handler.InferenceRequests).Body); + } + finally + { + await session2.DisposeAsync(); + await session1.DisposeAsync(); + } + } + + [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Create_Session_With_Custom_Provider_Config() { // Per the TS test (session_config.e2e.test.ts), this only verifies that a @@ -476,6 +688,9 @@ public async Task Should_Create_Session_With_Custom_Provider_Config() } [Fact] + // TODO(BYOK): Anthropic Messages request history diverged while replaying this blob attachment. + // Confirm native clients preserve blob/image turns before keeping this CAPI-only. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Accept_Blob_Attachments() { // Write the image to disk so the model can view it if it tries @@ -542,6 +757,95 @@ private static bool HasImageUrlContent(List messages) typeProp.GetString() == "image_url")); } + private CopilotClient CreateClientWithRequestHandler( + CopilotRequestHandler handler, + RuntimeConnection? connection = null) + { + return Ctx.CreateClient(options: new CopilotClientOptions + { + Connection = connection ?? RuntimeConnection.ForStdio(), + RequestHandler = handler, + }); + } + + private async Task SendAndGetNextExchangeAsync(CopilotSession session, string prompt) + { + var existingCount = (await Ctx.GetExchangesAsync()).Count; + var exchanges = await SendAndWaitForExchangesAsync( + session, + new MessageOptions { Prompt = prompt }, + minimumCount: existingCount + 1); + return exchanges[existingCount]; + } + + private static void AssertSessionLimitsStatus(ParsedHttpExchange exchange, string expectedRemaining) + { + var message = exchange.Request.Messages.SingleOrDefault(m => + m.Role == "user" + && m.StringContent?.Contains("", StringComparison.Ordinal) == true); + + Assert.NotNull(message); + Assert.Contains($"Remaining session limits: {expectedRemaining}.", message!.StringContent); + Assert.Contains( + "Be frugal; avoid optional exploration and unnecessary tool calls.", + message.StringContent); + } + + private static IReadOnlyList GetTaskAgentTypes(ParsedHttpExchange exchange) + { + var taskTool = Assert.Single( + exchange.Request.Tools ?? [], + tool => string.Equals(tool.Function.Name, "task", StringComparison.Ordinal)); + var parameters = taskTool.Function.Parameters; + + Assert.NotNull(parameters); + var enumValues = parameters!.Value + .GetProperty("properties") + .GetProperty("agent_type") + .GetProperty("enum"); + + return [.. enumValues.EnumerateArray().Select(value => value.GetString()).OfType()]; + } + + private static AttachmentBlob CreatePdfAttachment() + { + const string pdfText = "%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n"; + + return new AttachmentBlob + { + Data = Convert.ToBase64String(Encoding.ASCII.GetBytes(pdfText)), + DisplayName = "citation-source.pdf", + MimeType = "application/pdf", + }; + } + + private static ProviderConfig CreateAnthropicProvider() + { + return new ProviderConfig + { + Type = "anthropic", + BaseUrl = "https://anthropic-citations.invalid/v1", + ApiKey = "test-provider-key", + ModelId = "claude-sonnet-4.5", + WireModel = "claude-sonnet-4.5", + }; + } + + private static void AssertAnthropicDocumentCitationsEnabled(string requestBody) + { + using var document = JsonDocument.Parse(requestBody); + var documentBlocks = document.RootElement + .GetProperty("messages") + .EnumerateArray() + .SelectMany(message => message.GetProperty("content").EnumerateArray()) + .Where(block => block.GetProperty("type").GetString() == "document") + .ToList(); + + var documentBlock = Assert.Single(documentBlocks); + Assert.Equal("citation-source.pdf", documentBlock.GetProperty("title").GetString()); + Assert.True(documentBlock.GetProperty("citations").GetProperty("enabled").GetBoolean()); + } + private ProviderConfig CreateProxyProvider(string headerValue) { return new ProviderConfig diff --git a/dotnet/test/E2E/SessionE2ETests.cs b/dotnet/test/E2E/SessionE2ETests.cs index 979144b6e9..bcc8fc268d 100644 --- a/dotnet/test/E2E/SessionE2ETests.cs +++ b/dotnet/test/E2E/SessionE2ETests.cs @@ -34,7 +34,7 @@ public async Task ShouldCreateAndDisconnectSessions() [Fact] public async Task Should_Have_Stateful_Conversation() { - var session = await CreateSessionAsync(); + await using var session = await CreateSessionAsync(); var assistantMessage = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 1+1?" }); Assert.NotNull(assistantMessage); @@ -232,7 +232,7 @@ public async Task Should_Reject_Resuming_Active_Session_Using_The_Same_Client() var sessionId = session1.SessionId; var exception = await Assert.ThrowsAsync(() => - Client.ResumeSessionAsync(sessionId, new ResumeSessionConfig + Ctx.ResumeSessionAsync(Client, sessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, })); @@ -251,7 +251,7 @@ public async Task Should_Resume_A_Session_Using_A_New_Client() Assert.Contains("2", answer!.Data.Content ?? string.Empty); using var newClient = Ctx.CreateClient(); - var session2 = await newClient.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(newClient, sessionId, new ResumeSessionConfig { ContinuePendingWork = true, OnPermissionRequest = PermissionHandler.ApproveAll, @@ -269,6 +269,33 @@ public async Task Should_Resume_A_Session_Using_A_New_Client() Assert.Contains("4", answer2!.Data.Content ?? string.Empty); } + [Fact] + public async Task Resumes_A_Persisted_Session_From_A_New_Client_When_An_Mcp_OAuth_Handler_Is_Configured() + { + static Task CancelMcpAuthAsync(McpAuthContext request) + => Task.FromResult(McpAuthResult.Cancel()); + + await using var session1 = await CreateSessionAsync(new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnMcpAuthRequest = CancelMcpAuthAsync, + }); + var sessionId = session1.SessionId; + + var answer = await session1.SendAndWaitAsync(new MessageOptions { Prompt = "What is 1+1?" }); + Assert.NotNull(answer); + Assert.Contains("2", answer!.Data.Content ?? string.Empty); + + using var newClient = Ctx.CreateClient(); + await using var session2 = await Ctx.ResumeSessionAsync(newClient, sessionId, new ResumeSessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnMcpAuthRequest = CancelMcpAuthAsync, + }); + + Assert.Equal(sessionId, session2.SessionId); + } + [Fact] public async Task Should_Throw_Error_When_Resuming_Non_Existent_Session() { @@ -689,20 +716,25 @@ public async Task DisposeAsync_From_Handler_Does_Not_Deadlock() session.On(evt => { - if (evt is UserMessageEvent) + if (evt is SessionInfoEvent) { // Call DisposeAsync from within a handler — must not deadlock. session.DisposeAsync().AsTask().ContinueWith(_ => disposed.TrySetResult()); } }); - await session.SendAsync(new MessageOptions { Prompt = "What is 1+1?" }); + await session.LogAsync("Dispose from handler trigger"); // If this times out, we deadlocked. await disposed.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + await Client.ForceStopAsync(); } [Fact] + // TODO(BYOK): Anthropic Messages request history diverged while replaying this blob attachment. + // Confirm native clients preserve blob/image turns before keeping this CAPI-only. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Accept_Blob_Attachments() { var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; @@ -893,6 +925,7 @@ await session.SendAndWaitAsync(new MessageOptions } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Create_Session_With_Custom_Provider() { var session = await CreateSessionAsync(new SessionConfig @@ -918,6 +951,7 @@ public async Task Should_Create_Session_With_Custom_Provider() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Create_Session_With_Azure_Provider() { var session = await CreateSessionAsync(new SessionConfig @@ -947,6 +981,7 @@ public async Task Should_Create_Session_With_Azure_Provider() } [Fact] + [Trait(E2ETestTraits.Backend, E2ETestTraits.SelfConfiguredBackend)] public async Task Should_Resume_Session_With_Custom_Provider() { var session = await CreateSessionAsync(); diff --git a/dotnet/test/E2E/SessionFsE2ETests.cs b/dotnet/test/E2E/SessionFsE2ETests.cs index b1b4848adc..cf91e3ddc8 100644 --- a/dotnet/test/E2E/SessionFsE2ETests.cs +++ b/dotnet/test/E2E/SessionFsE2ETests.cs @@ -28,7 +28,7 @@ public async Task Should_Route_File_Operations_Through_The_Session_Fs_Provider() { await using var client = CreateSessionFsClient(providerRoot); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = s => new TestSessionFsHandler(s.SessionId, providerRoot), @@ -58,7 +58,7 @@ public async Task Should_Load_Session_Data_From_Fs_Provider_On_Resume() await using var client = CreateSessionFsClient(providerRoot); Func createSessionFsHandler = s => new TestSessionFsHandler(s.SessionId, providerRoot); - var session1 = await client.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = createSessionFsHandler, @@ -72,7 +72,7 @@ public async Task Should_Load_Session_Data_From_Fs_Provider_On_Resume() var eventsPath = GetStoredPath(providerRoot, sessionId, $"{SessionFsConfig.SessionStatePath}/events.jsonl"); await WaitForConditionAsync(() => File.Exists(eventsPath)); - var session2 = await client.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(client, sessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = createSessionFsHandler, @@ -97,7 +97,7 @@ public async Task Should_Reject_SetProvider_When_Sessions_Already_Exist() await using var client1 = CreateSessionFsClient(providerRoot, useStdio: false, tcpConnectionToken: "session-fs-shared-token"); var createSessionFsHandler = (Func)(s => new TestSessionFsHandler(s.SessionId, providerRoot)); - _ = await client1.CreateSessionAsync(new SessionConfig + _ = await Ctx.CreateSessionAsync(client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = createSessionFsHandler, @@ -319,7 +319,7 @@ public async Task Should_Map_Large_Output_Handling_Into_SessionFs() var suppliedFileContent = new string('x', largeContentSize); await using var client = CreateSessionFsClient(providerRoot); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = s => new TestSessionFsHandler(s.SessionId, providerRoot), @@ -361,7 +361,7 @@ public async Task Should_Succeed_With_Compaction_While_Using_SessionFs() try { await using var client = CreateSessionFsClient(providerRoot); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = s => new TestSessionFsHandler(s.SessionId, providerRoot), @@ -400,7 +400,7 @@ public async Task Should_Write_Workspace_Metadata_Via_SessionFs() try { await using var client = CreateSessionFsClient(providerRoot); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = s => new TestSessionFsHandler(s.SessionId, providerRoot), @@ -433,7 +433,7 @@ public async Task Should_Persist_Plan_Md_Via_SessionFs() try { await using var client = CreateSessionFsClient(providerRoot); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = s => new TestSessionFsHandler(s.SessionId, providerRoot), diff --git a/dotnet/test/E2E/SessionFsSqliteE2ETests.cs b/dotnet/test/E2E/SessionFsSqliteE2ETests.cs index 1e6175f9c4..8ed86c72e3 100644 --- a/dotnet/test/E2E/SessionFsSqliteE2ETests.cs +++ b/dotnet/test/E2E/SessionFsSqliteE2ETests.cs @@ -31,7 +31,7 @@ public async Task Should_Route_Sql_Queries_Through_The_Sessionfs_Sqlite_Handler( { await using var client = CreateSessionFsClient(); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = s => new InMemorySessionFsSqliteHandler(s.SessionId, _sqliteCalls), @@ -65,7 +65,7 @@ public async Task Should_Allow_Subagents_To_Use_Sql_Tool_Via_Inherited_Sessionfs await using var client = CreateSessionFsClient(); var handler = (InMemorySessionFsSqliteHandler?)null; - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, CreateSessionFsProvider = s => @@ -117,9 +117,9 @@ await TestHelper.WaitForConditionAsync( private CopilotClient CreateSessionFsClient() { return Ctx.CreateClient( - useStdio: true, options: new CopilotClientOptions { + Connection = RuntimeConnection.ForStdio(), SessionFs = SessionFsConfig, }); } diff --git a/dotnet/test/E2E/StreamingFidelityE2ETests.cs b/dotnet/test/E2E/StreamingFidelityE2ETests.cs index fec00f1cb1..4df9ca4420 100644 --- a/dotnet/test/E2E/StreamingFidelityE2ETests.cs +++ b/dotnet/test/E2E/StreamingFidelityE2ETests.cs @@ -2,6 +2,7 @@ * Copyright (c) Microsoft Corporation. All rights reserved. *--------------------------------------------------------------------------------------------*/ +using GitHub.Copilot.Test.Harness; using Xunit; using Xunit.Abstractions; @@ -46,6 +47,9 @@ public async Task Should_Produce_Delta_Events_When_Streaming_Is_Enabled() } [Fact] + // TODO(BYOK): Anthropic Messages emitted delta events with Streaming=false. Investigate the + // native-client streaming contract before keeping this disabled for every BYOK backend. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Not_Produce_Deltas_When_Streaming_Is_Disabled() { var session = await CreateSessionAsync(new SessionConfig { Streaming = false }); @@ -79,7 +83,7 @@ public async Task Should_Produce_Deltas_After_Session_Resume() // Resume using a new client using var newClient = Ctx.CreateClient(); - var session2 = await newClient.ResumeSessionAsync(session.SessionId, + var session2 = await Ctx.ResumeSessionAsync(newClient, session.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Streaming = true }); var events = new List(); @@ -106,6 +110,9 @@ public async Task Should_Produce_Deltas_After_Session_Resume() } [Fact] + // TODO(BYOK): Anthropic Messages emitted delta events after resuming with Streaming=false. + // Investigate the native-client streaming contract before keeping this disabled for every BYOK backend. + [Trait(E2ETestTraits.Backend, E2ETestTraits.CapiOnly)] public async Task Should_Not_Produce_Deltas_After_Session_Resume_With_Streaming_Disabled() { var session = await CreateSessionAsync(new SessionConfig { Streaming = true }); @@ -114,7 +121,7 @@ public async Task Should_Not_Produce_Deltas_After_Session_Resume_With_Streaming_ // Resume using a new client with streaming DISABLED using var newClient = Ctx.CreateClient(); - var session2 = await newClient.ResumeSessionAsync(session.SessionId, + var session2 = await Ctx.ResumeSessionAsync(newClient, session.SessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Streaming = false }); var events = new List(); diff --git a/dotnet/test/E2E/SubagentHooksE2ETests.cs b/dotnet/test/E2E/SubagentHooksE2ETests.cs index 5c85432152..8314b8c098 100644 --- a/dotnet/test/E2E/SubagentHooksE2ETests.cs +++ b/dotnet/test/E2E/SubagentHooksE2ETests.cs @@ -3,12 +3,15 @@ *--------------------------------------------------------------------------------------------*/ using System.Collections.Concurrent; +using System.Net.Http; using GitHub.Copilot.Test.Harness; using Xunit; using Xunit.Abstractions; namespace GitHub.Copilot.Test.E2E; +#pragma warning disable GHCP001 // The LLM inference surface is intentionally experimental. + public class SubagentHooksE2ETests(E2ETestFixture fixture, ITestOutputHelper output) : E2ETestBase(fixture, "subagent_hooks", output) { @@ -16,13 +19,18 @@ public class SubagentHooksE2ETests(E2ETestFixture fixture, ITestOutputHelper out public async Task Should_Invoke_PreToolUse_And_PostToolUse_Hooks_For_Sub_Agent_Tool_Calls() { var hookLog = new ConcurrentBag<(string Kind, string ToolName, string SessionId)>(); + var requestHandler = new RecordingForwardingRequestHandler(); // Create a client with the session-based subagents feature flag var env = new Dictionary(Ctx.GetEnvironment()); env["COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS"] = "true"; - var client = Ctx.CreateClient(options: new CopilotClientOptions { Environment = env }); + var client = Ctx.CreateClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForStdio(), + RequestHandler = requestHandler + }, environment: env); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, Hooks = new SessionHooks @@ -44,7 +52,7 @@ public async Task Should_Invoke_PreToolUse_And_PostToolUse_Hooks_For_Sub_Agent_T }); // Create a file for the sub-agent to read - await File.WriteAllTextAsync(Path.Combine(Ctx.WorkDir, "subagent-test.txt"), "Hello from subagent test!"); + await File.WriteAllTextAsync(Path.Join(Ctx.WorkDir, "subagent-test.txt"), "Hello from subagent test!"); await session.SendAndWaitAsync( new MessageOptions @@ -69,5 +77,42 @@ await session.SendAndWaitAsync( // input.SessionId distinguishes parent from sub-agent Assert.NotEqual(viewPre[0].SessionId, taskPre[0].SessionId); + AssertSubagentRequestMetadata(requestHandler.InferenceRequests); + } + + private static void AssertSubagentRequestMetadata(IReadOnlyCollection records) + { + Assert.NotEmpty(records); + var subagentRequest = records.FirstOrDefault(r => !string.IsNullOrEmpty(r.ParentAgentId)); + Assert.NotNull(subagentRequest); + Assert.False(string.IsNullOrEmpty(subagentRequest.AgentId), + "Sub-agent inference request should carry an agent id"); + Assert.False(string.IsNullOrEmpty(subagentRequest.InteractionType), + "Sub-agent inference request should carry an interaction type"); + Assert.NotEqual(subagentRequest.ParentAgentId, subagentRequest.AgentId); + } + + private sealed class RecordingForwardingRequestHandler : CopilotRequestHandler + { + private readonly ConcurrentBag _records = []; + + public IReadOnlyCollection InferenceRequests => + [.. _records.Where(r => RecordingRequestHandler.IsInferenceUrl(r.Url))]; + + protected override Task SendRequestAsync(HttpRequestMessage request, CopilotRequestContext ctx) + { + _records.Add(new RequestRecord( + request.RequestUri!.ToString(), + ctx.AgentId, + ctx.ParentAgentId, + ctx.InteractionType)); + return base.SendRequestAsync(request, ctx); + } } + + private sealed record RequestRecord( + string Url, + string? AgentId, + string? ParentAgentId, + string? InteractionType); } diff --git a/dotnet/test/E2E/SuspendE2ETests.cs b/dotnet/test/E2E/SuspendE2ETests.cs index f531f0e59c..b88a9897be 100644 --- a/dotnet/test/E2E/SuspendE2ETests.cs +++ b/dotnet/test/E2E/SuspendE2ETests.cs @@ -58,7 +58,7 @@ public async Task Should_Allow_Resume_And_Continue_Conversation_After_Suspend() string sessionId; await using (var client1 = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: sharedToken) })) { - var session1 = await client1.CreateSessionAsync(new SessionConfig + var session1 = await Ctx.CreateSessionAsync(client1, new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); @@ -78,7 +78,7 @@ await session1.SendAndWaitAsync(new MessageOptions // A different client should be able to pick the session back up. The previous // turn was completed before suspend, so there is no pending work to continue. await using var client2 = Ctx.CreateClient(options: new CopilotClientOptions { Connection = RuntimeConnection.ForUri(cliUrl, connectionToken: sharedToken) }); - var session2 = await client2.ResumeSessionAsync(sessionId, new ResumeSessionConfig + var session2 = await Ctx.ResumeSessionAsync(client2, sessionId, new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll, }); diff --git a/dotnet/test/E2E/TelemetryExportE2ETests.cs b/dotnet/test/E2E/TelemetryExportE2ETests.cs index 22ed5663d0..48e3b53ad6 100644 --- a/dotnet/test/E2E/TelemetryExportE2ETests.cs +++ b/dotnet/test/E2E/TelemetryExportE2ETests.cs @@ -24,6 +24,7 @@ public async Task Should_Export_File_Telemetry_For_Sdk_Interactions() await using var client = Ctx.CreateClient(options: new CopilotClientOptions { + Connection = RuntimeConnection.ForStdio(), Telemetry = new TelemetryConfig { FilePath = telemetryPath, @@ -33,7 +34,7 @@ public async Task Should_Export_File_Telemetry_For_Sdk_Interactions() }, }); - var session = await client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(client, new SessionConfig { Tools = [AIFunctionFactory.Create(EchoTelemetryMarker, toolName, "Echoes a marker string for telemetry validation.")], OnPermissionRequest = PermissionHandler.ApproveAll, diff --git a/dotnet/test/E2E/ToolsE2ETests.cs b/dotnet/test/E2E/ToolsE2ETests.cs index 7424cfa3a3..ea615fbc4a 100644 --- a/dotnet/test/E2E/ToolsE2ETests.cs +++ b/dotnet/test/E2E/ToolsE2ETests.cs @@ -306,7 +306,7 @@ public async Task Invokes_Custom_Tool_With_Permission_Handler() { var permissionRequests = new List(); - var session = await Client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(Client, new SessionConfig { Tools = [AIFunctionFactory.Create(EncryptStringForPermission, "encrypt_string")], OnPermissionRequest = (request, invocation) => @@ -340,7 +340,7 @@ public async Task Denies_Custom_Tool_When_Permission_Denied() { var toolHandlerCalled = false; - var session = await Client.CreateSessionAsync(new SessionConfig + var session = await Ctx.CreateSessionAsync(Client, new SessionConfig { Tools = [AIFunctionFactory.Create(EncryptStringDenied, "encrypt_string")], OnPermissionRequest = async (request, invocation) => PermissionDecision.Reject(), diff --git a/dotnet/test/Harness/E2ETestBackend.cs b/dotnet/test/Harness/E2ETestBackend.cs new file mode 100644 index 0000000000..04808ed7a9 --- /dev/null +++ b/dotnet/test/Harness/E2ETestBackend.cs @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +namespace GitHub.Copilot.Test.Harness; + +internal enum E2ETestBackend +{ + Capi, + AnthropicMessages, + OpenAIResponses, + OpenAICompletions, +} + +internal static class E2ETestBackendConfiguration +{ + internal const string EnvironmentVariable = "COPILOT_SDK_E2E_BACKEND"; + private const string AnthropicDefaultModel = "claude-sonnet-4.5"; + private const string OpenAIDefaultModel = "gpt-4.1"; + private const string FakeCredential = "fake-byok-credential-for-e2e-tests"; + + internal static E2ETestBackend Current + => Parse(Environment.GetEnvironmentVariable(EnvironmentVariable)); + + internal static E2ETestBackend Parse(string? value) + => value?.Trim().ToLowerInvariant() switch + { + null or "" or "capi" => E2ETestBackend.Capi, + "anthropic-messages" => E2ETestBackend.AnthropicMessages, + "openai-responses" => E2ETestBackend.OpenAIResponses, + "openai-completions" => E2ETestBackend.OpenAICompletions, + _ => throw new ArgumentOutOfRangeException( + nameof(value), + value, + $"Unsupported {EnvironmentVariable} value. Expected capi, anthropic-messages, openai-responses, or openai-completions."), + }; + + internal static string ToWireName(this E2ETestBackend backend) + => backend switch + { + E2ETestBackend.Capi => "capi", + E2ETestBackend.AnthropicMessages => "anthropic-messages", + E2ETestBackend.OpenAIResponses => "openai-responses", + E2ETestBackend.OpenAICompletions => "openai-completions", + _ => throw new ArgumentOutOfRangeException(nameof(backend), backend, null), + }; + + internal static void ApplyProvider( + this E2ETestBackend backend, + SessionConfig config, + string proxyUrl) + { + if (backend == E2ETestBackend.Capi + || config.Provider is not null + || config.Providers is not null) + { + return; + } + + var model = config.Model ??= backend.GetDefaultModel(); + config.Provider = CreateProvider(backend, proxyUrl, model); + } + + internal static void ApplyProvider( + this E2ETestBackend backend, + ResumeSessionConfig config, + string proxyUrl) + { + if (backend == E2ETestBackend.Capi || config.Provider is not null) + { + return; + } + + var model = config.Model ??= backend.GetDefaultModel(); + config.Provider = CreateProvider(backend, proxyUrl, model); + } + + private static string GetDefaultModel(this E2ETestBackend backend) + => backend switch + { + E2ETestBackend.AnthropicMessages => AnthropicDefaultModel, + E2ETestBackend.OpenAIResponses or E2ETestBackend.OpenAICompletions => OpenAIDefaultModel, + _ => throw new ArgumentOutOfRangeException(nameof(backend), backend, null), + }; + + private static ProviderConfig CreateProvider( + E2ETestBackend backend, + string proxyUrl, + string model) + => new() + { + BaseUrl = proxyUrl, + Type = backend switch + { + E2ETestBackend.AnthropicMessages => "anthropic", + E2ETestBackend.OpenAIResponses or E2ETestBackend.OpenAICompletions => "openai", + _ => throw new ArgumentOutOfRangeException(nameof(backend), backend, null), + }, + WireApi = backend switch + { + E2ETestBackend.AnthropicMessages => null, + E2ETestBackend.OpenAIResponses => "responses", + E2ETestBackend.OpenAICompletions => "completions", + _ => throw new ArgumentOutOfRangeException(nameof(backend), backend, null), + }, + BearerToken = FakeCredential, + ModelId = model, + WireModel = model, + }; +} + +internal static class E2ETestTraits +{ + // Trait key used by workflow filters to classify backend compatibility. + internal const string Backend = "E2EBackend"; + + // Requires the default CAPI backend and is excluded from BYOK legs. + internal const string CapiOnly = "CapiOnly"; + + // Owns its backend setup and must not inherit the backend selected by the test matrix. + internal const string SelfConfiguredBackend = "SelfConfiguredBackend"; +} diff --git a/dotnet/test/Harness/E2ETestBase.cs b/dotnet/test/Harness/E2ETestBase.cs index ddd1b894bb..a3006389bb 100644 --- a/dotnet/test/Harness/E2ETestBase.cs +++ b/dotnet/test/Harness/E2ETestBase.cs @@ -76,7 +76,7 @@ protected Task CreateSessionAsync(SessionConfig? config = null) { config ??= new SessionConfig(); config.OnPermissionRequest ??= PermissionHandler.ApproveAll; - return Client.CreateSessionAsync(config); + return Ctx.CreateSessionAsync(Client, config); } /// @@ -96,7 +96,7 @@ protected async Task ResumeSessionAsync(string sessionId, Resume { Connection = RuntimeConnection.ForUri($"localhost:{port}", connectionToken: E2ETestFixture.SharedTcpConnectionToken), }); - return await client.ResumeSessionAsync(sessionId, config); + return await Ctx.ResumeSessionAsync(client, sessionId, config); } protected static string GetSystemMessage(ParsedHttpExchange exchange) diff --git a/dotnet/test/Harness/E2ETestContext.cs b/dotnet/test/Harness/E2ETestContext.cs index 2e2043183a..c01f4efcff 100644 --- a/dotnet/test/Harness/E2ETestContext.cs +++ b/dotnet/test/Harness/E2ETestContext.cs @@ -20,13 +20,13 @@ public sealed class E2ETestContext : IAsyncDisposable /// Optional logger injected by tests; applied to all clients created via . public ILogger? Logger { get; set; } - private readonly CapiProxy _proxy; + private readonly ReplayProxy _proxy; private readonly string _repoRoot; private readonly object _clientsLock = new(); private readonly List _persistentClients = []; private readonly List _transientClients = []; - private E2ETestContext(string homeDir, string workDir, string proxyUrl, CapiProxy proxy, string repoRoot) + private E2ETestContext(string homeDir, string workDir, string proxyUrl, ReplayProxy proxy, string repoRoot) { HomeDir = homeDir; WorkDir = workDir; @@ -50,7 +50,7 @@ public static async Task CreateAsync() homeDir = ResolveSymlinks(homeDir); workDir = ResolveSymlinks(workDir); - var proxy = new CapiProxy(); + var proxy = new ReplayProxy(); var proxyUrl = await proxy.StartAsync(); await proxy.SetCopilotUserByTokenAsync(DefaultGitHubToken, new CopilotUserConfig( Login: "e2e-test-user", @@ -163,7 +163,10 @@ public async Task ConfigureForTestAsync(string testFile, [CallerMemberName] stri // to avoid case collisions on case-insensitive filesystems (macOS/Windows) var sanitizedName = Regex.Replace(testName!, @"[^a-zA-Z0-9]", "_").ToLowerInvariant(); var snapshotPath = Path.Combine(_repoRoot, "test", "snapshots", testFile, $"{sanitizedName}.yaml"); - await _proxy.ConfigureAsync(snapshotPath, WorkDir); + await _proxy.ConfigureAsync( + snapshotPath, + WorkDir, + E2ETestBackendConfiguration.Current.ToWireName()); } public Task> GetExchangesAsync() @@ -192,6 +195,8 @@ public Dictionary GetEnvironment() env["GH_CONFIG_DIR"] = HomeDir; env["XDG_CONFIG_HOME"] = HomeDir; env["XDG_STATE_HOME"] = HomeDir; + env["COPILOT_MCP_APPS"] = "true"; + env["MCP_APPS"] = "true"; if (!string.IsNullOrEmpty(_proxy.ConnectProxyUrl) && !string.IsNullOrEmpty(_proxy.CaFilePath)) { const string noProxy = "127.0.0.1,localhost,::1"; @@ -214,6 +219,16 @@ public Dictionary GetEnvironment() env["GITHUB_TOKEN"] = env["GH_TOKEN"] = DefaultGitHubToken; + // Disable HMAC auth for E2E runs. CI sets COPILOT_HMAC_KEY at the job + // level as an ambient credential, but the replay snapshots are captured + // against Bearer/OAuth (SDK-token) requests. In stdio the SDK token + // outranks HMAC so this is a no-op, but in-process auth resolution runs + // host-side in this process and would otherwise pick HMAC (which ranks + // above the GitHub token) and fail provider.getEndpoint. An empty value + // disables the method (runtime filters out empty HMAC keys). + env["COPILOT_HMAC_KEY"] = ""; + env["CAPI_HMAC_KEY"] = ""; + return env!; } @@ -225,41 +240,97 @@ public Dictionary GetEnvironment() } public CopilotClient CreateClient( - bool? useStdio = null, CopilotClientOptions? options = null, bool autoInjectGitHubToken = true, - bool persistent = false) + bool persistent = false, + IReadOnlyDictionary? environment = null) { options ??= new CopilotClientOptions(); - options.WorkingDirectory ??= WorkDir; - options.Environment ??= GetEnvironment(); options.Logger ??= Logger; - // Build the connection. If the caller supplied one, just ensure the runtime path is set; - // otherwise default to Stdio with the bundled runtime (matches CopilotClient's own default). - // useStdio is a convenience shortcut for the no-Connection case; passing both is ambiguous. - if (useStdio is not null && options.Connection is not null) + // Resolve the working directory the worker should run in. Child-process and + // URI transports take it as a per-client option; the in-process transport + // rejects a per-client WorkingDirectory (the native host spawns the worker + // without a cwd parameter), so — mirroring the Node/Rust harnesses — we point + // THIS process's cwd at the desired directory before the worker spawns and + // clear the per-client option. InProcessEnvIsolationAttribute.After restores + // the cwd after the test. + var desiredWorkingDirectory = options.WorkingDirectory ?? WorkDir; + + // Tests must supply environment via the 'environment' parameter, which the + // harness routes to the right place per transport (the connection for + // child-process transports, the host process for in-process). Setting + // options.Environment directly bypasses that routing and is unsupported + // in-process, so reject it here. + if (options.Environment is not null) { throw new ArgumentException( - "Specify either useStdio or options.Connection, not both. " + - "Use options.Connection (e.g. RuntimeConnection.ForStdio() / RuntimeConnection.ForTcp()) to control transport when supplying a Connection.", - nameof(useStdio)); + "Do not set options.Environment in E2E tests; pass the 'environment' parameter to CreateClient instead.", + nameof(options)); } + // The full environment the client runs with: harness defaults (proxy + // redirect, isolated home, cleared HMAC/tokens, etc.) unless the test + // supplied a complete replacement. + var env = environment is not null + ? environment.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) + : GetEnvironment(); + + // When the test doesn't pin a transport, leave Connection null so + // CopilotClient honors COPILOT_SDK_DEFAULT_CONNECTION (stdio by default, + // or in-process); the CI matrix uses this to run the suite under both. + // Tests that need a specific transport set options.Connection directly. var cliPath = GetCliPath(_repoRoot); switch (options.Connection) { + case null when !IsInProcess(null): + // No explicit connection and not the in-process default: the + // default resolves to stdio, so materialize it here so the + // environment can be attached to the connection below. + options.Connection = RuntimeConnection.ForStdio(path: cliPath); + break; case null: - options.Connection = useStdio == false - ? RuntimeConnection.ForTcp(path: cliPath) - : RuntimeConnection.ForStdio(path: cliPath); + // In-process default: leave Connection unset so CopilotClient's + // ResolveDefaultConnection honors COPILOT_SDK_DEFAULT_CONNECTION. break; case ChildProcessRuntimeConnection child when child.Path is null: child.Path = cliPath; break; } + if (IsInProcess(options.Connection)) + { + // In-process hosting: runtime code runs host-side in this process (the + // loaded cdylib) and reads the ambient process environment rather than + // the environment passed to copilot_runtime_host_start, so the per-test + // redirects, cleared tokens/HMAC, and isolated home must be mirrored + // onto this process's real environment. Restored after each test by + // InProcessEnvIsolationAttribute. + foreach (var (name, value) in env) + { + InProcessEnvIsolation.Apply(name, value); + } + + // A per-client WorkingDirectory is rejected in-process; instead point this + // process's cwd at the desired directory so the worker inherits it at spawn + // (restored after the test by InProcessEnvIsolationAttribute). + options.WorkingDirectory = null; + InProcessEnvIsolation.SetWorkingDirectory(desiredWorkingDirectory); + } + else if (options.Connection is ChildProcessRuntimeConnection child) + { + // Child-process transport: hand the environment to the spawned child + // via the connection, where per-client environment is coherent. + child.Environment = env; + options.WorkingDirectory = desiredWorkingDirectory; + } + else + { + // URI / existing-runtime transport: per-client WorkingDirectory applies normally. + options.WorkingDirectory = desiredWorkingDirectory; + } + // Auto-inject auth token unless connecting to an existing runtime via URI. var isExistingRuntime = options.Connection is UriRuntimeConnection; if (autoInjectGitHubToken @@ -284,6 +355,25 @@ public CopilotClient CreateClient( return client; } + public Task CreateSessionAsync( + CopilotClient client, + SessionConfig? config = null) + { + config ??= new SessionConfig(); + E2ETestBackendConfiguration.Current.ApplyProvider(config, ProxyUrl); + return client.CreateSessionAsync(config); + } + + public Task ResumeSessionAsync( + CopilotClient client, + string sessionId, + ResumeSessionConfig? config = null) + { + config ??= new ResumeSessionConfig(); + E2ETestBackendConfiguration.Current.ApplyProvider(config, ProxyUrl); + return client.ResumeSessionAsync(sessionId, config); + } + public void UntrackClient(CopilotClient client) { lock (_clientsLock) @@ -310,7 +400,7 @@ public async Task CleanupAfterTestAsync() { try { - await client.ForceStopAsync(); + await StopClientForCleanupAsync(client); } catch (Exception ex) when (IsTransientCleanupException(ex)) { @@ -344,7 +434,7 @@ public async ValueTask DisposeAsync() { try { - await client.ForceStopAsync(); + await StopClientForCleanupAsync(client); } catch (Exception ex) when (IsTransientCleanupException(ex)) { @@ -406,6 +496,45 @@ private static async Task DeleteDirectoryAsync(string path) } } + /// + /// Determines whether the resolved transport is the in-process (FFI) host, + /// mirroring 's own default-connection resolution: + /// an explicit , or (when no connection + /// is given) the COPILOT_SDK_DEFAULT_CONNECTION=inprocess default. + /// + private static bool IsInProcess(RuntimeConnection? connection) + { + if (connection is InProcessRuntimeConnection) + { + return true; + } + if (connection is null) + { + return string.Equals( + Environment.GetEnvironmentVariable("COPILOT_SDK_DEFAULT_CONNECTION"), + "inprocess", + StringComparison.OrdinalIgnoreCase); + } + return false; + } + + // Inproc holds the session-store SQLite handle in-process; graceful StopAsync releases it so the temp-dir delete succeeds on Windows. + private static async Task StopClientForCleanupAsync(CopilotClient client) + { + var isInProcess = string.Equals( + Environment.GetEnvironmentVariable("COPILOT_SDK_DEFAULT_CONNECTION"), + "inprocess", + StringComparison.OrdinalIgnoreCase); + if (isInProcess) + { + await client.StopAsync(); + } + else + { + await client.ForceStopAsync(); + } + } + private static bool IsTransientCleanupException(Exception exception) => exception is IOException or UnauthorizedAccessException; } diff --git a/dotnet/test/Harness/InProcessEnvIsolation.cs b/dotnet/test/Harness/InProcessEnvIsolation.cs new file mode 100644 index 0000000000..af06001eda --- /dev/null +++ b/dotnet/test/Harness/InProcessEnvIsolation.cs @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +using System.Collections; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Xunit.Sdk; + +namespace GitHub.Copilot.Test.Harness; + +// Because many of the tests mutate global environment variables, we have to snapshot the original +// state and restore it after each test. Otherwise tests influence each other depending on run order. +// This is especially important for the in-process transport because the runtime is inside the test +// host process and will be reading/writing its environment variables directly. +internal static class InProcessEnvIsolation +{ + // Unset because CI sets them but the replay snapshots expect Bearer/OAuth. + private static readonly string[] SuppressEnvVars = ["COPILOT_HMAC_KEY", "CAPI_HMAC_KEY"]; + + // Captured at load, before any fixture/test mutates env. + private static readonly Dictionary s_ambient = CaptureEnvironment(); + + // The process working directory captured at load, restored after each test so an + // in-process test that repoints the cwd (the FFI worker inherits it at spawn) + // can't leak that change into the next test. + private static readonly string s_ambientCwd = Directory.GetCurrentDirectory(); + + // Runs at assembly load so the ambient env is snapshotted before the shared + // fixture mirrors per-test env onto the process. Justifies suppressing CA2255. +#pragma warning disable CA2255 // ModuleInitializer discouraged in libraries; intentional in this test harness. + [ModuleInitializer] + internal static void CaptureAtLoad() => _ = s_ambient; +#pragma warning restore CA2255 + + [DllImport("libc", EntryPoint = "setenv", CharSet = CharSet.Ansi, + BestFitMapping = false, ThrowOnUnmappableChar = true)] + private static extern int NativeSetEnv(string name, string value, int overwrite); + + [DllImport("libc", EntryPoint = "unsetenv", CharSet = CharSet.Ansi, + BestFitMapping = false, ThrowOnUnmappableChar = true)] + private static extern int NativeUnsetEnv(string name); + + // Sets/unsets on the managed cache and, on Unix, the libc block so native + // readers in the loaded cdylib observe it. + public static void Apply(string name, string? value) + { + Environment.SetEnvironmentVariable(name, value); + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + _ = value is null ? NativeUnsetEnv(name) : NativeSetEnv(name, value, 1); + } + } + + public static void NeutralizeAmbientCredentials() + { + foreach (var name in SuppressEnvVars) + { + Apply(name, null); + } + } + + // Points the process working directory at the given path so the in-process FFI + // worker inherits it at spawn (the native host has no per-client cwd parameter). + // RestoreAmbient() returns the process to its load-time cwd after the test. + public static void SetWorkingDirectory(string path) => + Directory.SetCurrentDirectory(path); + + public static void RestoreAmbient() + { + // Unconditionally repoint the process cwd at its load-time value. We must + // not read Directory.GetCurrentDirectory() first: an in-process test can + // chdir into a temp work dir that the harness then deletes, so getcwd() + // would throw FileNotFoundException. SetCurrentDirectory to an absolute + // path succeeds regardless of whether the old cwd still exists. + Directory.SetCurrentDirectory(s_ambientCwd); + + foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) + { + var name = (string)entry.Key; + if (!s_ambient.ContainsKey(name)) + { + Apply(name, null); + } + } + + foreach (var (name, value) in s_ambient) + { + if (!string.Equals(Environment.GetEnvironmentVariable(name), value, StringComparison.Ordinal)) + { + Apply(name, value); + } + } + } + + private static Dictionary CaptureEnvironment() => + Environment.GetEnvironmentVariables() + .Cast() + .ToDictionary(e => (string)e.Key, e => e.Value?.ToString(), StringComparer.Ordinal); +} + +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] +public sealed class InProcessEnvIsolationAttribute : BeforeAfterTestAttribute +{ + public override void Before(MethodInfo methodUnderTest) => + InProcessEnvIsolation.NeutralizeAmbientCredentials(); + + public override void After(MethodInfo methodUnderTest) => + InProcessEnvIsolation.RestoreAmbient(); +} diff --git a/dotnet/test/Harness/ModuleInitializerAttribute.cs b/dotnet/test/Harness/ModuleInitializerAttribute.cs new file mode 100644 index 0000000000..fd95287335 --- /dev/null +++ b/dotnet/test/Harness/ModuleInitializerAttribute.cs @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +#if !NET5_0_OR_GREATER +namespace System.Runtime.CompilerServices; + +// Polyfill so [ModuleInitializer] compiles on net472; recognized by the compiler. +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class ModuleInitializerAttribute : Attribute +{ +} +#endif diff --git a/dotnet/test/Harness/CapiProxy.cs b/dotnet/test/Harness/ReplayProxy.cs similarity index 94% rename from dotnet/test/Harness/CapiProxy.cs rename to dotnet/test/Harness/ReplayProxy.cs index 905aa192ba..895ebccb87 100644 --- a/dotnet/test/Harness/CapiProxy.cs +++ b/dotnet/test/Harness/ReplayProxy.cs @@ -13,7 +13,7 @@ namespace GitHub.Copilot.Test.Harness; -public sealed partial class CapiProxy : IAsyncDisposable +public sealed partial class ReplayProxy : IAsyncDisposable { private Process? _process; private Task? _startupTask; @@ -76,7 +76,7 @@ async Task StartCoreAsync() { var metadata = JsonSerializer.Deserialize( match.Groups["metadata"].Value, - CapiProxyJsonContext.Default.ProxyStartupMetadata); + ReplayProxyJsonContext.Default.ProxyStartupMetadata); ConnectProxyUrl = metadata?.ConnectProxyUrl; CaFilePath = metadata?.CaFilePath; } @@ -150,16 +150,19 @@ public async Task StopAsync(bool skipWritingCache = false) _startupTask = null; } - public async Task ConfigureAsync(string filePath, string workDir) + public async Task ConfigureAsync(string filePath, string workDir, string backend) { var url = await (_startupTask ?? throw new InvalidOperationException("Proxy not started")); using var client = new HttpClient(); - var response = await client.PostAsJsonAsync($"{url}/config", new ConfigureRequest(filePath, workDir), CapiProxyJsonContext.Default.ConfigureRequest); + var response = await client.PostAsJsonAsync( + $"{url}/config", + new ConfigureRequest(filePath, workDir, backend), + ReplayProxyJsonContext.Default.ConfigureRequest); response.EnsureSuccessStatusCode(); } - private record ConfigureRequest(string FilePath, string WorkDir); + private record ConfigureRequest(string FilePath, string WorkDir, string Backend); private record ProxyStartupMetadata(string? ConnectProxyUrl, string? CaFilePath); @@ -168,7 +171,7 @@ public async Task> GetExchangesAsync() var url = await (_startupTask ?? throw new InvalidOperationException("Proxy not started")); using var client = new HttpClient(); - return await client.GetFromJsonAsync($"{url}/exchanges", CapiProxyJsonContext.Default.ListParsedHttpExchange) + return await client.GetFromJsonAsync($"{url}/exchanges", ReplayProxyJsonContext.Default.ListParsedHttpExchange) ?? []; } @@ -178,7 +181,7 @@ public async Task SetCopilotUserByTokenAsync(string token, CopilotUserConfig res using var client = new HttpClient(); var payload = new CopilotUserByTokenRequest(token, response); - var resp = await client.PostAsJsonAsync($"{url}/copilot-user-config", payload, CapiProxyJsonContext.Default.CopilotUserByTokenRequest); + var resp = await client.PostAsJsonAsync($"{url}/copilot-user-config", payload, ReplayProxyJsonContext.Default.CopilotUserByTokenRequest); resp.EnsureSuccessStatusCode(); } @@ -205,7 +208,7 @@ private static string FindRepoRoot() [JsonSerializable(typeof(CopilotUserByTokenRequest))] [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(ProxyStartupMetadata))] - private partial class CapiProxyJsonContext : JsonSerializerContext; + private partial class ReplayProxyJsonContext : JsonSerializerContext; } public record CopilotUserByTokenRequest(string Token, CopilotUserConfig Response); @@ -268,7 +271,7 @@ public record ChatCompletionToolCallFunction(string Name, string? Arguments); public record ChatCompletionTool(string Type, ChatCompletionToolFunction Function); -public record ChatCompletionToolFunction(string Name, string? Description); +public record ChatCompletionToolFunction(string Name, string? Description, JsonElement? Parameters); public record ChatCompletionResponse(string Id, string Model, List Choices); diff --git a/dotnet/test/Unit/CanvasTests.cs b/dotnet/test/Unit/CanvasTests.cs index 612814d1f3..4993d88f6f 100644 --- a/dotnet/test/Unit/CanvasTests.cs +++ b/dotnet/test/Unit/CanvasTests.cs @@ -166,6 +166,7 @@ public void SessionCanvasOpenedEvent_UpdatesOpenCanvasSnapshots() ExtensionName = "Counter Provider", InstanceId = "counter-1", Title = "Counter", + Icon = "beaker", Status = "ready", Url = "https://example.test/counter", Input = JsonDocument.Parse("""{"seed":1}""").RootElement.Clone(), @@ -200,6 +201,7 @@ public void SessionCanvasOpenedEvent_UpdatesOpenCanvasSnapshots() ExtensionName = "Counter Provider", InstanceId = "counter-1", Title = "Counter Updated", + Icon = "beaker-filled", Status = "reconnected", Url = "https://example.test/counter-updated", Input = JsonDocument.Parse("""{"seed":2}""").RootElement.Clone(), @@ -212,6 +214,7 @@ public void SessionCanvasOpenedEvent_UpdatesOpenCanvasSnapshots() { Assert.Equal("counter-1", canvas.InstanceId); Assert.Equal("Counter Updated", canvas.Title); + Assert.Equal("beaker-filled", canvas.Icon); Assert.Equal("reconnected", canvas.Status); Assert.Equal("https://example.test/counter-updated", canvas.Url); Assert.Equal(2, canvas.Input!.Value.GetProperty("seed").GetInt32()); @@ -313,6 +316,28 @@ public void ExtensionInfo_Serializes_SourceAndName() Assert.Equal("demo", doc.RootElement.GetProperty("name").GetString()); } + [Fact] + public void CanvasProviderIdentity_Serializes_IdAndName() + { + var options = GetSerializerOptions(); + var identity = new CanvasProviderIdentity { Id = "app:builtin:window-1", Name = "Built-in" }; + var json = JsonSerializer.Serialize(identity, options); + using var doc = JsonDocument.Parse(json); + Assert.Equal("app:builtin:window-1", doc.RootElement.GetProperty("id").GetString()); + Assert.Equal("Built-in", doc.RootElement.GetProperty("name").GetString()); + } + + [Fact] + public void CanvasProviderIdentity_OmitsNullName() + { + var options = GetSerializerOptions(); + var identity = new CanvasProviderIdentity { Id = "app:builtin:window-1" }; + var json = JsonSerializer.Serialize(identity, options); + using var doc = JsonDocument.Parse(json); + Assert.Equal("app:builtin:window-1", doc.RootElement.GetProperty("id").GetString()); + Assert.False(doc.RootElement.TryGetProperty("name", out _)); + } + [Fact] public async Task CanvasHandlerBase_DefaultOnClose_Completes() { @@ -348,6 +373,7 @@ public void SessionConfig_Clone_CopiesCanvasFields() RequestCanvasRenderer = true, RequestExtensions = true, ExtensionInfo = new ExtensionInfo { Source = "github-app", Name = "demo" }, + CanvasProvider = new CanvasProviderIdentity { Id = "app:builtin:window-1", Name = "Built-in" }, CanvasHandler = handler }; @@ -360,6 +386,8 @@ public void SessionConfig_Clone_CopiesCanvasFields() Assert.True(clone.RequestExtensions); Assert.NotNull(clone.ExtensionInfo); Assert.Equal("github-app", clone.ExtensionInfo!.Source); + Assert.NotNull(clone.CanvasProvider); + Assert.Equal("app:builtin:window-1", clone.CanvasProvider!.Id); Assert.Same(handler, clone.CanvasHandler); // Mutating the clone's list does not affect the original. @@ -376,6 +404,7 @@ public void ResumeSessionConfig_Clone_CopiesCanvasFields() Canvases = new[] { new CanvasDeclaration { Id = "c1", DisplayName = "C", Description = "d" } }, RequestCanvasRenderer = true, ExtensionInfo = new ExtensionInfo { Source = "s", Name = "n" }, + CanvasProvider = new CanvasProviderIdentity { Id = "app:builtin:window-2" }, CanvasHandler = handler }; @@ -385,6 +414,8 @@ public void ResumeSessionConfig_Clone_CopiesCanvasFields() Assert.Single(clone.Canvases!); Assert.True(clone.RequestCanvasRenderer); Assert.NotNull(clone.ExtensionInfo); + Assert.NotNull(clone.CanvasProvider); + Assert.Equal("app:builtin:window-2", clone.CanvasProvider!.Id); Assert.Same(handler, clone.CanvasHandler); } diff --git a/dotnet/test/Unit/ClientSessionLifetimeTests.cs b/dotnet/test/Unit/ClientSessionLifetimeTests.cs index 2c11c7d6b5..e1143db17c 100644 --- a/dotnet/test/Unit/ClientSessionLifetimeTests.cs +++ b/dotnet/test/Unit/ClientSessionLifetimeTests.cs @@ -16,6 +16,8 @@ namespace GitHub.Copilot.Test.Unit; public sealed class ClientSessionLifetimeTests { + private sealed record RpcRequestRecord(string Method, JsonElement Params); + [Fact] public async Task StopAsync_Requests_Runtime_Shutdown_For_Owned_Process() { @@ -30,6 +32,20 @@ public async Task StopAsync_Requests_Runtime_Shutdown_For_Owned_Process() Assert.Equal(1, server.RuntimeShutdownCount); } + [Fact] + public async Task DisposeAsync_Requests_Runtime_Shutdown_For_Owned_Process() + { + await using var server = await FakeCopilotServer.StartAsync(); + var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) }); + await client.StartAsync(); + using var process = StartExitedProcess(); + await ReplaceConnectionCliProcessAsync(client, process); + + await client.DisposeAsync(); + + Assert.Equal(1, server.RuntimeShutdownCount); + } + [Fact] public async Task StopAsync_Does_Not_Throw_When_Runtime_Shutdown_Fails() { @@ -188,6 +204,202 @@ public async Task ResumeSessionAsync_Throws_When_Same_Client_Already_Tracks_Sess AssertSessionCount(client, sessions: 1); } + [Fact] + public async Task CreateSessionAsync_Serializes_CustomAgent_ReasoningEffort() + { + await using var server = await FakeCopilotServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) }); + await client.StartAsync(); + + await using var session = await client.CreateSessionAsync(new SessionConfig + { + CustomAgents = + [ + new CustomAgentConfig + { + Name = "reasoning-agent", + Prompt = "Think carefully.", + ReasoningEffort = "high" + } + ], + OnPermissionRequest = PermissionHandler.ApproveAll + }); + + var request = Assert.Single(server.Requests, request => request.Method == "session.create"); + var agent = Assert.Single(request.Params.GetProperty("customAgents").EnumerateArray()); + Assert.Equal("high", agent.GetProperty("reasoningEffort").GetString()); + } + + [Fact] + public async Task CreateSessionAsync_Omits_CustomAgent_ReasoningEffort_When_Unset() + { + await using var server = await FakeCopilotServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) }); + await client.StartAsync(); + + await using var session = await client.CreateSessionAsync(new SessionConfig + { + CustomAgents = + [ + new CustomAgentConfig + { + Name = "default-agent", + Prompt = "Use runtime defaults." + } + ], + OnPermissionRequest = PermissionHandler.ApproveAll + }); + + var request = Assert.Single(server.Requests, request => request.Method == "session.create"); + var agent = Assert.Single(request.Params.GetProperty("customAgents").EnumerateArray()); + Assert.False(agent.TryGetProperty("reasoningEffort", out _)); + } + + [Fact] + public async Task CreateSessionAsync_Registers_McpAuth_Interest_Only_When_Handler_Configured() + { + await using var server = await FakeCopilotServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) }); + + await using var withoutAuth = await client.CreateSessionAsync(new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnEvent = _ => { } + }); + + Assert.DoesNotContain(server.Requests, request => + request.Method == "session.eventLog.registerInterest" + && request.Params.GetProperty("eventType").GetString() == "mcp.oauth_required"); + Assert.Contains(server.Requests, request => + request.Method == "session.create" + && request.Params.GetProperty("requestPermission").GetBoolean()); + + server.ClearRequests(); + + await using var withAuth = await client.CreateSessionAsync(new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnMcpAuthRequest = _ => Task.FromResult(McpAuthResult.Cancel()) + }); + + Assert.Collection( + server.Requests.Take(2), + request => Assert.Equal("session.create", request.Method), + request => + { + Assert.Equal("session.eventLog.registerInterest", request.Method); + Assert.Equal("mcp.oauth_required", request.Params.GetProperty("eventType").GetString()); + }); + } + + [Fact] + public async Task CreateSessionAsync_Registers_McpAuth_Interest_After_Cloud_Create_When_Handler_Configured() + { + await using var server = await FakeCopilotServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) }); + var cloud = new CloudSessionOptions + { + Repository = new CloudSessionRepository + { + Owner = "github", + Name = "copilot-sdk", + Branch = "main" + } + }; + + await using var withoutAuth = await client.CreateSessionAsync(new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + Cloud = cloud + }); + + Assert.DoesNotContain(server.Requests, request => + request.Method == "session.eventLog.registerInterest" + && request.Params.GetProperty("eventType").GetString() == "mcp.oauth_required"); + + server.ClearRequests(); + + await using var withAuth = await client.CreateSessionAsync(new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnMcpAuthRequest = _ => Task.FromResult(McpAuthResult.Cancel()), + Cloud = cloud + }); + + Assert.Collection( + server.Requests.Take(2), + request => Assert.Equal("session.create", request.Method), + request => + { + Assert.Equal("session.eventLog.registerInterest", request.Method); + Assert.Equal("mcp.oauth_required", request.Params.GetProperty("eventType").GetString()); + }); + } + + [Fact] + public async Task ResumeSessionAsync_Registers_McpAuth_Interest_Only_When_Handler_Configured() + { + await using var server = await FakeCopilotServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) }); + + await using var withoutAuth = await client.ResumeSessionAsync("session-without-auth", new ResumeSessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnEvent = _ => { } + }); + + Assert.DoesNotContain(server.Requests, request => + request.Method == "session.eventLog.registerInterest" + && request.Params.GetProperty("eventType").GetString() == "mcp.oauth_required"); + Assert.Contains(server.Requests, request => + request.Method == "session.resume" + && request.Params.GetProperty("requestPermission").GetBoolean()); + + server.ClearRequests(); + + await using var withAuth = await client.ResumeSessionAsync("session-with-auth", new ResumeSessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnMcpAuthRequest = _ => Task.FromResult(McpAuthResult.Cancel()) + }); + + Assert.Collection( + server.Requests.Take(2), + request => Assert.Equal("session.resume", request.Method), + request => + { + Assert.Equal("session.eventLog.registerInterest", request.Method); + Assert.Equal("mcp.oauth_required", request.Params.GetProperty("eventType").GetString()); + }); + } + + [Fact] + public async Task McpAuth_Handler_Exception_Cancels_Pending_Request() + { + await using var server = await FakeCopilotServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) }); + await using var session = await client.CreateSessionAsync(new SessionConfig + { + OnPermissionRequest = PermissionHandler.ApproveAll, + OnMcpAuthRequest = _ => throw new ApplicationException("boom") + }); + + DispatchEvent(session, new McpOauthRequiredEvent + { + Data = new McpOauthRequiredData + { + RequestId = "mcp-auth-request-1", + ServerName = "oauth-mcp", + ServerUrl = "http://localhost/mcp", + Reason = McpOauthRequestReason.Initial + } + }); + + var request = await WaitForRequestAsync(server, "session.mcp.oauth.handlePendingRequest"); + Assert.Equal("mcp-auth-request-1", request.Params.GetProperty("requestId").GetString()); + Assert.Equal("cancelled", request.Params.GetProperty("result").GetProperty("kind").GetString()); + } + [Fact] public async Task Generated_Session_Rpc_Throws_When_Session_Disposed() { @@ -238,6 +450,30 @@ private static int GetPrivateDictionaryCount(CopilotClient client, string fieldN return (int)count.GetValue(dictionary)!; } + private static void DispatchEvent(CopilotSession session, SessionEvent evt) + { + var method = typeof(CopilotSession).GetMethod("DispatchEvent", BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("DispatchEvent method was not found."); + method.Invoke(session, [evt]); + } + + private static async Task WaitForRequestAsync(FakeCopilotServer server, string method) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + while (!timeout.IsCancellationRequested) + { + var request = server.Requests.FirstOrDefault(request => request.Method == method); + if (request is not null) + { + return request; + } + + await Task.Delay(20, CancellationToken.None); + } + + throw new TimeoutException($"Timed out waiting for RPC method '{method}'."); + } + private static async Task ReplaceConnectionCliProcessAsync(CopilotClient client, Process process) { var field = typeof(CopilotClient).GetField("_connectionTask", BindingFlags.Instance | BindingFlags.NonPublic) @@ -252,7 +488,7 @@ private static async Task ReplaceConnectionCliProcessAsync(CopilotClient client, var rpc = connectionType.GetProperty("Rpc")!.GetValue(connection); var networkStream = connectionType.GetProperty("NetworkStream")!.GetValue(connection); var constructor = connectionType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Single(); - var updatedConnection = constructor.Invoke([rpc, process, networkStream, null]); + var updatedConnection = constructor.Invoke([rpc, process, networkStream, null, null]); var fromResult = typeof(Task).GetMethod(nameof(Task.FromResult))!.MakeGenericMethod(connectionType); field.SetValue(client, fromResult.Invoke(null, [updatedConnection])); } @@ -277,6 +513,8 @@ private sealed class FakeCopilotServer : IAsyncDisposable private readonly TaskCompletionSource _destroyStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly TaskCompletionSource _allowDestroy = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly Task _serverTask; + private readonly List _requests = []; + private readonly object _requestsLock = new(); private string? _lastSessionId; private bool _delayDestroy; private bool _failRuntimeShutdown; @@ -307,6 +545,25 @@ public static Task StartAsync() public int RuntimeShutdownCount { get; private set; } + public IReadOnlyList Requests + { + get + { + lock (_requestsLock) + { + return _requests.ToArray(); + } + } + } + + public void ClearRequests() + { + lock (_requestsLock) + { + _requests.Clear(); + } + } + public void DelayDestroy() { _delayDestroy = true; @@ -382,6 +639,13 @@ private async Task HandleRequestAsync(Stream stream, JsonElement request, Cancel return; } + var paramsElement = request.TryGetProperty("params", out var rawParams) + ? rawParams.Clone() + : JsonDocument.Parse("{}").RootElement.Clone(); + lock (_requestsLock) + { + _requests.Add(new RpcRequestRecord(method!, paramsElement)); + } object? result = method switch { "connect" => new Dictionary @@ -392,10 +656,18 @@ private async Task HandleRequestAsync(Stream stream, JsonElement request, Cancel }, "session.create" => CreateSessionResult(request), "session.resume" => CreateSessionResult(request), + "session.eventLog.registerInterest" => new Dictionary + { + ["id"] = "interest-1" + }, "session.send" => new Dictionary { ["messageId"] = "message-1" }, + "session.mcp.oauth.handlePendingRequest" => new Dictionary + { + ["success"] = true + }, "session.delete" => new Dictionary { ["success"] = true diff --git a/dotnet/test/Unit/CloneTests.cs b/dotnet/test/Unit/CloneTests.cs index 9df9a200c9..ec509ab169 100644 --- a/dotnet/test/Unit/CloneTests.cs +++ b/dotnet/test/Unit/CloneTests.cs @@ -73,14 +73,16 @@ public void SessionConfig_Clone_CopiesAllProperties() ConfigDirectory = "/config", AvailableTools = ["tool1", "tool2"], ExcludedTools = ["tool3"], + ExcludedBuiltInAgents = ["explore", "task"], WorkingDirectory = "/workspace", Streaming = true, + EnableCitations = true, EnableSessionTelemetry = false, EnableOnDemandInstructionDiscovery = true, IncludeSubAgentStreamingEvents = false, McpServers = new Dictionary { ["server1"] = new McpStdioServerConfig { Command = "echo" } }, McpOAuthTokenStorage = McpOAuthTokenStorageMode.Persistent, - CustomAgents = [new CustomAgentConfig { Name = "agent1", Model = "claude-haiku-4.5" }], + CustomAgents = [new CustomAgentConfig { Name = "agent1", Model = "claude-haiku-4.5", ReasoningEffort = "high" }], Agent = "agent1", Capi = new CapiSessionOptions { EnableWebSocketResponses = false }, Cloud = new CloudSessionOptions @@ -99,6 +101,7 @@ public void SessionConfig_Clone_CopiesAllProperties() PluginDirectories = ["/plugins"], LargeOutput = new LargeToolOutputConfig { Enabled = true, MaxSizeBytes = 2048, OutputDirectory = "/tmp/out" }, Memory = new MemoryConfiguration { Enabled = true }, + SessionLimits = new SessionLimitsConfig { MaxAiCredits = 42.5 }, OnExitPlanModeRequest = static (_, _) => Task.FromResult(new ExitPlanModeResult()), OnAutoModeSwitchRequest = static (_, _) => Task.FromResult(AutoModeSwitchResponse.No), }; @@ -114,8 +117,10 @@ public void SessionConfig_Clone_CopiesAllProperties() Assert.Equal(original.ConfigDirectory, clone.ConfigDirectory); Assert.Equal(original.AvailableTools, clone.AvailableTools); Assert.Equal(original.ExcludedTools, clone.ExcludedTools); + Assert.Equal(original.ExcludedBuiltInAgents, clone.ExcludedBuiltInAgents); Assert.Equal(original.WorkingDirectory, clone.WorkingDirectory); Assert.Equal(original.Streaming, clone.Streaming); + Assert.Equal(original.EnableCitations, clone.EnableCitations); Assert.Equal(original.EnableSessionTelemetry, clone.EnableSessionTelemetry); Assert.Equal(original.EnableOnDemandInstructionDiscovery, clone.EnableOnDemandInstructionDiscovery); Assert.Equal(original.IncludeSubAgentStreamingEvents, clone.IncludeSubAgentStreamingEvents); @@ -123,6 +128,7 @@ public void SessionConfig_Clone_CopiesAllProperties() Assert.Equal(original.McpOAuthTokenStorage, clone.McpOAuthTokenStorage); Assert.Equal(original.CustomAgents.Count, clone.CustomAgents!.Count); Assert.Equal(original.CustomAgents[0].Model, clone.CustomAgents[0].Model); + Assert.Equal(original.CustomAgents[0].ReasoningEffort, clone.CustomAgents[0].ReasoningEffort); Assert.Equal(original.Agent, clone.Agent); Assert.Same(original.Capi, clone.Capi); Assert.Same(original.Cloud, clone.Cloud); @@ -133,6 +139,7 @@ public void SessionConfig_Clone_CopiesAllProperties() Assert.Equal(original.PluginDirectories, clone.PluginDirectories); Assert.Same(original.LargeOutput, clone.LargeOutput); Assert.Same(original.Memory, clone.Memory); + Assert.Same(original.SessionLimits, clone.SessionLimits); Assert.Same(original.OnExitPlanModeRequest, clone.OnExitPlanModeRequest); Assert.Same(original.OnAutoModeSwitchRequest, clone.OnAutoModeSwitchRequest); } @@ -144,6 +151,7 @@ public void SessionConfig_Clone_CollectionsAreIndependent() { AvailableTools = ["tool1"], ExcludedTools = ["tool2"], + ExcludedBuiltInAgents = ["explore"], McpServers = new Dictionary { ["s1"] = new McpStdioServerConfig { Command = "echo" } }, CustomAgents = [new CustomAgentConfig { Name = "a1" }], SkillDirectories = ["/skills"], @@ -156,6 +164,7 @@ public void SessionConfig_Clone_CollectionsAreIndependent() // Mutate clone collections clone.AvailableTools!.Add("tool99"); clone.ExcludedTools!.Add("tool99"); + clone.ExcludedBuiltInAgents!.Add("task"); clone.McpServers!["s2"] = new McpStdioServerConfig { Command = "echo" }; clone.CustomAgents!.Add(new CustomAgentConfig { Name = "a2" }); clone.SkillDirectories!.Add("/more"); @@ -165,6 +174,7 @@ public void SessionConfig_Clone_CollectionsAreIndependent() // Original is unaffected Assert.Single(original.AvailableTools!); Assert.Single(original.ExcludedTools!); + Assert.Single(original.ExcludedBuiltInAgents!); Assert.Single(original.McpServers!); Assert.Single(original.CustomAgents!); Assert.Single(original.SkillDirectories!); @@ -190,6 +200,7 @@ public void ResumeSessionConfig_Clone_CollectionsAreIndependent() { AvailableTools = ["tool1"], ExcludedTools = ["tool2"], + ExcludedBuiltInAgents = ["explore"], McpServers = new Dictionary { ["s1"] = new McpStdioServerConfig { Command = "echo" } }, CustomAgents = [new CustomAgentConfig { Name = "a1" }], SkillDirectories = ["/skills"], @@ -202,6 +213,7 @@ public void ResumeSessionConfig_Clone_CollectionsAreIndependent() // Mutate clone collections clone.AvailableTools!.Add("tool99"); clone.ExcludedTools!.Add("tool99"); + clone.ExcludedBuiltInAgents!.Add("task"); clone.McpServers!["s2"] = new McpStdioServerConfig { Command = "echo" }; clone.CustomAgents!.Add(new CustomAgentConfig { Name = "a2" }); clone.SkillDirectories!.Add("/more"); @@ -211,6 +223,7 @@ public void ResumeSessionConfig_Clone_CollectionsAreIndependent() // Original is unaffected Assert.Single(original.AvailableTools!); Assert.Single(original.ExcludedTools!); + Assert.Single(original.ExcludedBuiltInAgents!); Assert.Single(original.McpServers!); Assert.Single(original.CustomAgents!); Assert.Single(original.SkillDirectories!); @@ -270,6 +283,7 @@ public void Clone_WithNullCollections_ReturnsNullCollections() Assert.Null(clone.AvailableTools); Assert.Null(clone.ExcludedTools); + Assert.Null(clone.ExcludedBuiltInAgents); Assert.Null(clone.McpServers); Assert.Null(clone.CustomAgents); Assert.Null(clone.SkillDirectories); diff --git a/dotnet/test/Unit/CopilotToolTests.cs b/dotnet/test/Unit/CopilotToolTests.cs index 9c9e2a93ba..c3f5861492 100644 --- a/dotnet/test/Unit/CopilotToolTests.cs +++ b/dotnet/test/Unit/CopilotToolTests.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.AI; using System.ComponentModel; using System.Text.Json; +using System.Text.Json.Nodes; using Xunit; namespace GitHub.Copilot.Test.Unit; @@ -43,6 +44,34 @@ public void DefineTool_Omits_Copilot_Metadata_When_Flags_Are_False() Assert.False(function.AdditionalProperties.ContainsKey("defer")); } + [Fact] + public void DefineTool_Sets_Metadata_In_Additional_Properties() + { + var metadata = new Dictionary + { + ["github.com/copilot:safeForTelemetry"] = new JsonObject + { + ["name"] = true, + ["inputsNames"] = false + } + }; + + var function = CopilotTool.DefineTool( + ReturnsOk, + new CopilotToolOptions { Metadata = metadata }); + + Assert.True(function.AdditionalProperties.TryGetValue("metadata", out var value)); + Assert.Same(metadata, value); + } + + [Fact] + public void DefineTool_Omits_Metadata_When_Unset() + { + var function = CopilotTool.DefineTool(ReturnsOk); + + Assert.False(function.AdditionalProperties.ContainsKey("metadata")); + } + [Fact] public void DefineTool_Accepts_Lambda_Handlers_Without_Casts() { diff --git a/dotnet/test/Unit/E2ETestBackendTests.cs b/dotnet/test/Unit/E2ETestBackendTests.cs new file mode 100644 index 0000000000..f7c39a5083 --- /dev/null +++ b/dotnet/test/Unit/E2ETestBackendTests.cs @@ -0,0 +1,80 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +using GitHub.Copilot.Test.Harness; +using Xunit; + +namespace GitHub.Copilot.Test.Unit; + +public class E2ETestBackendTests +{ + [Theory] + [InlineData(null, "capi")] + [InlineData("", "capi")] + [InlineData("capi", "capi")] + [InlineData("ANTHROPIC-MESSAGES", "anthropic-messages")] + [InlineData("openai-responses", "openai-responses")] + [InlineData("openai-completions", "openai-completions")] + public void ParsesBackend(string? value, string expected) + => Assert.Equal(expected, E2ETestBackendConfiguration.Parse(value).ToWireName()); + + [Fact] + public void RejectsUnknownBackend() + => Assert.Throws( + () => E2ETestBackendConfiguration.Parse("unknown")); + + [Theory] + [InlineData("anthropic-messages", "anthropic", null, "claude-sonnet-4.5")] + [InlineData("openai-responses", "openai", "responses", "gpt-4.1")] + [InlineData("openai-completions", "openai", "completions", "gpt-4.1")] + public void AppliesProvider( + string backendValue, + string expectedType, + string? expectedWireApi, + string expectedModel) + { + var backend = E2ETestBackendConfiguration.Parse(backendValue); + var config = new SessionConfig(); + backend.ApplyProvider(config, "http://localhost:1234"); + + Assert.Equal(expectedModel, config.Model); + Assert.Equal("http://localhost:1234", config.Provider!.BaseUrl); + Assert.Equal(expectedType, config.Provider.Type); + Assert.Equal(expectedWireApi, config.Provider.WireApi); + Assert.Equal(expectedModel, config.Provider.ModelId); + Assert.Equal(expectedModel, config.Provider.WireModel); + Assert.False(string.IsNullOrEmpty(config.Provider.BearerToken)); + } + + [Fact] + public void PreservesExplicitModel() + { + var config = new SessionConfig { Model = "test-model" }; + E2ETestBackend.OpenAIResponses.ApplyProvider(config, "http://localhost:1234"); + + Assert.Equal("test-model", config.Model); + Assert.Equal("test-model", config.Provider!.ModelId); + Assert.Equal("test-model", config.Provider.WireModel); + } + + [Fact] + public void PreservesExplicitProvider() + { + var provider = new ProviderConfig + { + Type = "custom", + ModelId = "provider-model", + }; + var config = new SessionConfig + { + Model = "session-model", + Provider = provider, + }; + + E2ETestBackend.OpenAIResponses.ApplyProvider(config, "http://localhost:1234"); + + Assert.Equal("session-model", config.Model); + Assert.Same(provider, config.Provider); + } +} diff --git a/dotnet/test/Unit/ForwardCompatibilityTests.cs b/dotnet/test/Unit/ForwardCompatibilityTests.cs index 09133dfb52..b52a7713f7 100644 --- a/dotnet/test/Unit/ForwardCompatibilityTests.cs +++ b/dotnet/test/Unit/ForwardCompatibilityTests.cs @@ -168,6 +168,24 @@ public void FromJson_UnknownEventType_WithUnknownEnumInData_DoesNotThrow() Assert.Equal("unknown", result.Type); } + [Fact] + public void FromJson_InternalEventType_ReturnsBaseSessionEvent() + { + var json = """ + { + "id": "12345678-1234-1234-1234-123456789abc", + "timestamp": "2026-06-15T10:30:00Z", + "type": "session.memory_changed", + "data": {} + } + """; + + var result = SessionEvent.FromJson(json); + + Assert.IsType(result); + Assert.Equal("unknown", result.Type); + } + [Fact] public void FromJson_KnownEventType_WithUnknownEnumInData_PreservesValue() { diff --git a/dotnet/test/Unit/GitHubTelemetryTests.cs b/dotnet/test/Unit/GitHubTelemetryTests.cs new file mode 100644 index 0000000000..f82e0db6e0 --- /dev/null +++ b/dotnet/test/Unit/GitHubTelemetryTests.cs @@ -0,0 +1,482 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +#if NET8_0_OR_GREATER +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using Xunit; + +using GitHub.Copilot.Rpc; + +namespace GitHub.Copilot.Test.Unit; + +#pragma warning disable GHCP001 // GitHub telemetry forwarding is experimental. + +public sealed class GitHubTelemetryTests +{ + [Fact] + public async Task CreateSession_Opts_Into_Forwarding_When_Handler_Provided() + { + await using var server = await FakeTelemetryServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri(server.Url), + OnGitHubTelemetry = _ => Task.CompletedTask, + }); + await client.StartAsync(); + + await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); + + var createParams = server.LastCreateParams ?? throw new InvalidOperationException("session.create was not captured."); + Assert.True(createParams.TryGetProperty("enableGitHubTelemetryForwarding", out var flag)); + Assert.True(flag.GetBoolean()); + } + + [Fact] + public async Task ResumeSession_Opts_Into_Forwarding_When_Handler_Provided() + { + await using var server = await FakeTelemetryServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri(server.Url), + OnGitHubTelemetry = _ => Task.CompletedTask, + }); + await client.StartAsync(); + + await client.ResumeSessionAsync("session-1", new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); + + var resumeParams = server.LastResumeParams ?? throw new InvalidOperationException("session.resume was not captured."); + Assert.True(resumeParams.TryGetProperty("enableGitHubTelemetryForwarding", out var flag)); + Assert.True(flag.GetBoolean()); + } + + [Fact] + public async Task Connect_Opts_Into_Forwarding_When_Handler_Provided() + { + await using var server = await FakeTelemetryServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri(server.Url), + OnGitHubTelemetry = _ => Task.CompletedTask, + }); + await client.StartAsync(); + + var connectParams = server.LastConnectParams ?? throw new InvalidOperationException("connect was not captured."); + Assert.True(connectParams.TryGetProperty("enableGitHubTelemetryForwarding", out var flag)); + Assert.True(flag.GetBoolean()); + } + + [Fact] + public async Task Connect_Does_Not_Opt_In_Without_Handler() + { + await using var server = await FakeTelemetryServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri(server.Url), + }); + await client.StartAsync(); + + var connectParams = server.LastConnectParams ?? throw new InvalidOperationException("connect was not captured."); + var present = connectParams.TryGetProperty("enableGitHubTelemetryForwarding", out var flag); + Assert.True( + !present || flag.ValueKind == JsonValueKind.Null, + "connect request should omit enableGitHubTelemetryForwarding (or send null) when no handler is registered"); + } + + [Fact] + public async Task CreateSession_Does_Not_Opt_In_Without_Handler() + { + await using var server = await FakeTelemetryServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri(server.Url), + }); + await client.StartAsync(); + + await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll }); + + var createParams = server.LastCreateParams ?? throw new InvalidOperationException("session.create was not captured."); + var optedIn = createParams.TryGetProperty("enableGitHubTelemetryForwarding", out var flag) + && flag.ValueKind == JsonValueKind.True; + Assert.False(optedIn); + } + + [Fact] + public async Task GitHubTelemetry_Event_Is_Forwarded_To_OnGitHubTelemetry() + { + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await using var server = await FakeTelemetryServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri(server.Url), + OnGitHubTelemetry = notification => + { + received.TrySetResult(notification); + return Task.CompletedTask; + }, + }); + await client.StartAsync(); + + await server.SendGitHubTelemetryEventAsync(new Dictionary + { + ["sessionId"] = "session-1", + ["restricted"] = false, + ["event"] = new Dictionary + { + ["kind"] = "tool_call_executed", + ["properties"] = new Dictionary { ["tool"] = "shell" }, + ["metrics"] = new Dictionary { ["duration_ms"] = 42 }, + ["session_id"] = "session-1", + }, + }); + + var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal("session-1", notification.SessionId); + Assert.False(notification.Restricted); + Assert.Equal("tool_call_executed", notification.Event.Kind); + Assert.Equal("shell", notification.Event.Properties["tool"]); + Assert.Equal(42, notification.Event.Metrics["duration_ms"]); + Assert.Equal("session-1", notification.Event.SessionId); + } + + [Fact] + public async Task GitHubTelemetry_Event_Maps_Restricted_And_ClientInfo() + { + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await using var server = await FakeTelemetryServer.StartAsync(); + await using var client = new CopilotClient(new CopilotClientOptions + { + Connection = RuntimeConnection.ForUri(server.Url), + OnGitHubTelemetry = notification => + { + received.TrySetResult(notification); + return Task.CompletedTask; + }, + }); + await client.StartAsync(); + + await server.SendGitHubTelemetryEventAsync(new Dictionary + { + ["sessionId"] = "session-2", + ["restricted"] = true, + ["event"] = new Dictionary + { + ["kind"] = "model_call", + ["properties"] = new Dictionary { ["model"] = "gpt-5" }, + ["metrics"] = new Dictionary { ["tokens"] = 128 }, + ["session_id"] = "session-2", + ["client"] = new Dictionary + { + ["cli_version"] = "1.2.3", + ["os_platform"] = "win32", + ["os_arch"] = "x64", + ["node_version"] = "20.0.0", + ["is_staff"] = false, + }, + }, + }); + + var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(notification.Restricted); + + var clientInfo = notification.Event.Client; + Assert.NotNull(clientInfo); + Assert.Equal("1.2.3", clientInfo!.CliVersion); + Assert.Equal("win32", clientInfo.OsPlatform); + Assert.Equal("x64", clientInfo.OsArch); + Assert.Equal("20.0.0", clientInfo.NodeVersion); + Assert.Equal(false, clientInfo.IsStaff); + } + + private sealed class FakeTelemetryServer : IAsyncDisposable + { + private readonly TcpListener _listener; + private readonly CancellationTokenSource _cts = new(); + private readonly SemaphoreSlim _writeLock = new(1, 1); + private readonly TaskCompletionSource _connected = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Task _serverTask; + + private FakeTelemetryServer(TcpListener listener) + { + _listener = listener; + _serverTask = RunAsync(); + } + + public string Url + { + get + { + var endpoint = (IPEndPoint)_listener.LocalEndpoint; + return $"http://127.0.0.1:{endpoint.Port}"; + } + } + + public JsonElement? LastCreateParams { get; private set; } + + public JsonElement? LastResumeParams { get; private set; } + + public JsonElement? LastConnectParams { get; private set; } + + public static Task StartAsync() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + return Task.FromResult(new FakeTelemetryServer(listener)); + } + + public async Task SendGitHubTelemetryEventAsync(Dictionary notificationParams) + { + var stream = await _connected.Task.WaitAsync(_cts.Token); + + // Send a genuine JSON-RPC notification (no "id"), exactly as the runtime + // does via sendNotification. This exercises the real notification dispatch + // path rather than masking it behind a request that carries an id. + await WriteMessageAsync(stream, new Dictionary + { + ["jsonrpc"] = "2.0", + ["method"] = "gitHubTelemetry.event", + ["params"] = notificationParams, + }, _cts.Token); + } + + public async ValueTask DisposeAsync() + { + _cts.Cancel(); + _listener.Stop(); + + try + { + await _serverTask; + } + catch (Exception ex) when (ex is OperationCanceledException or ObjectDisposedException or IOException or SocketException) + { + // Expected during teardown: the listener/socket is torn down while the + // server loop is still awaiting I/O. Observe the exception and move on. + _ = ex; + } + + _cts.Dispose(); + _writeLock.Dispose(); + } + + private async Task RunAsync() + { + using var tcpClient = await _listener.AcceptTcpClientAsync(_cts.Token); + using var stream = tcpClient.GetStream(); + _connected.TrySetResult(stream); + + while (!_cts.Token.IsCancellationRequested) + { + using var message = await ReadMessageAsync(stream, _cts.Token); + if (message is null) + { + return; + } + + // Inbound messages without a "method" are responses to our own + // server-initiated requests (e.g. session.* the SDK answers); the + // SDK never replies to the gitHubTelemetry.event notification. + if (!message.RootElement.TryGetProperty("method", out _)) + { + continue; + } + + await HandleRequestAsync(stream, message.RootElement, _cts.Token); + } + } + + private async Task HandleRequestAsync(Stream stream, JsonElement request, CancellationToken cancellationToken) + { + if (!request.TryGetProperty("id", out var idElement)) + { + return; + } + + var id = idElement.Clone(); + var method = request.GetProperty("method").GetString(); + + object? result = method switch + { + "connect" => CaptureConnect(request), + "session.create" => CaptureCreate(request), + "session.resume" => CaptureResume(request), + "session.send" => new Dictionary { ["messageId"] = "message-1" }, + "session.destroy" => new Dictionary(), + "runtime.shutdown" => new Dictionary(), + _ => throw new InvalidOperationException($"Unexpected RPC method '{method}'."), + }; + + await WriteMessageAsync(stream, new Dictionary + { + ["jsonrpc"] = "2.0", + ["id"] = id, + ["result"] = result, + }, cancellationToken); + } + + private Dictionary CaptureConnect(JsonElement request) + { + LastConnectParams = request.TryGetProperty("params", out var p) ? p.Clone() : null; + return new Dictionary + { + ["ok"] = true, + ["protocolVersion"] = 3, + ["version"] = "test", + }; + } + + private Dictionary CaptureCreate(JsonElement request) + { + LastCreateParams = request.TryGetProperty("params", out var p) ? p.Clone() : null; + return SessionResult(LastCreateParams); + } + + private Dictionary CaptureResume(JsonElement request) + { + LastResumeParams = request.TryGetProperty("params", out var p) ? p.Clone() : null; + return SessionResult(LastResumeParams); + } + + private static Dictionary SessionResult(JsonElement? paramsElement) + { + string sessionId = "session-1"; + if (paramsElement is { ValueKind: JsonValueKind.Object } p + && p.TryGetProperty("sessionId", out var sidProp) + && sidProp.ValueKind == JsonValueKind.String + && sidProp.GetString() is string sid + && !string.IsNullOrEmpty(sid)) + { + sessionId = sid; + } + + return new Dictionary + { + ["sessionId"] = sessionId, + ["workspacePath"] = null, + ["capabilities"] = null, + }; + } + + private async Task WriteMessageAsync(Stream stream, object payload, CancellationToken cancellationToken) + { + using var bodyStream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(bodyStream)) + { + WriteJsonValue(writer, payload); + } + + var body = bodyStream.ToArray(); + var header = Encoding.ASCII.GetBytes($"Content-Length: {body.Length}\r\n\r\n"); + + await _writeLock.WaitAsync(cancellationToken); + try + { + await stream.WriteAsync(header, cancellationToken); + await stream.WriteAsync(body, cancellationToken); + await stream.FlushAsync(cancellationToken); + } + finally + { + _writeLock.Release(); + } + } + + private static void WriteJsonValue(Utf8JsonWriter writer, object? value) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case string stringValue: + writer.WriteStringValue(stringValue); + break; + case bool boolValue: + writer.WriteBooleanValue(boolValue); + break; + case int intValue: + writer.WriteNumberValue(intValue); + break; + case long longValue: + writer.WriteNumberValue(longValue); + break; + case JsonElement jsonElement: + jsonElement.WriteTo(writer); + break; + case Dictionary dictionary: + writer.WriteStartObject(); + foreach (var (propertyName, propertyValue) in dictionary) + { + writer.WritePropertyName(propertyName); + WriteJsonValue(writer, propertyValue); + } + writer.WriteEndObject(); + break; + default: + throw new InvalidOperationException($"Unexpected JSON value type '{value.GetType().Name}'."); + } + } + + private static async Task ReadMessageAsync(Stream stream, CancellationToken cancellationToken) + { + var headerBytes = new List(); + while (true) + { + var value = await ReadByteAsync(stream, cancellationToken); + if (value < 0) + { + return null; + } + + headerBytes.Add((byte)value); + var count = headerBytes.Count; + if (count >= 4 && + headerBytes[count - 4] == '\r' && + headerBytes[count - 3] == '\n' && + headerBytes[count - 2] == '\r' && + headerBytes[count - 1] == '\n') + { + break; + } + } + + var header = Encoding.ASCII.GetString([.. headerBytes]); + var contentLength = header + .Split(["\r\n"], StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Split(':', 2)) + .Where(parts => parts.Length == 2 && parts[0].Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) + .Select(parts => int.Parse(parts[1].Trim(), System.Globalization.CultureInfo.InvariantCulture)) + .Single(); + + var body = new byte[contentLength]; + var offset = 0; + while (offset < body.Length) + { + var read = await stream.ReadAsync(body.AsMemory(offset, body.Length - offset), cancellationToken); + if (read == 0) + { + return null; + } + + offset += read; + } + + return JsonDocument.Parse(body); + } + + private static async Task ReadByteAsync(Stream stream, CancellationToken cancellationToken) + { + var buffer = new byte[1]; + var read = await stream.ReadAsync(buffer, cancellationToken); + return read == 0 ? -1 : buffer[0]; + } + } +} + +#pragma warning restore GHCP001 +#endif diff --git a/dotnet/test/Unit/PublicDtoTests.cs b/dotnet/test/Unit/PublicDtoTests.cs index c81a8a7a64..d1918d2b9a 100644 --- a/dotnet/test/Unit/PublicDtoTests.cs +++ b/dotnet/test/Unit/PublicDtoTests.cs @@ -20,6 +20,25 @@ namespace GitHub.Copilot.Test.Unit; /// public class PublicDtoTests { + [Fact] + public void McpAuth_Result_Factories_Represent_Token_And_Cancellation() + { + var token = new McpAuthToken + { + AccessToken = "host-token", + TokenType = "Bearer", + ExpiresIn = 3600, + }; + + var tokenResult = McpAuthResult.FromToken(token); + Assert.Same(token, tokenResult.Token); + Assert.False(tokenResult.Cancelled); + + var cancelled = McpAuthResult.Cancel(); + Assert.True(cancelled.Cancelled); + Assert.Null(cancelled.Token); + } + [Fact] public void Public_Dto_Properties_Can_Be_Set_And_Read() { diff --git a/dotnet/test/Unit/SerializationTests.cs b/dotnet/test/Unit/SerializationTests.cs index 48ef2e5538..ae7e885138 100644 --- a/dotnet/test/Unit/SerializationTests.cs +++ b/dotnet/test/Unit/SerializationTests.cs @@ -422,6 +422,43 @@ public void SessionRequests_CanSerializeMemory_WithSdkOptions() Assert.False(resumeRoot.GetProperty("memory").GetProperty("enabled").GetBoolean()); } + [Fact] + public void SessionRequests_CanSerializeCitationAgentExclusionAndLimits_WithSdkOptions() + { + var options = GetSerializerOptions(); + var excludedAgents = new List { "explore", "task" }; + + var createRequestType = GetNestedType(typeof(CopilotClient), "CreateSessionRequest"); + var createRequest = CreateInternalRequest( + createRequestType, + ("SessionId", "session-id"), + ("EnableCitations", true), + ("ExcludedBuiltInAgents", excludedAgents), + ("SessionLimits", new SessionLimitsConfig { MaxAiCredits = 12.5 })); + + var createJson = JsonSerializer.Serialize(createRequest, createRequestType, options); + using var createDocument = JsonDocument.Parse(createJson); + var createRoot = createDocument.RootElement; + Assert.True(createRoot.GetProperty("enableCitations").GetBoolean()); + Assert.Equal("explore", createRoot.GetProperty("excludedBuiltinAgents")[0].GetString()); + Assert.Equal(12.5, createRoot.GetProperty("sessionLimits").GetProperty("maxAiCredits").GetDouble()); + + var resumeRequestType = GetNestedType(typeof(CopilotClient), "ResumeSessionRequest"); + var resumeRequest = CreateInternalRequest( + resumeRequestType, + ("SessionId", "session-id"), + ("EnableCitations", true), + ("ExcludedBuiltInAgents", excludedAgents), + ("SessionLimits", new SessionLimitsConfig { MaxAiCredits = 7.25 })); + + var resumeJson = JsonSerializer.Serialize(resumeRequest, resumeRequestType, options); + using var resumeDocument = JsonDocument.Parse(resumeJson); + var resumeRoot = resumeDocument.RootElement; + Assert.True(resumeRoot.GetProperty("enableCitations").GetBoolean()); + Assert.Equal("task", resumeRoot.GetProperty("excludedBuiltinAgents")[1].GetString()); + Assert.Equal(7.25, resumeRoot.GetProperty("sessionLimits").GetProperty("maxAiCredits").GetDouble()); + } + [Fact] public void SessionRequests_OmitMemory_WhenUnset() { @@ -819,6 +856,48 @@ public void HooksInvokeResponse_SerializesNullOutput_AsEmptyOrNoOutputProperty() // else: property omitted, which is fine (runtime treats undefined output as no-op) } + [Fact] + public void ToolResultObject_SerializesToolReferences_WithSdkOptions() + { + var options = GetSerializerOptions(); + var original = new ToolResultObject + { + TextResultForLlm = "found 2 tools", + ResultType = "success", + ToolReferences = ["get_weather", "check_status"], + }; + + var json = JsonSerializer.Serialize(original, options); + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + Assert.Equal("found 2 tools", root.GetProperty("textResultForLlm").GetString()); + var refs = root.GetProperty("toolReferences"); + Assert.Equal(JsonValueKind.Array, refs.ValueKind); + Assert.Equal(2, refs.GetArrayLength()); + Assert.Equal("get_weather", refs[0].GetString()); + Assert.Equal("check_status", refs[1].GetString()); + + var deserialized = JsonSerializer.Deserialize(json, options); + Assert.NotNull(deserialized); + string[] expectedReferences = ["get_weather", "check_status"]; + Assert.Equal(expectedReferences, deserialized!.ToolReferences); + } + + [Fact] + public void ToolResultObject_OmitsToolReferences_WhenNull_WithSdkOptions() + { + var options = GetSerializerOptions(); + var original = new ToolResultObject + { + TextResultForLlm = "ok", + ResultType = "success", + }; + + var json = JsonSerializer.Serialize(original, options); + using var document = JsonDocument.Parse(json); + Assert.False(document.RootElement.TryGetProperty("toolReferences", out _)); + } + private static JsonSerializerOptions GetSerializerOptions() { var prop = typeof(CopilotClient) diff --git a/dotnet/test/Unit/SessionEventSerializationTests.cs b/dotnet/test/Unit/SessionEventSerializationTests.cs index 47b4ac3f73..64e28a5aee 100644 --- a/dotnet/test/Unit/SessionEventSerializationTests.cs +++ b/dotnet/test/Unit/SessionEventSerializationTests.cs @@ -150,14 +150,21 @@ public class SessionEventSerializationTests Data = new McpOauthRequiredData { RequestId = "oauth-request", + Reason = McpOauthRequestReason.Initial, ServerName = "oauth-server", ServerUrl = "https://example.com/mcp", StaticClientConfig = new McpOauthRequiredStaticClientConfig { ClientId = "client-id", + ClientSecret = "static-secret", GrantType = "client_credentials", PublicClient = false, }, + WwwAuthenticateParams = new McpOauthWWWAuthenticateParams + { + ResourceMetadataUrl = "https://example.com/.well-known/oauth-protected-resource", + }, + ResourceMetadata = """{"resource":"https://example.com/mcp"}""", }, }, "mcp.oauth_required" @@ -281,6 +288,17 @@ public void SessionEvent_ToJson_RoundTrips_JsonElementBackedPayloads(SessionEven .GetProperty("staticClientConfig") .GetProperty("grantType") .GetString()); + Assert.Equal( + "static-secret", + root.GetProperty("data") + .GetProperty("staticClientConfig") + .GetProperty("clientSecret") + .GetString()); + Assert.Equal( + """{"resource":"https://example.com/mcp"}""", + root.GetProperty("data") + .GetProperty("resourceMetadata") + .GetString()); break; case "assistant.message_start": @@ -297,4 +315,57 @@ public void SessionEvent_ToJson_RoundTrips_JsonElementBackedPayloads(SessionEven break; } } + + [Fact] + public void McpOauthRequiredData_Allows_Missing_Optional_Metadata() + { + const string json = """ + { + "id": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", + "timestamp": "2026-03-15T21:26:54.987Z", + "parentId": null, + "type": "mcp.oauth_required", + "data": { + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp" + } + } + """; + + var authEvent = Assert.IsType(SessionEvent.FromJson(json)); + Assert.Null(authEvent.Data.WwwAuthenticateParams); + Assert.Null(authEvent.Data.ResourceMetadata); + } + + [Fact] + public void McpOauthRequiredData_Preserves_Static_Client_Secret() + { + const string json = """ + { + "id": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", + "timestamp": "2026-03-15T21:26:54.987Z", + "parentId": null, + "type": "mcp.oauth_required", + "data": { + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp", + "staticClientConfig": { + "clientId": "static-client", + "clientSecret": "static-secret", + "grantType": "client_credentials", + "publicClient": false + } + } + } + """; + + var authEvent = Assert.IsType(SessionEvent.FromJson(json)); + + Assert.NotNull(authEvent.Data.StaticClientConfig); + Assert.Equal("static-secret", authEvent.Data.StaticClientConfig.ClientSecret); + } } diff --git a/go/README.md b/go/README.md index 5787e5a53e..44ba01d66a 100644 --- a/go/README.md +++ b/go/README.md @@ -101,6 +101,49 @@ Follow these steps to embed the CLI: That's it! When your application calls `copilot.NewClient` without a `Connection` field (or with an empty `StdioConnection{}`) and no `COPILOT_CLI_PATH` environment variable, the SDK will automatically install the embedded CLI to a cache directory and use it for all operations. +The bundler prepares the native runtime library required by the [in-process transport](#in-process-transport-experimental). It is included in the application only when building with the `copilot_inprocess` build tag. + +## In-process transport (Experimental) + +> **Experimental:** the in-process API may change in a future release. + +By default the SDK starts the runtime as a child process and talks JSON-RPC over stdio or TCP. The **in-process** transport instead loads a native runtime library directly into your process. + +Build your application with the `copilot_inprocess` build tag: + +```sh +go build -tags copilot_inprocess +``` + +```go +client := copilot.NewClient(&copilot.ClientOptions{ + Connection: copilot.InProcessConnection{}, +}) +if err := client.Start(context.Background()); err != nil { + log.Fatal(err) +} +defer client.Stop() +``` + +Resolution and requirements: + +- The application must be built with the `copilot_inprocess` build tag. +- Set `COPILOT_SDK_DEFAULT_CONNECTION=inprocess` to select the in-process + transport when `ClientOptions.Connection` is nil. An explicit connection + always takes precedence. +- Set `COPILOT_CLI_PATH` only when using an externally provisioned compatible runtime package; otherwise the bundled runtime is used. No `PATH` lookup is performed. +- Embedded runtime versions are isolated in separate cache directories. Start fails loudly if the native runtime is unavailable. +- Linux in-process bundles include both glibc and musl runtime packages and select the matching package automatically at startup. +- Only one native runtime version may be loaded per process. + +The in-process transport rejects options that cannot be honored by a runtime hosted in your shared process (each panics at `NewClient`): + +- `Env` — the host process has a single environment block. Set variables on the host process environment instead. +- `WorkingDirectory` — the runtime shares the host process's working directory. Change the process working directory before creating the client. +- `Telemetry` — per-client telemetry is lowered to native-runtime environment variables. Use a child-process transport for per-client telemetry. + +Implemented with pure-Go FFI (via [purego](https://github.com/ebitengine/purego)), so `CGO_ENABLED=0` and cross-compilation are preserved; no C toolchain is required. + ## API Reference ### Client @@ -142,11 +185,14 @@ Event types: `SessionLifecycleCreated`, `SessionLifecycleDeleted`, `SessionLifec **ClientOptions:** - `Connection` (RuntimeConnection): How the SDK connects to the runtime. Construct via one of: - - `StdioConnection{Path, Args}` — spawn a runtime over stdio (the default if `Connection` is nil) - - `TCPConnection{Port, ConnectionToken, Path, Args}` — spawn a runtime that listens on TCP + - `StdioConnection{Path, Args, Env}` — spawn a runtime over stdio (the default if `Connection` is nil) + - `TCPConnection{Port, ConnectionToken, Path, Args, Env}` — spawn a runtime that listens on TCP - `URIConnection{URL, ConnectionToken}` — connect to an already-running runtime (no process spawned) + - `InProcessConnection{}` — **Experimental.** Host the runtime in-process via the native FFI library instead of spawning a child process. See [In-process transport](#in-process-transport-experimental) below. When `Path` is empty for stdio/tcp, the SDK uses the bundled CLI (or `COPILOT_CLI_PATH` env var). + + `StdioConnection` and `TCPConnection` accept an optional connection-level `Env`. Set environment variables via **either** the client-level `Env` option or the connection's `Env`, not both (setting both panics); prefer the connection-level `Env`. - `WorkingDirectory` (string): Working directory for the runtime process - `BaseDirectory` (string): Base directory for Copilot data (session state, config, etc.). Sets `COPILOT_HOME` on the spawned runtime. When empty, the runtime defaults to `~/.copilot`. Ignored with `URIConnection`. This does **not** affect where the Go SDK extracts the embedded CLI binary; use `embeddedcli.Config.Dir` for the extraction/cache location. - `LogLevel` (string): Log level. When empty (default), the runtime uses its own default level (the SDK does not pass `--log-level`). diff --git a/go/canvas.go b/go/canvas.go index 375f7c6eef..e31598bb1e 100644 --- a/go/canvas.go +++ b/go/canvas.go @@ -42,6 +42,24 @@ type ExtensionInfo struct { Name string `json:"name"` } +// CanvasProviderIdentity is the stable identity for a host/SDK connection +// that supplies built-in canvases. +// +// When set on session create or resume, the runtime uses ID verbatim as the +// agent-facing canvas extension id, so host-provided canvases survive +// reconnect and CLI restart. +// +// Experimental: CanvasProviderIdentity is part of an experimental +// wire-protocol surface and may change or be removed in future SDK or CLI +// releases. +type CanvasProviderIdentity struct { + // ID is an opaque, stable provider id used verbatim as the canvas + // extension id. + ID string `json:"id"` + // Name is an optional display name surfaced as the canvas extension name. + Name *string `json:"name,omitempty"` +} + // CanvasError is a structured error returned from canvas handlers. // // Wire envelope: diff --git a/go/client.go b/go/client.go index 970f046425..f243268aa4 100644 --- a/go/client.go +++ b/go/client.go @@ -93,6 +93,37 @@ func validateSessionFSConfig(config *SessionFSConfig) error { return nil } +// validateEnvironmentOptions enforces the transport-specific rules for +// per-client environment, working directory, and telemetry. It panics (fails +// loud) on a misconfiguration, matching the other SDKs. +// +// The in-process transport loads the native runtime into this process, whose +// single environment block and process-global working directory cannot carry +// per-client values, and whose telemetry lowers to shared process-global env +// vars — so options that depend on them are rejected there. Child-process +// transports each own their OS process, so per-connection env is allowed, but +// setting it in both the client-level option and the connection is rejected. +func validateEnvironmentOptions(connection RuntimeConnection, opts *ClientOptions) { + if _, ok := connection.(InProcessConnection); ok { + if opts.Env != nil { + panic("Env is not supported with InProcessConnection: the in-process transport loads the native runtime into the shared host process, whose single environment block cannot carry per-client values. Set the variables on the host process environment instead.") + } + if opts.WorkingDirectory != "" { + panic("WorkingDirectory is not supported with InProcessConnection: the native runtime shares the host process working directory. Use a child-process transport, or set the process working directory before creating the client.") + } + if opts.Telemetry != nil { + panic("Telemetry is not supported with InProcessConnection: telemetry configuration is lowered to environment variables read by native runtime code running in the shared host process, so per-client telemetry cannot be honored in-process. Configure telemetry via the host process environment, or use a child-process transport.") + } + return + } + + if cp, ok := connection.(childProcessConnection); ok { + if cp.connEnv() != nil && opts.Env != nil { + panic("Set environment variables via either the client-level Env option or the connection's Env, not both. Prefer the connection-level Env for child-process transports.") + } + } +} + // Client manages the connection to the Copilot CLI server and provides session management. // // The Client can either spawn a CLI server process or connect to an existing server. @@ -124,6 +155,8 @@ type Client struct { isExternalServer bool conn net.Conn // stores net.Conn for external TCP connections useStdio bool // resolved value from options + useInProcess bool // true for InProcessConnection (FFI transport) + ffiHost inProcessHost // resolved process options for the spawned runtime (zero values for URIConnection) cliPath string cliArgs []string @@ -193,10 +226,15 @@ func NewClient(options *ClientOptions) *Client { opts = *options } - // Resolve the connection. nil defaults to an empty StdioConnection. + // Resolve the connection. An explicit connection always wins; otherwise + // honor the same process/environment override as the other SDKs. connection := opts.Connection if connection == nil { - connection = StdioConnection{} + env := opts.Env + if env == nil { + env = os.Environ() + } + connection = resolveDefaultConnection(env) } switch conn := connection.(type) { case StdioConnection: @@ -223,32 +261,52 @@ func NewClient(options *ClientOptions) *Client { client.isExternalServer = true client.useStdio = false client.tcpConnectionToken = conn.ConnectionToken + case InProcessConnection: + client.useStdio = false + client.useInProcess = true default: panic(fmt.Sprintf("unknown RuntimeConnection type: %T", connection)) } + // Validate transport-specific option constraints (fail loud). The in-process + // transport loads the runtime into this process, whose single environment + // block, process-global working directory, and shared telemetry state cannot + // carry per-client values. Child-process transports may set env via either + // the client-level option or the connection, but not both. + validateEnvironmentOptions(connection, &opts) + // Validate auth options when connecting to an external runtime. if client.isExternalServer && (opts.GitHubToken != "" || opts.UseLoggedInUser != nil) { panic("GitHubToken and UseLoggedInUser cannot be used with URIConnection (external runtime manages its own auth)") } + // For child-process transports, a connection-level env takes precedence over + // the client-level env (setting both was rejected above). Resolve it before + // defaulting so an explicit empty connection env stays authoritative. + if cp, ok := connection.(childProcessConnection); ok { + if env := cp.connEnv(); env != nil { + opts.Env = env + } + } + // Default Env to current environment if not set if opts.Env == nil { opts.Env = os.Environ() } - // Check effective environment for CLI path (only if not explicitly set via options) - if client.cliPath == "" { + // Check the effective environment for a child-process runtime override. + if client.cliPath == "" && !client.useInProcess { if cliPath := getEnvValue(opts.Env, "COPILOT_CLI_PATH"); cliPath != "" { client.cliPath = cliPath } } // Resolve the effective connection token: explicit value if set; else if the SDK - // spawns its own runtime in TCP mode, generate a UUID; otherwise empty. + // spawns its own runtime in TCP mode, generate a UUID; otherwise empty. The + // in-process transport uses no socket, so it needs no connection token. if client.tcpConnectionToken != "" { client.effectiveConnectionToken = client.tcpConnectionToken - } else if !client.useStdio && !client.isExternalServer { + } else if !client.useStdio && !client.isExternalServer && !client.useInProcess { client.effectiveConnectionToken = uuid.NewString() } @@ -266,6 +324,27 @@ func NewClient(options *ClientOptions) *Client { return client } +const defaultConnectionEnvVar = "COPILOT_SDK_DEFAULT_CONNECTION" + +// resolveDefaultConnection selects the transport when no explicit connection +// was supplied. The override is primarily used by hosts and the E2E transport +// matrix; explicit connection options always take precedence. +func resolveDefaultConnection(env []string) RuntimeConnection { + value := getEnvValue(env, defaultConnectionEnvVar) + switch { + case value == "", strings.EqualFold(value, "stdio"): + return StdioConnection{} + case strings.EqualFold(value, "inprocess"): + return InProcessConnection{} + default: + panic(fmt.Sprintf( + "invalid %s value %q: expected \"inprocess\", \"stdio\", or unset", + defaultConnectionEnvVar, + value, + )) + } +} + // getEnvValue looks up a key in an environment slice ([]string of "KEY=VALUE"). // Returns the value if found, or empty string otherwise. func getEnvValue(env []string, key string) string { @@ -451,7 +530,7 @@ func (c *Client) Stop() error { c.startStopMux.Lock() defer c.startStopMux.Unlock() - if c.process != nil && !c.isExternalServer && c.RPC != nil { + if (c.process != nil || c.ffiHost != nil) && !c.isExternalServer && c.RPC != nil { rpcClient := c.RPC runtimeShutdownStart := time.Now() shutdownDone := make(chan error, 1) @@ -486,6 +565,13 @@ func (c *Client) Stop() error { } c.process = nil + // Tear down the in-process FFI host (closes the connection and shuts down the + // native runtime). No child process to reap in this mode. + if c.ffiHost != nil { + c.ffiHost.Dispose() + c.ffiHost = nil + } + // Close external TCP connection if exists if c.isExternalServer && c.conn != nil { if err := c.conn.Close(); err != nil { @@ -567,6 +653,12 @@ func (c *Client) ForceStop() { } c.process = nil + // Dispose the in-process FFI host (if any) without waiting on graceful shutdown. + if c.ffiHost != nil { + c.ffiHost.Dispose() + c.ffiHost = nil + } + // Close external TCP connection if exists if c.isExternalServer && c.conn != nil { _ = c.conn.Close() // Ignore errors @@ -696,11 +788,14 @@ func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Ses req.AvailableTools = availableTools req.ExcludedTools = excludedTools req.ToolFilterPrecedence = precedence + req.ExcludedBuiltInAgents = config.ExcludedBuiltInAgents req.Provider = config.Provider req.Capi = config.Capi req.Providers = config.Providers req.Models = config.Models req.EnableSessionTelemetry = config.EnableSessionTelemetry + req.EnableCitations = config.EnableCitations + req.SessionLimits = config.SessionLimits req.SkipCustomInstructions = config.SkipCustomInstructions req.CustomAgentsLocalOnly = config.CustomAgentsLocalOnly req.CoauthorEnabled = config.CoauthorEnabled @@ -719,15 +814,20 @@ func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Ses req.DisabledSkills = config.DisabledSkills req.InfiniteSessions = config.InfiniteSessions req.LargeOutput = config.LargeOutput + req.ToolSearch = config.ToolSearch req.Memory = config.Memory req.GitHubToken = config.GitHubToken req.RemoteSession = config.RemoteSession req.Cloud = config.Cloud req.Canvases = config.Canvases + req.ExtensionInfo = config.ExtensionInfo + req.CanvasProvider = config.CanvasProvider req.RequestCanvasRenderer = config.RequestCanvasRenderer req.RequestExtensions = config.RequestExtensions req.ExtensionSDKPath = config.ExtensionSDKPath + req.ExtensionInfo = config.ExtensionInfo req.ExpAssignments = config.ExpAssignments + req.EnableManagedSettings = config.EnableManagedSettings if len(config.Commands) > 0 { cmds := make([]wireCommand, 0, len(config.Commands)) @@ -757,6 +857,9 @@ func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Ses } else { req.IncludeSubAgentStreamingEvents = Bool(true) } + if c.options.OnGitHubTelemetry != nil { + req.EnableGitHubTelemetryForwarding = Bool(true) + } if config.OnUserInputRequest != nil { req.RequestUserInput = Bool(true) } @@ -806,6 +909,7 @@ func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Ses s.registerTools(config.Tools) s.registerPermissionHandler(config.OnPermissionRequest) + s.registerMCPAuthHandler(config.OnMCPAuthRequest) if config.OnUserInputRequest != nil { s.registerUserInputHandler(config.OnUserInputRequest) } @@ -937,6 +1041,14 @@ func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Ses c.sessionsMux.Unlock() return nil, fmt.Errorf("session.create returned sessionId %s but the caller requested %s", response.SessionID, localSessionID) } + if config.OnMCPAuthRequest != nil { + if _, err := c.client.Request(ctx, "session.eventLog.registerInterest", map[string]any{ + "sessionId": session.SessionID, + "eventType": "mcp.oauth_required", + }); err != nil { + return nil, err + } + } session.workspacePath = response.WorkspacePath session.setCapabilities(response.Capabilities) @@ -1015,6 +1127,9 @@ func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, req.AvailableTools = availableTools req.ExcludedTools = excludedTools req.ToolFilterPrecedence = precedence + req.ExcludedBuiltInAgents = config.ExcludedBuiltInAgents + req.EnableCitations = config.EnableCitations + req.SessionLimits = config.SessionLimits if config.Streaming != nil { req.Streaming = config.Streaming } @@ -1023,6 +1138,9 @@ func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, } else { req.IncludeSubAgentStreamingEvents = Bool(true) } + if c.options.OnGitHubTelemetry != nil { + req.EnableGitHubTelemetryForwarding = Bool(true) + } if config.OnUserInputRequest != nil { req.RequestUserInput = Bool(true) } @@ -1063,15 +1181,20 @@ func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, req.DisabledSkills = config.DisabledSkills req.InfiniteSessions = config.InfiniteSessions req.LargeOutput = config.LargeOutput + req.ToolSearch = config.ToolSearch req.Memory = config.Memory req.GitHubToken = config.GitHubToken req.RemoteSession = config.RemoteSession req.Canvases = config.Canvases req.OpenCanvases = config.OpenCanvases + req.ExtensionInfo = config.ExtensionInfo + req.CanvasProvider = config.CanvasProvider req.RequestCanvasRenderer = config.RequestCanvasRenderer req.RequestExtensions = config.RequestExtensions req.ExtensionSDKPath = config.ExtensionSDKPath + req.ExtensionInfo = config.ExtensionInfo req.ExpAssignments = config.ExpAssignments + req.EnableManagedSettings = config.EnableManagedSettings if config.OnPermissionRequest != nil { req.RequestPermission = Bool(true) } @@ -1106,6 +1229,7 @@ func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, session.registerTools(config.Tools) session.registerPermissionHandler(config.OnPermissionRequest) + session.registerMCPAuthHandler(config.OnMCPAuthRequest) if config.OnUserInputRequest != nil { session.registerUserInputHandler(config.OnUserInputRequest) } @@ -1176,6 +1300,18 @@ func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, return nil, fmt.Errorf("failed to unmarshal response: %w", err) } + if config.OnMCPAuthRequest != nil { + if _, err := c.client.Request(ctx, "session.eventLog.registerInterest", map[string]any{ + "sessionId": sessionID, + "eventType": "mcp.oauth_required", + }); err != nil { + c.sessionsMux.Lock() + delete(c.sessions, sessionID) + c.sessionsMux.Unlock() + return nil, err + } + } + session.workspacePath = response.WorkspacePath session.setCapabilities(response.Capabilities) session.setOpenCanvases(response.OpenCanvases) @@ -1651,7 +1787,15 @@ func (c *Client) verifyProtocolVersion(ctx context.Context) error { t := c.effectiveConnectionToken tokenPtr = &t } - connectResult, err := c.internalRPC.Connect(ctx, &rpc.ConnectRequest{Token: tokenPtr}) + connectReq := &connectHandshakeRequest{Token: tokenPtr} + // Opt in to GitHub telemetry forwarding at the connection level when a handler is + // registered (mirrors the runtime, which reads this flag on the `connect` handshake + // so the first session's un-replayable `session.start` event is forwarded). Also + // sent on session.create/resume for older CLIs. + if c.options.OnGitHubTelemetry != nil { + connectReq.EnableGitHubTelemetryForwarding = Bool(true) + } + rawConnectResult, err := c.client.Request(ctx, "connect", connectReq) if err != nil { var rpcErr *jsonrpc2.Error if errors.As(err, &rpcErr) && (rpcErr.Code == jsonrpc2.ErrMethodNotFound.Code || rpcErr.Message == "Unhandled method connect") { @@ -1666,6 +1810,10 @@ func (c *Client) verifyProtocolVersion(ctx context.Context) error { return err } } else { + var connectResult rpc.ConnectResult + if err := json.Unmarshal(rawConnectResult, &connectResult); err != nil { + return err + } v := int(connectResult.ProtocolVersion) serverVersion = &v } @@ -1682,6 +1830,11 @@ func (c *Client) verifyProtocolVersion(ctx context.Context) error { return nil } +type connectHandshakeRequest struct { + Token *string `json:"token,omitempty"` + EnableGitHubTelemetryForwarding *bool `json:"enableGitHubTelemetryForwarding,omitempty"` +} + // stderrBufferSize is the maximum number of bytes kept from the CLI process's // stderr. Only the tail is retained so that memory stays bounded even when the // process produces a large amount of diagnostic output. @@ -1692,6 +1845,10 @@ const stderrBufferSize = 64 * 1024 // This spawns the CLI server as a subprocess using the configured transport // mode (stdio or TCP). func (c *Client) startCLIServer(ctx context.Context) error { + if c.useInProcess { + return c.startInProcess(ctx) + } + cliPath := c.cliPath if cliPath == "" { // If no CLI path is provided, attempt to use the embedded CLI if available @@ -1901,7 +2058,122 @@ func (c *Client) startCLIServer(ctx context.Context) error { } } +// startInProcess loads the native runtime library and wires the JSON-RPC client +// to its FFI byte streams. +func (c *Client) startInProcess(ctx context.Context) error { + if !inProcessAvailable { + return errors.New("in-process transport unavailable: rebuild with -tags copilot_inprocess on a supported platform") + } + + runtimePath := c.cliPath + if runtimePath == "" { + // The in-process transport does not resolve a bare command name from PATH + // (unlike the child-process transport). + if p := getEnvValue(c.options.Env, "COPILOT_CLI_PATH"); p != "" { + runtimePath = p + } + } + if runtimePath == "" { + runtimePath = embeddedcli.Path() + } + if runtimePath == "" { + return errors.New("in-process runtime unavailable: set COPILOT_CLI_PATH to a compatible runtime package or build with the bundled embedded runtime") + } + + config := c.inProcessHostConfig() + + host, err := createInProcessHost(runtimePath, config) + if err != nil { + return err + } + // Own the host before the blocking handshake so a cancelled or failed start + // leaves it disposable by Stop/ForceStop rather than leaking (host.Start runs + // on its own goroutine and cannot be interrupted once the native call begins). + c.ffiHost = host + + errCh := make(chan error, 1) + go func() { errCh <- host.Start() }() + select { + case err := <-errCh: + if err != nil { + host.Dispose() + c.ffiHost = nil + return err + } + case <-ctx.Done(): + c.ffiHost = nil + go func() { + <-errCh + host.Dispose() + }() + return ctx.Err() + } + + c.client = jsonrpc2.NewClient(host.Writer(), host.Reader()) + c.client.SetOnClose(func() { + // Run in a goroutine to avoid deadlocking with Stop/ForceStop, which hold + // startStopMux while waiting for readLoop to finish. + go func() { + c.startStopMux.Lock() + defer c.startStopMux.Unlock() + c.state = stateDisconnected + }() + }) + c.RPC = rpc.NewServerRPC(c.client) + c.internalRPC = rpc.NewInternalServerRPC(c.client) + c.setupNotificationHandler() + c.client.Start() + return nil +} + +func (c *Client) inProcessHostConfig() inProcessHostConfig { + args := make([]string, 0, 8) + if c.options.LogLevel != "" { + args = append(args, "--log-level", c.options.LogLevel) + } + if c.options.GitHubToken != "" { + args = append(args, "--auth-token-env", "COPILOT_SDK_AUTH_TOKEN") + } + useLoggedInUser := true + if c.options.UseLoggedInUser != nil { + useLoggedInUser = *c.options.UseLoggedInUser + } else if c.options.GitHubToken != "" { + useLoggedInUser = false + } + if !useLoggedInUser { + args = append(args, "--no-auto-login") + } + if c.options.SessionIdleTimeoutSeconds > 0 { + args = append(args, "--session-idle-timeout", strconv.Itoa(c.options.SessionIdleTimeoutSeconds)) + } + if c.options.EnableRemoteSessions { + args = append(args, "--remote") + } + + environment := make(map[string]string) + if c.options.GitHubToken != "" { + environment["COPILOT_SDK_AUTH_TOKEN"] = c.options.GitHubToken + } + if c.options.BaseDirectory != "" { + environment["COPILOT_HOME"] = c.options.BaseDirectory + } + if c.options.Mode == ModeEmpty { + environment["COPILOT_DISABLE_KEYTAR"] = "1" + } + + return inProcessHostConfig{ + Environment: environment, + Args: args, + } +} + func (c *Client) killProcess() error { + // Tear down the in-process FFI host on error paths that reuse killProcess to + // abort a start (there is no OS process to kill in that mode). + if c.ffiHost != nil { + c.ffiHost.Dispose() + c.ffiHost = nil + } if p := c.osProcess.Swap(nil); p != nil { if err := p.Kill(); err != nil { return fmt.Errorf("failed to kill CLI process: %w", err) @@ -1963,8 +2235,8 @@ func (c *Client) monitorProcess() { // connectToServer establishes a connection to the server. func (c *Client) connectToServer(ctx context.Context) error { - if c.useStdio { - // Already connected via stdio in startCLIServer + if c.useStdio || c.useInProcess { + // Already connected: stdio in startCLIServer, FFI streams in startInProcess. return nil } @@ -2018,7 +2290,6 @@ func (c *Client) setupNotificationHandler() { c.client.SetRequestHandler("userInput.request", jsonrpc2.RequestHandlerFor(c.handleUserInputRequest)) c.client.SetRequestHandler("exitPlanMode.request", jsonrpc2.RequestHandlerFor(c.handleExitPlanModeRequest)) c.client.SetRequestHandler("autoModeSwitch.request", jsonrpc2.RequestHandlerFor(c.handleAutoModeSwitchRequest)) - c.client.SetRequestHandler("hooks.invoke", jsonrpc2.RequestHandlerFor(c.handleHooksInvoke)) c.client.SetRequestHandler("systemMessage.transform", jsonrpc2.RequestHandlerFor(c.handleSystemMessageTransform)) rpc.RegisterClientSessionAPIHandlers(c.client, func(sessionID string) *rpc.ClientSessionAPIHandlers { c.sessionsMux.Lock() @@ -2029,15 +2300,37 @@ func (c *Client) setupNotificationHandler() { } return session.clientSessionAPIs }) + // hooks.invoke is a client-global RPC method: one connection-level handler + // receives every hook callback and routes to the owning session via the + // payload's sessionId. Always register the global handlers so the generated + // hooks.invoke handler is wired to our dispatcher. + handlers := &rpc.ClientGlobalAPIHandlers{ + Hooks: &hooksAdapter{client: c}, + } if c.options.RequestHandler != nil { - adapter := newCopilotRequestAdapter(c.options.RequestHandler, func() *rpc.ServerLlmInferenceAPI { + handlers.LlmInference = newCopilotRequestAdapter(c.options.RequestHandler, func() *rpc.ServerLlmInferenceAPI { if c.RPC == nil { return nil } return c.RPC.LlmInference }) - rpc.RegisterClientGlobalAPIHandlers(c.client, &rpc.ClientGlobalAPIHandlers{LlmInference: adapter}) } + if c.options.OnGitHubTelemetry != nil { + handlers.GitHubTelemetry = &gitHubTelemetryAdapter{callback: c.options.OnGitHubTelemetry} + } + rpc.RegisterClientGlobalAPIHandlers(c.client, handlers) +} + +// gitHubTelemetryAdapter adapts the OnGitHubTelemetry option to the generated +// rpc.GitHubTelemetryHandler interface. +type gitHubTelemetryAdapter struct { + callback func(notification *rpc.GitHubTelemetryNotification) +} + +func (a *gitHubTelemetryAdapter) Event(request *rpc.GitHubTelemetryNotification) error { + defer func() { recover() }() // Ignore handler panics + a.callback(request) + return nil } func (c *Client) handleSessionEvent(req sessionEventRequest) { @@ -2133,7 +2426,8 @@ func (c *Client) handleAutoModeSwitchRequest(req autoModeSwitchRequest) (*autoMo return &autoModeSwitchResponse{Response: response}, nil } -// handleHooksInvoke handles a hooks invocation from the CLI server. +// handleHooksInvoke routes a hook callback to its owning session, keyed by the +// payload's sessionId. func (c *Client) handleHooksInvoke(req hooksInvokeRequest) (map[string]any, *jsonrpc2.Error) { if req.SessionID == "" || req.Type == "" { return nil, &jsonrpc2.Error{Code: -32602, Message: "invalid hooks invoke payload"} @@ -2158,6 +2452,34 @@ func (c *Client) handleHooksInvoke(req hooksInvokeRequest) (map[string]any, *jso return result, nil } +// hooksAdapter implements the generated rpc.HooksHandler, delegating to the +// client's per-session hook dispatcher. +type hooksAdapter struct { + client *Client +} + +func (a *hooksAdapter) Invoke(request *rpc.HookInvokeRequest) (*rpc.HookInvokeResponse, error) { + rawInput, err := json.Marshal(request.Input) + if err != nil { + return nil, &jsonrpc2.Error{Code: -32602, Message: fmt.Sprintf("invalid hooks invoke payload: %v", err)} + } + + result, rpcErr := a.client.handleHooksInvoke(hooksInvokeRequest{ + SessionID: request.SessionID, + Type: string(request.HookType), + Input: rawInput, + }) + if rpcErr != nil { + return nil, rpcErr + } + + response := &rpc.HookInvokeResponse{} + if result != nil { + response.Output = result["output"] + } + return response, nil +} + // handleSystemMessageTransform handles a system message transform request from the CLI server. func (c *Client) handleSystemMessageTransform(req systemMessageTransformRequest) (systemMessageTransformResponse, *jsonrpc2.Error) { if req.SessionID == "" { diff --git a/go/client_test.go b/go/client_test.go index d59c71c6f9..b24628d836 100644 --- a/go/client_test.go +++ b/go/client_test.go @@ -3,6 +3,8 @@ package copilot import ( "context" "encoding/json" + "fmt" + "io" "net" "os" "os/exec" @@ -13,6 +15,7 @@ import ( "strings" "sync" "testing" + "time" "github.com/github/copilot-sdk/go/internal/jsonrpc2" "github.com/github/copilot-sdk/go/internal/truncbuffer" @@ -248,6 +251,125 @@ func TestClient_ForwardsCapiOptionsToSessionRequests(t *testing.T) { assertCapiEnableWebSocketResponses(t, <-resumeParams) } +func TestClient_ForwardsCanvasProviderToSessionRequests(t *testing.T) { + rpcClient, server, _ := newRuntimeShutdownRpcPair(t) + t.Cleanup(server.Stop) + client := &Client{ + client: rpcClient, + RPC: rpc.NewServerRPC(rpcClient), + sessions: make(map[string]*Session), + } + + createParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.create", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + createParams <- append(json.RawMessage(nil), params...) + sessionID := sessionIDFromParams(t, params) + return []byte(`{"sessionId":"` + sessionID + `","workspacePath":"/workspace"}`), nil + }) + + _, err := client.CreateSession(t.Context(), &SessionConfig{ + ExtensionInfo: &ExtensionInfo{Source: "github-app", Name: "counter-provider"}, + CanvasProvider: &CanvasProviderIdentity{ID: "app:builtin:window-1", Name: String("Built-in")}, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + assertCanvasProviderForwarded(t, <-createParams, "app:builtin:window-1", "Built-in", "counter-provider") + + resumeParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.resume", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + resumeParams <- append(json.RawMessage(nil), params...) + return []byte(`{"sessionId":"resumed-canvas","workspacePath":"/workspace"}`), nil + }) + + _, err = client.ResumeSessionWithOptions(t.Context(), "resumed-canvas", &ResumeSessionConfig{ + CanvasProvider: &CanvasProviderIdentity{ID: "app:builtin:window-1"}, + }) + if err != nil { + t.Fatalf("ResumeSessionWithOptions failed: %v", err) + } + assertCanvasProviderForwarded(t, <-resumeParams, "app:builtin:window-1", "", "") +} + +// assertCanvasProviderForwarded checks the outbound params carry canvasProvider +// with the expected id. A non-empty wantName asserts the name is present; an +// empty wantName asserts the name key is omitted from the wire. A non-empty +// wantExtensionName asserts extensionInfo.name is forwarded alongside it. +func assertCanvasProviderForwarded(t *testing.T, params json.RawMessage, wantID, wantName, wantExtensionName string) { + t.Helper() + + var decoded map[string]any + if err := json.Unmarshal(params, &decoded); err != nil { + t.Fatalf("failed to unmarshal request params: %v", err) + } + provider, ok := decoded["canvasProvider"].(map[string]any) + if !ok { + t.Fatalf("expected canvasProvider object in request params, got %T", decoded["canvasProvider"]) + } + if provider["id"] != wantID { + t.Fatalf("expected canvasProvider.id=%q, got %v", wantID, provider["id"]) + } + if wantName == "" { + if _, present := provider["name"]; present { + t.Fatalf("expected canvasProvider.name to be omitted, got %v", provider["name"]) + } + } else if provider["name"] != wantName { + t.Fatalf("expected canvasProvider.name=%q, got %v", wantName, provider["name"]) + } + if wantExtensionName != "" { + info, ok := decoded["extensionInfo"].(map[string]any) + if !ok { + t.Fatalf("expected extensionInfo object in request params, got %T", decoded["extensionInfo"]) + } + if info["name"] != wantExtensionName { + t.Fatalf("expected extensionInfo.name=%q, got %v", wantExtensionName, info["name"]) + } + } +} + +func TestClient_ForwardsNewSessionOptionsToSessionRequests(t *testing.T) { + rpcClient, server, _ := newRuntimeShutdownRpcPair(t) + t.Cleanup(server.Stop) + client := &Client{ + client: rpcClient, + RPC: rpc.NewServerRPC(rpcClient), + sessions: make(map[string]*Session), + } + + createParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.create", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + createParams <- append(json.RawMessage(nil), params...) + sessionID := sessionIDFromParams(t, params) + return []byte(`{"sessionId":"` + sessionID + `","workspacePath":"/workspace"}`), nil + }) + + _, err := client.CreateSession(t.Context(), &SessionConfig{ + ExcludedBuiltInAgents: []string{"explore"}, + EnableCitations: Bool(true), + SessionLimits: &rpc.SessionLimitsConfig{MaxAiCredits: float64Ptr(30)}, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + assertNewSessionOptions(t, <-createParams, true, "explore", 30) + + resumeParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.resume", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + resumeParams <- append(json.RawMessage(nil), params...) + return []byte(`{"sessionId":"resumed-options","workspacePath":"/workspace"}`), nil + }) + + _, err = client.ResumeSessionWithOptions(t.Context(), "resumed-options", &ResumeSessionConfig{ + ExcludedBuiltInAgents: []string{"task"}, + EnableCitations: Bool(false), + SessionLimits: &rpc.SessionLimitsConfig{MaxAiCredits: float64Ptr(15)}, + }) + if err != nil { + t.Fatalf("ResumeSessionWithOptions failed: %v", err) + } + assertNewSessionOptions(t, <-resumeParams, false, "task", 15) +} + func assertCapiEnableWebSocketResponses(t *testing.T, params json.RawMessage) { t.Helper() @@ -255,6 +377,7 @@ func assertCapiEnableWebSocketResponses(t *testing.T, params json.RawMessage) { if err := json.Unmarshal(params, &decoded); err != nil { t.Fatalf("failed to unmarshal request params: %v", err) } + capi, ok := decoded["capi"].(map[string]any) if !ok { t.Fatalf("expected capi object in request params, got %T", decoded["capi"]) @@ -264,6 +387,39 @@ func assertCapiEnableWebSocketResponses(t *testing.T, params json.RawMessage) { } } +func assertNewSessionOptions( + t *testing.T, + params json.RawMessage, + expectedCitations bool, + expectedAgent string, + expectedCredits float64, +) { + t.Helper() + + var decoded map[string]any + if err := json.Unmarshal(params, &decoded); err != nil { + t.Fatalf("failed to unmarshal request params: %v", err) + } + if decoded["enableCitations"] != expectedCitations { + t.Fatalf("expected enableCitations=%v, got %v", expectedCitations, decoded["enableCitations"]) + } + agents, ok := decoded["excludedBuiltinAgents"].([]any) + if !ok || len(agents) != 1 || agents[0] != expectedAgent { + t.Fatalf("expected excludedBuiltinAgents=[%q], got %#v", expectedAgent, decoded["excludedBuiltinAgents"]) + } + limits, ok := decoded["sessionLimits"].(map[string]any) + if !ok { + t.Fatalf("expected sessionLimits object, got %T", decoded["sessionLimits"]) + } + if limits["maxAiCredits"] != expectedCredits { + t.Fatalf("expected sessionLimits.maxAiCredits=%v, got %v", expectedCredits, limits["maxAiCredits"]) + } +} + +func float64Ptr(value float64) *float64 { + return &value +} + func sessionIDFromParams(t *testing.T, params json.RawMessage) string { t.Helper() @@ -469,6 +625,198 @@ func TestClient_EnvOptions(t *testing.T) { }) } +func TestClient_InProcessConnection(t *testing.T) { + t.Run("requires build tag", func(t *testing.T) { + if inProcessAvailable { + t.Skip("in-process transport is enabled") + } + + client := NewClient(&ClientOptions{Connection: InProcessConnection{}}) + err := client.Start(context.Background()) + if err == nil || !strings.Contains(err.Error(), "-tags copilot_inprocess") { + t.Fatalf("Expected build-tag error, got %v", err) + } + }) + + t.Run("uses in-process transport", func(t *testing.T) { + client := NewClient(&ClientOptions{Connection: InProcessConnection{}}) + if !client.useInProcess { + t.Error("Expected useInProcess=true for InProcessConnection") + } + if client.useStdio { + t.Error("Expected useStdio=false for InProcessConnection") + } + if client.isExternalServer { + t.Error("Expected isExternalServer=false for InProcessConnection") + } + if client.cliPath != "" { + t.Errorf("Expected in-process cliPath to stay empty at construction, got %q", client.cliPath) + } + }) + + t.Run("does not resolve COPILOT_CLI_PATH into cliPath at construction", func(t *testing.T) { + t.Setenv("COPILOT_CLI_PATH", "/from/env/copilot") + client := NewClient(&ClientOptions{Connection: InProcessConnection{}}) + if client.cliPath != "" { + t.Errorf("Expected in-process cliPath to stay empty at construction, got %q", client.cliPath) + } + }) + + t.Run("panics when Env is set", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Expected panic when Env is set with InProcessConnection") + } + }() + NewClient(&ClientOptions{ + Connection: InProcessConnection{}, + Env: []string{"FOO=bar"}, + }) + }) + + t.Run("panics when WorkingDirectory is set", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Expected panic when WorkingDirectory is set with InProcessConnection") + } + }() + NewClient(&ClientOptions{ + Connection: InProcessConnection{}, + WorkingDirectory: "/tmp/work", + }) + }) + + t.Run("panics when Telemetry is set", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Expected panic when Telemetry is set with InProcessConnection") + } + }() + NewClient(&ClientOptions{ + Connection: InProcessConnection{}, + Telemetry: &TelemetryConfig{ExporterType: "file"}, + }) + }) + + t.Run("forwards typed runtime options", func(t *testing.T) { + client := NewClient(&ClientOptions{ + Connection: InProcessConnection{}, + GitHubToken: "test-token", + UseLoggedInUser: Bool(false), + BaseDirectory: "/copilot-home", + LogLevel: "debug", + SessionIdleTimeoutSeconds: 30, + EnableRemoteSessions: true, + Mode: ModeEmpty, + }) + + config := client.inProcessHostConfig() + expectedArgs := []string{ + "--log-level", "debug", + "--auth-token-env", "COPILOT_SDK_AUTH_TOKEN", + "--no-auto-login", + "--session-idle-timeout", "30", + "--remote", + } + if !reflect.DeepEqual(config.Args, expectedArgs) { + t.Fatalf("Expected managed arguments %v, got %v", expectedArgs, config.Args) + } + expectedEnvironment := map[string]string{ + "COPILOT_SDK_AUTH_TOKEN": "test-token", + "COPILOT_HOME": "/copilot-home", + "COPILOT_DISABLE_KEYTAR": "1", + } + if !reflect.DeepEqual(config.Environment, expectedEnvironment) { + t.Fatalf("Expected managed environment %v, got %v", expectedEnvironment, config.Environment) + } + }) +} + +func TestClient_DefaultConnection(t *testing.T) { + t.Run("defaults to stdio when override is unset", func(t *testing.T) { + t.Setenv(defaultConnectionEnvVar, "") + + client := NewClient(nil) + + if !client.useStdio || client.useInProcess { + t.Fatalf("Expected stdio default, got useStdio=%v useInProcess=%v", client.useStdio, client.useInProcess) + } + }) + + t.Run("selects in-process case-insensitively", func(t *testing.T) { + t.Setenv(defaultConnectionEnvVar, "InPrOcEsS") + + client := NewClient(nil) + + if !client.useInProcess || client.useStdio { + t.Fatalf("Expected in-process default, got useStdio=%v useInProcess=%v", client.useStdio, client.useInProcess) + } + }) + + t.Run("accepts explicit stdio override", func(t *testing.T) { + t.Setenv(defaultConnectionEnvVar, "STDIO") + + client := NewClient(nil) + + if !client.useStdio || client.useInProcess { + t.Fatalf("Expected stdio default, got useStdio=%v useInProcess=%v", client.useStdio, client.useInProcess) + } + }) + + t.Run("explicit connection takes precedence", func(t *testing.T) { + t.Setenv(defaultConnectionEnvVar, "inprocess") + + client := NewClient(&ClientOptions{Connection: TCPConnection{Port: 1234}}) + + if client.useInProcess || client.useStdio || client.port != 1234 { + t.Fatalf("Expected explicit TCP connection to win, got useStdio=%v useInProcess=%v port=%d", client.useStdio, client.useInProcess, client.port) + } + }) + + t.Run("panics for invalid override", func(t *testing.T) { + t.Setenv(defaultConnectionEnvVar, "tcp") + + defer func() { + if r := recover(); r == nil { + t.Fatal("Expected invalid default connection override to panic") + } + }() + NewClient(nil) + }) +} + +func TestClient_ConnectionLevelEnv(t *testing.T) { + t.Run("rejects env set on both client and connection", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Expected panic when env is set on both client and connection") + } + }() + NewClient(&ClientOptions{ + Connection: StdioConnection{Env: []string{"A=1"}}, + Env: []string{"B=2"}, + }) + }) + + t.Run("stdio connection env is used when client env is unset", func(t *testing.T) { + client := NewClient(&ClientOptions{ + Connection: StdioConnection{Env: []string{"ONLY=conn"}}, + }) + if len(client.options.Env) != 1 || client.options.Env[0] != "ONLY=conn" { + t.Errorf("Expected connection-level Env to be used, got %v", client.options.Env) + } + }) + + t.Run("tcp connection env is used when client env is unset", func(t *testing.T) { + client := NewClient(&ClientOptions{ + Connection: TCPConnection{Port: 9000, Env: []string{"ONLY=conn"}}, + }) + if len(client.options.Env) != 1 || client.options.Env[0] != "ONLY=conn" { + t.Errorf("Expected connection-level Env to be used, got %v", client.options.Env) + } + }) +} + func TestClient_SessionIdleTimeoutSeconds(t *testing.T) { t.Run("should store SessionIdleTimeoutSeconds option", func(t *testing.T) { client := NewClient(&ClientOptions{ @@ -1080,6 +1428,53 @@ func TestToolDefer(t *testing.T) { }) } +func TestToolMetadata(t *testing.T) { + t.Run("Metadata is serialized in tool definition", func(t *testing.T) { + tool := Tool{ + Name: "my_tool", + Description: "A custom tool", + Metadata: map[string]any{ + "github.com/copilot:safeForTelemetry": map[string]any{"name": true, "inputsNames": false}, + }, + Handler: func(_ ToolInvocation) (ToolResult, error) { return ToolResult{}, nil }, + } + data, err := json.Marshal(tool) + if err != nil { + t.Fatalf("failed to marshal: %v", err) + } + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("failed to unmarshal: %v", err) + } + meta, ok := m["metadata"].(map[string]any) + if !ok { + t.Fatalf("expected metadata object, got %v", m) + } + if _, ok := meta["github.com/copilot:safeForTelemetry"]; !ok { + t.Errorf("expected namespaced key preserved, got %v", meta) + } + }) + + t.Run("Metadata omitted when unset", func(t *testing.T) { + tool := Tool{ + Name: "custom_tool", + Description: "A custom tool", + Handler: func(_ ToolInvocation) (ToolResult, error) { return ToolResult{}, nil }, + } + data, err := json.Marshal(tool) + if err != nil { + t.Fatalf("failed to marshal: %v", err) + } + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("failed to unmarshal: %v", err) + } + if _, ok := m["metadata"]; ok { + t.Errorf("expected metadata to be omitted, got %v", m) + } + }) +} + func TestClient_CreateSession_AllowsMissingPermissionHandler(t *testing.T) { t.Run("accepts nil config before connection validation", func(t *testing.T) { client := NewClient(&ClientOptions{Connection: StdioConnection{Path: "/__nonexistent_copilot_binary__"}}) @@ -1315,6 +1710,291 @@ func TestClient_StartStopRace(t *testing.T) { } } +func TestClient_MCPAuthInterestRegistration(t *testing.T) { + t.Run("create skips MCP OAuth interest without auth handler", func(t *testing.T) { + client, requests, cleanup := newInMemoryClient(t) + defer cleanup() + + session, err := client.CreateSession(t.Context(), &SessionConfig{ + OnPermissionRequest: PermissionHandler.ApproveAll, + OnEvent: func(SessionEvent) {}, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + defer session.Disconnect() + + assertNoMCPAuthInterest(t, requests.snapshot()) + assertRequestMethod(t, requests.snapshot(), "session.create") + assertCreateRequestPermission(t, requests.snapshot()) + }) + + t.Run("create registers MCP OAuth interest after local session create when auth handler is configured", func(t *testing.T) { + client, requests, cleanup := newInMemoryClient(t) + defer cleanup() + + session, err := client.CreateSession(t.Context(), &SessionConfig{ + OnPermissionRequest: PermissionHandler.ApproveAll, + OnMCPAuthRequest: func(MCPAuthRequest, MCPAuthInvocation) (*MCPAuthResult, error) { + return MCPAuthResultCancelled(), nil + }, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + defer session.Disconnect() + + snapshot := requests.snapshot() + assertRequestMethod(t, snapshot, "session.eventLog.registerInterest") + if snapshot[0].Method != "session.create" { + t.Fatalf("expected session.create before MCP auth interest, got %s", snapshot[0].Method) + } + if snapshot[1].Method != "session.eventLog.registerInterest" { + t.Fatalf("expected MCP auth interest after session.create, got %s", snapshot[1].Method) + } + assertMCPAuthInterest(t, snapshot[1]) + assertCreateRequestPermission(t, snapshot) + }) + + t.Run("cloud create registers MCP OAuth interest after server assigns id only when auth handler is configured", func(t *testing.T) { + client, requests, cleanup := newInMemoryClient(t) + defer cleanup() + + withoutAuth, err := client.CreateSession(t.Context(), &SessionConfig{ + OnPermissionRequest: PermissionHandler.ApproveAll, + Cloud: &CloudSessionOptions{ + Repository: &CloudSessionRepository{Owner: "github", Name: "copilot-sdk", Branch: "main"}, + }, + }) + if err != nil { + t.Fatalf("CreateSession without auth failed: %v", err) + } + defer withoutAuth.Disconnect() + + assertNoMCPAuthInterest(t, requests.snapshot()) + requests.clear() + + withAuth, err := client.CreateSession(t.Context(), &SessionConfig{ + OnPermissionRequest: PermissionHandler.ApproveAll, + OnMCPAuthRequest: func(MCPAuthRequest, MCPAuthInvocation) (*MCPAuthResult, error) { + return MCPAuthResultCancelled(), nil + }, + Cloud: &CloudSessionOptions{ + Repository: &CloudSessionRepository{Owner: "github", Name: "copilot-sdk", Branch: "main"}, + }, + }) + if err != nil { + t.Fatalf("CreateSession with auth failed: %v", err) + } + defer withAuth.Disconnect() + + snapshot := requests.snapshot() + if snapshot[0].Method != "session.create" { + t.Fatalf("expected cloud session.create before MCP auth interest, got %s", snapshot[0].Method) + } + if snapshot[1].Method != "session.eventLog.registerInterest" { + t.Fatalf("expected MCP auth interest after cloud session.create, got %s", snapshot[1].Method) + } + assertMCPAuthInterest(t, snapshot[1]) + }) + + t.Run("resume conditionally registers MCP OAuth interest after session resume", func(t *testing.T) { + client, requests, cleanup := newInMemoryClient(t) + defer cleanup() + + withoutAuth, err := client.ResumeSession(t.Context(), "session-without-auth", &ResumeSessionConfig{ + OnPermissionRequest: PermissionHandler.ApproveAll, + OnEvent: func(SessionEvent) {}, + }) + if err != nil { + t.Fatalf("ResumeSession without auth failed: %v", err) + } + defer withoutAuth.Disconnect() + + assertNoMCPAuthInterest(t, requests.snapshot()) + assertRequestMethod(t, requests.snapshot(), "session.resume") + requests.clear() + + withAuth, err := client.ResumeSession(t.Context(), "session-with-auth", &ResumeSessionConfig{ + OnPermissionRequest: PermissionHandler.ApproveAll, + OnMCPAuthRequest: func(MCPAuthRequest, MCPAuthInvocation) (*MCPAuthResult, error) { + return MCPAuthResultCancelled(), nil + }, + }) + if err != nil { + t.Fatalf("ResumeSession with auth failed: %v", err) + } + defer withAuth.Disconnect() + + snapshot := requests.snapshot() + if snapshot[0].Method != "session.resume" { + t.Fatalf("expected session.resume before MCP auth interest, got %s", snapshot[0].Method) + } + if snapshot[1].Method != "session.eventLog.registerInterest" { + t.Fatalf("expected MCP auth interest after session.resume, got %s", snapshot[1].Method) + } + assertMCPAuthInterest(t, snapshot[1]) + }) +} + +type recordedRequest struct { + Method string + Params map[string]any +} + +type requestRecorder struct { + mu sync.Mutex + requests []recordedRequest +} + +func (r *requestRecorder) append(request recordedRequest) { + r.mu.Lock() + defer r.mu.Unlock() + r.requests = append(r.requests, request) +} + +func (r *requestRecorder) snapshot() []recordedRequest { + r.mu.Lock() + defer r.mu.Unlock() + out := make([]recordedRequest, len(r.requests)) + copy(out, r.requests) + return out +} + +func (r *requestRecorder) clear() { + r.mu.Lock() + defer r.mu.Unlock() + r.requests = nil +} + +func newInMemoryClient(t *testing.T) (*Client, *requestRecorder, func()) { + t.Helper() + + stdinR, stdinW := io.Pipe() + stdoutR, stdoutW := io.Pipe() + rpcClient := jsonrpc2.NewClient(stdinW, stdoutR) + rpcClient.Start() + + client := NewClient(&ClientOptions{}) + client.client = rpcClient + client.RPC = rpc.NewServerRPC(rpcClient) + client.state = stateConnected + + requests := &requestRecorder{} + done := make(chan struct{}) + go serveInMemoryRuntime(t, stdinR, stdoutW, requests, done) + + cleanup := func() { + rpcClient.Stop() + stdinR.Close() + stdinW.Close() + stdoutR.Close() + stdoutW.Close() + <-done + } + return client, requests, cleanup +} + +func serveInMemoryRuntime(t *testing.T, stdinR *io.PipeReader, stdoutW *io.PipeWriter, requests *requestRecorder, done chan<- struct{}) { + t.Helper() + defer close(done) + + serverAssignedSessions := 0 + for { + frame, err := readTestJSONRPCFrame(stdinR) + if err != nil { + return + } + + var request struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params map[string]any `json:"params"` + } + if err := json.Unmarshal(frame, &request); err != nil { + t.Errorf("failed to unmarshal JSON-RPC request: %v", err) + return + } + requests.append(recordedRequest{Method: request.Method, Params: request.Params}) + + var result map[string]any + switch request.Method { + case "session.create", "session.resume": + sessionID, _ := request.Params["sessionId"].(string) + if sessionID == "" { + serverAssignedSessions++ + sessionID = fmt.Sprintf("server-assigned-session-%d", serverAssignedSessions) + } + result = map[string]any{"sessionId": sessionID, "workspacePath": nil} + case "session.eventLog.registerInterest": + result = map[string]any{"id": "interest-1"} + case "session.options.update": + result = map[string]any{"success": true} + case "session.skills.reload", "session.destroy": + result = map[string]any{} + default: + t.Errorf("unexpected JSON-RPC method %s", request.Method) + return + } + + response := map[string]any{ + "jsonrpc": "2.0", + "id": json.RawMessage(request.ID), + "result": result, + } + data, err := json.Marshal(response) + if err != nil { + t.Errorf("failed to marshal JSON-RPC response: %v", err) + return + } + if _, err := fmt.Fprintf(stdoutW, "Content-Length: %d\r\n\r\n%s", len(data), data); err != nil { + return + } + } +} + +func assertRequestMethod(t *testing.T, requests []recordedRequest, method string) { + t.Helper() + for _, request := range requests { + if request.Method == method { + return + } + } + t.Fatalf("expected %s request in %+v", method, requests) +} + +func assertNoMCPAuthInterest(t *testing.T, requests []recordedRequest) { + t.Helper() + for _, request := range requests { + if request.Method == "session.eventLog.registerInterest" && request.Params["eventType"] == "mcp.oauth_required" { + t.Fatalf("did not expect MCP auth interest registration in %+v", requests) + } + } +} + +func assertMCPAuthInterest(t *testing.T, request recordedRequest) { + t.Helper() + if request.Method != "session.eventLog.registerInterest" { + t.Fatalf("expected registerInterest request, got %s", request.Method) + } + if request.Params["eventType"] != "mcp.oauth_required" { + t.Fatalf("expected mcp.oauth_required interest, got %v", request.Params["eventType"]) + } +} + +func assertCreateRequestPermission(t *testing.T, requests []recordedRequest) { + t.Helper() + for _, request := range requests { + if request.Method == "session.create" { + if request.Params["requestPermission"] != true { + t.Fatalf("expected create requestPermission=true, got %v", request.Params["requestPermission"]) + } + return + } + } + t.Fatalf("session.create request not found in %+v", requests) +} + func TestCreateSessionRequest_Commands(t *testing.T) { t.Run("forwards commands in session.create RPC", func(t *testing.T) { req := createSessionRequest{ @@ -1973,6 +2653,285 @@ func TestResumeSessionRequest_IncludeSubAgentStreamingEvents(t *testing.T) { }) } +func TestCreateSessionRequest_EnableGitHubTelemetryForwarding(t *testing.T) { + t.Run("forwards explicit true", func(t *testing.T) { + req := createSessionRequest{ + EnableGitHubTelemetryForwarding: Bool(true), + } + data, err := json.Marshal(req) + if err != nil { + t.Fatalf("Failed to marshal: %v", err) + } + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("Failed to unmarshal: %v", err) + } + if m["enableGitHubTelemetryForwarding"] != true { + t.Errorf("Expected enableGitHubTelemetryForwarding to be true, got %v", m["enableGitHubTelemetryForwarding"]) + } + }) + + t.Run("omits when not set", func(t *testing.T) { + req := createSessionRequest{} + data, _ := json.Marshal(req) + var m map[string]any + json.Unmarshal(data, &m) + if _, ok := m["enableGitHubTelemetryForwarding"]; ok { + t.Error("Expected enableGitHubTelemetryForwarding to be omitted when not set") + } + }) +} + +func TestResumeSessionRequest_EnableGitHubTelemetryForwarding(t *testing.T) { + t.Run("forwards explicit true", func(t *testing.T) { + req := resumeSessionRequest{ + SessionID: "s1", + EnableGitHubTelemetryForwarding: Bool(true), + } + data, err := json.Marshal(req) + if err != nil { + t.Fatalf("Failed to marshal: %v", err) + } + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("Failed to unmarshal: %v", err) + } + if m["enableGitHubTelemetryForwarding"] != true { + t.Errorf("Expected enableGitHubTelemetryForwarding to be true, got %v", m["enableGitHubTelemetryForwarding"]) + } + }) + + t.Run("omits when not set", func(t *testing.T) { + req := resumeSessionRequest{SessionID: "s1"} + data, _ := json.Marshal(req) + var m map[string]any + json.Unmarshal(data, &m) + if _, ok := m["enableGitHubTelemetryForwarding"]; ok { + t.Error("Expected enableGitHubTelemetryForwarding to be omitted when not set") + } + }) +} + +func TestClient_ForwardsGitHubTelemetryForwardingToSessionRequests(t *testing.T) { + rpcClient, server, _ := newRuntimeShutdownRpcPair(t) + t.Cleanup(server.Stop) + client := &Client{ + client: rpcClient, + RPC: rpc.NewServerRPC(rpcClient), + sessions: make(map[string]*Session), + options: ClientOptions{OnGitHubTelemetry: func(*rpc.GitHubTelemetryNotification) {}}, + } + + createParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.create", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + createParams <- append(json.RawMessage(nil), params...) + sessionID := sessionIDFromParams(t, params) + return []byte(`{"sessionId":"` + sessionID + `","workspacePath":"/workspace"}`), nil + }) + + if _, err := client.CreateSession(t.Context(), &SessionConfig{}); err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + assertForwardingFlagTrue(t, <-createParams) + + resumeParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.resume", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + resumeParams <- append(json.RawMessage(nil), params...) + return []byte(`{"sessionId":"resumed","workspacePath":"/workspace"}`), nil + }) + + if _, err := client.ResumeSessionWithOptions(t.Context(), "resumed", &ResumeSessionConfig{}); err != nil { + t.Fatalf("ResumeSessionWithOptions failed: %v", err) + } + assertForwardingFlagTrue(t, <-resumeParams) +} + +func assertForwardingFlagTrue(t *testing.T, params json.RawMessage) { + t.Helper() + var decoded map[string]any + if err := json.Unmarshal(params, &decoded); err != nil { + t.Fatalf("failed to unmarshal request params: %v", err) + } + if decoded["enableGitHubTelemetryForwarding"] != true { + t.Fatalf("expected enableGitHubTelemetryForwarding=true, got %v", decoded["enableGitHubTelemetryForwarding"]) + } +} + +func TestClient_OmitsGitHubTelemetryForwardingWhenNoHandler(t *testing.T) { + rpcClient, server, _ := newRuntimeShutdownRpcPair(t) + t.Cleanup(server.Stop) + client := &Client{ + client: rpcClient, + RPC: rpc.NewServerRPC(rpcClient), + sessions: make(map[string]*Session), + options: ClientOptions{}, + } + + createParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.create", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + createParams <- append(json.RawMessage(nil), params...) + sessionID := sessionIDFromParams(t, params) + return []byte(`{"sessionId":"` + sessionID + `","workspacePath":"/workspace"}`), nil + }) + + if _, err := client.CreateSession(t.Context(), &SessionConfig{}); err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + assertForwardingFlagAbsent(t, <-createParams) + + resumeParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("session.resume", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + resumeParams <- append(json.RawMessage(nil), params...) + return []byte(`{"sessionId":"resumed","workspacePath":"/workspace"}`), nil + }) + + if _, err := client.ResumeSessionWithOptions(t.Context(), "resumed", &ResumeSessionConfig{}); err != nil { + t.Fatalf("ResumeSessionWithOptions failed: %v", err) + } + assertForwardingFlagAbsent(t, <-resumeParams) +} + +func assertForwardingFlagAbsent(t *testing.T, params json.RawMessage) { + t.Helper() + var decoded map[string]any + if err := json.Unmarshal(params, &decoded); err != nil { + t.Fatalf("failed to unmarshal request params: %v", err) + } + if _, ok := decoded["enableGitHubTelemetryForwarding"]; ok { + t.Fatalf("expected enableGitHubTelemetryForwarding to be omitted, got %v", decoded["enableGitHubTelemetryForwarding"]) + } +} + +func TestClient_ForwardsGitHubTelemetryForwardingOnConnect(t *testing.T) { + rpcClient, server, _ := newRuntimeShutdownRpcPair(t) + t.Cleanup(server.Stop) + client := &Client{ + client: rpcClient, + RPC: rpc.NewServerRPC(rpcClient), + internalRPC: rpc.NewInternalServerRPC(rpcClient), + sessions: make(map[string]*Session), + options: ClientOptions{OnGitHubTelemetry: func(*rpc.GitHubTelemetryNotification) {}}, + } + + connectParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("connect", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + connectParams <- append(json.RawMessage(nil), params...) + return []byte(`{"ok":true,"protocolVersion":3,"version":"test"}`), nil + }) + + if err := client.verifyProtocolVersion(t.Context()); err != nil { + t.Fatalf("verifyProtocolVersion failed: %v", err) + } + assertForwardingFlagTrue(t, <-connectParams) +} + +func TestClient_OmitsGitHubTelemetryForwardingOnConnectWhenNoHandler(t *testing.T) { + rpcClient, server, _ := newRuntimeShutdownRpcPair(t) + t.Cleanup(server.Stop) + client := &Client{ + client: rpcClient, + RPC: rpc.NewServerRPC(rpcClient), + internalRPC: rpc.NewInternalServerRPC(rpcClient), + sessions: make(map[string]*Session), + options: ClientOptions{}, + } + + connectParams := make(chan json.RawMessage, 1) + server.SetRequestHandler("connect", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + connectParams <- append(json.RawMessage(nil), params...) + return []byte(`{"ok":true,"protocolVersion":3,"version":"test"}`), nil + }) + + if err := client.verifyProtocolVersion(t.Context()); err != nil { + t.Fatalf("verifyProtocolVersion failed: %v", err) + } + assertForwardingFlagAbsent(t, <-connectParams) +} + +func TestGitHubTelemetryNotificationRoutesToCallback(t *testing.T) { + // The runtime forwards telemetry via a JSON-RPC *notification* (no id). + // Drive a real Content-Length-framed notification through the transport and + // verify that a real Client wired with OnGitHubTelemetry routes it to the + // callback through the client's own client-global handler registration + // (setupNotificationHandler), rather than registering the adapter by hand. + clientConn, serverConn := net.Pipe() + defer clientConn.Close() + defer serverConn.Close() + + rpcClient := jsonrpc2.NewClient(clientConn, clientConn) + rpcClient.Start() + defer rpcClient.Stop() + + // Drain the client->server direction so net.Pipe writes never block. + go func() { + buf := make([]byte, 4096) + for { + if _, err := serverConn.Read(buf); err != nil { + return + } + } + }() + + received := make(chan *rpc.GitHubTelemetryNotification, 1) + client := &Client{ + client: rpcClient, + RPC: rpc.NewServerRPC(rpcClient), + sessions: make(map[string]*Session), + options: ClientOptions{ + OnGitHubTelemetry: func(n *rpc.GitHubTelemetryNotification) { received <- n }, + }, + } + // setupNotificationHandler is what registers the gitHubTelemetryAdapter when + // OnGitHubTelemetry is set; exercising it here covers the real client wiring. + client.setupNotificationHandler() + + notification := map[string]any{ + "jsonrpc": "2.0", + "method": "gitHubTelemetry.event", + "params": map[string]any{ + "sessionId": "sess-telemetry", + "restricted": true, + "event": map[string]any{ + "kind": "tool_call_executed", + "metrics": map[string]any{"duration_ms": 12.5}, + "properties": map[string]any{"tool": "shell"}, + }, + }, + } + data, err := json.Marshal(notification) + if err != nil { + t.Fatalf("marshal notification: %v", err) + } + go func() { + _, _ = fmt.Fprintf(serverConn, "Content-Length: %d\r\n\r\n%s", len(data), data) + }() + + select { + case n := <-received: + sessionID := "" + if n.SessionID != nil { + sessionID = *n.SessionID + } + if sessionID != "sess-telemetry" { + t.Errorf("session id = %q, want sess-telemetry", sessionID) + } + if !n.Restricted { + t.Error("expected restricted to be true") + } + if n.Event.Kind != "tool_call_executed" { + t.Errorf("kind = %q, want tool_call_executed", n.Event.Kind) + } + if n.Event.Metrics["duration_ms"] != 12.5 { + t.Errorf("metrics[duration_ms] = %v, want 12.5", n.Event.Metrics["duration_ms"]) + } + if n.Event.Properties["tool"] != "shell" { + t.Errorf("properties[tool] = %q, want shell", n.Event.Properties["tool"]) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for telemetry notification") + } +} + func TestCreateSessionRequest_EnableOnDemandInstructionDiscovery(t *testing.T) { t.Run("forwards explicit true", func(t *testing.T) { req := createSessionRequest{ diff --git a/go/cmd/bundler/main.go b/go/cmd/bundler/main.go index 1e5f5ecd8b..e63d1fde66 100644 --- a/go/cmd/bundler/main.go +++ b/go/cmd/bundler/main.go @@ -91,14 +91,47 @@ func main() { fmt.Printf("Building bundle for %s (CLI version %s)\n", *platform, version) - binaryPath, sha256Hash, err := buildBundle(info, version, outputPath) + binaryPath, sha256Hash, runtimeArtifactPath, runtimeHash, err := buildBundle(info, version, outputPath, goos) if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } + var muslBinaryPath, muslRuntimeArtifactPath string + var muslBinaryHash, muslRuntimeHash []byte + if goos == "linux" { + muslInfo := platformInfo{ + npmPlatform: strings.Replace(info.npmPlatform, "linux-", "linuxmusl-", 1), + binaryName: info.binaryName, + } + muslOutputPath := filepath.Join(*output, defaultOutputFileName(version, "linuxmusl", goarch, info.binaryName)) + muslBinaryPath, muslBinaryHash, muslRuntimeArtifactPath, muslRuntimeHash, err = buildBundle( + muslInfo, + version, + muslOutputPath, + goos, + ) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } + } + // Generate the Go file with embed directive - if err := generateGoFile(goos, goarch, binaryPath, version, sha256Hash, "main"); err != nil { + if err := generateGoFile( + goos, + goarch, + binaryPath, + version, + sha256Hash, + runtimeArtifactPath, + runtimeHash, + muslBinaryPath, + muslBinaryHash, + muslRuntimeArtifactPath, + muslRuntimeHash, + "main", + ); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } @@ -253,12 +286,16 @@ func isHex(s string) bool { return true } -// buildBundle downloads the CLI binary and writes it to outputPath. -func buildBundle(info platformInfo, cliVersion, outputPath string) (string, []byte, error) { +// buildBundle downloads the CLI binary (and, when the CLI package ships it, the +// native in-process runtime library) and writes them to outputPath's directory. +// It returns the CLI bundle path and hash, plus the runtime-library artifact path +// and hash (both empty when the package does not ship the runtime library). +func buildBundle(info platformInfo, cliVersion, outputPath, goos string) (string, []byte, string, []byte, error) { outputDir := filepath.Dir(outputPath) if outputDir == "" { outputDir = "." } + runtimeArtifactPath := filepath.Join(outputDir, runtimeLibArtifactName(cliVersion, info.npmPlatform, goos)) // Check if output already exists if _, err := os.Stat(outputPath); err == nil { @@ -266,68 +303,254 @@ func buildBundle(info platformInfo, cliVersion, outputPath string) (string, []by fmt.Printf("Output %s already exists, skipping download\n", outputPath) sha256Hash, err := sha256FileFromCompressed(outputPath) if err != nil { - return "", nil, fmt.Errorf("failed to hash existing output: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to hash existing output: %w", err) } if err := downloadCLILicense(cliVersion, outputPath); err != nil { - return "", nil, fmt.Errorf("failed to download CLI license: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to download CLI license: %w", err) + } + // Reuse an existing runtime-library artifact if present. + if _, err := os.Stat(runtimeArtifactPath); err == nil { + runtimeHash, err := sha256FileFromCompressed(runtimeArtifactPath) + if err != nil { + return "", nil, "", nil, fmt.Errorf("failed to hash existing runtime library: %w", err) + } + return outputPath, sha256Hash, runtimeArtifactPath, runtimeHash, nil } - return outputPath, sha256Hash, nil + return outputPath, sha256Hash, "", nil, nil } // Create temp directory for download tempDir, err := os.MkdirTemp("", "copilot-bundler-*") if err != nil { - return "", nil, fmt.Errorf("failed to create temp dir: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to create temp dir: %w", err) } defer os.RemoveAll(tempDir) // Download the binary - binaryPath, err := downloadCLIBinary(info.npmPlatform, info.binaryName, cliVersion, tempDir) + binaryPath, tarballPath, err := downloadCLIBinary(info.npmPlatform, info.binaryName, cliVersion, tempDir) if err != nil { - return "", nil, fmt.Errorf("failed to download CLI binary: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to download CLI binary: %w", err) } // Create output directory if needed if outputDir != "." { if err := os.MkdirAll(outputDir, 0755); err != nil { - return "", nil, fmt.Errorf("failed to create output directory: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to create output directory: %w", err) } } sha256Hash, err := sha256File(binaryPath) if err != nil { - return "", nil, fmt.Errorf("failed to hash output binary: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to hash output binary: %w", err) } if err := compressZstdFile(binaryPath, outputPath); err != nil { - return "", nil, fmt.Errorf("failed to write output binary: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to write output binary: %w", err) } if err := downloadCLILicense(cliVersion, outputPath); err != nil { - return "", nil, fmt.Errorf("failed to download CLI license: %w", err) + return "", nil, "", nil, fmt.Errorf("failed to download CLI license: %w", err) } + + // Extract the native in-process runtime library from the same tarball, if the + // package ships it (older CLI versions do not). Missing is not an error — the + // generated file simply omits the runtime embed for that platform. + rawLibPath := filepath.Join(tempDir, "runtime.node") + found, err := extractOptionalFileFromTarball(tarballPath, tempDir, + "package/prebuilds/"+info.npmPlatform+"/runtime.node", "runtime.node") + if err != nil { + return "", nil, "", nil, fmt.Errorf("failed to extract runtime library: %w", err) + } + var runtimeHash []byte + returnedRuntimeArtifact := "" + if found { + runtimeHash, err = sha256File(rawLibPath) + if err != nil { + return "", nil, "", nil, fmt.Errorf("failed to hash runtime library: %w", err) + } + if err := compressZstdFile(rawLibPath, runtimeArtifactPath); err != nil { + return "", nil, "", nil, fmt.Errorf("failed to write runtime library: %w", err) + } + returnedRuntimeArtifact = runtimeArtifactPath + fmt.Printf("Successfully created %s\n", runtimeArtifactPath) + } else { + fmt.Printf("Package %s does not ship a runtime library; in-process transport unavailable for this platform bundle\n", info.npmPlatform) + } + fmt.Printf("Successfully created %s\n", outputPath) - return outputPath, sha256Hash, nil + return outputPath, sha256Hash, returnedRuntimeArtifact, runtimeHash, nil } -// generateGoFile creates a Go source file that embeds the binary and metadata. -func generateGoFile(goos, goarch, binaryPath, cliVersion string, sha256Hash []byte, pkgName string) error { - // Generate Go file path: zcopilot_linux_amd64.go (without version) +// runtimeLibArtifactName builds the compressed runtime-library artifact filename. +func runtimeLibArtifactName(version, npmPlatform, goos string) string { + return fmt.Sprintf("zcopilotruntime_%s_%s.%s.zst", version, npmPlatform, runtimeLibExt(goos)) +} + +// runtimeLibExt returns the shared-library extension for the target OS. +func runtimeLibExt(goos string) string { + switch goos { + case "windows": + return "dll" + case "darwin": + return "dylib" + default: + return "so" + } +} + +// generateGoFile creates separate source files for normal and in-process builds. +// Both embed the CLI, while only the copilot_inprocess-tagged file embeds the +// native runtime library. +func generateGoFile( + goos, + goarch, + binaryPath, + cliVersion string, + sha256Hash []byte, + runtimeArtifactPath string, + runtimeHash []byte, + muslBinaryPath string, + muslBinaryHash []byte, + muslRuntimeArtifactPath string, + muslRuntimeHash []byte, + pkgName string, +) error { binaryName := filepath.Base(binaryPath) licenseName := licenseFileName(binaryName) - goFileName := fmt.Sprintf("zcopilot_%s_%s.go", goos, goarch) - goFilePath := filepath.Join(filepath.Dir(binaryPath), goFileName) hashBase64 := "" if len(sha256Hash) > 0 { hashBase64 = base64.StdEncoding.EncodeToString(sha256Hash) } - content := fmt.Sprintf(`// Code generated by copilot-sdk bundler; DO NOT EDIT. + outputDir := filepath.Dir(binaryPath) + defaultPath := filepath.Join(outputDir, fmt.Sprintf("zcopilot_%s_%s.go", goos, goarch)) + defaultContent := generatedGoFileContent( + "!copilot_inprocess", + pkgName, + binaryName, + licenseName, + cliVersion, + hashBase64, + "", + nil, + "", + nil, + "", + nil, + ) + if err := os.WriteFile(defaultPath, []byte(defaultContent), 0644); err != nil { + return err + } + + inProcessPath := filepath.Join(outputDir, fmt.Sprintf("zcopilot_inprocess_%s_%s.go", goos, goarch)) + inProcessContent := generatedGoFileContent( + "copilot_inprocess", + pkgName, + binaryName, + licenseName, + cliVersion, + hashBase64, + runtimeArtifactPath, + runtimeHash, + muslBinaryPath, + muslBinaryHash, + muslRuntimeArtifactPath, + muslRuntimeHash, + ) + if err := os.WriteFile(inProcessPath, []byte(inProcessContent), 0644); err != nil { + return err + } + + fmt.Printf("Generated %s\n", defaultPath) + fmt.Printf("Generated %s\n", inProcessPath) + return nil +} + +func generatedGoFileContent( + buildConstraint, + pkgName, + binaryName, + licenseName, + cliVersion, + hashBase64, + runtimeArtifactPath string, + runtimeHash []byte, + muslBinaryPath string, + muslBinaryHash []byte, + muslRuntimeArtifactPath string, + muslRuntimeHash []byte, +) string { + runtimeEmbed := "" + runtimeConfig := "" + runtimeReader := "" + if runtimeArtifactPath != "" { + runtimeArtifactName := filepath.Base(runtimeArtifactPath) + runtimeHashBase64 := base64.StdEncoding.EncodeToString(runtimeHash) + runtimeEmbed = fmt.Sprintf(` +//go:embed %s +var localEmbeddedCopilotRuntimeLib []byte +`, runtimeArtifactName) + runtimeConfig = fmt.Sprintf(` + RuntimeLib: runtimeLibReader(), + RuntimeLibHash: mustDecodeBase64(%q),`, runtimeHashBase64) + runtimeReader = ` +func runtimeLibReader() io.Reader { + r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotRuntimeLib)) + if err != nil { + panic("failed to create zstd reader: " + err.Error()) + } + return r +} +` + } + + muslEmbed := "" + muslConfig := "" + muslReaders := "" + if muslBinaryPath != "" && muslRuntimeArtifactPath != "" { + muslBinaryName := filepath.Base(muslBinaryPath) + muslBinaryHashBase64 := base64.StdEncoding.EncodeToString(muslBinaryHash) + muslRuntimeName := filepath.Base(muslRuntimeArtifactPath) + muslRuntimeHashBase64 := base64.StdEncoding.EncodeToString(muslRuntimeHash) + muslEmbed = fmt.Sprintf(` +//go:embed %s +var localEmbeddedCopilotCLILinuxMusl []byte + +//go:embed %s +var localEmbeddedCopilotRuntimeLibLinuxMusl []byte +`, muslBinaryName, muslRuntimeName) + muslConfig = fmt.Sprintf(` + LinuxMuslCli: linuxMuslCLIReader(), + LinuxMuslCliHash: mustDecodeBase64(%q), + LinuxMuslRuntimeLib: linuxMuslRuntimeLibReader(), + LinuxMuslRuntimeLibHash: mustDecodeBase64(%q),`, muslBinaryHashBase64, muslRuntimeHashBase64) + muslReaders = ` +func linuxMuslCLIReader() io.Reader { + r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotCLILinuxMusl)) + if err != nil { + panic("failed to create zstd reader: " + err.Error()) + } + return r +} + +func linuxMuslRuntimeLibReader() io.Reader { + r, err := zstd.NewReader(bytes.NewReader(localEmbeddedCopilotRuntimeLibLinuxMusl)) + if err != nil { + panic("failed to create zstd reader: " + err.Error()) + } + return r +} +` + } + + return fmt.Sprintf(`//go:build %s + +// Code generated by copilot-sdk bundler; DO NOT EDIT. package %s import ( "bytes" - "io" "encoding/base64" _ "embed" + "io" "github.com/github/copilot-sdk/go/embeddedcli" "github.com/klauspost/compress/zstd" @@ -338,14 +561,15 @@ var localEmbeddedCopilotCLI []byte //go:embed %s var localEmbeddedCopilotCLILicense []byte - +%s +%s func init() { embeddedcli.Setup(embeddedcli.Config{ Cli: cliReader(), License: localEmbeddedCopilotCLILicense, Version: %q, - CliHash: mustDecodeBase64(%q), + CliHash: mustDecodeBase64(%q),%s%s }) } @@ -356,7 +580,8 @@ func cliReader() io.Reader { } return r } - +%s +%s func mustDecodeBase64(s string) []byte { b, err := base64.StdEncoding.DecodeString(s) if err != nil { @@ -364,73 +589,68 @@ func mustDecodeBase64(s string) []byte { } return b } -`, pkgName, binaryName, licenseName, cliVersion, hashBase64) - - if err := os.WriteFile(goFilePath, []byte(content), 0644); err != nil { - return err - } - - fmt.Printf("Generated %s\n", goFilePath) - return nil +`, buildConstraint, pkgName, binaryName, licenseName, runtimeEmbed, muslEmbed, cliVersion, hashBase64, runtimeConfig, muslConfig, runtimeReader, muslReaders) } -// downloadCLIBinary downloads the npm tarball and extracts the CLI binary. -func downloadCLIBinary(npmPlatform, binaryName, cliVersion, destDir string) (string, error) { +// downloadCLIBinary downloads the npm tarball and extracts the CLI binary. It +// returns the extracted binary path and the downloaded tarball path (retained so +// callers can extract additional files, such as the runtime library). +func downloadCLIBinary(npmPlatform, binaryName, cliVersion, destDir string) (string, string, error) { tarballURL := fmt.Sprintf(tarballURLFmt, npmPlatform, npmPlatform, cliVersion) fmt.Printf("Downloading from %s...\n", tarballURL) resp, err := http.Get(tarballURL) if err != nil { - return "", fmt.Errorf("failed to download: %w", err) + return "", "", fmt.Errorf("failed to download: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("failed to download: %s", resp.Status) + return "", "", fmt.Errorf("failed to download: %s", resp.Status) } // Save tarball to temp file tarballPath := filepath.Join(destDir, fmt.Sprintf("copilot-%s-%s.tgz", npmPlatform, cliVersion)) tarballFile, err := os.Create(tarballPath) if err != nil { - return "", fmt.Errorf("failed to create tarball file: %w", err) + return "", "", fmt.Errorf("failed to create tarball file: %w", err) } if _, err := io.Copy(tarballFile, resp.Body); err != nil { tarballFile.Close() - return "", fmt.Errorf("failed to save tarball: %w", err) + return "", "", fmt.Errorf("failed to save tarball: %w", err) } if err := tarballFile.Close(); err != nil { - return "", fmt.Errorf("failed to close tarball file: %w", err) + return "", "", fmt.Errorf("failed to close tarball file: %w", err) } // Extract only the CLI binary to avoid unpacking the full package tree. binaryPath := filepath.Join(destDir, binaryName) if err := extractFileFromTarball(tarballPath, destDir, "package/"+binaryName, binaryName); err != nil { - return "", fmt.Errorf("failed to extract binary: %w", err) + return "", "", fmt.Errorf("failed to extract binary: %w", err) } // Verify binary exists if _, err := os.Stat(binaryPath); err != nil { - return "", fmt.Errorf("binary not found after extraction: %w", err) + return "", "", fmt.Errorf("binary not found after extraction: %w", err) } // Make executable on Unix if !strings.HasSuffix(binaryName, ".exe") { if err := os.Chmod(binaryPath, 0755); err != nil { - return "", fmt.Errorf("failed to chmod binary: %w", err) + return "", "", fmt.Errorf("failed to chmod binary: %w", err) } } stat, err := os.Stat(binaryPath) if err != nil { - return "", fmt.Errorf("failed to stat binary: %w", err) + return "", "", fmt.Errorf("failed to stat binary: %w", err) } sizeMB := float64(stat.Size()) / 1024 / 1024 fmt.Printf("Downloaded %s (%.1f MB)\n", binaryName, sizeMB) - return binaryPath, nil + return binaryPath, tarballPath, nil } // downloadCLILicense downloads the @github/copilot package and writes its license next to outputPath. @@ -561,6 +781,21 @@ func extractFileFromTarball(tarballPath, destDir, targetPath, outputName string) return fmt.Errorf("file %q not found in tarball", targetPath) } +// extractOptionalFileFromTarball extracts a single file from a .tgz into destDir +// like extractFileFromTarball, but returns (false, nil) instead of an error when +// the file is absent. Used for the runtime library, which older CLI packages do +// not ship. +func extractOptionalFileFromTarball(tarballPath, destDir, targetPath, outputName string) (bool, error) { + err := extractFileFromTarball(tarballPath, destDir, targetPath, outputName) + if err == nil { + return true, nil + } + if strings.Contains(err.Error(), "not found in tarball") { + return false, nil + } + return false, err +} + // compressZstdFile compresses src into dst using zstd. func compressZstdFile(src, dst string) error { srcFile, err := os.Open(src) diff --git a/go/cmd/bundler/main_test.go b/go/cmd/bundler/main_test.go new file mode 100644 index 0000000000..badc791359 --- /dev/null +++ b/go/cmd/bundler/main_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestGenerateGoFileGatesRuntimeEmbed(t *testing.T) { + dir := t.TempDir() + binaryPath := filepath.Join(dir, "copilot.zst") + runtimePath := filepath.Join(dir, "runtime.node.zst") + muslBinaryPath := filepath.Join(dir, "copilot-musl.zst") + muslRuntimePath := filepath.Join(dir, "runtime-musl.node.zst") + for _, path := range []string{ + binaryPath, + licensePathForOutput(binaryPath), + runtimePath, + muslBinaryPath, + muslRuntimePath, + } { + if err := os.WriteFile(path, []byte("test"), 0644); err != nil { + t.Fatal(err) + } + } + + hash := make([]byte, 32) + if err := generateGoFile( + "linux", + "amd64", + binaryPath, + "1.2.3", + hash, + runtimePath, + hash, + muslBinaryPath, + hash, + muslRuntimePath, + hash, + "main", + ); err != nil { + t.Fatal(err) + } + + defaultSource, err := os.ReadFile(filepath.Join(dir, "zcopilot_linux_amd64.go")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(defaultSource), "//go:build !copilot_inprocess") { + t.Fatal("default embed file does not exclude copilot_inprocess builds") + } + if strings.Contains(string(defaultSource), "localEmbeddedCopilotRuntimeLib") { + t.Fatal("default embed file includes the native runtime") + } + if _, err := parser.ParseFile(token.NewFileSet(), "zcopilot_linux_amd64.go", defaultSource, parser.AllErrors); err != nil { + t.Fatalf("default generated source is invalid: %v", err) + } + + inProcessSource, err := os.ReadFile(filepath.Join(dir, "zcopilot_inprocess_linux_amd64.go")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(inProcessSource), "//go:build copilot_inprocess") { + t.Fatal("in-process embed file does not require the copilot_inprocess tag") + } + if !strings.Contains(string(inProcessSource), "localEmbeddedCopilotRuntimeLib") { + t.Fatal("in-process embed file does not include the native runtime") + } + if !strings.Contains(string(inProcessSource), "localEmbeddedCopilotCLILinuxMusl") { + t.Fatal("in-process embed file does not include the Linux musl CLI") + } + if !strings.Contains(string(inProcessSource), "localEmbeddedCopilotRuntimeLibLinuxMusl") { + t.Fatal("in-process embed file does not include the Linux musl runtime") + } + if _, err := parser.ParseFile(token.NewFileSet(), "zcopilot_inprocess_linux_amd64.go", inProcessSource, parser.AllErrors); err != nil { + t.Fatalf("in-process generated source is invalid: %v", err) + } +} diff --git a/go/copilot_request_handler.go b/go/copilot_request_handler.go index c1ac52bc2e..ba8bb9b919 100644 --- a/go/copilot_request_handler.go +++ b/go/copilot_request_handler.go @@ -50,8 +50,11 @@ var sharedHTTPTransport = func() http.RoundTripper { // CopilotRequestContext is the per-request context handed to every // [CopilotRequestHandler] seam. type CopilotRequestContext struct { - RequestID string - SessionID string + RequestID string + SessionID string + AgentID string + ParentAgentID string + InteractionType string // Transport is "http" (covering plain HTTP and SSE) or "websocket". Transport string Method string @@ -144,12 +147,12 @@ type CopilotWebSocketHandler interface { // copilotContextKey is used to attach [CopilotRequestContext] to an // [http.Request] so custom [http.RoundTripper] implementations can access -// metadata (e.g. SessionID) without additional parameters. +// metadata (e.g. SessionID and AgentID) without additional parameters. type copilotContextKey struct{} // RequestContextFrom returns the [CopilotRequestContext] attached to an // http.Request by the adapter, or nil if not present. Call this from a custom -// [http.RoundTripper] to access metadata such as SessionID. +// [http.RoundTripper] to access metadata such as SessionID and AgentID. func RequestContextFrom(r *http.Request) *CopilotRequestContext { v, _ := r.Context().Value(copilotContextKey{}).(*CopilotRequestContext) return v @@ -194,7 +197,7 @@ func buildHTTPRequest(rctx *CopilotRequestContext) (*http.Request, error) { return nil, err } // Attach rctx so custom RoundTripper implementations can read metadata - // (e.g. SessionID) via [RequestContextFrom]. + // (e.g. SessionID and AgentID) via [RequestContextFrom]. httpReq = httpReq.WithContext(context.WithValue(httpReq.Context(), copilotContextKey{}, rctx)) for name, values := range rctx.Headers { if isForbiddenRequestHeader(name) { @@ -615,14 +618,17 @@ func (a *copilotRequestAdapter) HttpRequestStart(params *rpc.LlmInferenceHTTPReq } rctx := &CopilotRequestContext{ - RequestID: params.RequestID, - SessionID: sessionID, - Method: params.Method, - URL: params.URL, - Headers: headers, - Transport: transport, - body: bodyCh, - Context: ctx, + RequestID: params.RequestID, + SessionID: sessionID, + AgentID: stringOrEmpty(params.AgentID), + ParentAgentID: stringOrEmpty(params.ParentAgentID), + InteractionType: stringOrEmpty(params.InteractionType), + Method: params.Method, + URL: params.URL, + Headers: headers, + Transport: transport, + body: bodyCh, + Context: ctx, } sink := &responseSink{requestID: params.RequestID, adapter: a, exchange: exchange} go a.runHandler(rctx, sink, exchange) @@ -706,6 +712,13 @@ func (a *copilotRequestAdapter) removePending(requestID string) { a.mu.Unlock() } +func stringOrEmpty(value *string) string { + if value == nil { + return "" + } + return *value +} + func decodeChunkData(data string, binary bool) ([]byte, error) { if binary { return base64.StdEncoding.DecodeString(data) diff --git a/go/definetool.go b/go/definetool.go index bc223dc10d..a63aeab9f8 100644 --- a/go/definetool.go +++ b/go/definetool.go @@ -207,7 +207,7 @@ func generateSchemaForType(t reflect.Type) map[string]any { } // Handle pointer types - if t.Kind() == reflect.Ptr { + if t.Kind() == reflect.Pointer { t = t.Elem() } diff --git a/go/embeddedcli/installer.go b/go/embeddedcli/installer.go index 6edddf281a..9702b3aec6 100644 --- a/go/embeddedcli/installer.go +++ b/go/embeddedcli/installer.go @@ -5,9 +5,10 @@ import "github.com/github/copilot-sdk/go/internal/embeddedcli" // Config defines the inputs used to install and locate the embedded Copilot CLI. // // Cli and CliHash are required. If Dir is empty, the CLI is installed into the -// system cache directory. Version is used to suffix the installed binary name to -// allow multiple versions to coexist. License, when provided, is written next -// to the installed binary. +// system cache directory. When Version is set, the CLI and runtime library are +// installed into a version-specific child directory so multiple versions can +// coexist. Linux musl alternatives, when provided, are selected automatically. +// License, when provided, is written next to the installed binary. type Config = embeddedcli.Config // Setup sets the embedded GitHub Copilot CLI install configuration. diff --git a/go/go.mod b/go/go.mod index 586a5d3360..ba0f4feb73 100644 --- a/go/go.mod +++ b/go/go.mod @@ -9,6 +9,7 @@ require ( require ( github.com/coder/websocket v1.8.15 + github.com/ebitengine/purego v0.10.1 github.com/google/uuid v1.6.0 go.opentelemetry.io/otel v1.35.0 go.opentelemetry.io/otel/trace v1.35.0 diff --git a/go/go.sum b/go/go.sum index e7ac53d5a4..cab5b6aabe 100644 --- a/go/go.sum +++ b/go/go.sum @@ -2,6 +2,8 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= +github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= diff --git a/go/inprocess.go b/go/inprocess.go new file mode 100644 index 0000000000..c74410e42b --- /dev/null +++ b/go/inprocess.go @@ -0,0 +1,15 @@ +package copilot + +import "io" + +type inProcessHost interface { + Start() error + Writer() io.WriteCloser + Reader() io.ReadCloser + Dispose() +} + +type inProcessHostConfig struct { + Environment map[string]string + Args []string +} diff --git a/go/inprocess_disabled.go b/go/inprocess_disabled.go new file mode 100644 index 0000000000..b86ed5ca36 --- /dev/null +++ b/go/inprocess_disabled.go @@ -0,0 +1,11 @@ +//go:build !copilot_inprocess || (!darwin && !linux && !windows) + +package copilot + +import "errors" + +const inProcessAvailable = false + +func createInProcessHost(string, inProcessHostConfig) (inProcessHost, error) { + return nil, errors.New("in-process transport unavailable") +} diff --git a/go/inprocess_enabled.go b/go/inprocess_enabled.go new file mode 100644 index 0000000000..c20013d8ab --- /dev/null +++ b/go/inprocess_enabled.go @@ -0,0 +1,11 @@ +//go:build copilot_inprocess && (darwin || linux || windows) + +package copilot + +import "github.com/github/copilot-sdk/go/internal/ffihost" + +const inProcessAvailable = true + +func createInProcessHost(runtimePath string, config inProcessHostConfig) (inProcessHost, error) { + return ffihost.Create(runtimePath, config.Environment, config.Args) +} diff --git a/go/internal/e2e/byok_bearer_token_provider_e2e_test.go b/go/internal/e2e/byok_bearer_token_provider_e2e_test.go index 2f298596d1..33e32b1322 100644 --- a/go/internal/e2e/byok_bearer_token_provider_e2e_test.go +++ b/go/internal/e2e/byok_bearer_token_provider_e2e_test.go @@ -111,6 +111,7 @@ func (rt *byokCapturingRoundTripper) reset() { // 3. per-provider dispatch routes each provider's turn to its own callback, and // the resulting token reaches that provider's endpoint. func TestBYOKBearerTokenProvider(t *testing.T) { + testharness.SkipIfInProcess(t, "an LLM inference provider is process-global in-process") ctx := testharness.NewTestContext(t) rt := &byokCapturingRoundTripper{} handler := &copilot.CopilotRequestHandler{Transport: rt} diff --git a/go/internal/e2e/client_options_e2e_test.go b/go/internal/e2e/client_options_e2e_test.go index aa42be1f3a..0d3c802b06 100644 --- a/go/internal/e2e/client_options_e2e_test.go +++ b/go/internal/e2e/client_options_e2e_test.go @@ -10,6 +10,7 @@ import ( copilot "github.com/github/copilot-sdk/go" "github.com/github/copilot-sdk/go/internal/e2e/testharness" + "github.com/github/copilot-sdk/go/rpc" ) // Mirrors the E2E portions of dotnet/test/ClientOptionsTests.cs (snapshot category "client_options"). @@ -198,6 +199,315 @@ func TestClientOptionsE2E(t *testing.T) { } }) + t.Run("should forward advanced session creation options to the CLI", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + cliPath := filepath.Join(ctx.WorkDir, "fake-cli-"+randomHex(t)+".js") + capturePath := filepath.Join(ctx.WorkDir, "fake-cli-capture-"+randomHex(t)+".json") + if err := os.WriteFile(cliPath, []byte(fakeStdioCliScript), 0644); err != nil { + t.Fatalf("Failed to write fake CLI script: %v", err) + } + + client := ctx.NewClient(func(opts *copilot.ClientOptions) { + opts.Connection = copilot.StdioConnection{Path: cliPath, Args: []string{"--capture-file", capturePath}} + opts.GitHubToken = "advanced-create-client-token" + opts.UseLoggedInUser = copilot.Bool(false) + }) + t.Cleanup(func() { client.ForceStop() }) + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Start failed: %v", err) + } + + sessionID := "advanced-session-id" + workingDirectory := t.TempDir() + configDirectory := t.TempDir() + embeddingCacheStorage := "in-memory" + organizationCustomInstructions := "organization guidance" + maxAiCredits := float64(42) + extensionSDKPath := filepath.Join(ctx.WorkDir, "extension-sdk") + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + SessionID: sessionID, + ClientName: "go-sdk-e2e-client", + Model: "claude-sonnet-4.5", + ReasoningEffort: "low", + ReasoningSummary: copilot.ReasoningSummaryNone, + ContextTier: copilot.ContextTierLongContext, + ConfigDirectory: configDirectory, + EnableConfigDiscovery: copilot.Bool(true), + SkipEmbeddingRetrieval: copilot.Bool(true), + EmbeddingCacheStorage: &embeddingCacheStorage, + OrganizationCustomInstructions: &organizationCustomInstructions, + EnableOnDemandInstructionDiscovery: copilot.Bool(true), + EnableFileHooks: copilot.Bool(false), + EnableHostGitOperations: copilot.Bool(false), + EnableSessionStore: copilot.Bool(false), + EnableSkills: copilot.Bool(false), + WorkingDirectory: workingDirectory, + Streaming: copilot.Bool(true), + IncludeSubAgentStreamingEvents: copilot.Bool(false), + AvailableTools: []string{"read_file"}, + ExcludedTools: []string{"bash"}, + ExcludedBuiltInAgents: []string{"legacy-agent"}, + EnableSessionTelemetry: copilot.Bool(false), + EnableCitations: copilot.Bool(true), + SessionLimits: &rpc.SessionLimitsConfig{MaxAiCredits: &maxAiCredits}, + SkipCustomInstructions: copilot.Bool(true), + CustomAgentsLocalOnly: copilot.Bool(true), + CoauthorEnabled: copilot.Bool(false), + ManageScheduleEnabled: copilot.Bool(false), + GitHubToken: "advanced-create-session-token", + RemoteSession: rpc.RemoteSessionModeExport, + SkillDirectories: []string{"skills"}, + PluginDirectories: []string{"plugins"}, + InstructionDirectories: []string{"instructions"}, + DisabledSkills: []string{"disabled-skill"}, + EnableMCPApps: true, + Canvases: []copilot.CanvasDeclaration{{ + ID: "canvas", + DisplayName: "Canvas", + Description: "Canvas description", + InputSchema: map[string]any{"type": "object"}, + }}, + RequestCanvasRenderer: copilot.Bool(true), + RequestExtensions: copilot.Bool(true), + ExtensionSDKPath: &extensionSDKPath, + ExtensionInfo: &copilot.ExtensionInfo{Source: "github-app", Name: "go-e2e-extension"}, + ExpAssignments: map[string]any{"feature": "enabled"}, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + session.Disconnect() + + createReq := getCapturedRequest(t, capturePath, "session.create") + params, ok := createReq.Params.(map[string]any) + if !ok { + t.Fatalf("Expected session.create params object, got %T", createReq.Params) + } + expectedValues := map[string]any{ + "sessionId": sessionID, + "clientName": "go-sdk-e2e-client", + "model": "claude-sonnet-4.5", + "reasoningEffort": "low", + "reasoningSummary": "none", + "contextTier": "long_context", + "configDir": configDirectory, + "enableConfigDiscovery": true, + "skipEmbeddingRetrieval": true, + "embeddingCacheStorage": embeddingCacheStorage, + "organizationCustomInstructions": organizationCustomInstructions, + "enableOnDemandInstructionDiscovery": true, + "enableFileHooks": false, + "enableHostGitOperations": false, + "enableSessionStore": false, + "enableSkills": false, + "workingDirectory": workingDirectory, + "streaming": true, + "includeSubAgentStreamingEvents": false, + "enableSessionTelemetry": false, + "enableCitations": true, + "skipCustomInstructions": true, + "customAgentsLocalOnly": true, + "coauthorEnabled": false, + "manageScheduleEnabled": false, + "gitHubToken": "advanced-create-session-token", + "remoteSession": "export", + "requestMcpApps": true, + "requestCanvasRenderer": true, + "requestExtensions": true, + "extensionSdkPath": extensionSDKPath, + "envValueMode": "direct", + } + for key, expected := range expectedValues { + if params[key] != expected { + t.Fatalf("Expected %s=%#v, got %#v in %#v", key, expected, params[key], params) + } + } + assertStringArray(t, params["availableTools"], []string{"read_file"}) + assertStringArray(t, params["excludedTools"], []string{"bash"}) + assertStringArray(t, params["excludedBuiltinAgents"], []string{"legacy-agent"}) + assertStringArray(t, params["skillDirectories"], []string{"skills"}) + assertStringArray(t, params["pluginDirectories"], []string{"plugins"}) + assertStringArray(t, params["instructionDirectories"], []string{"instructions"}) + assertStringArray(t, params["disabledSkills"], []string{"disabled-skill"}) + if params["sessionLimits"].(map[string]any)["maxAiCredits"] != maxAiCredits { + t.Fatalf("Expected sessionLimits to be forwarded, got %#v", params["sessionLimits"]) + } + extensionInfo := params["extensionInfo"].(map[string]any) + if extensionInfo["source"] != "github-app" || extensionInfo["name"] != "go-e2e-extension" { + t.Fatalf("Expected extensionInfo to be forwarded, got %#v", extensionInfo) + } + canvases := params["canvases"].([]any) + canvas := canvases[0].(map[string]any) + if canvas["id"] != "canvas" || canvas["displayName"] != "Canvas" || canvas["description"] != "Canvas description" { + t.Fatalf("Expected canvas declaration to be forwarded, got %#v", canvas) + } + if params["expAssignments"].(map[string]any)["feature"] != "enabled" { + t.Fatalf("Expected expAssignments to be forwarded, got %#v", params["expAssignments"]) + } + }) + + t.Run("should forward singular provider configuration on session creation", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + cliPath := filepath.Join(ctx.WorkDir, "fake-cli-"+randomHex(t)+".js") + capturePath := filepath.Join(ctx.WorkDir, "fake-cli-capture-"+randomHex(t)+".json") + if err := os.WriteFile(cliPath, []byte(fakeStdioCliScript), 0644); err != nil { + t.Fatalf("Failed to write fake CLI script: %v", err) + } + + client := ctx.NewClient(func(opts *copilot.ClientOptions) { + opts.Connection = copilot.StdioConnection{Path: cliPath, Args: []string{"--capture-file", capturePath}} + opts.GitHubToken = "provider-client-token" + opts.UseLoggedInUser = copilot.Bool(false) + }) + t.Cleanup(func() { client.ForceStop() }) + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Start failed: %v", err) + } + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + Provider: &copilot.ProviderConfig{ + Type: "openai", + WireAPI: "responses", + Transport: "websockets", + BaseURL: "https://models.example.test/v1", + APIKey: "provider-key", + ModelID: "base-model", + WireModel: "wire-model", + MaxPromptTokens: 1000, + MaxOutputTokens: 2000, + Headers: map[string]string{"x-provider": "go"}, + }, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + session.Disconnect() + + createReq := getCapturedRequest(t, capturePath, "session.create") + params := createReq.Params.(map[string]any) + provider := params["provider"].(map[string]any) + for key, expected := range map[string]any{ + "type": "openai", + "wireApi": "responses", + "transport": "websockets", + "baseUrl": "https://models.example.test/v1", + "apiKey": "provider-key", + "modelId": "base-model", + "wireModel": "wire-model", + "maxPromptTokens": float64(1000), + "maxOutputTokens": float64(2000), + } { + if provider[key] != expected { + t.Fatalf("Expected provider.%s=%#v, got %#v in %#v", key, expected, provider[key], provider) + } + } + if provider["headers"].(map[string]any)["x-provider"] != "go" { + t.Fatalf("Expected provider headers to be forwarded, got %#v", provider["headers"]) + } + }) + + t.Run("should forward advanced session resume options to the CLI", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + cliPath := filepath.Join(ctx.WorkDir, "fake-cli-"+randomHex(t)+".js") + capturePath := filepath.Join(ctx.WorkDir, "fake-cli-capture-"+randomHex(t)+".json") + if err := os.WriteFile(cliPath, []byte(fakeStdioCliScript), 0644); err != nil { + t.Fatalf("Failed to write fake CLI script: %v", err) + } + + client := ctx.NewClient(func(opts *copilot.ClientOptions) { + opts.Connection = copilot.StdioConnection{Path: cliPath, Args: []string{"--capture-file", capturePath}} + opts.GitHubToken = "advanced-resume-client-token" + opts.UseLoggedInUser = copilot.Bool(false) + }) + t.Cleanup(func() { client.ForceStop() }) + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Start failed: %v", err) + } + + workingDirectory := t.TempDir() + configDirectory := t.TempDir() + continuePendingWork := false + extensionSDKPath := filepath.Join(ctx.WorkDir, "resume-extension-sdk") + session, err := client.ResumeSession(t.Context(), "resume-session-id", &copilot.ResumeSessionConfig{ + Model: "gpt-5-mini", + ReasoningEffort: "low", + ReasoningSummary: copilot.ReasoningSummaryNone, + ContextTier: copilot.ContextTierLongContext, + WorkingDirectory: workingDirectory, + ConfigDirectory: configDirectory, + EnableConfigDiscovery: copilot.Bool(false), + SuppressResumeEvent: true, + ContinuePendingWork: &continuePendingWork, + Streaming: copilot.Bool(true), + IncludeSubAgentStreamingEvents: copilot.Bool(false), + GitHubToken: "advanced-resume-session-token", + Canvases: []copilot.CanvasDeclaration{{ + ID: "resume-canvas", + DisplayName: "Resume Canvas", + Description: "Resume canvas description", + InputSchema: map[string]any{"type": "object"}, + }}, + OpenCanvases: []rpc.OpenCanvasInstance{{ + CanvasID: "resume-canvas", + ExtensionID: "github-app/go-e2e-extension", + InstanceID: "resume-instance", + Input: map[string]any{"value": "from-resume"}, + }}, + RequestCanvasRenderer: copilot.Bool(true), + RequestExtensions: copilot.Bool(true), + ExtensionSDKPath: &extensionSDKPath, + ExtensionInfo: &copilot.ExtensionInfo{Source: "github-app", Name: "go-e2e-extension"}, + ExpAssignments: map[string]any{"resumeFeature": "enabled"}, + }) + if err != nil { + t.Fatalf("ResumeSession failed: %v", err) + } + session.Disconnect() + + resumeReq := getCapturedRequest(t, capturePath, "session.resume") + params := resumeReq.Params.(map[string]any) + expectedValues := map[string]any{ + "sessionId": "resume-session-id", + "model": "gpt-5-mini", + "reasoningEffort": "low", + "reasoningSummary": "none", + "contextTier": "long_context", + "workingDirectory": workingDirectory, + "configDir": configDirectory, + "enableConfigDiscovery": false, + "disableResume": true, + "continuePendingWork": false, + "streaming": true, + "includeSubAgentStreamingEvents": false, + "gitHubToken": "advanced-resume-session-token", + "requestCanvasRenderer": true, + "requestExtensions": true, + "extensionSdkPath": extensionSDKPath, + "envValueMode": "direct", + } + for key, expected := range expectedValues { + if params[key] != expected { + t.Fatalf("Expected resume %s=%#v, got %#v in %#v", key, expected, params[key], params) + } + } + openCanvases := params["openCanvases"].([]any) + openCanvas := openCanvases[0].(map[string]any) + if openCanvas["canvasId"] != "resume-canvas" || openCanvas["extensionId"] != "github-app/go-e2e-extension" || + openCanvas["instanceId"] != "resume-instance" { + t.Fatalf("Expected open canvas state to be forwarded, got %#v", openCanvas) + } + extensionInfo := params["extensionInfo"].(map[string]any) + if extensionInfo["source"] != "github-app" || extensionInfo["name"] != "go-e2e-extension" { + t.Fatalf("Expected extensionInfo on resume, got %#v", extensionInfo) + } + if params["expAssignments"].(map[string]any)["resumeFeature"] != "enabled" { + t.Fatalf("Expected resume expAssignments to be forwarded, got %#v", params["expAssignments"]) + } + }) + } // --------------------------------------------------------------------------- @@ -353,8 +663,36 @@ func readCapture(t *testing.T, path string) capturedCli { return c } -// fakeStdioCliScript is identical to the one used by the .NET / Python -// equivalents (dotnet/test/ClientOptionsTests.cs and python/e2e/test_client_options.py). +func getCapturedRequest(t *testing.T, path, method string) capturedRequest { + t.Helper() + capture := readCapture(t, path) + for _, request := range capture.Requests { + if request.Method == method { + return request + } + } + t.Fatalf("Expected %s request in capture, got %+v", method, capture.Requests) + return capturedRequest{} +} + +func assertStringArray(t *testing.T, value any, expected []string) { + t.Helper() + items, ok := value.([]any) + if !ok { + t.Fatalf("Expected string array %v, got %#v", expected, value) + } + if len(items) != len(expected) { + t.Fatalf("Expected string array %v, got %#v", expected, items) + } + for i, expectedValue := range expected { + if items[i] != expectedValue { + t.Fatalf("Expected string array %v, got %#v", expected, items) + } + } +} + +// fakeStdioCliScript is intentionally kept close to the fake CLIs used by the +// other SDK client-options E2E tests, while still matching Go's request capture shape. const fakeStdioCliScript = ` const fs = require("fs"); @@ -430,6 +768,11 @@ function handleMessage(message) { writeResponse(message.id, { sessionId, workspacePath: null, capabilities: null }); return; } + if (message.method === "session.resume") { + const sessionId = (message.params && message.params.sessionId) || "fake-session"; + writeResponse(message.id, { sessionId, workspacePath: null, capabilities: null }); + return; + } writeResponse(message.id, {}); } diff --git a/go/internal/e2e/copilot_request_cancel_error_e2e_test.go b/go/internal/e2e/copilot_request_cancel_error_e2e_test.go index c48a617021..46091d5ac7 100644 --- a/go/internal/e2e/copilot_request_cancel_error_e2e_test.go +++ b/go/internal/e2e/copilot_request_cancel_error_e2e_test.go @@ -54,6 +54,7 @@ func (tr *throwingTransport) RoundTrip(req *http.Request) (*http.Response, error } func TestCopilotRequestError(t *testing.T) { + testharness.SkipIfInProcess(t, "an LLM inference provider is process-global in-process") ctx := testharness.NewTestContext(t) transport := &throwingTransport{} handler := &copilot.CopilotRequestHandler{Transport: transport} @@ -132,6 +133,7 @@ func waitFor(t *testing.T, predicate func() bool, timeout time.Duration) { } func TestCopilotRequestCancel(t *testing.T) { + testharness.SkipIfInProcess(t, "an LLM inference provider is process-global in-process") ctx := testharness.NewTestContext(t) transport := newCancellingTransport() handler := &copilot.CopilotRequestHandler{Transport: transport} diff --git a/go/internal/e2e/copilot_request_handler_e2e_test.go b/go/internal/e2e/copilot_request_handler_e2e_test.go index 052a1bdebc..a0cfcb63ea 100644 --- a/go/internal/e2e/copilot_request_handler_e2e_test.go +++ b/go/internal/e2e/copilot_request_handler_e2e_test.go @@ -119,6 +119,7 @@ func (rt *rewritingRoundTripper) RoundTrip(req *http.Request) (*http.Response, e } func TestCopilotRequestHandler(t *testing.T) { + testharness.SkipIfInProcess(t, "an LLM inference provider is process-global in-process") ctx := testharness.NewTestContext(t) counters := &handlerCounters{} httpURL, wsURL := startFakeUpstreams(t, counters) diff --git a/go/internal/e2e/copilot_request_helpers_test.go b/go/internal/e2e/copilot_request_helpers_test.go index 69e82c2ab9..81d14f4d94 100644 --- a/go/internal/e2e/copilot_request_helpers_test.go +++ b/go/internal/e2e/copilot_request_helpers_test.go @@ -128,6 +128,47 @@ func buildResponsesSSEBody(text, respID string) string { return sb.String() } +// buildAnthropicMessageSSEBody returns a complete Anthropic Messages SSE body for a +// streaming /messages response (message_start … message_stop). The buffered JSON +// message is only valid for a non-streaming request; a streaming request expects +// named SSE events or the runtime fails to finalize the message. +func buildAnthropicMessageSSEBody(text string) string { + events := []struct { + name string + data map[string]any + }{ + {"message_start", map[string]any{ + "type": "message_start", + "message": map[string]any{ + "id": "msg_stub_1", "type": "message", "role": "assistant", + "model": "claude-sonnet-4.5", "content": []any{}, + "stop_reason": nil, "stop_sequence": nil, + "usage": map[string]any{"input_tokens": 5, "output_tokens": 1}, + }, + }}, + {"content_block_start", map[string]any{ + "type": "content_block_start", "index": 0, + "content_block": map[string]any{"type": "text", "text": ""}, + }}, + {"content_block_delta", map[string]any{ + "type": "content_block_delta", "index": 0, + "delta": map[string]any{"type": "text_delta", "text": text}, + }}, + {"content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}}, + {"message_delta", map[string]any{ + "type": "message_delta", + "delta": map[string]any{"stop_reason": "end_turn", "stop_sequence": nil}, + "usage": map[string]any{"output_tokens": 7}, + }}, + {"message_stop", map[string]any{"type": "message_stop"}}, + } + var sb strings.Builder + for _, event := range events { + sb.WriteString(sseFrame(event.name, event.data)) + } + return sb.String() +} + // buildInferenceResponse synthesizes a well-formed inference HTTP response. func buildInferenceResponse(url string, bodyText string) *http.Response { wantsStream := isStreamingRequest(bodyText) @@ -166,6 +207,23 @@ func buildInferenceResponse(url string, bodyText string) *http.Response { return buildSSEResponse(sb.String()) } + if strings.HasSuffix(u, "/messages") { + if wantsStream { + return buildSSEResponse(buildAnthropicMessageSSEBody(syntheticResponseText)) + } + raw, _ := json.Marshal(map[string]any{ + "id": "msg_stub_1", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4.5", + "content": []any{map[string]any{"type": "text", "text": syntheticResponseText}}, + "stop_reason": "end_turn", + "stop_sequence": nil, + "usage": map[string]any{"input_tokens": 5, "output_tokens": 7}, + }) + return buildJSONResponse(200, string(raw)) + } + raw, _ := json.Marshal(map[string]any{ "id": "chatcmpl-stub-1", "object": "chat.completion", "created": 1, "model": "claude-sonnet-4.5", "choices": []any{map[string]any{"index": 0, "message": map[string]any{"role": "assistant", "content": syntheticResponseText}, "finish_reason": "stop"}}, diff --git a/go/internal/e2e/copilot_request_session_id_e2e_test.go b/go/internal/e2e/copilot_request_session_id_e2e_test.go index 809f77da76..f7673bd457 100644 --- a/go/internal/e2e/copilot_request_session_id_e2e_test.go +++ b/go/internal/e2e/copilot_request_session_id_e2e_test.go @@ -6,18 +6,22 @@ package e2e import ( "io" + "net/http" "strings" "sync" "testing" copilot "github.com/github/copilot-sdk/go" "github.com/github/copilot-sdk/go/internal/e2e/testharness" - "net/http" ) type interceptedRequest struct { - url string - sessionID string + url string + sessionID string + agentID string + parentAgentID string + interactionType string + body string } // recordingTransport intercepts every model-layer request, records its URL and @@ -31,19 +35,32 @@ type recordingTransport struct { func (rt *recordingTransport) RoundTrip(req *http.Request) (*http.Response, error) { rctx := copilot.RequestContextFrom(req) sessionID := "" + agentID := "" + parentAgentID := "" + interactionType := "" if rctx != nil { sessionID = rctx.SessionID + agentID = rctx.AgentID + parentAgentID = rctx.ParentAgentID + interactionType = rctx.InteractionType } - rt.mu.Lock() - rt.records = append(rt.records, interceptedRequest{url: req.URL.String(), sessionID: sessionID}) - rt.mu.Unlock() - bodyBytes := []byte(nil) if req.Body != nil { bodyBytes, _ = io.ReadAll(req.Body) } bodyText := string(bodyBytes) + rt.mu.Lock() + rt.records = append(rt.records, interceptedRequest{ + url: req.URL.String(), + sessionID: sessionID, + agentID: agentID, + parentAgentID: parentAgentID, + interactionType: interactionType, + body: bodyText, + }) + rt.mu.Unlock() + if isInferenceURL(req.URL.String()) { return buildInferenceResponse(req.URL.String(), bodyText), nil } @@ -62,7 +79,18 @@ func (rt *recordingTransport) inferenceRecords() []interceptedRequest { return out } +func assertAgentMetadata(t *testing.T, r interceptedRequest) { + t.Helper() + if r.agentID == "" { + t.Fatal("inference request must carry an agent id") + } + if r.interactionType == "" { + t.Fatal("inference request must carry an interaction type") + } +} + func TestCopilotRequestSessionID(t *testing.T) { + testharness.SkipIfInProcess(t, "an LLM inference provider is process-global in-process") ctx := testharness.NewTestContext(t) transport := &recordingTransport{} handler := &copilot.CopilotRequestHandler{Transport: transport} @@ -98,6 +126,7 @@ func TestCopilotRequestSessionID(t *testing.T) { if r.sessionID != capiSessionID { t.Fatalf("CAPI inference request must carry session id %q, got %q", capiSessionID, r.sessionID) } + assertAgentMetadata(t, r) } // Validate the final assistant response arrived (guards against truncated captures) @@ -139,6 +168,7 @@ func TestCopilotRequestSessionID(t *testing.T) { if r.sessionID != byokSessionID { t.Fatalf("BYOK inference request must carry session id %q, got %q", byokSessionID, r.sessionID) } + assertAgentMetadata(t, r) } if byokSessionID == capiSessionID { diff --git a/go/internal/e2e/event_fidelity_e2e_test.go b/go/internal/e2e/event_fidelity_e2e_test.go index c48a4908a1..e7cc4bfb37 100644 --- a/go/internal/e2e/event_fidelity_e2e_test.go +++ b/go/internal/e2e/event_fidelity_e2e_test.go @@ -168,6 +168,7 @@ func TestEventFidelityE2E(t *testing.T) { if answer == nil { t.Fatal("Expected SendAndWait to return an assistant message") + return } if ad, ok := answer.Data.(*copilot.AssistantMessageData); !ok || !strings.Contains(ad.Content, "18") { t.Errorf("Expected answer to contain '18', got %v", answer.Data) diff --git a/go/internal/e2e/github_telemetry_e2e_test.go b/go/internal/e2e/github_telemetry_e2e_test.go new file mode 100644 index 0000000000..aa26ba31f2 --- /dev/null +++ b/go/internal/e2e/github_telemetry_e2e_test.go @@ -0,0 +1,68 @@ +package e2e + +import ( + "sync" + "testing" + "time" + + copilot "github.com/github/copilot-sdk/go" + "github.com/github/copilot-sdk/go/internal/e2e/testharness" + "github.com/github/copilot-sdk/go/rpc" +) + +func TestGitHubTelemetryE2E(t *testing.T) { + t.Run("should forward github telemetry for a live session", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + ctx.ConfigureForTest(t) + + var mu sync.Mutex + var notifications []*rpc.GitHubTelemetryNotification + client := ctx.NewClient(func(opts *copilot.ClientOptions) { + opts.OnGitHubTelemetry = func(notification *rpc.GitHubTelemetryNotification) { + mu.Lock() + notifications = append(notifications, notification) + mu.Unlock() + } + }) + t.Cleanup(func() { client.ForceStop() }) + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + t.Cleanup(func() { session.Disconnect() }) + + notification := waitForGitHubTelemetryNotification(t, &mu, ¬ifications, 30*time.Second) + if notification.SessionID == nil || *notification.SessionID == "" { + t.Fatal("Expected a non-empty SessionID") + } + if notification.Event.Kind == "" { + t.Fatal("Expected a non-empty Event.Kind") + } + }) +} + +func waitForGitHubTelemetryNotification(t *testing.T, mu *sync.Mutex, notifications *[]*rpc.GitHubTelemetryNotification, timeout time.Duration) *rpc.GitHubTelemetryNotification { + t.Helper() + + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + mu.Lock() + if len(*notifications) > 0 { + notification := (*notifications)[0] + mu.Unlock() + if notification != nil { + return notification + } + t.Fatal("Received nil GitHub telemetry notification") + } + mu.Unlock() + + time.Sleep(50 * time.Millisecond) + } + + t.Fatalf("Timed out waiting for GitHub telemetry notification after %s", timeout) + return nil +} diff --git a/go/internal/e2e/inprocess_ffi_e2e_test.go b/go/internal/e2e/inprocess_ffi_e2e_test.go new file mode 100644 index 0000000000..6923384a28 --- /dev/null +++ b/go/internal/e2e/inprocess_ffi_e2e_test.go @@ -0,0 +1,62 @@ +package e2e + +import ( + "testing" + + copilot "github.com/github/copilot-sdk/go" + "github.com/github/copilot-sdk/go/internal/e2e/testharness" +) + +// TestInProcessFfiE2E is a smoke test for the in-process (FFI) transport. It +// starts a client that loads the native runtime cdylib next to the resolved CLI +// entrypoint, lets the native host spawn the worker, performs a purely local +// "ping" round-trip through the runtime, and stops cleanly. No auth or replay +// proxy is involved, so it needs no snapshot. +// +// Mirrors python/e2e/test_inprocess_ffi_e2e.py and +// nodejs/test/e2e/inprocess_ffi.e2e.test.ts. +func TestInProcessFfiE2E(t *testing.T) { + // Loading the native runtime cdylib (libnode) into this test process installs + // foreign signal handlers. On macOS the Go runtime then aborts when it reaps + // its own os/exec children (see ffihost signal re-arming). The in-process + // matrix cell already loads libnode for the whole suite and re-arms those + // handlers; the default (child-process) cell must never load it, so restrict + // this dedicated FFI smoke test to the in-process cell. + if !testharness.IsInProcessTransport() { + t.Skip("in-process FFI smoke test runs only under the inprocess transport cell") + } + + cliPath := testharness.CLIPath() + if cliPath == "" { + t.Fatal("CLI not found. Run 'npm install' in the nodejs directory first.") + } + t.Setenv("COPILOT_CLI_PATH", cliPath) + + t.Run("should start and connect over in-process FFI", func(t *testing.T) { + client := copilot.NewClient(&copilot.ClientOptions{ + Connection: copilot.InProcessConnection{}, + }) + t.Cleanup(func() { client.ForceStop() }) + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Failed to start client over in-process FFI: %v", err) + } + + pong, err := client.Ping(t.Context(), "ffi message") + if err != nil { + t.Fatalf("Failed to ping: %v", err) + } + + if pong.Message != "pong: ffi message" { + t.Errorf("Expected pong.message to be 'pong: ffi message', got %q", pong.Message) + } + + if pong.Timestamp.IsZero() { + t.Errorf("Expected non-zero pong.timestamp, got %s", pong.Timestamp) + } + + if err := client.Stop(); err != nil { + t.Errorf("Expected no errors on stop, got %v", err) + } + }) +} diff --git a/go/internal/e2e/mcp_and_agents_e2e_test.go b/go/internal/e2e/mcp_and_agents_e2e_test.go index e4bd34e268..71a152ecaf 100644 --- a/go/internal/e2e/mcp_and_agents_e2e_test.go +++ b/go/internal/e2e/mcp_and_agents_e2e_test.go @@ -115,10 +115,7 @@ func TestMCPServersE2E(t *testing.T) { t.Run("should pass literal env values to MCP server subprocess", func(t *testing.T) { ctx.ConfigureForTest(t) - mcpServerPath, err := filepath.Abs("../../../test/harness/test-mcp-server.mjs") - if err != nil { - t.Fatalf("Failed to resolve test-mcp-server path: %v", err) - } + mcpServerPath := testharness.RepoPath("test", "harness", "test-mcp-server.mjs") mcpServerDir := filepath.Dir(mcpServerPath) mcpServers := map[string]copilot.MCPServerConfig{ diff --git a/go/internal/e2e/mcp_oauth_e2e_test.go b/go/internal/e2e/mcp_oauth_e2e_test.go new file mode 100644 index 0000000000..95de73eddd --- /dev/null +++ b/go/internal/e2e/mcp_oauth_e2e_test.go @@ -0,0 +1,456 @@ +package e2e + +import ( + "bufio" + "encoding/json" + "net/http" + "os" + "os/exec" + "slices" + "strings" + "sync" + "testing" + "time" + + copilot "github.com/github/copilot-sdk/go" + "github.com/github/copilot-sdk/go/internal/e2e/testharness" + "github.com/github/copilot-sdk/go/rpc" +) + +const expectedMCPOAuthToken = "sdk-host-token" +const refreshMCPOAuthToken = expectedMCPOAuthToken + "-refresh" +const upscopeMCPOAuthToken = expectedMCPOAuthToken + "-upscope" +const reauthMCPOAuthToken = expectedMCPOAuthToken + "-reauth" + +func TestMCPOAuthE2E(t *testing.T) { + ctx := testharness.NewTestContext(t) + client := ctx.NewClient() + t.Cleanup(func() { client.ForceStop() }) + + t.Run("satisfy MCP OAuth using host-provided token", func(t *testing.T) { + baseURL := startOAuthMCPServer(t) + serverName := "oauth-protected-mcp" + tokenType := "Bearer" + expiresIn := int64(3600) + var observedRequest copilot.MCPAuthRequest + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + OnMCPAuthRequest: func(request copilot.MCPAuthRequest, _ copilot.MCPAuthInvocation) (*copilot.MCPAuthResult, error) { + observedRequest = request + return copilot.MCPAuthResultToken(&copilot.MCPAuthToken{ + AccessToken: expectedMCPOAuthToken, + TokenType: &tokenType, + ExpiresIn: &expiresIn, + }), nil + }, + MCPServers: map[string]copilot.MCPServerConfig{ + serverName: copilot.MCPHTTPServerConfig{ + URL: baseURL + "/mcp", + Tools: []string{"*"}, + }, + }, + }) + if err != nil { + t.Fatalf("Failed to create session: %v", err) + } + t.Cleanup(func() { session.Disconnect() }) + + waitForMCPServerStatus(t, session, serverName, rpc.MCPServerStatusConnected) + tools, err := session.RPC.MCP.ListTools(t.Context(), &rpc.MCPListToolsRequest{ServerName: serverName}) + if err != nil { + t.Fatalf("Failed to list MCP tools: %v", err) + } + if len(tools.Tools) != 1 || tools.Tools[0].Name != "whoami" { + t.Fatalf("Expected whoami tool, got %#v", tools.Tools) + } + + if observedRequest.ServerName != serverName { + t.Fatalf("Expected serverName %q, got %q", serverName, observedRequest.ServerName) + } + if observedRequest.ServerURL != baseURL+"/mcp" { + t.Fatalf("Expected serverUrl %q, got %q", baseURL+"/mcp", observedRequest.ServerURL) + } + if observedRequest.WwwAuthenticateParams == nil { + t.Fatal("Expected WWW-Authenticate params") + } + if observedRequest.Reason != "initial" { + t.Fatalf("Unexpected auth request reason: %q", observedRequest.Reason) + } + if observedRequest.WwwAuthenticateParams.ResourceMetadataURL == nil || + *observedRequest.WwwAuthenticateParams.ResourceMetadataURL != baseURL+"/.well-known/oauth-protected-resource" { + t.Fatalf("Unexpected resource metadata URL: %v", observedRequest.WwwAuthenticateParams.ResourceMetadataURL) + } + if stringValue(observedRequest.WwwAuthenticateParams.Scope) != "mcp.read" || stringValue(observedRequest.WwwAuthenticateParams.Error) != "invalid_token" { + t.Fatalf("Unexpected WWW-Authenticate params: %#v", observedRequest.WwwAuthenticateParams) + } + + var metadata map[string]any + if observedRequest.ResourceMetadata == nil { + t.Fatal("Expected resource metadata to be propagated") + } + if err := json.Unmarshal([]byte(*observedRequest.ResourceMetadata), &metadata); err != nil { + t.Fatalf("Failed to parse resource metadata: %v", err) + } + if metadata["resource"] != baseURL+"/mcp" { + t.Fatalf("Expected resource %q, got %#v", baseURL+"/mcp", metadata["resource"]) + } + + requests := fetchOAuthMCPRequests(t, baseURL) + if !hasAuthorization(requests, "") { + t.Fatal("Expected at least one unauthenticated MCP request") + } + if !hasAuthorization(requests, "Bearer "+expectedMCPOAuthToken) { + t.Fatal("Expected at least one MCP request with host-provided token") + } + }) + + t.Run("request replacement tokens across MCP OAuth lifecycle", func(t *testing.T) { + baseURL := startOAuthMCPServer(t) + serverName := "oauth-lifecycle-mcp" + var mu sync.Mutex + var observedReasons []copilot.MCPOauthRequestReason + refreshCount := 0 + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + EnableMCPApps: true, + OnMCPAuthRequest: func(request copilot.MCPAuthRequest, _ copilot.MCPAuthInvocation) (*copilot.MCPAuthResult, error) { + mu.Lock() + observedReasons = append(observedReasons, request.Reason) + refreshOrdinal := 0 + if request.Reason == copilot.MCPOauthRequestReasonRefresh { + refreshCount++ + refreshOrdinal = refreshCount + } + mu.Unlock() + + token := expectedMCPOAuthToken + switch request.Reason { + case copilot.MCPOauthRequestReasonRefresh: + if request.WwwAuthenticateParams == nil || + request.WwwAuthenticateParams.ResourceMetadataURL != nil || + stringValue(request.WwwAuthenticateParams.Error) != "invalid_token" { + t.Fatalf("Unexpected refresh WWW-Authenticate params: %#v", request.WwwAuthenticateParams) + } + if refreshOrdinal > 1 { + return copilot.MCPAuthResultCancelled(), nil + } + token = refreshMCPOAuthToken + case copilot.MCPOauthRequestReasonUpscope: + token = upscopeMCPOAuthToken + if request.WwwAuthenticateParams == nil || + request.WwwAuthenticateParams.ResourceMetadataURL == nil || + *request.WwwAuthenticateParams.ResourceMetadataURL != baseURL+"/.well-known/oauth-protected-resource" || + stringValue(request.WwwAuthenticateParams.Scope) != "mcp.write" || + stringValue(request.WwwAuthenticateParams.Error) != "insufficient_scope" { + t.Fatalf("Unexpected upscope WWW-Authenticate params: %#v", request.WwwAuthenticateParams) + } + case copilot.MCPOauthRequestReasonReauth: + token = reauthMCPOAuthToken + } + return copilot.MCPAuthResultToken(&copilot.MCPAuthToken{AccessToken: token}), nil + }, + MCPServers: map[string]copilot.MCPServerConfig{ + serverName: copilot.MCPHTTPServerConfig{ + URL: baseURL + "/mcp", + Tools: []string{"*"}, + }, + }, + }) + if err != nil { + t.Fatalf("Failed to create session: %v", err) + } + t.Cleanup(func() { session.Disconnect() }) + + waitForMCPServerStatus(t, session, serverName, rpc.MCPServerStatusConnected) + callWhoami(t, session, serverName, "refresh") + callWhoami(t, session, serverName, "upscope") + callWhoami(t, session, serverName, "reauth") + + mu.Lock() + reasons := append([]copilot.MCPOauthRequestReason(nil), observedReasons...) + mu.Unlock() + expectedReasons := []copilot.MCPOauthRequestReason{ + copilot.MCPOauthRequestReasonInitial, + copilot.MCPOauthRequestReasonRefresh, + copilot.MCPOauthRequestReasonUpscope, + copilot.MCPOauthRequestReasonRefresh, + copilot.MCPOauthRequestReasonReauth, + } + if !slices.Equal(reasons, expectedReasons) { + t.Fatalf("Unexpected auth request reasons: %#v", reasons) + } + + requests := fetchOAuthMCPRequests(t, baseURL) + if !hasAuthorization(requests, "Bearer "+refreshMCPOAuthToken) { + t.Fatal("Expected at least one MCP request with refresh token") + } + if !hasAuthorization(requests, "Bearer "+upscopeMCPOAuthToken) { + t.Fatal("Expected at least one MCP request with upscope token") + } + if !hasAuthorization(requests, "Bearer "+reauthMCPOAuthToken) { + t.Fatal("Expected at least one MCP request with reauth token") + } + }) + + t.Run("cancel pending MCP OAuth request", func(t *testing.T) { + baseURL := startOAuthMCPServer(t) + serverName := "oauth-cancelled-mcp" + var mu sync.Mutex + var observedRequest copilot.MCPAuthRequest + var observed bool + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + OnMCPAuthRequest: func(request copilot.MCPAuthRequest, _ copilot.MCPAuthInvocation) (*copilot.MCPAuthResult, error) { + mu.Lock() + observedRequest = request + observed = true + mu.Unlock() + return copilot.MCPAuthResultCancelled(), nil + }, + MCPServers: map[string]copilot.MCPServerConfig{ + serverName: copilot.MCPHTTPServerConfig{ + URL: baseURL + "/mcp", + Tools: []string{"*"}, + }, + }, + }) + if err != nil { + t.Fatalf("Failed to create session: %v", err) + } + t.Cleanup(func() { session.Disconnect() }) + + waitForMCPServerStatus(t, session, serverName, rpc.MCPServerStatusNeedsAuth) + + // The MCP connection is kicked off by session.create, but the SDK only registers its + // `mcp.oauth_required` event interest once create returns. If the server's initial 401 + // wins that race, the runtime records `needs-auth` WITHOUT invoking the host callback, + // so `observedRequest` is briefly unset even after `needs-auth` is observed. A later + // auth retry (now that interest is registered) invokes the callback with the same + // `Initial` reason. Wait for the callback rather than sampling it the instant + // `needs-auth` first appears, which is what made this test flaky. + var request copilot.MCPAuthRequest + deadline := time.Now().Add(60 * time.Second) + for { + mu.Lock() + got := observed + request = observedRequest + mu.Unlock() + if got { + break + } + if time.Now().After(deadline) { + t.Fatalf("%s OAuth request did not reach the host callback", serverName) + } + time.Sleep(200 * time.Millisecond) + } + + if request.ServerName != serverName { + t.Fatalf("Expected serverName %q, got %q", serverName, request.ServerName) + } + if request.Reason != copilot.MCPOauthRequestReasonInitial { + t.Fatalf("Unexpected auth request reason: %q", request.Reason) + } + }) + + t.Run("resolve pending MCP OAuth request through RPC", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + ctx.ConfigureWithoutSnapshot(t) + client := ctx.NewClient() + defer client.ForceStop() + + baseURL := startOAuthMCPServer(t) + serverName := "oauth-direct-rpc-mcp" + requests := make(chan copilot.MCPAuthRequest, 1) + releaseHandler := make(chan struct{}) + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + EnableMCPApps: true, + OnMCPAuthRequest: func(request copilot.MCPAuthRequest, _ copilot.MCPAuthInvocation) (*copilot.MCPAuthResult, error) { + requests <- request + <-releaseHandler + return copilot.MCPAuthResultCancelled(), nil + }, + MCPServers: map[string]copilot.MCPServerConfig{ + serverName: copilot.MCPHTTPServerConfig{ + URL: baseURL + "/mcp", + Tools: []string{"*"}, + }, + }, + }) + if err != nil { + t.Fatalf("Failed to create session: %v", err) + } + t.Cleanup(func() { session.Disconnect() }) + + connected := make(chan error, 1) + go func() { + connected <- waitForMCPServerStatusResult(t.Context(), session, serverName, rpc.MCPServerStatusConnected, 60*time.Second) + }() + + var request copilot.MCPAuthRequest + select { + case request = <-requests: + case <-time.After(30 * time.Second): + t.Fatal("Timed out waiting for MCP OAuth request") + } + + tokenType := "Bearer" + expiresIn := int64(3600) + result, err := session.RPC.MCP.Oauth().HandlePendingRequest(t.Context(), &rpc.MCPOauthHandlePendingRequest{ + RequestID: request.RequestID, + Result: rpc.MCPOauthPendingRequestResponseToken{ + AccessToken: expectedMCPOAuthToken, + TokenType: &tokenType, + ExpiresIn: &expiresIn, + }, + }) + if err != nil { + close(releaseHandler) + t.Fatalf("HandlePendingRequest failed: %v", err) + } + close(releaseHandler) + if !result.Success { + t.Fatal("Expected direct MCP OAuth pending request resolution to succeed") + } + + if err := <-connected; err != nil { + t.Fatal(err) + } + requestLog := fetchOAuthMCPRequests(t, baseURL) + if !hasAuthorization(requestLog, "Bearer "+expectedMCPOAuthToken) { + t.Fatal("Expected MCP request with token supplied through direct RPC") + } + }) +} + +type oauthMCPRequest struct { + Authorization *string `json:"authorization"` +} + +func startOAuthMCPServer(t *testing.T) string { + t.Helper() + + serverPath := testharness.RepoPath("test", "harness", "test-mcp-oauth-server.mjs") + cmd := exec.Command("node", serverPath) + cmd.Env = append(os.Environ(), "EXPECTED_TOKEN="+expectedMCPOAuthToken) + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatalf("Failed to pipe OAuth MCP server stdout: %v", err) + } + var stderr syncBuffer + cmd.Stderr = &stderr + if err := cmd.Start(); err != nil { + t.Fatalf("Failed to start OAuth MCP server: %v", err) + } + t.Cleanup(func() { + if cmd.ProcessState != nil && cmd.ProcessState.Exited() { + return + } + _ = cmd.Process.Kill() + _, _ = cmd.Process.Wait() + }) + + lines := make(chan string, 1) + go func() { + scanner := bufio.NewScanner(stdout) + for scanner.Scan() { + lines <- scanner.Text() + return + } + close(lines) + }() + + select { + case line, ok := <-lines: + if !ok { + t.Fatalf("OAuth MCP server exited before listening: %s", stderr.String()) + } + const prefix = "Listening: " + if !strings.HasPrefix(line, prefix) { + t.Fatalf("Unexpected OAuth MCP server startup line %q. stderr=%s", line, stderr.String()) + } + return strings.TrimPrefix(line, prefix) + case <-time.After(10 * time.Second): + t.Fatalf("Timed out waiting for OAuth MCP server: %s", stderr.String()) + } + return "" +} + +func stringValue(value *string) string { + if value == nil { + return "" + } + return *value +} + +// syncBuffer is a minimal io.Writer whose contents can be read concurrently. +// os/exec writes to cmd.Stderr on a separate goroutine, so reading a plain +// strings.Builder while the process is running is a data race (caught by -race). +type syncBuffer struct { + mu sync.Mutex + buf strings.Builder +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func fetchOAuthMCPRequests(t *testing.T, baseURL string) []oauthMCPRequest { + t.Helper() + + response, err := http.Get(baseURL + "/__requests") + if err != nil { + t.Fatalf("Failed to fetch OAuth MCP requests: %v", err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + t.Fatalf("Failed to fetch OAuth MCP requests: %s", response.Status) + } + var requests []oauthMCPRequest + if err := json.NewDecoder(response.Body).Decode(&requests); err != nil { + t.Fatalf("Failed to decode OAuth MCP requests: %v", err) + } + return requests +} + +func hasAuthorization(requests []oauthMCPRequest, expected string) bool { + for _, request := range requests { + if request.Authorization == nil && expected == "" { + return true + } + if request.Authorization != nil && *request.Authorization == expected { + return true + } + } + return false +} + +func callWhoami(t *testing.T, session *copilot.Session, serverName string, scenario string) { + t.Helper() + + result, err := session.RPC.MCP.Apps().CallTool(t.Context(), &rpc.MCPAppsCallToolRequest{ + OriginServerName: serverName, + ServerName: serverName, + ToolName: "whoami", + Arguments: map[string]any{"scenario": scenario}, + }) + if err != nil { + t.Fatalf("Failed to call whoami for %s: %v", scenario, err) + } + content, ok := (*result)["content"].([]any) + if !ok || len(content) != 1 { + t.Fatalf("Unexpected whoami result: %#v", result) + } +} diff --git a/go/internal/e2e/mcp_server_helpers_test.go b/go/internal/e2e/mcp_server_helpers_test.go index 1860067eda..68e72b18bc 100644 --- a/go/internal/e2e/mcp_server_helpers_test.go +++ b/go/internal/e2e/mcp_server_helpers_test.go @@ -1,21 +1,21 @@ package e2e import ( + "context" + "fmt" "path/filepath" "testing" "time" copilot "github.com/github/copilot-sdk/go" + "github.com/github/copilot-sdk/go/internal/e2e/testharness" "github.com/github/copilot-sdk/go/rpc" ) func testMCPServers(t *testing.T, serverNames ...string) map[string]copilot.MCPServerConfig { t.Helper() - mcpServerPath, err := filepath.Abs("../../../test/harness/test-mcp-server.mjs") - if err != nil { - t.Fatalf("Failed to resolve test-mcp-server path: %v", err) - } + mcpServerPath := testharness.RepoPath("test", "harness", "test-mcp-server.mjs") mcpServerDir := filepath.Dir(mcpServerPath) mcpServers := make(map[string]copilot.MCPServerConfig, len(serverNames)) @@ -33,10 +33,16 @@ func testMCPServers(t *testing.T, serverNames ...string) map[string]copilot.MCPS func waitForMCPServerStatus(t *testing.T, session *copilot.Session, serverName string, expectedStatus rpc.MCPServerStatus) { t.Helper() + if err := waitForMCPServerStatusResult(t.Context(), session, serverName, expectedStatus, 60*time.Second); err != nil { + t.Fatal(err) + } +} + +func waitForMCPServerStatusResult(ctx context.Context, session *copilot.Session, serverName string, expectedStatus rpc.MCPServerStatus, timeout time.Duration) error { var lastStatus string - deadline := time.Now().Add(60 * time.Second) + deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { - result, err := session.RPC.MCP.List(t.Context()) + result, err := session.RPC.MCP.List(ctx) if err != nil { lastStatus = err.Error() } else { @@ -46,7 +52,7 @@ func waitForMCPServerStatus(t *testing.T, session *copilot.Session, serverName s continue } if server.Status == expectedStatus { - return + return nil } lastStatus = string(server.Status) break @@ -55,5 +61,5 @@ func waitForMCPServerStatus(t *testing.T, session *copilot.Session, serverName s time.Sleep(200 * time.Millisecond) } - t.Fatalf("%s did not reach %s; last status was %s", serverName, expectedStatus, lastStatus) + return fmt.Errorf("%s did not reach %s; last status was %s", serverName, expectedStatus, lastStatus) } diff --git a/go/internal/e2e/mode_handlers_e2e_test.go b/go/internal/e2e/mode_handlers_e2e_test.go index 15800bf858..e7471fbd06 100644 --- a/go/internal/e2e/mode_handlers_e2e_test.go +++ b/go/internal/e2e/mode_handlers_e2e_test.go @@ -101,7 +101,7 @@ func TestModeHandlersE2E(t *testing.T) { if request.Summary != planSummary { t.Fatalf("Expected summary %q, got %q", planSummary, request.Summary) } - if len(request.Actions) != 3 || request.Actions[0] != "interactive" || request.Actions[1] != "autopilot" || request.Actions[2] != "exit_only" { + if len(request.Actions) != 3 || request.Actions[0] != "autopilot" || request.Actions[1] != "interactive" || request.Actions[2] != "exit_only" { t.Fatalf("Unexpected actions: %#v", request.Actions) } if request.RecommendedAction != "interactive" { diff --git a/go/internal/e2e/per_session_auth_e2e_test.go b/go/internal/e2e/per_session_auth_e2e_test.go index eed11bcfa2..e004fa6b5a 100644 --- a/go/internal/e2e/per_session_auth_e2e_test.go +++ b/go/internal/e2e/per_session_auth_e2e_test.go @@ -47,7 +47,7 @@ func TestPerSessionAuthE2E(t *testing.T) { t.Fatalf("Failed to create session: %v", err) } - authStatus, err := session.RPC.Auth.GetStatus(t.Context()) + authStatus, err := session.RPC.GitHubAuth.GetStatus(t.Context()) if err != nil { t.Fatalf("Failed to get auth status: %v", err) } @@ -79,12 +79,12 @@ func TestPerSessionAuthE2E(t *testing.T) { t.Fatalf("Failed to create session B: %v", err) } - statusA, err := sessionA.RPC.Auth.GetStatus(t.Context()) + statusA, err := sessionA.RPC.GitHubAuth.GetStatus(t.Context()) if err != nil { t.Fatalf("Failed to get auth status for session A: %v", err) } - statusB, err := sessionB.RPC.Auth.GetStatus(t.Context()) + statusB, err := sessionB.RPC.GitHubAuth.GetStatus(t.Context()) if err != nil { t.Fatalf("Failed to get auth status for session B: %v", err) } @@ -115,7 +115,7 @@ func TestPerSessionAuthE2E(t *testing.T) { t.Fatalf("Failed to create session: %v", err) } - authStatus, err := session.RPC.Auth.GetStatus(t.Context()) + authStatus, err := session.RPC.GitHubAuth.GetStatus(t.Context()) if err != nil { t.Fatalf("Failed to get auth status: %v", err) } diff --git a/go/internal/e2e/pre_mcp_tool_call_hook_e2e_test.go b/go/internal/e2e/pre_mcp_tool_call_hook_e2e_test.go index 1847270922..111cfb86a4 100644 --- a/go/internal/e2e/pre_mcp_tool_call_hook_e2e_test.go +++ b/go/internal/e2e/pre_mcp_tool_call_hook_e2e_test.go @@ -15,7 +15,7 @@ func TestPreMCPToolCallHookE2E(t *testing.T) { client := ctx.NewClient() t.Cleanup(func() { client.ForceStop() }) - testHarnessDir, _ := filepath.Abs("../../../test/harness") + testHarnessDir := testharness.RepoPath("test", "harness") metaEchoServer := filepath.Join(testHarnessDir, "test-mcp-meta-echo-server.mjs") metaEchoConfig := func() map[string]copilot.MCPServerConfig { diff --git a/go/internal/e2e/resume_mcp_oauth_e2e_test.go b/go/internal/e2e/resume_mcp_oauth_e2e_test.go new file mode 100644 index 0000000000..db61f483a9 --- /dev/null +++ b/go/internal/e2e/resume_mcp_oauth_e2e_test.go @@ -0,0 +1,60 @@ +package e2e + +import ( + "strings" + "testing" + + copilot "github.com/github/copilot-sdk/go" + "github.com/github/copilot-sdk/go/internal/e2e/testharness" +) + +func TestResumeMCPOAuthE2E(t *testing.T) { + ctx := testharness.NewTestContext(t) + client := ctx.NewClient() + t.Cleanup(func() { client.ForceStop() }) + + t.Run("should resume a persisted session with mcp auth handler", func(t *testing.T) { + ctx.ConfigureForTest(t) + + mcpAuthHandler := func(copilot.MCPAuthRequest, copilot.MCPAuthInvocation) (*copilot.MCPAuthResult, error) { + return copilot.MCPAuthResultCancelled(), nil + } + + session1, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + OnMCPAuthRequest: mcpAuthHandler, + }) + if err != nil { + t.Fatalf("Failed to create session: %v", err) + } + sessionID := session1.SessionID + + _, err = session1.Send(t.Context(), copilot.MessageOptions{Prompt: "What is 1+1?"}) + if err != nil { + t.Fatalf("Failed to send message: %v", err) + } + + answer, err := testharness.GetFinalAssistantMessage(t.Context(), session1) + if err != nil { + t.Fatalf("Failed to get assistant message: %v", err) + } + if ad, ok := answer.Data.(*copilot.AssistantMessageData); !ok || !strings.Contains(ad.Content, "2") { + t.Errorf("Expected answer to contain '2', got %v", answer.Data) + } + + newClient := ctx.NewClient() + t.Cleanup(func() { newClient.ForceStop() }) + + session2, err := newClient.ResumeSession(t.Context(), sessionID, &copilot.ResumeSessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + OnMCPAuthRequest: mcpAuthHandler, + }) + if err != nil { + t.Fatalf("Failed to resume session: %v", err) + } + + if session2.SessionID != sessionID { + t.Errorf("Expected resumed session ID to match, got %q vs %q", session2.SessionID, sessionID) + } + }) +} diff --git a/go/internal/e2e/rpc_server_e2e_test.go b/go/internal/e2e/rpc_server_e2e_test.go index ba661acdba..6ea9ad6851 100644 --- a/go/internal/e2e/rpc_server_e2e_test.go +++ b/go/internal/e2e/rpc_server_e2e_test.go @@ -3,6 +3,7 @@ package e2e import ( "fmt" "path/filepath" + "runtime" "strings" "testing" "time" @@ -196,6 +197,44 @@ func TestRPCServerE2E(t *testing.T) { } }) + t.Run("should return false for missing LLM response frames", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + client := ctx.NewClient() + t.Cleanup(func() { client.ForceStop() }) + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Start failed: %v", err) + } + + start, err := client.RPC.LlmInference.HttpResponseStart(t.Context(), &rpc.LlmInferenceHTTPResponseStartRequest{ + RequestID: "missing-response-start-request", + Status: 200, + StatusText: rpcPtr("OK"), + Headers: map[string][]string{ + "content-type": {"application/json"}, + }, + }) + if err != nil { + t.Fatalf("LlmInference.HttpResponseStart failed: %v", err) + } + if start.Accepted { + t.Fatal("Expected Accepted=false for missing LLM response start request id") + } + + end := true + chunk, err := client.RPC.LlmInference.HttpResponseChunk(t.Context(), &rpc.LlmInferenceHTTPResponseChunkRequest{ + RequestID: "missing-response-chunk-request", + Data: "{}", + End: &end, + }) + if err != nil { + t.Fatalf("LlmInference.HttpResponseChunk failed: %v", err) + } + if chunk.Accepted { + t.Fatal("Expected Accepted=false for missing LLM response chunk request id") + } + }) + t.Run("should list find and inspect persisted session state", func(t *testing.T) { ctx := testharness.NewTestContext(t) token := "rpc-server-list-token-" + randomHex(t) @@ -554,6 +593,84 @@ func TestRPCServerE2E(t *testing.T) { t.Errorf("Expected skill path to end with %q, got %v", expectedSuffix, discovered.Path) } + excludeHost := true + skillPaths, err := client.RPC.Skills.GetDiscoveryPaths(t.Context(), &rpc.SkillsGetDiscoveryPathsRequest{ + ProjectPaths: []string{ctx.WorkDir}, + ExcludeHostSkills: &excludeHost, + }) + if err != nil { + t.Fatalf("Skills.GetDiscoveryPaths failed: %v", err) + } + projectSkillPath := findSkillDiscoveryPath(skillPaths.Paths, ctx.WorkDir) + if projectSkillPath == nil { + t.Fatalf("Expected skill discovery paths to include %q", ctx.WorkDir) + return + } + if strings.TrimSpace(projectSkillPath.Path) == "" { + t.Fatal("Expected non-empty skill discovery path") + } + + agents, err := client.RPC.Agents.Discover(t.Context(), &rpc.AgentsDiscoverRequest{ + ProjectPaths: []string{ctx.WorkDir}, + ExcludeHostAgents: &excludeHost, + }) + if err != nil { + t.Fatalf("Agents.Discover failed: %v", err) + } + for _, agent := range agents.Agents { + if strings.TrimSpace(agent.Name) == "" { + t.Fatalf("Expected discovered agent to have a name: %+v", agent) + } + } + + agentPaths, err := client.RPC.Agents.GetDiscoveryPaths(t.Context(), &rpc.AgentsGetDiscoveryPathsRequest{ + ProjectPaths: []string{ctx.WorkDir}, + ExcludeHostAgents: &excludeHost, + }) + if err != nil { + t.Fatalf("Agents.GetDiscoveryPaths failed: %v", err) + } + projectAgentPath := findAgentDiscoveryPath(agentPaths.Paths, ctx.WorkDir) + if projectAgentPath == nil { + t.Fatalf("Expected agent discovery paths to include %q", ctx.WorkDir) + return + } + if strings.TrimSpace(projectAgentPath.Path) == "" { + t.Fatal("Expected non-empty agent discovery path") + } + + instructions, err := client.RPC.Instructions.Discover(t.Context(), &rpc.InstructionsDiscoverRequest{ + ProjectPaths: []string{ctx.WorkDir}, + ExcludeHostInstructions: &excludeHost, + }) + if err != nil { + t.Fatalf("Instructions.Discover failed: %v", err) + } + for _, source := range instructions.Sources { + if strings.TrimSpace(source.ID) == "" || strings.TrimSpace(source.Label) == "" || strings.TrimSpace(source.SourcePath) == "" { + t.Fatalf("Expected discovered instruction source fields to be populated: %+v", source) + } + } + + instructionPaths, err := client.RPC.Instructions.GetDiscoveryPaths(t.Context(), &rpc.InstructionsGetDiscoveryPathsRequest{ + ProjectPaths: []string{ctx.WorkDir}, + ExcludeHostInstructions: &excludeHost, + }) + if err != nil { + t.Fatalf("Instructions.GetDiscoveryPaths failed: %v", err) + } + if len(instructionPaths.Paths) == 0 { + t.Fatal("Expected instruction discovery paths") + } + if !hasInstructionDiscoveryPath(instructionPaths.Paths, ctx.WorkDir) { + t.Fatalf("Expected instruction discovery paths to include %q", ctx.WorkDir) + } + for _, path := range instructionPaths.Paths { + if strings.TrimSpace(path.Path) == "" { + t.Fatalf("Expected non-empty instruction discovery path: %+v", path) + } + } + // Disable the skill globally and re-discover. if _, err := client.RPC.Skills.Config().SetDisabledSkills(t.Context(), &rpc.SkillsConfigSetDisabledSkillsRequest{ DisabledSkills: []string{skillName}, @@ -615,6 +732,42 @@ func findServerSkill(skills []rpc.ServerSkill, name string) *rpc.ServerSkill { return nil } +func findSkillDiscoveryPath(paths []rpc.SkillDiscoveryPath, projectPath string) *rpc.SkillDiscoveryPath { + for i, path := range paths { + if path.ProjectPath != nil && path.PreferredForCreation && pathsEqual(*path.ProjectPath, projectPath) { + return &paths[i] + } + } + return nil +} + +func findAgentDiscoveryPath(paths []rpc.AgentDiscoveryPath, projectPath string) *rpc.AgentDiscoveryPath { + for i, path := range paths { + if path.ProjectPath != nil && path.PreferredForCreation && pathsEqual(*path.ProjectPath, projectPath) { + return &paths[i] + } + } + return nil +} + +func hasInstructionDiscoveryPath(paths []rpc.InstructionDiscoveryPath, projectPath string) bool { + for _, path := range paths { + if path.ProjectPath != nil && pathsEqual(*path.ProjectPath, projectPath) { + return true + } + } + return false +} + +func pathsEqual(left, right string) bool { + left = filepath.Clean(left) + right = filepath.Clean(right) + if runtime.GOOS == "windows" { + return strings.EqualFold(left, right) + } + return left == right +} + func saveSession(t *testing.T, client *copilot.Client, sessionID string) { t.Helper() if _, err := client.RPC.Sessions.Save(t.Context(), &rpc.SessionsSaveRequest{SessionID: sessionID}); err != nil { diff --git a/go/internal/e2e/rpc_server_misc_e2e_test.go b/go/internal/e2e/rpc_server_misc_e2e_test.go index 34b48b5063..37ec57e1ba 100644 --- a/go/internal/e2e/rpc_server_misc_e2e_test.go +++ b/go/internal/e2e/rpc_server_misc_e2e_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + copilot "github.com/github/copilot-sdk/go" "github.com/github/copilot-sdk/go/internal/e2e/testharness" "github.com/github/copilot-sdk/go/rpc" ) @@ -25,6 +26,169 @@ func TestRpcServerMisc(t *testing.T) { } }) + t.Run("should_get_set_and_clear_user_settings", func(t *testing.T) { + ctx.ConfigureForTest(t) + client := newStartedIsolatedPortedClient(t, ctx) + defer client.ForceStop() + + initial, err := client.RPC.User.Settings().Get(t.Context()) + if err != nil { + t.Fatalf("User.Settings.Get initial failed: %v", err) + } + if initial.Settings == nil { + t.Fatal("Expected settings map") + } + var key string + var value bool + for candidateKey, setting := range initial.Settings { + if candidateValue, ok := setting.Value.(bool); ok { + key = candidateKey + value = candidateValue + break + } + } + if key == "" { + t.Fatalf("Expected at least one boolean setting, got %+v", initial.Settings) + } + toggledValue := !value + + set, err := client.RPC.User.Settings().Set(t.Context(), &rpc.UserSettingsSetRequest{ + Settings: map[string]any{key: toggledValue}, + }) + if err != nil { + t.Fatalf("User.Settings.Set(toggle) failed: %v", err) + } + if len(set.ShadowedKeys) != 0 { + t.Fatalf("Expected no shadowed settings keys, got %+v", set.ShadowedKeys) + } + if _, err := client.RPC.User.Settings().Reload(t.Context()); err != nil { + t.Fatalf("User.Settings.Reload after set failed: %v", err) + } + afterSet, err := client.RPC.User.Settings().Get(t.Context()) + if err != nil { + t.Fatalf("User.Settings.Get after set failed: %v", err) + } + metadata, ok := afterSet.Settings[key] + if !ok { + t.Fatalf("Expected setting %q in %+v", key, afterSet.Settings) + } + if metadata.Value != toggledValue || metadata.IsDefault { + t.Fatalf("Expected explicit true setting, got %+v", metadata) + } + + clear, err := client.RPC.User.Settings().Set(t.Context(), &rpc.UserSettingsSetRequest{ + Settings: map[string]any{key: nil}, + }) + if err != nil { + t.Fatalf("User.Settings.Set(null) failed: %v", err) + } + if len(clear.ShadowedKeys) != 0 { + t.Fatalf("Expected no shadowed settings keys from clear, got %+v", clear.ShadowedKeys) + } + if _, err := client.RPC.User.Settings().Reload(t.Context()); err != nil { + t.Fatalf("User.Settings.Reload after clear failed: %v", err) + } + afterClear, err := client.RPC.User.Settings().Get(t.Context()) + if err != nil { + t.Fatalf("User.Settings.Get after clear failed: %v", err) + } + metadata, ok = afterClear.Settings[key] + if !ok { + t.Fatalf("Expected setting %q after clear in %+v", key, afterClear.Settings) + } + if !metadata.IsDefault { + t.Fatalf("Expected cleared setting to be default, got %+v", metadata) + } + }) + + t.Run("should_login_list_getcurrentauth_and_logout_account", func(t *testing.T) { + ctx.ConfigureForTest(t) + if err := ctx.SetCopilotUserByToken("go-account-token", map[string]interface{}{ + "login": "go-account-user", + "copilot_plan": "individual_pro", + "endpoints": map[string]interface{}{ + "api": ctx.ProxyURL, + "telemetry": "https://localhost:1/telemetry", + }, + "analytics_tracking_id": "go-account-user-tracking-id", + }); err != nil { + t.Fatalf("SetCopilotUserByToken failed: %v", err) + } + client := newNoTokenClient(t, ctx) + defer client.ForceStop() + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Start failed: %v", err) + } + + initial, err := client.RPC.Account.GetCurrentAuth(t.Context()) + if err != nil { + t.Fatalf("Account.GetCurrentAuth initial failed: %v", err) + } + if initial.AuthInfo != nil { + t.Fatalf("Expected no initial auth info, got %+v", initial.AuthInfo) + } + + login, err := client.RPC.Account.Login(t.Context(), &rpc.AccountLoginRequest{ + Host: "https://github.com", + Login: "go-account-user", + Token: "go-account-token", + }) + if err != nil { + t.Fatalf("Account.Login failed: %v", err) + } + if login == nil { + t.Fatal("Expected login result") + } + + current, err := client.RPC.Account.GetCurrentAuth(t.Context()) + if err != nil { + t.Fatalf("Account.GetCurrentAuth after login failed: %v", err) + } + authInfo, ok := current.AuthInfo.(*rpc.UserAuthInfo) + if !ok { + t.Fatalf("Expected user auth info after login, got %#v", current.AuthInfo) + } + if authInfo.Login != "go-account-user" || authInfo.Host != "https://github.com" { + t.Fatalf("Unexpected current auth info: %+v", authInfo) + } + + users, err := client.RPC.Account.GetAllUsers(t.Context()) + if err != nil { + t.Fatalf("Account.GetAllUsers failed: %v", err) + } + if users == nil { + t.Fatal("Expected non-nil users result") + return + } + for _, user := range *users { + userInfo, ok := user.AuthInfo.(*rpc.UserAuthInfo) + if !ok { + t.Fatalf("Expected user auth info in all users, got %#v", user.AuthInfo) + } + if userInfo.Login == "go-account-user" && (user.Token == nil || *user.Token != "go-account-token") { + t.Fatalf("Expected logged-in user's token to round trip, got %+v", user) + } + } + + logout, err := client.RPC.Account.Logout(t.Context(), &rpc.AccountLogoutRequest{ + AuthInfo: authInfo, + }) + if err != nil { + t.Fatalf("Account.Logout failed: %v", err) + } + if logout.HasMoreUsers { + t.Fatalf("Expected no users after isolated logout, got %+v", logout) + } + afterLogout, err := client.RPC.Account.GetCurrentAuth(t.Context()) + if err != nil { + t.Fatalf("Account.GetCurrentAuth after logout failed: %v", err) + } + if afterLogout.AuthInfo != nil { + t.Fatalf("Expected no auth after logout, got %+v", afterLogout.AuthInfo) + } + }) + t.Run("should_report_agent_registry_spawn_gate_closed", func(t *testing.T) { ctx.ConfigureForTest(t) client := newStartedIsolatedPortedClient(t, ctx) @@ -91,3 +255,22 @@ func TestRpcServerMisc(t *testing.T) { assertPortedContainsFold(t, message, "extension") }) } + +func newNoTokenClient(t *testing.T, ctx *testharness.TestContext) *copilot.Client { + t.Helper() + env := append([]string{}, ctx.Env()...) + env = append(env, + "COPILOT_HOME="+t.TempDir(), + "GH_CONFIG_DIR="+t.TempDir(), + "GH_TOKEN=", + "GITHUB_TOKEN=", + "COPILOT_SDK_AUTH_TOKEN=", + ) + useLoggedInUser := false + return copilot.NewClient(&copilot.ClientOptions{ + Connection: copilot.StdioConnection{Path: ctx.CLIPath}, + WorkingDirectory: ctx.WorkDir, + Env: env, + UseLoggedInUser: &useLoggedInUser, + }) +} diff --git a/go/internal/e2e/rpc_server_plugins_e2e_test.go b/go/internal/e2e/rpc_server_plugins_e2e_test.go index e79760e4a7..a9d1d243cc 100644 --- a/go/internal/e2e/rpc_server_plugins_e2e_test.go +++ b/go/internal/e2e/rpc_server_plugins_e2e_test.go @@ -20,7 +20,7 @@ const ( func TestRpcServerPlugins(t *testing.T) { ctx := testharness.NewTestContext(t) - t.Run("should_install_list_and_uninstall_plugin_from_local_marketplace", func(t *testing.T) { + t.Run("should_install_and_list_plugin_from_local_marketplace", func(t *testing.T) { ctx.ConfigureForTest(t) marketplaceDir := createPortedLocalMarketplaceFixture(t) client := newStartedIsolatedPortedClient(t, ctx) @@ -58,22 +58,12 @@ func TestRpcServerPlugins(t *testing.T) { listed := findPortedInstalledPlugin(afterInstall.Plugins, portedPluginName, portedMarketplaceName) if listed == nil { t.Fatalf("Expected installed plugin %q in marketplace %q", portedPluginName, portedMarketplaceName) + return } if !listed.Enabled { t.Fatal("Expected listed marketplace plugin to be enabled") } - if _, err := client.RPC.Plugins.Uninstall(t.Context(), &rpc.PluginsUninstallRequest{Name: spec}); err != nil { - t.Fatalf("Plugins.Uninstall failed: %v", err) - } - - afterUninstall, err := client.RPC.Plugins.List(t.Context()) - if err != nil { - t.Fatalf("Plugins.List after uninstall failed: %v", err) - } - if findPortedInstalledPlugin(afterUninstall.Plugins, portedPluginName, portedMarketplaceName) != nil { - t.Fatalf("Expected plugin %q to be removed", spec) - } }) t.Run("should_enable_and_disable_marketplace_plugin", func(t *testing.T) { @@ -200,8 +190,14 @@ func TestRpcServerPlugins(t *testing.T) { if countPortedInstalledPluginByName(afterInstall.Plugins, portedDirectPluginName) != 1 { t.Fatalf("Expected exactly one direct plugin named %q, got %+v", portedDirectPluginName, afterInstall.Plugins) } + if install.Plugin.DirectSourceID == nil { + t.Fatal("Expected direct plugin install to include directSourceId") + } - if _, err := client.RPC.Plugins.Uninstall(t.Context(), &rpc.PluginsUninstallRequest{Name: portedDirectPluginName}); err != nil { + if _, err := client.RPC.Plugins.Uninstall(t.Context(), &rpc.PluginsUninstallRequest{ + DirectSourceID: install.Plugin.DirectSourceID, + Name: portedDirectPluginName, + }); err != nil { t.Fatalf("Plugins.Uninstall direct failed: %v", err) } afterUninstall, err := client.RPC.Plugins.List(t.Context()) @@ -234,6 +230,7 @@ func TestRpcServerPlugins(t *testing.T) { mine := findPortedMarketplace(list.Marketplaces, portedMarketplaceName) if mine == nil { t.Fatalf("Expected marketplace %q in list %+v", portedMarketplaceName, list.Marketplaces) + return } if mine.IsDefault != nil && *mine.IsDefault { t.Fatal("Expected local marketplace not to be marked default") @@ -316,7 +313,10 @@ func newStartedPortedClient(t *testing.T, ctx *testharness.TestContext, opts ... func newStartedIsolatedPortedClient(t *testing.T, ctx *testharness.TestContext) *copilot.Client { t.Helper() - home := t.TempDir() + home, err := os.MkdirTemp(ctx.WorkDir, "plugin-home-") + if err != nil { + t.Fatalf("Failed to create isolated plugin home: %v", err) + } return newStartedPortedClient(t, ctx, func(opts *copilot.ClientOptions) { opts.Env = append(opts.Env, "COPILOT_HOME="+home, diff --git a/go/internal/e2e/rpc_session_state_e2e_test.go b/go/internal/e2e/rpc_session_state_e2e_test.go index 9b28471ba3..07ec4138d6 100644 --- a/go/internal/e2e/rpc_session_state_e2e_test.go +++ b/go/internal/e2e/rpc_session_state_e2e_test.go @@ -704,7 +704,7 @@ func TestRPCSessionStateE2E(t *testing.T) { api := ctx.ProxyURL telemetry := "https://localhost:1/telemetry" - setCredentials, err := session.RPC.Auth.SetCredentials(t.Context(), &rpc.SessionSetCredentialsParams{ + setCredentials, err := session.RPC.GitHubAuth.SetCredentials(t.Context(), &rpc.SessionSetCredentialsParams{ Credentials: &rpc.UserAuthInfo{ CopilotUser: &rpc.CopilotUserResponse{ AnalyticsTrackingID: rpcPtr("rpc-session-state-tracking-id"), @@ -727,7 +727,7 @@ func TestRPCSessionStateE2E(t *testing.T) { t.Fatalf("Expected Auth.SetCredentials Success=true, got %+v", setCredentials) } - status, err := session.RPC.Auth.GetStatus(t.Context()) + status, err := session.RPC.GitHubAuth.GetStatus(t.Context()) if err != nil { t.Fatalf("Auth.GetStatus failed: %v", err) } diff --git a/go/internal/e2e/rpc_session_state_extras_e2e_test.go b/go/internal/e2e/rpc_session_state_extras_e2e_test.go index f4de1c1867..1e33e8a8bc 100644 --- a/go/internal/e2e/rpc_session_state_extras_e2e_test.go +++ b/go/internal/e2e/rpc_session_state_extras_e2e_test.go @@ -70,7 +70,7 @@ func TestRpcSessionStateExtras(t *testing.T) { session := createPortedSession(t, client, nil) defer session.Disconnect() defer func() { - _, _ = session.RPC.Permissions.SetAllowAll(t.Context(), &rpc.PermissionsSetAllowAllRequest{Enabled: false}) + _, _ = session.RPC.Permissions.SetAllowAll(t.Context(), &rpc.PermissionsSetAllowAllRequest{Enabled: copilot.Bool(false)}) }() initial, err := session.RPC.Permissions.GetAllowAll(t.Context()) @@ -81,7 +81,7 @@ func TestRpcSessionStateExtras(t *testing.T) { t.Fatal("Allow-all should be disabled on a fresh session") } - enable, err := session.RPC.Permissions.SetAllowAll(t.Context(), &rpc.PermissionsSetAllowAllRequest{Enabled: true}) + enable, err := session.RPC.Permissions.SetAllowAll(t.Context(), &rpc.PermissionsSetAllowAllRequest{Enabled: copilot.Bool(true)}) if err != nil { t.Fatalf("Permissions.SetAllowAll(true) failed: %v", err) } @@ -96,7 +96,7 @@ func TestRpcSessionStateExtras(t *testing.T) { t.Fatal("Expected allow-all to be enabled") } - disable, err := session.RPC.Permissions.SetAllowAll(t.Context(), &rpc.PermissionsSetAllowAllRequest{Enabled: false}) + disable, err := session.RPC.Permissions.SetAllowAll(t.Context(), &rpc.PermissionsSetAllowAllRequest{Enabled: copilot.Bool(false)}) if err != nil { t.Fatalf("Permissions.SetAllowAll(false) failed: %v", err) } @@ -176,6 +176,157 @@ func TestRpcSessionStateExtras(t *testing.T) { } }) + t.Run("should_add_byok_provider_and_model_at_runtime", func(t *testing.T) { + ctx.ConfigureForTest(t) + session := createPortedSession(t, client, nil) + defer session.Disconnect() + + apiKey := "provider-key" + providerType := rpc.ProviderConfigTypeOpenai + wireAPI := rpc.ProviderConfigWireAPICompletions + modelName := "Go Added Model" + maxPromptTokens := float64(4096) + result, err := session.RPC.Provider.Add(t.Context(), &rpc.ProviderAddRequest{ + Providers: []rpc.NamedProviderConfig{{ + Name: "go-e2e-provider", + Type: &providerType, + BaseURL: "https://models.example.test/v1", + APIKey: &apiKey, + Headers: map[string]string{"x-provider": "go"}, + WireAPI: &wireAPI, + }}, + Models: []rpc.ProviderModelConfig{{ + ID: "small", + Provider: "go-e2e-provider", + Name: &modelName, + MaxPromptTokens: &maxPromptTokens, + }}, + }) + if err != nil { + t.Fatalf("Provider.Add failed: %v", err) + } + if len(result.Models) != 1 { + t.Fatalf("Expected one added provider model, got %+v", result.Models) + } + + selectionID := "go-e2e-provider/small" + if _, err := session.RPC.Model.SwitchTo(t.Context(), &rpc.ModelSwitchToRequest{ModelID: selectionID}); err != nil { + t.Fatalf("Model.SwitchTo added model failed: %v", err) + } + current, err := session.RPC.Model.GetCurrent(t.Context()) + if err != nil { + t.Fatalf("Model.GetCurrent after provider add failed: %v", err) + } + if current.ModelID == nil || *current.ModelID != selectionID { + t.Fatalf("Expected current model %q, got %+v", selectionID, current) + } + }) + + t.Run("should_return_empty_completions_when_host_does_not_provide_them", func(t *testing.T) { + ctx.ConfigureForTest(t) + session := createPortedSession(t, client, nil) + defer session.Disconnect() + + result, err := session.RPC.Completions.Request(t.Context(), &rpc.CompletionsRequestRequest{ + Text: "Use @ to mention context", + Offset: 5, + }) + if err != nil { + t.Fatalf("Completions.Request failed: %v", err) + } + if result.Items == nil { + t.Fatal("Expected non-nil completion items list") + } + }) + + t.Run("should_report_visibility_as_unsynced_for_local_session", func(t *testing.T) { + ctx.ConfigureForTest(t) + session := createPortedSession(t, client, nil) + defer session.Disconnect() + + status := rpc.SessionVisibilityStatusUnshared + set, err := session.RPC.Visibility.Set(t.Context(), &rpc.VisibilitySetRequest{Status: status}) + if err != nil { + t.Fatalf("Visibility.Set failed: %v", err) + } + if set.Synced || set.Status != nil || set.ShareURL != nil { + t.Fatalf("Expected unsynced visibility set result, got %+v", set) + } + get, err := session.RPC.Visibility.Get(t.Context()) + if err != nil { + t.Fatalf("Visibility.Get failed: %v", err) + } + if get.Synced || get.Status != nil || get.ShareURL != nil { + t.Fatalf("Expected unsynced visibility get result, got %+v", get) + } + }) + + t.Run("should_get_context_attribution_and_heaviest_messages_after_turn", func(t *testing.T) { + ctx.ConfigureForTest(t) + session := createPortedSession(t, client, nil) + defer session.Disconnect() + + answer, err := session.SendAndWait(t.Context(), copilot.MessageOptions{Prompt: "Say CONTEXT_METADATA_OK exactly."}) + if err != nil { + t.Fatalf("SendAndWait failed: %v", err) + } + if answer == nil { + t.Fatal("Expected final assistant message") + } + + attribution, err := session.RPC.Metadata.GetContextAttribution(t.Context()) + if err != nil { + t.Fatalf("Metadata.GetContextAttribution failed: %v", err) + } + if attribution == nil { + t.Fatal("Expected attribution result") + } + limit := int64(5) + heaviest, err := session.RPC.Metadata.GetContextHeaviestMessages(t.Context(), &rpc.MetadataContextHeaviestMessagesRequest{Limit: &limit}) + if err != nil { + t.Fatalf("Metadata.GetContextHeaviestMessages failed: %v", err) + } + if heaviest.Messages == nil { + t.Fatal("Expected non-nil heaviest messages list") + } + }) + + t.Run("should_update_and_clear_live_subagent_settings", func(t *testing.T) { + ctx.ConfigureForTest(t) + session := createPortedSession(t, client, nil) + defer session.Disconnect() + + contextTier := rpc.SubagentSettingsEntryContextTierLongContext + model := "gpt-5-mini" + reasoningEffort := "low" + update, err := session.RPC.Tools.UpdateSubagentSettings(t.Context(), &rpc.UpdateSubagentSettingsRequest{ + Subagents: &rpc.SubagentSettings{ + DisabledSubagents: []string{"legacy-agent"}, + Agents: map[string]rpc.SubagentSettingsEntry{ + "general-purpose": { + ContextTier: &contextTier, + Model: &model, + EffortLevel: &reasoningEffort, + }, + }, + }, + }) + if err != nil { + t.Fatalf("Tools.UpdateSubagentSettings failed: %v", err) + } + if update == nil { + t.Fatal("Expected update result") + } + + clear, err := session.RPC.Tools.UpdateSubagentSettings(t.Context(), &rpc.UpdateSubagentSettingsRequest{}) + if err != nil { + t.Fatalf("Tools.UpdateSubagentSettings clear failed: %v", err) + } + if clear == nil { + t.Fatal("Expected clear result") + } + }) + t.Run("should_reload_session_plugins", func(t *testing.T) { ctx.ConfigureForTest(t) session := createPortedSession(t, client, nil) diff --git a/go/internal/e2e/rpc_tasks_and_handlers_e2e_test.go b/go/internal/e2e/rpc_tasks_and_handlers_e2e_test.go index 60ae3f1fd3..0267f8d042 100644 --- a/go/internal/e2e/rpc_tasks_and_handlers_e2e_test.go +++ b/go/internal/e2e/rpc_tasks_and_handlers_e2e_test.go @@ -302,6 +302,39 @@ func TestRPCTasksAndHandlersE2E(t *testing.T) { if locationApproval.Success { t.Error("Expected Success=false for missing location approval request id") } + + sessionLimits, err := session.RPC.UI.HandlePendingSessionLimitsExhausted(t.Context(), &rpc.UIHandlePendingSessionLimitsExhaustedRequest{ + RequestID: "missing-session-limits-request", + Response: rpc.UISessionLimitsExhaustedResponse{Action: rpc.UISessionLimitsExhaustedResponseActionCancel}, + }) + if err != nil { + t.Fatalf("UI.HandlePendingSessionLimitsExhausted failed: %v", err) + } + if sessionLimits.Success { + t.Error("Expected Success=false for missing session limits request id") + } + + headers, err := session.RPC.MCP.Headers().HandlePendingHeadersRefreshRequest(t.Context(), &rpc.MCPHeadersHandlePendingHeadersRefreshRequestRequest{ + RequestID: "missing-headers-refresh-request", + Result: rpc.MCPHeadersHandlePendingHeadersRefreshRequestHeaders{Headers: map[string]string{"authorization": "Bearer refreshed"}}, + }) + if err != nil { + t.Fatalf("MCP.Headers.HandlePendingHeadersRefreshRequest failed: %v", err) + } + if headers.Success { + t.Error("Expected Success=false for missing MCP headers refresh request id") + } + + noHeaders, err := session.RPC.MCP.Headers().HandlePendingHeadersRefreshRequest(t.Context(), &rpc.MCPHeadersHandlePendingHeadersRefreshRequestRequest{ + RequestID: "missing-headers-refresh-none-request", + Result: rpc.MCPHeadersHandlePendingHeadersRefreshRequestNone{}, + }) + if err != nil { + t.Fatalf("MCP.Headers.HandlePendingHeadersRefreshRequest none failed: %v", err) + } + if noHeaders.Success { + t.Error("Expected Success=false for missing MCP headers refresh none request id") + } }) t.Run("should round trip rpc elicitation through config handler", func(t *testing.T) { diff --git a/go/internal/e2e/rpc_ui_ephemeral_query_e2e_test.go b/go/internal/e2e/rpc_ui_ephemeral_query_e2e_test.go index c6e4033609..2669faea9a 100644 --- a/go/internal/e2e/rpc_ui_ephemeral_query_e2e_test.go +++ b/go/internal/e2e/rpc_ui_ephemeral_query_e2e_test.go @@ -26,6 +26,7 @@ func TestRpcUiEphemeralQuery(t *testing.T) { } if result == nil { t.Fatal("Expected non-nil ephemeral query result") + return } if strings.TrimSpace(result.Answer) == "" { t.Fatal("Expected non-empty ephemeral query answer") diff --git a/go/internal/e2e/rpc_workspace_checkpoints_e2e_test.go b/go/internal/e2e/rpc_workspace_checkpoints_e2e_test.go index 87c3c8da83..849e3a5fa6 100644 --- a/go/internal/e2e/rpc_workspace_checkpoints_e2e_test.go +++ b/go/internal/e2e/rpc_workspace_checkpoints_e2e_test.go @@ -33,6 +33,11 @@ func TestRPCWorkspaceCheckpointsE2E(t *testing.T) { }) t.Run("should return nil or empty content for unknown checkpoint", func(t *testing.T) { + // In-process, session.workspaces.readCheckpoint is answered by the native + // runtime, which decodes the checkpoint number as a u32 and rejects the + // large sentinel this test uses. Covered by the default (stdio) transport. + // Mirrors Rust's should_return_null_or_empty_content_for_unknown_checkpoint. + testharness.SkipIfInProcess(t, "readCheckpoint decodes the id as u32 in-process") session := createWorkspaceRPCSession(t, client) defer session.Disconnect() diff --git a/go/internal/e2e/session_config_e2e_test.go b/go/internal/e2e/session_config_e2e_test.go index e5daf931b9..672a905dc0 100644 --- a/go/internal/e2e/session_config_e2e_test.go +++ b/go/internal/e2e/session_config_e2e_test.go @@ -12,6 +12,7 @@ import ( copilot "github.com/github/copilot-sdk/go" "github.com/github/copilot-sdk/go/internal/e2e/testharness" + "github.com/github/copilot-sdk/go/rpc" ) // hasImageURLContent returns true if any user message in the given exchanges @@ -36,6 +37,126 @@ func hasImageURLContent(exchanges []testharness.ParsedHttpExchange) bool { return false } +func sendAndGetNextExchange(t *testing.T, ctx *testharness.TestContext, session *copilot.Session, prompt string) testharness.ParsedHttpExchange { + t.Helper() + + existing, err := ctx.GetExchanges() + if err != nil { + t.Fatalf("GetExchanges failed: %v", err) + } + if _, err := session.SendAndWait(t.Context(), copilot.MessageOptions{Prompt: prompt}); err != nil { + t.Fatalf("SendAndWait failed: %v", err) + } + exchanges := ctx.WaitForExchanges(t, len(existing)+1) + return exchanges[len(existing)] +} + +func assertSessionLimitsStatus(t *testing.T, exchange testharness.ParsedHttpExchange, expectedRemaining string) { + t.Helper() + + for _, message := range exchange.Request.Messages { + if message.Role != "user" || !strings.Contains(message.Content, "") { + continue + } + if !strings.Contains(message.Content, "Remaining session limits: "+expectedRemaining+".") { + t.Fatalf("Expected session limits status to include remaining %q, got %q", expectedRemaining, message.Content) + } + if !strings.Contains(message.Content, "Be frugal; avoid optional exploration and unnecessary tool calls.") { + t.Fatalf("Expected frugality instruction in session limits status, got %q", message.Content) + } + return + } + t.Fatal("Expected session limits status message") +} + +func getTaskAgentTypes(t *testing.T, exchange testharness.ParsedHttpExchange) []string { + t.Helper() + + for _, tool := range exchange.Request.Tools { + if tool.Function.Name != "task" { + continue + } + var parameters struct { + Properties struct { + AgentType struct { + Enum []string `json:"enum"` + } `json:"agent_type"` + } `json:"properties"` + } + if err := json.Unmarshal(tool.Function.Parameters, ¶meters); err != nil { + t.Fatalf("Failed to unmarshal task tool parameters: %v", err) + } + return parameters.Properties.AgentType.Enum + } + t.Fatal("Expected task tool in request") + return nil +} + +func containsAgentType(values []string, needle string) bool { + for _, value := range values { + if value == needle { + return true + } + } + return false +} + +func createPDFAttachment() copilot.Attachment { + pdfText := "%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n" + data := base64.StdEncoding.EncodeToString([]byte(pdfText)) + displayName := "citation-source.pdf" + return copilot.AttachmentBlob{ + Data: &data, + DisplayName: &displayName, + MIMEType: "application/pdf", + } +} + +func createAnthropicProvider() *copilot.ProviderConfig { + return &copilot.ProviderConfig{ + Type: "anthropic", + BaseURL: "https://anthropic-citations.invalid/v1", + APIKey: "test-provider-key", + ModelID: "claude-sonnet-4.5", + WireModel: "claude-sonnet-4.5", + } +} + +func assertAnthropicDocumentCitationsEnabled(t *testing.T, requestBody string) { + t.Helper() + + var body struct { + Messages []struct { + Content []map[string]any `json:"content"` + } `json:"messages"` + } + if err := json.Unmarshal([]byte(requestBody), &body); err != nil { + t.Fatalf("Failed to unmarshal Anthropic request body: %v", err) + } + var documents []map[string]any + for _, message := range body.Messages { + for _, block := range message.Content { + if block["type"] == "document" { + documents = append(documents, block) + } + } + } + if len(documents) != 1 { + t.Fatalf("Expected one Anthropic document block, got %d in body %s", len(documents), requestBody) + } + if documents[0]["title"] != "citation-source.pdf" { + t.Fatalf("Expected document title citation-source.pdf, got %v", documents[0]["title"]) + } + citations, ok := documents[0]["citations"].(map[string]any) + if !ok || citations["enabled"] != true { + t.Fatalf("Expected document citations.enabled=true, got %#v", documents[0]["citations"]) + } +} + +func float64Ref(value float64) *float64 { + return &value +} + func TestSessionConfigE2E(t *testing.T) { ctx := testharness.NewTestContext(t) client := ctx.NewClient() @@ -165,6 +286,224 @@ func TestSessionConfigE2E(t *testing.T) { }) } +func TestSessionConfigNewOptionsE2E(t *testing.T) { + ctx := testharness.NewTestContext(t) + client := ctx.NewClient() + t.Cleanup(func() { client.ForceStop() }) + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Failed to start client: %v", err) + } + + t.Run("should apply session limits on create", func(t *testing.T) { + ctx.ConfigureForTest(t) + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + SessionLimits: &rpc.SessionLimitsConfig{MaxAiCredits: float64Ref(30)}, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + defer session.Disconnect() + + exchange := sendAndGetNextExchange(t, ctx, session, "Acknowledge the current session limits.") + assertSessionLimitsStatus(t, exchange, "30 AI credits") + }) + + t.Run("should apply session limits on resume", func(t *testing.T) { + ctx.ConfigureForTest(t) + + session1, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + defer session1.Disconnect() + + session2, err := client.ResumeSessionWithOptions(t.Context(), session1.SessionID, &copilot.ResumeSessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + SessionLimits: &rpc.SessionLimitsConfig{MaxAiCredits: float64Ref(30)}, + }) + if err != nil { + t.Fatalf("ResumeSessionWithOptions failed: %v", err) + } + defer session2.Disconnect() + + exchange := sendAndGetNextExchange(t, ctx, session2, "Acknowledge the current session limits.") + assertSessionLimitsStatus(t, exchange, "30 AI credits") + }) + + t.Run("should apply excluded built in agents on create", func(t *testing.T) { + ctx.ConfigureForTest(t) + + const excludedAgent = "explore" + const prompt = "What is 1+1?" + baseline, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + }) + if err != nil { + t.Fatalf("CreateSession baseline failed: %v", err) + } + baselineExchange := sendAndGetNextExchange(t, ctx, baseline, prompt) + if !containsAgentType(getTaskAgentTypes(t, baselineExchange), excludedAgent) { + t.Fatalf("Expected baseline task agents to include %q", excludedAgent) + } + _ = baseline.Disconnect() + + excluded, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + ExcludedBuiltInAgents: []string{excludedAgent}, + }) + if err != nil { + t.Fatalf("CreateSession excluded failed: %v", err) + } + defer excluded.Disconnect() + + excludedExchange := sendAndGetNextExchange(t, ctx, excluded, prompt) + agentTypes := getTaskAgentTypes(t, excludedExchange) + if len(agentTypes) == 0 { + t.Fatal("Expected task tool agent types") + } + if containsAgentType(agentTypes, excludedAgent) { + t.Fatalf("Expected excluded task agents not to include %q; got %v", excludedAgent, agentTypes) + } + }) + + t.Run("should apply excluded built in agents on resume", func(t *testing.T) { + ctx.ConfigureForTest(t) + + const excludedAgent = "explore" + session1, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + defer session1.Disconnect() + + session2, err := client.ResumeSessionWithOptions(t.Context(), session1.SessionID, &copilot.ResumeSessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + ExcludedBuiltInAgents: []string{excludedAgent}, + }) + if err != nil { + t.Fatalf("ResumeSessionWithOptions failed: %v", err) + } + defer session2.Disconnect() + + exchange := sendAndGetNextExchange(t, ctx, session2, "What is 1+1?") + agentTypes := getTaskAgentTypes(t, exchange) + if len(agentTypes) == 0 { + t.Fatal("Expected task tool agent types") + } + if containsAgentType(agentTypes, excludedAgent) { + t.Fatalf("Expected excluded task agents not to include %q; got %v", excludedAgent, agentTypes) + } + }) +} + +func TestSessionConfigNewOptionsCopilotRequestE2E(t *testing.T) { + testharness.SkipIfInProcess(t, "an LLM inference provider is process-global in-process") + t.Run("should enable citations for Anthropic file attachments on create", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + transport := &recordingTransport{} + handler := &copilot.CopilotRequestHandler{Transport: transport} + client := newCopilotRequestClient(ctx, handler) + t.Cleanup(func() { client.ForceStop() }) + + if err := client.Start(t.Context()); err != nil { + t.Fatalf("Failed to start client: %v", err) + } + + session, err := client.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + Model: "claude-sonnet-4.5", + EnableCitations: copilot.Bool(true), + Provider: createAnthropicProvider(), + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + defer session.Disconnect() + + _, err = session.SendAndWait(t.Context(), copilot.MessageOptions{ + Prompt: "Summarize the attached PDF with citations enabled.", + Attachments: []copilot.Attachment{createPDFAttachment()}, + }) + if err != nil { + t.Fatalf("SendAndWait failed: %v", err) + } + + inference := transport.inferenceRecords() + if len(inference) != 1 { + t.Fatalf("Expected exactly one intercepted inference request, got %d", len(inference)) + } + assertAnthropicDocumentCitationsEnabled(t, inference[0].body) + }) + + t.Run("should enable citations for Anthropic file attachments on resume", func(t *testing.T) { + ctx := testharness.NewTestContext(t) + transport := &recordingTransport{} + handler := &copilot.CopilotRequestHandler{Transport: transport} + const connectionToken = "go-citation-resume-token" + server := ctx.NewClient(func(o *copilot.ClientOptions) { + o.Connection = copilot.TCPConnection{Path: ctx.CLIPath, ConnectionToken: connectionToken} + o.RequestHandler = handler + }) + t.Cleanup(func() { server.ForceStop() }) + + if err := server.Start(t.Context()); err != nil { + t.Fatalf("Failed to start server client: %v", err) + } + + session1, err := server.CreateSession(t.Context(), &copilot.SessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + }) + if err != nil { + t.Fatalf("CreateSession failed: %v", err) + } + defer session1.Disconnect() + + runtimePort := server.RuntimePort() + if runtimePort == 0 { + t.Fatal("Expected non-zero runtime port") + } + resumeClient := ctx.NewClient(func(o *copilot.ClientOptions) { + o.Connection = copilot.URIConnection{ + URL: fmt.Sprintf("localhost:%d", runtimePort), + ConnectionToken: connectionToken, + } + }) + t.Cleanup(func() { resumeClient.ForceStop() }) + + session2, err := resumeClient.ResumeSessionWithOptions(t.Context(), session1.SessionID, &copilot.ResumeSessionConfig{ + OnPermissionRequest: copilot.PermissionHandler.ApproveAll, + Model: "claude-sonnet-4.5", + EnableCitations: copilot.Bool(true), + Provider: createAnthropicProvider(), + }) + if err != nil { + t.Fatalf("ResumeSessionWithOptions failed: %v", err) + } + defer session2.Disconnect() + + _, err = session2.SendAndWait(t.Context(), copilot.MessageOptions{ + Prompt: "Summarize the attached PDF with citations enabled.", + Attachments: []copilot.Attachment{createPDFAttachment()}, + }) + if err != nil { + t.Fatalf("SendAndWait failed: %v", err) + } + + inference := transport.inferenceRecords() + if len(inference) != 1 { + t.Fatalf("Expected exactly one intercepted inference request, got %d", len(inference)) + } + assertAnthropicDocumentCitationsEnabled(t, inference[0].body) + }) +} + // TestSessionConfigExtras mirrors the additional Should_* tests in dotnet/test/SessionConfigTests.cs: // // Should_Use_Custom_SessionId diff --git a/go/internal/e2e/subagent_hooks_e2e_test.go b/go/internal/e2e/subagent_hooks_e2e_test.go index c632b1e606..0e2fde9f86 100644 --- a/go/internal/e2e/subagent_hooks_e2e_test.go +++ b/go/internal/e2e/subagent_hooks_e2e_test.go @@ -1,6 +1,7 @@ package e2e import ( + "net/http" "os" "path/filepath" "sync" @@ -10,10 +11,78 @@ import ( "github.com/github/copilot-sdk/go/internal/e2e/testharness" ) +type subagentRequestRecord struct { + agentID string + parentAgentID string + interactionType string +} + +type recordingForwardingTransport struct { + inner http.RoundTripper + mu sync.Mutex + records []subagentRequestRecord +} + +func newRecordingForwardingTransport() *recordingForwardingTransport { + inner := http.DefaultTransport.(*http.Transport).Clone() + inner.DisableCompression = true + return &recordingForwardingTransport{inner: inner} +} + +func (rt *recordingForwardingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if isInferenceURL(req.URL.String()) { + rctx := copilot.RequestContextFrom(req) + record := subagentRequestRecord{} + if rctx != nil { + record.agentID = rctx.AgentID + record.parentAgentID = rctx.ParentAgentID + record.interactionType = rctx.InteractionType + } + rt.mu.Lock() + rt.records = append(rt.records, record) + rt.mu.Unlock() + } + return rt.inner.RoundTrip(req) +} + +func (rt *recordingForwardingTransport) inferenceRecords() []subagentRequestRecord { + rt.mu.Lock() + defer rt.mu.Unlock() + out := make([]subagentRequestRecord, len(rt.records)) + copy(out, rt.records) + return out +} + +func assertSubagentRequestMetadata(t *testing.T, records []subagentRequestRecord) { + t.Helper() + if len(records) == 0 { + t.Fatal("request handler should observe inference requests") + } + for _, r := range records { + if r.parentAgentID == "" { + continue + } + if r.agentID == "" { + t.Fatal("sub-agent inference request should carry an agent id") + } + if r.interactionType == "" { + t.Fatal("sub-agent inference request should carry an interaction type") + } + if r.parentAgentID == r.agentID { + t.Fatal("sub-agent inference request should have distinct parent and child agent ids") + } + return + } + t.Fatal("sub-agent inference request should carry a parent agent id") +} + func TestSubagentHooksE2E(t *testing.T) { + testharness.SkipIfInProcess(t, "an LLM inference provider is process-global in-process") ctx := testharness.NewTestContext(t) + transport := newRecordingForwardingTransport() client := ctx.NewClient(func(o *copilot.ClientOptions) { o.Env = append(o.Env, "COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS=true") + o.RequestHandler = &copilot.CopilotRequestHandler{Transport: transport} }) t.Cleanup(func() { client.ForceStop() }) @@ -100,5 +169,6 @@ func TestSubagentHooksE2E(t *testing.T) { if viewPre[0].sessionID == taskPre.sessionID { t.Error("Sub-agent tool hooks should have a different sessionId than parent tool hooks") } + assertSubagentRequestMetadata(t, transport.inferenceRecords()) }) } diff --git a/go/internal/e2e/system_message_sections_e2e_test.go b/go/internal/e2e/system_message_sections_e2e_test.go index 61493c8122..c1eb313a25 100644 --- a/go/internal/e2e/system_message_sections_e2e_test.go +++ b/go/internal/e2e/system_message_sections_e2e_test.go @@ -43,6 +43,7 @@ func TestSystemMessageSectionsE2E(t *testing.T) { } if response == nil { t.Fatal("Expected a response from the assistant") + return } ad, ok := response.Data.(*copilot.AssistantMessageData) @@ -82,6 +83,7 @@ func TestSystemMessageSectionsE2E(t *testing.T) { } if response == nil { t.Fatal("Expected a response from the assistant") + return } ad, ok := response.Data.(*copilot.AssistantMessageData) diff --git a/go/internal/e2e/telemetry_e2e_test.go b/go/internal/e2e/telemetry_e2e_test.go index eff384d020..4567817fd9 100644 --- a/go/internal/e2e/telemetry_e2e_test.go +++ b/go/internal/e2e/telemetry_e2e_test.go @@ -14,6 +14,7 @@ import ( // Mirrors dotnet/test/TelemetryExportTests.cs (snapshot category "telemetry"). func TestTelemetryE2E(t *testing.T) { + testharness.SkipIfInProcess(t, "telemetry configuration is not honored in-process") t.Run("should export file telemetry for sdk interactions", func(t *testing.T) { ctx := testharness.NewTestContext(t) ctx.ConfigureForTest(t) diff --git a/go/internal/e2e/testharness/context.go b/go/internal/e2e/testharness/context.go index adceb9a746..b73153dfff 100644 --- a/go/internal/e2e/testharness/context.go +++ b/go/internal/e2e/testharness/context.go @@ -33,13 +33,11 @@ func CLIPath() string { // 1.0.64-1 the @github/copilot package is a thin loader; the runnable // index.js ships in the installed platform package // (e.g. @github/copilot-linux-x64). - base, err := filepath.Abs("../../../nodejs/node_modules/@github") - if err == nil { - matches, _ := filepath.Glob(filepath.Join(base, "copilot-*", "index.js")) - if len(matches) > 0 { - cliPath = matches[0] - return - } + base := RepoPath("nodejs", "node_modules", "@github") + matches, _ := filepath.Glob(filepath.Join(base, "copilot-*", "index.js")) + if len(matches) > 0 { + cliPath = matches[0] + return } }) return cliPath @@ -53,6 +51,67 @@ type TestContext struct { ProxyURL string proxy *CapiProxy + + // In-process transport state. When the inprocess CI matrix cell is active the + // worker inherits this process's ambient env and cwd (per-client env/working + // directory are rejected in-process), so the isolated test env/cwd are mirrored + // onto the real process and restored on Close. + inProcess bool + restoreEnv []envRestore + restoreCwd string +} + +// envRestore captures a single environment variable's prior value so the +// in-process ambient mirror can be undone during teardown. +type envRestore struct { + key string + prev string + had bool +} + +// isInProcessTransport reports whether the in-process (FFI) transport is selected +// for E2E tests via COPILOT_SDK_DEFAULT_CONNECTION=inprocess. Mirrors the +// Node/Python/.NET harnesses. +func isInProcessTransport() bool { + return strings.EqualFold(os.Getenv("COPILOT_SDK_DEFAULT_CONNECTION"), "inprocess") +} + +// init neutralizes any ambient HMAC signing key as early as package load when the +// in-process transport is selected. Host-side auth resolution ranks the HMAC key +// above the GitHub token, so an ambient COPILOT_HMAC_KEY (CI injects one as a +// job-level credential) would be picked over the token the replay snapshots +// expect, producing request signatures that miss the recorded exchanges. Because +// the runtime is hosted in this process, the key must be removed before the native +// library is loaded and captures it — a later, per-client override is too late and +// setting it to an empty value is still treated as a signing key. Out-of-process +// children resolve auth in their own process where the token already outranks the +// HMAC key, so this is scoped to the in-process cell. Mirrors the analogous +// module-load neutralization in the Node/Python/.NET harnesses. +// See https://github.com/github/copilot-sdk/issues/1934. +func init() { + if isInProcessTransport() { + os.Unsetenv("COPILOT_HMAC_KEY") + os.Unsetenv("CAPI_HMAC_KEY") + } +} + +// IsInProcessTransport reports whether E2E tests run under the in-process (FFI) +// transport. Tests that configure options unsupported in-process (e.g. per-client +// telemetry) should skip when this returns true. +func IsInProcessTransport() bool { + return isInProcessTransport() +} + +// SkipIfInProcess skips the test when E2E tests run under the in-process (FFI) +// transport, for behavior the shared in-process runtime cannot support (e.g. a +// process-global LLM inference provider, or per-client telemetry). The reason is +// surfaced in the test log so the skip is explicit rather than a silent transport +// downgrade. Such tests still run over stdio in the default matrix cell. +func SkipIfInProcess(t *testing.T, reason string) { + t.Helper() + if isInProcessTransport() { + t.Skipf("unsupported over the in-process (FFI) transport: %s", reason) + } } // NewTestContext creates a new test context with isolated directories and a replaying proxy. @@ -106,11 +165,12 @@ func NewTestContext(t *testing.T) *TestContext { } ctx := &TestContext{ - CLIPath: cliPath, - HomeDir: homeDir, - WorkDir: workDir, - ProxyURL: proxyURL, - proxy: proxy, + CLIPath: cliPath, + HomeDir: homeDir, + WorkDir: workDir, + ProxyURL: proxyURL, + proxy: proxy, + inProcess: isInProcessTransport(), } t.Cleanup(func() { @@ -146,7 +206,14 @@ func (c *TestContext) ConfigureForTest(t *testing.T) { t.Fatalf("Expected test name with subtest, got: %s", testName) } sanitizedName := strings.ToLower(regexp.MustCompile(`[^a-zA-Z0-9]`).ReplaceAllString(parts[1], "_")) - snapshotPath := filepath.Join("..", "..", "..", "test", "snapshots", testFile, sanitizedName+".yaml") + // Anchor the snapshot path to the caller's source directory rather than the + // process working directory: the in-process transport chdir's into the test's + // isolated work dir (the worker inherits the process cwd), so a cwd-relative + // path would resolve against the wrong root for every subtest after the first. + // All e2e test files live in go/internal/e2e, so the repo root is three levels + // up from the caller's directory. + repoRoot := filepath.Join(filepath.Dir(callerFile), "..", "..", "..") + snapshotPath := filepath.Join(repoRoot, "test", "snapshots", testFile, sanitizedName+".yaml") absSnapshotPath, err := filepath.Abs(snapshotPath) if err != nil { @@ -158,8 +225,21 @@ func (c *TestContext) ConfigureForTest(t *testing.T) { } } +// ConfigureWithoutSnapshot initializes the replay proxy without loading a recorded CAPI +// exchange file. Use this for tests that serve all model-layer behavior locally but +// still need proxy-backed auth and GitHub API endpoints. +func (c *TestContext) ConfigureWithoutSnapshot(t *testing.T) { + t.Helper() + + dummySnapshotPath := filepath.Join(c.WorkDir, "__no_snapshot__.yaml") + if err := c.proxy.Configure(dummySnapshotPath, c.WorkDir); err != nil { + t.Fatalf("Failed to configure proxy without snapshot: %v", err) + } +} + // Close cleans up the test context resources. func (c *TestContext) Close(testFailed bool) { + c.restoreInProcessEnvironment() if c.proxy != nil { c.proxy.StopWithOptions(testFailed) } @@ -171,6 +251,62 @@ func (c *TestContext) Close(testFailed bool) { } } +// applyInProcessEnvironment mirrors the isolated test environment onto the real +// process for in-process hosting: the worker inherits this process's env and cwd +// at spawn, so per-test redirects must live on os.Environ and the process cwd. +// Auth flows via GH_TOKEN/GITHUB_TOKEN (the FFI argv omits the stdio auth-token +// wiring); the ambient HMAC signing key is removed process-wide at package load +// (see init) so host-side auth matches the replay snapshots. mergedEnv is the +// effective per-client env (harness defaults plus any per-test additions); workDir +// is the effective working directory. Values are restored in Close. Safe to call +// more than once (restores unwind in reverse). +func (c *TestContext) applyInProcessEnvironment(mergedEnv []string, workDir string) { + inprocessEnv := map[string]string{} + for _, kv := range mergedEnv { + if key, value, ok := strings.Cut(kv, "="); ok { + inprocessEnv[key] = value + } + } + // Auth flows via GH_TOKEN/GITHUB_TOKEN for the in-process host, overriding any + // inherited values. The HMAC key is neutralized process-wide at package load. + inprocessEnv["GH_TOKEN"] = defaultGitHubToken + inprocessEnv["GITHUB_TOKEN"] = defaultGitHubToken + inprocessEnv["COPILOT_CLI_PATH"] = c.CLIPath + delete(inprocessEnv, "COPILOT_HMAC_KEY") + delete(inprocessEnv, "CAPI_HMAC_KEY") + + for key, value := range inprocessEnv { + prev, had := os.LookupEnv(key) + c.restoreEnv = append(c.restoreEnv, envRestore{key: key, prev: prev, had: had}) + os.Setenv(key, value) + } + if workDir != "" { + if c.restoreCwd == "" { + if cwd, err := os.Getwd(); err == nil { + c.restoreCwd = cwd + } + } + os.Chdir(workDir) + } +} + +// restoreInProcessEnvironment undoes applyInProcessEnvironment during teardown. +func (c *TestContext) restoreInProcessEnvironment() { + for i := len(c.restoreEnv) - 1; i >= 0; i-- { + r := c.restoreEnv[i] + if r.had { + os.Setenv(r.key, r.prev) + } else { + os.Unsetenv(r.key) + } + } + c.restoreEnv = nil + if c.restoreCwd != "" { + os.Chdir(c.restoreCwd) + c.restoreCwd = "" + } +} + // GetExchanges retrieves the captured HTTP exchanges from the proxy. func (c *TestContext) GetExchanges() ([]ParsedHttpExchange, error) { return c.proxy.GetExchanges() @@ -223,6 +359,8 @@ func (c *TestContext) Env() []string { "GH_CONFIG_DIR="+c.HomeDir, "GH_TOKEN="+defaultGitHubToken, "GITHUB_TOKEN="+defaultGitHubToken, + "COPILOT_MCP_APPS=true", + "MCP_APPS=true", "XDG_CONFIG_HOME="+c.HomeDir, "XDG_STATE_HOME="+c.HomeDir, ) @@ -247,9 +385,39 @@ func (c *TestContext) NewClient(opts ...func(*copilot.ClientOptions)) *copilot.C options.GitHubToken = defaultGitHubToken } + // Under the inprocess matrix cell, host the default stdio connection in-process. + // The worker inherits this process's ambient env/cwd (per-client env and working + // directory are rejected in-process), so mirror the effective (merged) env and + // cwd onto the real process and drop those options. Tests that pin a specific + // transport (TCP/URI/custom stdio) or configure per-client telemetry are left on + // their transport, mirroring the Node/.NET harnesses. + if c.inProcess && c.shouldUseInProcess(options) { + c.applyInProcessEnvironment(options.Env, options.WorkingDirectory) + options.Connection = copilot.InProcessConnection{} + options.Env = nil + options.WorkingDirectory = "" + } + return copilot.NewClient(options) } +// shouldUseInProcess reports whether a client built from options should be hosted +// in-process for the inprocess matrix cell. Only the harness default stdio +// connection is swapped; a test that pins a custom stdio path/args/env or a +// TCP/URI connection is exercising behavior that must stay on its own transport. +// +// Options the in-process runtime cannot support (per-client telemetry, an LLM +// inference provider) are NOT silently downgraded here — the affected tests skip +// explicitly via testharness.SkipIfInProcess so the limitation is visible rather +// than masked by a quiet transport swap. +func (c *TestContext) shouldUseInProcess(options *copilot.ClientOptions) bool { + s, ok := options.Connection.(copilot.StdioConnection) + if !ok { + return false + } + return s.Path == c.CLIPath && len(s.Args) == 0 && s.Env == nil +} + func fileExists(path string) bool { _, err := os.Stat(path) return err == nil diff --git a/go/internal/e2e/testharness/helper.go b/go/internal/e2e/testharness/helper.go index ca94d03adf..af08b2dbcc 100644 --- a/go/internal/e2e/testharness/helper.go +++ b/go/internal/e2e/testharness/helper.go @@ -3,11 +3,32 @@ package testharness import ( "context" "errors" + "path/filepath" + "runtime" "time" copilot "github.com/github/copilot-sdk/go" ) +// RepoPath resolves a path relative to the repository root, anchored to this +// source file's directory rather than the process working directory. The +// in-process (FFI) transport os.Chdir's the whole test process into a per-test +// temp workdir (the shared runtime host inherits the process cwd), so any +// cwd-relative resolution (e.g. filepath.Abs("../../../test/...")) would break +// for every test after the first in-process one. This helper stays correct +// regardless of the current working directory. +func RepoPath(elem ...string) string { + _, callerFile, _, ok := runtime.Caller(0) + if !ok { + // Fall back to a cwd-relative join; only correct before any chdir. + return filepath.Join(append([]string{"..", "..", ".."}, elem...)...) + } + // This file lives at go/internal/e2e/testharness/, so the repo root is four + // levels up from its directory. + repoRoot := filepath.Join(filepath.Dir(callerFile), "..", "..", "..", "..") + return filepath.Join(append([]string{repoRoot}, elem...)...) +} + // GetFinalAssistantMessage waits for and returns the final assistant message from a session turn. // If alreadyIdle is true, skip waiting for session.idle (useful for resumed sessions where the // idle event was ephemeral and not persisted in the event history). diff --git a/go/internal/e2e/testharness/proxy.go b/go/internal/e2e/testharness/proxy.go index e407f13e06..ec16124bc6 100644 --- a/go/internal/e2e/testharness/proxy.go +++ b/go/internal/e2e/testharness/proxy.go @@ -38,11 +38,14 @@ func (p *CapiProxy) Start() (string, error) { return p.proxyURL, nil } - // The harness server is in the shared test directory - serverPath := "../../../test/harness/server.ts" + // The harness server is in the shared test directory. Anchor the path to + // the repo root (not the process cwd), because the in-process (FFI) + // transport os.Chdir's into a per-test temp workdir, which would otherwise + // break the cwd-relative resolution. + serverPath := RepoPath("test", "harness", "server.ts") p.cmd = exec.Command("npx", "tsx", serverPath) - p.cmd.Dir = "." // Will be resolved relative to test execution + p.cmd.Dir = RepoPath("test", "harness") stdout, err := p.cmd.StdoutPipe() if err != nil { @@ -256,8 +259,9 @@ type ChatCompletionTool struct { // ChatCompletionToolFunction represents a function tool. type ChatCompletionToolFunction struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + Parameters json.RawMessage `json:"parameters,omitempty"` } // ChatCompletionResponse represents an OpenAI chat completion response. diff --git a/go/internal/e2e/tools_e2e_test.go b/go/internal/e2e/tools_e2e_test.go index 1600eb1630..062d377917 100644 --- a/go/internal/e2e/tools_e2e_test.go +++ b/go/internal/e2e/tools_e2e_test.go @@ -140,6 +140,7 @@ func TestToolsE2E(t *testing.T) { if answer == nil { t.Fatalf("Expected non-nil assistant message") + return } ad, ok := answer.Data.(*copilot.AssistantMessageData) if !ok { diff --git a/go/internal/embeddedcli/embeddedcli.go b/go/internal/embeddedcli/embeddedcli.go index 0866a3f811..cd0be21895 100644 --- a/go/internal/embeddedcli/embeddedcli.go +++ b/go/internal/embeddedcli/embeddedcli.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "os/exec" "path/filepath" "runtime" "strings" @@ -18,15 +19,30 @@ import ( // Config defines the inputs used to install and locate the embedded Copilot CLI. // // Cli and CliHash are required. If Dir is empty, the CLI is installed into the -// system cache directory. Version is used to suffix the installed binary name to -// allow multiple versions to coexist. License, when provided, is written next -// to the installed binary. +// system cache directory. When Version is set, the CLI is installed into a +// version-specific child directory so multiple versions can coexist. License, +// when provided, is written next to the installed binary. +// +// RuntimeLib and RuntimeLibHash are optional: when set, the native in-process +// runtime library (cdylib) is installed next to the CLI binary so the in-process +// (FFI) transport can load it. They are omitted for CLI packages that do not +// ship the native runtime. type Config struct { Cli io.Reader CliHash []byte License []byte + RuntimeLib io.Reader + RuntimeLibHash []byte + + // LinuxMuslCli and LinuxMuslRuntimeLib are optional alternatives selected + // automatically when the application runs on a musl-based Linux system. + LinuxMuslCli io.Reader + LinuxMuslCliHash []byte + LinuxMuslRuntimeLib io.Reader + LinuxMuslRuntimeLibHash []byte + Dir string Version string } @@ -38,6 +54,12 @@ func Setup(cfg Config) { if len(cfg.CliHash) != sha256.Size { panic(fmt.Sprintf("CliHash must be a SHA-256 hash (%d bytes), got %d bytes", sha256.Size, len(cfg.CliHash))) } + if cfg.LinuxMuslCli != nil && len(cfg.LinuxMuslCliHash) != sha256.Size { + panic(fmt.Sprintf("LinuxMuslCliHash must be a SHA-256 hash (%d bytes), got %d bytes", sha256.Size, len(cfg.LinuxMuslCliHash))) + } + if cfg.LinuxMuslRuntimeLib != nil && len(cfg.LinuxMuslRuntimeLibHash) != sha256.Size { + panic(fmt.Sprintf("LinuxMuslRuntimeLibHash must be a SHA-256 hash (%d bytes), got %d bytes", sha256.Size, len(cfg.LinuxMuslRuntimeLibHash))) + } setupMu.Lock() defer setupMu.Unlock() if setupDone { @@ -61,14 +83,28 @@ var Path = sync.OnceValue(func() string { return path }) +// RuntimeLibPath returns the on-disk path to the installed native in-process +// runtime library (cdylib), or "" when no runtime library was bundled or the +// CLI could not be installed. It ensures the embedded CLI is installed first. +func RuntimeLibPath() string { + Path() + setupMu.Lock() + defer setupMu.Unlock() + return runtimeLibPath +} + var ( config Config setupMu sync.Mutex setupDone bool pathInitialized bool + runtimeLibPath string + linuxMuslBundle bool ) func install() (path string) { + selectLinuxMuslBundle() + verbose := os.Getenv("COPILOT_CLI_INSTALL_VERBOSE") == "1" logError := func(msg string, err error) { if verbose { @@ -103,18 +139,41 @@ func install() (path string) { return path } -func installAt(installDir string) (string, error) { - if err := os.MkdirAll(installDir, 0755); err != nil { - return "", fmt.Errorf("creating install directory: %w", err) +func selectLinuxMuslBundle() { + if runtime.GOOS != "linux" || config.LinuxMuslCli == nil || !isMusl() { + return } + config = linuxMuslConfig(config) + linuxMuslBundle = true +} + +func linuxMuslConfig(cfg Config) Config { + cfg.Cli = cfg.LinuxMuslCli + cfg.CliHash = cfg.LinuxMuslCliHash + cfg.RuntimeLib = cfg.LinuxMuslRuntimeLib + cfg.RuntimeLibHash = cfg.LinuxMuslRuntimeLibHash + return cfg +} + +func isMusl() bool { + out, _ := exec.Command("ldd", "--version").CombinedOutput() + return strings.Contains(strings.ToLower(string(out)), "musl") +} + +func installAt(installDir string) (string, error) { version := sanitizeVersion(config.Version) - lockName := ".copilot-cli.lock" if version != "" { - lockName = fmt.Sprintf(".copilot-cli-%s.lock", version) + installDir = filepath.Join(installDir, version) + } + if linuxMuslBundle { + installDir = filepath.Join(installDir, "linuxmusl") + } + if err := os.MkdirAll(installDir, 0755); err != nil { + return "", fmt.Errorf("creating install directory: %w", err) } // Best effort to prevent concurrent installs. - if release, _ := flock.Acquire(filepath.Join(installDir, lockName)); release != nil { + if release, _ := flock.Acquire(filepath.Join(installDir, ".copilot-cli.lock")); release != nil { defer release() } @@ -122,7 +181,7 @@ func installAt(installDir string) (string, error) { if runtime.GOOS == "windows" { binaryName += ".exe" } - finalPath := versionedBinaryPath(installDir, binaryName, version) + finalPath := filepath.Join(installDir, binaryName) if _, err := os.Stat(finalPath); err == nil { existingHash, err := hashFile(finalPath) @@ -132,6 +191,13 @@ func installAt(installDir string) (string, error) { if !bytes.Equal(existingHash, config.CliHash) { return "", fmt.Errorf("existing binary hash mismatch") } + if config.RuntimeLib != nil { + libPath, err := installRuntimeLib(installDir) + if err != nil { + return "", err + } + runtimeLibPath = libPath + } return finalPath, nil } @@ -155,17 +221,81 @@ func installAt(installDir string) (string, error) { return "", fmt.Errorf("writing license file: %w", err) } } + + // Install the native in-process runtime library (if bundled) next to the CLI. + // Fail closed on any hash mismatch; never place unverified native code. + if config.RuntimeLib != nil { + libPath, err := installRuntimeLib(installDir) + if err != nil { + return "", err + } + runtimeLibPath = libPath + } + return finalPath, nil } -// versionedBinaryPath builds the unpacked binary filename with an optional version suffix. -func versionedBinaryPath(dir, binaryName, version string) string { - if version == "" { - return filepath.Join(dir, binaryName) +// installRuntimeLib writes the embedded runtime cdylib into installDir under its +// natural platform file name, verifying its SHA-256. It is idempotent: an +// existing file with a matching hash is reused; a mismatch is a hard error. +func installRuntimeLib(installDir string) (string, error) { + if len(config.RuntimeLibHash) != sha256.Size { + return "", fmt.Errorf("RuntimeLibHash must be a SHA-256 hash (%d bytes), got %d bytes", sha256.Size, len(config.RuntimeLibHash)) + } + libPath := filepath.Join(installDir, naturalRuntimeLibName()) + + if _, err := os.Stat(libPath); err == nil { + existingHash, err := hashFile(libPath) + if err != nil { + return "", fmt.Errorf("hashing existing runtime library: %w", err) + } + if !bytes.Equal(existingHash, config.RuntimeLibHash) { + return "", fmt.Errorf("existing runtime library hash mismatch") + } + return libPath, nil + } + + // Write to a temp file in the same directory, verify, then atomically rename. + tmp, err := os.CreateTemp(installDir, ".copilot-runtime-*.tmp") + if err != nil { + return "", fmt.Errorf("creating temp runtime library: %w", err) + } + tmpPath := tmp.Name() + h := sha256.New() + _, err = io.Copy(io.MultiWriter(tmp, h), config.RuntimeLib) + if err1 := tmp.Close(); err1 != nil && err == nil { + err = err1 + } + if closer, ok := config.RuntimeLib.(io.Closer); ok { + closer.Close() + } + if err != nil { + os.Remove(tmpPath) + return "", fmt.Errorf("writing runtime library: %w", err) + } + if !bytes.Equal(h.Sum(nil), config.RuntimeLibHash) { + os.Remove(tmpPath) + return "", fmt.Errorf("runtime library hash mismatch") + } + if err := os.Rename(tmpPath, libPath); err != nil { + os.Remove(tmpPath) + return "", fmt.Errorf("installing runtime library: %w", err) + } + return libPath, nil +} + +// naturalRuntimeLibName is the flat platform file name for the runtime cdylib, +// matching ffihost.NaturalLibraryName (kept in sync; embeddedcli stays +// dependency-free for use by generated embed files). +func naturalRuntimeLibName() string { + switch runtime.GOOS { + case "windows": + return "copilot_runtime.dll" + case "darwin": + return "libcopilot_runtime.dylib" + default: + return "libcopilot_runtime.so" } - base := strings.TrimSuffix(binaryName, filepath.Ext(binaryName)) - ext := filepath.Ext(binaryName) - return filepath.Join(dir, fmt.Sprintf("%s_%s%s", base, version, ext)) } // sanitizeVersion makes a version string safe for filenames. @@ -188,7 +318,11 @@ func sanitizeVersion(version string) string { b.WriteRune('_') } } - return b.String() + sanitized := b.String() + if sanitized == "." || sanitized == ".." { + return strings.Repeat("_", len(sanitized)) + } + return sanitized } // hashFile returns the SHA-256 hash of a file on disk. diff --git a/go/internal/embeddedcli/embeddedcli_test.go b/go/internal/embeddedcli/embeddedcli_test.go index 0453f7293d..b0394e0f69 100644 --- a/go/internal/embeddedcli/embeddedcli_test.go +++ b/go/internal/embeddedcli/embeddedcli_test.go @@ -16,6 +16,8 @@ func resetGlobals() { config = Config{} setupDone = false pathInitialized = false + runtimeLibPath = "" + linuxMuslBundle = false } func mustPanic(t *testing.T, fn func()) { @@ -36,6 +38,31 @@ func binaryNameForOS() string { return name } +func TestLinuxMuslConfigSelectsAlternativeArtifacts(t *testing.T) { + glibcCLI := strings.NewReader("glibc-cli") + glibcRuntime := strings.NewReader("glibc-runtime") + muslCLI := strings.NewReader("musl-cli") + muslRuntime := strings.NewReader("musl-runtime") + muslCLIHash := bytes.Repeat([]byte{1}, sha256.Size) + muslRuntimeHash := bytes.Repeat([]byte{2}, sha256.Size) + + selected := linuxMuslConfig(Config{ + Cli: glibcCLI, + RuntimeLib: glibcRuntime, + LinuxMuslCli: muslCLI, + LinuxMuslCliHash: muslCLIHash, + LinuxMuslRuntimeLib: muslRuntime, + LinuxMuslRuntimeLibHash: muslRuntimeHash, + }) + + if selected.Cli != muslCLI || selected.RuntimeLib != muslRuntime { + t.Fatal("Expected Linux musl artifacts to replace the glibc artifacts") + } + if !bytes.Equal(selected.CliHash, muslCLIHash) || !bytes.Equal(selected.RuntimeLibHash, muslRuntimeHash) { + t.Fatal("Expected Linux musl hashes to replace the glibc hashes") + } +} + func TestSetupPanicsOnNilCli(t *testing.T) { resetGlobals() mustPanic(t, func() { Setup(Config{}) }) @@ -65,7 +92,7 @@ func TestInstallAtWritesBinaryAndLicense(t *testing.T) { path := Path() - expectedPath := versionedBinaryPath(tempDir, binaryNameForOS(), "1.2.3") + expectedPath := filepath.Join(tempDir, "1.2.3", binaryNameForOS()) if path != expectedPath { t.Fatalf("unexpected path: got %q want %q", path, expectedPath) } @@ -99,7 +126,7 @@ func TestInstallAtWritesBinaryAndLicense(t *testing.T) { func TestInstallAtExistingBinaryHashMismatch(t *testing.T) { resetGlobals() tempDir := t.TempDir() - binaryPath := versionedBinaryPath(tempDir, binaryNameForOS(), "") + binaryPath := filepath.Join(tempDir, binaryNameForOS()) if err := os.MkdirAll(filepath.Dir(binaryPath), 0755); err != nil { t.Fatalf("mkdir: %v", err) } @@ -120,17 +147,102 @@ func TestInstallAtExistingBinaryHashMismatch(t *testing.T) { } func TestSanitizeVersion(t *testing.T) { - got := sanitizeVersion("v1.2.3+build/abc") - want := "v1.2.3_build_abc" - if got != want { - t.Fatalf("sanitizeVersion() = %q want %q", got, want) + tests := map[string]string{ + "v1.2.3+build/abc": "v1.2.3_build_abc", + ".": "_", + "..": "__", + } + for input, want := range tests { + if got := sanitizeVersion(input); got != want { + t.Errorf("sanitizeVersion(%q) = %q want %q", input, got, want) + } } } -func TestVersionedBinaryPath(t *testing.T) { - got := versionedBinaryPath("/tmp", "copilot.exe", "1.0.0") - want := filepath.Join("/tmp", "copilot_1.0.0.exe") - if got != want { - t.Fatalf("versionedBinaryPath() = %q want %q", got, want) +func TestInstallAtAllowsMultipleRuntimeVersions(t *testing.T) { + resetGlobals() + tempDir := t.TempDir() + + installVersion := func(version string, cliContent, runtimeContent []byte) (string, string) { + t.Helper() + cliHash := sha256.Sum256(cliContent) + runtimeHash := sha256.Sum256(runtimeContent) + config = Config{ + Cli: bytes.NewReader(cliContent), + CliHash: cliHash[:], + RuntimeLib: bytes.NewReader(runtimeContent), + RuntimeLibHash: runtimeHash[:], + Version: version, + } + + cliPath, err := installAt(tempDir) + if err != nil { + t.Fatalf("install version %s: %v", version, err) + } + return cliPath, runtimeLibPath + } + + cli1, runtime1 := installVersion("1.0.0", []byte("cli-one"), []byte("runtime-one")) + cli2, runtime2 := installVersion("2.0.0", []byte("cli-two"), []byte("runtime-two")) + + if cli1 == cli2 { + t.Fatalf("Expected versioned CLI paths to differ, got %q", cli1) + } + if runtime1 == runtime2 { + t.Fatalf("Expected versioned runtime paths to differ, got %q", runtime1) + } + if got, want := filepath.Base(cli1), binaryNameForOS(); got != want { + t.Fatalf("First CLI filename = %q, want %q", got, want) + } + if got, want := filepath.Base(runtime1), naturalRuntimeLibName(); got != want { + t.Fatalf("First runtime filename = %q, want %q", got, want) + } + if got, want := filepath.Base(filepath.Dir(cli1)), "1.0.0"; got != want { + t.Fatalf("First CLI version directory = %q, want %q", got, want) + } + if filepath.Dir(cli1) != filepath.Dir(runtime1) { + t.Fatalf("CLI and runtime were installed in different directories: %q and %q", cli1, runtime1) + } + if got, err := os.ReadFile(runtime1); err != nil || string(got) != "runtime-one" { + t.Fatalf("Unexpected first runtime: content=%q err=%v", got, err) + } + if got, err := os.ReadFile(runtime2); err != nil || string(got) != "runtime-two" { + t.Fatalf("Unexpected second runtime: content=%q err=%v", got, err) + } +} + +func TestInstallAtExistingBinaryInstallsMissingRuntime(t *testing.T) { + resetGlobals() + tempDir := t.TempDir() + versionDir := filepath.Join(tempDir, "1.2.3") + if err := os.MkdirAll(versionDir, 0755); err != nil { + t.Fatalf("mkdir: %v", err) + } + + cliContent := []byte("cli") + cliPath := filepath.Join(versionDir, binaryNameForOS()) + if err := os.WriteFile(cliPath, cliContent, 0755); err != nil { + t.Fatalf("write CLI: %v", err) + } + cliHash := sha256.Sum256(cliContent) + runtimeContent := []byte("runtime") + runtimeHash := sha256.Sum256(runtimeContent) + config = Config{ + Cli: bytes.NewReader(cliContent), + CliHash: cliHash[:], + RuntimeLib: bytes.NewReader(runtimeContent), + RuntimeLibHash: runtimeHash[:], + Version: "1.2.3", + } + + gotCLIPath, err := installAt(tempDir) + if err != nil { + t.Fatalf("installAt(): %v", err) + } + if gotCLIPath != cliPath { + t.Fatalf("installAt() = %q, want %q", gotCLIPath, cliPath) + } + if got, err := os.ReadFile(filepath.Join(versionDir, naturalRuntimeLibName())); err != nil || string(got) != "runtime" { + t.Fatalf("Unexpected runtime: content=%q err=%v", got, err) } } diff --git a/go/internal/ffihost/buffer.go b/go/internal/ffihost/buffer.go new file mode 100644 index 0000000000..2185ce833d --- /dev/null +++ b/go/internal/ffihost/buffer.go @@ -0,0 +1,67 @@ +//go:build copilot_inprocess && (darwin || linux || windows) + +package ffihost + +import ( + "io" + "sync" +) + +// receiveBuffer is a thread-safe byte buffer that feeds blocking Read from a +// producer thread. The native outbound callback (invoked on a foreign runtime +// thread) appends frames via feed without ever blocking; the JSON-RPC reader +// goroutine drains them via Read, which blocks until data or EOF. +// +// It implements io.ReadCloser so it can be handed to jsonrpc2.NewClient as the +// server → client stream. +type receiveBuffer struct { + mu sync.Mutex + cond *sync.Cond + buf []byte + closed bool +} + +func newReceiveBuffer() *receiveBuffer { + rb := &receiveBuffer{} + rb.cond = sync.NewCond(&rb.mu) + return rb +} + +func (rb *receiveBuffer) feed(data []byte) { + rb.mu.Lock() + defer rb.mu.Unlock() + if rb.closed { + return + } + rb.buf = append(rb.buf, data...) + rb.cond.Broadcast() +} + +// Read blocks until at least one byte is available or the buffer is closed. +// It returns io.EOF only once the buffer is closed and fully drained. +func (rb *receiveBuffer) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + rb.mu.Lock() + defer rb.mu.Unlock() + for len(rb.buf) == 0 && !rb.closed { + rb.cond.Wait() + } + if len(rb.buf) == 0 { + return 0, io.EOF + } + n := copy(p, rb.buf) + rb.buf = rb.buf[n:] + return n, nil +} + +// Close marks the buffer closed; subsequent Reads drain remaining bytes then +// return io.EOF. Idempotent. +func (rb *receiveBuffer) Close() error { + rb.mu.Lock() + defer rb.mu.Unlock() + rb.closed = true + rb.cond.Broadcast() + return nil +} diff --git a/go/internal/ffihost/ffihost.go b/go/internal/ffihost/ffihost.go new file mode 100644 index 0000000000..30cd831281 --- /dev/null +++ b/go/internal/ffihost/ffihost.go @@ -0,0 +1,384 @@ +//go:build copilot_inprocess && (darwin || linux || windows) + +// Package ffihost hosts the Copilot runtime in-process by loading its native +// library and driving JSON-RPC over the runtime's C ABI. +// +// It pumps opaque LSP Content-Length-framed JSON-RPC bytes across the boundary: +// +// - client → server frames go to copilot_runtime_connection_write +// - server → client frames arrive on a native callback that feeds a +// thread-safe receive buffer read by the JSON-RPC client +// +// The existing internal/jsonrpc2 client handles framing unchanged — this is a +// transport swap, not a new protocol. Host exposes an io.WriteCloser (client → +// server) and io.ReadCloser (server → client) that plug straight into +// jsonrpc2.NewClient. +// +// The C ABI (shared with the .NET, Node.js, Python, and Rust SDKs): +// +// uint32 copilot_runtime_host_start(uint8 *argv, size_t argv_len, +// uint8 *env, size_t env_len); +// bool copilot_runtime_host_shutdown(uint32 server_id); +// uint32 copilot_runtime_connection_open(uint32 server_id, outbound cb, +// void *user_data, +// uint8 *a, size_t a_len, +// uint8 *b, size_t b_len, +// uint8 *c, size_t c_len); +// bool copilot_runtime_connection_write(uint32 conn_id, uint8 *bytes, size_t len); +// bool copilot_runtime_connection_close(uint32 conn_id); +// // outbound callback: +// void outbound(void *user_data, uint8 *bytes, size_t len); +// +// The native binding uses github.com/ebitengine/purego so the library is loaded +// at runtime with CGO disabled, preserving the SDK's pure-Go build and +// cross-compilation. +package ffihost + +import ( + "encoding/json" + "fmt" + "io" + "runtime" + "strings" + "sync" + "sync/atomic" + "unsafe" + + "github.com/ebitengine/purego" +) + +const symbolPrefix = "copilot_runtime_" + +// ffiLibrary binds the copilot_runtime_* C ABI exports of a loaded cdylib. +type ffiLibrary struct { + handle uintptr + hostStart func(argv unsafe.Pointer, argvLen uintptr, env unsafe.Pointer, envLen uintptr) uint32 + hostShutdown func(serverID uint32) bool + connectionOpen func(serverID uint32, cb uintptr, userData uintptr, a unsafe.Pointer, aLen uintptr, b unsafe.Pointer, bLen uintptr, c unsafe.Pointer, cLen uintptr) uint32 + connectionWrite func(connID uint32, bytes unsafe.Pointer, length uintptr) bool + connectionClose func(connID uint32) bool +} + +// The cdylib may only be loaded once per process; a second load of a different +// path is unsupported (matches the .NET/Node/Python/Rust hosts). Guard it here. +var ( + loadMu sync.Mutex + loadedLibrary *ffiLibrary + loadedLibraryPath string +) + +var ( + outboundCallbackOnce sync.Once + outboundCallbackHandle uintptr + outboundTargets sync.Map + nextOutboundToken atomic.Uint64 +) + +func sharedOutboundCallback() uintptr { + outboundCallbackOnce.Do(func() { + outboundCallbackHandle = purego.NewCallback(routeOutbound) + }) + return outboundCallbackHandle +} + +func routeOutbound(userData uintptr, bytesPtr uintptr, bytesLen uintptr) uintptr { + target, ok := outboundTargets.Load(userData) + if !ok { + return 0 + } + return target.(*Host).onOutbound(bytesPtr, bytesLen) +} + +func loadLibrary(libraryPath string) (lib *ffiLibrary, err error) { + loadMu.Lock() + defer loadMu.Unlock() + + if loadedLibrary != nil { + if loadedLibraryPath != libraryPath { + return nil, fmt.Errorf( + "an in-process FFI runtime library is already loaded from %q; loading a different library from %q in the same process is not supported", + loadedLibraryPath, libraryPath) + } + return loadedLibrary, nil + } + + handle, err := openLibrary(libraryPath) + if err != nil { + return nil, fmt.Errorf("loading FFI runtime library %q: %w", libraryPath, err) + } + + // RegisterLibFunc panics if a symbol is missing; convert that to an error so + // callers get a clean failure instead of a crash. + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("binding FFI runtime library %q: %v", libraryPath, r) + lib = nil + } + }() + + bound := &ffiLibrary{handle: handle} + purego.RegisterLibFunc(&bound.hostStart, handle, symbolPrefix+"host_start") + purego.RegisterLibFunc(&bound.hostShutdown, handle, symbolPrefix+"host_shutdown") + purego.RegisterLibFunc(&bound.connectionOpen, handle, symbolPrefix+"connection_open") + purego.RegisterLibFunc(&bound.connectionWrite, handle, symbolPrefix+"connection_write") + purego.RegisterLibFunc(&bound.connectionClose, handle, symbolPrefix+"connection_close") + + loadedLibrary = bound + loadedLibraryPath = libraryPath + return bound, nil +} + +// Host hosts the Copilot runtime in-process via its native C ABI. +// +// Construct with Create, call Start to open the FFI connection, wire +// Writer/Reader into jsonrpc2.NewClient, and call Dispose to tear everything +// down. +type Host struct { + libraryPath string + cliEntrypoint string + environment map[string]string + args []string + lib *ffiLibrary + + // lifecycleMu serializes native start/write/shutdown operations. hostStart + // cannot be interrupted, so Dispose waits for it before closing native IDs. + lifecycleMu sync.Mutex + // mu serializes disposal with native callbacks so the receive buffer cannot + // be fed after it is closed. + mu sync.Mutex + serverID uint32 + connectionID uint32 + disposed bool + // activeCallbacks counts outbound native callbacks currently executing. + activeCallbacks int + + recv *receiveBuffer + + callbackToken uintptr +} + +// Create resolves the native library and prepares the host. environment and +// args contain SDK-managed runtime options. +func Create(cliEntrypoint string, environment map[string]string, args []string) (*Host, error) { + libraryPath, err := ResolveLibraryPath(cliEntrypoint) + if err != nil { + return nil, err + } + lib, err := loadLibrary(libraryPath) + if err != nil { + return nil, err + } + return &Host{ + libraryPath: libraryPath, + cliEntrypoint: cliEntrypoint, + environment: environment, + args: append([]string(nil), args...), + lib: lib, + recv: newReceiveBuffer(), + }, nil +} + +// Start opens the FFI connection. Native startup may block, so callers should +// run it off any latency-sensitive goroutine. +func (h *Host) Start() error { + h.lifecycleMu.Lock() + defer h.lifecycleMu.Unlock() + + h.mu.Lock() + if h.disposed { + h.mu.Unlock() + return fmt.Errorf("the in-process runtime host is disposed") + } + h.mu.Unlock() + + argv := h.buildArgv() + env := h.buildEnv() + + var argvPtr, envPtr unsafe.Pointer + if len(argv) > 0 { + argvPtr = unsafe.Pointer(&argv[0]) + } + if len(env) > 0 { + envPtr = unsafe.Pointer(&env[0]) + } + + h.serverID = h.lib.hostStart(argvPtr, uintptr(len(argv)), envPtr, uintptr(len(env))) + // Keep the JSON buffers alive across the (synchronous) native call. + runtime.KeepAlive(argv) + runtime.KeepAlive(env) + if h.serverID == 0 { + return fmt.Errorf("copilot_runtime_host_start failed (library %q, entrypoint %q)", h.libraryPath, h.cliEntrypoint) + } + + // host_start spawned the worker child via libuv's uv_spawn, which installs a + // SIGCHLD handler without SA_ONSTACK on its first call. The Go runtime aborts + // ("non-Go code set up signal handler without SA_ONSTACK flag") when it later + // reaps one of its own os/exec children (e.g. a test-spawned MCP server) and + // the delivered SIGCHLD lands on a non-signal stack. Re-add SA_ONSTACK to that + // foreign handler now that it exists (implemented on darwin+linux; a no-op on + // other platforms, and before the first spawn there is nothing to fix — hence + // here rather than at library load). + rearmForeignSignalHandlers(h.lib.handle) + + callbackHandle := sharedOutboundCallback() + callbackToken := uintptr(nextOutboundToken.Add(1)) + outboundTargets.Store(callbackToken, h) + h.callbackToken = callbackToken + h.connectionID = h.lib.connectionOpen(h.serverID, callbackHandle, callbackToken, nil, 0, nil, 0, nil, 0) + if h.connectionID == 0 { + outboundTargets.Delete(callbackToken) + h.callbackToken = 0 + h.lib.hostShutdown(h.serverID) + rearmForeignSignalHandlers(h.lib.handle) + h.serverID = 0 + return fmt.Errorf("copilot_runtime_connection_open failed") + } + return nil +} + +// Writer returns the client → server frame sink (plug into jsonrpc2 as stdin). +func (h *Host) Writer() io.WriteCloser { return hostWriter{h} } + +// Reader returns the server → client frame source (plug into jsonrpc2 as stdout). +func (h *Host) Reader() io.ReadCloser { return h.recv } + +func (h *Host) buildArgv() []byte { + // A `.js` entrypoint (dev) is launched via node; the packaged single-file CLI + // embeds its own Node and is invoked directly. `--no-auto-update` pins the + // worker to the runtime package matching the loaded cdylib (avoids ABI skew). + var argv []string + if strings.HasSuffix(strings.ToLower(h.cliEntrypoint), ".js") { + argv = []string{"node", h.cliEntrypoint, "--embedded-host", "--no-auto-update"} + } else { + argv = []string{h.cliEntrypoint, "--embedded-host", "--no-auto-update"} + } + argv = append(argv, h.args...) + b, _ := json.Marshal(argv) + return b +} + +func (h *Host) buildEnv() []byte { + if len(h.environment) == 0 { + return nil + } + b, _ := json.Marshal(h.environment) + return b +} + +// onOutbound is the native server → client callback, invoked on a foreign +// runtime thread. The native pointer is only valid for this call, so the bytes +// are copied out before returning. Nothing may panic across the FFI boundary. +func (h *Host) onOutbound(bytesPtr uintptr, bytesLen uintptr) uintptr { + h.mu.Lock() + if h.disposed { + h.mu.Unlock() + return 0 + } + h.activeCallbacks++ + h.mu.Unlock() + + defer func() { + h.mu.Lock() + h.activeCallbacks-- + h.mu.Unlock() + // Never let a panic unwind into native code. + _ = recover() + }() + + if bytesPtr != 0 && bytesLen > 0 { + // The native runtime delivers the outbound frame as a raw buffer address + // (uintptr) plus length. Materialize a slice over it just long enough to + // copy the bytes into Go-owned memory before returning to native code. + //nolint:govet // FFI callback receives the buffer address as an integer; converting it to a pointer to copy out is the intended, checked-length use. + src := unsafe.Slice((*byte)(unsafe.Pointer(bytesPtr)), int(bytesLen)) + buf := make([]byte, len(src)) + copy(buf, src) + h.recv.feed(buf) + } + return 0 +} + +func (h *Host) writeFrame(frame []byte) (int, error) { + h.lifecycleMu.Lock() + defer h.lifecycleMu.Unlock() + + h.mu.Lock() + disposed := h.disposed + h.mu.Unlock() + connID := h.connectionID + if disposed || connID == 0 { + return 0, fmt.Errorf("the in-process runtime connection is closed") + } + if len(frame) == 0 { + return 0, nil + } + ok := h.lib.connectionWrite(connID, unsafe.Pointer(&frame[0]), uintptr(len(frame))) + runtime.KeepAlive(frame) + if !ok { + return 0, fmt.Errorf("failed to write a frame to the in-process runtime connection") + } + return len(frame), nil +} + +// Dispose closes the FFI connection, shuts down the native host, and releases +// resources. It is idempotent and waits for any in-flight outbound callback to +// finish before closing the receive buffer. +func (h *Host) Dispose() { + h.lifecycleMu.Lock() + defer h.lifecycleMu.Unlock() + + h.mu.Lock() + if h.disposed { + h.mu.Unlock() + return + } + // Publish disposed under the same lock onOutbound uses to check it, so no new + // callback can pass the check and increment activeCallbacks after the drain + // loop below observes zero. + h.disposed = true + connID := h.connectionID + serverID := h.serverID + callbackToken := h.callbackToken + h.connectionID = 0 + h.serverID = 0 + h.callbackToken = 0 + h.mu.Unlock() + + if callbackToken != 0 { + outboundTargets.Delete(callbackToken) + } + + // Stop accepting new callbacks and wait for in-flight ones to drain before + // closing the receive buffer they feed. + for { + h.mu.Lock() + if h.activeCallbacks == 0 { + h.mu.Unlock() + break + } + h.mu.Unlock() + runtime.Gosched() + } + + if connID != 0 { + h.lib.connectionClose(connID) + } + if serverID != 0 { + h.lib.hostShutdown(serverID) + // libuv may restore a previously saved SIGCHLD action while tearing down + // its final child watcher, so repair the process-wide handler again after + // shutdown before Go reaps another os/exec child. + rearmForeignSignalHandlers(h.lib.handle) + } + h.recv.Close() +} + +// hostWriter adapts Host into the io.WriteCloser jsonrpc2 writes request frames to. +type hostWriter struct{ h *Host } + +func (w hostWriter) Write(p []byte) (int, error) { return w.h.writeFrame(p) } + +func (w hostWriter) Close() error { + w.h.Dispose() + return nil +} diff --git a/go/internal/ffihost/ffihost_test.go b/go/internal/ffihost/ffihost_test.go new file mode 100644 index 0000000000..bc588fa6a9 --- /dev/null +++ b/go/internal/ffihost/ffihost_test.go @@ -0,0 +1,98 @@ +//go:build copilot_inprocess && (darwin || linux || windows) + +package ffihost + +import ( + "encoding/json" + "sync/atomic" + "testing" + "time" + "unsafe" +) + +func TestDisposeUnregistersOutboundTarget(t *testing.T) { + token := uintptr(nextOutboundToken.Add(1)) + host := &Host{ + recv: newReceiveBuffer(), + callbackToken: token, + } + outboundTargets.Store(token, host) + + host.Dispose() + + if _, ok := outboundTargets.Load(token); ok { + t.Fatal("Expected disposed host to be removed from outbound callback registry") + } +} + +func TestBuildArgvAppendsManagedOptions(t *testing.T) { + host := &Host{ + cliEntrypoint: "copilot", + args: []string{"--log-level", "debug", "--remote"}, + } + + var argv []string + if err := json.Unmarshal(host.buildArgv(), &argv); err != nil { + t.Fatal(err) + } + + expected := []string{"copilot", "--embedded-host", "--no-auto-update", "--log-level", "debug", "--remote"} + if len(argv) != len(expected) { + t.Fatalf("Expected %d arguments, got %d: %v", len(expected), len(argv), argv) + } + for i := range expected { + if argv[i] != expected[i] { + t.Fatalf("Expected argument %d to be %q, got %q", i, expected[i], argv[i]) + } + } +} + +func TestDisposeWaitsForStartBeforeShuttingDown(t *testing.T) { + started := make(chan struct{}) + releaseStart := make(chan struct{}) + startDone := make(chan error, 1) + disposeDone := make(chan struct{}) + var shutdownID atomic.Uint32 + + host := &Host{ + lib: &ffiLibrary{ + hostStart: func(_ unsafe.Pointer, _ uintptr, _ unsafe.Pointer, _ uintptr) uint32 { + close(started) + <-releaseStart + return 41 + }, + hostShutdown: func(serverID uint32) bool { + shutdownID.Store(serverID) + return true + }, + connectionOpen: func(_ uint32, _ uintptr, _ uintptr, _ unsafe.Pointer, _ uintptr, _ unsafe.Pointer, _ uintptr, _ unsafe.Pointer, _ uintptr) uint32 { + return 42 + }, + connectionClose: func(_ uint32) bool { return true }, + }, + recv: newReceiveBuffer(), + } + + go func() { startDone <- host.Start() }() + <-started + go func() { + host.Dispose() + close(disposeDone) + }() + + select { + case <-disposeDone: + t.Fatal("Dispose returned before native startup completed") + case <-time.After(20 * time.Millisecond): + } + + close(releaseStart) + if err := <-startDone; err != nil { + t.Fatal(err) + } + <-disposeDone + + if got := shutdownID.Load(); got != 41 { + t.Fatalf("Expected shutdown of server 41, got %d", got) + } +} diff --git a/go/internal/ffihost/loader_other.go b/go/internal/ffihost/loader_other.go new file mode 100644 index 0000000000..0b7bcc40b9 --- /dev/null +++ b/go/internal/ffihost/loader_other.go @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT + +//go:build copilot_inprocess && (darwin || linux) + +package ffihost + +import "github.com/ebitengine/purego" + +// openLibrary loads the shared library at path and returns an opaque handle. +// RTLD_NOW surfaces any load problem here (eager binding) rather than at first +// call, matching the .NET/Python hosts; RTLD_LOCAL keeps the runtime's symbols +// private to this handle. +func openLibrary(path string) (uintptr, error) { + return purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_LOCAL) +} diff --git a/go/internal/ffihost/loader_windows.go b/go/internal/ffihost/loader_windows.go new file mode 100644 index 0000000000..4ac2789f98 --- /dev/null +++ b/go/internal/ffihost/loader_windows.go @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT + +//go:build copilot_inprocess && windows + +package ffihost + +import "syscall" + +// openLibrary loads the DLL at path and returns its module handle. purego's +// RegisterLibFunc resolves exports from this handle via GetProcAddress, so the +// standard-library loader is sufficient and keeps CGO disabled. +func openLibrary(path string) (uintptr, error) { + handle, err := syscall.LoadLibrary(path) + if err != nil { + return 0, err + } + return uintptr(handle), nil +} diff --git a/go/internal/ffihost/resolve.go b/go/internal/ffihost/resolve.go new file mode 100644 index 0000000000..c8d4052322 --- /dev/null +++ b/go/internal/ffihost/resolve.go @@ -0,0 +1,117 @@ +package ffihost + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" +) + +// NaturalLibraryName is the natural platform shared-library file name for the +// runtime cdylib — the `.node` file renamed to what a Rust cdylib would be +// called on this OS. The library is loaded by absolute path, so the on-disk name +// is ours to choose; this matches the flat name the bundler installs next to the +// CLI binary and the name the other SDKs use. +func NaturalLibraryName() string { + switch runtime.GOOS { + case "windows": + return "copilot_runtime.dll" + case "darwin": + return "libcopilot_runtime.dylib" + default: + return "libcopilot_runtime.so" + } +} + +// PrebuildsFolder returns the napi-rs `-` folder name the +// runtime package ships under prebuilds/ (e.g. linux-x64, darwin-arm64, +// win32-x64, including the musl variant on Alpine). Returns "" for unsupported +// platforms. +func PrebuildsFolder() string { + var platform string + switch runtime.GOOS { + case "linux": + if isMusl() { + platform = "linuxmusl" + } else { + platform = "linux" + } + case "darwin": + platform = "darwin" + case "windows": + platform = "win32" + default: + return "" + } + + var arch string + switch runtime.GOARCH { + case "amd64": + arch = "x64" + case "arm64": + arch = "arm64" + default: + return "" + } + return platform + "-" + arch +} + +// ResolveLibraryPath resolves the native runtime library next to the given CLI +// entrypoint. It checks, in order: +// +// 1. The natural platform library name next to the CLI (bundled/flat layout). +// 2. prebuilds//runtime.node next to the CLI (dev/package layout). +// +// It returns an error when neither exists. +func ResolveLibraryPath(cliEntrypoint string) (string, error) { + abs, err := filepath.Abs(cliEntrypoint) + if err != nil { + abs = cliEntrypoint + } + dir := filepath.Dir(abs) + + flat := filepath.Join(dir, NaturalLibraryName()) + if fileExists(flat) { + return flat, nil + } + + if folder := PrebuildsFolder(); folder != "" { + prebuilt := filepath.Join(dir, "prebuilds", folder, "runtime.node") + if fileExists(prebuilt) { + return prebuilt, nil + } + } + + return "", fmt.Errorf( + "in-process FFI runtime library not found next to %q (looked for %q and prebuilds/%s/runtime.node); "+ + "use a runtime package that ships the native library", + abs, NaturalLibraryName(), PrebuildsFolder()) +} + +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} + +var ( + muslOnce sync.Once + muslResult bool +) + +// isMusl reports whether the current Linux system uses musl libc (e.g. Alpine), +// which ships the runtime under the linuxmusl- prebuilds folder. +func isMusl() bool { + muslOnce.Do(func() { + if runtime.GOOS != "linux" { + return + } + // `ldd --version` prints "musl libc" on musl systems and errors/glibc text + // elsewhere; a best-effort check is enough to pick the prebuilds folder. + out, _ := exec.Command("ldd", "--version").CombinedOutput() + muslResult = strings.Contains(strings.ToLower(string(out)), "musl") + }) + return muslResult +} diff --git a/go/internal/ffihost/resolve_test.go b/go/internal/ffihost/resolve_test.go new file mode 100644 index 0000000000..df3a668dfe --- /dev/null +++ b/go/internal/ffihost/resolve_test.go @@ -0,0 +1,54 @@ +package ffihost + +import ( + "os" + "path/filepath" + "testing" +) + +func TestResolveLibraryPathUsesNaturalLibraryNextToCLI(t *testing.T) { + dir := t.TempDir() + cliPath := filepath.Join(dir, "copilot") + libraryPath := filepath.Join(dir, NaturalLibraryName()) + + for _, path := range []string{cliPath, libraryPath} { + if err := os.WriteFile(path, []byte("test"), 0600); err != nil { + t.Fatalf("WriteFile(%q): %v", path, err) + } + } + + got, err := ResolveLibraryPath(cliPath) + if err != nil { + t.Fatalf("ResolveLibraryPath() error: %v", err) + } + if got != libraryPath { + t.Fatalf("ResolveLibraryPath() = %q, want %q", got, libraryPath) + } +} + +func TestResolveLibraryPathFallsBackToPrebuilds(t *testing.T) { + folder := PrebuildsFolder() + if folder == "" { + t.Skip("unsupported platform") + } + + dir := t.TempDir() + cliPath := filepath.Join(dir, "copilot") + libraryPath := filepath.Join(dir, "prebuilds", folder, "runtime.node") + if err := os.MkdirAll(filepath.Dir(libraryPath), 0755); err != nil { + t.Fatalf("MkdirAll(): %v", err) + } + for _, path := range []string{cliPath, libraryPath} { + if err := os.WriteFile(path, []byte("test"), 0600); err != nil { + t.Fatalf("WriteFile(%q): %v", path, err) + } + } + + got, err := ResolveLibraryPath(cliPath) + if err != nil { + t.Fatalf("ResolveLibraryPath() error: %v", err) + } + if got != libraryPath { + t.Fatalf("ResolveLibraryPath() = %q, want %q", got, libraryPath) + } +} diff --git a/go/internal/ffihost/sigonstack_darwin.go b/go/internal/ffihost/sigonstack_darwin.go new file mode 100644 index 0000000000..2e7d2a99b7 --- /dev/null +++ b/go/internal/ffihost/sigonstack_darwin.go @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT + +//go:build copilot_inprocess && darwin + +package ffihost + +import ( + "encoding/binary" + "unsafe" + + "github.com/ebitengine/purego" +) + +// Darwin `struct sigaction` layout (16 bytes, little-endian on amd64/arm64): +// +// offset 0: union __sigaction_u sa_handler/sa_sigaction (8 bytes, pointer) +// offset 8: sigset_t sa_mask (4 bytes, uint32) +// offset 12: int sa_flags (4 bytes) +const ( + darwinSigactionSize = 16 + darwinFlagsOffset = 12 + saOnStack = 0x0001 // SA_ONSTACK on Darwin + sigDfl = 0 // SIG_DFL + sigIgn = 1 // SIG_IGN + maxSignal = 31 // NSIG-1 on Darwin +) + +// rearmForeignSignalHandlers re-adds the SA_ONSTACK flag to any signal handler +// installed by the native runtime (libnode/libuv, loaded via dlopen) that +// omitted it. The Go runtime aborts with "non-Go code set up signal handler +// without SA_ONSTACK flag" when such a signal (notably SIGCHLD, signal 20 on +// Darwin) is delivered while a Go-managed child process is reaped. libuv +// installs a SIGCHLD handler without SA_ONSTACK, which poisons every subsequent +// os/exec child reaped by Go in the same process (enforced by the Go runtime on +// both macOS and Linux; the Linux variant lives in sigonstack_linux.go). +// +// We preserve each foreign handler and merely OR in SA_ONSTACK, so libuv's child +// watching keeps working while the Go runtime stays happy. Handlers left at +// SIG_DFL/SIG_IGN and Go's own handlers (which already carry SA_ONSTACK) are +// untouched. Best-effort: any failure is silently ignored, since the worst case +// is the pre-existing crash. +func rearmForeignSignalHandlers(_ uintptr) { + handle, err := purego.Dlopen("/usr/lib/libSystem.B.dylib", purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil || handle == 0 { + return + } + + var sigaction func(sig int32, act, oact unsafe.Pointer) int32 + if !bindSigaction(handle, &sigaction) { + return + } + + for sig := int32(1); sig <= maxSignal; sig++ { + var cur [darwinSigactionSize]byte + if sigaction(sig, nil, unsafe.Pointer(&cur[0])) != 0 { + continue + } + handler := binary.LittleEndian.Uint64(cur[0:8]) + if handler == sigDfl || handler == sigIgn { + continue + } + flags := binary.LittleEndian.Uint32(cur[darwinFlagsOffset : darwinFlagsOffset+4]) + if flags&saOnStack != 0 { + continue + } + binary.LittleEndian.PutUint32(cur[darwinFlagsOffset:darwinFlagsOffset+4], flags|saOnStack) + sigaction(sig, unsafe.Pointer(&cur[0]), nil) + } +} + +// bindSigaction resolves libc's sigaction into fn, converting the panic +// RegisterLibFunc raises on a missing symbol into a false return. +func bindSigaction(handle uintptr, fn *func(sig int32, act, oact unsafe.Pointer) int32) (ok bool) { + defer func() { + if recover() != nil { + ok = false + } + }() + purego.RegisterLibFunc(fn, handle, "sigaction") + return true +} diff --git a/go/internal/ffihost/sigonstack_linux.go b/go/internal/ffihost/sigonstack_linux.go new file mode 100644 index 0000000000..668cf67055 --- /dev/null +++ b/go/internal/ffihost/sigonstack_linux.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT + +//go:build copilot_inprocess && linux + +package ffihost + +import ( + "syscall" + "unsafe" +) + +const ( + linuxSaOnStack = 0x08000000 + linuxSigDfl = 0 + linuxSigIgn = 1 + linuxMaxSignal = 31 +) + +// linuxSigaction matches the kernel rt_sigaction ABI used by the Go runtime on +// Linux amd64 and arm64. +type linuxSigaction struct { + handler uintptr + flags uint64 + restorer uintptr + mask uint64 +} + +// rearmForeignSignalHandlers re-adds the SA_ONSTACK flag to any signal handler +// installed by the native runtime (libnode/libuv, loaded via dlopen) that +// omitted it. The Go runtime aborts with "non-Go code set up signal handler +// without SA_ONSTACK flag" when such a signal (notably SIGCHLD, signal 17 on +// Linux) is delivered while a Go-managed child process is reaped. libuv installs +// a SIGCHLD handler without SA_ONSTACK, which poisons every subsequent os/exec +// child reaped by Go in the same process. +// +// We preserve each foreign handler and merely OR in SA_ONSTACK, so libuv's child +// watching keeps working while the Go runtime stays happy. Handlers left at +// SIG_DFL/SIG_IGN and Go's own handlers (which already carry SA_ONSTACK) are +// untouched. Best-effort: any failure is silently ignored, since the worst case +// is the pre-existing crash. +func rearmForeignSignalHandlers(_ uintptr) { + for sig := 1; sig <= linuxMaxSignal; sig++ { + var action linuxSigaction + if !linuxGetSigaction(sig, &action) { + continue + } + if action.handler == linuxSigDfl || action.handler == linuxSigIgn { + continue + } + if action.flags&linuxSaOnStack != 0 { + continue + } + action.flags |= linuxSaOnStack + linuxSetSigaction(sig, &action) + } +} + +func linuxGetSigaction(signal int, action *linuxSigaction) bool { + _, _, errno := syscall.RawSyscall6( + syscall.SYS_RT_SIGACTION, + uintptr(signal), + 0, + uintptr(unsafe.Pointer(action)), + unsafe.Sizeof(action.mask), + 0, + 0, + ) + return errno == 0 +} + +func linuxSetSigaction(signal int, action *linuxSigaction) bool { + _, _, errno := syscall.RawSyscall6( + syscall.SYS_RT_SIGACTION, + uintptr(signal), + uintptr(unsafe.Pointer(action)), + 0, + unsafe.Sizeof(action.mask), + 0, + 0, + ) + return errno == 0 +} diff --git a/go/internal/ffihost/sigonstack_linux_test.go b/go/internal/ffihost/sigonstack_linux_test.go new file mode 100644 index 0000000000..3a382385f2 --- /dev/null +++ b/go/internal/ffihost/sigonstack_linux_test.go @@ -0,0 +1,38 @@ +//go:build copilot_inprocess && linux + +package ffihost + +import ( + "os" + "os/signal" + "syscall" + "testing" +) + +func TestRearmForeignSignalHandlersAddsOnStack(t *testing.T) { + signals := make(chan os.Signal, 1) + signal.Notify(signals, syscall.SIGUSR1) + defer signal.Stop(signals) + + var original linuxSigaction + if !linuxGetSigaction(int(syscall.SIGUSR1), &original) { + t.Fatal("failed to read SIGUSR1 action") + } + defer linuxSetSigaction(int(syscall.SIGUSR1), &original) + + withoutOnStack := original + withoutOnStack.flags &^= linuxSaOnStack + if !linuxSetSigaction(int(syscall.SIGUSR1), &withoutOnStack) { + t.Fatal("failed to clear SA_ONSTACK") + } + + rearmForeignSignalHandlers(0) + + var rearmed linuxSigaction + if !linuxGetSigaction(int(syscall.SIGUSR1), &rearmed) { + t.Fatal("failed to read rearmed SIGUSR1 action") + } + if rearmed.flags&linuxSaOnStack == 0 { + t.Fatal("SA_ONSTACK was not restored") + } +} diff --git a/go/internal/ffihost/sigonstack_other.go b/go/internal/ffihost/sigonstack_other.go new file mode 100644 index 0000000000..9da78255f6 --- /dev/null +++ b/go/internal/ffihost/sigonstack_other.go @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT + +//go:build copilot_inprocess && windows + +package ffihost + +// rearmForeignSignalHandlers is a no-op on platforms other than darwin and +// linux. Only those Unix platforms deliver the SA_ONSTACK-less SIGCHLD handler +// (installed by libuv) that the Go runtime rejects; Windows is unaffected. +func rearmForeignSignalHandlers(_ uintptr) {} diff --git a/go/rpc/zrpc.go b/go/rpc/zrpc.go index 03ec16cea1..30ae6ff271 100644 --- a/go/rpc/zrpc.go +++ b/go/rpc/zrpc.go @@ -28,7 +28,9 @@ type AbortResult struct { Success bool `json:"success"` } -// Schema for the `AccountAllUsers` type. +// Authenticated account entry returned by `account.getAllUsers`, with auth info and an +// optional associated token. +// Experimental: AccountAllUsers is part of an experimental API and may change or be removed. type AccountAllUsers struct { // Authentication information for this user AuthInfo AuthInfo `json:"authInfo"` @@ -37,9 +39,13 @@ type AccountAllUsers struct { } // List of all authenticated users +// Experimental: AccountGetAllUsersResult is part of an experimental API and may change or +// be removed. type AccountGetAllUsersResult []AccountAllUsers // Current authentication state +// Experimental: AccountGetCurrentAuthResult is part of an experimental API and may change +// or be removed. type AccountGetCurrentAuthResult struct { // Authentication errors from the last auth attempt, if any AuthErrors []string `json:"authErrors,omitzero"` @@ -47,6 +53,8 @@ type AccountGetCurrentAuthResult struct { AuthInfo AuthInfo `json:"authInfo,omitempty"` } +// Experimental: AccountGetQuotaRequest is part of an experimental API and may change or be +// removed. type AccountGetQuotaRequest struct { // GitHub token for per-user quota lookup. When provided, resolves this token to determine // the user's quota instead of using the global auth. @@ -54,12 +62,16 @@ type AccountGetQuotaRequest struct { } // Quota usage snapshots for the resolved user, keyed by quota type. +// Experimental: AccountGetQuotaResult is part of an experimental API and may change or be +// removed. type AccountGetQuotaResult struct { // Quota snapshots keyed by type (e.g., chat, completions, premium_interactions) QuotaSnapshots map[string]AccountQuotaSnapshot `json:"quotaSnapshots"` } // Credentials to store after successful authentication +// Experimental: AccountLoginRequest is part of an experimental API and may change or be +// removed. type AccountLoginRequest struct { // GitHub host URL Host string `json:"host"` @@ -70,6 +82,8 @@ type AccountLoginRequest struct { } // Result of a successful login; throws on failure +// Experimental: AccountLoginResult is part of an experimental API and may change or be +// removed. type AccountLoginResult struct { // Whether the credential was persisted to a secure store (system keychain, or the config // file when plaintext storage is enabled). False when no secure store was available and the @@ -78,18 +92,25 @@ type AccountLoginResult struct { } // User to log out +// Experimental: AccountLogoutRequest is part of an experimental API and may change or be +// removed. type AccountLogoutRequest struct { // Authentication information for the user to log out AuthInfo AuthInfo `json:"authInfo"` } // Logout result indicating if more users remain +// Experimental: AccountLogoutResult is part of an experimental API and may change or be +// removed. type AccountLogoutResult struct { // Whether other authenticated users remain after logout HasMoreUsers bool `json:"hasMoreUsers"` } -// Schema for the `AccountQuotaSnapshot` type. +// Quota usage snapshot for a Copilot quota type, including entitlement, used requests, +// overage, reset date, and remaining percentage. +// Experimental: AccountQuotaSnapshot is part of an experimental API and may change or be +// removed. type AccountQuotaSnapshot struct { // Number of requests included in the entitlement, or -1 for unlimited entitlements EntitlementRequests int64 `json:"entitlementRequests"` @@ -109,7 +130,8 @@ type AccountQuotaSnapshot struct { UsedRequests int64 `json:"usedRequests"` } -// Schema for the `AgentDiscoveryPath` type. +// Canonical directory where custom agents can be discovered or created, with scope, +// preference, and optional project path. // Experimental: AgentDiscoveryPath is part of an experimental API and may change or be // removed. type AgentDiscoveryPath struct { @@ -140,7 +162,8 @@ type AgentGetCurrentResult struct { Agent *AgentInfo `json:"agent,omitempty"` } -// Schema for the `AgentInfo` type. +// Custom agent metadata, including identifiers, display details, source, tools, model, MCP +// servers, skills, and file path. // Experimental: AgentInfo is part of an experimental API and may change or be removed. type AgentInfo struct { // Description of the agent's purpose @@ -410,22 +433,26 @@ type AgentsGetDiscoveryPathsRequest struct { // Experimental: AllowAllPermissionSetResult is part of an experimental API and may change // or be removed. type AllowAllPermissionSetResult struct { - // Authoritative allow-all state after the mutation + // Authoritative full allow-all state after the mutation Enabled bool `json:"enabled"` + // Authoritative allow-all mode after the mutation + Mode *PermissionsAllowAllMode `json:"mode,omitempty"` // Whether the operation succeeded Success bool `json:"success"` } -// Current full allow-all permission state. +// Current allow-all permission mode. // Experimental: AllowAllPermissionState is part of an experimental API and may change or be // removed. type AllowAllPermissionState struct { // Whether full allow-all permissions are currently active Enabled bool `json:"enabled"` + // Current allow-all mode + Mode *PermissionsAllowAllMode `json:"mode,omitempty"` } -// A user message attachment — a file, directory, code selection, blob, GitHub reference, or -// extension-supplied context payload +// A user message attachment — a file, directory, code selection, blob, GitHub-anchored +// pointer, or extension-supplied context payload // Experimental: Attachment is part of an experimental API and may change or be removed. type Attachment interface { attachment() @@ -545,6 +572,85 @@ func (AttachmentFile) Type() AttachmentType { return AttachmentTypeFile } +// Pointer to a GitHub Actions job. +// Experimental: AttachmentGitHubActionsJob is part of an experimental API and may change or +// be removed. +type AttachmentGitHubActionsJob struct { + // Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent + // for in-progress jobs. + Conclusion *string `json:"conclusion,omitempty"` + // Job id within the workflow run + JobID int64 `json:"jobId"` + // Display name of the job + JobName string `json:"jobName"` + // Repository the workflow run belongs to + Repo GitHubRepoRef `json:"repo"` + // URL to the job on GitHub + URL string `json:"url"` + // Display name of the workflow the job ran in + WorkflowName string `json:"workflowName"` +} + +func (AttachmentGitHubActionsJob) attachment() {} +func (AttachmentGitHubActionsJob) Type() AttachmentType { + return AttachmentTypeGitHubActionsJob +} + +// Pointer to a GitHub commit. +// Experimental: AttachmentGitHubCommit is part of an experimental API and may change or be +// removed. +type AttachmentGitHubCommit struct { + // First line of the commit message + Message string `json:"message"` + // Full commit SHA + Oid string `json:"oid"` + // Repository the commit belongs to + Repo GitHubRepoRef `json:"repo"` + // URL to the commit on GitHub + URL string `json:"url"` +} + +func (AttachmentGitHubCommit) attachment() {} +func (AttachmentGitHubCommit) Type() AttachmentType { + return AttachmentTypeGitHubCommit +} + +// Pointer to a file in a GitHub repository at a specific ref. +// Experimental: AttachmentGitHubFile is part of an experimental API and may change or be +// removed. +type AttachmentGitHubFile struct { + // Repository-relative path to the file + Path string `json:"path"` + // Git ref the file is read at (branch, tag, or commit SHA) + Ref string `json:"ref"` + // Repository the file lives in + Repo GitHubRepoRef `json:"repo"` + // URL to the file on GitHub + URL string `json:"url"` +} + +func (AttachmentGitHubFile) attachment() {} +func (AttachmentGitHubFile) Type() AttachmentType { + return AttachmentTypeGitHubFile +} + +// Pointer to a single-file diff. At least one of `head` and `base` must be present. +// Experimental: AttachmentGitHubFileDiff is part of an experimental API and may change or +// be removed. +type AttachmentGitHubFileDiff struct { + // File location on the base side of the diff. Absent for additions. + Base *AttachmentGitHubFileDiffSide `json:"base,omitempty"` + // File location on the head side of the diff. Absent for deletions. + Head *AttachmentGitHubFileDiffSide `json:"head,omitempty"` + // URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) + URL string `json:"url"` +} + +func (AttachmentGitHubFileDiff) attachment() {} +func (AttachmentGitHubFileDiff) Type() AttachmentType { + return AttachmentTypeGitHubFileDiff +} + // GitHub issue, pull request, or discussion reference // Experimental: AttachmentGitHubReference is part of an experimental API and may change or // be removed. @@ -566,6 +672,96 @@ func (AttachmentGitHubReference) Type() AttachmentType { return AttachmentTypeGitHubReference } +// Pointer to a GitHub release. +// Experimental: AttachmentGitHubRelease is part of an experimental API and may change or be +// removed. +type AttachmentGitHubRelease struct { + // Human-readable release name + Name string `json:"name"` + // Repository the release belongs to + Repo GitHubRepoRef `json:"repo"` + // Git tag the release is anchored to + TagName string `json:"tagName"` + // URL to the release on GitHub + URL string `json:"url"` +} + +func (AttachmentGitHubRelease) attachment() {} +func (AttachmentGitHubRelease) Type() AttachmentType { + return AttachmentTypeGitHubRelease +} + +// Pointer to a GitHub repository. +// Experimental: AttachmentGitHubRepository is part of an experimental API and may change or +// be removed. +type AttachmentGitHubRepository struct { + // Short description of the repository + Description *string `json:"description,omitempty"` + // Git ref this attachment is anchored at (branch, tag, or commit). When absent the default + // branch is implied. + Ref *string `json:"ref,omitempty"` + // Repository pointer + Repo GitHubRepoRef `json:"repo"` + // URL to the repository on GitHub + URL string `json:"url"` +} + +func (AttachmentGitHubRepository) attachment() {} +func (AttachmentGitHubRepository) Type() AttachmentType { + return AttachmentTypeGitHubRepository +} + +// Pointer to a line range inside a file in a GitHub repository. +// Experimental: AttachmentGitHubSnippet is part of an experimental API and may change or be +// removed. +type AttachmentGitHubSnippet struct { + // Line range the snippet covers + LineRange AttachmentFileLineRange `json:"lineRange"` + // Repository-relative path to the file + Path string `json:"path"` + // Git ref the file is read at (branch, tag, or commit SHA) + Ref string `json:"ref"` + // Repository the file lives in + Repo GitHubRepoRef `json:"repo"` + // URL to the snippet on GitHub (with line anchor) + URL string `json:"url"` +} + +func (AttachmentGitHubSnippet) attachment() {} +func (AttachmentGitHubSnippet) Type() AttachmentType { + return AttachmentTypeGitHubSnippet +} + +// Pointer to a comparison between two git revisions. +// Experimental: AttachmentGitHubTreeComparison is part of an experimental API and may +// change or be removed. +type AttachmentGitHubTreeComparison struct { + // Base side of the comparison + Base AttachmentGitHubTreeComparisonSide `json:"base"` + // Head side of the comparison + Head AttachmentGitHubTreeComparisonSide `json:"head"` + // URL to the comparison on GitHub + URL string `json:"url"` +} + +func (AttachmentGitHubTreeComparison) attachment() {} +func (AttachmentGitHubTreeComparison) Type() AttachmentType { + return AttachmentTypeGitHubTreeComparison +} + +// Generic GitHub URL reference. +// Experimental: AttachmentGitHubURL is part of an experimental API and may change or be +// removed. +type AttachmentGitHubURL struct { + // URL to the GitHub resource + URL string `json:"url"` +} + +func (AttachmentGitHubURL) attachment() {} +func (AttachmentGitHubURL) Type() AttachmentType { + return AttachmentTypeGitHubURL +} + // Code selection attachment from an editor // Experimental: AttachmentSelection is part of an experimental API and may change or be // removed. @@ -595,6 +791,28 @@ type AttachmentFileLineRange struct { Start int64 `json:"start"` } +// One side of a file diff (head or base) +// Experimental: AttachmentGitHubFileDiffSide is part of an experimental API and may change +// or be removed. +type AttachmentGitHubFileDiffSide struct { + // Repository-relative path to the file + Path string `json:"path"` + // Git ref (branch, tag, or commit SHA) the file is read at + Ref string `json:"ref"` + // Repository the file lives in + Repo GitHubRepoRef `json:"repo"` +} + +// One side of a tree comparison (head or base) +// Experimental: AttachmentGitHubTreeComparisonSide is part of an experimental API and may +// change or be removed. +type AttachmentGitHubTreeComparisonSide struct { + // Repository the revision belongs to + Repo GitHubRepoRef `json:"repo"` + // Git revision (branch, tag, or commit SHA) + Revision string `json:"revision"` +} + // Position range of the selection within the file // Experimental: AttachmentSelectionDetails is part of an experimental API and may change or // be removed. @@ -626,6 +844,7 @@ type AttachmentSelectionDetailsStart struct { } // Initial authentication info for the session. +// Experimental: AuthInfo is part of an experimental API and may change or be removed. type AuthInfo interface { authInfo() Type() AuthInfoType @@ -641,7 +860,9 @@ func (r RawAuthInfoData) Type() AuthInfoType { return r.Discriminator } -// Schema for the `ApiKeyAuthInfo` type. +// Authentication-info variant for API-key authentication to a non-GitHub LLM provider, +// carrying the secret `apiKey` and host. +// Experimental: APIKeyAuthInfo is part of an experimental API and may change or be removed. type APIKeyAuthInfo struct { // The API key. Treat as a secret. APIKey string `json:"apiKey"` @@ -658,7 +879,10 @@ func (APIKeyAuthInfo) Type() AuthInfoType { return AuthInfoTypeAPIKey } -// Schema for the `CopilotApiTokenAuthInfo` type. +// Authentication-info variant for direct Copilot API token auth sourced from environment +// variables, with public GitHub host. +// Experimental: CopilotAPITokenAuthInfo is part of an experimental API and may change or be +// removed. type CopilotAPITokenAuthInfo struct { // Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the // GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this @@ -673,7 +897,9 @@ func (CopilotAPITokenAuthInfo) Type() AuthInfoType { return AuthInfoTypeCopilotAPIToken } -// Schema for the `EnvAuthInfo` type. +// Authentication-info variant for a token sourced from an environment variable, with host, +// optional login, token, and env var name. +// Experimental: EnvAuthInfo is part of an experimental API and may change or be removed. type EnvAuthInfo struct { // Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the // GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this @@ -695,7 +921,9 @@ func (EnvAuthInfo) Type() AuthInfoType { return AuthInfoTypeEnv } -// Schema for the `GhCliAuthInfo` type. +// Authentication-info variant for GitHub CLI credentials, carrying host, login, and the `gh +// auth token` value. +// Experimental: GhCLIAuthInfo is part of an experimental API and may change or be removed. type GhCLIAuthInfo struct { // Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the // GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this @@ -714,7 +942,9 @@ func (GhCLIAuthInfo) Type() AuthInfoType { return AuthInfoTypeGhCLI } -// Schema for the `HMACAuthInfo` type. +// Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub +// host and HMAC secret. +// Experimental: HMACAuthInfo is part of an experimental API and may change or be removed. type HMACAuthInfo struct { // Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the // GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this @@ -731,7 +961,9 @@ func (HMACAuthInfo) Type() AuthInfoType { return AuthInfoTypeHMAC } -// Schema for the `TokenAuthInfo` type. +// Authentication-info variant for SDK-configured token authentication, carrying host and +// the secret token value. +// Experimental: TokenAuthInfo is part of an experimental API and may change or be removed. type TokenAuthInfo struct { // Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the // GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this @@ -748,7 +980,9 @@ func (TokenAuthInfo) Type() AuthInfoType { return AuthInfoTypeToken } -// Schema for the `UserAuthInfo` type. +// Authentication-info variant for OAuth user auth, with host and login; the token remains +// in the runtime secret store. +// Experimental: UserAuthInfo is part of an experimental API and may change or be removed. type UserAuthInfo struct { // Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the // GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this @@ -1028,6 +1262,36 @@ type CommandsRespondToQueuedCommandResult struct { Success bool `json:"success"` } +// Characters that, when typed in the composer, should trigger a `completions.request`. +// Empty when the session has no host-driven completions (e.g. local sessions, or a relay +// host that does not advertise `completionTriggerCharacters`). +// Experimental: CompletionsGetTriggerCharactersResult is part of an experimental API and +// may change or be removed. +type CompletionsGetTriggerCharactersResult struct { + // Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven + // completions for the session. + TriggerCharacters []string `json:"triggerCharacters"` +} + +// Request host-driven completions for the current composer input. +// Experimental: CompletionsRequestRequest is part of an experimental API and may change or +// be removed. +type CompletionsRequestRequest struct { + // Cursor offset within `text`, in UTF-16 code units. + Offset int64 `json:"offset"` + // The full composed composer input. + Text string `json:"text"` +} + +// Host-driven completion items for the current composer input. Empty when the host returns +// no items or does not support completions. +// Experimental: CompletionsRequestResult is part of an experimental API and may change or +// be removed. +type CompletionsRequestResult struct { + // Completion items in host-ranked order. + Items []SessionCompletionItem `json:"items"` +} + // Params to attach or detach an in-process ExtensionController delegate. // Experimental: ConfigureSessionExtensionsParams is part of an experimental API and may // change or be removed. @@ -1092,14 +1356,25 @@ type ConnectRemoteSessionParams struct { SessionID string `json:"sessionId"` } -// Optional connection token presented by the SDK client during the handshake. +// Parameters for the `server.connect` handshake: an optional connection token and optional +// connection-level opt-ins (e.g. GitHub telemetry forwarding). +// Experimental: ConnectRequest is part of an experimental API and may change or be removed. // Internal: ConnectRequest is an internal SDK API and is not part of the public surface. type ConnectRequest struct { + // Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the + // runtime forwards every internal telemetry event it emits — across all sessions, plus + // sessionless events — to this connection over the `gitHubTelemetry.event` notification, in + // addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for + // first-party hosts that re-emit the events into their own telemetry stores. Both + // unrestricted and restricted events are forwarded, each tagged with a `restricted` + // discriminator; a backstop drops restricted events when restricted telemetry is disabled. + EnableGitHubTelemetryForwarding *bool `json:"enableGitHubTelemetryForwarding,omitempty"` // Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN Token *string `json:"token,omitempty"` } // Handshake result reporting the server's protocol version and package version on success. +// Experimental: ConnectResult is part of an experimental API and may change or be removed. // Internal: ConnectResult is an internal SDK API and is not part of the public surface. type ConnectResult struct { // Always true on success @@ -1110,40 +1385,88 @@ type ConnectResult struct { Version string `json:"version"` } +// A single large message currently in context. +// Experimental: ContextHeaviestMessage is part of an experimental API and may change or be +// removed. +type ContextHeaviestMessage struct { + // Stable identifier for this message within the snapshot. + ID string `json:"id"` + // Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. + Label string `json:"label"` + // Role of the chat message (`user`, `assistant`, or `tool`). + Role string `json:"role"` + // Token count currently in context for this individual message. + Tokens int64 `json:"tokens"` +} + // Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the // GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this // verbatim and does not re-fetch when set. +// Experimental: CopilotUserResponse is part of an experimental API and may change or be +// removed. type CopilotUserResponse struct { - AccessTypeSku *string `json:"access_type_sku,omitempty"` - AnalyticsTrackingID *string `json:"analytics_tracking_id,omitempty"` - AssignedDate *string `json:"assigned_date,omitempty"` - CanSignupForLimited *bool `json:"can_signup_for_limited,omitempty"` - CanUpgradePlan *bool `json:"can_upgrade_plan,omitempty"` - ChatEnabled *bool `json:"chat_enabled,omitempty"` - CLIRemoteControlEnabled *bool `json:"cli_remote_control_enabled,omitempty"` - CloudSessionStorageEnabled *bool `json:"cloud_session_storage_enabled,omitempty"` - CodexAgentEnabled *bool `json:"codex_agent_enabled,omitempty"` - CopilotignoreEnabled *bool `json:"copilotignore_enabled,omitempty"` - CopilotPlan *string `json:"copilot_plan,omitempty"` - // Schema for the `CopilotUserResponseEndpoints` type. - Endpoints *CopilotUserResponseEndpoints `json:"endpoints,omitempty"` - IsMCPEnabled *bool `json:"is_mcp_enabled,omitempty"` - IsStaff *bool `json:"is_staff,omitempty"` - LimitedUserQuotas map[string]float64 `json:"limited_user_quotas,omitzero"` - LimitedUserResetDate *string `json:"limited_user_reset_date,omitempty"` - Login *string `json:"login,omitempty"` - MonthlyQuotas map[string]float64 `json:"monthly_quotas,omitzero"` - OrganizationList []CopilotUserResponseOrganizationListItem `json:"organization_list,omitzero"` - OrganizationLoginList []string `json:"organization_login_list,omitzero"` - QuotaResetDate *string `json:"quota_reset_date,omitempty"` - QuotaResetDateUTC *string `json:"quota_reset_date_utc,omitempty"` - // Schema for the `CopilotUserResponseQuotaSnapshots` type. - QuotaSnapshots *CopilotUserResponseQuotaSnapshots `json:"quota_snapshots,omitempty"` - RestrictedTelemetry *bool `json:"restricted_telemetry,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` -} - -// Schema for the `CopilotUserResponseEndpoints` type. + // Copilot access SKU identifier (e.g. `free_limited_copilot`, + // `copilot_for_business_seat_quota`) used to gate model and feature access. + AccessTypeSku *string `json:"access_type_sku,omitempty"` + // Opaque analytics tracking identifier for the user, forwarded from the Copilot API. + AnalyticsTrackingID *string `json:"analytics_tracking_id,omitempty"` + // Date the Copilot seat was assigned to the user, if applicable. + AssignedDate *string `json:"assigned_date,omitempty"` + // Whether the user is eligible to sign up for the free/limited Copilot tier. + CanSignupForLimited *bool `json:"can_signup_for_limited,omitempty"` + // Whether the user is able to upgrade their Copilot plan. + CanUpgradePlan *bool `json:"can_upgrade_plan,omitempty"` + // Whether Copilot chat is enabled for the user. + ChatEnabled *bool `json:"chat_enabled,omitempty"` + // Whether CLI remote control is enabled for the user. + CLIRemoteControlEnabled *bool `json:"cli_remote_control_enabled,omitempty"` + // Whether cloud session storage is enabled for the user. + CloudSessionStorageEnabled *bool `json:"cloud_session_storage_enabled,omitempty"` + // Whether the Codex agent is enabled for the user. + CodexAgentEnabled *bool `json:"codex_agent_enabled,omitempty"` + // Whether `.copilotignore` content-exclusion support is enabled for the user. + CopilotignoreEnabled *bool `json:"copilotignore_enabled,omitempty"` + // Copilot plan name for the user (e.g. `individual`, `business`, `enterprise`). + CopilotPlan *string `json:"copilot_plan,omitempty"` + // Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. + Endpoints *CopilotUserResponseEndpoints `json:"endpoints,omitempty"` + // Whether MCP (Model Context Protocol) support is enabled for the user. + IsMCPEnabled *bool `json:"is_mcp_enabled,omitempty"` + // Whether the user is a GitHub/Microsoft staff member. + IsStaff *bool `json:"is_staff,omitempty"` + // Per-category quota allotments for free/limited-tier users, keyed by quota category. + LimitedUserQuotas map[string]float64 `json:"limited_user_quotas,omitzero"` + // Date the free/limited-tier user's quotas next reset, as a raw string from the Copilot API. + LimitedUserResetDate *string `json:"limited_user_reset_date,omitempty"` + // GitHub login of the authenticated user. + Login *string `json:"login,omitempty"` + // Per-category monthly quota allotments, keyed by quota category. + MonthlyQuotas map[string]float64 `json:"monthly_quotas,omitzero"` + // Organizations the user belongs to, each with an optional login and display name. + OrganizationList []CopilotUserResponseOrganizationListItem `json:"organization_list,omitzero"` + // Logins of the organizations the user belongs to. + OrganizationLoginList []string `json:"organization_login_list,omitzero"` + // Date the user's usage quota next resets, as a raw string from the Copilot API; see + // `quota_reset_date_utc` for the UTC-normalized value. + QuotaResetDate *string `json:"quota_reset_date,omitempty"` + // UTC-normalized form of `quota_reset_date` (the date the user's usage quota next resets). + QuotaResetDateUTC *string `json:"quota_reset_date_utc,omitempty"` + // Quota snapshot map from the raw Copilot user-response passthrough, with chat, + // completions, premium-interactions, and other entries. + QuotaSnapshots *CopilotUserResponseQuotaSnapshots `json:"quota_snapshots,omitempty"` + // Whether the user's telemetry is subject to restricted-data handling. + RestrictedTelemetry *bool `json:"restricted_telemetry,omitempty"` + // Raw passthrough of the Copilot API `te` flag for the user (an opaque server-side + // eligibility signal surfaced in telemetry); not otherwise interpreted by the runtime. + Te *bool `json:"te,omitempty"` + // Whether the account is on usage-based (token/AI-credit) billing rather than a fixed + // premium-request quota. + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` +} + +// Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. +// Experimental: CopilotUserResponseEndpoints is part of an experimental API and may change +// or be removed. type CopilotUserResponseEndpoints struct { API *string `json:"api,omitempty"` OriginTracker *string `json:"origin-tracker,omitempty"` @@ -1156,62 +1479,122 @@ type CopilotUserResponseOrganizationListItem struct { Name *string `json:"name,omitempty"` } -// Schema for the `CopilotUserResponseQuotaSnapshots` type. +// Quota snapshot map from the raw Copilot user-response passthrough, with chat, +// completions, premium-interactions, and other entries. +// Experimental: CopilotUserResponseQuotaSnapshots is part of an experimental API and may +// change or be removed. type CopilotUserResponseQuotaSnapshots struct { - // Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + // Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, + // overage, remaining quota, reset, and billing fields. Chat *CopilotUserResponseQuotaSnapshotsChat `json:"chat,omitempty"` - // Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + // Completions quota snapshot from the raw Copilot user-response passthrough, with + // entitlement, overage, remaining quota, reset, and billing fields. Completions *CopilotUserResponseQuotaSnapshotsCompletions `json:"completions,omitempty"` - // Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + // Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with + // entitlement, overage, remaining quota, reset, and billing fields. PremiumInteractions *CopilotUserResponseQuotaSnapshotsPremiumInteractions `json:"premium_interactions,omitempty"` } -// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. +// Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, +// overage, remaining quota, reset, and billing fields. +// Experimental: CopilotUserResponseQuotaSnapshotsChat is part of an experimental API and +// may change or be removed. type CopilotUserResponseQuotaSnapshotsChat struct { - Entitlement *float64 `json:"entitlement,omitempty"` - HasQuota *bool `json:"has_quota,omitempty"` - OverageCount *float64 `json:"overage_count,omitempty"` - OveragePermitted *bool `json:"overage_permitted,omitempty"` - PercentRemaining *float64 `json:"percent_remaining,omitempty"` - QuotaID *string `json:"quota_id,omitempty"` - QuotaRemaining *float64 `json:"quota_remaining,omitempty"` - QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` - Remaining *float64 `json:"remaining,omitempty"` - TimestampUTC *string `json:"timestamp_utc,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` - Unlimited *bool `json:"unlimited,omitempty"` -} - -// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + // Number of requests/units included in the entitlement for this period; `-1` denotes an + // unlimited entitlement. + Entitlement *float64 `json:"entitlement,omitempty"` + // Whether the user currently has quota available; when `false` and not unlimited, further + // requests are blocked until the quota resets. + HasQuota *bool `json:"has_quota,omitempty"` + // Count of additional pay-per-request usage consumed this period beyond the entitlement. + OverageCount *float64 `json:"overage_count,omitempty"` + // Whether usage may continue at pay-per-request rates once the entitlement is exhausted. + OveragePermitted *bool `json:"overage_permitted,omitempty"` + // Percentage of the entitlement remaining at the snapshot timestamp. + PercentRemaining *float64 `json:"percent_remaining,omitempty"` + // Identifier of the quota bucket this snapshot describes. + QuotaID *string `json:"quota_id,omitempty"` + // Amount of quota remaining at the snapshot timestamp. + QuotaRemaining *float64 `json:"quota_remaining,omitempty"` + // Unix epoch time, in seconds, when this quota next resets. + QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` + // Remaining entitlement/quota amount at the snapshot timestamp. + Remaining *float64 `json:"remaining,omitempty"` + // UTC timestamp when this snapshot was captured. + TimestampUTC *string `json:"timestamp_utc,omitempty"` + // Whether this category uses usage-based (token/AI-credit) billing rather than a fixed + // premium-request count. + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` + // Whether the entitlement for this category is unlimited. + Unlimited *bool `json:"unlimited,omitempty"` +} + +// Completions quota snapshot from the raw Copilot user-response passthrough, with +// entitlement, overage, remaining quota, reset, and billing fields. +// Experimental: CopilotUserResponseQuotaSnapshotsCompletions is part of an experimental API +// and may change or be removed. type CopilotUserResponseQuotaSnapshotsCompletions struct { - Entitlement *float64 `json:"entitlement,omitempty"` - HasQuota *bool `json:"has_quota,omitempty"` - OverageCount *float64 `json:"overage_count,omitempty"` - OveragePermitted *bool `json:"overage_permitted,omitempty"` - PercentRemaining *float64 `json:"percent_remaining,omitempty"` - QuotaID *string `json:"quota_id,omitempty"` - QuotaRemaining *float64 `json:"quota_remaining,omitempty"` - QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` - Remaining *float64 `json:"remaining,omitempty"` - TimestampUTC *string `json:"timestamp_utc,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` - Unlimited *bool `json:"unlimited,omitempty"` -} - -// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + // Number of requests/units included in the entitlement for this period; `-1` denotes an + // unlimited entitlement. + Entitlement *float64 `json:"entitlement,omitempty"` + // Whether the user currently has quota available; when `false` and not unlimited, further + // requests are blocked until the quota resets. + HasQuota *bool `json:"has_quota,omitempty"` + // Count of additional pay-per-request usage consumed this period beyond the entitlement. + OverageCount *float64 `json:"overage_count,omitempty"` + // Whether usage may continue at pay-per-request rates once the entitlement is exhausted. + OveragePermitted *bool `json:"overage_permitted,omitempty"` + // Percentage of the entitlement remaining at the snapshot timestamp. + PercentRemaining *float64 `json:"percent_remaining,omitempty"` + // Identifier of the quota bucket this snapshot describes. + QuotaID *string `json:"quota_id,omitempty"` + // Amount of quota remaining at the snapshot timestamp. + QuotaRemaining *float64 `json:"quota_remaining,omitempty"` + // Unix epoch time, in seconds, when this quota next resets. + QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` + // Remaining entitlement/quota amount at the snapshot timestamp. + Remaining *float64 `json:"remaining,omitempty"` + // UTC timestamp when this snapshot was captured. + TimestampUTC *string `json:"timestamp_utc,omitempty"` + // Whether this category uses usage-based (token/AI-credit) billing rather than a fixed + // premium-request count. + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` + // Whether the entitlement for this category is unlimited. + Unlimited *bool `json:"unlimited,omitempty"` +} + +// Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with +// entitlement, overage, remaining quota, reset, and billing fields. +// Experimental: CopilotUserResponseQuotaSnapshotsPremiumInteractions is part of an +// experimental API and may change or be removed. type CopilotUserResponseQuotaSnapshotsPremiumInteractions struct { - Entitlement *float64 `json:"entitlement,omitempty"` - HasQuota *bool `json:"has_quota,omitempty"` - OverageCount *float64 `json:"overage_count,omitempty"` - OveragePermitted *bool `json:"overage_permitted,omitempty"` - PercentRemaining *float64 `json:"percent_remaining,omitempty"` - QuotaID *string `json:"quota_id,omitempty"` - QuotaRemaining *float64 `json:"quota_remaining,omitempty"` - QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` - Remaining *float64 `json:"remaining,omitempty"` - TimestampUTC *string `json:"timestamp_utc,omitempty"` - TokenBasedBilling *bool `json:"token_based_billing,omitempty"` - Unlimited *bool `json:"unlimited,omitempty"` + // Number of requests/units included in the entitlement for this period; `-1` denotes an + // unlimited entitlement. + Entitlement *float64 `json:"entitlement,omitempty"` + // Whether the user currently has quota available; when `false` and not unlimited, further + // requests are blocked until the quota resets. + HasQuota *bool `json:"has_quota,omitempty"` + // Count of additional pay-per-request usage consumed this period beyond the entitlement. + OverageCount *float64 `json:"overage_count,omitempty"` + // Whether usage may continue at pay-per-request rates once the entitlement is exhausted. + OveragePermitted *bool `json:"overage_permitted,omitempty"` + // Percentage of the entitlement remaining at the snapshot timestamp. + PercentRemaining *float64 `json:"percent_remaining,omitempty"` + // Identifier of the quota bucket this snapshot describes. + QuotaID *string `json:"quota_id,omitempty"` + // Amount of quota remaining at the snapshot timestamp. + QuotaRemaining *float64 `json:"quota_remaining,omitempty"` + // Unix epoch time, in seconds, when this quota next resets. + QuotaResetAt *float64 `json:"quota_reset_at,omitempty"` + // Remaining entitlement/quota amount at the snapshot timestamp. + Remaining *float64 `json:"remaining,omitempty"` + // UTC timestamp when this snapshot was captured. + TimestampUTC *string `json:"timestamp_utc,omitempty"` + // Whether this category uses usage-based (token/AI-credit) billing rather than a fixed + // premium-request count. + TokenBasedBilling *bool `json:"token_based_billing,omitempty"` + // Whether the entitlement for this category is unlimited. + Unlimited *bool `json:"unlimited,omitempty"` } // The currently selected model, reasoning effort, and context tier for the session. The @@ -1249,6 +1632,142 @@ type CurrentToolMetadata struct { NamespacedName *string `json:"namespacedName,omitempty"` } +// A file included in the redacted debug bundle. +// Experimental: DebugCollectLogsCollectedEntry is part of an experimental API and may +// change or be removed. +type DebugCollectLogsCollectedEntry struct { + // Relative path of the file in the staged bundle/archive. + BundlePath string `json:"bundlePath"` + // Redacted output size in bytes. + SizeBytes int64 `json:"sizeBytes"` + // Source category for this entry. + Source DebugCollectLogsSource `json:"source"` +} + +// Destination for the redacted debug bundle. +// Experimental: DebugCollectLogsDestination is part of an experimental API and may change +// or be removed. +type DebugCollectLogsDestination interface { + debugCollectLogsDestination() + Kind() DebugCollectLogsDestinationKind +} + +type RawDebugCollectLogsDestinationData struct { + Discriminator DebugCollectLogsDestinationKind + Raw json.RawMessage +} + +func (RawDebugCollectLogsDestinationData) debugCollectLogsDestination() {} +func (r RawDebugCollectLogsDestinationData) Kind() DebugCollectLogsDestinationKind { + return r.Discriminator +} + +type DebugCollectLogsDestinationArchive struct { + // When true, create the archive atomically without overwriting an existing file by + // appending ` (N)` before the extension as needed. Defaults to false. + NoOverwrite *bool `json:"noOverwrite,omitempty"` + // Absolute or server-relative path for the .tgz archive to create. + OutputPath string `json:"outputPath"` +} + +func (DebugCollectLogsDestinationArchive) debugCollectLogsDestination() {} +func (DebugCollectLogsDestinationArchive) Kind() DebugCollectLogsDestinationKind { + return DebugCollectLogsDestinationKindArchive +} + +type DebugCollectLogsDestinationDirectory struct { + // Directory where redacted files should be staged. The directory is created if needed. + OutputDirectory string `json:"outputDirectory"` +} + +func (DebugCollectLogsDestinationDirectory) debugCollectLogsDestination() {} +func (DebugCollectLogsDestinationDirectory) Kind() DebugCollectLogsDestinationKind { + return DebugCollectLogsDestinationKindDirectory +} + +// A caller-provided server-local file or directory to include in the debug bundle. +// Experimental: DebugCollectLogsEntry is part of an experimental API and may change or be +// removed. +type DebugCollectLogsEntry struct { + // Relative path to use inside the staged bundle/archive. + BundlePath string `json:"bundlePath"` + // Kind of source path to include. + Kind DebugCollectLogsEntryKind `json:"kind"` + // Server-local source path to read. + Path string `json:"path"` + // How text content from this entry should be redacted. Defaults to plain-text. + Redaction *DebugCollectLogsRedaction `json:"redaction,omitempty"` + // When true, collection fails if this entry cannot be read. Defaults to false, which + // records the entry in `skippedEntries`. + Required *bool `json:"required,omitempty"` +} + +// Built-in session diagnostics to include in the bundle. Omitted fields default to true. +// Experimental: DebugCollectLogsInclude is part of an experimental API and may change or be +// removed. +type DebugCollectLogsInclude struct { + // Server-local path to the current process log. When set, it is included as `process.log` + // and its directory is searched for prior logs from the same session. + CurrentProcessLogPath *string `json:"currentProcessLogPath,omitempty"` + // Include the session event log (`events.jsonl`). Defaults to true. + Events *bool `json:"events,omitempty"` + // Server-local path to the session's events.jsonl file. Internal callers normally omit this + // and let the runtime derive it from the session. + EventsPath *string `json:"eventsPath,omitempty"` + // Maximum number of previous process logs to include. Defaults to 5. + PreviousProcessLogLimit *int64 `json:"previousProcessLogLimit,omitempty"` + // Server-local process log directory to search when `currentProcessLogPath` is unavailable, + // useful for collecting logs for inactive sessions. + ProcessLogDirectory *string `json:"processLogDirectory,omitempty"` + // Include process logs for the session. Defaults to true. + ProcessLogs *bool `json:"processLogs,omitempty"` + // Include interactive shell logs written under the session's `shell-logs` directory. + // Defaults to true. + ShellLogs *bool `json:"shellLogs,omitempty"` +} + +// Options for collecting a redacted session debug bundle. +// Experimental: DebugCollectLogsRequest is part of an experimental API and may change or be +// removed. +type DebugCollectLogsRequest struct { + // Caller-provided server-local files or directories to include in addition to the runtime's + // built-in session diagnostics. This lets host applications add their own diagnostics + // without changing the API shape. + AdditionalEntries []DebugCollectLogsEntry `json:"additionalEntries,omitzero"` + // Where the redacted bundle should be written. Use `archive` to produce a .tgz, or + // `directory` to stage redacted files for caller-managed upload/post-processing. + Destination DebugCollectLogsDestination `json:"destination"` + // Which built-in session diagnostics to include. Omitted fields default to true. + Include *DebugCollectLogsInclude `json:"include,omitempty"` +} + +// Result of collecting a redacted debug bundle. +// Experimental: DebugCollectLogsResult is part of an experimental API and may change or be +// removed. +type DebugCollectLogsResult struct { + // Files included in the redacted bundle. + Entries []DebugCollectLogsCollectedEntry `json:"entries"` + // Destination kind that was written. + Kind DebugCollectLogsResultKind `json:"kind"` + // Actual archive path or staging directory path written. This may differ from the requested + // path when no-overwrite suffixing or fallback-to-temp-directory was needed. + Path string `json:"path"` + // Optional files or directories that could not be included. + SkippedEntries []DebugCollectLogsSkippedEntry `json:"skippedEntries,omitzero"` +} + +// An optional debug bundle entry that could not be included. +// Experimental: DebugCollectLogsSkippedEntry is part of an experimental API and may change +// or be removed. +type DebugCollectLogsSkippedEntry struct { + // Relative path requested for this bundle entry. + BundlePath string `json:"bundlePath"` + // Server-local source path that could not be read. + Path *string `json:"path,omitempty"` + // Reason the entry was skipped. + Reason string `json:"reason"` +} + // Canvas available in the current session. // Experimental: DiscoveredCanvas is part of an experimental API and may change or be // removed. @@ -1265,11 +1784,16 @@ type DiscoveredCanvas struct { ExtensionID string `json:"extensionId"` // Owning extension display name, when available ExtensionName *string `json:"extensionName,omitempty"` + // Host-local PNG path for the canvas icon, when supplied + Icon *string `json:"icon,omitempty"` // JSON Schema for canvas open input InputSchema any `json:"inputSchema,omitempty"` } -// Schema for the `DiscoveredMcpServer` type. +// MCP server discovered by `mcp.discover`, with config source, optional plugin source, +// transport type, and enabled state. +// Experimental: DiscoveredMCPServer is part of an experimental API and may change or be +// removed. type DiscoveredMCPServer struct { // Whether the server is enabled (not in the disabled list) Enabled bool `json:"enabled"` @@ -1397,7 +1921,8 @@ type ExecuteCommandResult struct { Error *string `json:"error,omitempty"` } -// Schema for the `Extension` type. +// Discovered extension metadata, including source-qualified ID, name, discovery source, +// status, and optional process ID. // Experimental: Extension is part of an experimental API and may change or be removed. type Extension struct { // Source-qualified ID (e.g., 'project:my-ext', 'user:auth-helper', @@ -1467,6 +1992,10 @@ type ExternalToolTextResultForLlm struct { SessionLog *string `json:"sessionLog,omitempty"` // Text result returned to the model TextResultForLlm string `json:"textResultForLlm"` + // Tool references returned by a tool-search override: names of deferred tools to surface to + // the model. When set, the tool result is materialized as `tool_reference` content blocks + // (rather than plain text) so the model knows which deferred tools are now available. + ToolReferences []string `json:"toolReferences,omitzero"` // Optional tool-specific telemetry ToolTelemetry map[string]any `json:"toolTelemetry,omitzero"` } @@ -1575,6 +2104,28 @@ func (ExternalToolTextResultForLlmContentResourceLink) Type() ExternalToolTextRe return ExternalToolTextResultForLlmContentTypeResourceLink } +// Shell command exit metadata with optional output preview +// Experimental: ExternalToolTextResultForLlmContentShellExit is part of an experimental API +// and may change or be removed. +type ExternalToolTextResultForLlmContentShellExit struct { + // Working directory where the shell command was executed + Cwd *string `json:"cwd,omitempty"` + // Exit code from the completed shell command + ExitCode int64 `json:"exitCode"` + // Output associated with this shell command, if available. May be partial, truncated, or a + // preview; not guaranteed to be full output. + OutputPreview *string `json:"outputPreview,omitempty"` + // Whether outputPreview is known to be incomplete or truncated + OutputTruncated *bool `json:"outputTruncated,omitempty"` + // Shell id, as assigned by Copilot runtime + ShellID string `json:"shellId"` +} + +func (ExternalToolTextResultForLlmContentShellExit) externalToolTextResultForLlmContent() {} +func (ExternalToolTextResultForLlmContentShellExit) Type() ExternalToolTextResultForLlmContentType { + return ExternalToolTextResultForLlmContentTypeShellExit +} + // Terminal/shell output content block with optional exit code and working directory // Experimental: ExternalToolTextResultForLlmContentTerminal is part of an experimental API // and may change or be removed. @@ -1619,7 +2170,8 @@ type RawExternalToolTextResultForLlmContentResourceDetailsData struct { func (RawExternalToolTextResultForLlmContentResourceDetailsData) externalToolTextResultForLlmContentResourceDetails() { } -// Schema for the `EmbeddedBlobResourceContents` type. +// Embedded binary resource contents identified by a URI, with an optional MIME type and a +// base64-encoded blob. // Experimental: EmbeddedBlobResourceContents is part of an experimental API and may change // or be removed. type EmbeddedBlobResourceContents struct { @@ -1633,7 +2185,8 @@ type EmbeddedBlobResourceContents struct { func (EmbeddedBlobResourceContents) externalToolTextResultForLlmContentResourceDetails() {} -// Schema for the `EmbeddedTextResourceContents` type. +// Embedded text resource contents identified by a URI, with an optional MIME type and a +// text payload. // Experimental: EmbeddedTextResourceContents is part of an experimental API and may change // or be removed. type EmbeddedTextResourceContents struct { @@ -1663,6 +2216,7 @@ type ExternalToolTextResultForLlmContentResourceLinkIcon struct { // Content filtering mode to apply to all tools, or a map of tool name to content filtering // mode. +// Experimental: FilterMapping is part of an experimental API and may change or be removed. type FilterMapping interface { filterMapping() } @@ -1713,6 +2267,94 @@ type FolderTrustCheckResult struct { Trusted bool `json:"trusted"` } +// Pointer to a GitHub repository. +// Experimental: GitHubRepoRef is part of an experimental API and may change or be removed. +type GitHubRepoRef struct { + // Numeric GitHub repository id + ID *int64 `json:"id,omitempty"` + // Repository name (without owner) + Name string `json:"name"` + // Repository owner login (user or organization) + Owner string `json:"owner"` +} + +// Client environment metadata describing the process that produced a telemetry event. +// Experimental: GitHubTelemetryClientInfo is part of an experimental API and may change or +// be removed. +type GitHubTelemetryClientInfo struct { + // Name of the client application. + ClientName *string `json:"client_name,omitempty"` + // Type of client. + ClientType *string `json:"client_type,omitempty"` + // Copilot CLI version string. + CLIVersion string `json:"cli_version"` + // Copilot subscription plan, when known. + CopilotPlan *string `json:"copilot_plan,omitempty"` + // Stable machine identifier for the device. + DevDeviceID *string `json:"dev_device_id,omitempty"` + // Whether the user is a GitHub/Microsoft staff member. + IsStaff *bool `json:"is_staff,omitempty"` + // Node.js runtime version string. + NodeVersion string `json:"node_version"` + // Operating system architecture (e.g. arm64, x64). + OsArch string `json:"os_arch"` + // Operating system platform (e.g. darwin, linux, win32). + OsPlatform string `json:"os_platform"` + // Operating system version string. + OsVersion string `json:"os_version"` +} + +// A single telemetry event in the runtime's native GitHub-shaped telemetry format, +// forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing +// GitHubTelemetryNotification distinguishes standard from restricted events; the payload +// shape is identical for both. +// Experimental: GitHubTelemetryEvent is part of an experimental API and may change or be +// removed. +type GitHubTelemetryEvent struct { + // Client environment metadata. + Client *GitHubTelemetryClientInfo `json:"client,omitempty"` + // Copilot tracking ID for user-level attribution. + CopilotTrackingID *string `json:"copilot_tracking_id,omitempty"` + // Timestamp when the event was created (ISO 8601 format). + CreatedAt *string `json:"created_at,omitempty"` + // Experiment assignment context. + ExpAssignmentContext *string `json:"exp_assignment_context,omitempty"` + // Feature flags enabled for this session, as a map from flag to value. + Features map[string]string `json:"features,omitzero"` + // Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed). + Kind string `json:"kind"` + // Numeric metrics as a map from key to value. + Metrics map[string]float64 `json:"metrics"` + // Reference to the model call that produced this event. + ModelCallID *string `json:"model_call_id,omitempty"` + // String-valued properties as a map from key to value. + Properties map[string]string `json:"properties"` + // Session identifier the event belongs to. + SessionID *string `json:"session_id,omitempty"` +} + +// Experimental: GitHubTelemetryEventResult is part of an experimental API and may change or +// be removed. +type GitHubTelemetryEventResult struct { +} + +// Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the +// runtime forwards to a host connection that opted into telemetry forwarding during the +// `server.connect` handshake. +// Experimental: GitHubTelemetryNotification is part of an experimental API and may change +// or be removed. +type GitHubTelemetryNotification struct { + // The telemetry event, in the runtime's native GitHub-shaped telemetry format. + Event GitHubTelemetryEvent `json:"event"` + // Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route + // restricted events to first-party Microsoft stores only. + Restricted bool `json:"restricted"` + // Session the telemetry event belongs to, when it is session-scoped. Omitted for + // sessionless events (for example, `server.sendTelemetry` calls with no session id), which + // are still forwarded to opted-in connections. + SessionID *string `json:"sessionId,omitempty"` +} + // Pending external tool call request ID, with the tool result or an error describing why it // failed. // Experimental: HandlePendingToolCallRequest is part of an experimental API and may change @@ -1821,7 +2463,28 @@ type HistoryTruncateResult struct { EventsRemoved int64 `json:"eventsRemoved"` } -// Schema for the `InstalledPlugin` type. +// Runtime-owned wire payload for a server-to-client hook callback invocation. +// Experimental: HookInvokeRequest is part of an experimental API and may change or be +// removed. +// Internal: HookInvokeRequest is an internal SDK API and is not part of the public surface. +type HookInvokeRequest struct { + // Internal: HookType is part of the SDK's internal API surface and is not intended for + // external use. + HookType HookType `json:"hookType"` + Input any `json:"input"` + SessionID string `json:"sessionId"` +} + +// Optional output returned by an SDK callback hook. +// Experimental: HookInvokeResponse is part of an experimental API and may change or be +// removed. +// Internal: HookInvokeResponse is an internal SDK API and is not part of the public surface. +type HookInvokeResponse struct { + Output any `json:"output,omitempty"` +} + +// Installed plugin record from global state, with marketplace, version, install time, +// enabled state, cache path, and source. // Experimental: InstalledPlugin is part of an experimental API and may change or be removed. type InstalledPlugin struct { // Path where the plugin is cached locally @@ -1844,6 +2507,10 @@ type InstalledPlugin struct { // Experimental: InstalledPluginInfo is part of an experimental API and may change or be // removed. type InstalledPluginInfo struct { + // Opaque, stable hash identifying a direct (non-marketplace) install source. Present only + // for direct repo / URL / local installs; absent for marketplace plugins. Same source + // yields the same id; distinct sources never collide. + DirectSourceID *string `json:"directSourceId,omitempty"` // Whether the plugin is currently enabled for new sessions Enabled bool `json:"enabled"` // Marketplace the plugin came from. Empty string ("") for direct repo / URL / local @@ -1865,7 +2532,8 @@ type InstalledPluginSource struct { String *string } -// Schema for the `InstalledPluginSourceGitHub` type. +// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, +// and optional subpath. // Experimental: InstalledPluginSourceGitHub is part of an experimental API and may change // or be removed. type InstalledPluginSourceGitHub struct { @@ -1876,7 +2544,7 @@ type InstalledPluginSourceGitHub struct { Source InstalledPluginSourceGitHubSource `json:"source"` } -// Schema for the `InstalledPluginSourceLocal` type. +// Source descriptor for a direct local plugin install, with a local filesystem path. // Experimental: InstalledPluginSourceLocal is part of an experimental API and may change or // be removed. type InstalledPluginSourceLocal struct { @@ -1885,7 +2553,8 @@ type InstalledPluginSourceLocal struct { Source InstalledPluginSourceLocalSource `json:"source"` } -// Schema for the `InstalledPluginSourceUrl` type. +// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional +// subpath. // Experimental: InstalledPluginSourceURL is part of an experimental API and may change or // be removed. type InstalledPluginSourceURL struct { @@ -1896,7 +2565,8 @@ type InstalledPluginSourceURL struct { URL string `json:"url"` } -// Schema for the `InstructionDiscoveryPath` type. +// Canonical file or directory where custom instructions can be discovered or created, with +// location, kind, preference, and project path. // Experimental: InstructionDiscoveryPath is part of an experimental API and may change or // be removed. type InstructionDiscoveryPath struct { @@ -1955,7 +2625,8 @@ type InstructionsGetSourcesResult struct { Sources []InstructionSource `json:"sources"` } -// Schema for the `InstructionSource` type. +// Loaded instruction source for a session, including path, content, category, location, +// applicability, and optional description. // Experimental: InstructionSource is part of an experimental API and may change or be // removed. type InstructionSource struct { @@ -1992,6 +2663,8 @@ type InstructionSource struct { type LlmInferenceHeaders map[string][]string // A request body chunk or cancellation signal. +// Experimental: LlmInferenceHTTPRequestChunkRequest is part of an experimental API and may +// change or be removed. type LlmInferenceHTTPRequestChunkRequest struct { // When true, `data` is base64-encoded bytes. When absent or false, `data` is UTF-8 text. Binary *bool `json:"binary,omitempty"` @@ -2012,14 +2685,44 @@ type LlmInferenceHTTPRequestChunkRequest struct { // Acknowledgement. The SDK is free to ignore the ack and treat chunk delivery as // fire-and-forget. +// Experimental: LlmInferenceHTTPRequestChunkResult is part of an experimental API and may +// change or be removed. type LlmInferenceHTTPRequestChunkResult struct { } // The head of an outbound model-layer HTTP request. +// Experimental: LlmInferenceHTTPRequestStartRequest is part of an experimental API and may +// change or be removed. type LlmInferenceHTTPRequestStartRequest struct { + // Stable per-agent-instance id attributing this request to a specific agent trajectory. + // Present when the request originates from an agent turn; absent for requests issued + // outside any agent context (e.g. some SDK callers). A request with an `agentId` but no + // `parentAgentId` is a root-agent request; one carrying both is a subagent request. Sourced + // from the runtime's per-request agent context and surfaced on the envelope independently + // of transport, so it is available for both first-party (CAPI) and BYOK/custom-provider + // requests; on the CAPI transport the runtime derives the upstream `X-Agent-Task-Id` header + // from this same context. Consumers routing each provider call to a training trajectory + // should key on this rather than on lifecycle events, since it is available on the request + // path before sampling. + AgentID *string `json:"agentId,omitempty"` Headers map[string][]string `json:"headers"` + // Coarse classification of the interaction that produced this request. Open string for + // forward-compatibility; known values include `conversation-agent`, + // `conversation-subagent`, `conversation-sampling`, `conversation-background`, + // `conversation-compaction`, and `conversation-user`. Absent when the runtime did not + // classify the request. Comes from the runtime's per-request agent context independently of + // transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` + // header from this same context. + InteractionType *string `json:"interactionType,omitempty"` // HTTP method, e.g. GET, POST. Method string `json:"method"` + // Id of the parent agent that spawned the agent issuing this request. Present only for + // subagent requests; absent for root-agent requests and non-agent requests. Combined with + // `agentId`, this lets consumers attribute a call to a child trajectory versus the root. + // Like `agentId`, it comes from the runtime's per-request agent context independently of + // transport; on the CAPI transport the runtime derives the upstream `X-Parent-Agent-Id` + // header from this same context. + ParentAgentID *string `json:"parentAgentId,omitempty"` // Opaque runtime-minted id, unique per in-flight request. The SDK uses this to correlate // httpRequestChunk frames and to address its httpResponseStart / httpResponseChunk replies // back to the runtime. @@ -2042,6 +2745,8 @@ type LlmInferenceHTTPRequestStartRequest struct { // Acknowledgement. Returning successfully simply means the SDK accepted the start frame; it // does not imply the request will succeed. +// Experimental: LlmInferenceHTTPRequestStartResult is part of an experimental API and may +// change or be removed. type LlmInferenceHTTPRequestStartResult struct { } @@ -2113,7 +2818,8 @@ type LlmInferenceSetProviderResult struct { Success bool `json:"success"` } -// Schema for the `LocalSessionMetadataValue` type. +// Persisted local session metadata, including identifiers, timestamps, summary/name, +// client, context, detached state, and task ID. // Experimental: LocalSessionMetadataValue is part of an experimental API and may change or // be removed. type LocalSessionMetadataValue struct { @@ -2229,7 +2935,8 @@ type MarketplacePluginInfo struct { Name string `json:"name"` } -// Schema for the `MarketplaceRefreshEntry` type. +// Per-marketplace refresh result, including marketplace name, success flag, and optional +// failure error. // Experimental: MarketplaceRefreshEntry is part of an experimental API and may change or be // removed. type MarketplaceRefreshEntry struct { @@ -2260,7 +2967,7 @@ type MarketplaceRemoveResult struct { Removed bool `json:"removed"` } -// Schema for the `McpAllowedServer` type. +// MCP server allowed by policy, with server name and optional PII-free explanatory note. // Experimental: MCPAllowedServer is part of an experimental API and may change or be // removed. type MCPAllowedServer struct { @@ -2396,7 +3103,8 @@ type MCPAppsReadResourceResult struct { Contents []MCPAppsResourceContent `json:"contents"` } -// Schema for the `McpAppsResourceContent` type. +// MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource +// metadata. // Experimental: MCPAppsResourceContent is part of an experimental API and may change or be // removed. type MCPAppsResourceContent struct { @@ -2460,6 +3168,8 @@ type MCPCancelSamplingExecutionResult struct { } // MCP server name and configuration to add to user configuration. +// Experimental: MCPConfigAddRequest is part of an experimental API and may change or be +// removed. type MCPConfigAddRequest struct { // MCP server configuration (stdio process or remote HTTP/SSE) Config MCPServerConfig `json:"config"` @@ -2467,10 +3177,14 @@ type MCPConfigAddRequest struct { Name string `json:"name"` } +// Experimental: MCPConfigAddResult is part of an experimental API and may change or be +// removed. type MCPConfigAddResult struct { } // MCP server names to disable for new sessions. +// Experimental: MCPConfigDisableRequest is part of an experimental API and may change or be +// removed. type MCPConfigDisableRequest struct { // Names of MCP servers to disable. Each server is added to the persisted disabled list so // new sessions skip it. Already-disabled names are ignored. Active sessions keep their @@ -2478,38 +3192,53 @@ type MCPConfigDisableRequest struct { Names []string `json:"names"` } +// Experimental: MCPConfigDisableResult is part of an experimental API and may change or be +// removed. type MCPConfigDisableResult struct { } // MCP server names to enable for new sessions. +// Experimental: MCPConfigEnableRequest is part of an experimental API and may change or be +// removed. type MCPConfigEnableRequest struct { // Names of MCP servers to enable. Each server is removed from the persisted disabled list // so new sessions spawn it. Unknown or already-enabled names are ignored. Names []string `json:"names"` } +// Experimental: MCPConfigEnableResult is part of an experimental API and may change or be +// removed. type MCPConfigEnableResult struct { } // User-configured MCP servers, keyed by server name. +// Experimental: MCPConfigList is part of an experimental API and may change or be removed. type MCPConfigList struct { // All MCP servers from user config, keyed by name Servers map[string]MCPServerConfig `json:"servers"` } +// Experimental: MCPConfigReloadResult is part of an experimental API and may change or be +// removed. type MCPConfigReloadResult struct { } // MCP server name to remove from user configuration. +// Experimental: MCPConfigRemoveRequest is part of an experimental API and may change or be +// removed. type MCPConfigRemoveRequest struct { // Name of the MCP server to remove Name string `json:"name"` } +// Experimental: MCPConfigRemoveResult is part of an experimental API and may change or be +// removed. type MCPConfigRemoveResult struct { } // MCP server name and replacement configuration to write to user configuration. +// Experimental: MCPConfigUpdateRequest is part of an experimental API and may change or be +// removed. type MCPConfigUpdateRequest struct { // MCP server configuration (stdio process or remote HTTP/SSE) Config MCPServerConfig `json:"config"` @@ -2517,6 +3246,8 @@ type MCPConfigUpdateRequest struct { Name string `json:"name"` } +// Experimental: MCPConfigUpdateResult is part of an experimental API and may change or be +// removed. type MCPConfigUpdateResult struct { } @@ -2548,12 +3279,16 @@ type MCPDisableRequest struct { } // Optional working directory used as context for MCP server discovery. +// Experimental: MCPDiscoverRequest is part of an experimental API and may change or be +// removed. type MCPDiscoverRequest struct { // Working directory used as context for discovery (e.g., plugin resolution) WorkingDirectory *string `json:"workingDirectory,omitempty"` } // MCP servers discovered from user, workspace, plugin, and built-in sources. +// Experimental: MCPDiscoverResult is part of an experimental API and may change or be +// removed. type MCPDiscoverResult struct { // MCP servers discovered from all sources Servers []DiscoveredMCPServer `json:"servers"` @@ -2603,7 +3338,8 @@ type MCPExecuteSamplingRequest struct { type MCPExecuteSamplingResult struct { } -// Schema for the `McpFilteredServer` type. +// MCP server filtered by policy, with name, reason, optional redacted reason, and +// enterprise login. // Experimental: MCPFilteredServer is part of an experimental API and may change or be // removed. type MCPFilteredServer struct { @@ -2617,6 +3353,65 @@ type MCPFilteredServer struct { RedactedReason *string `json:"redactedReason,omitempty"` } +// Host response: supply dynamic headers or decline this refresh. +// Experimental: MCPHeadersHandlePendingHeadersRefreshRequest is part of an experimental API +// and may change or be removed. +type MCPHeadersHandlePendingHeadersRefreshRequest interface { + mcpHeadersHandlePendingHeadersRefreshRequest() + Kind() MCPHeadersHandlePendingHeadersRefreshRequestKind +} + +type RawMCPHeadersHandlePendingHeadersRefreshRequestData struct { + Discriminator MCPHeadersHandlePendingHeadersRefreshRequestKind + Raw json.RawMessage +} + +func (RawMCPHeadersHandlePendingHeadersRefreshRequestData) mcpHeadersHandlePendingHeadersRefreshRequest() { +} +func (r RawMCPHeadersHandlePendingHeadersRefreshRequestData) Kind() MCPHeadersHandlePendingHeadersRefreshRequestKind { + return r.Discriminator +} + +type MCPHeadersHandlePendingHeadersRefreshRequestHeaders struct { + // Headers to overlay onto the MCP request. Dynamic headers override static config headers + // but do not replace SDK-managed request headers. + Headers map[string]string `json:"headers"` +} + +func (MCPHeadersHandlePendingHeadersRefreshRequestHeaders) mcpHeadersHandlePendingHeadersRefreshRequest() { +} +func (MCPHeadersHandlePendingHeadersRefreshRequestHeaders) Kind() MCPHeadersHandlePendingHeadersRefreshRequestKind { + return MCPHeadersHandlePendingHeadersRefreshRequestKindHeaders +} + +type MCPHeadersHandlePendingHeadersRefreshRequestNone struct { +} + +func (MCPHeadersHandlePendingHeadersRefreshRequestNone) mcpHeadersHandlePendingHeadersRefreshRequest() { +} +func (MCPHeadersHandlePendingHeadersRefreshRequestNone) Kind() MCPHeadersHandlePendingHeadersRefreshRequestKind { + return MCPHeadersHandlePendingHeadersRefreshRequestKindNone +} + +// MCP headers refresh request id and the host response. +// Experimental: MCPHeadersHandlePendingHeadersRefreshRequestRequest is part of an +// experimental API and may change or be removed. +type MCPHeadersHandlePendingHeadersRefreshRequestRequest struct { + // Headers refresh request identifier from mcp.headers_refresh_required + RequestID string `json:"requestId"` + // Host response: supply dynamic headers or decline this refresh. + Result MCPHeadersHandlePendingHeadersRefreshRequest `json:"result"` +} + +// Indicates whether the pending MCP headers refresh response was accepted. +// Experimental: MCPHeadersHandlePendingHeadersRefreshRequestResult is part of an +// experimental API and may change or be removed. +type MCPHeadersHandlePendingHeadersRefreshRequestResult struct { + // Whether the response was accepted. False if the request was unknown, timed out, or + // already resolved. + Success bool `json:"success"` +} + // Host-level state, omitted when no MCP host is initialized. // Experimental: MCPHostState is part of an experimental API and may change or be removed. type MCPHostState struct { @@ -2768,8 +3563,6 @@ type MCPOauthPendingRequestResponseToken struct { AccessToken string `json:"accessToken"` // Token lifetime in seconds, if known. ExpiresIn *int64 `json:"expiresIn,omitempty"` - // Refresh token supplied by the host, if available. - RefreshToken *string `json:"refreshToken,omitempty"` // OAuth token type. Defaults to Bearer when omitted. TokenType *string `json:"tokenType,omitempty"` } @@ -2779,25 +3572,6 @@ func (MCPOauthPendingRequestResponseToken) Kind() MCPOauthPendingRequestResponse return MCPOauthPendingRequestResponseKindToken } -// MCP OAuth request id and optional provider response. -// Experimental: MCPOauthRespondRequest is part of an experimental API and may change or be -// removed. -type MCPOauthRespondRequest struct { - // In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be - // serialized across the JSON-RPC boundary. - // Internal: Provider is part of the SDK's internal API surface and is not intended for - // external use. - Provider any `json:"provider,omitempty"` - // OAuth request identifier from mcp.oauth_required - RequestID string `json:"requestId"` -} - -// Empty result after recording the MCP OAuth response. -// Experimental: MCPOauthRespondResult is part of an experimental API and may change or be -// removed. -type MCPOauthRespondResult struct { -} - // Registration parameters for an external MCP client. // Experimental: MCPRegisterExternalClientRequest is part of an experimental API and may // change or be removed. @@ -2843,43 +3617,200 @@ type MCPRemoveGitHubResult struct { Removed bool `json:"removed"` } -// Server name and opaque configuration for an individual MCP server restart. -// Experimental: MCPRestartServerRequest is part of an experimental API and may change or be -// removed. -type MCPRestartServerRequest struct { - // Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime - // shape supplied only by in-process CLI callers. - // Internal: Config is part of the SDK's internal API surface and is not intended for - // external use. - Config any `json:"config"` - // Name of the MCP server to restart - ServerName string `json:"serverName"` +// An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, +// MIME type, size, icons, annotations, and metadata. Server-provided fields outside the +// standard descriptor shape are exposed under `additionalProperties`. +// Experimental: MCPResource is part of an experimental API and may change or be removed. +type MCPResource struct { + // Server-provided non-standard descriptor fields preserved from the MCP response + AdditionalProperties map[string]any `json:"additionalProperties,omitzero"` + // Model/client annotations associated with this resource + Annotations *MCPResourceAnnotations `json:"annotations,omitempty"` + // Optional description of what this resource represents + Description *string `json:"description,omitempty"` + // Icons associated with this resource + Icons []MCPResourceIcon `json:"icons,omitzero"` + // Resource-level metadata + Meta map[string]any `json:"_meta,omitzero"` + // MIME type of the resource, if known + MIMEType *string `json:"mimeType,omitempty"` + // The programmatic name of the resource + Name string `json:"name"` + // Resource size in bytes, when known + Size *int64 `json:"size,omitempty"` + // Optional human-readable display title + Title *string `json:"title,omitempty"` + // The resource URI (e.g. ui://... or file:///...) + URI string `json:"uri"` } -// Outcome of an MCP sampling execution: success result, failure error, or cancellation. -// Experimental: MCPSamplingExecutionResult is part of an experimental API and may change or -// be removed. -type MCPSamplingExecutionResult struct { - // Outcome of the sampling inference. 'success' produced a response; 'failure' encountered - // an error (including agent-side rejection by content filter or criteria); 'cancelled' the - // caller cancelled this execution via cancelSamplingExecution. - Action MCPSamplingExecutionAction `json:"action"` - // Error description, present when action='failure'. - Error *string `json:"error,omitempty"` - // MCP CreateMessageResult payload (with optional 'tools' extension), present when - // action='success'. Treated as opaque at the schema layer; consumers should - // construct/consume it per the MCP CreateMessageResult shape. - Result *MCPExecuteSamplingResult `json:"result,omitempty"` +// Standard MCP resource annotations plus preserved non-standard annotation fields. +// Experimental: MCPResourceAnnotations is part of an experimental API and may change or be +// removed. +type MCPResourceAnnotations struct { + // Server-provided non-standard annotation fields preserved from the MCP response + AdditionalProperties map[string]any `json:"additionalProperties,omitzero"` + // Intended audience roles for this resource + Audience []string `json:"audience,omitzero"` + // Last-modified timestamp hint + LastModified *string `json:"lastModified,omitempty"` + // Priority hint for model/client use + Priority *float64 `json:"priority,omitempty"` } -// Schema for the `McpServer` type. -// Experimental: MCPServer is part of an experimental API and may change or be removed. -type MCPServer struct { - // Error message if the server failed to connect - Error *string `json:"error,omitempty"` - // Server name (config key) - Name string `json:"name"` - // Configuration source: user, workspace, plugin, or builtin +// MCP resource content with URI, optional MIME type, text or base64 blob, and resource +// metadata. +// Experimental: MCPResourceContent is part of an experimental API and may change or be +// removed. +type MCPResourceContent struct { + // Base64-encoded binary content + Blob *string `json:"blob,omitempty"` + // Resource-level metadata (CSP, permissions, etc.) + Meta map[string]any `json:"_meta,omitzero"` + // MIME type of the content + MIMEType *string `json:"mimeType,omitempty"` + // Text content (e.g. HTML) + Text *string `json:"text,omitempty"` + // The resource URI + URI string `json:"uri"` +} + +// A resource icon descriptor plus preserved non-standard icon fields. +// Experimental: MCPResourceIcon is part of an experimental API and may change or be removed. +type MCPResourceIcon struct { + // Server-provided non-standard icon fields preserved from the MCP response + AdditionalProperties map[string]any `json:"additionalProperties,omitzero"` + // Icon MIME type, when known + MIMEType *string `json:"mimeType,omitempty"` + // Icon sizes hint + Sizes *string `json:"sizes,omitempty"` + // Icon URI + Src string `json:"src"` + // Theme hint for this icon + Theme *string `json:"theme,omitempty"` +} + +// MCP server whose resources to enumerate. +// Experimental: MCPResourcesListRequest is part of an experimental API and may change or be +// removed. +type MCPResourcesListRequest struct { + // Opaque MCP pagination cursor from a prior `nextCursor` value + Cursor *string `json:"cursor,omitempty"` + // Name of the MCP server whose resources to enumerate + ServerName string `json:"serverName"` +} + +// One page of resources advertised by the named MCP server. +// Experimental: MCPResourcesListResult is part of an experimental API and may change or be +// removed. +type MCPResourcesListResult struct { + // Opaque cursor for the next page, if the server has more resources + NextCursor *string `json:"nextCursor,omitempty"` + // Resources advertised by the server (proxied MCP `resources/list`) + Resources []MCPResource `json:"resources"` +} + +// MCP server whose resource templates to enumerate. +// Experimental: MCPResourcesListTemplatesRequest is part of an experimental API and may +// change or be removed. +type MCPResourcesListTemplatesRequest struct { + // Opaque MCP pagination cursor from a prior `nextCursor` value + Cursor *string `json:"cursor,omitempty"` + // Name of the MCP server whose resource templates to enumerate + ServerName string `json:"serverName"` +} + +// One page of resource templates advertised by the named MCP server. +// Experimental: MCPResourcesListTemplatesResult is part of an experimental API and may +// change or be removed. +type MCPResourcesListTemplatesResult struct { + // Opaque cursor for the next page, if the server has more resource templates + NextCursor *string `json:"nextCursor,omitempty"` + // Resource templates advertised by the server (proxied MCP `resources/templates/list`) + ResourceTemplates []MCPResourceTemplate `json:"resourceTemplates"` +} + +// MCP server and resource URI to fetch. +// Experimental: MCPResourcesReadRequest is part of an experimental API and may change or be +// removed. +type MCPResourcesReadRequest struct { + // Name of the MCP server hosting the resource + ServerName string `json:"serverName"` + // Resource URI + URI string `json:"uri"` +} + +// Resource contents returned by the MCP server. +// Experimental: MCPResourcesReadResult is part of an experimental API and may change or be +// removed. +type MCPResourcesReadResult struct { + // Resource contents returned by the server + Contents []MCPResourceContent `json:"contents"` +} + +// An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, +// name, and optional title, description, MIME type, icons, annotations, and metadata. +// Server-provided fields outside the standard descriptor shape are exposed under +// `additionalProperties`. +// Experimental: MCPResourceTemplate is part of an experimental API and may change or be +// removed. +type MCPResourceTemplate struct { + // Server-provided non-standard descriptor fields preserved from the MCP response + AdditionalProperties map[string]any `json:"additionalProperties,omitzero"` + // Model/client annotations associated with this template + Annotations *MCPResourceAnnotations `json:"annotations,omitempty"` + // Optional description of what this template is for + Description *string `json:"description,omitempty"` + // Icons associated with resources matching this template + Icons []MCPResourceIcon `json:"icons,omitzero"` + // Resource-template-level metadata + Meta map[string]any `json:"_meta,omitzero"` + // MIME type for resources matching this template, if uniform + MIMEType *string `json:"mimeType,omitempty"` + // The programmatic name of the resource template + Name string `json:"name"` + // Optional human-readable display title + Title *string `json:"title,omitempty"` + // An RFC 6570 URI template for constructing resource URIs + URITemplate string `json:"uriTemplate"` +} + +// Server name and optional replacement configuration for an individual MCP server restart. +// Omit `config` for a config-free restart-by-name of an already-configured server. +// Experimental: MCPRestartServerRequest is part of an experimental API and may change or be +// removed. +type MCPRestartServerRequest struct { + // Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart + // the server with its already-registered configuration (config-free restart-by-name). + Config MCPServerConfig `json:"config,omitempty"` + // Name of the MCP server to restart + ServerName string `json:"serverName"` +} + +// Outcome of an MCP sampling execution: success result, failure error, or cancellation. +// Experimental: MCPSamplingExecutionResult is part of an experimental API and may change or +// be removed. +type MCPSamplingExecutionResult struct { + // Outcome of the sampling inference. 'success' produced a response; 'failure' encountered + // an error (including agent-side rejection by content filter or criteria); 'cancelled' the + // caller cancelled this execution via cancelSamplingExecution. + Action MCPSamplingExecutionAction `json:"action"` + // Error description, present when action='failure'. + Error *string `json:"error,omitempty"` + // MCP CreateMessageResult payload (with optional 'tools' extension), present when + // action='success'. Treated as opaque at the schema layer; consumers should + // construct/consume it per the MCP CreateMessageResult shape. + Result *MCPExecuteSamplingResult `json:"result,omitempty"` +} + +// MCP server status entry, including config source/plugin source and any connection error. +// Experimental: MCPServer is part of an experimental API and may change or be removed. +type MCPServer struct { + // Error message if the server failed to connect + Error *string `json:"error,omitempty"` + // Server name (config key) + Name string `json:"name"` + // Configuration source: user, workspace, plugin, or builtin Source *MCPServerSource `json:"source,omitempty"` // Plugin name that provided this server, when source is plugin. SourcePlugin *string `json:"sourcePlugin,omitempty"` @@ -2890,6 +3821,8 @@ type MCPServer struct { } // Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. +// Experimental: MCPServerAuthConfig is part of an experimental API and may change or be +// removed. type MCPServerAuthConfig interface { mcpServerAuthConfig() } @@ -2901,12 +3834,15 @@ func (MCPServerAuthConfigBoolean) mcpServerAuthConfig() {} func (MCPServerAuthConfigRedirectPort) mcpServerAuthConfig() {} // Authentication settings with optional redirect port configuration. +// Experimental: MCPServerAuthConfigRedirectPort is part of an experimental API and may +// change or be removed. type MCPServerAuthConfigRedirectPort struct { // Fixed port for the OAuth redirect callback server. RedirectPort *int32 `json:"redirectPort,omitempty"` } // MCP server configuration (stdio process or remote HTTP/SSE) +// Experimental: MCPServerConfig is part of an experimental API and may change or be removed. type MCPServerConfig interface { mcpServerConfig() } @@ -2918,6 +3854,8 @@ type RawMCPServerConfigData struct { func (RawMCPServerConfigData) mcpServerConfig() {} // Remote MCP server configuration accessed over HTTP or SSE. +// Experimental: MCPServerConfigHTTP is part of an experimental API and may change or be +// removed. type MCPServerConfigHTTP struct { // Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. Auth MCPServerAuthConfig `json:"auth,omitempty"` @@ -2953,6 +3891,8 @@ type MCPServerConfigHTTP struct { func (MCPServerConfigHTTP) mcpServerConfig() {} // Stdio MCP server configuration launched as a child process. +// Experimental: MCPServerConfigStdio is part of an experimental API and may change or be +// removed. type MCPServerConfigStdio struct { // Command-line arguments passed to the Stdio MCP server process. Args []string `json:"args,omitzero"` @@ -3030,15 +3970,12 @@ type MCPSetEnvValueModeResult struct { Mode MCPSetEnvValueModeDetails `json:"mode"` } -// Server name and opaque configuration for an individual MCP server start. +// Server name and configuration for an individual MCP server start. // Experimental: MCPStartServerRequest is part of an experimental API and may change or be // removed. type MCPStartServerRequest struct { - // Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime - // shape supplied only by in-process CLI callers. - // Internal: Config is part of the SDK's internal API surface and is not intended for - // external use. - Config any `json:"config"` + // MCP server configuration (stdio process or remote HTTP/SSE) + Config MCPServerConfig `json:"config"` // Name of the MCP server to start ServerName string `json:"serverName"` } @@ -3061,13 +3998,27 @@ type MCPStopServerRequest struct { ServerName string `json:"serverName"` } -// Schema for the `McpTools` type. +// MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery +// metadata. // Experimental: MCPTools is part of an experimental API and may change or be removed. type MCPTools struct { // Tool description, when provided. Description *string `json:"description,omitempty"` // Tool name. Name string `json:"name"` + // Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` + // block was present without recognized fields. + UI *MCPToolUI `json:"ui,omitempty"` +} + +// Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. +// Experimental: MCPToolUI is part of an experimental API and may change or be removed. +type MCPToolUI struct { + // URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use + // `session.mcp.resources.read` to fetch its HTML and resource metadata. + ResourceURI *string `json:"resourceUri,omitempty"` + // Tool visibility advertised by the server. When absent, MCP Apps defaults apply. + Visibility []MCPToolUIVisibility `json:"visibility,omitzero"` } // Server name identifying the external client to remove. @@ -3086,6 +4037,35 @@ type MemoryConfiguration struct { Enabled bool `json:"enabled"` } +// Per-source attribution breakdown for the session's current context window, or null if +// uninitialized. +// Experimental: MetadataContextAttributionResult is part of an experimental API and may +// change or be removed. +type MetadataContextAttributionResult struct { + // Per-source context-window attribution, or null if the session has not yet been + // initialized (no system prompt or tool metadata cached). + ContextAttribution *SessionContextAttribution `json:"contextAttribution,omitempty"` +} + +// Parameters for the heaviest-messages query. +// Experimental: MetadataContextHeaviestMessagesRequest is part of an experimental API and +// may change or be removed. +type MetadataContextHeaviestMessagesRequest struct { + // Maximum number of messages to return, most-expensive first. Omit for the server default. + Limit *int64 `json:"limit,omitempty"` +} + +// The heaviest individual messages in the session's context window, most-expensive first. +// Experimental: MetadataContextHeaviestMessagesResult is part of an experimental API and +// may change or be removed. +type MetadataContextHeaviestMessagesResult struct { + // Heaviest messages, most-expensive first. + Messages []ContextHeaviestMessage `json:"messages"` + // Total token count of the current context window, so callers can compute each message's + // share without a second call. + TotalTokens int64 `json:"totalTokens"` +} + // Model identifier and token limits used to compute the context-info breakdown. // Experimental: MetadataContextInfoRequest is part of an experimental API and may change or // be removed. @@ -3162,7 +4142,10 @@ type MetadataRecordContextChangeRequest struct { type MetadataRecordContextChangeResult struct { } -// Absolute path to set as the session's new working directory. +// Absolute path to set as the session's new working directory. For local sessions the path +// must be absolute and exist on disk: it is validated before any session state changes, and +// a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote +// sessions record the path as-is. // Experimental: MetadataSetWorkingDirectoryRequest is part of an experimental API and may // change or be removed. type MetadataSetWorkingDirectoryRequest struct { @@ -3173,9 +4156,13 @@ type MetadataSetWorkingDirectoryRequest struct { } // Update the session's working directory. Used by the host when the user explicitly changes -// cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any -// related side-effects (file index, etc.); this method only updates the session's own -// recorded path. +// cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects +// (file index, etc.); it does NOT change the process working directory (a session's cwd is +// per-session, not process-global). For local sessions the runtime validates the target +// first (an absolute path that exists on disk) and re-bases the permission primary +// directory; a rejected validation fails the call before anything is mutated, persisted, or +// emitted. Location-scoped permission rules are then re-keyed to the new directory +// (best-effort). Remote sessions only record the path. // Experimental: MetadataSetWorkingDirectoryResult is part of an experimental API and may // change or be removed. type MetadataSetWorkingDirectoryResult struct { @@ -3212,7 +4199,9 @@ type MetadataSnapshotRemoteMetadataRepository struct { Owner string `json:"owner"` } -// Schema for the `Model` type. +// Copilot model metadata, including identifier, display name, capabilities, policy, +// billing, reasoning efforts, and picker categories. +// Experimental: Model is part of an experimental API and may change or be removed. type Model struct { // Billing information Billing *ModelBilling `json:"billing,omitempty"` @@ -3235,14 +4224,41 @@ type Model struct { } // Billing information +// Experimental: ModelBilling is part of an experimental API and may change or be removed. type ModelBilling struct { + // Whole-number percentage discount (0-100) applied to usage billed through this model. + // Populated for the synthetic `auto` model, where requests routed by auto-mode are billed + // at a reduced rate; absent for concrete models. + DiscountPercent *int32 `json:"discountPercent,omitempty"` // Billing cost multiplier relative to the base rate Multiplier *float64 `json:"multiplier,omitempty"` + // Active server-driven promotion for this model, if any. Present when the model is being + // promoted with a time-boxed discount. + Promo *ModelBillingPromo `json:"promo,omitempty"` // Token-level pricing information for this model TokenPrices *ModelBillingTokenPrices `json:"tokenPrices,omitempty"` } +// Active server-driven promotion for a model, including its discount and expiry. +// Experimental: ModelBillingPromo is part of an experimental API and may change or be +// removed. +type ModelBillingPromo struct { + // Percentage discount (0-100) applied while the promotion is active. May be fractional. + DiscountPercent *float64 `json:"discountPercent,omitempty"` + // UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only + // surfaces a promo whose expiry parses and is in the future. Consumers should treat a past + // value as expired. + EndsAt string `json:"endsAt"` + // Stable identifier for the promotion campaign. + ID *string `json:"id,omitempty"` + // Human-readable promotion message. Does not include the expiry timestamp; consumers may + // format endsAt and append it. + Message *string `json:"message,omitempty"` +} + // Token-level pricing information for this model +// Experimental: ModelBillingTokenPrices is part of an experimental API and may change or be +// removed. type ModelBillingTokenPrices struct { // Number of tokens per standard billing batch BatchSize *int64 `json:"batchSize,omitempty"` @@ -3269,6 +4285,8 @@ type ModelBillingTokenPrices struct { } // Long context tier pricing (available for models with extended context windows) +// Experimental: ModelBillingTokenPricesLongContext is part of an experimental API and may +// change or be removed. type ModelBillingTokenPricesLongContext struct { // Use cacheReadPrice instead. AI Credits cost per billing batch of cached tokens // Deprecated: CachePrice is deprecated. @@ -3291,6 +4309,8 @@ type ModelBillingTokenPricesLongContext struct { } // Model capabilities and limits +// Experimental: ModelCapabilities is part of an experimental API and may change or be +// removed. type ModelCapabilities struct { // Token limits for prompts, outputs, and context window Limits *ModelCapabilitiesLimits `json:"limits,omitempty"` @@ -3299,6 +4319,8 @@ type ModelCapabilities struct { } // Token limits for prompts, outputs, and context window +// Experimental: ModelCapabilitiesLimits is part of an experimental API and may change or be +// removed. type ModelCapabilitiesLimits struct { // Maximum total context window size in tokens MaxContextWindowTokens *int64 `json:"max_context_window_tokens,omitempty"` @@ -3311,6 +4333,8 @@ type ModelCapabilitiesLimits struct { } // Vision-specific limits +// Experimental: ModelCapabilitiesLimitsVision is part of an experimental API and may change +// or be removed. type ModelCapabilitiesLimitsVision struct { // Maximum number of images per prompt MaxPromptImages int64 `json:"max_prompt_images"` @@ -3360,6 +4384,9 @@ type ModelCapabilitiesOverrideLimitsVision struct { // Experimental: ModelCapabilitiesOverrideSupports is part of an experimental API and may // change or be removed. type ModelCapabilitiesOverrideSupports struct { + // Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. + // 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + AdaptiveThinking *AdaptiveThinkingSupport `json:"adaptive_thinking,omitempty"` // Whether this model supports reasoning effort configuration ReasoningEffort *bool `json:"reasoningEffort,omitempty"` // Whether this model supports vision/image input @@ -3367,7 +4394,12 @@ type ModelCapabilitiesOverrideSupports struct { } // Feature flags indicating what the model supports +// Experimental: ModelCapabilitiesSupports is part of an experimental API and may change or +// be removed. type ModelCapabilitiesSupports struct { + // Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. + // 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + AdaptiveThinking *AdaptiveThinkingSupport `json:"adaptive_thinking,omitempty"` // Whether this model supports reasoning effort configuration ReasoningEffort *bool `json:"reasoningEffort,omitempty"` // Whether this model supports vision/image input @@ -3376,6 +4408,7 @@ type ModelCapabilitiesSupports struct { // List of Copilot models available to the resolved user, including capabilities and billing // metadata. +// Experimental: ModelList is part of an experimental API and may change or be removed. type ModelList struct { // List of available models with full metadata Models []Model `json:"models"` @@ -3390,6 +4423,7 @@ type ModelListRequest struct { } // Policy state (if applicable) +// Experimental: ModelPolicy is part of an experimental API and may change or be removed. type ModelPolicy struct { // Current policy state for this model State ModelPolicyState `json:"state"` @@ -3416,6 +4450,8 @@ type ModelSetReasoningEffortResult struct { ReasoningEffort string `json:"reasoningEffort"` } +// Experimental: ModelsListRequest is part of an experimental API and may change or be +// removed. type ModelsListRequest struct { // GitHub token for per-user model listing. When provided, resolves this token to determine // the user's Copilot plan and available models instead of using the global auth. @@ -3440,6 +4476,8 @@ type ModelSwitchToRequest struct { ReasoningEffort *string `json:"reasoningEffort,omitempty"` // Reasoning summary mode to request for supported model clients ReasoningSummary *ReasoningSummary `json:"reasoningSummary,omitempty"` + // Output verbosity level to request for supported models + Verbosity *Verbosity `json:"verbosity,omitempty"` } // The model identifier active on the session after the switch. @@ -3536,6 +4574,8 @@ type OpenCanvasInstance struct { ExtensionID string `json:"extensionId"` // Owning extension display name, when available ExtensionName *string `json:"extensionName,omitempty"` + // Host-local PNG path for the canvas icon, when supplied + Icon *string `json:"icon,omitempty"` // Input supplied when the instance was opened Input any `json:"input,omitempty"` // Stable caller-supplied canvas instance identifier @@ -3548,7 +4588,8 @@ type OpenCanvasInstance struct { URL *string `json:"url,omitempty"` } -// Schema for the `OptionsUpdateAdditionalContentExclusionPolicy` type. +// Content-exclusion policy supplied to `session.options.update`, with rules, last-updated +// data, and scope. // Experimental: OptionsUpdateAdditionalContentExclusionPolicy is part of an experimental // API and may change or be removed. type OptionsUpdateAdditionalContentExclusionPolicy struct { @@ -3558,18 +4599,21 @@ type OptionsUpdateAdditionalContentExclusionPolicy struct { Scope OptionsUpdateAdditionalContentExclusionPolicyScope `json:"scope"` } -// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRule` type. +// Single content-exclusion rule supplied to `session.options.update`, with paths, match +// conditions, and source. // Experimental: OptionsUpdateAdditionalContentExclusionPolicyRule is part of an // experimental API and may change or be removed. type OptionsUpdateAdditionalContentExclusionPolicyRule struct { IfAnyMatch []string `json:"ifAnyMatch,omitzero"` IfNoneMatch []string `json:"ifNoneMatch,omitzero"` Paths []string `json:"paths"` - // Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. + // Source descriptor for a `session.options.update` content-exclusion rule, with source name + // and type. Source OptionsUpdateAdditionalContentExclusionPolicyRuleSource `json:"source"` } -// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. +// Source descriptor for a `session.options.update` content-exclusion rule, with source name +// and type. // Experimental: OptionsUpdateAdditionalContentExclusionPolicyRuleSource is part of an // experimental API and may change or be removed. type OptionsUpdateAdditionalContentExclusionPolicyRuleSource struct { @@ -3577,7 +4621,8 @@ type OptionsUpdateAdditionalContentExclusionPolicyRuleSource struct { Type string `json:"type"` } -// Schema for the `PendingPermissionRequest` type. +// Pending permission prompt reconstructed from event history, with request ID and +// user-facing prompt details. // Experimental: PendingPermissionRequest is part of an experimental API and may change or // be removed. type PendingPermissionRequest struct { @@ -3617,7 +4662,7 @@ func (r RawPermissionDecisionData) Kind() PermissionDecisionKind { return r.Discriminator } -// Schema for the `PermissionDecisionApproved` type. +// Permission-decision variant indicating the request was approved. // Experimental: PermissionDecisionApproved is part of an experimental API and may change or // be removed. type PermissionDecisionApproved struct { @@ -3628,7 +4673,8 @@ func (PermissionDecisionApproved) Kind() PermissionDecisionKind { return PermissionDecisionKindApproved } -// Schema for the `PermissionDecisionApprovedForLocation` type. +// Permission-decision variant indicating approval was persisted for a project location, +// with approval details and location key. // Experimental: PermissionDecisionApprovedForLocation is part of an experimental API and // may change or be removed. type PermissionDecisionApprovedForLocation struct { @@ -3643,7 +4689,8 @@ func (PermissionDecisionApprovedForLocation) Kind() PermissionDecisionKind { return PermissionDecisionKindApprovedForLocation } -// Schema for the `PermissionDecisionApprovedForSession` type. +// Permission-decision variant indicating approval was remembered for the session, with +// approval details. // Experimental: PermissionDecisionApprovedForSession is part of an experimental API and may // change or be removed. type PermissionDecisionApprovedForSession struct { @@ -3656,7 +4703,8 @@ func (PermissionDecisionApprovedForSession) Kind() PermissionDecisionKind { return PermissionDecisionKindApprovedForSession } -// Schema for the `PermissionDecisionApproveForLocation` type. +// Permission-decision request variant to approve and persist a permission for a project +// location, with approval details and location key. // Experimental: PermissionDecisionApproveForLocation is part of an experimental API and may // change or be removed. type PermissionDecisionApproveForLocation struct { @@ -3671,7 +4719,8 @@ func (PermissionDecisionApproveForLocation) Kind() PermissionDecisionKind { return PermissionDecisionKindApproveForLocation } -// Schema for the `PermissionDecisionApproveForSession` type. +// Permission-decision request variant to approve for the rest of the session, with optional +// tool approval or URL domain. // Experimental: PermissionDecisionApproveForSession is part of an experimental API and may // change or be removed. type PermissionDecisionApproveForSession struct { @@ -3686,7 +4735,7 @@ func (PermissionDecisionApproveForSession) Kind() PermissionDecisionKind { return PermissionDecisionKindApproveForSession } -// Schema for the `PermissionDecisionApproveOnce` type. +// Permission-decision request variant to approve only the current permission request. // Experimental: PermissionDecisionApproveOnce is part of an experimental API and may change // or be removed. type PermissionDecisionApproveOnce struct { @@ -3697,7 +4746,7 @@ func (PermissionDecisionApproveOnce) Kind() PermissionDecisionKind { return PermissionDecisionKindApproveOnce } -// Schema for the `PermissionDecisionApprovePermanently` type. +// Permission-decision request variant to permanently approve a URL domain across sessions. // Experimental: PermissionDecisionApprovePermanently is part of an experimental API and may // change or be removed. type PermissionDecisionApprovePermanently struct { @@ -3710,7 +4759,8 @@ func (PermissionDecisionApprovePermanently) Kind() PermissionDecisionKind { return PermissionDecisionKindApprovePermanently } -// Schema for the `PermissionDecisionCancelled` type. +// Permission-decision variant indicating the request was cancelled before use, with an +// optional reason. // Experimental: PermissionDecisionCancelled is part of an experimental API and may change // or be removed. type PermissionDecisionCancelled struct { @@ -3723,7 +4773,8 @@ func (PermissionDecisionCancelled) Kind() PermissionDecisionKind { return PermissionDecisionKindCancelled } -// Schema for the `PermissionDecisionDeniedByContentExclusionPolicy` type. +// Permission-decision variant indicating denial by content-exclusion policy, with path and +// message. // Experimental: PermissionDecisionDeniedByContentExclusionPolicy is part of an experimental // API and may change or be removed. type PermissionDecisionDeniedByContentExclusionPolicy struct { @@ -3738,7 +4789,8 @@ func (PermissionDecisionDeniedByContentExclusionPolicy) Kind() PermissionDecisio return PermissionDecisionKindDeniedByContentExclusionPolicy } -// Schema for the `PermissionDecisionDeniedByPermissionRequestHook` type. +// Permission-decision variant indicating denial by a permission request hook, with optional +// message and interrupt flag. // Experimental: PermissionDecisionDeniedByPermissionRequestHook is part of an experimental // API and may change or be removed. type PermissionDecisionDeniedByPermissionRequestHook struct { @@ -3753,7 +4805,8 @@ func (PermissionDecisionDeniedByPermissionRequestHook) Kind() PermissionDecision return PermissionDecisionKindDeniedByPermissionRequestHook } -// Schema for the `PermissionDecisionDeniedByRules` type. +// Permission-decision variant indicating explicit denial by permission rules, with the +// matching rules. // Experimental: PermissionDecisionDeniedByRules is part of an experimental API and may // change or be removed. type PermissionDecisionDeniedByRules struct { @@ -3766,7 +4819,8 @@ func (PermissionDecisionDeniedByRules) Kind() PermissionDecisionKind { return PermissionDecisionKindDeniedByRules } -// Schema for the `PermissionDecisionDeniedInteractivelyByUser` type. +// Permission-decision variant indicating the user denied an interactive prompt, with +// optional feedback and force-reject flag. // Experimental: PermissionDecisionDeniedInteractivelyByUser is part of an experimental API // and may change or be removed. type PermissionDecisionDeniedInteractivelyByUser struct { @@ -3781,7 +4835,8 @@ func (PermissionDecisionDeniedInteractivelyByUser) Kind() PermissionDecisionKind return PermissionDecisionKindDeniedInteractivelyByUser } -// Schema for the `PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. +// Permission-decision variant indicating no approval rule matched and user confirmation was +// unavailable. // Experimental: PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser is part of // an experimental API and may change or be removed. type PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser struct { @@ -3792,7 +4847,8 @@ func (PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser) Kind() P return PermissionDecisionKindDeniedNoApprovalRuleAndCouldNotRequestFromUser } -// Schema for the `PermissionDecisionReject` type. +// Permission-decision request variant to reject a pending permission request, with optional +// feedback. // Experimental: PermissionDecisionReject is part of an experimental API and may change or // be removed. type PermissionDecisionReject struct { @@ -3805,7 +4861,7 @@ func (PermissionDecisionReject) Kind() PermissionDecisionKind { return PermissionDecisionKindReject } -// Schema for the `PermissionDecisionUserNotAvailable` type. +// Permission-decision variant indicating no user was available to confirm the request. // Experimental: PermissionDecisionUserNotAvailable is part of an experimental API and may // change or be removed. type PermissionDecisionUserNotAvailable struct { @@ -3835,7 +4891,7 @@ func (r RawPermissionDecisionApproveForLocationApprovalData) Kind() PermissionDe return r.Discriminator } -// Schema for the `PermissionDecisionApproveForLocationApprovalCommands` type. +// Location-scoped approval details for specific command identifiers. // Experimental: PermissionDecisionApproveForLocationApprovalCommands is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForLocationApprovalCommands struct { @@ -3849,7 +4905,7 @@ func (PermissionDecisionApproveForLocationApprovalCommands) Kind() PermissionDec return PermissionDecisionApproveForLocationApprovalKindCommands } -// Schema for the `PermissionDecisionApproveForLocationApprovalCustomTool` type. +// Location-scoped approval details for a custom tool, keyed by tool name. // Experimental: PermissionDecisionApproveForLocationApprovalCustomTool is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForLocationApprovalCustomTool struct { @@ -3863,7 +4919,8 @@ func (PermissionDecisionApproveForLocationApprovalCustomTool) Kind() PermissionD return PermissionDecisionApproveForLocationApprovalKindCustomTool } -// Schema for the `PermissionDecisionApproveForLocationApprovalExtensionManagement` type. +// Location-scoped approval details for extension-management operations, optionally narrowed +// by operation. // Experimental: PermissionDecisionApproveForLocationApprovalExtensionManagement is part of // an experimental API and may change or be removed. type PermissionDecisionApproveForLocationApprovalExtensionManagement struct { @@ -3878,8 +4935,8 @@ func (PermissionDecisionApproveForLocationApprovalExtensionManagement) Kind() Pe return PermissionDecisionApproveForLocationApprovalKindExtensionManagement } -// Schema for the `PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess` -// type. +// Location-scoped approval details for an extension's permission-gated capability access, +// keyed by extension name. // Experimental: PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess is // part of an experimental API and may change or be removed. type PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess struct { @@ -3893,7 +4950,8 @@ func (PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess) Kin return PermissionDecisionApproveForLocationApprovalKindExtensionPermissionAccess } -// Schema for the `PermissionDecisionApproveForLocationApprovalMcp` type. +// Location-scoped approval details for an MCP server tool, or all tools on the server when +// `toolName` is null. // Experimental: PermissionDecisionApproveForLocationApprovalMCP is part of an experimental // API and may change or be removed. type PermissionDecisionApproveForLocationApprovalMCP struct { @@ -3909,7 +4967,7 @@ func (PermissionDecisionApproveForLocationApprovalMCP) Kind() PermissionDecision return PermissionDecisionApproveForLocationApprovalKindMCP } -// Schema for the `PermissionDecisionApproveForLocationApprovalMcpSampling` type. +// Location-scoped approval details for MCP sampling requests from a server. // Experimental: PermissionDecisionApproveForLocationApprovalMCPSampling is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForLocationApprovalMCPSampling struct { @@ -3923,7 +4981,7 @@ func (PermissionDecisionApproveForLocationApprovalMCPSampling) Kind() Permission return PermissionDecisionApproveForLocationApprovalKindMCPSampling } -// Schema for the `PermissionDecisionApproveForLocationApprovalMemory` type. +// Location-scoped approval details for writes to long-term memory. // Experimental: PermissionDecisionApproveForLocationApprovalMemory is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForLocationApprovalMemory struct { @@ -3935,7 +4993,7 @@ func (PermissionDecisionApproveForLocationApprovalMemory) Kind() PermissionDecis return PermissionDecisionApproveForLocationApprovalKindMemory } -// Schema for the `PermissionDecisionApproveForLocationApprovalRead` type. +// Location-scoped approval details for read-only filesystem operations. // Experimental: PermissionDecisionApproveForLocationApprovalRead is part of an experimental // API and may change or be removed. type PermissionDecisionApproveForLocationApprovalRead struct { @@ -3947,7 +5005,7 @@ func (PermissionDecisionApproveForLocationApprovalRead) Kind() PermissionDecisio return PermissionDecisionApproveForLocationApprovalKindRead } -// Schema for the `PermissionDecisionApproveForLocationApprovalWrite` type. +// Location-scoped approval details for filesystem write operations. // Experimental: PermissionDecisionApproveForLocationApprovalWrite is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForLocationApprovalWrite struct { @@ -3978,7 +5036,7 @@ func (r RawPermissionDecisionApproveForSessionApprovalData) Kind() PermissionDec return r.Discriminator } -// Schema for the `PermissionDecisionApproveForSessionApprovalCommands` type. +// Session-scoped approval details for specific command identifiers. // Experimental: PermissionDecisionApproveForSessionApprovalCommands is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForSessionApprovalCommands struct { @@ -3992,7 +5050,7 @@ func (PermissionDecisionApproveForSessionApprovalCommands) Kind() PermissionDeci return PermissionDecisionApproveForSessionApprovalKindCommands } -// Schema for the `PermissionDecisionApproveForSessionApprovalCustomTool` type. +// Session-scoped approval details for a custom tool, keyed by tool name. // Experimental: PermissionDecisionApproveForSessionApprovalCustomTool is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForSessionApprovalCustomTool struct { @@ -4006,7 +5064,8 @@ func (PermissionDecisionApproveForSessionApprovalCustomTool) Kind() PermissionDe return PermissionDecisionApproveForSessionApprovalKindCustomTool } -// Schema for the `PermissionDecisionApproveForSessionApprovalExtensionManagement` type. +// Session-scoped approval details for extension-management operations, optionally narrowed +// by operation. // Experimental: PermissionDecisionApproveForSessionApprovalExtensionManagement is part of // an experimental API and may change or be removed. type PermissionDecisionApproveForSessionApprovalExtensionManagement struct { @@ -4021,8 +5080,8 @@ func (PermissionDecisionApproveForSessionApprovalExtensionManagement) Kind() Per return PermissionDecisionApproveForSessionApprovalKindExtensionManagement } -// Schema for the `PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess` -// type. +// Session-scoped approval details for an extension's permission-gated capability access, +// keyed by extension name. // Experimental: PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess is // part of an experimental API and may change or be removed. type PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess struct { @@ -4036,7 +5095,8 @@ func (PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess) Kind return PermissionDecisionApproveForSessionApprovalKindExtensionPermissionAccess } -// Schema for the `PermissionDecisionApproveForSessionApprovalMcp` type. +// Session-scoped approval details for an MCP server tool, or all tools on the server when +// `toolName` is null. // Experimental: PermissionDecisionApproveForSessionApprovalMCP is part of an experimental // API and may change or be removed. type PermissionDecisionApproveForSessionApprovalMCP struct { @@ -4051,7 +5111,7 @@ func (PermissionDecisionApproveForSessionApprovalMCP) Kind() PermissionDecisionA return PermissionDecisionApproveForSessionApprovalKindMCP } -// Schema for the `PermissionDecisionApproveForSessionApprovalMcpSampling` type. +// Session-scoped approval details for MCP sampling requests from a server. // Experimental: PermissionDecisionApproveForSessionApprovalMCPSampling is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForSessionApprovalMCPSampling struct { @@ -4065,7 +5125,7 @@ func (PermissionDecisionApproveForSessionApprovalMCPSampling) Kind() PermissionD return PermissionDecisionApproveForSessionApprovalKindMCPSampling } -// Schema for the `PermissionDecisionApproveForSessionApprovalMemory` type. +// Session-scoped approval details for writes to long-term memory. // Experimental: PermissionDecisionApproveForSessionApprovalMemory is part of an // experimental API and may change or be removed. type PermissionDecisionApproveForSessionApprovalMemory struct { @@ -4077,7 +5137,7 @@ func (PermissionDecisionApproveForSessionApprovalMemory) Kind() PermissionDecisi return PermissionDecisionApproveForSessionApprovalKindMemory } -// Schema for the `PermissionDecisionApproveForSessionApprovalRead` type. +// Session-scoped approval details for read-only filesystem operations. // Experimental: PermissionDecisionApproveForSessionApprovalRead is part of an experimental // API and may change or be removed. type PermissionDecisionApproveForSessionApprovalRead struct { @@ -4089,7 +5149,7 @@ func (PermissionDecisionApproveForSessionApprovalRead) Kind() PermissionDecision return PermissionDecisionApproveForSessionApprovalKindRead } -// Schema for the `PermissionDecisionApproveForSessionApprovalWrite` type. +// Session-scoped approval details for filesystem write operations. // Experimental: PermissionDecisionApproveForSessionApprovalWrite is part of an experimental // API and may change or be removed. type PermissionDecisionApproveForSessionApprovalWrite struct { @@ -4265,7 +5325,8 @@ type PermissionRequestResult struct { Success bool `json:"success"` } -// Schema for the `PermissionRule` type. +// A permission approval or denial rule matched against a tool request, identified by a rule +// kind with an optional argument value. // Experimental: PermissionRule is part of an experimental API and may change or be removed. type PermissionRule struct { // Argument value matched against the request, or null when the rule kind has no argument @@ -4286,7 +5347,8 @@ type PermissionRulesSet struct { Denied []PermissionRule `json:"denied"` } -// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. +// Content-exclusion policy supplied to `session.permissions.configure`, with rules, +// last-updated data, and scope. // Experimental: PermissionsConfigureAdditionalContentExclusionPolicy is part of an // experimental API and may change or be removed. type PermissionsConfigureAdditionalContentExclusionPolicy struct { @@ -4297,18 +5359,21 @@ type PermissionsConfigureAdditionalContentExclusionPolicy struct { Scope PermissionsConfigureAdditionalContentExclusionPolicyScope `json:"scope"` } -// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRule` type. +// Single content-exclusion rule supplied to `session.permissions.configure`, with paths, +// match conditions, and source. // Experimental: PermissionsConfigureAdditionalContentExclusionPolicyRule is part of an // experimental API and may change or be removed. type PermissionsConfigureAdditionalContentExclusionPolicyRule struct { IfAnyMatch []string `json:"ifAnyMatch,omitzero"` IfNoneMatch []string `json:"ifNoneMatch,omitzero"` Paths []string `json:"paths"` - // Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. + // Source descriptor for a `session.permissions.configure` content-exclusion rule, with + // source name and type. Source PermissionsConfigureAdditionalContentExclusionPolicyRuleSource `json:"source"` } -// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. +// Source descriptor for a `session.permissions.configure` content-exclusion rule, with +// source name and type. // Experimental: PermissionsConfigureAdditionalContentExclusionPolicyRuleSource is part of // an experimental API and may change or be removed. type PermissionsConfigureAdditionalContentExclusionPolicyRuleSource struct { @@ -4384,7 +5449,7 @@ func (r RawPermissionsLocationsAddToolApprovalDetailsData) Kind() PermissionsLoc return r.Discriminator } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsCommands` type. +// Location-persisted tool approval details for specific command identifiers. // Experimental: PermissionsLocationsAddToolApprovalDetailsCommands is part of an // experimental API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsCommands struct { @@ -4398,7 +5463,7 @@ func (PermissionsLocationsAddToolApprovalDetailsCommands) Kind() PermissionsLoca return PermissionsLocationsAddToolApprovalDetailsKindCommands } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsCustomTool` type. +// Location-persisted tool approval details for a custom tool, keyed by tool name. // Experimental: PermissionsLocationsAddToolApprovalDetailsCustomTool is part of an // experimental API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsCustomTool struct { @@ -4412,7 +5477,8 @@ func (PermissionsLocationsAddToolApprovalDetailsCustomTool) Kind() PermissionsLo return PermissionsLocationsAddToolApprovalDetailsKindCustomTool } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionManagement` type. +// Location-persisted tool approval details for extension-management operations, optionally +// narrowed by operation. // Experimental: PermissionsLocationsAddToolApprovalDetailsExtensionManagement is part of an // experimental API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsExtensionManagement struct { @@ -4427,7 +5493,8 @@ func (PermissionsLocationsAddToolApprovalDetailsExtensionManagement) Kind() Perm return PermissionsLocationsAddToolApprovalDetailsKindExtensionManagement } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess` type. +// Location-persisted tool approval details for an extension's permission-gated capability +// access, keyed by extension name. // Experimental: PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess is part // of an experimental API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess struct { @@ -4441,7 +5508,8 @@ func (PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess) Kind( return PermissionsLocationsAddToolApprovalDetailsKindExtensionPermissionAccess } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsMcp` type. +// Location-persisted tool approval details for an MCP server tool, or all tools when +// `toolName` is null. // Experimental: PermissionsLocationsAddToolApprovalDetailsMCP is part of an experimental // API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsMCP struct { @@ -4456,7 +5524,7 @@ func (PermissionsLocationsAddToolApprovalDetailsMCP) Kind() PermissionsLocations return PermissionsLocationsAddToolApprovalDetailsKindMCP } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsMcpSampling` type. +// Location-persisted tool approval details for MCP sampling requests from a server. // Experimental: PermissionsLocationsAddToolApprovalDetailsMCPSampling is part of an // experimental API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsMCPSampling struct { @@ -4470,7 +5538,7 @@ func (PermissionsLocationsAddToolApprovalDetailsMCPSampling) Kind() PermissionsL return PermissionsLocationsAddToolApprovalDetailsKindMCPSampling } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsMemory` type. +// Location-persisted tool approval details for writes to long-term memory. // Experimental: PermissionsLocationsAddToolApprovalDetailsMemory is part of an experimental // API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsMemory struct { @@ -4482,7 +5550,7 @@ func (PermissionsLocationsAddToolApprovalDetailsMemory) Kind() PermissionsLocati return PermissionsLocationsAddToolApprovalDetailsKindMemory } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsRead` type. +// Location-persisted tool approval details for read-only filesystem operations. // Experimental: PermissionsLocationsAddToolApprovalDetailsRead is part of an experimental // API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsRead struct { @@ -4493,7 +5561,7 @@ func (PermissionsLocationsAddToolApprovalDetailsRead) Kind() PermissionsLocation return PermissionsLocationsAddToolApprovalDetailsKindRead } -// Schema for the `PermissionsLocationsAddToolApprovalDetailsWrite` type. +// Location-persisted tool approval details for filesystem write operations. // Experimental: PermissionsLocationsAddToolApprovalDetailsWrite is part of an experimental // API and may change or be removed. type PermissionsLocationsAddToolApprovalDetailsWrite struct { @@ -4587,12 +5655,19 @@ type PermissionsResetSessionApprovalsResult struct { Success bool `json:"success"` } -// Whether to enable full allow-all permissions for the session. +// Allow-all mode to apply for the session. // Experimental: PermissionsSetAllowAllRequest is part of an experimental API and may change // or be removed. type PermissionsSetAllowAllRequest struct { - // Whether to enable full allow-all permissions - Enabled bool `json:"enabled"` + // Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is + // treated as `mode: "on"` and any other value is treated as `mode: "off"`. + Enabled *bool `json:"enabled,omitempty"` + // Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM + // auto-approval; `off` disables both. + Mode *PermissionsAllowAllMode `json:"mode,omitempty"` + // Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when + // `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. + Model *string `json:"model,omitempty"` // Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. Source *PermissionsSetAllowAllSource `json:"source,omitempty"` } @@ -4665,6 +5740,7 @@ type PermissionURLsSetUnrestrictedModeParams struct { } // Optional message to echo back to the caller. +// Experimental: PingRequest is part of an experimental API and may change or be removed. type PingRequest struct { // Optional message to echo back Message *string `json:"message,omitempty"` @@ -4672,6 +5748,7 @@ type PingRequest struct { // Server liveness response, including the echoed message, current server timestamp, and // protocol version. +// Experimental: PingResult is part of an experimental API and may change or be removed. type PingResult struct { // Echoed message (or default greeting) Message string `json:"message"` @@ -4746,7 +5823,7 @@ type PlanUpdateRequest struct { Content string `json:"content"` } -// Schema for the `Plugin` type. +// Session plugin metadata, with name, marketplace, optional version, and enabled state. // Experimental: Plugin is part of an experimental API and may change or be removed. type Plugin struct { // Whether the plugin is currently enabled @@ -4833,7 +5910,7 @@ type PluginsInstallRequest struct { WorkingDirectory *string `json:"workingDirectory,omitempty"` } -// Marketplace source to register. +// Marketplace source and optional working directory for relative-path resolution. // Experimental: PluginsMarketplacesAddRequest is part of an experimental API and may change // or be removed. type PluginsMarketplacesAddRequest struct { @@ -4842,6 +5919,9 @@ type PluginsMarketplacesAddRequest struct { // (user@host:path), or a local path. The marketplace's own name (from its manifest) is used // as the registration key. Source string `json:"source"` + // Working directory used to resolve relative local paths in `source`. Defaults to the + // server's current working directory. + WorkingDirectory *string `json:"workingDirectory,omitempty"` } // Name of the marketplace whose plugin catalog to fetch. @@ -4880,6 +5960,10 @@ type PluginsReloadRequest struct { DeferRepoHooks *bool `json:"deferRepoHooks,omitempty"` // Re-run custom-agent discovery after refreshing plugins. Defaults to true. ReloadCustomAgents *bool `json:"reloadCustomAgents,omitempty"` + // Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) + // after refreshing plugins. Defaults to true. Has no effect when the session has no active + // extension controller (e.g. extensions were not requested for the session). + ReloadExtensions *bool `json:"reloadExtensions,omitempty"` // Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has // no effect when the host has not registered a hook reloader (e.g. remote sessions). ReloadHooks *bool `json:"reloadHooks,omitempty"` @@ -4891,6 +5975,9 @@ type PluginsReloadRequest struct { // Experimental: PluginsUninstallRequest is part of an experimental API and may change or be // removed. type PluginsUninstallRequest struct { + // Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall + // when multiple installed plugins share the same name. + DirectSourceID *string `json:"directSourceId,omitempty"` // Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the // fully-qualified spec. Name string `json:"name"` @@ -4909,7 +5996,8 @@ type PluginsUpdateRequest struct { Name string `json:"name"` } -// Schema for the `PluginUpdateAllEntry` type. +// Per-plugin result from updating all plugins, with versions, skills installed, success +// flag, and optional error. // Experimental: PluginUpdateAllEntry is part of an experimental API and may change or be // removed. type PluginUpdateAllEntry struct { @@ -4949,16 +6037,6 @@ type PluginUpdateResult struct { SkillsInstalled int64 `json:"skillsInstalled"` } -// Batch of spawn events plus a cursor for follow-up polls. -// Experimental: PollSpawnedSessionsResult is part of an experimental API and may change or -// be removed. -type PollSpawnedSessionsResult struct { - // Opaque cursor to pass back to receive only events after this batch. - Cursor string `json:"cursor"` - // Spawn events emitted since the supplied cursor. - Events []SessionsPollSpawnedSessionsEvent `json:"events"` -} - // BYOK providers and/or models to add to the session's registry at runtime. Both fields are // optional; provide providers, models, or both. // Experimental: ProviderAddRequest is part of an experimental API and may change or be @@ -5133,7 +6211,8 @@ type ProviderTokenAcquireResult struct { Token string `json:"token"` } -// Schema for the `PushAttachment` type. +// Attachment union accepted by push input, covering files, directories, GitHub objects, +// blobs, snippets, and extension context. // Experimental: PushAttachment is part of an experimental API and may change or be removed. type PushAttachment interface { pushAttachment() @@ -5214,6 +6293,85 @@ func (PushAttachmentFile) Type() PushAttachmentType { return PushAttachmentTypeFile } +// Pointer to a GitHub Actions job. +// Experimental: PushAttachmentGitHubActionsJob is part of an experimental API and may +// change or be removed. +type PushAttachmentGitHubActionsJob struct { + // Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent + // for in-progress jobs. + Conclusion *string `json:"conclusion,omitempty"` + // Job id within the workflow run + JobID int64 `json:"jobId"` + // Display name of the job + JobName string `json:"jobName"` + // Repository the workflow run belongs to + Repo PushGitHubRepoRef `json:"repo"` + // URL to the job on GitHub + URL string `json:"url"` + // Display name of the workflow the job ran in + WorkflowName string `json:"workflowName"` +} + +func (PushAttachmentGitHubActionsJob) pushAttachment() {} +func (PushAttachmentGitHubActionsJob) Type() PushAttachmentType { + return PushAttachmentTypeGitHubActionsJob +} + +// Pointer to a GitHub commit. +// Experimental: PushAttachmentGitHubCommit is part of an experimental API and may change or +// be removed. +type PushAttachmentGitHubCommit struct { + // First line of the commit message + Message string `json:"message"` + // Full commit SHA + Oid string `json:"oid"` + // Repository the commit belongs to + Repo PushGitHubRepoRef `json:"repo"` + // URL to the commit on GitHub + URL string `json:"url"` +} + +func (PushAttachmentGitHubCommit) pushAttachment() {} +func (PushAttachmentGitHubCommit) Type() PushAttachmentType { + return PushAttachmentTypeGitHubCommit +} + +// Pointer to a file in a GitHub repository at a specific ref. +// Experimental: PushAttachmentGitHubFile is part of an experimental API and may change or +// be removed. +type PushAttachmentGitHubFile struct { + // Repository-relative path to the file + Path string `json:"path"` + // Git ref the file is read at (branch, tag, or commit SHA) + Ref string `json:"ref"` + // Repository the file lives in + Repo PushGitHubRepoRef `json:"repo"` + // URL to the file on GitHub + URL string `json:"url"` +} + +func (PushAttachmentGitHubFile) pushAttachment() {} +func (PushAttachmentGitHubFile) Type() PushAttachmentType { + return PushAttachmentTypeGitHubFile +} + +// Pointer to a single-file diff. At least one of `head` and `base` must be present. +// Experimental: PushAttachmentGitHubFileDiff is part of an experimental API and may change +// or be removed. +type PushAttachmentGitHubFileDiff struct { + // File location on the base side of the diff. Absent for additions. + Base *PushAttachmentGitHubFileDiffSide `json:"base,omitempty"` + // File location on the head side of the diff. Absent for deletions. + Head *PushAttachmentGitHubFileDiffSide `json:"head,omitempty"` + // URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) + URL string `json:"url"` +} + +func (PushAttachmentGitHubFileDiff) pushAttachment() {} +func (PushAttachmentGitHubFileDiff) Type() PushAttachmentType { + return PushAttachmentTypeGitHubFileDiff +} + // GitHub issue, pull request, or discussion reference // Experimental: PushAttachmentGitHubReference is part of an experimental API and may change // or be removed. @@ -5235,6 +6393,96 @@ func (PushAttachmentGitHubReference) Type() PushAttachmentType { return PushAttachmentTypeGitHubReference } +// Pointer to a GitHub release. +// Experimental: PushAttachmentGitHubRelease is part of an experimental API and may change +// or be removed. +type PushAttachmentGitHubRelease struct { + // Human-readable release name + Name string `json:"name"` + // Repository the release belongs to + Repo PushGitHubRepoRef `json:"repo"` + // Git tag the release is anchored to + TagName string `json:"tagName"` + // URL to the release on GitHub + URL string `json:"url"` +} + +func (PushAttachmentGitHubRelease) pushAttachment() {} +func (PushAttachmentGitHubRelease) Type() PushAttachmentType { + return PushAttachmentTypeGitHubRelease +} + +// Pointer to a GitHub repository. +// Experimental: PushAttachmentGitHubRepository is part of an experimental API and may +// change or be removed. +type PushAttachmentGitHubRepository struct { + // Short description of the repository + Description *string `json:"description,omitempty"` + // Git ref this attachment is anchored at (branch, tag, or commit). When absent the default + // branch is implied. + Ref *string `json:"ref,omitempty"` + // Repository pointer + Repo PushGitHubRepoRef `json:"repo"` + // URL to the repository on GitHub + URL string `json:"url"` +} + +func (PushAttachmentGitHubRepository) pushAttachment() {} +func (PushAttachmentGitHubRepository) Type() PushAttachmentType { + return PushAttachmentTypeGitHubRepository +} + +// Pointer to a line range inside a file in a GitHub repository. +// Experimental: PushAttachmentGitHubSnippet is part of an experimental API and may change +// or be removed. +type PushAttachmentGitHubSnippet struct { + // Line range the snippet covers + LineRange PushAttachmentFileLineRange `json:"lineRange"` + // Repository-relative path to the file + Path string `json:"path"` + // Git ref the file is read at (branch, tag, or commit SHA) + Ref string `json:"ref"` + // Repository the file lives in + Repo PushGitHubRepoRef `json:"repo"` + // URL to the snippet on GitHub (with line anchor) + URL string `json:"url"` +} + +func (PushAttachmentGitHubSnippet) pushAttachment() {} +func (PushAttachmentGitHubSnippet) Type() PushAttachmentType { + return PushAttachmentTypeGitHubSnippet +} + +// Pointer to a comparison between two git revisions. +// Experimental: PushAttachmentGitHubTreeComparison is part of an experimental API and may +// change or be removed. +type PushAttachmentGitHubTreeComparison struct { + // Base side of the comparison + Base PushAttachmentGitHubTreeComparisonSide `json:"base"` + // Head side of the comparison + Head PushAttachmentGitHubTreeComparisonSide `json:"head"` + // URL to the comparison on GitHub + URL string `json:"url"` +} + +func (PushAttachmentGitHubTreeComparison) pushAttachment() {} +func (PushAttachmentGitHubTreeComparison) Type() PushAttachmentType { + return PushAttachmentTypeGitHubTreeComparison +} + +// Generic GitHub URL reference. +// Experimental: PushAttachmentGitHubURL is part of an experimental API and may change or be +// removed. +type PushAttachmentGitHubURL struct { + // URL to the GitHub resource + URL string `json:"url"` +} + +func (PushAttachmentGitHubURL) pushAttachment() {} +func (PushAttachmentGitHubURL) Type() PushAttachmentType { + return PushAttachmentTypeGitHubURL +} + // Code selection attachment from an editor // Experimental: PushAttachmentSelection is part of an experimental API and may change or be // removed. @@ -5264,6 +6512,28 @@ type PushAttachmentFileLineRange struct { Start int64 `json:"start"` } +// One side of a file diff (head or base) +// Experimental: PushAttachmentGitHubFileDiffSide is part of an experimental API and may +// change or be removed. +type PushAttachmentGitHubFileDiffSide struct { + // Repository-relative path to the file + Path string `json:"path"` + // Git ref (branch, tag, or commit SHA) the file is read at + Ref string `json:"ref"` + // Repository the file lives in + Repo PushGitHubRepoRef `json:"repo"` +} + +// One side of a tree comparison (head or base) +// Experimental: PushAttachmentGitHubTreeComparisonSide is part of an experimental API and +// may change or be removed. +type PushAttachmentGitHubTreeComparisonSide struct { + // Repository the revision belongs to + Repo PushGitHubRepoRef `json:"repo"` + // Git revision (branch, tag, or commit SHA) + Revision string `json:"revision"` +} + // Position range of the selection within the file // Experimental: PushAttachmentSelectionDetails is part of an experimental API and may // change or be removed. @@ -5294,6 +6564,18 @@ type PushAttachmentSelectionDetailsStart struct { Line int64 `json:"line"` } +// Pointer to a GitHub repository. +// Experimental: PushGitHubRepoRef is part of an experimental API and may change or be +// removed. +type PushGitHubRepoRef struct { + // Numeric GitHub repository id + ID *int64 `json:"id,omitempty"` + // Repository name (without owner) + Name string `json:"name"` + // Repository owner login (user or organization) + Owner string `json:"owner"` +} + // Result of the queued command execution. // Experimental: QueuedCommandResult is part of an experimental API and may change or be // removed. @@ -5302,7 +6584,8 @@ type QueuedCommandResult interface { Handled() bool } -// Schema for the `QueuedCommandHandled` type. +// Queued-command response indicating the host executed the command, with an optional flag +// to stop queue processing. // Experimental: QueuedCommandHandled is part of an experimental API and may change or be // removed. type QueuedCommandHandled struct { @@ -5316,7 +6599,8 @@ func (QueuedCommandHandled) Handled() bool { return true } -// Schema for the `QueuedCommandNotHandled` type. +// Queued-command response indicating the host did not execute the command and the queue may +// continue. // Experimental: QueuedCommandNotHandled is part of an experimental API and may change or be // removed. type QueuedCommandNotHandled struct { @@ -5327,7 +6611,8 @@ func (QueuedCommandNotHandled) Handled() bool { return false } -// Schema for the `QueuePendingItems` type. +// User-facing pending queue entry, with kind and display text for a queued message, slash +// command, or model change. // Experimental: QueuePendingItems is part of an experimental API and may change or be // removed. type QueuePendingItems struct { @@ -5365,16 +6650,18 @@ type RegisterEventInterestParams struct { // The event type the consumer wants the runtime to treat as 'observed' for // behavior-switching gating. Some runtime code paths inspect whether any consumer is // interested in a specific event type and choose a different implementation accordingly - // (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates the full - // interactive OAuth flow to the consumer; when no interest is registered the runtime - // installs a browserless fallback that silently reuses cached tokens). SDK clients that - // long-poll events do NOT automatically appear as listeners to these gating checks — they - // must explicitly call `registerInterest` for each event type they want the runtime to - // count as having a consumer. Multiple registrations for the same event type from the same - // or different consumers are tracked independently and must each be released. See: - // `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, - // `user_input.requested`, `elicitation.requested`, `command.queued`, - // `exit_plan_mode.requested`. + // (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive + // OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest + // is registered the runtime still attempts non-interactive reconnect from cached or + // refreshable tokens, and only marks the server `needs-auth` if usable credentials are + // unavailable — it does not open a browser or start interactive OAuth without a consumer). + // SDK clients that long-poll events do NOT automatically appear as listeners to these + // gating checks — they must explicitly call `registerInterest` for each event type they + // want the runtime to count as having a consumer. Multiple registrations for the same event + // type from the same or different consumers are tracked independently and must each be + // released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, + // `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, + // `command.queued`, `exit_plan_mode.requested`. EventType string `json:"eventType"` } @@ -5484,6 +6771,12 @@ func (r RawRemoteControlStatusData) State() RemoteControlStatusState { type RemoteControlStatusActive struct { // Session id remote control is pointed at. AttachedSessionID string `json:"attachedSessionId"` + // True while a read-only/session-sync export is deferred, awaiting the first `user.message` + // before its MC session exists. Marked internal: this field is excluded from the public SDK + // surface and is populated only on the CLI in-process path. + // Internal: AwaitingFirstMessage is part of the SDK's internal API surface and is not + // intended for external use. + AwaitingFirstMessage *bool `json:"awaitingFirstMessage,omitempty"` // MC frontend URL for this session, when known. FrontendURL *string `json:"frontendUrl,omitempty"` // Whether the MC session may steer this session. @@ -5641,6 +6934,8 @@ type RemoteSessionRepository struct { Owner string `json:"owner"` } +// Experimental: RuntimeShutdownResult is part of an experimental API and may change or be +// removed. type RuntimeShutdownResult struct { } @@ -5704,14 +6999,10 @@ type SandboxConfigUserPolicyFilesystem struct { // Experimental: SandboxConfigUserPolicyNetwork is part of an experimental API and may // change or be removed. type SandboxConfigUserPolicyNetwork struct { - // Hosts allowed in addition to the base policy. - AllowedHosts []string `json:"allowedHosts,omitzero"` // Whether traffic to local/loopback addresses is allowed. AllowLocalNetwork *bool `json:"allowLocalNetwork,omitempty"` // Whether outbound network traffic is allowed at all. AllowOutbound *bool `json:"allowOutbound,omitempty"` - // Hosts explicitly blocked. - BlockedHosts []string `json:"blockedHosts,omitzero"` } // macOS seatbelt-specific options. @@ -5722,7 +7013,8 @@ type SandboxConfigUserPolicySeatbelt struct { KeychainAccess *bool `json:"keychainAccess,omitempty"` } -// Schema for the `ScheduleEntry` type. +// Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, +// recurrence, and next run time. // Experimental: ScheduleEntry is part of an experimental API and may change or be removed. type ScheduleEntry struct { // Absolute fire time (epoch milliseconds) for a one-shot calendar schedule. @@ -5774,12 +7066,16 @@ type ScheduleStopResult struct { } // Secret values to add to the redaction filter. +// Experimental: SecretsAddFilterValuesRequest is part of an experimental API and may change +// or be removed. type SecretsAddFilterValuesRequest struct { // Raw secret values to register for redaction Values []string `json:"values"` } // Confirmation that the secret values were registered. +// Experimental: SecretsAddFilterValuesResult is part of an experimental API and may change +// or be removed. type SecretsAddFilterValuesResult struct { // Whether the values were successfully registered Ok bool `json:"ok"` @@ -5799,6 +7095,73 @@ type SendAttachmentsToMessageParams struct { InstanceID *string `json:"instanceId,omitempty"` } +// A single user message to append to the session as part of a `session.sendMessages` turn +// Experimental: SendMessageItem is part of an experimental API and may change or be removed. +type SendMessageItem struct { + // Optional attachments (files, directories, selections, blobs, GitHub references) to + // include with this message + Attachments []Attachment `json:"attachments,omitzero"` + // If false, this message will not trigger a Premium Request Unit charge. User messages + // default to billable. + // Internal: Billable is part of the SDK's internal API surface and is not intended for + // external use. + Billable *bool `json:"billable,omitempty"` + // If provided, this is shown in the timeline instead of `prompt` + DisplayPrompt *string `json:"displayPrompt,omitempty"` + // The user message text + Prompt string `json:"prompt"` + // If set, the request will fail if the named tool is not available when this message is + // among the user messages at the start of the current exchange + RequiredTool *string `json:"requiredTool,omitempty"` + // Optional provenance tag copied to the resulting user.message event. Must match one of + // three forms: the literal `system`, `command-` for messages originating from a + // command (e.g. slash command, Mission Control command), or `schedule-` for + // messages originating from a scheduled job. + // Internal: Source is part of the SDK's internal API surface and is not intended for + // external use. + Source *string `json:"source,omitempty"` +} + +// Parameters for sending zero or more user messages to the session in a single turn. +// Remote-backed (Mission Control) sessions do not support this method and will return an +// error. +// Experimental: SendMessagesRequest is part of an experimental API and may change or be +// removed. +type SendMessagesRequest struct { + // The UI mode the agent was in when these messages were sent. Defaults to the session's + // current mode. + AgentMode *SendAgentMode `json:"agentMode,omitempty"` + // The user messages to append to the conversation, in order. May be empty, in which case a + // single turn runs over the existing history with no new user message. + Messages []SendMessageItem `json:"messages"` + // How to deliver the messages. `enqueue` (default) appends to the message queue. + // `immediate` interjects during an in-progress turn. + Mode *SendMode `json:"mode,omitempty"` + // If true, adds the messages to the front of the queue instead of the end + Prepend *bool `json:"prepend,omitempty"` + // Custom HTTP headers to include in outbound model requests for this turn. Merged with + // session-level provider headers; per-turn headers augment and overwrite session-level + // headers with the same key. + RequestHeaders map[string]string `json:"requestHeaders,omitzero"` + // W3C Trace Context traceparent header for distributed tracing of this agent turn + Traceparent *string `json:"traceparent,omitempty"` + // W3C Trace Context tracestate header for distributed tracing + Tracestate *string `json:"tracestate,omitempty"` + // If true, await completion of the agentic loop for this turn before returning. Defaults to + // false (fire-and-forget). When true, the result still contains the same `messageIds`; the + // caller can rely on the agent having processed the messages before the call resolves. + Wait *bool `json:"wait,omitempty"` +} + +// Result of sending zero or more user messages +// Experimental: SendMessagesResult is part of an experimental API and may change or be +// removed. +type SendMessagesResult struct { + // Unique identifiers assigned to the messages, one per provided message in order. Empty + // when no messages were provided. + MessageIDs []string `json:"messageIds"` +} + // Parameters for sending a user message to the session // Experimental: SendRequest is part of an experimental API and may change or be removed. type SendRequest struct { @@ -5866,7 +7229,9 @@ type ServerInstructionSourceList struct { Sources []InstructionSource `json:"sources"` } -// Schema for the `ServerSkill` type. +// Server-side skill metadata, including name, description, source, enabled/invocable state, +// path, project path, and argument hint. +// Experimental: ServerSkill is part of an experimental API and may change or be removed. type ServerSkill struct { // Optional freeform hint describing the skill's expected arguments, from the // `argument-hint` frontmatter field @@ -5888,6 +7253,7 @@ type ServerSkill struct { } // Skills discovered across global and project sources. +// Experimental: ServerSkillList is part of an experimental API and may change or be removed. type ServerSkillList struct { // All discovered skills across all sources Skills []ServerSkill `json:"skills"` @@ -5940,6 +7306,25 @@ type SessionBulkDeleteResult struct { type SessionCanvasCloseResult struct { } +// A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` +// (UTF-16 code units) in the composer with `insertText`; when the range is absent, the +// active token around the cursor is replaced. +// Experimental: SessionCompletionItem is part of an experimental API and may change or be +// removed. +type SessionCompletionItem struct { + // Text spliced into the composer when the item is accepted. + InsertText string `json:"insertText"` + // Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the + // host's display kind. + Kind *string `json:"kind,omitempty"` + // Primary display label for the picker row. Falls back to `insertText` when absent. + Label *string `json:"label,omitempty"` + // End (exclusive) of the replacement range in `text`, in UTF-16 code units. + RangeEnd *int64 `json:"rangeEnd,omitempty"` + // Start of the replacement range in `text`, in UTF-16 code units. + RangeStart *int64 `json:"rangeStart,omitempty"` +} + // Pre-resolved working-directory context for session startup. // Experimental: SessionContext is part of an experimental API and may change or be removed. type SessionContext struct { @@ -5955,14 +7340,60 @@ type SessionContext struct { Repository *string `json:"repository,omitempty"` } -// Token-usage breakdown for the session's current context window -// Experimental: SessionContextInfo is part of an experimental API and may change or be -// removed. -type SessionContextInfo struct { - // Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%) - BufferTokens int64 `json:"bufferTokens"` - // Token count at which background compaction starts (configurable percentage of - // promptTokenLimit) +// Per-source token attribution snapshot for the current context window. The heaviest +// individual messages are available separately via `metadata.getContextHeaviestMessages`. +// Experimental: SessionContextAttribution is part of an experimental API and may change or +// be removed. +type SessionContextAttribution struct { + // Successful compaction history for the session. + Compactions SessionContextAttributionCompactions `json:"compactions"` + // Flat list of per-source attribution entries. Group by `kind` and render unrecognized + // kinds generically. Nesting and rollups are expressed via `parentId`. + Entries []SessionContextAttributionEntriesItem `json:"entries"` + // Total token count of the current context window the entries are measured against (system + // message + conversation messages + tool definitions — the same total reported by + // /context). Divide an entry's `tokens` by this to derive its share. + TotalTokens int64 `json:"totalTokens"` +} + +// Successful compaction history for the session. +type SessionContextAttributionCompactions struct { + // Number of successful compactions in this session. + Count int64 `json:"count"` +} + +type SessionContextAttributionEntriesItem struct { + // Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, + // `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + Attributes map[string]string `json:"attributes,omitzero"` + // Identifier for this entry, formed by joining its `kind` and source name (e.g. + // `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to + // match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP + // registries), and as the `parentId` target for nesting. Distinct from the human-facing + // `label`. + ID string `json:"id"` + // Source category for this entry. Not a closed set — tolerate unknown values. Known values + // today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + Kind string `json:"kind"` + // Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be + // localized/reformatted without notice — do not key off it. + Label string `json:"label"` + // Optional `id` of the parent entry: e.g. a `plugin` entry parenting its + // `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. + // Omitted for top-level entries. + ParentID *string `json:"parentId,omitempty"` + // Token count currently in context attributable to this entry. + Tokens int64 `json:"tokens"` +} + +// Token-usage breakdown for the session's current context window +// Experimental: SessionContextInfo is part of an experimental API and may change or be +// removed. +type SessionContextInfo struct { + // Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%) + BufferTokens int64 `json:"bufferTokens"` + // Token count at which background compaction starts (configurable percentage of + // promptTokenLimit) CompactionThreshold int64 `json:"compactionThreshold"` // Tokens consumed by user/assistant/tool messages ConversationTokens int64 `json:"conversationTokens"` @@ -6090,7 +7521,8 @@ type SessionFSReaddirResult struct { Error *SessionFSError `json:"error,omitempty"` } -// Schema for the `SessionFsReaddirWithTypesEntry` type. +// Directory entry returned by session filesystem `readdirWithTypes`, with name and entry +// type. // Experimental: SessionFSReaddirWithTypesEntry is part of an experimental API and may // change or be removed. type SessionFSReaddirWithTypesEntry struct { @@ -6171,6 +7603,8 @@ type SessionFSRmRequest struct { } // Optional capabilities declared by the provider +// Experimental: SessionFSSetProviderCapabilities is part of an experimental API and may +// change or be removed. type SessionFSSetProviderCapabilities struct { // Whether the provider supports SQLite query/exists operations Sqlite *bool `json:"sqlite,omitempty"` @@ -6178,6 +7612,8 @@ type SessionFSSetProviderCapabilities struct { // Initial working directory, session-state path layout, and path conventions used to // register the calling SDK client as the session filesystem provider. +// Experimental: SessionFSSetProviderRequest is part of an experimental API and may change +// or be removed. type SessionFSSetProviderRequest struct { // Optional capabilities declared by the provider Capabilities *SessionFSSetProviderCapabilities `json:"capabilities,omitempty"` @@ -6190,6 +7626,8 @@ type SessionFSSetProviderRequest struct { } // Indicates whether the calling client was registered as the session filesystem provider. +// Experimental: SessionFSSetProviderResult is part of an experimental API and may change or +// be removed. type SessionFSSetProviderResult struct { // Whether the provider was set successfully Success bool `json:"success"` @@ -6286,7 +7724,8 @@ type SessionFSWriteFileRequest struct { SessionID string `json:"sessionId"` } -// Schema for the `SessionInstalledPlugin` type. +// Installed plugin record for a session, with marketplace, version, install time, enabled +// state, cache path, and source. // Experimental: SessionInstalledPlugin is part of an experimental API and may change or be // removed. type SessionInstalledPlugin struct { @@ -6316,7 +7755,8 @@ type SessionInstalledPluginSource struct { String *string } -// Schema for the `SessionInstalledPluginSourceGitHub` type. +// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, +// and optional subpath. // Experimental: SessionInstalledPluginSourceGitHub is part of an experimental API and may // change or be removed. type SessionInstalledPluginSourceGitHub struct { @@ -6327,7 +7767,7 @@ type SessionInstalledPluginSourceGitHub struct { Source SessionInstalledPluginSourceGitHubSource `json:"source"` } -// Schema for the `SessionInstalledPluginSourceLocal` type. +// Source descriptor for a direct local plugin install, with a local filesystem path. // Experimental: SessionInstalledPluginSourceLocal is part of an experimental API and may // change or be removed. type SessionInstalledPluginSourceLocal struct { @@ -6336,7 +7776,8 @@ type SessionInstalledPluginSourceLocal struct { Source SessionInstalledPluginSourceLocalSource `json:"source"` } -// Schema for the `SessionInstalledPluginSourceUrl` type. +// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional +// subpath. // Experimental: SessionInstalledPluginSourceURL is part of an experimental API and may // change or be removed. type SessionInstalledPluginSourceURL struct { @@ -6347,6 +7788,14 @@ type SessionInstalledPluginSourceURL struct { URL string `json:"url"` } +// Optional session limits. +// Experimental: SessionLimitsConfig is part of an experimental API and may change or be +// removed. +type SessionLimitsConfig struct { + // Maximum AI Credits allowed across the session's current accounting window. + MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` +} + // Sessions matching the filter, ordered most-recently-modified first. // Experimental: SessionList is part of an experimental API and may change or be removed. type SessionList struct { @@ -6517,6 +7966,8 @@ type SessionMetadataSnapshot struct { SelectedModel *string `json:"selectedModel,omitempty"` // The unique identifier of the session SessionID string `json:"sessionId"` + // Current session limits, or null when no limits are active + SessionLimits *SessionLimitsConfig `json:"sessionLimits"` // ISO 8601 timestamp of when the session started StartTime time.Time `json:"startTime"` // Short human-readable summary of the session, if known. Omitted when no summary has been @@ -6541,10 +7992,21 @@ type SessionModelList struct { // (CAPI) models and any registry BYOK models; a BYOK model appears under its // provider-qualified selection id (`provider/id`). List []any `json:"list"` + // Cost categories for the full CAPI catalog, including picker-disabled models that Auto may + // select. Metadata only; entries absent from `list` are not manually selectable. + ModelPriceCategories []SessionModelPriceCategory `json:"modelPriceCategories,omitzero"` // Per-quota snapshots returned alongside the model list, keyed by quota type. QuotaSnapshots map[string]any `json:"quotaSnapshots,omitzero"` } +// Cost-category metadata for a CAPI model. +// Experimental: SessionModelPriceCategory is part of an experimental API and may change or +// be removed. +type SessionModelPriceCategory struct { + ID string `json:"id"` + PriceCategory ModelPickerPriceCategory `json:"priceCategory"` +} + // Experimental: SessionModeSetResult is part of an experimental API and may change or be // removed. type SessionModeSetResult struct { @@ -6565,6 +8027,9 @@ type SessionOpenOptions struct { AdditionalContentExclusionPolicies []SessionOpenOptionsAdditionalContentExclusionPolicy `json:"additionalContentExclusionPolicies,omitzero"` // Runtime context discriminator for agent filtering. AgentContext *string `json:"agentContext,omitempty"` + // Whether to include instructions from every MCP server in the system prompt instead of + // only allowlisted servers. + AllowAllMCPServerInstructions *bool `json:"allowAllMcpServerInstructions,omitempty"` // Whether ask_user is explicitly disabled. AskUserDisabled *bool `json:"askUserDisabled,omitempty"` // Initial authentication info for the session. @@ -6600,6 +8065,8 @@ type SessionOpenOptions struct { // surface is experimental. // Experimental: EnableCitations is part of an experimental API and may change or be removed. EnableCitations *bool `json:"enableCitations,omitempty"` + // Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. + EnableManagedSettings *bool `json:"enableManagedSettings,omitempty"` // Whether on-demand custom instruction discovery is enabled. EnableOnDemandInstructionDiscovery *bool `json:"enableOnDemandInstructionDiscovery,omitempty"` // Whether shell-script safety heuristics are enabled. @@ -6610,6 +8077,10 @@ type SessionOpenOptions struct { EnvValueMode *SessionOpenOptionsEnvValueMode `json:"envValueMode,omitempty"` // Override directory for session event logs. EventsLogDirectory *string `json:"eventsLogDirectory,omitempty"` + // Built-in subagent names to exclude from this session. Excluded built-ins are hidden from + // agent discovery and cannot be dispatched unless a custom agent with the same name is + // available. + ExcludedBuiltinAgents []string `json:"excludedBuiltinAgents,omitzero"` // Denylist of tool names. ExcludedTools []string `json:"excludedTools,omitzero"` // ExP assignment ('flight') data injected by an SDK integrator, in the same JSON shape the @@ -6621,6 +8092,10 @@ type SessionOpenOptions struct { ExpAssignments any `json:"expAssignments,omitempty"` // Feature-flag values resolved by the host. FeatureFlags map[string]bool `json:"featureFlags,omitzero"` + // Built-in subagent names to include in this session. When specified, only these built-ins + // are available, subject to runtime availability and exclusions. Custom agents with the + // same name remain available. + IncludedBuiltinAgents []string `json:"includedBuiltinAgents,omitzero"` // Installed plugins visible to the session. InstalledPlugins []InstalledPlugin `json:"installedPlugins,omitzero"` // Stable integration identifier for analytics. @@ -6670,6 +8145,8 @@ type SessionOpenOptions struct { SessionCapabilities []SessionCapability `json:"sessionCapabilities,omitzero"` // Optional stable session identifier to use for a new session. SessionID *string `json:"sessionId,omitempty"` + // Initial session limits. + SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` // Shell init profile. ShellInitProfile *string `json:"shellInitProfile,omitempty"` // Per-shell process flags. @@ -6680,13 +8157,16 @@ type SessionOpenOptions struct { SkipCustomInstructions *bool `json:"skipCustomInstructions,omitempty"` // Optional trajectory output file path. TrajectoryFile *string `json:"trajectoryFile,omitempty"` + // Initial output verbosity level for supported models. + Verbosity *Verbosity `json:"verbosity,omitempty"` // Working directory to anchor the session. WorkingDirectory *string `json:"workingDirectory,omitempty"` // Pre-resolved working-directory context for session startup. WorkingDirectoryContext *SessionContext `json:"workingDirectoryContext,omitempty"` } -// Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicy` type. +// Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated +// data, and scope. // Experimental: SessionOpenOptionsAdditionalContentExclusionPolicy is part of an // experimental API and may change or be removed. type SessionOpenOptionsAdditionalContentExclusionPolicy struct { @@ -6697,18 +8177,19 @@ type SessionOpenOptionsAdditionalContentExclusionPolicy struct { Scope SessionOpenOptionsAdditionalContentExclusionPolicyScope `json:"scope"` } -// Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRule` type. +// Single content-exclusion rule supplied to `sessions.open` options, with paths, match +// conditions, and source. // Experimental: SessionOpenOptionsAdditionalContentExclusionPolicyRule is part of an // experimental API and may change or be removed. type SessionOpenOptionsAdditionalContentExclusionPolicyRule struct { IfAnyMatch []string `json:"ifAnyMatch,omitzero"` IfNoneMatch []string `json:"ifNoneMatch,omitzero"` Paths []string `json:"paths"` - // Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type. + // Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. Source SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource `json:"source"` } -// Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type. +// Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. // Experimental: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource is part of an // experimental API and may change or be removed. type SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource struct { @@ -6795,6 +8276,15 @@ type SessionsOpenHandoff struct { // Remote session metadata for the session to hand off (typically obtained from // `sessions.list` with `source: "remote"`). Metadata RemoteSessionMetadataValue `json:"metadata"` + // In-process confirmation callback `(request) => boolean | Promise` invoked when + // the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch + // between the current working directory and the remote session). Returning `true` proceeds + // with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal + // because a function reference cannot cross the JSON-RPC boundary, for the same reasons as + // `onProgress`. + // Internal: OnConfirm is part of the SDK's internal API surface and is not intended for + // external use. + OnConfirm any `json:"onConfirm,omitempty"` // In-process progress callback `(update) => void` invoked for each handoff step. Marked // internal because a function reference cannot cross the JSON-RPC boundary. The host-side // `handoffSession` is already declared as `AsyncGenerator`; @@ -6996,10 +8486,14 @@ type SessionsEnrichMetadataRequest struct { // or be removed. type SessionSetCredentialsParams struct { // The new auth credentials to install on the session. When omitted or `undefined`, the call - // is a no-op and the session's existing credentials are preserved. The runtime stores the - // value verbatim and uses it for outbound model/API requests; it does NOT re-validate or - // re-fetch the associated Copilot user response. Several variants carry secret material; - // treat this method's params as containing secrets at rest and in transit. + // is a no-op and the session's existing credentials are preserved. The runtime installs the + // supplied value immediately for outbound model/API requests. When the credential carries a + // raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally + // re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous + // install) so plan/quota/billing metadata regains fidelity; on resolution failure the + // verbatim credential remains installed. It does NOT otherwise validate the credential. + // Several variants carry secret material; treat this method's params as containing secrets + // at rest and in transit. Credentials AuthInfo `json:"credentials,omitempty"` } @@ -7007,10 +8501,120 @@ type SessionSetCredentialsParams struct { // Experimental: SessionSetCredentialsResult is part of an experimental API and may change // or be removed. type SessionSetCredentialsResult struct { + // Whether the session ended up with a populated `copilotUser` for the installed + // credentials. `true` when the supplied credential already carried `copilotUser` or it was + // successfully re-resolved server-side. `false` when the credential is installed without + // `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from + // the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In + // both `false` cases the token swap still applied, but plan/quota/billing metadata is + // degraded. Present whenever a credential was supplied; omitted only when no credential was + // supplied (no-op call). + CopilotUserResolved *bool `json:"copilotUserResolved,omitempty"` // Whether the operation succeeded Success bool `json:"success"` } +// Availability of built-in job tools surfaced to boundary consumers. +// Experimental: SessionSettingsBuiltInToolAvailabilitySnapshot is part of an experimental +// API and may change or be removed. +type SessionSettingsBuiltInToolAvailabilitySnapshot struct { + CreatePullRequest *bool `json:"createPullRequest,omitempty"` + ReportProgress *bool `json:"reportProgress,omitempty"` +} + +// Named Rust-owned settings predicate to evaluate for this session. +// Experimental: SessionSettingsEvaluatePredicateRequest is part of an experimental API and +// may change or be removed. +type SessionSettingsEvaluatePredicateRequest struct { + // Predicate name. The runtime owns the raw feature-flag names and composition logic. + Name SessionSettingsPredicateName `json:"name"` + // Tool name for tool-scoped predicates such as trivial-change handling. + ToolName *string `json:"toolName,omitempty"` +} + +// Result of evaluating a Rust-owned settings predicate. +// Experimental: SessionSettingsEvaluatePredicateResult is part of an experimental API and +// may change or be removed. +type SessionSettingsEvaluatePredicateResult struct { + Enabled bool `json:"enabled"` +} + +// Redacted job settings for a session. The job nonce is excluded. +// Experimental: SessionSettingsJobSnapshot is part of an experimental API and may change or +// be removed. +type SessionSettingsJobSnapshot struct { + BuiltInToolAvailability *SessionSettingsBuiltInToolAvailabilitySnapshot `json:"builtInToolAvailability,omitempty"` + EventType *string `json:"eventType,omitempty"` + IsTriggerJob *bool `json:"isTriggerJob,omitempty"` +} + +// Redacted model routing settings for a session. +// Experimental: SessionSettingsModelSnapshot is part of an experimental API and may change +// or be removed. +type SessionSettingsModelSnapshot struct { + CallbackURL *string `json:"callbackUrl,omitempty"` + DefaultReasoningEffort *string `json:"defaultReasoningEffort,omitempty"` + InstanceID *string `json:"instanceId,omitempty"` + Model *string `json:"model,omitempty"` +} + +// Online-evaluation settings safe to expose across the SDK boundary. +// Experimental: SessionSettingsOnlineEvaluationSnapshot is part of an experimental API and +// may change or be removed. +type SessionSettingsOnlineEvaluationSnapshot struct { + DisableOnlineEvaluation *bool `json:"disableOnlineEvaluation,omitempty"` + EnableOnlineEvaluationOutputFile *bool `json:"enableOnlineEvaluationOutputFile,omitempty"` +} + +// Redacted repository and GitHub host settings for a session. +// Experimental: SessionSettingsRepoSnapshot is part of an experimental API and may change +// or be removed. +type SessionSettingsRepoSnapshot struct { + Branch *string `json:"branch,omitempty"` + Commit *string `json:"commit,omitempty"` + Host *string `json:"host,omitempty"` + HostProtocol *string `json:"hostProtocol,omitempty"` + ID *float64 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + OwnerID *float64 `json:"ownerId,omitempty"` + OwnerName *string `json:"ownerName,omitempty"` + PrCommitCount *float64 `json:"prCommitCount,omitempty"` + ReadWrite *bool `json:"readWrite,omitempty"` + SecretScanningURL *string `json:"secretScanningUrl,omitempty"` + ServerURL *string `json:"serverUrl,omitempty"` +} + +// Redacted, serializable view of session runtime settings for SDK boundary consumers. +// Secrets and raw feature flags are intentionally excluded. +// Experimental: SessionSettingsSnapshot is part of an experimental API and may change or be +// removed. +type SessionSettingsSnapshot struct { + ClientName *string `json:"clientName,omitempty"` + Job SessionSettingsJobSnapshot `json:"job"` + Model SessionSettingsModelSnapshot `json:"model"` + OnlineEvaluation SessionSettingsOnlineEvaluationSnapshot `json:"onlineEvaluation"` + Repo SessionSettingsRepoSnapshot `json:"repo"` + StartTimeMs *float64 `json:"startTimeMs,omitempty"` + TimeoutMs *float64 `json:"timeoutMs,omitempty"` + Validation SessionSettingsValidationSnapshot `json:"validation"` + Version *string `json:"version,omitempty"` +} + +// Redacted validation and memory-tool settings for a session. +// Experimental: SessionSettingsValidationSnapshot is part of an experimental API and may +// change or be removed. +type SessionSettingsValidationSnapshot struct { + AdvisoryEnabled *bool `json:"advisoryEnabled,omitempty"` + CodeqlEnabled *bool `json:"codeqlEnabled,omitempty"` + CodeReviewEnabled *bool `json:"codeReviewEnabled,omitempty"` + CodeReviewModel *string `json:"codeReviewModel,omitempty"` + DependabotTimeout *float64 `json:"dependabotTimeout,omitempty"` + MemoryStoreEnabled *bool `json:"memoryStoreEnabled,omitempty"` + MemoryVoteEnabled *bool `json:"memoryVoteEnabled,omitempty"` + SecretScanningEnabled *bool `json:"secretScanningEnabled,omitempty"` + Timeout *float64 `json:"timeout,omitempty"` +} + // UUID prefix to resolve to a unique session ID. // Experimental: SessionsFindByPrefixRequest is part of an experimental API and may change // or be removed. @@ -7192,7 +8796,7 @@ type SessionsLoadDeferredRepoHooksRequest struct { SessionID string `json:"sessionId"` } -// Schema for the `SessionsOpenProgress` type. +// `sessions.open` handoff progress update with step, status, and optional message. // Experimental: SessionsOpenProgress is part of an experimental API and may change or be // removed. type SessionsOpenProgress struct { @@ -7204,25 +8808,6 @@ type SessionsOpenProgress struct { Step SessionsOpenProgressStep `json:"step"` } -// Schema for the `SessionsPollSpawnedSessionsEvent` type. -// Experimental: SessionsPollSpawnedSessionsEvent is part of an experimental API and may -// change or be removed. -type SessionsPollSpawnedSessionsEvent struct { - // Session id of the newly-spawned session. - SessionID string `json:"sessionId"` -} - -// Experimental: SessionsPollSpawnedSessionsRequest is part of an experimental API and may -// change or be removed. -type SessionsPollSpawnedSessionsRequest struct { - // Opaque cursor returned by a previous poll. Omit on the first call to receive any spawn - // events buffered since the runtime started. - Cursor *string `json:"cursor,omitempty"` - // Milliseconds to wait for new spawn events when the cursor is at the tail. 0 (default) - // returns immediately even if no events are buffered. Capped at 60000ms. - WaitMs *int32 `json:"waitMs,omitempty"` -} - // Age threshold and optional flags controlling which old sessions are pruned (or simulated // when dryRun is true). // Experimental: SessionsPruneOldRequest is part of an experimental API and may change or be @@ -7384,6 +8969,9 @@ type SessionUpdateOptionsParams struct { AdditionalContentExclusionPolicies []OptionsUpdateAdditionalContentExclusionPolicy `json:"additionalContentExclusionPolicies,omitzero"` // Runtime context discriminator (e.g., `cli`, `actions`). AgentContext *string `json:"agentContext,omitempty"` + // Whether to include instructions from every MCP server in the system prompt instead of + // only allowlisted servers. + AllowAllMCPServerInstructions *bool `json:"allowAllMcpServerInstructions,omitempty"` // Whether to disable the `ask_user` tool (encourages autonomous behavior). AskUserDisabled *bool `json:"askUserDisabled,omitempty"` // Allowlist of tool names available to this session. @@ -7435,10 +9023,18 @@ type SessionUpdateOptionsParams struct { // Override directory for the session-events log. When unset, the runtime's default events // log directory is used. EventsLogDirectory *string `json:"eventsLogDirectory,omitempty"` + // Built-in subagent names to exclude from this session. Excluded built-ins are hidden from + // agent discovery and cannot be dispatched unless a custom agent with the same name is + // available. + ExcludedBuiltinAgents []string `json:"excludedBuiltinAgents,omitzero"` // Denylist of tool names for this session. ExcludedTools []string `json:"excludedTools,omitzero"` // Map of feature-flag IDs to their boolean enabled state. FeatureFlags map[string]bool `json:"featureFlags,omitzero"` + // Built-in subagent names to include in this session. When specified, only these built-ins + // are available, subject to runtime availability and exclusions. Custom agents with the + // same name remain available. Set to null to remove the allowlist restriction. + IncludedBuiltinAgents []string `json:"includedBuiltinAgents,omitzero"` // Full set of installed plugins for the session. Replaces the existing list; the runtime // invalidates the skills cache only when the list materially changes. InstalledPlugins []SessionInstalledPlugin `json:"installedPlugins,omitzero"` @@ -7479,6 +9075,8 @@ type SessionUpdateOptionsParams struct { // capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the // field to leave the existing capability set unchanged. SessionCapabilities []SessionCapability `json:"sessionCapabilities,omitzero"` + // Optional session limits. Pass null to clear the session limits. + SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` // Shell init profile (`None` or `NonInteractive`). ShellInitProfile *string `json:"shellInitProfile,omitempty"` // Per-shell process flags (e.g., `pwsh` arguments). @@ -7498,6 +9096,8 @@ type SessionUpdateOptionsParams struct { ToolFilterPrecedence *OptionsUpdateToolFilterPrecedence `json:"toolFilterPrecedence,omitempty"` // Optional path for trajectory output. TrajectoryFile *string `json:"trajectoryFile,omitempty"` + // Output verbosity level for supported models. + Verbosity *Verbosity `json:"verbosity,omitempty"` // Absolute working-directory path for shell tools. WorkingDirectory *string `json:"workingDirectory,omitempty"` } @@ -7506,6 +9106,8 @@ type SessionUpdateOptionsParams struct { // Experimental: SessionUpdateOptionsResult is part of an experimental API and may change or // be removed. type SessionUpdateOptionsResult struct { + // Number of hooks loaded from installed plugins, returned when installedPlugins is updated + PluginHookCount *int64 `json:"pluginHookCount,omitempty"` // Whether the operation succeeded Success bool `json:"success"` } @@ -7605,7 +9207,8 @@ type ShutdownRequest struct { Type *ShutdownType `json:"type,omitempty"` } -// Schema for the `Skill` type. +// Skill metadata available to a session, with name, description, source, enabled/invocable +// state, path, plugin, and argument hint. // Experimental: Skill is part of an experimental API and may change or be removed. type Skill struct { // Optional freeform hint describing the skill's expected arguments, from the @@ -7627,7 +9230,8 @@ type Skill struct { UserInvocable bool `json:"userInvocable"` } -// Schema for the `SkillDiscoveryPath` type. +// Canonical directory where skills can be discovered or created, with scope, preference, +// and optional project path. // Experimental: SkillDiscoveryPath is part of an experimental API and may change or be // removed. type SkillDiscoveryPath struct { @@ -7659,11 +9263,15 @@ type SkillList struct { } // Skill names to mark as disabled in global configuration, replacing any previous list. +// Experimental: SkillsConfigSetDisabledSkillsRequest is part of an experimental API and may +// change or be removed. type SkillsConfigSetDisabledSkillsRequest struct { // List of skill names to disable DisabledSkills []string `json:"disabledSkills"` } +// Experimental: SkillsConfigSetDisabledSkillsResult is part of an experimental API and may +// change or be removed. type SkillsConfigSetDisabledSkillsResult struct { } @@ -7676,6 +9284,8 @@ type SkillsDisableRequest struct { } // Optional project paths and additional skill directories to include in discovery. +// Experimental: SkillsDiscoverRequest is part of an experimental API and may change or be +// removed. type SkillsDiscoverRequest struct { // When true, omit skills from the host's global sources (personal, custom, plugin, and // built-in), returning only project-scoped skills. For multitenant deployments. @@ -7714,7 +9324,7 @@ type SkillsGetInvokedResult struct { Skills []SkillsInvokedSkill `json:"skills"` } -// Schema for the `SkillsInvokedSkill` type. +// Skill invocation record with name, path, content, allowed tools, and turn number. // Experimental: SkillsInvokedSkill is part of an experimental API and may change or be // removed. type SkillsInvokedSkill struct { @@ -7740,7 +9350,8 @@ type SkillsLoadDiagnostics struct { Warnings []string `json:"warnings"` } -// Schema for the `SlashCommandInfo` type. +// Slash-command metadata with name, aliases, description, kind, input hint, execution +// allowance, and schedulability. // Experimental: SlashCommandInfo is part of an experimental API and may change or be // removed. type SlashCommandInfo struct { @@ -7769,6 +9380,9 @@ type SlashCommandInfo struct { // Experimental: SlashCommandInput is part of an experimental API and may change or be // removed. type SlashCommandInput struct { + // Optional literal choices the input accepts, each with a human-facing description; clients + // may render these as selectable options + Choices []SlashCommandInputChoice `json:"choices,omitzero"` // Optional completion hint for the input (e.g. 'directory' for filesystem path completion) Completion *SlashCommandInputCompletion `json:"completion,omitempty"` // Hint to display when command input has not been provided @@ -7781,8 +9395,18 @@ type SlashCommandInput struct { Required *bool `json:"required,omitempty"` } -// Result of invoking the slash command (text output, prompt to send to the agent, or -// completion). +// A literal choice the command input accepts, with a human-facing description +// Experimental: SlashCommandInputChoice is part of an experimental API and may change or be +// removed. +type SlashCommandInputChoice struct { + // Human-readable description shown alongside the choice + Description string `json:"description"` + // The literal choice value (e.g. 'on', 'off', 'show') + Name string `json:"name"` +} + +// Result of invoking the slash command (text output, prompt to send to the agent, +// completion, or subcommand selection). // Experimental: SlashCommandInvocationResult is part of an experimental API and may change // or be removed. type SlashCommandInvocationResult interface { @@ -7800,7 +9424,8 @@ func (r RawSlashCommandInvocationResultData) Kind() SlashCommandInvocationResult return r.Discriminator } -// Schema for the `SlashCommandAgentPromptResult` type. +// Slash-command invocation result that submits an agent prompt, with display prompt, +// optional mode, optional user-facing notice, and settings-change flag. // Experimental: SlashCommandAgentPromptResult is part of an experimental API and may change // or be removed. type SlashCommandAgentPromptResult struct { @@ -7808,6 +9433,8 @@ type SlashCommandAgentPromptResult struct { DisplayPrompt string `json:"displayPrompt"` // Optional target session mode for the agent prompt Mode *SessionMode `json:"mode,omitempty"` + // Optional user-facing notice to show before the prompt is submitted + Notice *string `json:"notice,omitempty"` // Prompt to submit to the agent Prompt string `json:"prompt"` // True when the invocation mutated user runtime settings; consumers caching settings should @@ -7820,7 +9447,8 @@ func (SlashCommandAgentPromptResult) Kind() SlashCommandInvocationResultKind { return SlashCommandInvocationResultKindAgentPrompt } -// Schema for the `SlashCommandCompletedResult` type. +// Slash-command invocation result indicating completion, with optional message and +// settings-change flag. // Experimental: SlashCommandCompletedResult is part of an experimental API and may change // or be removed. type SlashCommandCompletedResult struct { @@ -7836,7 +9464,8 @@ func (SlashCommandCompletedResult) Kind() SlashCommandInvocationResultKind { return SlashCommandInvocationResultKindCompleted } -// Schema for the `SlashCommandSelectSubcommandResult` type. +// Slash-command invocation result asking the client to present subcommand options for a +// parent command. // Experimental: SlashCommandSelectSubcommandResult is part of an experimental API and may // change or be removed. type SlashCommandSelectSubcommandResult struct { @@ -7856,7 +9485,7 @@ func (SlashCommandSelectSubcommandResult) Kind() SlashCommandInvocationResultKin return SlashCommandInvocationResultKindSelectSubcommand } -// Schema for the `SlashCommandTextResult` type. +// Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. // Experimental: SlashCommandTextResult is part of an experimental API and may change or be // removed. type SlashCommandTextResult struct { @@ -7876,7 +9505,8 @@ func (SlashCommandTextResult) Kind() SlashCommandInvocationResultKind { return SlashCommandInvocationResultKindText } -// Schema for the `SlashCommandSelectSubcommandOption` type. +// Selectable slash-command subcommand option with name, description, and optional group +// label. // Experimental: SlashCommandSelectSubcommandOption is part of an experimental API and may // change or be removed. type SlashCommandSelectSubcommandOption struct { @@ -7896,6 +9526,11 @@ type SubagentSettings struct { Agents map[string]SubagentSettingsEntry `json:"agents,omitzero"` // Names of subagents the user has turned off; they cannot be dispatched DisabledSubagents []string `json:"disabledSubagents,omitzero"` + // Maximum number of subagents that can run concurrently; applies to usage-based billing + // users only + MaxConcurrency *int32 `json:"maxConcurrency,omitempty"` + // Maximum subagent nesting depth; applies to usage-based billing users only + MaxDepth *int32 `json:"maxDepth,omitempty"` } // Subagent model, reasoning effort, and context tier settings @@ -7910,7 +9545,7 @@ type SubagentSettingsEntry struct { Model *string `json:"model,omitempty"` } -// Schema for the `TaskInfo` type. +// Tracked task union returned by task APIs, containing either an agent task or a shell task. // Experimental: TaskInfo is part of an experimental API and may change or be removed. type TaskInfo interface { taskInfo() @@ -7927,7 +9562,8 @@ func (r RawTaskInfoData) Type() TaskInfoType { return r.Discriminator } -// Schema for the `TaskAgentInfo` type. +// Tracked background agent task metadata, including IDs, status, timing, agent type, +// prompt, model, result, and latest response. // Experimental: TaskAgentInfo is part of an experimental API and may change or be removed. type TaskAgentInfo struct { // ISO 8601 timestamp when the current active period began @@ -7976,7 +9612,8 @@ func (TaskAgentInfo) Type() TaskInfoType { return TaskInfoTypeAgent } -// Schema for the `TaskShellInfo` type. +// Tracked shell task metadata, including ID, command, status, timing, attachment/execution +// mode, log path, and PID. // Experimental: TaskShellInfo is part of an experimental API and may change or be removed. type TaskShellInfo struct { // Whether the shell runs inside a managed PTY session or as an independent background @@ -8032,7 +9669,8 @@ func (r RawTaskProgressData) Type() TaskProgressType { return r.Discriminator } -// Schema for the `TaskAgentProgress` type. +// Progress snapshot for an agent task, with recent activity lines and optional latest +// intent. // Experimental: TaskAgentProgress is part of an experimental API and may change or be // removed. type TaskAgentProgress struct { @@ -8047,7 +9685,8 @@ func (TaskAgentProgress) Type() TaskProgressType { return TaskProgressTypeAgent } -// Schema for the `TaskShellProgress` type. +// Progress snapshot for a shell task, with recent stdout/stderr output and optional process +// ID. // Experimental: TaskShellProgress is part of an experimental API and may change or be // removed. type TaskShellProgress struct { @@ -8062,7 +9701,7 @@ func (TaskShellProgress) Type() TaskProgressType { return TaskProgressTypeShell } -// Schema for the `TaskProgressLine` type. +// Timestamped display line for task progress output or recent agent activity. // Experimental: TaskProgressLine is part of an experimental API and may change or be // removed. type TaskProgressLine struct { @@ -8232,7 +9871,9 @@ type TelemetrySetFeatureOverridesRequest struct { Features map[string]string `json:"features"` } -// Schema for the `Tool` type. +// Built-in tool metadata with identifier, optional namespaced name, description, +// input-parameter schema, and usage instructions. +// Experimental: Tool is part of an experimental API and may change or be removed. type Tool struct { // Description of what the tool does Description string `json:"description"` @@ -8248,6 +9889,7 @@ type Tool struct { } // Built-in tools available for the requested model, with their parameters and instructions. +// Experimental: ToolList is part of an experimental API and may change or be removed. type ToolList struct { // List of available built-in tools with metadata Tools []Tool `json:"tools"` @@ -8270,6 +9912,8 @@ type ToolsInitializeAndValidateResult struct { } // Optional model identifier whose tool overrides should be applied to the listing. +// Experimental: ToolsListRequest is part of an experimental API and may change or be +// removed. type ToolsListRequest struct { // Optional model ID — when provided, the returned tool list reflects model-specific // overrides @@ -8290,7 +9934,8 @@ type UIElicitationArrayAnyOfFieldItems struct { AnyOf []UIElicitationArrayAnyOfFieldItemsAnyOf `json:"anyOf"` } -// Schema for the `UIElicitationArrayAnyOfFieldItemsAnyOf` type. +// Selectable option for a UI elicitation multi-select array item, with submitted value and +// display label. // Experimental: UIElicitationArrayAnyOfFieldItemsAnyOf is part of an experimental API and // may change or be removed. type UIElicitationArrayAnyOfFieldItemsAnyOf struct { @@ -8310,7 +9955,7 @@ type UIElicitationArrayEnumFieldItems struct { Type UIElicitationArrayEnumFieldItemsType `json:"type"` } -// Schema for the `UIElicitationFieldValue` type. +// Submitted UI elicitation field value: string, number, boolean, or an array of strings. // Experimental: UIElicitationFieldValue is part of an experimental API and may change or be // removed. type UIElicitationFieldValue interface { @@ -8549,7 +10194,8 @@ func (UIElicitationStringOneOfField) Type() UIElicitationSchemaPropertyType { return UIElicitationSchemaPropertyTypeString } -// Schema for the `UIElicitationStringOneOfFieldOneOf` type. +// Selectable option for a UI elicitation single-select string field, with submitted value +// and display label. // Experimental: UIElicitationStringOneOfFieldOneOf is part of an experimental API and may // change or be removed. type UIElicitationStringOneOfFieldOneOf struct { @@ -8587,7 +10233,8 @@ type UIEphemeralQueryResult struct { Answer string `json:"answer"` } -// Schema for the `UIExitPlanModeResponse` type. +// User response for a pending exit-plan-mode request, with approval state, selected action, +// auto-approve flag, and feedback. // Experimental: UIExitPlanModeResponse is part of an experimental API and may change or be // removed. type UIExitPlanModeResponse struct { @@ -8630,7 +10277,8 @@ type UIHandlePendingElicitationRequest struct { type UIHandlePendingExitPlanModeRequest struct { // The unique request ID from the exit_plan_mode.requested event RequestID string `json:"requestId"` - // Schema for the `UIExitPlanModeResponse` type. + // User response for a pending exit-plan-mode request, with approval state, selected action, + // auto-approve flag, and feedback. Response UIExitPlanModeResponse `json:"response"` } @@ -8663,13 +10311,25 @@ type UIHandlePendingSamplingRequest struct { type UIHandlePendingSamplingResponse struct { } +// Request ID of a pending `session_limits_exhausted.requested` event and the user's +// selected limit action. +// Experimental: UIHandlePendingSessionLimitsExhaustedRequest is part of an experimental API +// and may change or be removed. +type UIHandlePendingSessionLimitsExhaustedRequest struct { + // The unique request ID from the session_limits_exhausted.requested event + RequestID string `json:"requestId"` + // The selected session-limit action. + Response UISessionLimitsExhaustedResponse `json:"response"` +} + // Request ID of a pending `user_input.requested` event and the user's response. // Experimental: UIHandlePendingUserInputRequest is part of an experimental API and may // change or be removed. type UIHandlePendingUserInputRequest struct { // The unique request ID from the user_input.requested event RequestID string `json:"requestId"` - // Schema for the `UIUserInputResponse` type. + // User response for a pending user-input request, with answer text and whether it was typed + // freeform. Response UIUserInputResponse `json:"response"` } @@ -8687,6 +10347,18 @@ type UIRegisterDirectAutoModeSwitchHandlerResult struct { Handle string `json:"handle"` } +// The user's selected action for an exhausted session limit. +// Experimental: UISessionLimitsExhaustedResponse is part of an experimental API and may +// change or be removed. +type UISessionLimitsExhaustedResponse struct { + // Action selected by the user. + Action UISessionLimitsExhaustedResponseAction `json:"action"` + // AI Credits to add to the current max when action is 'add'. + AdditionalAiCredits *float64 `json:"additionalAiCredits,omitempty"` + // New absolute max AI Credits when action is 'set'. + MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` +} + // Opaque handle previously returned by `registerDirectAutoModeSwitchHandler` to release. // Experimental: UIUnregisterDirectAutoModeSwitchHandlerRequest is part of an experimental // API and may change or be removed. @@ -8704,7 +10376,8 @@ type UIUnregisterDirectAutoModeSwitchHandlerResult struct { Unregistered bool `json:"unregistered"` } -// Schema for the `UIUserInputResponse` type. +// User response for a pending user-input request, with answer text and whether it was typed +// freeform. // Experimental: UIUserInputResponse is part of an experimental API and may change or be // removed. type UIUserInputResponse struct { @@ -8767,7 +10440,8 @@ type UsageMetricsCodeChanges struct { LinesRemoved int64 `json:"linesRemoved"` } -// Schema for the `UsageMetricsModelMetric` type. +// Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and +// per-token-type details. // Experimental: UsageMetricsModelMetric is part of an experimental API and may change or be // removed. type UsageMetricsModelMetric struct { @@ -8791,7 +10465,7 @@ type UsageMetricsModelMetricRequests struct { Count int64 `json:"count"` } -// Schema for the `UsageMetricsModelMetricTokenDetail` type. +// Per-model token-detail entry containing the accumulated token count for one token type. // Experimental: UsageMetricsModelMetricTokenDetail is part of an experimental API and may // change or be removed. type UsageMetricsModelMetricTokenDetail struct { @@ -8815,7 +10489,7 @@ type UsageMetricsModelMetricUsage struct { ReasoningTokens *int64 `json:"reasoningTokens,omitempty"` } -// Schema for the `UsageMetricsTokenDetail` type. +// Session-wide token-detail entry containing the accumulated token count for one token type. // Experimental: UsageMetricsTokenDetail is part of an experimental API and may change or be // removed. type UsageMetricsTokenDetail struct { @@ -8839,9 +10513,57 @@ type UserRequestedShellCommandResult struct { ToolCallID string `json:"toolCallId"` } +// A single user setting's effective value alongside its default, so consumers can render +// settings left at their default. +// Experimental: UserSettingMetadata is part of an experimental API and may change or be +// removed. +type UserSettingMetadata struct { + // The centrally-known default for this setting (null when no default is registered). + Default any `json:"default"` + // True when the user has not set an explicit value for this setting (i.e. it is left at its + // default). Reflects whether the user has overridden the key, not whether the effective + // value happens to equal the default — a key explicitly set to a value identical to the + // default still reports false. + IsDefault bool `json:"isDefault"` + // The effective value: the user's value if set, otherwise the default. + Value any `json:"value"` +} + +// Per-key metadata for every known user setting (settings.json overlaid with the legacy +// config.json, config.json wins), including settings left at their default. Excludes +// repository- and enterprise-managed overrides. +// Experimental: UserSettingsGetResult is part of an experimental API and may change or be +// removed. +type UserSettingsGetResult struct { + // Every known user setting keyed by setting name, each with its effective value, default, + // and whether it is at the default. + Settings map[string]UserSettingMetadata `json:"settings"` +} + +// Experimental: UserSettingsReloadResult is part of an experimental API and may change or +// be removed. type UserSettingsReloadResult struct { } +// Partial user settings to write to settings.json. Each top-level key is written +// individually, replacing the existing value; a key whose value is null is removed. +// Experimental: UserSettingsSetRequest is part of an experimental API and may change or be +// removed. +type UserSettingsSetRequest struct { + // Partial user settings to write, as a free-form object keyed by setting name + Settings any `json:"settings"` +} + +// Outcome of writing user settings. +// Experimental: UserSettingsSetResult is part of an experimental API and may change or be +// removed. +type UserSettingsSetResult struct { + // Top-level keys whose write landed in settings.json but is shadowed by a value still + // present in the legacy config.json (config.json wins on read). The write does not take + // effect until the legacy value is removed. + ShadowedKeys []string `json:"shadowedKeys"` +} + // The approval to add as a session-scoped rule // Experimental: UserToolSessionApproval is part of an experimental API and may change or be // removed. @@ -8860,7 +10582,7 @@ func (r RawUserToolSessionApprovalData) Kind() UserToolSessionApprovalKind { return r.Discriminator } -// Schema for the `UserToolSessionApprovalCommands` type. +// Session-scoped tool-approval rule for specific shell command identifiers. // Experimental: UserToolSessionApprovalCommands is part of an experimental API and may // change or be removed. type UserToolSessionApprovalCommands struct { @@ -8873,7 +10595,7 @@ func (UserToolSessionApprovalCommands) Kind() UserToolSessionApprovalKind { return UserToolSessionApprovalKindCommands } -// Schema for the `UserToolSessionApprovalCustomTool` type. +// Session-scoped tool-approval rule for a custom tool, keyed by tool name. // Experimental: UserToolSessionApprovalCustomTool is part of an experimental API and may // change or be removed. type UserToolSessionApprovalCustomTool struct { @@ -8886,7 +10608,8 @@ func (UserToolSessionApprovalCustomTool) Kind() UserToolSessionApprovalKind { return UserToolSessionApprovalKindCustomTool } -// Schema for the `UserToolSessionApprovalExtensionManagement` type. +// Session-scoped tool-approval rule for extension-management operations, optionally +// narrowed by operation. // Experimental: UserToolSessionApprovalExtensionManagement is part of an experimental API // and may change or be removed. type UserToolSessionApprovalExtensionManagement struct { @@ -8899,7 +10622,8 @@ func (UserToolSessionApprovalExtensionManagement) Kind() UserToolSessionApproval return UserToolSessionApprovalKindExtensionManagement } -// Schema for the `UserToolSessionApprovalExtensionPermissionAccess` type. +// Session-scoped tool-approval rule for an extension's permission-gated capability access, +// keyed by extension name. // Experimental: UserToolSessionApprovalExtensionPermissionAccess is part of an experimental // API and may change or be removed. type UserToolSessionApprovalExtensionPermissionAccess struct { @@ -8912,7 +10636,8 @@ func (UserToolSessionApprovalExtensionPermissionAccess) Kind() UserToolSessionAp return UserToolSessionApprovalKindExtensionPermissionAccess } -// Schema for the `UserToolSessionApprovalMcp` type. +// Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when +// `toolName` is null. // Experimental: UserToolSessionApprovalMCP is part of an experimental API and may change or // be removed. type UserToolSessionApprovalMCP struct { @@ -8927,7 +10652,7 @@ func (UserToolSessionApprovalMCP) Kind() UserToolSessionApprovalKind { return UserToolSessionApprovalKindMCP } -// Schema for the `UserToolSessionApprovalMemory` type. +// Session-scoped tool-approval rule for writes to long-term memory. // Experimental: UserToolSessionApprovalMemory is part of an experimental API and may change // or be removed. type UserToolSessionApprovalMemory struct { @@ -8938,7 +10663,7 @@ func (UserToolSessionApprovalMemory) Kind() UserToolSessionApprovalKind { return UserToolSessionApprovalKindMemory } -// Schema for the `UserToolSessionApprovalRead` type. +// Session-scoped tool-approval rule for read-only filesystem operations. // Experimental: UserToolSessionApprovalRead is part of an experimental API and may change // or be removed. type UserToolSessionApprovalRead struct { @@ -8949,7 +10674,7 @@ func (UserToolSessionApprovalRead) Kind() UserToolSessionApprovalKind { return UserToolSessionApprovalKindRead } -// Schema for the `UserToolSessionApprovalWrite` type. +// Session-scoped tool-approval rule for filesystem write operations. // Experimental: UserToolSessionApprovalWrite is part of an experimental API and may change // or be removed. type UserToolSessionApprovalWrite struct { @@ -8960,6 +10685,46 @@ func (UserToolSessionApprovalWrite) Kind() UserToolSessionApprovalKind { return UserToolSessionApprovalKindWrite } +// Current sharing status and shareable GitHub URL for a session. +// Experimental: VisibilityGetResult is part of an experimental API and may change or be +// removed. +type VisibilityGetResult struct { + // Shareable GitHub URL for the session. Present when the session is synced and the URL can + // be resolved. + ShareURL *string `json:"shareUrl,omitempty"` + // Current sharing status. Absent when the session is not synced or the status could not be + // retrieved (e.g. the user is not authenticated). + Status *SessionVisibilityStatus `json:"status,omitempty"` + // Whether the session has been synced to Mission Control (i.e. has a GitHub task). When + // false, the session cannot be shared and `status`/`shareUrl` are absent. + Synced bool `json:"synced"` +} + +// Desired sharing status for the session. +// Experimental: VisibilitySetRequest is part of an experimental API and may change or be +// removed. +type VisibilitySetRequest struct { + // Sharing status to apply. "repo" makes the session visible to repository readers; + // "unshared" restricts it to the creator and collaborators. + Status SessionVisibilityStatus `json:"status"` +} + +// Effective sharing status and shareable GitHub URL after updating session visibility. +// Experimental: VisibilitySetResult is part of an experimental API and may change or be +// removed. +type VisibilitySetResult struct { + // Shareable GitHub URL for the session. Present when the session is synced and the URL can + // be resolved. + ShareURL *string `json:"shareUrl,omitempty"` + // Effective sharing status after the update. May differ from the requested status for task + // types that are already visible to repository readers by default. Absent when the update + // could not be applied (e.g. the session is not synced or the user is not authenticated). + Status *SessionVisibilityStatus `json:"status,omitempty"` + // Whether the session has been synced to Mission Control (i.e. has a GitHub task). When + // false, the visibility change could not be applied and `status`/`shareUrl` are absent. + Synced bool `json:"synced"` +} + // A single changed file and its unified diff. // Experimental: WorkspaceDiffFileChange is part of an experimental API and may change or be // removed. @@ -8992,7 +10757,8 @@ type WorkspaceDiffResult struct { RequestedMode WorkspaceDiffMode `json:"requestedMode"` } -// Schema for the `WorkspacesCheckpoints` type. +// Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint +// filename. // Experimental: WorkspacesCheckpoints is part of an experimental API and may change or be // removed. type WorkspacesCheckpoints struct { @@ -9170,6 +10936,21 @@ const ( AbortReasonUserInitiated AbortReason = "user_initiated" ) +// Resolved Anthropic adaptive-thinking capability for a model. +// Experimental: AdaptiveThinkingSupport is part of an experimental API and may change or be +// removed. +type AdaptiveThinkingSupport string + +const ( + // The model accepts adaptive thinking but also accepts thinking.type='enabled' + AdaptiveThinkingSupportOptional AdaptiveThinkingSupport = "optional" + // The model only accepts adaptive thinking and rejects thinking.type='enabled' with HTTP + // 400 (e.g. opus-4.7/4.8) + AdaptiveThinkingSupportRequired AdaptiveThinkingSupport = "required" + // The model does not accept thinking.type='adaptive' + AdaptiveThinkingSupportUnsupported AdaptiveThinkingSupport = "unsupported" +) + // Which tier this directory belongs to // Experimental: AgentDiscoveryPathScope is part of an experimental API and may change or be // removed. @@ -9356,12 +11137,21 @@ const ( type AttachmentType string const ( - AttachmentTypeBlob AttachmentType = "blob" - AttachmentTypeDirectory AttachmentType = "directory" - AttachmentTypeExtensionContext AttachmentType = "extension_context" - AttachmentTypeFile AttachmentType = "file" - AttachmentTypeGitHubReference AttachmentType = "github_reference" - AttachmentTypeSelection AttachmentType = "selection" + AttachmentTypeBlob AttachmentType = "blob" + AttachmentTypeDirectory AttachmentType = "directory" + AttachmentTypeExtensionContext AttachmentType = "extension_context" + AttachmentTypeFile AttachmentType = "file" + AttachmentTypeGitHubActionsJob AttachmentType = "github_actions_job" + AttachmentTypeGitHubCommit AttachmentType = "github_commit" + AttachmentTypeGitHubFile AttachmentType = "github_file" + AttachmentTypeGitHubFileDiff AttachmentType = "github_file_diff" + AttachmentTypeGitHubReference AttachmentType = "github_reference" + AttachmentTypeGitHubRelease AttachmentType = "github_release" + AttachmentTypeGitHubRepository AttachmentType = "github_repository" + AttachmentTypeGitHubSnippet AttachmentType = "github_snippet" + AttachmentTypeGitHubTreeComparison AttachmentType = "github_tree_comparison" + AttachmentTypeGitHubURL AttachmentType = "github_url" + AttachmentTypeSelection AttachmentType = "selection" ) // Type discriminator for AuthInfo. @@ -9393,6 +11183,8 @@ const ( // Controls how MCP tool result content is filtered: none leaves content unchanged, markdown // sanitizes HTML while preserving Markdown-friendly output, and hidden_characters removes // characters that can hide directives. +// Experimental: ContentFilterMode is part of an experimental API and may change or be +// removed. type ContentFilterMode string const ( @@ -9422,7 +11214,70 @@ const ( CopilotAPITokenAuthInfoHostHTTPSGitHubCom CopilotAPITokenAuthInfoHost = "https://github.com" ) +// Kind discriminator for DebugCollectLogsDestination. +type DebugCollectLogsDestinationKind string + +const ( + DebugCollectLogsDestinationKindArchive DebugCollectLogsDestinationKind = "archive" + DebugCollectLogsDestinationKindDirectory DebugCollectLogsDestinationKind = "directory" +) + +// Kind of caller-provided debug log entry. +// Experimental: DebugCollectLogsEntryKind is part of an experimental API and may change or +// be removed. +type DebugCollectLogsEntryKind string + +const ( + // Include files from a server-local directory recursively. + DebugCollectLogsEntryKindDirectory DebugCollectLogsEntryKind = "directory" + // Include a single server-local file. + DebugCollectLogsEntryKindFile DebugCollectLogsEntryKind = "file" +) + +// How a collected debug entry should be redacted before being staged. +// Experimental: DebugCollectLogsRedaction is part of an experimental API and may change or +// be removed. +type DebugCollectLogsRedaction string + +const ( + // Redact each non-empty line as a session event JSON object, falling back to plain-text + // redaction for malformed lines. + DebugCollectLogsRedactionEventsJsonl DebugCollectLogsRedaction = "events-jsonl" + // Redact the file as plain UTF-8 log text. + DebugCollectLogsRedactionPlainText DebugCollectLogsRedaction = "plain-text" +) + +// Destination kind that was written. +// Experimental: DebugCollectLogsResultKind is part of an experimental API and may change or +// be removed. +type DebugCollectLogsResultKind string + +const ( + // A .tgz archive was written. + DebugCollectLogsResultKindArchive DebugCollectLogsResultKind = "archive" + // A directory containing redacted files was written. + DebugCollectLogsResultKindDirectory DebugCollectLogsResultKind = "directory" +) + +// Source category for a collected debug bundle entry. +// Experimental: DebugCollectLogsSource is part of an experimental API and may change or be +// removed. +type DebugCollectLogsSource string + +const ( + // Caller-provided diagnostic entry. + DebugCollectLogsSourceAdditional DebugCollectLogsSource = "additional" + // Session event log. + DebugCollectLogsSourceEvents DebugCollectLogsSource = "events" + // Process log for the session. + DebugCollectLogsSourceProcessLog DebugCollectLogsSource = "process-log" + // Interactive shell log for the session. + DebugCollectLogsSourceShellLog DebugCollectLogsSource = "shell-log" +) + // Server transport type: stdio, http, sse (deprecated), or memory +// Experimental: DiscoveredMCPServerType is part of an experimental API and may change or be +// removed. type DiscoveredMCPServerType string const ( @@ -9536,6 +11391,7 @@ const ( ExternalToolTextResultForLlmContentTypeImage ExternalToolTextResultForLlmContentType = "image" ExternalToolTextResultForLlmContentTypeResource ExternalToolTextResultForLlmContentType = "resource" ExternalToolTextResultForLlmContentTypeResourceLink ExternalToolTextResultForLlmContentType = "resource_link" + ExternalToolTextResultForLlmContentTypeShellExit ExternalToolTextResultForLlmContentType = "shell_exit" ExternalToolTextResultForLlmContentTypeTerminal ExternalToolTextResultForLlmContentType = "terminal" ExternalToolTextResultForLlmContentTypeText ExternalToolTextResultForLlmContentType = "text" ) @@ -9547,6 +11403,45 @@ const ( HMACAuthInfoHostHTTPSGitHubCom HMACAuthInfoHost = "https://github.com" ) +// Hook event name dispatched through the SDK callback transport. +// Experimental: HookType is part of an experimental API and may change or be removed. +type HookType string + +const ( + // Runs when the agent stops. + HookTypeAgentStop HookType = "agentStop" + // Runs when the agent encounters an error. + HookTypeErrorOccurred HookType = "errorOccurred" + // Runs when the agent emits a notification. + HookTypeNotification HookType = "notification" + // Runs when the agent requests permission. + HookTypePermissionRequest HookType = "permissionRequest" + // Runs after an agent result is produced. + HookTypePostResult HookType = "postResult" + // Runs after a tool completes successfully. + HookTypePostToolUse HookType = "postToolUse" + // Runs after a tool fails. + HookTypePostToolUseFailure HookType = "postToolUseFailure" + // Runs before conversation context is compacted. + HookTypePreCompact HookType = "preCompact" + // Runs before an MCP tool is invoked. + HookTypePreMCPToolCall HookType = "preMcpToolCall" + // Runs before a pull request description is generated. + HookTypePrePRDescription HookType = "prePRDescription" + // Runs before a tool is invoked. + HookTypePreToolUse HookType = "preToolUse" + // Runs when a session ends. + HookTypeSessionEnd HookType = "sessionEnd" + // Runs when a session starts. + HookTypeSessionStart HookType = "sessionStart" + // Runs when a subagent starts. + HookTypeSubagentStart HookType = "subagentStart" + // Runs when a subagent stops. + HookTypeSubagentStop HookType = "subagentStop" + // Runs after the user submits a prompt. + HookTypeUserPromptSubmitted HookType = "userPromptSubmitted" +) + // Constant value. Always "github". type InstalledPluginSourceGitHubSource string @@ -9640,6 +11535,8 @@ const ( // distinguishes text from binary frames. The SDK consumer uses this to decide whether to // service the request with an HTTP client or a WebSocket client. It is the one piece of // request metadata the consumer cannot reliably infer from the URL or headers alone. +// Experimental: LlmInferenceHTTPRequestStartTransport is part of an experimental API and +// may change or be removed. type LlmInferenceHTTPRequestStartTransport string const ( @@ -9760,6 +11657,14 @@ const ( MCPAppsSetHostContextDetailsThemeLight MCPAppsSetHostContextDetailsTheme = "light" ) +// Kind discriminator for MCPHeadersHandlePendingHeadersRefreshRequest. +type MCPHeadersHandlePendingHeadersRefreshRequestKind string + +const ( + MCPHeadersHandlePendingHeadersRefreshRequestKindHeaders MCPHeadersHandlePendingHeadersRefreshRequestKind = "headers" + MCPHeadersHandlePendingHeadersRefreshRequestKindNone MCPHeadersHandlePendingHeadersRefreshRequestKind = "none" +) + // OAuth grant type override for this login. // Experimental: MCPOauthLoginGrantType is part of an experimental API and may change or be // removed. @@ -9799,6 +11704,8 @@ const ( // Controls if tools provided by this server can be loaded on demand via tool search (auto) // or always included in the initial tool list (never) +// Experimental: MCPServerConfigDeferTools is part of an experimental API and may change or +// be removed. type MCPServerConfigDeferTools string const ( @@ -9809,6 +11716,8 @@ const ( ) // OAuth grant type to use when authenticating to the remote MCP server. +// Experimental: MCPServerConfigHTTPOauthGrantType is part of an experimental API and may +// change or be removed. type MCPServerConfigHTTPOauthGrantType string const ( @@ -9819,6 +11728,8 @@ const ( ) // Remote transport type. Defaults to "http" when omitted. +// Experimental: MCPServerConfigHTTPType is part of an experimental API and may change or be +// removed. type MCPServerConfigHTTPType string const ( @@ -9829,6 +11740,7 @@ const ( ) // Configuration source: user, workspace, plugin, or builtin +// Experimental: MCPServerSource is part of an experimental API and may change or be removed. type MCPServerSource string const ( @@ -9877,6 +11789,18 @@ const ( MCPSetEnvValueModeDetailsIndirect MCPSetEnvValueModeDetails = "indirect" ) +// Consumer allowed to call an MCP tool. +// Experimental: MCPToolUIVisibility is part of an experimental API and may change or be +// removed. +type MCPToolUIVisibility string + +const ( + // An MCP App view may call the tool. + MCPToolUIVisibilityApp MCPToolUIVisibility = "app" + // The model may call the tool. + MCPToolUIVisibilityModel MCPToolUIVisibility = "model" +) + // The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot') // Experimental: MetadataSnapshotCurrentMode is part of an experimental API and may change // or be removed. @@ -9905,6 +11829,8 @@ const ( ) // Model capability category for grouping in the model picker +// Experimental: ModelPickerCategory is part of an experimental API and may change or be +// removed. type ModelPickerCategory string const ( @@ -9917,6 +11843,8 @@ const ( ) // Relative cost tier for token-based billing users +// Experimental: ModelPickerPriceCategory is part of an experimental API and may change or +// be removed. type ModelPickerPriceCategory string const ( @@ -9931,6 +11859,8 @@ const ( ) // Current policy state for this model +// Experimental: ModelPolicyState is part of an experimental API and may change or be +// removed. type ModelPolicyState string const ( @@ -10088,6 +12018,21 @@ const ( PermissionLocationTypeRepo PermissionLocationType = "repo" ) +// Current or requested allow-all mode. +// Experimental: PermissionsAllowAllMode is part of an experimental API and may change or be +// removed. +type PermissionsAllowAllMode string + +const ( + // Permission requests follow the normal approval flow with an LLM advisory recommendation + // attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + PermissionsAllowAllModeAuto PermissionsAllowAllMode = "auto" + // Permission requests follow the normal approval flow. + PermissionsAllowAllModeOff PermissionsAllowAllMode = "off" + // Tool, path, and URL permission requests are automatically approved. + PermissionsAllowAllModeOn PermissionsAllowAllMode = "on" +) + // Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` // enumeration. // Experimental: PermissionsConfigureAdditionalContentExclusionPolicyScope is part of an @@ -10255,12 +12200,21 @@ const ( type PushAttachmentType string const ( - PushAttachmentTypeBlob PushAttachmentType = "blob" - PushAttachmentTypeDirectory PushAttachmentType = "directory" - PushAttachmentTypeExtensionContext PushAttachmentType = "extension_context" - PushAttachmentTypeFile PushAttachmentType = "file" - PushAttachmentTypeGitHubReference PushAttachmentType = "github_reference" - PushAttachmentTypeSelection PushAttachmentType = "selection" + PushAttachmentTypeBlob PushAttachmentType = "blob" + PushAttachmentTypeDirectory PushAttachmentType = "directory" + PushAttachmentTypeExtensionContext PushAttachmentType = "extension_context" + PushAttachmentTypeFile PushAttachmentType = "file" + PushAttachmentTypeGitHubActionsJob PushAttachmentType = "github_actions_job" + PushAttachmentTypeGitHubCommit PushAttachmentType = "github_commit" + PushAttachmentTypeGitHubFile PushAttachmentType = "github_file" + PushAttachmentTypeGitHubFileDiff PushAttachmentType = "github_file_diff" + PushAttachmentTypeGitHubReference PushAttachmentType = "github_reference" + PushAttachmentTypeGitHubRelease PushAttachmentType = "github_release" + PushAttachmentTypeGitHubRepository PushAttachmentType = "github_repository" + PushAttachmentTypeGitHubSnippet PushAttachmentType = "github_snippet" + PushAttachmentTypeGitHubTreeComparison PushAttachmentType = "github_tree_comparison" + PushAttachmentTypeGitHubURL PushAttachmentType = "github_url" + PushAttachmentTypeSelection PushAttachmentType = "selection" ) // Whether this item is a queued user message or a queued slash command / model change @@ -10421,6 +12375,8 @@ const ( ) // Path conventions used by this filesystem +// Experimental: SessionFSSetProviderConventions is part of an experimental API and may +// change or be removed. type SessionFSSetProviderConventions string const ( @@ -10545,6 +12501,53 @@ const ( SessionOpenParamsKindResumeLast SessionOpenParamsKind = "resumeLast" ) +// Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names +// are intentionally not part of the contract. +// Experimental: SessionSettingsPredicateName is part of an experimental API and may change +// or be removed. +type SessionSettingsPredicateName string + +const ( + // Whether Claude Opus token-limit caps should be applied. + SessionSettingsPredicateNameCapClaudeOpusTokenLimitsEnabled SessionSettingsPredicateName = "capClaudeOpusTokenLimitsEnabled" + // Whether CCA should use the TypeScript autofind behavior. + SessionSettingsPredicateNameCcaUseTsAutofindEnabled SessionSettingsPredicateName = "ccaUseTsAutofindEnabled" + // Whether Chronicle integration is enabled. + SessionSettingsPredicateNameChronicleEnabled SessionSettingsPredicateName = "chronicleEnabled" + // Whether the co-author hook is enabled. + SessionSettingsPredicateNameCoAuthorHookEnabled SessionSettingsPredicateName = "coAuthorHookEnabled" + // Whether the CodeQL checker is enabled. + SessionSettingsPredicateNameCodeqlCheckerEnabled SessionSettingsPredicateName = "codeqlCheckerEnabled" + // Whether code-review behavior is enabled. + SessionSettingsPredicateNameCodeReviewFeatureEnabled SessionSettingsPredicateName = "codeReviewFeatureEnabled" + // Whether content-exclusion policy may self-fetch data. + SessionSettingsPredicateNameContentExclusionSelfFetchEnabled SessionSettingsPredicateName = "contentExclusionSelfFetchEnabled" + // Whether the Dependabot checker is enabled. + SessionSettingsPredicateNameDependabotCheckerEnabled SessionSettingsPredicateName = "dependabotCheckerEnabled" + // Whether the dependency checker is enabled. + SessionSettingsPredicateNameDependencyCheckerEnabled SessionSettingsPredicateName = "dependencyCheckerEnabled" + // Whether validation may run in parallel. + SessionSettingsPredicateNameParallelValidationEnabled SessionSettingsPredicateName = "parallelValidationEnabled" + // Whether runtime timing telemetry is enabled. + SessionSettingsPredicateNameRuntimeTimingTelemetryEnabled SessionSettingsPredicateName = "runtimeTimingTelemetryEnabled" + // Whether the security-tools feature flag enables security tool wiring. + SessionSettingsPredicateNameSecurityToolsEnabled SessionSettingsPredicateName = "securityToolsEnabled" + // Whether third-party security tools should receive the security prompt. + SessionSettingsPredicateNameThirdPartySecurityPromptEnabled SessionSettingsPredicateName = "thirdPartySecurityPromptEnabled" + // Whether trivial-change handling is enabled. + SessionSettingsPredicateNameTrivialChangeEnabled SessionSettingsPredicateName = "trivialChangeEnabled" + // Whether trivial-change handling is enabled for code review. + SessionSettingsPredicateNameTrivialChangeEnabledForCodeReview SessionSettingsPredicateName = "trivialChangeEnabledForCodeReview" + // Whether trivial-change handling is enabled for a specific tool. + SessionSettingsPredicateNameTrivialChangeEnabledForTool SessionSettingsPredicateName = "trivialChangeEnabledForTool" + // Whether trivial-change skip behavior is enabled. + SessionSettingsPredicateNameTrivialChangeSkipEnabled SessionSettingsPredicateName = "trivialChangeSkipEnabled" + // Whether trivial-change skip behavior is enabled for code review. + SessionSettingsPredicateNameTrivialChangeSkipEnabledForCodeReview SessionSettingsPredicateName = "trivialChangeSkipEnabledForCodeReview" + // Whether trivial-change skip behavior is enabled for a specific tool. + SessionSettingsPredicateNameTrivialChangeSkipEnabledForTool SessionSettingsPredicateName = "trivialChangeSkipEnabledForTool" +) + // Task type determines the handoff strategy (CCA fetches events; CLI prepares a transient // session). // Experimental: SessionsOpenHandoffTaskType is part of an experimental API and may change @@ -10621,6 +12624,19 @@ const ( SessionSourceRemote SessionSource = "remote" ) +// Sharing status for a synced session. "repo" makes the session visible to anyone with read +// access to the repository; "unshared" restricts it to the creator and collaborators. +// Experimental: SessionVisibilityStatus is part of an experimental API and may change or be +// removed. +type SessionVisibilityStatus string + +const ( + // The session is visible to repository readers. + SessionVisibilityStatusRepo SessionVisibilityStatus = "repo" + // The session is restricted to its creator and collaborators. + SessionVisibilityStatusUnshared SessionVisibilityStatus = "unshared" +) + // Hosting platform type of the repository // Experimental: SessionWorkingDirectoryContextHostType is part of an experimental API and // may change or be removed. @@ -10674,6 +12690,7 @@ const ( ) // Source location type (e.g., project, personal-copilot, plugin, builtin) +// Experimental: SkillSource is part of an experimental API and may change or be removed. type SkillSource string const ( @@ -10899,6 +12916,22 @@ const ( UIExitPlanModeActionInteractive UIExitPlanModeAction = "interactive" ) +// User action selected for an exhausted session limit. +// Experimental: UISessionLimitsExhaustedResponseAction is part of an experimental API and +// may change or be removed. +type UISessionLimitsExhaustedResponseAction string + +const ( + // Increase the current max by an exact AI Credits amount. + UISessionLimitsExhaustedResponseActionAdd UISessionLimitsExhaustedResponseAction = "add" + // Leave the limit unchanged and cancel the blocked model request. + UISessionLimitsExhaustedResponseActionCancel UISessionLimitsExhaustedResponseAction = "cancel" + // Set a new absolute max AI Credits value. + UISessionLimitsExhaustedResponseActionSet UISessionLimitsExhaustedResponseAction = "set" + // Remove the current session limit. + UISessionLimitsExhaustedResponseActionUnset UISessionLimitsExhaustedResponseAction = "unset" +) + // Kind discriminator for UserToolSessionApproval. type UserToolSessionApprovalKind string @@ -10913,6 +12946,19 @@ const ( UserToolSessionApprovalKindWrite UserToolSessionApprovalKind = "write" ) +// Output verbosity level for supported models +// Experimental: Verbosity is part of an experimental API and may change or be removed. +type Verbosity string + +const ( + // Request a more detailed response. + VerbosityHigh Verbosity = "high" + // Request a terse response. + VerbosityLow Verbosity = "low" + // Request a medium amount of response detail. + VerbosityMedium Verbosity = "medium" +) + // Type of change represented by this file diff. // Experimental: WorkspaceDiffFileChangeType is part of an experimental API and may change // or be removed. @@ -10972,6 +13018,7 @@ type serverAPI struct { client *jsonrpc2.Client } +// Experimental: ServerAccountAPI contains experimental APIs that may change or be removed. type ServerAccountAPI serverAPI // GetAllUsers gets all authenticated users available for account switching. @@ -11138,6 +13185,29 @@ func (a *ServerAgentsAPI) GetDiscoveryPaths(ctx context.Context, params *AgentsG return &result, nil } +// Experimental: ServerCommandsAPI contains experimental APIs that may change or be removed. +type ServerCommandsAPI serverAPI + +// Lists the well-known built-in slash commands that work as the first message in a new +// session (e.g. /plan, /env), without requiring an active session. Commands that depend on +// session state, authentication, or a synced session are omitted. +// +// RPC method: commands.list. +// +// Returns: Slash commands available in the session, after applying any include/exclude +// filters. +func (a *ServerCommandsAPI) List(ctx context.Context) (*CommandList, error) { + raw, err := a.client.Request(ctx, "commands.list", nil) + if err != nil { + return nil, err + } + var result CommandList + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: ServerInstructionsAPI contains experimental APIs that may change or be // removed. type ServerInstructionsAPI serverAPI @@ -11249,6 +13319,7 @@ func (a *ServerLlmInferenceAPI) SetProvider(ctx context.Context) (*LlmInferenceS return &result, nil } +// Experimental: ServerMCPAPI contains experimental APIs that may change or be removed. type ServerMCPAPI serverAPI // Discovers MCP servers from user, workspace, plugin, and builtin sources. @@ -11270,6 +13341,7 @@ func (a *ServerMCPAPI) Discover(ctx context.Context, params *MCPDiscoverRequest) return &result, nil } +// Experimental: ServerMCPConfigAPI contains experimental APIs that may change or be removed. type ServerMCPConfigAPI serverAPI // Adds an MCP server to user configuration. @@ -11390,10 +13462,12 @@ func (a *ServerMCPConfigAPI) Update(ctx context.Context, params *MCPConfigUpdate return &result, nil } +// Experimental: Config returns experimental APIs that may change or be removed. func (s *ServerMCPAPI) Config() *ServerMCPConfigAPI { return (*ServerMCPConfigAPI)(s) } +// Experimental: ServerModelsAPI contains experimental APIs that may change or be removed. type ServerModelsAPI serverAPI // Lists Copilot models available to the authenticated user. @@ -11551,7 +13625,8 @@ type ServerPluginsMarketplacesAPI serverAPI // // RPC method: plugins.marketplaces.add. // -// Parameters: Marketplace source to register. +// Parameters: Marketplace source and optional working directory for relative-path +// resolution. // // Returns: Result of registering a new marketplace. func (a *ServerPluginsMarketplacesAPI) Add(ctx context.Context, params *PluginsMarketplacesAddRequest) (*MarketplaceAddResult, error) { @@ -11647,6 +13722,7 @@ func (s *ServerPluginsAPI) Marketplaces() *ServerPluginsMarketplacesAPI { return (*ServerPluginsMarketplacesAPI)(s) } +// Experimental: ServerRuntimeAPI contains experimental APIs that may change or be removed. type ServerRuntimeAPI serverAPI // Shutdown gracefully shuts down an SDK-owned runtime. The response is sent only after @@ -11665,6 +13741,7 @@ func (a *ServerRuntimeAPI) Shutdown(ctx context.Context) (*RuntimeShutdownResult return &result, nil } +// Experimental: ServerSecretsAPI contains experimental APIs that may change or be removed. type ServerSecretsAPI serverAPI // AddFilterValues registers secret values for redaction in session logs and exports. The @@ -11687,6 +13764,7 @@ func (a *ServerSecretsAPI) AddFilterValues(ctx context.Context, params *SecretsA return &result, nil } +// Experimental: ServerSessionFSAPI contains experimental APIs that may change or be removed. type ServerSessionFSAPI serverAPI // SetProvider registers an SDK client as the session filesystem provider. @@ -12189,6 +14267,7 @@ func (a *ServerSessionsAPI) TransferRemoteControl(ctx context.Context, params *S return &result, nil } +// Experimental: ServerSkillsAPI contains experimental APIs that may change or be removed. type ServerSkillsAPI serverAPI // Discovers skills across global and project sources. @@ -12221,8 +14300,6 @@ func (a *ServerSkillsAPI) Discover(ctx context.Context, params *SkillsDiscoverRe // // Returns: Canonical locations where skills can be created so the runtime will recognize // them. -// Experimental: GetDiscoveryPaths is an experimental API and may change or be removed in -// future versions. func (a *ServerSkillsAPI) GetDiscoveryPaths(ctx context.Context, params *SkillsGetDiscoveryPathsRequest) (*SkillDiscoveryPathList, error) { raw, err := a.client.Request(ctx, "skills.getDiscoveryPaths", params) if err != nil { @@ -12235,6 +14312,8 @@ func (a *ServerSkillsAPI) GetDiscoveryPaths(ctx context.Context, params *SkillsG return &result, nil } +// Experimental: ServerSkillsConfigAPI contains experimental APIs that may change or be +// removed. type ServerSkillsConfigAPI serverAPI // SetDisabledSkills replaces the global list of disabled skills. @@ -12255,10 +14334,12 @@ func (a *ServerSkillsConfigAPI) SetDisabledSkills(ctx context.Context, params *S return &result, nil } +// Experimental: Config returns experimental APIs that may change or be removed. func (s *ServerSkillsAPI) Config() *ServerSkillsConfigAPI { return (*ServerSkillsConfigAPI)(s) } +// Experimental: ServerToolsAPI contains experimental APIs that may change or be removed. type ServerToolsAPI serverAPI // Lists built-in tools available for a model. @@ -12282,10 +14363,36 @@ func (a *ServerToolsAPI) List(ctx context.Context, params *ToolsListRequest) (*T return &result, nil } +// Experimental: ServerUserAPI contains experimental APIs that may change or be removed. type ServerUserAPI serverAPI +// Experimental: ServerUserSettingsAPI contains experimental APIs that may change or be +// removed. type ServerUserSettingsAPI serverAPI +// Get lists every known user setting (settings.json overlaid with the legacy config.json, +// config.json wins), each with its effective value, its default, and whether it is at the +// default — so settings the user has never set still appear with their default value. Does +// not include repository- or enterprise-managed overrides that the runtime layers on top at +// session time. +// +// RPC method: user.settings.get. +// +// Returns: Per-key metadata for every known user setting (settings.json overlaid with the +// legacy config.json, config.json wins), including settings left at their default. Excludes +// repository- and enterprise-managed overrides. +func (a *ServerUserSettingsAPI) Get(ctx context.Context) (*UserSettingsGetResult, error) { + raw, err := a.client.Request(ctx, "user.settings.get", nil) + if err != nil { + return nil, err + } + var result UserSettingsGetResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Reload drops this runtime process's in-memory user settings cache so the next settings // read observes disk. // @@ -12302,6 +14409,30 @@ func (a *ServerUserSettingsAPI) Reload(ctx context.Context) (*UserSettingsReload return &result, nil } +// Set writes one or more user settings to settings.json, replacing each provided top-level +// key. A key whose value is null is removed. Returns the keys whose new value is shadowed +// by a legacy config.json entry (config.json wins on read), which the runtime leaves in +// place — such writes do not take effect until the legacy value is removed. +// +// RPC method: user.settings.set. +// +// Parameters: Partial user settings to write to settings.json. Each top-level key is +// written individually, replacing the existing value; a key whose value is null is removed. +// +// Returns: Outcome of writing user settings. +func (a *ServerUserSettingsAPI) Set(ctx context.Context, params *UserSettingsSetRequest) (*UserSettingsSetResult, error) { + raw, err := a.client.Request(ctx, "user.settings.set", params) + if err != nil { + return nil, err + } + var result UserSettingsSetResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Experimental: Settings returns experimental APIs that may change or be removed. func (s *ServerUserAPI) Settings() *ServerUserSettingsAPI { return (*ServerUserSettingsAPI)(s) } @@ -12314,6 +14445,7 @@ type ServerRPC struct { Account *ServerAccountAPI AgentRegistry *ServerAgentRegistryAPI Agents *ServerAgentsAPI + Commands *ServerCommandsAPI Instructions *ServerInstructionsAPI LlmInference *ServerLlmInferenceAPI MCP *ServerMCPAPI @@ -12336,6 +14468,7 @@ type ServerRPC struct { // // Returns: Server liveness response, including the echoed message, current server // timestamp, and protocol version. +// Experimental: Ping is an experimental API and may change or be removed in future versions. func (a *ServerRPC) Ping(ctx context.Context, params *PingRequest) (*PingResult, error) { raw, err := a.common.client.Request(ctx, "ping", params) if err != nil { @@ -12354,6 +14487,7 @@ func NewServerRPC(client *jsonrpc2.Client) *ServerRPC { r.Account = (*ServerAccountAPI)(&r.common) r.AgentRegistry = (*ServerAgentRegistryAPI)(&r.common) r.Agents = (*ServerAgentsAPI)(&r.common) + r.Commands = (*ServerCommandsAPI)(&r.common) r.Instructions = (*ServerInstructionsAPI)(&r.common) r.LlmInference = (*ServerLlmInferenceAPI)(&r.common) r.MCP = (*ServerMCPAPI)(&r.common) @@ -12479,33 +14613,6 @@ func (a *InternalServerSessionsAPI) GetPersistedRemoteSteerable(ctx context.Cont return &result, nil } -// PollSpawnedSessions cursor-based long-poll for sessions spawned by the runtime (e.g. in -// response to a Mission Control `start_session` command). The cursor is an opaque token; -// pass it back to receive only spawn events that occurred AFTER the cursor was issued. Omit -// the cursor on the first call to receive any events buffered since the runtime started. -// Internal: this is a CLI background-daemon plumbing primitive. SDK consumers that need to -// react to runtime-spawned sessions should subscribe to a higher-level event stream rather -// than driving a long-poll loop. -// -// RPC method: sessions.pollSpawnedSessions. -// -// Parameters: Cursor and optional long-poll wait for polling runtime-spawned sessions. -// -// Returns: Batch of spawn events plus a cursor for follow-up polls. -// Internal: PollSpawnedSessions is part of the SDK's internal handshake/plumbing; external -// callers should not use it. -func (a *InternalServerSessionsAPI) PollSpawnedSessions(ctx context.Context, params *SessionsPollSpawnedSessionsRequest) (*PollSpawnedSessionsResult, error) { - raw, err := a.client.Request(ctx, "sessions.pollSpawnedSessions", params) - if err != nil { - return nil, err - } - var result PollSpawnedSessionsResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - // RegisterExtensionToolsOnSession registers extension-provided tools on the given session, // gated by an optional `enabled` callback. Returns an opaque unsubscribe function the // caller must invoke to deregister the tools when the extension is torn down. Marked @@ -12551,10 +14658,13 @@ type InternalServerRPC struct { // // RPC method: connect. // -// Parameters: Optional connection token presented by the SDK client during the handshake. +// Parameters: Parameters for the `server.connect` handshake: an optional connection token +// and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). // // Returns: Handshake result reporting the server's protocol version and package version on // success. +// Experimental: Connect is an experimental API and may change or be removed in future +// versions. // Internal: Connect is part of the SDK's internal handshake/plumbing; external callers // should not use it. func (a *InternalServerRPC) Connect(ctx context.Context, params *ConnectRequest) (*ConnectResult, error) { @@ -12677,54 +14787,6 @@ func (a *AgentAPI) Select(ctx context.Context, params *AgentSelectRequest) (*Age return &result, nil } -// Experimental: AuthAPI contains experimental APIs that may change or be removed. -type AuthAPI sessionAPI - -// GetStatus gets authentication status and account metadata for the session. -// -// RPC method: session.auth.getStatus. -// -// Returns: Authentication status and account metadata for the session. -func (a *AuthAPI) GetStatus(ctx context.Context) (*SessionAuthStatus, error) { - req := map[string]any{"sessionId": a.sessionID} - raw, err := a.client.Request(ctx, "session.auth.getStatus", req) - if err != nil { - return nil, err - } - var result SessionAuthStatus - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// SetCredentials updates the session's auth credentials used for outbound model and API -// requests. -// -// RPC method: session.auth.setCredentials. -// -// Parameters: New auth credentials to install on the session. Omit to leave credentials -// unchanged. -// -// Returns: Indicates whether the credential update succeeded. -func (a *AuthAPI) SetCredentials(ctx context.Context, params *SessionSetCredentialsParams) (*SessionSetCredentialsResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - if params.Credentials != nil { - req["credentials"] = params.Credentials - } - } - raw, err := a.client.Request(ctx, "session.auth.setCredentials", req) - if err != nil { - return nil, err - } - var result SessionSetCredentialsResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - // Experimental: CanvasAPI contains experimental APIs that may change or be removed. type CanvasAPI sessionAPI @@ -12933,7 +14995,7 @@ func (a *CommandsAPI) HandlePendingCommand(ctx context.Context, params *Commands // Parameters: Slash command name and optional raw input string to invoke. // // Returns: Result of invoking the slash command (text output, prompt to send to the agent, -// or completion). +// completion, or subcommand selection). func (a *CommandsAPI) Invoke(ctx context.Context, params *CommandsInvokeRequest) (SlashCommandInvocationResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { @@ -13015,6 +15077,92 @@ func (a *CommandsAPI) RespondToQueuedCommand(ctx context.Context, params *Comman return &result, nil } +// Experimental: CompletionsAPI contains experimental APIs that may change or be removed. +type CompletionsAPI sessionAPI + +// GetTriggerCharacters gets the characters that should trigger host-driven completions for +// the session. Empty disables host-driven completions (e.g. local sessions, or a relay host +// that does not advertise them). +// +// RPC method: session.completions.getTriggerCharacters. +// +// Returns: Characters that, when typed in the composer, should trigger a +// `completions.request`. Empty when the session has no host-driven completions (e.g. local +// sessions, or a relay host that does not advertise `completionTriggerCharacters`). +func (a *CompletionsAPI) GetTriggerCharacters(ctx context.Context) (*CompletionsGetTriggerCharactersResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.completions.getTriggerCharacters", req) + if err != nil { + return nil, err + } + var result CompletionsGetTriggerCharactersResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Requests host-driven completion items for the current composer input. Returns an empty +// list when the host has no items or does not support completions. +// +// RPC method: session.completions.request. +// +// Parameters: Request host-driven completions for the current composer input. +// +// Returns: Host-driven completion items for the current composer input. Empty when the host +// returns no items or does not support completions. +func (a *CompletionsAPI) Request(ctx context.Context, params *CompletionsRequestRequest) (*CompletionsRequestResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["offset"] = params.Offset + req["text"] = params.Text + } + raw, err := a.client.Request(ctx, "session.completions.request", req) + if err != nil { + return nil, err + } + var result CompletionsRequestResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Experimental: DebugAPI contains experimental APIs that may change or be removed. +type DebugAPI sessionAPI + +// CollectLogs collects a redacted session debug log bundle into a local archive or staging +// directory. The runtime includes session-owned logs by default and accepts caller-provided +// diagnostic entries so host applications can add their own files without changing this API +// shape. +// +// RPC method: session.debug.collectLogs. +// +// Parameters: Options for collecting a redacted session debug bundle. +// +// Returns: Result of collecting a redacted debug bundle. +func (a *DebugAPI) CollectLogs(ctx context.Context, params *DebugCollectLogsRequest) (*DebugCollectLogsResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.AdditionalEntries != nil { + req["additionalEntries"] = params.AdditionalEntries + } + req["destination"] = params.Destination + if params.Include != nil { + req["include"] = *params.Include + } + } + raw, err := a.client.Request(ctx, "session.debug.collectLogs", req) + if err != nil { + return nil, err + } + var result DebugCollectLogsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: EventLogAPI contains experimental APIs that may change or be removed. type EventLogAPI sessionAPI @@ -13257,6 +15405,54 @@ func (a *FleetAPI) Start(ctx context.Context, params *FleetStartRequest) (*Fleet return &result, nil } +// Experimental: GitHubAuthAPI contains experimental APIs that may change or be removed. +type GitHubAuthAPI sessionAPI + +// GetStatus gets authentication status and account metadata for the session. +// +// RPC method: session.gitHubAuth.getStatus. +// +// Returns: Authentication status and account metadata for the session. +func (a *GitHubAuthAPI) GetStatus(ctx context.Context) (*SessionAuthStatus, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.gitHubAuth.getStatus", req) + if err != nil { + return nil, err + } + var result SessionAuthStatus + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// SetCredentials updates the session's auth credentials used for outbound model and API +// requests. +// +// RPC method: session.gitHubAuth.setCredentials. +// +// Parameters: New auth credentials to install on the session. Omit to leave credentials +// unchanged. +// +// Returns: Indicates whether the credential update succeeded. +func (a *GitHubAuthAPI) SetCredentials(ctx context.Context, params *SessionSetCredentialsParams) (*SessionSetCredentialsResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Credentials != nil { + req["credentials"] = params.Credentials + } + } + raw, err := a.client.Request(ctx, "session.gitHubAuth.setCredentials", req) + if err != nil { + return nil, err + } + var result SessionSetCredentialsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: HistoryAPI contains experimental APIs that may change or be removed. type HistoryAPI sessionAPI @@ -13566,7 +15762,9 @@ func (a *MCPAPI) List(ctx context.Context) (*MCPServerList, error) { return &result, nil } -// ListTools lists the tools exposed by a connected MCP server on this session's host. +// ListTools lists the tools exposed by a connected MCP server on this session's host. This +// performs a live `tools/list` request. Tool UI metadata is returned independently of +// whether MCP Apps rendering is enabled for the session. // // RPC method: session.mcp.listTools. // @@ -13625,6 +15823,35 @@ func (a *MCPAPI) RemoveGitHub(ctx context.Context) (*MCPRemoveGitHubResult, erro return &result, nil } +// RestartServer restarts an individual MCP server on the live session (stops then starts). +// Omit `config` for a config-free restart-by-name of an already-configured server; supply +// `config` to restart with a replacement configuration. Session-scoped and ephemeral: does +// NOT modify persistent user configuration (`mcp.config.*`). +// +// RPC method: session.mcp.restartServer. +// +// Parameters: Server name and optional replacement configuration for an individual MCP +// server restart. Omit `config` for a config-free restart-by-name of an already-configured +// server. +func (a *MCPAPI) RestartServer(ctx context.Context, params *MCPRestartServerRequest) (*SessionMCPRestartServerResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Config != nil { + req["config"] = params.Config + } + req["serverName"] = params.ServerName + } + raw, err := a.client.Request(ctx, "session.mcp.restartServer", req) + if err != nil { + return nil, err + } + var result SessionMCPRestartServerResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // SetEnvValueMode sets how environment-variable values supplied to MCP servers are resolved // (direct or indirect). // @@ -13650,6 +15877,33 @@ func (a *MCPAPI) SetEnvValueMode(ctx context.Context, params *MCPSetEnvValueMode return &result, nil } +// StartServer starts an individual MCP server on the live session from a caller-supplied +// config. Session-scoped and ephemeral: the server is added to this session's running set +// only and is reaped when the session ends. Does NOT modify persistent user configuration +// (`mcp.config.*`), so it does not affect future sessions. The server surfaces through +// `session.mcp.list` and the `session.mcp_servers_loaded` / +// `session.mcp_server_status_changed` events like any other server. +// +// RPC method: session.mcp.startServer. +// +// Parameters: Server name and configuration for an individual MCP server start. +func (a *MCPAPI) StartServer(ctx context.Context, params *MCPStartServerRequest) (*SessionMCPStartServerResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["config"] = params.Config + req["serverName"] = params.ServerName + } + raw, err := a.client.Request(ctx, "session.mcp.startServer", req) + if err != nil { + return nil, err + } + var result SessionMCPStartServerResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // StopServer stops an individual MCP server on the session's host. // // RPC method: session.mcp.stopServer. @@ -13824,6 +16078,41 @@ func (s *MCPAPI) Apps() *MCPAppsAPI { return (*MCPAppsAPI)(s) } +// Experimental: MCPHeadersAPI contains experimental APIs that may change or be removed. +type MCPHeadersAPI sessionAPI + +// HandlePendingHeadersRefreshRequest responds to a pending MCP dynamic headers refresh +// request. Hosts that subscribe to `mcp.headers_refresh_required` use this to provide +// short-lived per-server headers or to indicate that no dynamic headers are available for +// this refresh. +// +// RPC method: session.mcp.headers.handlePendingHeadersRefreshRequest. +// +// Parameters: MCP headers refresh request id and the host response. +// +// Returns: Indicates whether the pending MCP headers refresh response was accepted. +func (a *MCPHeadersAPI) HandlePendingHeadersRefreshRequest(ctx context.Context, params *MCPHeadersHandlePendingHeadersRefreshRequestRequest) (*MCPHeadersHandlePendingHeadersRefreshRequestResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["requestId"] = params.RequestID + req["result"] = params.Result + } + raw, err := a.client.Request(ctx, "session.mcp.headers.handlePendingHeadersRefreshRequest", req) + if err != nil { + return nil, err + } + var result MCPHeadersHandlePendingHeadersRefreshRequestResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Experimental: Headers returns experimental APIs that may change or be removed. +func (s *MCPAPI) Headers() *MCPHeadersAPI { + return (*MCPHeadersAPI)(s) +} + // Experimental: MCPOauthAPI contains experimental APIs that may change or be removed. type MCPOauthAPI sessionAPI @@ -13842,66 +16131,153 @@ func (a *MCPOauthAPI) HandlePendingRequest(ctx context.Context, params *MCPOauth req["requestId"] = params.RequestID req["result"] = params.Result } - raw, err := a.client.Request(ctx, "session.mcp.oauth.handlePendingRequest", req) + raw, err := a.client.Request(ctx, "session.mcp.oauth.handlePendingRequest", req) + if err != nil { + return nil, err + } + var result MCPOauthHandlePendingResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Login starts OAuth authentication for a remote MCP server. +// +// RPC method: session.mcp.oauth.login. +// +// Parameters: Remote MCP server name and optional overrides controlling reauthentication, +// OAuth client display name, callback success-page copy, and static OAuth client selection. +// +// Returns: OAuth authorization URL the caller should open, or empty when cached tokens +// already authenticated the server. +func (a *MCPOauthAPI) Login(ctx context.Context, params *MCPOauthLoginRequest) (*MCPOauthLoginResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.CallbackSuccessMessage != nil { + req["callbackSuccessMessage"] = *params.CallbackSuccessMessage + } + if params.ClientID != nil { + req["clientId"] = *params.ClientID + } + if params.ClientName != nil { + req["clientName"] = *params.ClientName + } + if params.ClientSecret != nil { + req["clientSecret"] = *params.ClientSecret + } + if params.ForceReauth != nil { + req["forceReauth"] = *params.ForceReauth + } + if params.GrantType != nil { + req["grantType"] = *params.GrantType + } + if params.PublicClient != nil { + req["publicClient"] = *params.PublicClient + } + req["serverName"] = params.ServerName + } + raw, err := a.client.Request(ctx, "session.mcp.oauth.login", req) + if err != nil { + return nil, err + } + var result MCPOauthLoginResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Experimental: Oauth returns experimental APIs that may change or be removed. +func (s *MCPAPI) Oauth() *MCPOauthAPI { + return (*MCPOauthAPI)(s) +} + +// Experimental: MCPResourcesAPI contains experimental APIs that may change or be removed. +type MCPResourcesAPI sessionAPI + +// List enumerate one page of resources a connected MCP server exposes (proxies MCP +// `resources/list`). Pass `cursor` to continue from a prior result's `nextCursor`. +// +// RPC method: session.mcp.resources.list. +// +// Parameters: MCP server whose resources to enumerate. +// +// Returns: One page of resources advertised by the named MCP server. +func (a *MCPResourcesAPI) List(ctx context.Context, params *MCPResourcesListRequest) (*MCPResourcesListResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Cursor != nil { + req["cursor"] = *params.Cursor + } + req["serverName"] = params.ServerName + } + raw, err := a.client.Request(ctx, "session.mcp.resources.list", req) + if err != nil { + return nil, err + } + var result MCPResourcesListResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// ListTemplates enumerate one page of resource templates a connected MCP server exposes +// (proxies MCP `resources/templates/list`). Pass `cursor` to continue from a prior result's +// `nextCursor`. +// +// RPC method: session.mcp.resources.listTemplates. +// +// Parameters: MCP server whose resource templates to enumerate. +// +// Returns: One page of resource templates advertised by the named MCP server. +func (a *MCPResourcesAPI) ListTemplates(ctx context.Context, params *MCPResourcesListTemplatesRequest) (*MCPResourcesListTemplatesResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Cursor != nil { + req["cursor"] = *params.Cursor + } + req["serverName"] = params.ServerName + } + raw, err := a.client.Request(ctx, "session.mcp.resources.listTemplates", req) if err != nil { return nil, err } - var result MCPOauthHandlePendingResult + var result MCPResourcesListTemplatesResult if err := json.Unmarshal(raw, &result); err != nil { return nil, err } return &result, nil } -// Login starts OAuth authentication for a remote MCP server. +// Read fetch an MCP resource from a connected server by URI (proxies MCP `resources/read`). // -// RPC method: session.mcp.oauth.login. +// RPC method: session.mcp.resources.read. // -// Parameters: Remote MCP server name and optional overrides controlling reauthentication, -// OAuth client display name, callback success-page copy, and static OAuth client selection. +// Parameters: MCP server and resource URI to fetch. // -// Returns: OAuth authorization URL the caller should open, or empty when cached tokens -// already authenticated the server. -func (a *MCPOauthAPI) Login(ctx context.Context, params *MCPOauthLoginRequest) (*MCPOauthLoginResult, error) { +// Returns: Resource contents returned by the MCP server. +func (a *MCPResourcesAPI) Read(ctx context.Context, params *MCPResourcesReadRequest) (*MCPResourcesReadResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { - if params.CallbackSuccessMessage != nil { - req["callbackSuccessMessage"] = *params.CallbackSuccessMessage - } - if params.ClientID != nil { - req["clientId"] = *params.ClientID - } - if params.ClientName != nil { - req["clientName"] = *params.ClientName - } - if params.ClientSecret != nil { - req["clientSecret"] = *params.ClientSecret - } - if params.ForceReauth != nil { - req["forceReauth"] = *params.ForceReauth - } - if params.GrantType != nil { - req["grantType"] = *params.GrantType - } - if params.PublicClient != nil { - req["publicClient"] = *params.PublicClient - } req["serverName"] = params.ServerName + req["uri"] = params.URI } - raw, err := a.client.Request(ctx, "session.mcp.oauth.login", req) + raw, err := a.client.Request(ctx, "session.mcp.resources.read", req) if err != nil { return nil, err } - var result MCPOauthLoginResult + var result MCPResourcesReadResult if err := json.Unmarshal(raw, &result); err != nil { return nil, err } return &result, nil } -// Experimental: Oauth returns experimental APIs that may change or be removed. -func (s *MCPAPI) Oauth() *MCPOauthAPI { - return (*MCPOauthAPI)(s) +// Experimental: Resources returns experimental APIs that may change or be removed. +func (s *MCPAPI) Resources() *MCPResourcesAPI { + return (*MCPResourcesAPI)(s) } // Experimental: MetadataAPI contains experimental APIs that may change or be removed. @@ -13954,6 +16330,58 @@ func (a *MetadataAPI) ContextInfo(ctx context.Context, params *MetadataContextIn return &result, nil } +// GetContextAttribution returns the experimental per-source attribution breakdown of the +// session's current context window as a flat list of entries (skills, subagents, MCP +// servers, built-in tools, plugin rollups, system/tool-definition costs, with nesting via +// parentId), plus the successful compaction count. The heaviest individual messages are +// available separately via `metadata.getContextHeaviestMessages`. Returns null until the +// session has initialized its system prompt and tool metadata. +// +// RPC method: session.metadata.getContextAttribution. +// +// Returns: Per-source attribution breakdown for the session's current context window, or +// null if uninitialized. +func (a *MetadataAPI) GetContextAttribution(ctx context.Context) (*MetadataContextAttributionResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.metadata.getContextAttribution", req) + if err != nil { + return nil, err + } + var result MetadataContextAttributionResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// GetContextHeaviestMessages returns the largest individual messages currently in the +// session's context window, most-expensive first. Companion to +// `metadata.getContextAttribution`. Returns an empty list until the session has initialized. +// +// RPC method: session.metadata.getContextHeaviestMessages. +// +// Parameters: Parameters for the heaviest-messages query. +// +// Returns: The heaviest individual messages in the session's context window, most-expensive +// first. +func (a *MetadataAPI) GetContextHeaviestMessages(ctx context.Context, params *MetadataContextHeaviestMessagesRequest) (*MetadataContextHeaviestMessagesResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Limit != nil { + req["limit"] = *params.Limit + } + } + raw, err := a.client.Request(ctx, "session.metadata.getContextHeaviestMessages", req) + if err != nil { + return nil, err + } + var result MetadataContextHeaviestMessagesResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // IsProcessing reports whether the local session is currently processing user/agent // messages. // @@ -14028,16 +16456,26 @@ func (a *MetadataAPI) RecordContextChange(ctx context.Context, params *MetadataR return &result, nil } -// SetWorkingDirectory updates the session's recorded working directory. +// SetWorkingDirectory updates the session's working directory. For local sessions the +// target is validated first (an absolute path that exists on disk) and the permission +// primary directory is re-based; a rejected validation fails the call before any session +// state changes. // // RPC method: session.metadata.setWorkingDirectory. // -// Parameters: Absolute path to set as the session's new working directory. +// Parameters: Absolute path to set as the session's new working directory. For local +// sessions the path must be absolute and exist on disk: it is validated before any session +// state changes, and a failing validation rejects the call with nothing mutated, persisted, +// or emitted. Remote sessions record the path as-is. // // Returns: Update the session's working directory. Used by the host when the user -// explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for -// `process.chdir` and any related side-effects (file index, etc.); this method only updates -// the session's own recorded path. +// explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any +// related side-effects (file index, etc.); it does NOT change the process working directory +// (a session's cwd is per-session, not process-global). For local sessions the runtime +// validates the target first (an absolute path that exists on disk) and re-bases the +// permission primary directory; a rejected validation fails the call before anything is +// mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the +// new directory (best-effort). Remote sessions only record the path. func (a *MetadataAPI) SetWorkingDirectory(ctx context.Context, params *MetadataSetWorkingDirectoryRequest) (*MetadataSetWorkingDirectoryResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { @@ -14219,6 +16657,9 @@ func (a *ModelAPI) SwitchTo(ctx context.Context, params *ModelSwitchToRequest) ( if params.ReasoningSummary != nil { req["reasoningSummary"] = *params.ReasoningSummary } + if params.Verbosity != nil { + req["verbosity"] = *params.Verbosity + } } raw, err := a.client.Request(ctx, "session.model.switchTo", req) if err != nil { @@ -14317,6 +16758,9 @@ func (a *OptionsAPI) Update(ctx context.Context, params *SessionUpdateOptionsPar if params.AgentContext != nil { req["agentContext"] = *params.AgentContext } + if params.AllowAllMCPServerInstructions != nil { + req["allowAllMcpServerInstructions"] = *params.AllowAllMCPServerInstructions + } if params.AskUserDisabled != nil { req["askUserDisabled"] = *params.AskUserDisabled } @@ -14380,12 +16824,18 @@ func (a *OptionsAPI) Update(ctx context.Context, params *SessionUpdateOptionsPar if params.EventsLogDirectory != nil { req["eventsLogDirectory"] = *params.EventsLogDirectory } + if params.ExcludedBuiltinAgents != nil { + req["excludedBuiltinAgents"] = params.ExcludedBuiltinAgents + } if params.ExcludedTools != nil { req["excludedTools"] = params.ExcludedTools } if params.FeatureFlags != nil { req["featureFlags"] = params.FeatureFlags } + if params.IncludedBuiltinAgents != nil { + req["includedBuiltinAgents"] = params.IncludedBuiltinAgents + } if params.InstalledPlugins != nil { req["installedPlugins"] = params.InstalledPlugins } @@ -14434,6 +16884,9 @@ func (a *OptionsAPI) Update(ctx context.Context, params *SessionUpdateOptionsPar if params.SessionCapabilities != nil { req["sessionCapabilities"] = params.SessionCapabilities } + if params.SessionLimits != nil { + req["sessionLimits"] = *params.SessionLimits + } if params.ShellInitProfile != nil { req["shellInitProfile"] = *params.ShellInitProfile } @@ -14458,6 +16911,9 @@ func (a *OptionsAPI) Update(ctx context.Context, params *SessionUpdateOptionsPar if params.TrajectoryFile != nil { req["trajectoryFile"] = *params.TrajectoryFile } + if params.Verbosity != nil { + req["verbosity"] = *params.Verbosity + } if params.WorkingDirectory != nil { req["workingDirectory"] = *params.WorkingDirectory } @@ -14518,12 +16974,11 @@ func (a *PermissionsAPI) Configure(ctx context.Context, params *PermissionsConfi return &result, nil } -// GetAllowAll returns whether full allow-all permissions are currently active for the -// session. +// GetAllowAll returns the current allow-all permission mode for the session. // // RPC method: session.permissions.getAllowAll. // -// Returns: Current full allow-all permission state. +// Returns: Current allow-all permission mode. func (a *PermissionsAPI) GetAllowAll(ctx context.Context) (*AllowAllPermissionState, error) { req := map[string]any{"sessionId": a.sessionID} raw, err := a.client.Request(ctx, "session.permissions.getAllowAll", req) @@ -14658,23 +17113,31 @@ func (a *PermissionsAPI) ResetSessionApprovals(ctx context.Context) (*Permission return &result, nil } -// SetAllowAll enables or disables full allow-all permissions (tools, paths, and URLs) for -// the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) -// to flip the target session's permission state. Unlike `setApproveAll`, this swaps in the -// unrestricted path and URL managers and emits `session.permissions_changed` on transition. -// The result returns the authoritative post-mutation state so callers can update their -// local mirrors without racing the `session.permissions_changed` notification on the same -// wire. +// SetAllowAll sets the allow-all permission mode for the session. Used by attach-mode +// clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's +// permission state. The `on` mode swaps in unrestricted path and URL managers and emits +// `session.permissions_changed` on transition; the `auto` mode keeps normal prompt paths +// active while attaching LLM safety recommendations. The result returns the authoritative +// post-mutation state so callers can update their local mirrors without racing the +// `session.permissions_changed` notification on the same wire. // // RPC method: session.permissions.setAllowAll. // -// Parameters: Whether to enable full allow-all permissions for the session. +// Parameters: Allow-all mode to apply for the session. // // Returns: Indicates whether the operation succeeded and reports the post-mutation state. func (a *PermissionsAPI) SetAllowAll(ctx context.Context, params *PermissionsSetAllowAllRequest) (*AllowAllPermissionSetResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { - req["enabled"] = params.Enabled + if params.Enabled != nil { + req["enabled"] = *params.Enabled + } + if params.Mode != nil { + req["mode"] = *params.Mode + } + if params.Model != nil { + req["model"] = *params.Model + } if params.Source != nil { req["source"] = *params.Source } @@ -15171,6 +17634,9 @@ func (a *PluginsAPI) Reload(ctx context.Context, params ...*PluginsReloadRequest if requestParams.ReloadCustomAgents != nil { req["reloadCustomAgents"] = *requestParams.ReloadCustomAgents } + if requestParams.ReloadExtensions != nil { + req["reloadExtensions"] = *requestParams.ReloadExtensions + } if requestParams.ReloadHooks != nil { req["reloadHooks"] = *requestParams.ReloadHooks } @@ -16225,6 +18691,32 @@ func (a *UIAPI) HandlePendingSampling(ctx context.Context, params *UIHandlePendi return &result, nil } +// HandlePendingSessionLimitsExhausted resolves a pending +// `session_limits_exhausted.requested` event with the user's selected limit action. +// +// RPC method: session.ui.handlePendingSessionLimitsExhausted. +// +// Parameters: Request ID of a pending `session_limits_exhausted.requested` event and the +// user's selected limit action. +// +// Returns: Indicates whether the pending UI request was resolved by this call. +func (a *UIAPI) HandlePendingSessionLimitsExhausted(ctx context.Context, params *UIHandlePendingSessionLimitsExhaustedRequest) (*UIHandlePendingResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["requestId"] = params.RequestID + req["response"] = params.Response + } + raw, err := a.client.Request(ctx, "session.ui.handlePendingSessionLimitsExhausted", req) + if err != nil { + return nil, err + } + var result UIHandlePendingResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // HandlePendingUserInput resolves a pending `user_input.requested` event with the user's // response. // @@ -16320,6 +18812,55 @@ func (a *UsageAPI) GetMetrics(ctx context.Context) (*UsageGetMetricsResult, erro return &result, nil } +// Experimental: VisibilityAPI contains experimental APIs that may change or be removed. +type VisibilityAPI sessionAPI + +// Get returns the session's current Mission Control sharing status and shareable GitHub +// URL. Reflects whether the synced session is visible to repository readers ("repo") or +// restricted to its creator and collaborators ("unshared"). +// +// RPC method: session.visibility.get. +// +// Returns: Current sharing status and shareable GitHub URL for a session. +func (a *VisibilityAPI) Get(ctx context.Context) (*VisibilityGetResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.visibility.get", req) + if err != nil { + return nil, err + } + var result VisibilityGetResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Sets the session's Mission Control sharing status, controlling whether the synced session +// is visible to repository readers. Returns the effective status and shareable GitHub URL +// after the change. +// +// RPC method: session.visibility.set. +// +// Parameters: Desired sharing status for the session. +// +// Returns: Effective sharing status and shareable GitHub URL after updating session +// visibility. +func (a *VisibilityAPI) Set(ctx context.Context, params *VisibilitySetRequest) (*VisibilitySetResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["status"] = params.Status + } + raw, err := a.client.Request(ctx, "session.visibility.set", req) + if err != nil { + return nil, err + } + var result VisibilitySetResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: WorkspacesAPI contains experimental APIs that may change or be removed. type WorkspacesAPI sessionAPI @@ -16503,12 +19044,14 @@ type SessionRPC struct { common sessionAPI Agent *AgentAPI - Auth *AuthAPI Canvas *CanvasAPI Commands *CommandsAPI + Completions *CompletionsAPI + Debug *DebugAPI EventLog *EventLogAPI Extensions *ExtensionsAPI Fleet *FleetAPI + GitHubAuth *GitHubAuthAPI History *HistoryAPI Instructions *InstructionsAPI Lsp *LspAPI @@ -16532,6 +19075,7 @@ type SessionRPC struct { Tools *ToolsAPI UI *UIAPI Usage *UsageAPI + Visibility *VisibilityAPI Workspaces *WorkspacesAPI } @@ -16662,6 +19206,58 @@ func (a *SessionRPC) Send(ctx context.Context, params *SendRequest) (*SendResult return &result, nil } +// SendMessages sends zero or more user messages to the session in a single turn and returns +// their message IDs. All provided messages are appended to the conversation in order, then +// exactly one agent turn runs over the resulting history. When the list is empty, one turn +// runs over the existing history with no new user message. Remote-backed (Mission Control) +// sessions do not support this method and will return an error. +// +// RPC method: session.sendMessages. +// +// Parameters: Parameters for sending zero or more user messages to the session in a single +// turn. Remote-backed (Mission Control) sessions do not support this method and will return +// an error. +// +// Returns: Result of sending zero or more user messages +// Experimental: SendMessages is an experimental API and may change or be removed in future +// versions. +func (a *SessionRPC) SendMessages(ctx context.Context, params *SendMessagesRequest) (*SendMessagesResult, error) { + req := map[string]any{"sessionId": a.common.sessionID} + if params != nil { + if params.AgentMode != nil { + req["agentMode"] = *params.AgentMode + } + req["messages"] = params.Messages + if params.Mode != nil { + req["mode"] = *params.Mode + } + if params.Prepend != nil { + req["prepend"] = *params.Prepend + } + if params.RequestHeaders != nil { + req["requestHeaders"] = params.RequestHeaders + } + if params.Traceparent != nil { + req["traceparent"] = *params.Traceparent + } + if params.Tracestate != nil { + req["tracestate"] = *params.Tracestate + } + if params.Wait != nil { + req["wait"] = *params.Wait + } + } + raw, err := a.common.client.Request(ctx, "session.sendMessages", req) + if err != nil { + return nil, err + } + var result SendMessagesResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Shutdown shuts down the session and persists its final state. Awaits any deferred // sessionEnd hooks before resolving so user-supplied hook scripts complete before the // runtime tears down. @@ -16714,12 +19310,14 @@ func NewSessionRPC(client *jsonrpc2.Client, sessionID string) *SessionRPC { r := &SessionRPC{} r.common = sessionAPI{client: client, sessionID: sessionID} r.Agent = (*AgentAPI)(&r.common) - r.Auth = (*AuthAPI)(&r.common) r.Canvas = (*CanvasAPI)(&r.common) r.Commands = (*CommandsAPI)(&r.common) + r.Completions = (*CompletionsAPI)(&r.common) + r.Debug = (*DebugAPI)(&r.common) r.EventLog = (*EventLogAPI)(&r.common) r.Extensions = (*ExtensionsAPI)(&r.common) r.Fleet = (*FleetAPI)(&r.common) + r.GitHubAuth = (*GitHubAuthAPI)(&r.common) r.History = (*HistoryAPI)(&r.common) r.Instructions = (*InstructionsAPI)(&r.common) r.Lsp = (*LspAPI)(&r.common) @@ -16743,6 +19341,7 @@ func NewSessionRPC(client *jsonrpc2.Client, sessionID string) *SessionRPC { r.Tools = (*ToolsAPI)(&r.common) r.UI = (*UIAPI)(&r.common) r.Usage = (*UsageAPI)(&r.common) + r.Visibility = (*VisibilityAPI)(&r.common) r.Workspaces = (*WorkspacesAPI)(&r.common) return r } @@ -16838,54 +19437,6 @@ func (a *InternalMCPAPI) ReloadWithConfig(ctx context.Context, params *MCPReload return &result, nil } -// RestartServer restarts an individual MCP server on the session's host (stops then starts). -// -// RPC method: session.mcp.restartServer. -// -// Parameters: Server name and opaque configuration for an individual MCP server restart. -// Internal: RestartServer is part of the SDK's internal handshake/plumbing; external -// callers should not use it. -func (a *InternalMCPAPI) RestartServer(ctx context.Context, params *MCPRestartServerRequest) (*SessionMCPRestartServerResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["config"] = params.Config - req["serverName"] = params.ServerName - } - raw, err := a.client.Request(ctx, "session.mcp.restartServer", req) - if err != nil { - return nil, err - } - var result SessionMCPRestartServerResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// StartServer starts an individual MCP server on the session's host. -// -// RPC method: session.mcp.startServer. -// -// Parameters: Server name and opaque configuration for an individual MCP server start. -// Internal: StartServer is part of the SDK's internal handshake/plumbing; external callers -// should not use it. -func (a *InternalMCPAPI) StartServer(ctx context.Context, params *MCPStartServerRequest) (*SessionMCPStartServerResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["config"] = params.Config - req["serverName"] = params.ServerName - } - raw, err := a.client.Request(ctx, "session.mcp.startServer", req) - if err != nil { - return nil, err - } - var result SessionMCPStartServerResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - // UnregisterExternalClient unregisters a previously registered external MCP client by // server name. Marked internal as the paired companion of `registerExternalClient`: only // in-process callers that registered a client this way can meaningfully unregister it. @@ -16914,44 +19465,64 @@ func (a *InternalMCPAPI) UnregisterExternalClient(ctx context.Context, params *M return &result, nil } -// Experimental: InternalMCPOauthAPI contains experimental APIs that may change or be +// Experimental: InternalSettingsAPI contains experimental APIs that may change or be // removed. -type InternalMCPOauthAPI internalSessionAPI +type InternalSettingsAPI internalSessionAPI -// Responds to a pending MCP OAuth request with an in-process provider. This internal -// CLI-only API accepts a live OAuthClientProvider instance and cannot be used over the SDK -// JSON-RPC boundary. Use session.mcp.oauth.handlePendingRequest instead for the public -// SDK-safe response path. +// EvaluatePredicate evaluates a named Rust-owned settings predicate without exposing raw +// feature flags. Internal: the raw feature-flag names and composition are runtime-internal, +// so this predicate-evaluation helper is kept out of the public SDK surface and is callable +// in-process only. // -// RPC method: session.mcp.oauth.respond. +// RPC method: session.settings.evaluatePredicate. // -// Parameters: MCP OAuth request id and optional provider response. +// Parameters: Named Rust-owned settings predicate to evaluate for this session. // -// Returns: Empty result after recording the MCP OAuth response. -// Internal: Respond is part of the SDK's internal handshake/plumbing; external callers -// should not use it. -func (a *InternalMCPOauthAPI) Respond(ctx context.Context, params *MCPOauthRespondRequest) (*MCPOauthRespondResult, error) { +// Returns: Result of evaluating a Rust-owned settings predicate. +// Internal: EvaluatePredicate is part of the SDK's internal handshake/plumbing; external +// callers should not use it. +func (a *InternalSettingsAPI) EvaluatePredicate(ctx context.Context, params *SessionSettingsEvaluatePredicateRequest) (*SessionSettingsEvaluatePredicateResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { - if params.Provider != nil { - req["provider"] = params.Provider + req["name"] = params.Name + if params.ToolName != nil { + req["toolName"] = *params.ToolName } - req["requestId"] = params.RequestID } - raw, err := a.client.Request(ctx, "session.mcp.oauth.respond", req) + raw, err := a.client.Request(ctx, "session.settings.evaluatePredicate", req) if err != nil { return nil, err } - var result MCPOauthRespondResult + var result SessionSettingsEvaluatePredicateResult if err := json.Unmarshal(raw, &result); err != nil { return nil, err } return &result, nil } -// Experimental: Oauth returns experimental APIs that may change or be removed. -func (s *InternalMCPAPI) Oauth() *InternalMCPOauthAPI { - return (*InternalMCPOauthAPI)(s) +// Snapshot returns a redacted snapshot of session runtime settings, with secrets and raw +// feature flags excluded. Internal: the runtime settings shape is a runtime-internal +// surface and is deliberately kept out of the public SDK, because consumers should not +// depend on the runtime's internal settings layout. It remains callable in-process and is +// expected to be reworked as the runtime internals are consolidated. +// +// RPC method: session.settings.snapshot. +// +// Returns: Redacted, serializable view of session runtime settings for SDK boundary +// consumers. Secrets and raw feature flags are intentionally excluded. +// Internal: Snapshot is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalSettingsAPI) Snapshot(ctx context.Context) (*SessionSettingsSnapshot, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.settings.snapshot", req) + if err != nil { + return nil, err + } + var result SessionSettingsSnapshot + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil } // InternalSessionRPC provides internal SDK session-scoped RPC methods (handshake helpers @@ -16960,13 +19531,15 @@ type InternalSessionRPC struct { // Reuse a single struct instead of allocating one for each service on the heap. common internalSessionAPI - MCP *InternalMCPAPI + MCP *InternalMCPAPI + Settings *InternalSettingsAPI } func NewInternalSessionRPC(client *jsonrpc2.Client, sessionID string) *InternalSessionRPC { r := &InternalSessionRPC{} r.common = internalSessionAPI{client: client, sessionID: sessionID} r.MCP = (*InternalMCPAPI)(&r.common) + r.Settings = (*InternalSettingsAPI)(&r.common) return r } @@ -17463,6 +20036,36 @@ func RegisterClientSessionAPIHandlers(client *jsonrpc2.Client, getHandlers func( }) } +// Experimental: GitHubTelemetryHandler contains experimental APIs that may change or be +// removed. +type GitHubTelemetryHandler interface { + // Event forwards a single GitHub telemetry event to a host connection that opted into + // telemetry forwarding during the `server.connect` handshake. Opted-in connections receive + // every event the runtime emits after the handshake — across all sessions, plus sessionless + // events (for example, `server.sendTelemetry` calls with no session id). + // + // RPC method: gitHubTelemetry.event. + // + // Parameters: Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry + // event the runtime forwards to a host connection that opted into telemetry forwarding + // during the `server.connect` handshake. + Event(request *GitHubTelemetryNotification) error +} + +// Experimental: HooksHandler contains experimental APIs that may change or be removed. +type HooksHandler interface { + // Invoke dispatches one SDK callback hook from the runtime to the connection that + // registered it. Internal transport plumbing: clients opt in through session initialization + // and the Rust hook processor owns ordering, policy, timeout, and callback routing. + // + // RPC method: hooks.invoke. + // + // Parameters: Runtime-owned wire payload for a server-to-client hook callback invocation. + // + // Returns: Optional output returned by an SDK callback hook. + Invoke(request *HookInvokeRequest) (*HookInvokeResponse, error) +} + // Experimental: LlmInferenceHandler contains experimental APIs that may change or be // removed. type LlmInferenceHandler interface { @@ -17499,7 +20102,9 @@ type LlmInferenceHandler interface { // Unlike client-session handlers these carry no implicit session id dispatch // key; a single set of handlers serves the entire connection. type ClientGlobalAPIHandlers struct { - LlmInference LlmInferenceHandler + GitHubTelemetry GitHubTelemetryHandler + Hooks HooksHandler + LlmInference LlmInferenceHandler } func clientGlobalHandlerError(err error) *jsonrpc2.Error { @@ -17516,6 +20121,37 @@ func clientGlobalHandlerError(err error) *jsonrpc2.Error { // RegisterClientGlobalAPIHandlers registers handlers for server-to-client client-global API // calls. func RegisterClientGlobalAPIHandlers(client *jsonrpc2.Client, handlers *ClientGlobalAPIHandlers) { + client.SetRequestHandler("gitHubTelemetry.event", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + var request GitHubTelemetryNotification + if err := json.Unmarshal(params, &request); err != nil { + return nil, &jsonrpc2.Error{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)} + } + if handlers == nil || handlers.GitHubTelemetry == nil { + return nil, nil + } + if err := handlers.GitHubTelemetry.Event(&request); err != nil { + return nil, clientGlobalHandlerError(err) + } + return nil, nil + }) + client.SetRequestHandler("hooks.invoke", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + var request HookInvokeRequest + if err := json.Unmarshal(params, &request); err != nil { + return nil, &jsonrpc2.Error{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)} + } + if handlers == nil || handlers.Hooks == nil { + return nil, &jsonrpc2.Error{Code: -32603, Message: "No hooks client-global handler registered"} + } + result, err := handlers.Hooks.Invoke(&request) + if err != nil { + return nil, clientGlobalHandlerError(err) + } + raw, err := json.Marshal(result) + if err != nil { + return nil, &jsonrpc2.Error{Code: -32603, Message: fmt.Sprintf("Failed to marshal response: %v", err)} + } + return raw, nil + }) client.SetRequestHandler("llmInference.httpRequestChunk", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { var request LlmInferenceHTTPRequestChunkRequest if err := json.Unmarshal(params, &request); err != nil { diff --git a/go/rpc/zrpc_encoding.go b/go/rpc/zrpc_encoding.go index b4942942b5..81e693120b 100644 --- a/go/rpc/zrpc_encoding.go +++ b/go/rpc/zrpc_encoding.go @@ -348,12 +348,66 @@ func unmarshalAttachment(data []byte) (Attachment, error) { return nil, err } return &d, nil + case AttachmentTypeGitHubActionsJob: + var d AttachmentGitHubActionsJob + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AttachmentTypeGitHubCommit: + var d AttachmentGitHubCommit + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AttachmentTypeGitHubFile: + var d AttachmentGitHubFile + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AttachmentTypeGitHubFileDiff: + var d AttachmentGitHubFileDiff + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case AttachmentTypeGitHubReference: var d AttachmentGitHubReference if err := json.Unmarshal(data, &d); err != nil { return nil, err } return &d, nil + case AttachmentTypeGitHubRelease: + var d AttachmentGitHubRelease + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AttachmentTypeGitHubRepository: + var d AttachmentGitHubRepository + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AttachmentTypeGitHubSnippet: + var d AttachmentGitHubSnippet + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AttachmentTypeGitHubTreeComparison: + var d AttachmentGitHubTreeComparison + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AttachmentTypeGitHubURL: + var d AttachmentGitHubURL + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case AttachmentTypeSelection: var d AttachmentSelection if err := json.Unmarshal(data, &d); err != nil { @@ -420,6 +474,50 @@ func (r AttachmentFile) MarshalJSON() ([]byte, error) { }) } +func (r AttachmentGitHubActionsJob) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubActionsJob + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubCommit) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubCommit + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubFile) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubFile + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubFileDiff) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubFileDiff + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r AttachmentGitHubReference) MarshalJSON() ([]byte, error) { type alias AttachmentGitHubReference return json.Marshal(struct { @@ -431,6 +529,61 @@ func (r AttachmentGitHubReference) MarshalJSON() ([]byte, error) { }) } +func (r AttachmentGitHubRelease) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubRelease + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubRepository) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubRepository + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubSnippet) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubSnippet + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubTreeComparison) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubTreeComparison + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubURL) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubURL + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r AttachmentSelection) MarshalJSON() ([]byte, error) { type alias AttachmentSelection return json.Marshal(struct { @@ -516,6 +669,91 @@ func (r *CommandsRespondToQueuedCommandRequest) UnmarshalJSON(data []byte) error return nil } +func unmarshalDebugCollectLogsDestination(data []byte) (DebugCollectLogsDestination, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind DebugCollectLogsDestinationKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case DebugCollectLogsDestinationKindArchive: + var d DebugCollectLogsDestinationArchive + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case DebugCollectLogsDestinationKindDirectory: + var d DebugCollectLogsDestinationDirectory + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawDebugCollectLogsDestinationData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawDebugCollectLogsDestinationData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind DebugCollectLogsDestinationKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r DebugCollectLogsDestinationArchive) MarshalJSON() ([]byte, error) { + type alias DebugCollectLogsDestinationArchive + return json.Marshal(struct { + Kind DebugCollectLogsDestinationKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r DebugCollectLogsDestinationDirectory) MarshalJSON() ([]byte, error) { + type alias DebugCollectLogsDestinationDirectory + return json.Marshal(struct { + Kind DebugCollectLogsDestinationKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r *DebugCollectLogsRequest) UnmarshalJSON(data []byte) error { + type rawDebugCollectLogsRequest struct { + AdditionalEntries []DebugCollectLogsEntry `json:"additionalEntries,omitzero"` + Destination json.RawMessage `json:"destination"` + Include *DebugCollectLogsInclude `json:"include,omitempty"` + } + var raw rawDebugCollectLogsRequest + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + r.AdditionalEntries = raw.AdditionalEntries + if raw.Destination != nil { + value, err := unmarshalDebugCollectLogsDestination(raw.Destination) + if err != nil { + return err + } + r.Destination = value + } + r.Include = raw.Include + return nil +} + func (r EventLogTypes) MarshalJSON() ([]byte, error) { if r.String != nil { return json.Marshal(r.String) @@ -585,6 +823,12 @@ func unmarshalExternalToolTextResultForLlmContent(data []byte) (ExternalToolText return nil, err } return &d, nil + case ExternalToolTextResultForLlmContentTypeShellExit: + var d ExternalToolTextResultForLlmContentShellExit + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case ExternalToolTextResultForLlmContentTypeTerminal: var d ExternalToolTextResultForLlmContentTerminal if err := json.Unmarshal(data, &d); err != nil { @@ -731,6 +975,17 @@ func (r ExternalToolTextResultForLlmContentResourceLink) MarshalJSON() ([]byte, }) } +func (r ExternalToolTextResultForLlmContentShellExit) MarshalJSON() ([]byte, error) { + type alias ExternalToolTextResultForLlmContentShellExit + return json.Marshal(struct { + Type ExternalToolTextResultForLlmContentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r ExternalToolTextResultForLlmContentTerminal) MarshalJSON() ([]byte, error) { type alias ExternalToolTextResultForLlmContentTerminal return json.Marshal(struct { @@ -761,6 +1016,7 @@ func (r *ExternalToolTextResultForLlm) UnmarshalJSON(data []byte) error { ResultType *string `json:"resultType,omitempty"` SessionLog *string `json:"sessionLog,omitempty"` TextResultForLlm string `json:"textResultForLlm"` + ToolReferences []string `json:"toolReferences,omitzero"` ToolTelemetry map[string]any `json:"toolTelemetry,omitzero"` } var raw rawExternalToolTextResultForLlm @@ -782,6 +1038,7 @@ func (r *ExternalToolTextResultForLlm) UnmarshalJSON(data []byte) error { r.ResultType = raw.ResultType r.SessionLog = raw.SessionLog r.TextResultForLlm = raw.TextResultForLlm + r.ToolReferences = raw.ToolReferences r.ToolTelemetry = raw.ToolTelemetry return nil } @@ -1138,6 +1395,89 @@ func (r *MCPConfigUpdateRequest) UnmarshalJSON(data []byte) error { return nil } +func unmarshalMCPHeadersHandlePendingHeadersRefreshRequest(data []byte) (MCPHeadersHandlePendingHeadersRefreshRequest, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind MCPHeadersHandlePendingHeadersRefreshRequestKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case MCPHeadersHandlePendingHeadersRefreshRequestKindHeaders: + var d MCPHeadersHandlePendingHeadersRefreshRequestHeaders + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case MCPHeadersHandlePendingHeadersRefreshRequestKindNone: + var d MCPHeadersHandlePendingHeadersRefreshRequestNone + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawMCPHeadersHandlePendingHeadersRefreshRequestData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawMCPHeadersHandlePendingHeadersRefreshRequestData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind MCPHeadersHandlePendingHeadersRefreshRequestKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r MCPHeadersHandlePendingHeadersRefreshRequestHeaders) MarshalJSON() ([]byte, error) { + type alias MCPHeadersHandlePendingHeadersRefreshRequestHeaders + return json.Marshal(struct { + Kind MCPHeadersHandlePendingHeadersRefreshRequestKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r MCPHeadersHandlePendingHeadersRefreshRequestNone) MarshalJSON() ([]byte, error) { + type alias MCPHeadersHandlePendingHeadersRefreshRequestNone + return json.Marshal(struct { + Kind MCPHeadersHandlePendingHeadersRefreshRequestKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r *MCPHeadersHandlePendingHeadersRefreshRequestRequest) UnmarshalJSON(data []byte) error { + type rawMCPHeadersHandlePendingHeadersRefreshRequestRequest struct { + RequestID string `json:"requestId"` + Result json.RawMessage `json:"result"` + } + var raw rawMCPHeadersHandlePendingHeadersRefreshRequestRequest + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + r.RequestID = raw.RequestID + if raw.Result != nil { + value, err := unmarshalMCPHeadersHandlePendingHeadersRefreshRequest(raw.Result) + if err != nil { + return err + } + r.Result = value + } + return nil +} + func unmarshalMCPOauthPendingRequestResponse(data []byte) (MCPOauthPendingRequestResponse, error) { if string(data) == "null" { return nil, nil @@ -1221,6 +1561,46 @@ func (r *MCPOauthHandlePendingRequest) UnmarshalJSON(data []byte) error { return nil } +func (r *MCPRestartServerRequest) UnmarshalJSON(data []byte) error { + type rawMCPRestartServerRequest struct { + Config json.RawMessage `json:"config,omitempty"` + ServerName string `json:"serverName"` + } + var raw rawMCPRestartServerRequest + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + if raw.Config != nil { + value, err := unmarshalMCPServerConfig(raw.Config) + if err != nil { + return err + } + r.Config = value + } + r.ServerName = raw.ServerName + return nil +} + +func (r *MCPStartServerRequest) UnmarshalJSON(data []byte) error { + type rawMCPStartServerRequest struct { + Config json.RawMessage `json:"config"` + ServerName string `json:"serverName"` + } + var raw rawMCPStartServerRequest + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + if raw.Config != nil { + value, err := unmarshalMCPServerConfig(raw.Config) + if err != nil { + return err + } + r.Config = value + } + r.ServerName = raw.ServerName + return nil +} + func unmarshalPermissionDecision(data []byte) (PermissionDecision, error) { if string(data) == "null" { return nil, nil @@ -2371,12 +2751,66 @@ func unmarshalPushAttachment(data []byte) (PushAttachment, error) { return nil, err } return &d, nil + case PushAttachmentTypeGitHubActionsJob: + var d PushAttachmentGitHubActionsJob + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case PushAttachmentTypeGitHubCommit: + var d PushAttachmentGitHubCommit + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case PushAttachmentTypeGitHubFile: + var d PushAttachmentGitHubFile + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case PushAttachmentTypeGitHubFileDiff: + var d PushAttachmentGitHubFileDiff + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case PushAttachmentTypeGitHubReference: var d PushAttachmentGitHubReference if err := json.Unmarshal(data, &d); err != nil { return nil, err } return &d, nil + case PushAttachmentTypeGitHubRelease: + var d PushAttachmentGitHubRelease + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case PushAttachmentTypeGitHubRepository: + var d PushAttachmentGitHubRepository + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case PushAttachmentTypeGitHubSnippet: + var d PushAttachmentGitHubSnippet + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case PushAttachmentTypeGitHubTreeComparison: + var d PushAttachmentGitHubTreeComparison + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case PushAttachmentTypeGitHubURL: + var d PushAttachmentGitHubURL + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case PushAttachmentTypeSelection: var d PushAttachmentSelection if err := json.Unmarshal(data, &d); err != nil { @@ -2443,6 +2877,50 @@ func (r PushAttachmentFile) MarshalJSON() ([]byte, error) { }) } +func (r PushAttachmentGitHubActionsJob) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubActionsJob + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r PushAttachmentGitHubCommit) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubCommit + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r PushAttachmentGitHubFile) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubFile + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r PushAttachmentGitHubFileDiff) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubFileDiff + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r PushAttachmentGitHubReference) MarshalJSON() ([]byte, error) { type alias PushAttachmentGitHubReference return json.Marshal(struct { @@ -2454,6 +2932,61 @@ func (r PushAttachmentGitHubReference) MarshalJSON() ([]byte, error) { }) } +func (r PushAttachmentGitHubRelease) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubRelease + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r PushAttachmentGitHubRepository) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubRepository + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r PushAttachmentGitHubSnippet) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubSnippet + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r PushAttachmentGitHubTreeComparison) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubTreeComparison + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r PushAttachmentGitHubURL) MarshalJSON() ([]byte, error) { + type alias PushAttachmentGitHubURL + return json.Marshal(struct { + Type PushAttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r PushAttachmentSelection) MarshalJSON() ([]byte, error) { type alias PushAttachmentSelection return json.Marshal(struct { @@ -2643,6 +3176,37 @@ func (r *SendAttachmentsToMessageParams) UnmarshalJSON(data []byte) error { return nil } +func (r *SendMessageItem) UnmarshalJSON(data []byte) error { + type rawSendMessageItem struct { + Attachments []json.RawMessage `json:"attachments,omitzero"` + Billable *bool `json:"billable,omitempty"` + DisplayPrompt *string `json:"displayPrompt,omitempty"` + Prompt string `json:"prompt"` + RequiredTool *string `json:"requiredTool,omitempty"` + Source *string `json:"source,omitempty"` + } + var raw rawSendMessageItem + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + if raw.Attachments != nil { + r.Attachments = make([]Attachment, 0, len(raw.Attachments)) + for _, rawItem := range raw.Attachments { + value, err := unmarshalAttachment(rawItem) + if err != nil { + return err + } + r.Attachments = append(r.Attachments, value) + } + } + r.Billable = raw.Billable + r.DisplayPrompt = raw.DisplayPrompt + r.Prompt = raw.Prompt + r.RequiredTool = raw.RequiredTool + r.Source = raw.Source + return nil +} + func (r *SendRequest) UnmarshalJSON(data []byte) error { type rawSendRequest struct { AgentMode *SendAgentMode `json:"agentMode,omitempty"` @@ -2819,6 +3383,7 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { type rawSessionOpenOptions struct { AdditionalContentExclusionPolicies []SessionOpenOptionsAdditionalContentExclusionPolicy `json:"additionalContentExclusionPolicies,omitzero"` AgentContext *string `json:"agentContext,omitempty"` + AllowAllMCPServerInstructions *bool `json:"allowAllMcpServerInstructions,omitempty"` AskUserDisabled *bool `json:"askUserDisabled,omitempty"` AuthInfo json.RawMessage `json:"authInfo,omitempty"` AvailableTools []string `json:"availableTools,omitzero"` @@ -2835,14 +3400,17 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { DisabledInstructionSources []string `json:"disabledInstructionSources,omitzero"` DisabledSkills []string `json:"disabledSkills,omitzero"` EnableCitations *bool `json:"enableCitations,omitempty"` + EnableManagedSettings *bool `json:"enableManagedSettings,omitempty"` EnableOnDemandInstructionDiscovery *bool `json:"enableOnDemandInstructionDiscovery,omitempty"` EnableScriptSafety *bool `json:"enableScriptSafety,omitempty"` EnableStreaming *bool `json:"enableStreaming,omitempty"` EnvValueMode *SessionOpenOptionsEnvValueMode `json:"envValueMode,omitempty"` EventsLogDirectory *string `json:"eventsLogDirectory,omitempty"` + ExcludedBuiltinAgents []string `json:"excludedBuiltinAgents,omitzero"` ExcludedTools []string `json:"excludedTools,omitzero"` ExpAssignments any `json:"expAssignments,omitempty"` FeatureFlags map[string]bool `json:"featureFlags,omitzero"` + IncludedBuiltinAgents []string `json:"includedBuiltinAgents,omitzero"` InstalledPlugins []InstalledPlugin `json:"installedPlugins,omitzero"` IntegrationID *string `json:"integrationId,omitempty"` IsExperimentalMode *bool `json:"isExperimentalMode,omitempty"` @@ -2865,11 +3433,13 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { SandboxConfig *SandboxConfig `json:"sandboxConfig,omitempty"` SessionCapabilities []SessionCapability `json:"sessionCapabilities,omitzero"` SessionID *string `json:"sessionId,omitempty"` + SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` ShellInitProfile *string `json:"shellInitProfile,omitempty"` ShellProcessFlags []string `json:"shellProcessFlags,omitzero"` SkillDirectories []string `json:"skillDirectories,omitzero"` SkipCustomInstructions *bool `json:"skipCustomInstructions,omitempty"` TrajectoryFile *string `json:"trajectoryFile,omitempty"` + Verbosity *Verbosity `json:"verbosity,omitempty"` WorkingDirectory *string `json:"workingDirectory,omitempty"` WorkingDirectoryContext *SessionContext `json:"workingDirectoryContext,omitempty"` } @@ -2879,6 +3449,7 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { } r.AdditionalContentExclusionPolicies = raw.AdditionalContentExclusionPolicies r.AgentContext = raw.AgentContext + r.AllowAllMCPServerInstructions = raw.AllowAllMCPServerInstructions r.AskUserDisabled = raw.AskUserDisabled if raw.AuthInfo != nil { value, err := unmarshalAuthInfo(raw.AuthInfo) @@ -2901,14 +3472,17 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { r.DisabledInstructionSources = raw.DisabledInstructionSources r.DisabledSkills = raw.DisabledSkills r.EnableCitations = raw.EnableCitations + r.EnableManagedSettings = raw.EnableManagedSettings r.EnableOnDemandInstructionDiscovery = raw.EnableOnDemandInstructionDiscovery r.EnableScriptSafety = raw.EnableScriptSafety r.EnableStreaming = raw.EnableStreaming r.EnvValueMode = raw.EnvValueMode r.EventsLogDirectory = raw.EventsLogDirectory + r.ExcludedBuiltinAgents = raw.ExcludedBuiltinAgents r.ExcludedTools = raw.ExcludedTools r.ExpAssignments = raw.ExpAssignments r.FeatureFlags = raw.FeatureFlags + r.IncludedBuiltinAgents = raw.IncludedBuiltinAgents r.InstalledPlugins = raw.InstalledPlugins r.IntegrationID = raw.IntegrationID r.IsExperimentalMode = raw.IsExperimentalMode @@ -2931,11 +3505,13 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { r.SandboxConfig = raw.SandboxConfig r.SessionCapabilities = raw.SessionCapabilities r.SessionID = raw.SessionID + r.SessionLimits = raw.SessionLimits r.ShellInitProfile = raw.ShellInitProfile r.ShellProcessFlags = raw.ShellProcessFlags r.SkillDirectories = raw.SkillDirectories r.SkipCustomInstructions = raw.SkipCustomInstructions r.TrajectoryFile = raw.TrajectoryFile + r.Verbosity = raw.Verbosity r.WorkingDirectory = raw.WorkingDirectory r.WorkingDirectoryContext = raw.WorkingDirectoryContext return nil diff --git a/go/rpc/zsession_encoding.go b/go/rpc/zsession_encoding.go index 89e9cc26d3..2bd212d884 100644 --- a/go/rpc/zsession_encoding.go +++ b/go/rpc/zsession_encoding.go @@ -41,6 +41,12 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeAssistantIdle: + var d AssistantIdleData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeAssistantIntent: var d AssistantIntentData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -77,12 +83,24 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeAssistantServerToolProgress: + var d AssistantServerToolProgressData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeAssistantStreamingDelta: var d AssistantStreamingDeltaData if err := json.Unmarshal(raw.Data, &d); err != nil { return err } e.Data = &d + case SessionEventTypeAssistantToolCallDelta: + var d AssistantToolCallDeltaData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeAssistantTurnEnd: var d AssistantTurnEndData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -203,6 +221,18 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeMCPHeadersRefreshCompleted: + var d MCPHeadersRefreshCompletedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d + case SessionEventTypeMCPHeadersRefreshRequired: + var d MCPHeadersRefreshRequiredData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeMCPOauthCompleted: var d MCPOauthCompletedData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -215,6 +245,24 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeMCPPromptsListChanged: + var d MCPPromptsListChangedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d + case SessionEventTypeMCPResourcesListChanged: + var d MCPResourcesListChangedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d + case SessionEventTypeMCPToolsListChanged: + var d MCPToolsListChangedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeModelCallFailure: var d ModelCallFailureData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -251,6 +299,12 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeSessionAutoModeResolved: + var d SessionAutoModeResolvedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeSessionAutopilotObjectiveChanged: var d SessionAutopilotObjectiveChangedData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -371,6 +425,24 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeSessionLimitsExhaustedCompleted: + var d SessionLimitsExhaustedCompletedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d + case SessionEventTypeSessionLimitsExhaustedRequested: + var d SessionLimitsExhaustedRequestedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d + case SessionEventTypeSessionManagedSettingsResolved: + var d SessionManagedSettingsResolvedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeSessionMCPServersLoaded: var d SessionMCPServersLoadedData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -437,6 +509,12 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeSessionSessionLimitsChanged: + var d SessionSessionLimitsChangedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeSessionShutdown: var d SessionShutdownData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -491,6 +569,12 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeSessionUsageCheckpoint: + var d SessionUsageCheckpointData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeSessionUsageInfo: var d SessionUsageInfoData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -645,6 +729,7 @@ func (r *UserMessageData) UnmarshalJSON(data []byte) error { AgentMode *UserMessageAgentMode `json:"agentMode,omitempty"` Attachments []json.RawMessage `json:"attachments,omitzero"` Content string `json:"content"` + Delivery *UserMessageDelivery `json:"delivery,omitempty"` InteractionID *string `json:"interactionId,omitempty"` IsAutopilotContinuation *bool `json:"isAutopilotContinuation,omitempty"` NativeDocumentPathFallbackPaths []string `json:"nativeDocumentPathFallbackPaths,omitzero"` @@ -669,6 +754,7 @@ func (r *UserMessageData) UnmarshalJSON(data []byte) error { } } r.Content = raw.Content + r.Delivery = raw.Delivery r.InteractionID = raw.InteractionID r.IsAutopilotContinuation = raw.IsAutopilotContinuation r.NativeDocumentPathFallbackPaths = raw.NativeDocumentPathFallbackPaths @@ -994,6 +1080,12 @@ func unmarshalToolExecutionCompleteContent(data []byte) (ToolExecutionCompleteCo return nil, err } return &d, nil + case ToolExecutionCompleteContentTypeShellExit: + var d ToolExecutionCompleteContentShellExit + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case ToolExecutionCompleteContentTypeTerminal: var d ToolExecutionCompleteContentTerminal if err := json.Unmarshal(data, &d); err != nil { @@ -1128,6 +1220,17 @@ func (r ToolExecutionCompleteContentResourceLink) MarshalJSON() ([]byte, error) }) } +func (r ToolExecutionCompleteContentShellExit) MarshalJSON() ([]byte, error) { + type alias ToolExecutionCompleteContentShellExit + return json.Marshal(struct { + Type ToolExecutionCompleteContentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r ToolExecutionCompleteContentTerminal) MarshalJSON() ([]byte, error) { type alias ToolExecutionCompleteContentTerminal return json.Marshal(struct { @@ -1157,6 +1260,7 @@ func (r *ToolExecutionCompleteResult) UnmarshalJSON(data []byte) error { Content string `json:"content"` Contents []json.RawMessage `json:"contents,omitzero"` DetailedContent *string `json:"detailedContent,omitempty"` + MCPMeta any `json:"mcpMeta,omitempty"` StructuredContent any `json:"structuredContent,omitempty"` UIResource *ToolExecutionCompleteUIResource `json:"uiResource,omitempty"` } @@ -1187,6 +1291,7 @@ func (r *ToolExecutionCompleteResult) UnmarshalJSON(data []byte) error { } } r.DetailedContent = raw.DetailedContent + r.MCPMeta = raw.MCPMeta r.StructuredContent = raw.StructuredContent r.UIResource = raw.UIResource return nil diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index 7964da76bc..ec211132df 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -53,42 +53,53 @@ func (r RawSessionEventData) Type() SessionEventType { type SessionEventType string const ( - SessionEventTypeAbort SessionEventType = "abort" - SessionEventTypeAssistantIntent SessionEventType = "assistant.intent" - SessionEventTypeAssistantMessage SessionEventType = "assistant.message" - SessionEventTypeAssistantMessageDelta SessionEventType = "assistant.message_delta" - SessionEventTypeAssistantMessageStart SessionEventType = "assistant.message_start" - SessionEventTypeAssistantReasoning SessionEventType = "assistant.reasoning" - SessionEventTypeAssistantReasoningDelta SessionEventType = "assistant.reasoning_delta" - SessionEventTypeAssistantStreamingDelta SessionEventType = "assistant.streaming_delta" - SessionEventTypeAssistantTurnEnd SessionEventType = "assistant.turn_end" - SessionEventTypeAssistantTurnStart SessionEventType = "assistant.turn_start" - SessionEventTypeAssistantUsage SessionEventType = "assistant.usage" - SessionEventTypeAutoModeSwitchCompleted SessionEventType = "auto_mode_switch.completed" - SessionEventTypeAutoModeSwitchRequested SessionEventType = "auto_mode_switch.requested" - SessionEventTypeCapabilitiesChanged SessionEventType = "capabilities.changed" - SessionEventTypeCommandCompleted SessionEventType = "command.completed" - SessionEventTypeCommandExecute SessionEventType = "command.execute" - SessionEventTypeCommandQueued SessionEventType = "command.queued" - SessionEventTypeCommandsChanged SessionEventType = "commands.changed" - SessionEventTypeElicitationCompleted SessionEventType = "elicitation.completed" - SessionEventTypeElicitationRequested SessionEventType = "elicitation.requested" - SessionEventTypeExitPlanModeCompleted SessionEventType = "exit_plan_mode.completed" - SessionEventTypeExitPlanModeRequested SessionEventType = "exit_plan_mode.requested" - SessionEventTypeExternalToolCompleted SessionEventType = "external_tool.completed" - SessionEventTypeExternalToolRequested SessionEventType = "external_tool.requested" - SessionEventTypeHookEnd SessionEventType = "hook.end" - SessionEventTypeHookProgress SessionEventType = "hook.progress" - SessionEventTypeHookStart SessionEventType = "hook.start" - SessionEventTypeMCPAppToolCallComplete SessionEventType = "mcp_app.tool_call_complete" - SessionEventTypeMCPOauthCompleted SessionEventType = "mcp.oauth_completed" - SessionEventTypeMCPOauthRequired SessionEventType = "mcp.oauth_required" - SessionEventTypeModelCallFailure SessionEventType = "model.call_failure" - SessionEventTypePendingMessagesModified SessionEventType = "pending_messages.modified" - SessionEventTypePermissionCompleted SessionEventType = "permission.completed" - SessionEventTypePermissionRequested SessionEventType = "permission.requested" - SessionEventTypeSamplingCompleted SessionEventType = "sampling.completed" - SessionEventTypeSamplingRequested SessionEventType = "sampling.requested" + SessionEventTypeAbort SessionEventType = "abort" + SessionEventTypeAssistantIdle SessionEventType = "assistant.idle" + SessionEventTypeAssistantIntent SessionEventType = "assistant.intent" + SessionEventTypeAssistantMessage SessionEventType = "assistant.message" + SessionEventTypeAssistantMessageDelta SessionEventType = "assistant.message_delta" + SessionEventTypeAssistantMessageStart SessionEventType = "assistant.message_start" + SessionEventTypeAssistantReasoning SessionEventType = "assistant.reasoning" + SessionEventTypeAssistantReasoningDelta SessionEventType = "assistant.reasoning_delta" + SessionEventTypeAssistantServerToolProgress SessionEventType = "assistant.server_tool_progress" + SessionEventTypeAssistantStreamingDelta SessionEventType = "assistant.streaming_delta" + SessionEventTypeAssistantToolCallDelta SessionEventType = "assistant.tool_call_delta" + SessionEventTypeAssistantTurnEnd SessionEventType = "assistant.turn_end" + SessionEventTypeAssistantTurnStart SessionEventType = "assistant.turn_start" + SessionEventTypeAssistantUsage SessionEventType = "assistant.usage" + SessionEventTypeAutoModeSwitchCompleted SessionEventType = "auto_mode_switch.completed" + SessionEventTypeAutoModeSwitchRequested SessionEventType = "auto_mode_switch.requested" + SessionEventTypeCapabilitiesChanged SessionEventType = "capabilities.changed" + SessionEventTypeCommandCompleted SessionEventType = "command.completed" + SessionEventTypeCommandExecute SessionEventType = "command.execute" + SessionEventTypeCommandQueued SessionEventType = "command.queued" + SessionEventTypeCommandsChanged SessionEventType = "commands.changed" + SessionEventTypeElicitationCompleted SessionEventType = "elicitation.completed" + SessionEventTypeElicitationRequested SessionEventType = "elicitation.requested" + SessionEventTypeExitPlanModeCompleted SessionEventType = "exit_plan_mode.completed" + SessionEventTypeExitPlanModeRequested SessionEventType = "exit_plan_mode.requested" + SessionEventTypeExternalToolCompleted SessionEventType = "external_tool.completed" + SessionEventTypeExternalToolRequested SessionEventType = "external_tool.requested" + SessionEventTypeHookEnd SessionEventType = "hook.end" + SessionEventTypeHookProgress SessionEventType = "hook.progress" + SessionEventTypeHookStart SessionEventType = "hook.start" + SessionEventTypeMCPAppToolCallComplete SessionEventType = "mcp_app.tool_call_complete" + SessionEventTypeMCPHeadersRefreshCompleted SessionEventType = "mcp.headers_refresh_completed" + SessionEventTypeMCPHeadersRefreshRequired SessionEventType = "mcp.headers_refresh_required" + SessionEventTypeMCPOauthCompleted SessionEventType = "mcp.oauth_completed" + SessionEventTypeMCPOauthRequired SessionEventType = "mcp.oauth_required" + SessionEventTypeMCPPromptsListChanged SessionEventType = "mcp.prompts.list_changed" + SessionEventTypeMCPResourcesListChanged SessionEventType = "mcp.resources.list_changed" + SessionEventTypeMCPToolsListChanged SessionEventType = "mcp.tools.list_changed" + SessionEventTypeModelCallFailure SessionEventType = "model.call_failure" + SessionEventTypePendingMessagesModified SessionEventType = "pending_messages.modified" + SessionEventTypePermissionCompleted SessionEventType = "permission.completed" + SessionEventTypePermissionRequested SessionEventType = "permission.requested" + SessionEventTypeSamplingCompleted SessionEventType = "sampling.completed" + SessionEventTypeSamplingRequested SessionEventType = "sampling.requested" + // Experimental: SessionEventTypeSessionAutoModeResolved identifies an experimental event + // that may change or be removed. + SessionEventTypeSessionAutoModeResolved SessionEventType = "session.auto_mode_resolved" SessionEventTypeSessionAutopilotObjectiveChanged SessionEventType = "session.autopilot_objective_changed" SessionEventTypeSessionBackgroundTasksChanged SessionEventType = "session.background_tasks_changed" // Experimental: SessionEventTypeSessionBinaryAsset identifies an experimental event that @@ -123,45 +134,52 @@ const ( SessionEventTypeSessionHandoff SessionEventType = "session.handoff" SessionEventTypeSessionIdle SessionEventType = "session.idle" SessionEventTypeSessionInfo SessionEventType = "session.info" - SessionEventTypeSessionMCPServersLoaded SessionEventType = "session.mcp_servers_loaded" - SessionEventTypeSessionMCPServerStatusChanged SessionEventType = "session.mcp_server_status_changed" - SessionEventTypeSessionModeChanged SessionEventType = "session.mode_changed" - SessionEventTypeSessionModelChange SessionEventType = "session.model_change" - SessionEventTypeSessionPermissionsChanged SessionEventType = "session.permissions_changed" - SessionEventTypeSessionPlanChanged SessionEventType = "session.plan_changed" - SessionEventTypeSessionRemoteSteerableChanged SessionEventType = "session.remote_steerable_changed" - SessionEventTypeSessionResume SessionEventType = "session.resume" - SessionEventTypeSessionScheduleCancelled SessionEventType = "session.schedule_cancelled" - SessionEventTypeSessionScheduleCreated SessionEventType = "session.schedule_created" - SessionEventTypeSessionScheduleRearmed SessionEventType = "session.schedule_rearmed" - SessionEventTypeSessionShutdown SessionEventType = "session.shutdown" - SessionEventTypeSessionSkillsLoaded SessionEventType = "session.skills_loaded" - SessionEventTypeSessionSnapshotRewind SessionEventType = "session.snapshot_rewind" - SessionEventTypeSessionStart SessionEventType = "session.start" - SessionEventTypeSessionTaskComplete SessionEventType = "session.task_complete" - SessionEventTypeSessionTitleChanged SessionEventType = "session.title_changed" - SessionEventTypeSessionTodosChanged SessionEventType = "session.todos_changed" - SessionEventTypeSessionToolsUpdated SessionEventType = "session.tools_updated" - SessionEventTypeSessionTruncation SessionEventType = "session.truncation" - SessionEventTypeSessionUsageInfo SessionEventType = "session.usage_info" - SessionEventTypeSessionWarning SessionEventType = "session.warning" - SessionEventTypeSessionWorkspaceFileChanged SessionEventType = "session.workspace_file_changed" - SessionEventTypeSkillInvoked SessionEventType = "skill.invoked" - SessionEventTypeSubagentCompleted SessionEventType = "subagent.completed" - SessionEventTypeSubagentDeselected SessionEventType = "subagent.deselected" - SessionEventTypeSubagentFailed SessionEventType = "subagent.failed" - SessionEventTypeSubagentSelected SessionEventType = "subagent.selected" - SessionEventTypeSubagentStarted SessionEventType = "subagent.started" - SessionEventTypeSystemMessage SessionEventType = "system.message" - SessionEventTypeSystemNotification SessionEventType = "system.notification" - SessionEventTypeToolExecutionComplete SessionEventType = "tool.execution_complete" - SessionEventTypeToolExecutionPartialResult SessionEventType = "tool.execution_partial_result" - SessionEventTypeToolExecutionProgress SessionEventType = "tool.execution_progress" - SessionEventTypeToolExecutionStart SessionEventType = "tool.execution_start" - SessionEventTypeToolUserRequested SessionEventType = "tool.user_requested" - SessionEventTypeUserInputCompleted SessionEventType = "user_input.completed" - SessionEventTypeUserInputRequested SessionEventType = "user_input.requested" - SessionEventTypeUserMessage SessionEventType = "user.message" + SessionEventTypeSessionLimitsExhaustedCompleted SessionEventType = "session_limits_exhausted.completed" + SessionEventTypeSessionLimitsExhaustedRequested SessionEventType = "session_limits_exhausted.requested" + // Experimental: SessionEventTypeSessionManagedSettingsResolved identifies an experimental + // event that may change or be removed. + SessionEventTypeSessionManagedSettingsResolved SessionEventType = "session.managed_settings_resolved" + SessionEventTypeSessionMCPServersLoaded SessionEventType = "session.mcp_servers_loaded" + SessionEventTypeSessionMCPServerStatusChanged SessionEventType = "session.mcp_server_status_changed" + SessionEventTypeSessionModeChanged SessionEventType = "session.mode_changed" + SessionEventTypeSessionModelChange SessionEventType = "session.model_change" + SessionEventTypeSessionPermissionsChanged SessionEventType = "session.permissions_changed" + SessionEventTypeSessionPlanChanged SessionEventType = "session.plan_changed" + SessionEventTypeSessionRemoteSteerableChanged SessionEventType = "session.remote_steerable_changed" + SessionEventTypeSessionResume SessionEventType = "session.resume" + SessionEventTypeSessionScheduleCancelled SessionEventType = "session.schedule_cancelled" + SessionEventTypeSessionScheduleCreated SessionEventType = "session.schedule_created" + SessionEventTypeSessionScheduleRearmed SessionEventType = "session.schedule_rearmed" + SessionEventTypeSessionSessionLimitsChanged SessionEventType = "session.session_limits_changed" + SessionEventTypeSessionShutdown SessionEventType = "session.shutdown" + SessionEventTypeSessionSkillsLoaded SessionEventType = "session.skills_loaded" + SessionEventTypeSessionSnapshotRewind SessionEventType = "session.snapshot_rewind" + SessionEventTypeSessionStart SessionEventType = "session.start" + SessionEventTypeSessionTaskComplete SessionEventType = "session.task_complete" + SessionEventTypeSessionTitleChanged SessionEventType = "session.title_changed" + SessionEventTypeSessionTodosChanged SessionEventType = "session.todos_changed" + SessionEventTypeSessionToolsUpdated SessionEventType = "session.tools_updated" + SessionEventTypeSessionTruncation SessionEventType = "session.truncation" + SessionEventTypeSessionUsageCheckpoint SessionEventType = "session.usage_checkpoint" + SessionEventTypeSessionUsageInfo SessionEventType = "session.usage_info" + SessionEventTypeSessionWarning SessionEventType = "session.warning" + SessionEventTypeSessionWorkspaceFileChanged SessionEventType = "session.workspace_file_changed" + SessionEventTypeSkillInvoked SessionEventType = "skill.invoked" + SessionEventTypeSubagentCompleted SessionEventType = "subagent.completed" + SessionEventTypeSubagentDeselected SessionEventType = "subagent.deselected" + SessionEventTypeSubagentFailed SessionEventType = "subagent.failed" + SessionEventTypeSubagentSelected SessionEventType = "subagent.selected" + SessionEventTypeSubagentStarted SessionEventType = "subagent.started" + SessionEventTypeSystemMessage SessionEventType = "system.message" + SessionEventTypeSystemNotification SessionEventType = "system.notification" + SessionEventTypeToolExecutionComplete SessionEventType = "tool.execution_complete" + SessionEventTypeToolExecutionPartialResult SessionEventType = "tool.execution_partial_result" + SessionEventTypeToolExecutionProgress SessionEventType = "tool.execution_progress" + SessionEventTypeToolExecutionStart SessionEventType = "tool.execution_start" + SessionEventTypeToolUserRequested SessionEventType = "tool.user_requested" + SessionEventTypeUserInputCompleted SessionEventType = "user_input.completed" + SessionEventTypeUserInputRequested SessionEventType = "user_input.requested" + SessionEventTypeUserMessage SessionEventType = "user.message" ) // Agent intent description for current activity or plan @@ -202,6 +220,8 @@ type AssistantMessageData struct { // Provider-agnostic citations linking spans of this message's content to the sources that support them. Experimental; only populated when citation emission is enabled. // Experimental: Citations is part of an experimental API and may change or be removed. Citations *Citations `json:"citations,omitempty"` + // Client-minted request id (x-request-id header) echoed by the server. Distinct from requestId (x-github-request-id) and serviceRequestId (x-copilot-service-request-id). + ClientRequestID *string `json:"clientRequestId,omitempty"` // The assistant's text response content Content string `json:"content"` // Encrypted reasoning content from OpenAI models. Session-bound and stripped on resume. @@ -223,6 +243,8 @@ type AssistantMessageData struct { ReasoningOpaque *string `json:"reasoningOpaque,omitempty"` // Readable reasoning text from the model's extended thinking ReasoningText *string `json:"reasoningText,omitempty"` + // OpenAI-compatible wire field the provider used for reasoning (e.g. reasoning_content/reasoning). Populated only when non-canonical, so the dialect round-trips across turns. + ReasoningWireField *string `json:"reasoningWireField,omitempty"` // GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs RequestID *string `json:"requestId,omitempty"` // Neutral provider-tagged server-side tool-use payload (tool search, advisor) for verbatim round-tripping @@ -238,6 +260,28 @@ type AssistantMessageData struct { func (*AssistantMessageData) sessionEventData() {} func (*AssistantMessageData) Type() SessionEventType { return SessionEventTypeAssistantMessage } +// Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. +// Experimental: SessionAutoModeResolvedData is part of an experimental API and may change or be removed. +type SessionAutoModeResolvedData struct { + // Ordered candidate model list the router returned, when not a fallback + CandidateModels []string `json:"candidateModels,omitzero"` + // Per-category classifier scores (0-1) behind the bucket: the granular HYDRA capability scores (reasoning, code_gen, debugging, tool_use), or the binary needs_reasoning/no_reasoning scores when HYDRA didn't run. Lets clients show a breakdown rather than just the bucket. + CategoryScores map[string]float64 `json:"categoryScores,omitzero"` + // The concrete model the session will use after any intent refinement + ChosenModel string `json:"chosenModel"` + // Classifier confidence for the predicted label, when available + Confidence *float64 `json:"confidence,omitempty"` + // The predicted classifier label (e.g. `needs_reasoning`), when available + PredictedLabel *string `json:"predictedLabel,omitempty"` + // Coarse request-difficulty bucket, for explaining why a model was chosen ("picked X because this looks like high-reasoning work") + ReasoningBucket *AutoModeResolvedReasoningBucket `json:"reasoningBucket,omitempty"` +} + +func (*SessionAutoModeResolvedData) sessionEventData() {} +func (*SessionAutoModeResolvedData) Type() SessionEventType { + return SessionEventTypeSessionAutoModeResolved +} + // Auto mode switch completion notification type AutoModeSwitchCompletedData struct { // Request ID of the resolved request; clients should dismiss any UI for this request @@ -306,6 +350,8 @@ func (*SessionBinaryAssetData) Type() SessionEventType { return SessionEventType type SessionCompactionStartData struct { // Token count from non-system messages (user, assistant, tool) at compaction start ConversationTokens *int64 `json:"conversationTokens,omitempty"` + // Model identifier used for compaction, when known + Model *string `json:"model,omitempty"` // Token count from system message(s) at compaction start SystemTokens *int64 `json:"systemTokens,omitempty"` // Token count from tool definitions at compaction start @@ -453,6 +499,37 @@ type SessionCanvasRemovedData struct { func (*SessionCanvasRemovedData) sessionEventData() {} func (*SessionCanvasRemovedData) Type() SessionEventType { return SessionEventTypeSessionCanvasRemoved } +// Durable session usage checkpoint for reconstructing aggregate accounting on resume +type SessionUsageCheckpointData struct { + // Session-wide accumulated nano-AI units cost at checkpoint time + TotalNanoAiu float64 `json:"totalNanoAiu"` + // Total number of premium API requests used at checkpoint time + // Internal: TotalPremiumRequests is part of the SDK's internal API surface and is not intended for external use. + TotalPremiumRequests *float64 `json:"totalPremiumRequests,omitempty"` +} + +func (*SessionUsageCheckpointData) sessionEventData() {} +func (*SessionUsageCheckpointData) Type() SessionEventType { + return SessionEventTypeSessionUsageCheckpoint +} + +// Dynamic headers refresh request for a remote MCP server +type MCPHeadersRefreshRequiredData struct { + // Why dynamic headers are being requested. + Reason MCPHeadersRefreshRequiredReason `json:"reason"` + // Unique identifier for this headers refresh request; used to respond via session.mcp.headers.handlePendingHeadersRefreshRequest() + RequestID string `json:"requestId"` + // Display name of the remote MCP server requesting headers + ServerName string `json:"serverName"` + // URL of the remote MCP server requesting headers + ServerURL string `json:"serverUrl"` +} + +func (*MCPHeadersRefreshRequiredData) sessionEventData() {} +func (*MCPHeadersRefreshRequiredData) Type() SessionEventType { + return SessionEventTypeMCPHeadersRefreshRequired +} + // Elicitation request completion with the user's response type ElicitationCompletedData struct { // The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed) @@ -487,6 +564,15 @@ type ElicitationRequestedData struct { func (*ElicitationRequestedData) sessionEventData() {} func (*ElicitationRequestedData) Type() SessionEventType { return SessionEventTypeElicitationRequested } +// Empty payload for `session.background_tasks_changed`, indicating background task state changed. +type SessionBackgroundTasksChangedData struct { +} + +func (*SessionBackgroundTasksChangedData) sessionEventData() {} +func (*SessionBackgroundTasksChangedData) Type() SessionEventType { + return SessionEventTypeSessionBackgroundTasksChanged +} + // Empty payload; the event signals that the custom agent was deselected, returning to the default agent type SubagentDeselectedData struct { } @@ -503,6 +589,30 @@ func (*PendingMessagesModifiedData) Type() SessionEventType { return SessionEventTypePendingMessagesModified } +// Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. +// Experimental: SessionManagedSettingsResolvedData is part of an experimental API and may change or be removed. +type SessionManagedSettingsResolvedData struct { + // Whether enterprise policy disables bypass-permissions ("yolo") mode for this session. Deny-wins across layers, and forced on when `failClosed` is true. + BypassPermissionsDisabled bool `json:"bypassPermissionsDisabled"` + // Whether the device (MDM/plist/registry/file) managed-settings layer was present + DeviceManaged bool `json:"deviceManaged"` + // Whether managed policy could not be determined (e.g. a failed server fetch) and the session fell back to the fail-closed restriction. When true, restrictions such as disabling bypass-permissions are enforced even though `settings` may be absent. + FailClosed bool `json:"failClosed"` + // The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. + ManagedKeys []string `json:"managedKeys"` + // Whether the server (account/org) managed-settings layer was present + ServerManaged bool `json:"serverManaged"` + // The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. + Settings any `json:"settings,omitempty"` + // Which channel supplied the effective managed settings (the winning layer), or `none` when no policy is in force + Source ManagedSettingsResolvedSource `json:"source"` +} + +func (*SessionManagedSettingsResolvedData) sessionEventData() {} +func (*SessionManagedSettingsResolvedData) Type() SessionEventType { + return SessionEventTypeSessionManagedSettingsResolved +} + // Ephemeral progress update from a running hook process type HookProgressData struct { // Human-readable progress message from the hook process @@ -702,12 +812,27 @@ type AssistantUsageData struct { // Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation ServiceRequestID *string `json:"serviceRequestId,omitempty"` // Time to first token in milliseconds. Only available for streaming requests - TimeToFirstTokenMs *int64 `json:"timeToFirstTokenMs,omitempty"` + TimeToFirstTokenMs *float64 `json:"timeToFirstTokenMs,omitempty"` } func (*AssistantUsageData) sessionEventData() {} func (*AssistantUsageData) Type() SessionEventType { return SessionEventTypeAssistantUsage } +// Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message +type AssistantServerToolProgressData struct { + // Kind of hosted server tool that is running. Only `web_search` is emitted today. + Kind string `json:"kind"` + // Position of the hosted tool call in the response output. Stable across the call's lifecycle events (unlike the provider's per-event item id, which CAPI rotates), so the host keys the live in-progress row on it. + OutputIndex int64 `json:"outputIndex"` + // Lifecycle status of the hosted call: `in_progress`, `searching`, or `completed`. + Status string `json:"status"` +} + +func (*AssistantServerToolProgressData) sessionEventData() {} +func (*AssistantServerToolProgressData) Type() SessionEventType { + return SessionEventTypeAssistantServerToolProgress +} + // MCP App view called a tool on a connected MCP server (SEP-1865) type MCPAppToolCallCompleteData struct { // Arguments passed to the tool by the app view, if any @@ -744,6 +869,19 @@ type MCPOauthCompletedData struct { func (*MCPOauthCompletedData) sessionEventData() {} func (*MCPOauthCompletedData) Type() SessionEventType { return SessionEventTypeMCPOauthCompleted } +// MCP headers refresh request completion notification +type MCPHeadersRefreshCompletedData struct { + // How the pending MCP headers refresh request resolved. + Outcome MCPHeadersRefreshCompletedOutcome `json:"outcome"` + // Request ID of the resolved headers refresh request + RequestID string `json:"requestId"` +} + +func (*MCPHeadersRefreshCompletedData) sessionEventData() {} +func (*MCPHeadersRefreshCompletedData) Type() SessionEventType { + return SessionEventTypeMCPHeadersRefreshCompleted +} + // Model change details including previous and new model identifiers type SessionModelChangeData struct { // Reason the change happened, when not user-initiated. Currently `"rate_limit_auto_switch"` for changes triggered by the auto-mode-switch rate-limit recovery path. UI clients can use this to render contextual copy. @@ -758,10 +896,14 @@ type SessionModelChangeData struct { PreviousReasoningEffort *string `json:"previousReasoningEffort,omitempty"` // Reasoning summary mode before the model change, if applicable PreviousReasoningSummary *ReasoningSummary `json:"previousReasoningSummary,omitempty"` + // Output verbosity level before the model change, if applicable + PreviousVerbosity *Verbosity `json:"previousVerbosity,omitempty"` // Reasoning effort level after the model change, if applicable ReasoningEffort *string `json:"reasoningEffort,omitempty"` // Reasoning summary mode after the model change, if applicable ReasoningSummary *ReasoningSummary `json:"reasoningSummary,omitempty"` + // Output verbosity level after the model change, if applicable + Verbosity *Verbosity `json:"verbosity,omitempty"` } func (*SessionModelChangeData) sessionEventData() {} @@ -780,6 +922,10 @@ func (*SessionRemoteSteerableChangedData) Type() SessionEventType { // OAuth authentication request for an MCP server type MCPOauthRequiredData struct { + // Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. Header order and casing are transport-dependent, and duplicate header names may appear multiple times. + HTTPResponse *MCPOauthHTTPResponse `json:"httpResponse,omitempty"` + // Why the runtime is requesting host-provided OAuth credentials. + Reason MCPOauthRequestReason `json:"reason"` // Unique identifier for this OAuth request; used to respond via session.mcp.oauth.handlePendingRequest RequestID string `json:"requestId"` // Raw OAuth protected-resource metadata document fetched for the MCP server, if available @@ -816,6 +962,46 @@ func (*SessionCustomNotificationData) Type() SessionEventType { return SessionEventTypeSessionCustomNotification } +// Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred +type AssistantIdleData struct { + // True when the preceding agentic loop was cancelled via abort signal + Aborted *bool `json:"aborted,omitempty"` +} + +func (*AssistantIdleData) sessionEventData() {} +func (*AssistantIdleData) Type() SessionEventType { return SessionEventTypeAssistantIdle } + +// Payload identifying the MCP server associated with a list change. +type MCPPromptsListChangedData struct { + // Name of the MCP server whose list changed + ServerName string `json:"serverName"` +} + +func (*MCPPromptsListChangedData) sessionEventData() {} +func (*MCPPromptsListChangedData) Type() SessionEventType { + return SessionEventTypeMCPPromptsListChanged +} + +// Payload identifying the MCP server associated with a list change. +type MCPResourcesListChangedData struct { + // Name of the MCP server whose list changed + ServerName string `json:"serverName"` +} + +func (*MCPResourcesListChangedData) sessionEventData() {} +func (*MCPResourcesListChangedData) Type() SessionEventType { + return SessionEventTypeMCPResourcesListChanged +} + +// Payload identifying the MCP server associated with a list change. +type MCPToolsListChangedData struct { + // Name of the MCP server whose list changed + ServerName string `json:"serverName"` +} + +func (*MCPToolsListChangedData) sessionEventData() {} +func (*MCPToolsListChangedData) Type() SessionEventType { return SessionEventTypeMCPToolsListChanged } + // Payload indicating the session is idle with no background agents or attached shell commands in flight type SessionIdleData struct { // True when the preceding agentic loop was cancelled via abort signal @@ -825,6 +1011,168 @@ type SessionIdleData struct { func (*SessionIdleData) sessionEventData() {} func (*SessionIdleData) Type() SessionEventType { return SessionEventTypeSessionIdle } +// Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. +// Experimental: SessionCanvasClosedData is part of an experimental API and may change or be removed. +type SessionCanvasClosedData struct { + // Provider-local canvas identifier + CanvasID string `json:"canvasId"` + // Owning provider identifier + ExtensionID string `json:"extensionId"` + // Stable caller-supplied identifier of the canvas instance that was closed + InstanceID string `json:"instanceId"` +} + +func (*SessionCanvasClosedData) sessionEventData() {} +func (*SessionCanvasClosedData) Type() SessionEventType { return SessionEventTypeSessionCanvasClosed } + +// Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. +// Experimental: SessionCanvasOpenedData is part of an experimental API and may change or be removed. +type SessionCanvasOpenedData struct { + // Provider-local canvas identifier + CanvasID string `json:"canvasId"` + // Owning provider identifier + ExtensionID string `json:"extensionId"` + // Owning extension display name, when available + ExtensionName *string `json:"extensionName,omitempty"` + // Host-local PNG path for the canvas icon, when supplied + Icon *string `json:"icon,omitempty"` + // Input supplied when the instance was opened + Input any `json:"input,omitempty"` + // Stable caller-supplied canvas instance identifier + InstanceID string `json:"instanceId"` + // Provider-supplied status text + Status *string `json:"status,omitempty"` + // Rendered title + Title *string `json:"title,omitempty"` + // URL for web-rendered canvases + URL *string `json:"url,omitempty"` +} + +func (*SessionCanvasOpenedData) sessionEventData() {} +func (*SessionCanvasOpenedData) Type() SessionEventType { return SessionEventTypeSessionCanvasOpened } + +// Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. +// Experimental: SessionCanvasRegistryChangedData is part of an experimental API and may change or be removed. +type SessionCanvasRegistryChangedData struct { + // Canvas declarations currently available + Canvases []CanvasRegistryChangedCanvas `json:"canvases"` +} + +func (*SessionCanvasRegistryChangedData) sessionEventData() {} +func (*SessionCanvasRegistryChangedData) Type() SessionEventType { + return SessionEventTypeSessionCanvasRegistryChanged +} + +// Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. +type SessionCustomAgentsUpdatedData struct { + // Array of loaded custom agent metadata + Agents []CustomAgentsUpdatedAgent `json:"agents"` + // Fatal errors from agent loading + Errors []string `json:"errors"` + // Non-fatal warnings from agent loading + Warnings []string `json:"warnings"` +} + +func (*SessionCustomAgentsUpdatedData) sessionEventData() {} +func (*SessionCustomAgentsUpdatedData) Type() SessionEventType { + return SessionEventTypeSessionCustomAgentsUpdated +} + +// Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. +type SessionExtensionsAttachmentsPushedData struct { + // Attachments contributed by an extension; the host should surface these as composer pills and forward them via the next session.send call. + Attachments []Attachment `json:"attachments"` +} + +func (*SessionExtensionsAttachmentsPushedData) sessionEventData() {} +func (*SessionExtensionsAttachmentsPushedData) Type() SessionEventType { + return SessionEventTypeSessionExtensionsAttachmentsPushed +} + +// Payload of `session.extensions_loaded` listing discovered extensions and their statuses. +type SessionExtensionsLoadedData struct { + // Array of discovered extensions and their status + Extensions []ExtensionsLoadedExtension `json:"extensions"` +} + +func (*SessionExtensionsLoadedData) sessionEventData() {} +func (*SessionExtensionsLoadedData) Type() SessionEventType { + return SessionEventTypeSessionExtensionsLoaded +} + +// Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. +type SessionMCPServerStatusChangedData struct { + // Error message if the server entered a failed state + Error *string `json:"error,omitempty"` + // Name of the MCP server whose status changed + ServerName string `json:"serverName"` + // Connection status: connected, failed, needs-auth, pending, disabled, or not_configured + Status MCPServerStatus `json:"status"` +} + +func (*SessionMCPServerStatusChangedData) sessionEventData() {} +func (*SessionMCPServerStatusChangedData) Type() SessionEventType { + return SessionEventTypeSessionMCPServerStatusChanged +} + +// Payload of `session.mcp_servers_loaded` listing MCP server status summaries. +type SessionMCPServersLoadedData struct { + // Array of MCP server status summaries + Servers []MCPServersLoadedServer `json:"servers"` +} + +func (*SessionMCPServersLoadedData) sessionEventData() {} +func (*SessionMCPServersLoadedData) Type() SessionEventType { + return SessionEventTypeSessionMCPServersLoaded +} + +// Payload of `session.skills_loaded` listing resolved skill metadata. +type SessionSkillsLoadedData struct { + // Array of resolved skill metadata + Skills []SkillsLoadedSkill `json:"skills"` +} + +func (*SessionSkillsLoadedData) sessionEventData() {} +func (*SessionSkillsLoadedData) Type() SessionEventType { return SessionEventTypeSessionSkillsLoaded } + +// Payload of `session.tools_updated` identifying the model whose resolved tools were updated. +type SessionToolsUpdatedData struct { + // Identifier of the model the resolved tools apply to. + Model string `json:"model"` +} + +func (*SessionToolsUpdatedData) sessionEventData() {} +func (*SessionToolsUpdatedData) Type() SessionEventType { return SessionEventTypeSessionToolsUpdated } + +// Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. +type UserMessageData struct { + // The agent mode that was active when this message was sent + AgentMode *UserMessageAgentMode `json:"agentMode,omitempty"` + // Files, selections, or GitHub references attached to the message + Attachments []Attachment `json:"attachments,omitzero"` + // The user's message text as displayed in the timeline + Content string `json:"content"` + // How this message was delivered to the agentic loop relative to loop state (idle-start vs. steering/queued while busy). The timing axis; combine with `source` (origin) for the full picture. Used for telemetry attribution. + Delivery *UserMessageDelivery `json:"delivery,omitempty"` + // CAPI interaction ID for correlating this user message with its turn + InteractionID *string `json:"interactionId,omitempty"` + // True when this user message was auto-injected by autopilot's continuation loop rather than typed by the user; used to distinguish autopilot-driven turns in telemetry. + IsAutopilotContinuation *bool `json:"isAutopilotContinuation,omitempty"` + // Path-backed native document attachments that stayed on the tagged_files path flow because native upload could not read them or would exceed the request size limit + NativeDocumentPathFallbackPaths []string `json:"nativeDocumentPathFallbackPaths,omitzero"` + // Parent agent task ID for background telemetry correlated to this user turn + ParentAgentTaskID *string `json:"parentAgentTaskId,omitempty"` + // Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) + Source *string `json:"source,omitempty"` + // Normalized document MIME types that were sent natively instead of through tagged_files XML + SupportedNativeDocumentMIMETypes []string `json:"supportedNativeDocumentMimeTypes,omitzero"` + // Transformed version of the message sent to the model, with XML wrapping, timestamps, and other augmentations for prompt caching + TransformedContent *string `json:"transformedContent,omitempty"` +} + +func (*UserMessageData) sessionEventData() {} +func (*UserMessageData) Type() SessionEventType { return SessionEventTypeUserMessage } + // Permission request completion notification signaling UI dismissal type PermissionCompletedData struct { // Request ID of the resolved permission request; clients should dismiss any UI for this request @@ -853,10 +1201,16 @@ type PermissionRequestedData struct { func (*PermissionRequestedData) sessionEventData() {} func (*PermissionRequestedData) Type() SessionEventType { return SessionEventTypePermissionRequested } -// Permissions change details carrying the aggregate allow-all boolean transition. +// Permissions change details carrying the aggregate allow-all transition. type SessionPermissionsChangedData struct { + // Allow-all mode after the change + // Experimental: AllowAllPermissionMode is part of an experimental API and may change or be removed. + AllowAllPermissionMode *PermissionAllowAllMode `json:"allowAllPermissionMode,omitempty"` // Aggregate allow-all flag after the change AllowAllPermissions bool `json:"allowAllPermissions"` + // Allow-all mode before the change + // Experimental: PreviousAllowAllPermissionMode is part of an experimental API and may change or be removed. + PreviousAllowAllPermissionMode *PermissionAllowAllMode `json:"previousAllowAllPermissionMode,omitempty"` // Aggregate allow-all flag before the change PreviousAllowAllPermissions bool `json:"previousAllowAllPermissions"` } @@ -1017,173 +1371,6 @@ func (*SessionScheduleCreatedData) Type() SessionEventType { return SessionEventTypeSessionScheduleCreated } -// Schema for the `BackgroundTasksChangedData` type. -type SessionBackgroundTasksChangedData struct { -} - -func (*SessionBackgroundTasksChangedData) sessionEventData() {} -func (*SessionBackgroundTasksChangedData) Type() SessionEventType { - return SessionEventTypeSessionBackgroundTasksChanged -} - -// Schema for the `CanvasClosedData` type. -// Experimental: SessionCanvasClosedData is part of an experimental API and may change or be removed. -type SessionCanvasClosedData struct { - // Provider-local canvas identifier - CanvasID string `json:"canvasId"` - // Owning provider identifier - ExtensionID string `json:"extensionId"` - // Stable caller-supplied identifier of the canvas instance that was closed - InstanceID string `json:"instanceId"` -} - -func (*SessionCanvasClosedData) sessionEventData() {} -func (*SessionCanvasClosedData) Type() SessionEventType { return SessionEventTypeSessionCanvasClosed } - -// Schema for the `CanvasOpenedData` type. -// Experimental: SessionCanvasOpenedData is part of an experimental API and may change or be removed. -type SessionCanvasOpenedData struct { - // Provider-local canvas identifier - CanvasID string `json:"canvasId"` - // Owning provider identifier - ExtensionID string `json:"extensionId"` - // Owning extension display name, when available - ExtensionName *string `json:"extensionName,omitempty"` - // Input supplied when the instance was opened - Input any `json:"input,omitempty"` - // Stable caller-supplied canvas instance identifier - InstanceID string `json:"instanceId"` - // Provider-supplied status text - Status *string `json:"status,omitempty"` - // Rendered title - Title *string `json:"title,omitempty"` - // URL for web-rendered canvases - URL *string `json:"url,omitempty"` -} - -func (*SessionCanvasOpenedData) sessionEventData() {} -func (*SessionCanvasOpenedData) Type() SessionEventType { return SessionEventTypeSessionCanvasOpened } - -// Schema for the `CanvasRegistryChangedData` type. -// Experimental: SessionCanvasRegistryChangedData is part of an experimental API and may change or be removed. -type SessionCanvasRegistryChangedData struct { - // Canvas declarations currently available - Canvases []CanvasRegistryChangedCanvas `json:"canvases"` -} - -func (*SessionCanvasRegistryChangedData) sessionEventData() {} -func (*SessionCanvasRegistryChangedData) Type() SessionEventType { - return SessionEventTypeSessionCanvasRegistryChanged -} - -// Schema for the `CustomAgentsUpdatedData` type. -type SessionCustomAgentsUpdatedData struct { - // Array of loaded custom agent metadata - Agents []CustomAgentsUpdatedAgent `json:"agents"` - // Fatal errors from agent loading - Errors []string `json:"errors"` - // Non-fatal warnings from agent loading - Warnings []string `json:"warnings"` -} - -func (*SessionCustomAgentsUpdatedData) sessionEventData() {} -func (*SessionCustomAgentsUpdatedData) Type() SessionEventType { - return SessionEventTypeSessionCustomAgentsUpdated -} - -// Schema for the `ExtensionsAttachmentsPushedData` type. -type SessionExtensionsAttachmentsPushedData struct { - // Attachments contributed by an extension; the host should surface these as composer pills and forward them via the next session.send call. - Attachments []Attachment `json:"attachments"` -} - -func (*SessionExtensionsAttachmentsPushedData) sessionEventData() {} -func (*SessionExtensionsAttachmentsPushedData) Type() SessionEventType { - return SessionEventTypeSessionExtensionsAttachmentsPushed -} - -// Schema for the `ExtensionsLoadedData` type. -type SessionExtensionsLoadedData struct { - // Array of discovered extensions and their status - Extensions []ExtensionsLoadedExtension `json:"extensions"` -} - -func (*SessionExtensionsLoadedData) sessionEventData() {} -func (*SessionExtensionsLoadedData) Type() SessionEventType { - return SessionEventTypeSessionExtensionsLoaded -} - -// Schema for the `McpServerStatusChangedData` type. -type SessionMCPServerStatusChangedData struct { - // Error message if the server entered a failed state - Error *string `json:"error,omitempty"` - // Name of the MCP server whose status changed - ServerName string `json:"serverName"` - // Connection status: connected, failed, needs-auth, pending, disabled, or not_configured - Status MCPServerStatus `json:"status"` -} - -func (*SessionMCPServerStatusChangedData) sessionEventData() {} -func (*SessionMCPServerStatusChangedData) Type() SessionEventType { - return SessionEventTypeSessionMCPServerStatusChanged -} - -// Schema for the `McpServersLoadedData` type. -type SessionMCPServersLoadedData struct { - // Array of MCP server status summaries - Servers []MCPServersLoadedServer `json:"servers"` -} - -func (*SessionMCPServersLoadedData) sessionEventData() {} -func (*SessionMCPServersLoadedData) Type() SessionEventType { - return SessionEventTypeSessionMCPServersLoaded -} - -// Schema for the `SkillsLoadedData` type. -type SessionSkillsLoadedData struct { - // Array of resolved skill metadata - Skills []SkillsLoadedSkill `json:"skills"` -} - -func (*SessionSkillsLoadedData) sessionEventData() {} -func (*SessionSkillsLoadedData) Type() SessionEventType { return SessionEventTypeSessionSkillsLoaded } - -// Schema for the `ToolsUpdatedData` type. -type SessionToolsUpdatedData struct { - // Identifier of the model the resolved tools apply to. - Model string `json:"model"` -} - -func (*SessionToolsUpdatedData) sessionEventData() {} -func (*SessionToolsUpdatedData) Type() SessionEventType { return SessionEventTypeSessionToolsUpdated } - -// Schema for the `UserMessageData` type. -type UserMessageData struct { - // The agent mode that was active when this message was sent - AgentMode *UserMessageAgentMode `json:"agentMode,omitempty"` - // Files, selections, or GitHub references attached to the message - Attachments []Attachment `json:"attachments,omitzero"` - // The user's message text as displayed in the timeline - Content string `json:"content"` - // CAPI interaction ID for correlating this user message with its turn - InteractionID *string `json:"interactionId,omitempty"` - // True when this user message was auto-injected by autopilot's continuation loop rather than typed by the user; used to distinguish autopilot-driven turns in telemetry. - IsAutopilotContinuation *bool `json:"isAutopilotContinuation,omitempty"` - // Path-backed native document attachments that stayed on the tagged_files path flow because native upload could not read them or would exceed the request size limit - NativeDocumentPathFallbackPaths []string `json:"nativeDocumentPathFallbackPaths,omitzero"` - // Parent agent task ID for background telemetry correlated to this user turn - ParentAgentTaskID *string `json:"parentAgentTaskId,omitempty"` - // Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) - Source *string `json:"source,omitempty"` - // Normalized document MIME types that were sent natively instead of through tagged_files XML - SupportedNativeDocumentMIMETypes []string `json:"supportedNativeDocumentMimeTypes,omitzero"` - // Transformed version of the message sent to the model, with XML wrapping, timestamps, and other augmentations for prompt caching - TransformedContent *string `json:"transformedContent,omitempty"` -} - -func (*UserMessageData) sessionEventData() {} -func (*UserMessageData) Type() SessionEventType { return SessionEventTypeUserMessage } - // Self-paced schedule re-armed for its next run type SessionScheduleRearmedData struct { // Id of the self-paced schedule that was re-armed @@ -1251,8 +1438,12 @@ type SessionStartData struct { SelectedModel *string `json:"selectedModel,omitempty"` // Unique identifier for the session SessionID string `json:"sessionId"` + // Session limits configured at session creation time, if any + SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` // ISO 8601 timestamp when the session was created StartTime time.Time `json:"startTime"` + // Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") + Verbosity *Verbosity `json:"verbosity,omitempty"` // Schema version number for the session event format Version int64 `json:"version"` } @@ -1260,6 +1451,45 @@ type SessionStartData struct { func (*SessionStartData) sessionEventData() {} func (*SessionStartData) Type() SessionEventType { return SessionEventTypeSessionStart } +// Session limit exhaustion notification requiring user action. +type SessionLimitsExhaustedRequestedData struct { + // Configured max AI Credits for the current accounting window. + MaxAiCredits float64 `json:"maxAiCredits"` + // Unique identifier for this request; used to respond via session.ui.handlePendingSessionLimitsExhausted(). + RequestID string `json:"requestId"` + // AI Credits already consumed in the current accounting window. + UsedAiCredits float64 `json:"usedAiCredits"` +} + +func (*SessionLimitsExhaustedRequestedData) sessionEventData() {} +func (*SessionLimitsExhaustedRequestedData) Type() SessionEventType { + return SessionEventTypeSessionLimitsExhaustedRequested +} + +// Session limit exhaustion prompt completion notification. +type SessionLimitsExhaustedCompletedData struct { + // Request ID of the resolved request; clients should dismiss any UI for this request. + RequestID string `json:"requestId"` + // The user's selected session-limit action. + Response SessionLimitsExhaustedResponse `json:"response"` +} + +func (*SessionLimitsExhaustedCompletedData) sessionEventData() {} +func (*SessionLimitsExhaustedCompletedData) Type() SessionEventType { + return SessionEventTypeSessionLimitsExhaustedCompleted +} + +// Session limits update details. Null clears the limits. +type SessionSessionLimitsChangedData struct { + // Current session limits, or null when no limits are active + SessionLimits *SessionLimitsConfig `json:"sessionLimits"` +} + +func (*SessionSessionLimitsChangedData) sessionEventData() {} +func (*SessionSessionLimitsChangedData) Type() SessionEventType { + return SessionEventTypeSessionSessionLimitsChanged +} + // Session resume metadata including current context and event count type SessionResumeData struct { // Whether the session was already in use by another client at resume time @@ -1284,8 +1514,12 @@ type SessionResumeData struct { ResumeTime time.Time `json:"resumeTime"` // Model currently selected at resume time SelectedModel *string `json:"selectedModel,omitempty"` + // Session limits currently configured at resume time; null when no limits are active + SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` // True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. SessionWasActive *bool `json:"sessionWasActive,omitempty"` + // Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") + Verbosity *Verbosity `json:"verbosity,omitempty"` } func (*SessionResumeData) sessionEventData() {} @@ -1367,6 +1601,8 @@ type SkillInvokedData struct { Content string `json:"content"` // Description of the skill from its SKILL.md frontmatter Description *string `json:"description,omitempty"` + // Model identifier active when the skill was invoked, when known + Model *string `json:"model,omitempty"` // Name of the invoked skill Name string `json:"name"` // File path to the SKILL.md definition @@ -1450,6 +1686,23 @@ func (*ToolExecutionPartialResultData) Type() SessionEventType { return SessionEventTypeToolExecutionPartialResult } +// Streaming tool-call input delta for incremental tool-call updates +type AssistantToolCallDeltaData struct { + // Raw provider tool input fragment to append for this tool call. Function/tool-use providers stream serialized JSON argument text (so newlines inside JSON string values may appear as escaped `\n` until the accumulated JSON is parsed); custom tool calls stream raw custom input. + InputDelta string `json:"inputDelta"` + // Tool call ID this delta belongs to, matching the corresponding assistant.message tool request + ToolCallID string `json:"toolCallId"` + // Name of the tool being invoked, when known from the stream + ToolName *string `json:"toolName,omitempty"` + // Tool call type, when known from the stream + ToolType *AssistantMessageToolRequestType `json:"toolType,omitempty"` +} + +func (*AssistantToolCallDeltaData) sessionEventData() {} +func (*AssistantToolCallDeltaData) Type() SessionEventType { + return SessionEventTypeAssistantToolCallDelta +} + // Sub-agent completion details for successful execution type SubagentCompletedData struct { // Human-readable display name of the sub-agent @@ -1556,6 +1809,9 @@ type ToolExecutionCompleteData struct { InteractionID *string `json:"interactionId,omitempty"` // Whether this tool call was explicitly requested by the user rather than the assistant IsUserRequested *bool `json:"isUserRequested,omitempty"` + // FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels). Persisted as `{ ifc: ... }` so the label survives session resume, including model-visible failure results. Experimental. + // Experimental: MCPMeta is part of an experimental API and may change or be removed. + MCPMeta any `json:"mcpMeta,omitempty"` // Model identifier that generated this tool call Model *string `json:"model,omitempty"` // Tool call ID of the parent tool invocation when this event originates from a sub-agent @@ -1610,6 +1866,8 @@ type ToolExecutionStartData struct { // Tool call ID of the parent tool invocation when this event originates from a sub-agent // Deprecated: ParentToolCallID is deprecated. ParentToolCallID *string `json:"parentToolCallId,omitempty"` + // Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. + ShellToolInfo *ToolExecutionStartShellToolInfo `json:"shellToolInfo,omitempty"` // Unique identifier for this tool call ToolCallID string `json:"toolCallId"` // Tool definition metadata, present for MCP tools with MCP Apps support @@ -1650,6 +1908,8 @@ func (*AbortData) Type() SessionEventType { return SessionEventTypeAbort } // Turn completion metadata including the turn identifier type AssistantTurnEndData struct { + // Model identifier used for this turn, when known + Model *string `json:"model,omitempty"` // Identifier of the turn that has ended, matching the corresponding assistant.turn_start event TurnID string `json:"turnId"` } @@ -1661,6 +1921,8 @@ func (*AssistantTurnEndData) Type() SessionEventType { return SessionEventTypeAs type AssistantTurnStartData struct { // CAPI interaction ID for correlating this turn with upstream telemetry InteractionID *string `json:"interactionId,omitempty"` + // Model identifier used for this turn, when known + Model *string `json:"model,omitempty"` // Identifier for this turn within the agentic loop, typically a stringified turn number TurnID string `json:"turnId"` } @@ -1813,7 +2075,7 @@ type AssistantUsageCopilotUsageTokenDetail struct { TokenType string `json:"tokenType"` } -// Schema for the `AssistantUsageQuotaSnapshot` type. +// Internal per-quota snapshot for assistant usage, including entitlement, consumed requests, overage, reset date, and remaining quota. // Internal: AssistantUsageQuotaSnapshot is an internal SDK API and is not part of the public surface. type AssistantUsageQuotaSnapshot struct { // Total requests allowed by the entitlement @@ -1851,7 +2113,7 @@ type AssistantUsageQuotaSnapshot struct { UsedRequests int64 `json:"usedRequests"` } -// Schema for the `CanvasRegistryChangedCanvas` type. +// A single canvas declaration in `session.canvas.registry_changed`, including provider IDs, display metadata, input schema, and actions. // Experimental: CanvasRegistryChangedCanvas is part of an experimental API and may change or be removed. type CanvasRegistryChangedCanvas struct { // Actions the agent or host may invoke @@ -1866,11 +2128,13 @@ type CanvasRegistryChangedCanvas struct { ExtensionID string `json:"extensionId"` // Owning extension display name, when available ExtensionName *string `json:"extensionName,omitempty"` + // Host-local PNG path for the canvas icon, when supplied + Icon *string `json:"icon,omitempty"` // JSON Schema for canvas open input InputSchema any `json:"inputSchema,omitempty"` } -// Schema for the `CanvasRegistryChangedCanvasAction` type. +// A single action within a canvas declaration, with its name, optional description, and optional input schema. // Experimental: CanvasRegistryChangedCanvasAction is part of an experimental API and may change or be removed. type CanvasRegistryChangedCanvasAction struct { // Action description @@ -2010,7 +2274,7 @@ type CitationSpan struct { StartIndex int64 `json:"startIndex"` } -// Schema for the `CommandsChangedCommand` type. +// A single slash command available in the session, as listed by the `commands.changed` event. type CommandsChangedCommand struct { // Optional human-readable command description. Description *string `json:"description,omitempty"` @@ -2059,7 +2323,7 @@ type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail struct { TokenType string `json:"tokenType"` } -// Schema for the `CustomAgentsUpdatedAgent` type. +// A single loaded custom agent in `session.custom_agents_updated`, with identity, source, tools, invocability, and model override. type CustomAgentsUpdatedAgent struct { // Description of what the agent does Description string `json:"description"` @@ -2089,7 +2353,7 @@ type ElicitationRequestedSchema struct { Type ElicitationRequestedSchemaType `json:"type"` } -// Schema for the `ExtensionsLoadedExtension` type. +// A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status. type ExtensionsLoadedExtension struct { // Source-qualified extension ID (e.g., 'project:my-ext', 'user:auth-helper', 'plugin:my-plugin:my-ext') ID string `json:"id"` @@ -2111,6 +2375,14 @@ type HandoffRepository struct { Owner string `json:"owner"` } +// Single HTTP header entry as a name/value pair. +type HeaderEntry struct { + // HTTP response header name as observed by the runtime. + Name string `json:"name"` + // HTTP response header value as observed by the runtime. + Value string `json:"value"` +} + // Error details when the hook failed type HookEndError struct { // Human-readable error message @@ -2129,11 +2401,11 @@ type MCPAppToolCallCompleteError struct { // The tool's `_meta.ui` block at the time of the call, so consumers can decide whether to forward the result to the model without re-listing tools. type MCPAppToolCallCompleteToolMeta struct { - // Schema for the `McpAppToolCallCompleteToolMetaUI` type. + // MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. UI *MCPAppToolCallCompleteToolMetaUI `json:"ui,omitempty"` } -// Schema for the `McpAppToolCallCompleteToolMetaUI` type. +// MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. type MCPAppToolCallCompleteToolMetaUI struct { // `ui://` URI declared by the tool's `_meta.ui.resourceUri` ResourceURI *string `json:"resourceUri,omitempty"` @@ -2141,10 +2413,22 @@ type MCPAppToolCallCompleteToolMetaUI struct { Visibility []string `json:"visibility,omitzero"` } +// Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. +type MCPOauthHTTPResponse struct { + // Complete UTF-8 response body for host-specific challenge handling, including an empty string for an empty body. Omitted when the complete body is not valid UTF-8; body read failures fail the HTTP operation rather than exposing a partial response. + Body *string `json:"body,omitempty"` + // HTTP response headers as observed by the runtime. Order and casing are transport-dependent, and duplicate header names may appear multiple times. + Headers []HeaderEntry `json:"headers"` + // HTTP status code returned with the auth challenge. + StatusCode int32 `json:"statusCode"` +} + // Static OAuth client configuration, if the server specifies one type MCPOauthRequiredStaticClientConfig struct { // OAuth client ID for the server ClientID string `json:"clientId"` + // Optional OAuth client secret for confidential static clients, when the runtime can resolve one + ClientSecret *string `json:"clientSecret,omitempty"` // Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). GrantType *MCPOauthRequiredStaticClientConfigGrantType `json:"grantType,omitempty"` // Whether this is a public OAuth client @@ -2155,13 +2439,13 @@ type MCPOauthRequiredStaticClientConfig struct { type MCPOauthWwwAuthenticateParams struct { // OAuth error from the WWW-Authenticate error parameter, if present Error *string `json:"error,omitempty"` - // Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter - ResourceMetadataURL string `json:"resourceMetadataUrl"` + // Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter, if present + ResourceMetadataURL *string `json:"resourceMetadataUrl,omitempty"` // Requested OAuth scopes from the WWW-Authenticate scope parameter, if present Scope *string `json:"scope,omitempty"` } -// Schema for the `McpServersLoadedServer` type. +// A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata. type MCPServersLoadedServer struct { // Error message if the server failed to connect Error *string `json:"error,omitempty"` @@ -2197,6 +2481,15 @@ type ModelCallFailureRequestFingerprint struct { ToolResultMessageCount int64 `json:"toolResultMessageCount"` } +// Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is "auto"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request. +// Experimental: PermissionAutoApproval is part of an experimental API and may change or be removed. +type PermissionAutoApproval struct { + // Human-readable reason for the judge's recommendation, when available. + Reason *string `json:"reason,omitempty"` + // The auto-approval safety judge's outcome for this request. + Recommendation AutoApprovalRecommendation `json:"recommendation"` +} + // Derived user-facing permission prompt details for UI consumers type PermissionPromptRequest interface { permissionPromptRequest() @@ -2215,6 +2508,9 @@ func (r RawPermissionPromptRequest) Kind() PermissionPromptRequestKind { // Shell command permission prompt type PermissionPromptRequestCommands struct { + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Whether the UI can offer session-wide approval for this command pattern CanOfferSessionApproval bool `json:"canOfferSessionApproval"` // Command identifiers covered by this approval prompt @@ -2238,6 +2534,9 @@ func (PermissionPromptRequestCommands) Kind() PermissionPromptRequestKind { type PermissionPromptRequestCustomTool struct { // Arguments to pass to the custom tool Args any `json:"args,omitempty"` + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Tool call ID that triggered this permission request ToolCallID *string `json:"toolCallId,omitempty"` // Description of what the custom tool does @@ -2253,6 +2552,9 @@ func (PermissionPromptRequestCustomTool) Kind() PermissionPromptRequestKind { // Extension management permission prompt type PermissionPromptRequestExtensionManagement struct { + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Name of the extension being managed ExtensionName *string `json:"extensionName,omitempty"` // The extension management operation (scaffold, reload) @@ -2268,6 +2570,9 @@ func (PermissionPromptRequestExtensionManagement) Kind() PermissionPromptRequest // Extension permission access prompt type PermissionPromptRequestExtensionPermissionAccess struct { + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Capabilities the extension is requesting Capabilities []string `json:"capabilities"` // Name of the extension requesting permission access @@ -2283,6 +2588,9 @@ func (PermissionPromptRequestExtensionPermissionAccess) Kind() PermissionPromptR // Hook confirmation permission prompt type PermissionPromptRequestHook struct { + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Optional message from the hook explaining why confirmation is needed HookMessage *string `json:"hookMessage,omitempty"` // Arguments of the tool call being gated @@ -2302,6 +2610,9 @@ func (PermissionPromptRequestHook) Kind() PermissionPromptRequestKind { type PermissionPromptRequestMCP struct { // Arguments to pass to the MCP tool Args any `json:"args,omitempty"` + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Name of the MCP server providing the tool ServerName string `json:"serverName"` // Tool call ID that triggered this permission request @@ -2321,6 +2632,9 @@ func (PermissionPromptRequestMCP) Kind() PermissionPromptRequestKind { type PermissionPromptRequestMemory struct { // Whether this is a store or vote memory operation Action *PermissionRequestMemoryAction `json:"action,omitempty"` + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Source references for the stored fact (store only) Citations *string `json:"citations,omitempty"` // Vote direction (vote only) @@ -2344,6 +2658,9 @@ func (PermissionPromptRequestMemory) Kind() PermissionPromptRequestKind { type PermissionPromptRequestPath struct { // Underlying permission kind that needs path approval AccessKind PermissionPromptRequestPathAccessKind `json:"accessKind"` + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // File paths that require explicit approval Paths []string `json:"paths"` // Tool call ID that triggered this permission request @@ -2357,6 +2674,9 @@ func (PermissionPromptRequestPath) Kind() PermissionPromptRequestKind { // File read permission prompt type PermissionPromptRequestRead struct { + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Human-readable description of why the file is being read Intention string `json:"intention"` // Path of the file or directory being read @@ -2372,8 +2692,15 @@ func (PermissionPromptRequestRead) Kind() PermissionPromptRequestKind { // URL access permission prompt type PermissionPromptRequestURL struct { + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Human-readable description of why the URL is being accessed Intention string `json:"intention"` + // True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + RequestSandboxBypass *bool `json:"requestSandboxBypass,omitempty"` + // Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + RequestSandboxBypassReason *string `json:"requestSandboxBypassReason,omitempty"` // Tool call ID that triggered this permission request ToolCallID *string `json:"toolCallId,omitempty"` // URL to be fetched @@ -2387,6 +2714,9 @@ func (PermissionPromptRequestURL) Kind() PermissionPromptRequestKind { // File write permission prompt type PermissionPromptRequestWrite struct { + // Auto-approval judge information for this request; present only when auto mode is enabled. + // Experimental: AutoApproval is part of an experimental API and may change or be removed. + AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Whether the UI can offer session-wide approval for file write operations CanOfferSessionApproval bool `json:"canOfferSessionApproval"` // Unified diff showing the proposed changes @@ -2536,6 +2866,10 @@ type PermissionRequestRead struct { Intention string `json:"intention"` // Path of the file or directory being read Path string `json:"path"` + // True when the model has requested to run this search outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the search runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + RequestSandboxBypass *bool `json:"requestSandboxBypass,omitempty"` + // Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + RequestSandboxBypassReason *string `json:"requestSandboxBypassReason,omitempty"` // Tool call ID that triggered this permission request ToolCallID *string `json:"toolCallId,omitempty"` } @@ -2580,6 +2914,10 @@ func (PermissionRequestShell) Kind() PermissionRequestKind { type PermissionRequestURL struct { // Human-readable description of why the URL is being accessed Intention string `json:"intention"` + // True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + RequestSandboxBypass *bool `json:"requestSandboxBypass,omitempty"` + // Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + RequestSandboxBypassReason *string `json:"requestSandboxBypassReason,omitempty"` // Tool call ID that triggered this permission request ToolCallID *string `json:"toolCallId,omitempty"` // URL to be fetched @@ -2603,6 +2941,10 @@ type PermissionRequestWrite struct { Intention string `json:"intention"` // Complete new file contents for newly created files NewFileContents *string `json:"newFileContents,omitempty"` + // True when a built-in file tool (apply_patch / str_replace_editor) asked to write a path the sandbox filesystem policy would block, and the host opted in via sandbox.allowBypass. This is a request, not a grant: the write happens unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + RequestSandboxBypass *bool `json:"requestSandboxBypass,omitempty"` + // Justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + RequestSandboxBypassReason *string `json:"requestSandboxBypassReason,omitempty"` // Tool call ID that triggered this permission request ToolCallID *string `json:"toolCallId,omitempty"` } @@ -2612,7 +2954,7 @@ func (PermissionRequestWrite) Kind() PermissionRequestKind { return PermissionRequestKindWrite } -// Schema for the `PermissionRequestShellCommand` type. +// A parsed command identifier in a shell permission request, including whether it is read-only. type PermissionRequestShellCommand struct { // Command identifier (e.g., executable name) Identifier string `json:"identifier"` @@ -2620,7 +2962,7 @@ type PermissionRequestShellCommand struct { ReadOnly bool `json:"readOnly"` } -// Schema for the `PermissionRequestShellPossibleUrl` type. +// A URL that may be accessed by a command in a shell permission request. type PermissionRequestShellPossibleURL struct { // URL that may be accessed by the command URL string `json:"url"` @@ -2642,7 +2984,7 @@ func (r RawPermissionResult) Kind() PermissionResultKind { return r.Discriminator } -// Schema for the `PermissionApproved` type. +// Permission response variant indicating the request was approved without persisting an approval rule. type PermissionApproved struct { } @@ -2651,7 +2993,7 @@ func (PermissionApproved) Kind() PermissionResultKind { return PermissionResultKindApproved } -// Schema for the `PermissionApprovedForLocation` type. +// Permission response variant that approves a request and persists the provided approval to a project location key. type PermissionApprovedForLocation struct { // The approval to persist for this location Approval UserToolSessionApproval `json:"approval"` @@ -2664,7 +3006,7 @@ func (PermissionApprovedForLocation) Kind() PermissionResultKind { return PermissionResultKindApprovedForLocation } -// Schema for the `PermissionApprovedForSession` type. +// Permission response variant that approves a request and remembers the provided approval for the rest of the session. type PermissionApprovedForSession struct { // The approval to add as a session-scoped rule Approval UserToolSessionApproval `json:"approval"` @@ -2675,7 +3017,7 @@ func (PermissionApprovedForSession) Kind() PermissionResultKind { return PermissionResultKindApprovedForSession } -// Schema for the `PermissionCancelled` type. +// Permission response variant indicating the request was cancelled before use, with an optional reason. type PermissionCancelled struct { // Optional explanation of why the request was cancelled Reason *string `json:"reason,omitempty"` @@ -2686,7 +3028,7 @@ func (PermissionCancelled) Kind() PermissionResultKind { return PermissionResultKindCancelled } -// Schema for the `PermissionDeniedByContentExclusionPolicy` type. +// Permission response variant denying a path under content exclusion policy, with the path and message. type PermissionDeniedByContentExclusionPolicy struct { // Human-readable explanation of why the path was excluded Message string `json:"message"` @@ -2699,7 +3041,7 @@ func (PermissionDeniedByContentExclusionPolicy) Kind() PermissionResultKind { return PermissionResultKindDeniedByContentExclusionPolicy } -// Schema for the `PermissionDeniedByPermissionRequestHook` type. +// Permission response variant denied by a permission-request hook, with optional message and interrupt flag. type PermissionDeniedByPermissionRequestHook struct { // Whether to interrupt the current agent turn Interrupt *bool `json:"interrupt,omitempty"` @@ -2712,7 +3054,7 @@ func (PermissionDeniedByPermissionRequestHook) Kind() PermissionResultKind { return PermissionResultKindDeniedByPermissionRequestHook } -// Schema for the `PermissionDeniedByRules` type. +// Permission response variant denied because matching approval rules explicitly blocked the request. type PermissionDeniedByRules struct { // Rules that denied the request Rules []PermissionRule `json:"rules"` @@ -2723,7 +3065,7 @@ func (PermissionDeniedByRules) Kind() PermissionResultKind { return PermissionResultKindDeniedByRules } -// Schema for the `PermissionDeniedInteractivelyByUser` type. +// Permission response variant denied in an interactive user prompt, with optional feedback and force-reject flag. type PermissionDeniedInteractivelyByUser struct { // Optional feedback from the user explaining the denial Feedback *string `json:"feedback,omitempty"` @@ -2736,7 +3078,7 @@ func (PermissionDeniedInteractivelyByUser) Kind() PermissionResultKind { return PermissionResultKindDeniedInteractivelyByUser } -// Schema for the `PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. +// Permission response variant denied because no approval rule matched and user confirmation was unavailable. type PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser struct { } @@ -2829,6 +3171,16 @@ func (r PersistedBinaryImage) Type() PersistedBinaryResultType { return PersistedBinaryResultType(r.Discriminator) } +// The user's selected action for an exhausted session limit. +type SessionLimitsExhaustedResponse struct { + // Action selected by the user. + Action SessionLimitsExhaustedResponseAction `json:"action"` + // AI Credits to add to the current max when action is 'add'. + AdditionalAiCredits *float64 `json:"additionalAiCredits,omitempty"` + // New absolute max AI Credits when action is 'set'. + MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` +} + // Aggregate code change metrics for the session type ShutdownCodeChanges struct { // List of file paths that were modified during the session @@ -2839,7 +3191,7 @@ type ShutdownCodeChanges struct { LinesRemoved int64 `json:"linesRemoved"` } -// Schema for the `ShutdownModelMetric` type. +// Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details. type ShutdownModelMetric struct { // Request count and cost metrics Requests ShutdownModelMetricRequests `json:"requests"` @@ -2862,7 +3214,7 @@ type ShutdownModelMetricRequests struct { Count *int64 `json:"count,omitempty"` } -// Schema for the `ShutdownModelMetricTokenDetail` type. +// A token-type entry in a shutdown model metric, storing the accumulated token count. type ShutdownModelMetricTokenDetail struct { // Accumulated token count for this token type TokenCount int64 `json:"tokenCount"` @@ -2882,13 +3234,13 @@ type ShutdownModelMetricUsage struct { ReasoningTokens *int64 `json:"reasoningTokens,omitempty"` } -// Schema for the `ShutdownTokenDetail` type. +// A session-wide shutdown token-type entry storing the accumulated token count. type ShutdownTokenDetail struct { // Accumulated token count for this token type TokenCount int64 `json:"tokenCount"` } -// Schema for the `SkillsLoadedSkill` type. +// A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. type SkillsLoadedSkill struct { // Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field ArgumentHint *string `json:"argumentHint,omitempty"` @@ -2930,7 +3282,7 @@ func (r RawSystemNotification) Type() SystemNotificationType { return r.Discriminator } -// Schema for the `SystemNotificationAgentCompleted` type. +// System notification metadata for a background agent that completed or failed, including agent ID, type, status, description, and prompt. type SystemNotificationAgentCompleted struct { // Unique identifier of the background agent AgentID string `json:"agentId"` @@ -2949,7 +3301,7 @@ func (SystemNotificationAgentCompleted) Type() SystemNotificationType { return SystemNotificationTypeAgentCompleted } -// Schema for the `SystemNotificationAgentIdle` type. +// System notification metadata for a background agent that became idle, including agent ID, type, and description. type SystemNotificationAgentIdle struct { // Unique identifier of the background agent AgentID string `json:"agentId"` @@ -2964,7 +3316,7 @@ func (SystemNotificationAgentIdle) Type() SystemNotificationType { return SystemNotificationTypeAgentIdle } -// Schema for the `SystemNotificationInstructionDiscovered` type. +// System notification metadata for an instruction file discovered during tool access, including source, trigger file, and tool. type SystemNotificationInstructionDiscovered struct { // Human-readable label for the timeline (e.g., 'AGENTS.md from packages/billing/') Description *string `json:"description,omitempty"` @@ -2981,7 +3333,7 @@ func (SystemNotificationInstructionDiscovered) Type() SystemNotificationType { return SystemNotificationTypeInstructionDiscovered } -// Schema for the `SystemNotificationNewInboxMessage` type. +// System notification metadata for a new inbox message, including entry ID, sender details, and summary. type SystemNotificationNewInboxMessage struct { // Unique identifier of the inbox entry EntryID string `json:"entryId"` @@ -2998,7 +3350,7 @@ func (SystemNotificationNewInboxMessage) Type() SystemNotificationType { return SystemNotificationTypeNewInboxMessage } -// Schema for the `SystemNotificationShellCompleted` type. +// System notification metadata for a shell session that completed, including shell ID, optional exit code, and description. type SystemNotificationShellCompleted struct { // Human-readable description of the command Description *string `json:"description,omitempty"` @@ -3013,7 +3365,7 @@ func (SystemNotificationShellCompleted) Type() SystemNotificationType { return SystemNotificationTypeShellCompleted } -// Schema for the `SystemNotificationShellDetachedCompleted` type. +// System notification metadata for a detached shell session that completed, including shell ID and description. type SystemNotificationShellDetachedCompleted struct { // Human-readable description of the command Description *string `json:"description,omitempty"` @@ -3102,7 +3454,26 @@ func (ToolExecutionCompleteContentResourceLink) Type() ToolExecutionCompleteCont return ToolExecutionCompleteContentTypeResourceLink } -// Terminal/shell output content block with optional exit code and working directory +// Shell command exit metadata with optional output preview +type ToolExecutionCompleteContentShellExit struct { + // Working directory where the shell command was executed + Cwd *string `json:"cwd,omitempty"` + // Exit code from the completed shell command + ExitCode int64 `json:"exitCode"` + // Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. + OutputPreview *string `json:"outputPreview,omitempty"` + // Whether outputPreview is known to be incomplete or truncated + OutputTruncated *bool `json:"outputTruncated,omitempty"` + // Shell id, as assigned by Copilot runtime + ShellID string `json:"shellId"` +} + +func (ToolExecutionCompleteContentShellExit) toolExecutionCompleteContent() {} +func (ToolExecutionCompleteContentShellExit) Type() ToolExecutionCompleteContentType { + return ToolExecutionCompleteContentTypeShellExit +} + +// Deprecated for shell command exit metadata. Use ToolExecutionCompleteContentShellExit instead. type ToolExecutionCompleteContentTerminal struct { // Working directory where the command was executed Cwd *string `json:"cwd,omitempty"` @@ -3168,6 +3539,9 @@ type ToolExecutionCompleteResult struct { Contents []ToolExecutionCompleteContent `json:"contents,omitzero"` // Full detailed tool result for UI/timeline display, preserving complete content such as diffs. Falls back to content when absent. DetailedContent *string `json:"detailedContent,omitempty"` + // FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels) — persisted as `{ ifc: ... }` (only the `ifc` key, not the whole `_meta`). Persisted so the FIDES IFC label survives session resume: the engine rehydrates accumulated taint by replaying these on load. Populated for ingress sources when FIDES IFC is on. Experimental. + // Experimental: MCPMeta is part of an experimental API and may change or be removed. + MCPMeta any `json:"mcpMeta,omitempty"` // Structured content (arbitrary JSON) returned verbatim by the MCP tool StructuredContent any `json:"structuredContent,omitempty"` // MCP Apps UI resource content for rendering in a sandboxed iframe @@ -3186,11 +3560,11 @@ type ToolExecutionCompleteToolDescription struct { // MCP Apps metadata for UI resource association type ToolExecutionCompleteToolDescriptionMeta struct { - // Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. + // MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. UI *ToolExecutionCompleteToolDescriptionMetaUI `json:"ui,omitempty"` } -// Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. +// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. type ToolExecutionCompleteToolDescriptionMetaUI struct { // URI of the UI resource ResourceURI *string `json:"resourceUri,omitempty"` @@ -3214,21 +3588,21 @@ type ToolExecutionCompleteUIResource struct { // Resource-level UI metadata (CSP, permissions, visual preferences) type ToolExecutionCompleteUIResourceMeta struct { - // Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. + // MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. UI *ToolExecutionCompleteUIResourceMetaUI `json:"ui,omitempty"` } -// Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. +// MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. type ToolExecutionCompleteUIResourceMetaUI struct { - // Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. + // CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. Csp *ToolExecutionCompleteUIResourceMetaUICsp `json:"csp,omitempty"` Domain *string `json:"domain,omitempty"` - // Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. + // Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. Permissions *ToolExecutionCompleteUIResourceMetaUIPermissions `json:"permissions,omitempty"` PrefersBorder *bool `json:"prefersBorder,omitempty"` } -// Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. +// CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. type ToolExecutionCompleteUIResourceMetaUICsp struct { BaseURIDomains []string `json:"baseUriDomains,omitzero"` ConnectDomains []string `json:"connectDomains,omitzero"` @@ -3236,34 +3610,42 @@ type ToolExecutionCompleteUIResourceMetaUICsp struct { ResourceDomains []string `json:"resourceDomains,omitzero"` } -// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. +// Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. type ToolExecutionCompleteUIResourceMetaUIPermissions struct { - // Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. + // Marker object for camera permission on an MCP Apps UI resource. Camera *ToolExecutionCompleteUIResourceMetaUIPermissionsCamera `json:"camera,omitempty"` - // Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. + // Marker object for clipboard-write permission on an MCP Apps UI resource. ClipboardWrite *ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite `json:"clipboardWrite,omitempty"` - // Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. + // Marker object for geolocation permission on an MCP Apps UI resource. Geolocation *ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation `json:"geolocation,omitempty"` - // Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. + // Marker object for microphone permission on an MCP Apps UI resource. Microphone *ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone `json:"microphone,omitempty"` } -// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. +// Marker object for camera permission on an MCP Apps UI resource. type ToolExecutionCompleteUIResourceMetaUIPermissionsCamera struct { } -// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. +// Marker object for clipboard-write permission on an MCP Apps UI resource. type ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite struct { } -// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. +// Marker object for geolocation permission on an MCP Apps UI resource. type ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation struct { } -// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. +// Marker object for microphone permission on an MCP Apps UI resource. type ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone struct { } +// Shell-aware path hints for a shell tool's command, captured at start time so consumers can snapshot a file's pre-image before the tool runs. +type ToolExecutionStartShellToolInfo struct { + // Whether the command includes a file write redirection (e.g., > or >>). + HasWriteFileRedirection bool `json:"hasWriteFileRedirection"` + // File paths the command may read or write, derived from the command at start time. Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. + PossiblePaths []string `json:"possiblePaths"` +} + // Tool definition metadata, present for MCP tools with MCP Apps support type ToolExecutionStartToolDescription struct { // Tool description @@ -3276,11 +3658,11 @@ type ToolExecutionStartToolDescription struct { // MCP Apps metadata for UI resource association type ToolExecutionStartToolDescriptionMeta struct { - // Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. + // MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. UI *ToolExecutionStartToolDescriptionMetaUI `json:"ui,omitempty"` } -// Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. +// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. type ToolExecutionStartToolDescriptionMetaUI struct { // URI of the UI resource ResourceURI *string `json:"resourceUri,omitempty"` @@ -3332,6 +3714,33 @@ const ( AssistantUsageAPIEndpointWsResponses AssistantUsageAPIEndpoint = "ws:/responses" ) +// Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). +// Experimental: AutoApprovalRecommendation is part of an experimental API and may change or be removed. +type AutoApprovalRecommendation string + +const ( + // The judge evaluated the request and recommends automatically approving it. + AutoApprovalRecommendationApprove AutoApprovalRecommendation = "approve" + // The judge was consulted but did not return a usable recommendation, so the request requires explicit approval. + AutoApprovalRecommendationError AutoApprovalRecommendation = "error" + // Auto mode is enabled, but this request category is never auto-approvable (for example, sandbox-bypass requests), so the judge was not consulted. + AutoApprovalRecommendationExcluded AutoApprovalRecommendation = "excluded" + // The judge evaluated the request and does not recommend auto-approving it; explicit approval is required. Whether that means prompting, denying, or something else is the consumer's decision. + AutoApprovalRecommendationRequireApproval AutoApprovalRecommendation = "requireApproval" +) + +// Coarse request-difficulty bucket for UX explainability +type AutoModeResolvedReasoningBucket string + +const ( + // The request looks high-reasoning; a stronger model is appropriate. + AutoModeResolvedReasoningBucketHigh AutoModeResolvedReasoningBucket = "high" + // The request looks low-reasoning; a lighter model is appropriate. + AutoModeResolvedReasoningBucketLow AutoModeResolvedReasoningBucket = "low" + // The request needs a moderate amount of reasoning. + AutoModeResolvedReasoningBucketMedium AutoModeResolvedReasoningBucket = "medium" +) + // The user's auto-mode-switch choice type AutoModeSwitchResponse string @@ -3494,6 +3903,42 @@ const ( HandoffSourceTypeRemote HandoffSourceType = "remote" ) +// Which channel supplied the effective enterprise managed settings (highest-authority present layer wins wholesale) +type ManagedSettingsResolvedSource string + +const ( + // Device-level MDM policy discovered from plist/registry/file (lower authority). + ManagedSettingsResolvedSourceDevice ManagedSettingsResolvedSource = "device" + // No managed policy is in force (no layer contributed). + ManagedSettingsResolvedSourceNone ManagedSettingsResolvedSource = "none" + // Account/org policy self-fetched from the GitHub managed-settings endpoint (higher authority). + ManagedSettingsResolvedSourceServer ManagedSettingsResolvedSource = "server" +) + +// How the pending MCP headers refresh request resolved. +type MCPHeadersRefreshCompletedOutcome string + +const ( + // The host supplied dynamic headers. + MCPHeadersRefreshCompletedOutcomeHeaders MCPHeadersRefreshCompletedOutcome = "headers" + // The host responded with no dynamic headers. + MCPHeadersRefreshCompletedOutcomeNone MCPHeadersRefreshCompletedOutcome = "none" + // No response arrived within the bounded window. + MCPHeadersRefreshCompletedOutcomeTimeout MCPHeadersRefreshCompletedOutcome = "timeout" +) + +// Why dynamic headers are being requested. +type MCPHeadersRefreshRequiredReason string + +const ( + // The server returned 401 and stale dynamic headers were invalidated. + MCPHeadersRefreshRequiredReasonAuthFailed MCPHeadersRefreshRequiredReason = "auth-failed" + // The transport is making its first dynamic header request for this server. + MCPHeadersRefreshRequiredReasonStartup MCPHeadersRefreshRequiredReason = "startup" + // The previously cached dynamic headers expired. + MCPHeadersRefreshRequiredReasonTtlExpired MCPHeadersRefreshRequiredReason = "ttl-expired" +) + // How the pending MCP OAuth request was completed type MCPOauthCompletionOutcome string @@ -3504,6 +3949,20 @@ const ( MCPOauthCompletionOutcomeToken MCPOauthCompletionOutcome = "token" ) +// Reason the runtime is requesting host-provided MCP OAuth credentials +type MCPOauthRequestReason string + +const ( + // Initial credentials are required before connecting to the MCP server. + MCPOauthRequestReasonInitial MCPOauthRequestReason = "initial" + // The server requires a new host authorization flow before continuing. + MCPOauthRequestReasonReauth MCPOauthRequestReason = "reauth" + // The current host-provided credential was rejected and a replacement is requested. + MCPOauthRequestReasonRefresh MCPOauthRequestReason = "refresh" + // The server requires a credential with additional scope or audience. + MCPOauthRequestReasonUpscope MCPOauthRequestReason = "upscope" +) + // Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). type MCPOauthRequiredStaticClientConfigGrantType string @@ -3557,6 +4016,19 @@ const ( OmittedBinaryTypeResource OmittedBinaryType = "resource" ) +// Allow-all mode for the session. +// Experimental: PermissionAllowAllMode is part of an experimental API and may change or be removed. +type PermissionAllowAllMode string + +const ( + // Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + PermissionAllowAllModeAuto PermissionAllowAllMode = "auto" + // Permission requests follow the normal approval flow. + PermissionAllowAllModeOff PermissionAllowAllMode = "off" + // Tool, path, and URL permission requests are automatically approved. + PermissionAllowAllModeOn PermissionAllowAllMode = "on" +) + // Kind discriminator for PermissionPromptRequest. type PermissionPromptRequestKind string @@ -3668,6 +4140,20 @@ const ( PlanChangedOperationUpdate PlanChangedOperation = "update" ) +// User action selected for an exhausted session limit. +type SessionLimitsExhaustedResponseAction string + +const ( + // Increase the current max by an exact AI Credits amount. + SessionLimitsExhaustedResponseActionAdd SessionLimitsExhaustedResponseAction = "add" + // Leave the limit unchanged and cancel the blocked model request. + SessionLimitsExhaustedResponseActionCancel SessionLimitsExhaustedResponseAction = "cancel" + // Set a new absolute max AI Credits value. + SessionLimitsExhaustedResponseActionSet SessionLimitsExhaustedResponseAction = "set" + // Remove the current session limit. + SessionLimitsExhaustedResponseActionUnset SessionLimitsExhaustedResponseAction = "unset" +) + // What triggered the skill invocation: `user-invoked` (explicit user action, such as via a slash command or UI affordance), `agent-invoked` (agent requested the skill), or `context-load` (loaded as part of another context, such as preloading skills configured on a custom agent or subagent) type SkillInvokedTrigger string @@ -3730,6 +4216,7 @@ const ( ToolExecutionCompleteContentTypeImage ToolExecutionCompleteContentType = "image" ToolExecutionCompleteContentTypeResource ToolExecutionCompleteContentType = "resource" ToolExecutionCompleteContentTypeResourceLink ToolExecutionCompleteContentType = "resource_link" + ToolExecutionCompleteContentTypeShellExit ToolExecutionCompleteContentType = "shell_exit" ToolExecutionCompleteContentTypeTerminal ToolExecutionCompleteContentType = "terminal" ToolExecutionCompleteContentTypeText ToolExecutionCompleteContentType = "text" ) @@ -3768,6 +4255,18 @@ const ( UserMessageAgentModeShell UserMessageAgentMode = "shell" ) +// How this user message was delivered to the agentic loop, relative to whether the loop was already running. This is the timing axis only; the message's origin (human vs. system/command/schedule/skill/etc.) is carried separately by `source`. A system-injected message has a delivery too — e.g. a background-task notification waking an idle agent is `idle`, the same mechanism as a human starting a fresh turn. +type UserMessageDelivery string + +const ( + // Delivered while the loop was idle; starts its own run immediately (a human's fresh turn, or a system notification waking an idle agent). + UserMessageDeliveryIdle UserMessageDelivery = "idle" + // Enqueued while the agent was busy; processed as its own run afterward. + UserMessageDeliveryQueued UserMessageDelivery = "queued" + // Injected into the current in-flight run while the agent was busy (immediate mode). + UserMessageDeliverySteering UserMessageDelivery = "steering" +) + // Hosting platform type of the repository (github or ado) type WorkingDirectoryContextHostType string diff --git a/go/session.go b/go/session.go index 851157ba87..c4e742e906 100644 --- a/go/session.go +++ b/go/session.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "fmt" + "log" "sync" "time" @@ -12,6 +13,11 @@ import ( "github.com/github/copilot-sdk/go/rpc" ) +// toolSearchToolName is the fixed name of the runtime's built-in tool-search +// tool. A client can replace its behavior by registering a [Tool] with this +// exact name and OverridesBuiltInTool set to true. +const toolSearchToolName = "tool_search_tool" + type sessionHandler struct { id uint64 fn SessionEventHandler @@ -61,6 +67,8 @@ type Session struct { toolHandlersM sync.RWMutex permissionHandler PermissionHandlerFunc permissionMux sync.RWMutex + mcpAuthHandler MCPAuthHandler + mcpAuthMu sync.RWMutex userInputHandler UserInputHandler userInputMux sync.RWMutex exitPlanModeHandler ExitPlanModeRequestHandler @@ -160,6 +168,7 @@ func (s *Session) updateOpenCanvasesFromEvent(event SessionEvent) { InstanceID: data.InstanceID, Status: data.Status, Title: data.Title, + Icon: data.Icon, URL: data.URL, }) case *SessionCanvasClosedData: @@ -924,6 +933,53 @@ func (s *Session) getElicitationHandler() ElicitationHandler { return s.elicitationHandler } +func (s *Session) registerMCPAuthHandler(handler MCPAuthHandler) { + s.mcpAuthMu.Lock() + defer s.mcpAuthMu.Unlock() + s.mcpAuthHandler = handler +} + +func (s *Session) getMCPAuthHandler() MCPAuthHandler { + s.mcpAuthMu.RLock() + defer s.mcpAuthMu.RUnlock() + return s.mcpAuthHandler +} + +func (s *Session) handleMCPAuthRequest(request MCPAuthRequest) { + handler := s.getMCPAuthHandler() + if handler == nil { + return + } + + ctx := context.Background() + cancel := &rpc.MCPOauthPendingRequestResponseCancelled{} + result, err := handler(request, MCPAuthInvocation{SessionID: s.SessionID}) + if err != nil { + log.Printf( + "MCP OAuth handler failed. SessionId=%s, RequestId=%s, Error=%v", + s.SessionID, + request.RequestID, + err, + ) + } + if err != nil || result == nil || result.Kind == MCPAuthResultKindCancelled || result.Token == nil { + s.RPC.MCP.Oauth().HandlePendingRequest(ctx, &rpc.MCPOauthHandlePendingRequest{ + RequestID: request.RequestID, + Result: cancel, + }) + return + } + + s.RPC.MCP.Oauth().HandlePendingRequest(ctx, &rpc.MCPOauthHandlePendingRequest{ + RequestID: request.RequestID, + Result: &rpc.MCPOauthPendingRequestResponseToken{ + AccessToken: result.Token.AccessToken, + TokenType: result.Token.TokenType, + ExpiresIn: result.Token.ExpiresIn, + }, + }) +} + // handleElicitationRequest dispatches an elicitation.requested event to the registered handler // and sends the result back via the RPC layer. Auto-cancels on error. func (s *Session) handleElicitationRequest(elicitCtx ElicitationContext, requestID string) { @@ -1370,6 +1426,52 @@ func (s *Session) handleBroadcastEvent(event SessionEvent) { } s.executePermissionAndRespond(d.RequestID, d.PermissionRequest, handler) + case *MCPOauthRequiredData: + handler := s.getMCPAuthHandler() + if d.RequestID == "" { + return + } + if handler == nil { + log.Printf( + "Received MCP OAuth request without a registered MCP auth handler. SessionId=%s, RequestId=%s", + s.SessionID, + d.RequestID, + ) + return + } + var staticClientConfig *MCPAuthStaticClientConfig + if d.StaticClientConfig != nil { + var grantType *string + if d.StaticClientConfig.GrantType != nil { + value := string(*d.StaticClientConfig.GrantType) + grantType = &value + } + staticClientConfig = &MCPAuthStaticClientConfig{ + ClientID: d.StaticClientConfig.ClientID, + ClientSecret: d.StaticClientConfig.ClientSecret, + GrantType: grantType, + PublicClient: d.StaticClientConfig.PublicClient, + } + } + request := MCPAuthRequest{ + RequestID: d.RequestID, + ServerName: d.ServerName, + ServerURL: d.ServerURL, + Reason: d.Reason, + StaticClientConfig: staticClientConfig, + } + if d.ResourceMetadata != nil { + request.ResourceMetadata = d.ResourceMetadata + } + if d.WwwAuthenticateParams != nil { + request.WwwAuthenticateParams = &MCPAuthWwwAuthenticateParams{ + ResourceMetadataURL: d.WwwAuthenticateParams.ResourceMetadataURL, + Scope: d.WwwAuthenticateParams.Scope, + Error: d.WwwAuthenticateParams.Error, + } + } + s.handleMCPAuthRequest(request) + case *CommandExecuteData: s.executeCommandAndRespond(d.RequestID, d.CommandName, d.Command, d.Args) @@ -1417,6 +1519,17 @@ func (s *Session) executeToolAndRespond(requestID, toolName, toolCallID string, TraceContext: ctx, } + // The built-in tool-search tool receives a snapshot of the session's + // currently initialized tools so an override can filter the live catalog + // without issuing its own RPC. Fetch it only for that tool to avoid a + // round-trip on every tool call; a failed fetch leaves the snapshot nil + // rather than failing the tool. + if toolName == toolSearchToolName { + if metadata, mErr := s.RPC.Tools.GetCurrentMetadata(ctx); mErr == nil && metadata != nil { + invocation.AvailableTools = metadata.Tools + } + } + result, err := handler(invocation) if err != nil { errMsg := err.Error() @@ -1446,6 +1559,7 @@ func (s *Session) executeToolAndRespond(requestID, toolName, toolCallID string, TextResultForLlm: textResultForLLM, ToolTelemetry: result.ToolTelemetry, ResultType: &effectiveResultType, + ToolReferences: result.ToolReferences, } if result.Error != "" { rpcResult.Error = &result.Error @@ -1639,7 +1753,7 @@ type SetModelOptions struct { // // Example: // -// if err := session.SetModel(context.Background(), "gpt-4.1", nil); err != nil { +// if err := session.SetModel(context.Background(), "gpt-5.4", nil); err != nil { // log.Printf("Failed to set model: %v", err) // } // if err := session.SetModel(context.Background(), "claude-sonnet-4.6", &SetModelOptions{ReasoningEffort: new("high")}); err != nil { diff --git a/go/session_event_serialization_test.go b/go/session_event_serialization_test.go index 5f8855336c..bd47fdfbe2 100644 --- a/go/session_event_serialization_test.go +++ b/go/session_event_serialization_test.go @@ -145,6 +145,26 @@ func TestSessionEventAgentIDRoundTripsUnknownEvent(t *testing.T) { } } +func TestInternalSessionEventUsesRawFallback(t *testing.T) { + var event SessionEvent + if err := json.Unmarshal([]byte(`{ + "id": "00000000-0000-0000-0000-000000000003", + "timestamp": "2026-01-01T00:00:00Z", + "parentId": null, + "type": "session.memory_changed", + "data": {} + }`), &event); err != nil { + t.Fatalf("failed to unmarshal internal session event: %v", err) + } + + if _, ok := event.Data.(*RawSessionEventData); !ok { + t.Fatalf("expected internal event to use raw session event data, got %T", event.Data) + } + if event.Type() != "session.memory_changed" { + t.Fatalf("expected internal event type to be preserved, got %q", event.Type()) + } +} + func TestRawSessionEventDataWithNilRawMarshalsAsNull(t *testing.T) { event := SessionEvent{ Data: &RawSessionEventData{EventType: "future.event"}, diff --git a/go/session_test.go b/go/session_test.go index 654be6ce46..d34c34233b 100644 --- a/go/session_test.go +++ b/go/session_test.go @@ -60,6 +60,205 @@ func TestSession_SetModelOmitsContextTierWhenUnset(t *testing.T) { } } +func TestSession_MCPAuthRequestSendsHostToken(t *testing.T) { + stdinR, stdinW := io.Pipe() + stdoutR, stdoutW := io.Pipe() + defer stdinR.Close() + defer stdinW.Close() + defer stdoutR.Close() + defer stdoutW.Close() + + client := jsonrpc2.NewClient(stdinW, stdoutR) + client.Start() + defer client.Stop() + + paramsCh := make(chan map[string]any, 1) + errCh := make(chan error, 1) + + go func() { + frame, err := readTestJSONRPCFrame(stdinR) + if err != nil { + errCh <- err + return + } + + var request struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params map[string]any `json:"params"` + } + if err := json.Unmarshal(frame, &request); err != nil { + errCh <- err + return + } + if request.Method != "session.mcp.oauth.handlePendingRequest" { + errCh <- fmt.Errorf("expected session.mcp.oauth.handlePendingRequest, got %s", request.Method) + return + } + + paramsCh <- request.Params + + response := map[string]any{ + "jsonrpc": "2.0", + "id": json.RawMessage(request.ID), + "result": map[string]any{"success": true}, + } + data, err := json.Marshal(response) + if err != nil { + errCh <- err + return + } + if _, err := fmt.Fprintf(stdoutW, "Content-Length: %d\r\n\r\n%s", len(data), data); err != nil { + errCh <- err + } + }() + + session := &Session{ + SessionID: "session-1", + client: client, + RPC: rpc.NewSessionRPC(client, "session-1"), + } + var observedRequest MCPAuthRequest + session.registerMCPAuthHandler(func(request MCPAuthRequest, invocation MCPAuthInvocation) (*MCPAuthResult, error) { + observedRequest = request + if invocation.SessionID != "session-1" { + t.Fatalf("expected invocation session-1, got %s", invocation.SessionID) + } + if request.RequestID != "oauth-request" { + t.Fatalf("expected oauth-request, got %s", request.RequestID) + } + tokenType := "Bearer" + return MCPAuthResultToken(&MCPAuthToken{ + AccessToken: "host-token", + TokenType: &tokenType, + }), nil + }) + resourceMetadataURL := "https://example.com/.well-known/oauth-protected-resource" + resourceMetadata := `{"resource":"https://example.com/mcp"}` + clientSecret := "static-secret" + grantType := rpc.MCPOauthRequiredStaticClientConfigGrantTypeClientCredentials + publicClient := false + session.handleBroadcastEvent(SessionEvent{ + Data: &MCPOauthRequiredData{ + RequestID: "oauth-request", + Reason: rpc.MCPOauthRequestReasonInitial, + ServerName: "oauth-server", + ServerURL: "https://example.com/mcp", + ResourceMetadata: &resourceMetadata, + StaticClientConfig: &MCPOauthRequiredStaticClientConfig{ + ClientID: "static-client", + ClientSecret: &clientSecret, + GrantType: &grantType, + PublicClient: &publicClient, + }, + WwwAuthenticateParams: &MCPOauthWwwAuthenticateParams{ + ResourceMetadataURL: &resourceMetadataURL, + }, + }, + }) + if observedRequest.ResourceMetadata == nil || *observedRequest.ResourceMetadata != `{"resource":"https://example.com/mcp"}` { + t.Fatalf("expected resource metadata to be propagated, got %#v", observedRequest.ResourceMetadata) + } + if observedRequest.Reason != MCPOauthRequestReasonInitial { + t.Fatalf("expected initial reason, got %q", observedRequest.Reason) + } + if observedRequest.WwwAuthenticateParams == nil { + t.Fatal("expected WWW-Authenticate params to be propagated") + } + if observedRequest.StaticClientConfig == nil { + t.Fatal("expected static client config to be propagated") + } + if observedRequest.StaticClientConfig.ClientSecret == nil || *observedRequest.StaticClientConfig.ClientSecret != "static-secret" { + t.Fatalf("expected static client secret to be propagated, got %#v", observedRequest.StaticClientConfig.ClientSecret) + } + if observedRequest.StaticClientConfig.GrantType == nil || *observedRequest.StaticClientConfig.GrantType != "client_credentials" { + t.Fatalf("expected static client grant type to be propagated, got %#v", observedRequest.StaticClientConfig.GrantType) + } + + select { + case params := <-paramsCh: + if params["sessionId"] != "session-1" { + t.Fatalf("expected sessionId session-1, got %v", params["sessionId"]) + } + if params["requestId"] != "oauth-request" { + t.Fatalf("expected requestId oauth-request, got %v", params["requestId"]) + } + result, ok := params["result"].(map[string]any) + if !ok { + t.Fatalf("expected result object, got %T", params["result"]) + } + if result["kind"] != "token" { + t.Fatalf("expected token kind, got %v", result["kind"]) + } + if result["accessToken"] != "host-token" { + t.Fatalf("expected accessToken host-token, got %v", result["accessToken"]) + } + if result["tokenType"] != "Bearer" { + t.Fatalf("expected tokenType Bearer, got %v", result["tokenType"]) + } + case err := <-errCh: + t.Fatal(err) + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for MCP OAuth request") + } +} + +func TestMCPAuthRequestAllowsMissingOptionalMetadata(t *testing.T) { + request := MCPAuthRequest{RequestID: "oauth-request"} + if request.ResourceMetadata != nil { + t.Fatalf("expected no resource metadata, got %#v", request.ResourceMetadata) + } + if request.WwwAuthenticateParams != nil { + t.Fatalf("expected no WWW-Authenticate params, got %#v", request.WwwAuthenticateParams) + } +} + +func TestMCPOauthRequiredDataAllowsOptionalMetadata(t *testing.T) { + var withMetadata rpc.MCPOauthRequiredData + if err := json.Unmarshal([]byte(`{ + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp", + "wwwAuthenticateParams": { + "resourceMetadataUrl": "https://example.com/.well-known/oauth-protected-resource" + }, + "resourceMetadata": "{\"resource\":\"https://example.com/mcp\"}", + "staticClientConfig": { + "clientId": "static-client", + "clientSecret": "static-secret", + "publicClient": false + } + }`), &withMetadata); err != nil { + t.Fatal(err) + } + if withMetadata.ResourceMetadata == nil || *withMetadata.ResourceMetadata != `{"resource":"https://example.com/mcp"}` { + t.Fatalf("expected resource metadata, got %#v", withMetadata.ResourceMetadata) + } + if withMetadata.WwwAuthenticateParams == nil { + t.Fatal("expected WWW-Authenticate params") + } + if withMetadata.StaticClientConfig == nil || withMetadata.StaticClientConfig.ClientSecret == nil || *withMetadata.StaticClientConfig.ClientSecret != "static-secret" { + t.Fatalf("expected static client secret, got %#v", withMetadata.StaticClientConfig) + } + + var withoutMetadata rpc.MCPOauthRequiredData + if err := json.Unmarshal([]byte(`{ + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp" + }`), &withoutMetadata); err != nil { + t.Fatal(err) + } + if withoutMetadata.ResourceMetadata != nil { + t.Fatalf("expected no resource metadata, got %#v", withoutMetadata.ResourceMetadata) + } + if withoutMetadata.WwwAuthenticateParams != nil { + t.Fatalf("expected no WWW-Authenticate params, got %#v", withoutMetadata.WwwAuthenticateParams) + } +} + func captureSetModelRequest(t *testing.T, opts *SetModelOptions) map[string]any { t.Helper() @@ -594,6 +793,7 @@ func TestSession_Capabilities(t *testing.T) { CanvasID: "counter", InstanceID: "counter-1", Title: ptr("Counter"), + Icon: ptr("beaker"), Status: ptr("ready"), URL: ptr("https://example.test/counter"), Input: map[string]any{"seed": float64(1)}, @@ -623,6 +823,7 @@ func TestSession_Capabilities(t *testing.T) { CanvasID: "counter", InstanceID: "counter-1", Title: ptr("Counter Updated"), + Icon: ptr("beaker-filled"), Status: ptr("reconnected"), URL: ptr("https://example.test/counter-updated"), Input: map[string]any{"seed": float64(2)}, @@ -639,6 +840,9 @@ func TestSession_Capabilities(t *testing.T) { if open[0].Title == nil || *open[0].Title != "Counter Updated" { t.Fatalf("expected updated title, got %+v", open[0].Title) } + if open[0].Icon == nil || *open[0].Icon != "beaker-filled" { + t.Fatalf("expected updated icon, got %+v", open[0].Icon) + } if open[0].Status == nil || *open[0].Status != "reconnected" { t.Fatalf("expected updated status, got %+v", open[0].Status) } diff --git a/go/types.go b/go/types.go index 8a7df3c46a..6760f25e07 100644 --- a/go/types.go +++ b/go/types.go @@ -20,14 +20,23 @@ const ( // RuntimeConnection describes how a [Client] connects to the Copilot runtime. // -// Construct one with a [StdioConnection], [TCPConnection], or [URIConnection] -// literal and pass it via [ClientOptions.Connection]. When [ClientOptions.Connection] -// is nil, the default is an empty [StdioConnection] (the SDK spawns the bundled -// runtime and communicates over stdin/stdout). +// Construct one with a [StdioConnection], [TCPConnection], [URIConnection], or +// [InProcessConnection] literal and pass it via [ClientOptions.Connection]. When +// [ClientOptions.Connection] is nil, COPILOT_SDK_DEFAULT_CONNECTION may select +// "inprocess" or "stdio"; when unset, the default is an empty [StdioConnection]. type RuntimeConnection interface { runtimeConnection() } +// childProcessConnection is implemented by the connection types that spawn a +// runtime child process ([StdioConnection] and [TCPConnection]). It exposes the +// per-connection environment so the client can resolve and validate it uniformly +// regardless of the specific child-process transport. +type childProcessConnection interface { + RuntimeConnection + connEnv() []string +} + // StdioConnection spawns a runtime child process and communicates over its // stdin/stdout pipes. This is the default when no connection is configured. type StdioConnection struct { @@ -35,10 +44,17 @@ type StdioConnection struct { Path string // Args are extra command-line arguments inserted before SDK-managed args. Args []string + // Env are the environment variables for the runtime process, each of the + // form "KEY=VALUE". When set, these take precedence over + // [ClientOptions.Env]; setting both is rejected. When nil, the client-level + // env (or the current process environment) is used. + Env []string } func (StdioConnection) runtimeConnection() {} +func (c StdioConnection) connEnv() []string { return c.Env } + // TCPConnection spawns a runtime child process that listens on a TCP socket // and connects to it. type TCPConnection struct { @@ -54,10 +70,17 @@ type TCPConnection struct { Path string // Args are extra command-line arguments inserted before SDK-managed args. Args []string + // Env are the environment variables for the runtime process, each of the + // form "KEY=VALUE". When set, these take precedence over + // [ClientOptions.Env]; setting both is rejected. When nil, the client-level + // env (or the current process environment) is used. + Env []string } func (TCPConnection) runtimeConnection() {} +func (c TCPConnection) connEnv() []string { return c.Env } + // URIConnection connects to an already-running runtime at the given URL. // The SDK does not spawn a process in this mode. type URIConnection struct { @@ -71,11 +94,29 @@ type URIConnection struct { func (URIConnection) runtimeConnection() {} +// InProcessConnection hosts the Copilot runtime in-process by loading its native +// runtime library (a Rust cdylib) and driving JSON-RPC over the library's C ABI, +// instead of spawning a runtime child process. +// +// Because the runtime is loaded into the calling process, per-client +// environment, working directory, and telemetry cannot be represented and are +// rejected by [NewClient] (see [ClientOptions]). Set those via the host process +// environment instead, or use a child-process transport ([StdioConnection] / +// [TCPConnection]). +// +// Experimental: the in-process transport is experimental and its API and +// behavior may change in a future release. Build the application with the +// copilot_inprocess build tag to enable this transport. +type InProcessConnection struct { +} + +func (InProcessConnection) runtimeConnection() {} + // ClientOptions configures the [Client]. type ClientOptions struct { // Connection describes how to connect to the Copilot runtime. When nil, - // defaults to an empty [StdioConnection] (spawn the bundled runtime over - // stdio). + // COPILOT_SDK_DEFAULT_CONNECTION may select "inprocess" or "stdio"; + // when unset, defaults to an empty [StdioConnection]. Connection RuntimeConnection // WorkingDirectory is the working directory for the runtime process. // If empty, inherits the current process's working directory. @@ -95,6 +136,12 @@ type ClientOptions struct { // Env are the environment variables for the runtime process (default: // inherits from current process). Each entry is of the form "KEY=VALUE". // If Env contains duplicate keys, only the last value for each key is used. + // + // For child-process transports ([StdioConnection] / [TCPConnection]) the + // per-connection Env, when set, takes precedence over this field; setting + // both is rejected. Env is not supported with [InProcessConnection] (the + // runtime shares this process's single environment block) and is rejected + // by [NewClient]. Env []string // GitHubToken is the GitHub token to use for authentication. // When provided, the token is passed to the runtime via environment @@ -122,6 +169,11 @@ type ClientOptions struct { // this handler instead of issuing the calls itself. Works for both CAPI // and BYOK sessions. RequestHandler *CopilotRequestHandler + // OnGitHubTelemetry registers a connection-level callback (experimental) + // that receives GitHub telemetry events the runtime forwards for sessions + // opened by this client. When non-nil, every session created or resumed by + // this client opts into telemetry forwarding (enableGitHubTelemetryForwarding). + OnGitHubTelemetry func(notification *rpc.GitHubTelemetryNotification) // Telemetry configures OpenTelemetry integration for the runtime. // When non-nil, COPILOT_OTEL_ENABLED=true is set and any populated // fields are mapped to the corresponding environment variables. @@ -326,6 +378,70 @@ type PermissionInvocation struct { SessionID string } +// MCPAuthWwwAuthenticateParams contains parsed parameters from an MCP server's WWW-Authenticate response. +type MCPAuthWwwAuthenticateParams struct { + ResourceMetadataURL *string `json:"resourceMetadataUrl,omitempty"` + Scope *string `json:"scope,omitempty"` + Error *string `json:"error,omitempty"` +} + +// MCPAuthStaticClientConfig is static OAuth client configuration supplied by an MCP server. +type MCPAuthStaticClientConfig struct { + ClientID string `json:"clientId"` + ClientSecret *string `json:"clientSecret,omitempty"` + GrantType *string `json:"grantType,omitempty"` + PublicClient *bool `json:"publicClient,omitempty"` +} + +// MCPAuthRequest describes an MCP OAuth request that the SDK host can satisfy with a token. +type MCPAuthRequest struct { + RequestID string `json:"requestId"` + ServerName string `json:"serverName"` + ServerURL string `json:"serverUrl"` + Reason MCPOauthRequestReason `json:"reason"` + WwwAuthenticateParams *MCPAuthWwwAuthenticateParams `json:"wwwAuthenticateParams,omitempty"` + ResourceMetadata *string `json:"resourceMetadata,omitempty"` + StaticClientConfig *MCPAuthStaticClientConfig `json:"staticClientConfig,omitempty"` +} + +// MCPAuthToken is host-provided OAuth token data for a pending MCP OAuth request. +type MCPAuthToken struct { + AccessToken string `json:"accessToken"` + TokenType *string `json:"tokenType,omitempty"` + ExpiresIn *int64 `json:"expiresIn,omitempty"` +} + +// MCPAuthResult is the result returned by an MCP auth request handler. +type MCPAuthResult struct { + Kind string + Token *MCPAuthToken +} + +const ( + // MCPAuthResultKindToken indicates that the host provided token data. + MCPAuthResultKindToken = "token" + // MCPAuthResultKindCancelled indicates that the host declined the request. + MCPAuthResultKindCancelled = "cancelled" +) + +// MCPAuthResultToken returns a token result for an MCP OAuth request. +func MCPAuthResultToken(token *MCPAuthToken) *MCPAuthResult { + return &MCPAuthResult{Kind: MCPAuthResultKindToken, Token: token} +} + +// MCPAuthResultCancelled returns a cancelled result for an MCP OAuth request. +func MCPAuthResultCancelled() *MCPAuthResult { + return &MCPAuthResult{Kind: MCPAuthResultKindCancelled} +} + +// MCPAuthInvocation provides context about an MCP auth handler invocation. +type MCPAuthInvocation struct { + SessionID string +} + +// MCPAuthHandler handles MCP OAuth requests from the runtime. +type MCPAuthHandler func(request MCPAuthRequest, invocation MCPAuthInvocation) (*MCPAuthResult, error) + // UserInputRequest represents a request for user input from the agent type UserInputRequest struct { Question string @@ -833,6 +949,10 @@ type CustomAgentConfig struct { // When set, the runtime will attempt to use this model for the agent, // falling back to the parent session model if unavailable. Model string `json:"model,omitempty"` + // ReasoningEffort is the reasoning effort level for this agent's model. + // When empty, no per-agent override is sent and the backend chooses its + // default. The parent session effort is not inherited. + ReasoningEffort string `json:"reasoningEffort,omitempty"` } // DefaultAgentConfig configures the default agent (the built-in agent that handles turns when no custom agent is selected). @@ -879,6 +999,18 @@ type LargeToolOutputConfig struct { OutputDirectory string `json:"outputDir,omitempty"` } +// ToolSearchConfig allows to configure tool search behavior. +// Tool search defers tools to keep the model's active tool set small. +// To override the tool-search tool's implementation, register a +// [Tool] named "tool_search_tool" with OverridesBuiltInTool set to true. +type ToolSearchConfig struct { + // Controls whether tool search is enabled. + Enabled *bool `json:"enabled,omitempty"` + // DeferThreshold is the tool count above which MCP and external tools are + // deferred behind tool search. When nil, the runtime default (30) applies. + DeferThreshold *int `json:"deferThreshold,omitempty"` +} + // SessionFSCapabilities declares optional provider capabilities. type SessionFSCapabilities struct { // Sqlite indicates whether the provider supports SQLite query/exists operations. @@ -971,10 +1103,19 @@ type SessionConfig struct { // ExcludedTools is a list of tool names to disable. All other tools remain available. // Ignored if AvailableTools is specified. ExcludedTools []string + // ExcludedBuiltInAgents is a list of built-in agent names to exclude from + // the session. Excluded built-in agents are hidden from discovery and cannot + // be selected or invoked unless a custom agent with the same name is + // configured. + ExcludedBuiltInAgents []string // OnPermissionRequest is an optional handler for permission requests from the server. // When nil, permission requests are surfaced as events and left pending for the // consumer to resolve via pending permission RPCs. OnPermissionRequest PermissionHandlerFunc + // OnMCPAuthRequest is an optional handler for MCP OAuth requests from MCP servers. + // When provided, the SDK can satisfy MCP server OAuth requests with host-provided + // token data or cancellation. + OnMCPAuthRequest MCPAuthHandler // OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool) OnUserInputRequest UserInputHandler // Hooks configures hook handlers for session lifecycle events @@ -1017,6 +1158,16 @@ type SessionConfig struct { // regardless of this setting. This is independent of the OpenTelemetry // configuration in ClientOptions.Telemetry. EnableSessionTelemetry *bool + // EnableCitations enables native model citations for supported providers. + // + // Experimental: EnableCitations is part of an experimental model capability + // surface and may change or be removed in future SDK or CLI releases. + EnableCitations *bool + // SessionLimits applies limits to this session's current accounting window. + // + // Experimental: SessionLimits is part of an experimental runtime accounting + // surface and may change or be removed in future SDK or CLI releases. + SessionLimits *rpc.SessionLimitsConfig // SkipCustomInstructions, when non-nil, controls whether the runtime loads // custom instruction files. See also [ClientOptions.Mode] = [ModeEmpty]. SkipCustomInstructions *bool @@ -1065,6 +1216,10 @@ type SessionConfig struct { // output exceeding the configured size, the output is written to a temp file // and a reference is returned to the model instead of the full payload. LargeOutput *LargeToolOutputConfig + // ToolSearch overrides the runtime's built-in tool-search behavior, which + // defers rarely used tools behind a searchable index. When nil, the runtime + // default applies. + ToolSearch *ToolSearchConfig // Memory configures the memory feature for the session. When omitted, the // runtime default applies. Memory *MemoryConfiguration @@ -1147,6 +1302,9 @@ type SessionConfig struct { CanvasHandler CanvasHandler `json:"-"` // ExtensionInfo identifies the stable extension providing this session's canvases. ExtensionInfo *ExtensionInfo + // CanvasProvider is the stable identity for a host/SDK connection that + // supplies built-in canvases, so they survive reconnect and CLI restart. + CanvasProvider *CanvasProviderIdentity // ExpAssignments injects ExP assignment ("flight") data for this session, // in the same JSON shape the Copilot CLI fetches from the experimentation // service (CopilotExpAssignmentResponse). When supplied, the runtime feeds @@ -1159,6 +1317,12 @@ type SessionConfig struct { // intended for trusted out-of-process integrators, and is not intended for // general external use. ExpAssignments any + // EnableManagedSettings, when set to true, opts the runtime into + // self-fetching enterprise managed settings (bypass-permissions policy) at + // session bootstrap using the session's GitHubToken. Requires GitHubToken to + // be set; if omitted, the runtime is expected to reject session creation + // (fail-closed). Unset behaves exactly as before. + EnableManagedSettings *bool } // ToolDefer controls whether a tool may be deferred (loaded lazily via tool @@ -1181,6 +1345,11 @@ type Tool struct { // Defer controls whether the tool may be deferred (loaded lazily via tool // search) rather than always pre-loaded. When empty, the runtime decides. Defer ToolDefer `json:"defer,omitempty"` + // Metadata is opaque, host-defined metadata associated with the tool + // definition. Keys are namespaced and not part of the stable public API; + // values are not interpreted and may be recognized to inform host-specific + // behavior. Unknown keys are preserved and round-tripped untouched. + Metadata map[string]any `json:"metadata,omitempty"` // Handler is optional. When nil, the SDK exposes the tool declaration but does // not automatically invoke it. Handler ToolHandler `json:"-"` @@ -1193,6 +1362,14 @@ type ToolInvocation struct { ToolName string Arguments any + // AvailableTools is a snapshot of the session's currently initialized + // tools. The SDK populates it only when this invocation targets the + // built-in tool-search tool ("tool_search_tool"), so a tool-search + // override can rank/filter the live catalog -- including MCP tools + // configured in settings -- without issuing its own RPC. It is nil for + // every other tool invocation. + AvailableTools []rpc.CurrentToolMetadata + // TraceContext carries the W3C Trace Context propagated from the CLI's // execute_tool span. Pass this to OpenTelemetry-aware code so that // child spans created inside the handler are parented to the CLI span. @@ -1212,6 +1389,8 @@ type ToolResult struct { Error string `json:"error,omitempty"` SessionLog string `json:"sessionLog,omitempty"` ToolTelemetry map[string]any `json:"toolTelemetry,omitempty"` + // ToolReferences lists names of tools returned by a tool-search tool. + ToolReferences []string `json:"toolReferences,omitempty"` } // CommandContext provides context about a slash-command invocation. @@ -1353,6 +1532,11 @@ type ResumeSessionConfig struct { // ExcludedTools is a list of tool names to disable. All other tools remain available. // Ignored if AvailableTools is specified. ExcludedTools []string + // ExcludedBuiltInAgents is a list of built-in agent names to exclude from + // the session. Excluded built-in agents are hidden from discovery and cannot + // be selected or invoked unless a custom agent with the same name is + // configured. + ExcludedBuiltInAgents []string // Provider configures a custom model provider Provider *ProviderConfig // Capi configures provider-scoped CAPI (Copilot API) session options. @@ -1376,6 +1560,16 @@ type ResumeSessionConfig struct { // regardless of this setting. This is independent of the OpenTelemetry // configuration in ClientOptions.Telemetry. EnableSessionTelemetry *bool + // EnableCitations enables native model citations for supported providers. + // + // Experimental: EnableCitations is part of an experimental model capability + // surface and may change or be removed in future SDK or CLI releases. + EnableCitations *bool + // SessionLimits applies limits to this session's current accounting window. + // + // Experimental: SessionLimits is part of an experimental runtime accounting + // surface and may change or be removed in future SDK or CLI releases. + SessionLimits *rpc.SessionLimitsConfig // SkipCustomInstructions, when non-nil, controls whether the runtime loads // custom instruction files. See also [ClientOptions.Mode] = [ModeEmpty]. SkipCustomInstructions *bool @@ -1405,6 +1599,9 @@ type ResumeSessionConfig struct { // When nil, permission requests are surfaced as events and left pending for the // consumer to resolve via pending permission RPCs. OnPermissionRequest PermissionHandlerFunc + // OnMCPAuthRequest is an optional handler for MCP OAuth requests from MCP servers. + // See SessionConfig.OnMCPAuthRequest. + OnMCPAuthRequest MCPAuthHandler // OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool) OnUserInputRequest UserInputHandler // Hooks configures hook handlers for session lifecycle events @@ -1490,6 +1687,10 @@ type ResumeSessionConfig struct { // output exceeding the configured size, the output is written to a temp file // and a reference is returned to the model instead of the full payload. LargeOutput *LargeToolOutputConfig + // ToolSearch overrides the runtime's built-in tool-search behavior, which + // defers rarely used tools behind a searchable index. When nil, the runtime + // default applies. + ToolSearch *ToolSearchConfig // Memory configures the memory feature for the session. When omitted, the // runtime default applies. Memory *MemoryConfiguration @@ -1554,6 +1755,9 @@ type ResumeSessionConfig struct { CanvasHandler CanvasHandler `json:"-"` // ExtensionInfo identifies the stable extension providing this session's canvases. ExtensionInfo *ExtensionInfo + // CanvasProvider is the stable identity for a host/SDK connection that + // supplies built-in canvases. See SessionConfig.CanvasProvider. + CanvasProvider *CanvasProviderIdentity // ExpAssignments injects ExP assignment ("flight") data on resume. See // SessionConfig.ExpAssignments. Re-supply on resume so the runtime // re-applies the assignments after a CLI process restart. @@ -1562,6 +1766,10 @@ type ResumeSessionConfig struct { // intended for trusted out-of-process integrators, and is not intended for // general external use. ExpAssignments any + // EnableManagedSettings injects the same opt-in flag on resume. See + // SessionConfig.EnableManagedSettings. Re-supply on resume so the runtime + // re-applies the managed-settings self-fetch after a CLI process restart. + EnableManagedSettings *bool } // ProviderTokenArgs carries the context passed to a [BearerTokenProvider] callback @@ -1959,11 +2167,14 @@ type createSessionRequest struct { AvailableTools []string `json:"availableTools"` ExcludedTools []string `json:"excludedTools,omitempty"` ToolFilterPrecedence *rpc.OptionsUpdateToolFilterPrecedence `json:"toolFilterPrecedence,omitempty"` + ExcludedBuiltInAgents []string `json:"excludedBuiltinAgents,omitempty"` Provider *ProviderConfig `json:"provider,omitempty"` Capi *CapiSessionOptions `json:"capi,omitempty"` Providers []NamedProviderConfig `json:"providers,omitempty"` Models []ProviderModelConfig `json:"models,omitempty"` EnableSessionTelemetry *bool `json:"enableSessionTelemetry,omitempty"` + EnableCitations *bool `json:"enableCitations,omitempty"` + SessionLimits *rpc.SessionLimitsConfig `json:"sessionLimits,omitempty"` SkipCustomInstructions *bool `json:"skipCustomInstructions,omitempty"` CustomAgentsLocalOnly *bool `json:"customAgentsLocalOnly,omitempty"` CoauthorEnabled *bool `json:"coauthorEnabled,omitempty"` @@ -1977,6 +2188,7 @@ type createSessionRequest struct { WorkingDirectory string `json:"workingDirectory,omitempty"` Streaming *bool `json:"streaming,omitempty"` IncludeSubAgentStreamingEvents *bool `json:"includeSubAgentStreamingEvents,omitempty"` + EnableGitHubTelemetryForwarding *bool `json:"enableGitHubTelemetryForwarding,omitempty"` MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"` MCPOAuthTokenStorage string `json:"mcpOAuthTokenStorage,omitempty"` EnvValueMode string `json:"envValueMode,omitempty"` @@ -1999,6 +2211,7 @@ type createSessionRequest struct { DisabledSkills []string `json:"disabledSkills,omitempty"` InfiniteSessions *InfiniteSessionConfig `json:"infiniteSessions,omitempty"` LargeOutput *LargeToolOutputConfig `json:"largeOutput,omitempty"` + ToolSearch *ToolSearchConfig `json:"toolSearch,omitempty"` Memory *MemoryConfiguration `json:"memory,omitempty"` Commands []wireCommand `json:"commands,omitempty"` RequestElicitation *bool `json:"requestElicitation,omitempty"` @@ -2011,7 +2224,9 @@ type createSessionRequest struct { RequestExtensions *bool `json:"requestExtensions,omitempty"` ExtensionSDKPath *string `json:"extensionSdkPath,omitempty"` ExtensionInfo *ExtensionInfo `json:"extensionInfo,omitempty"` + CanvasProvider *CanvasProviderIdentity `json:"canvasProvider,omitempty"` ExpAssignments any `json:"expAssignments,omitempty"` + EnableManagedSettings *bool `json:"enableManagedSettings,omitempty"` Traceparent string `json:"traceparent,omitempty"` Tracestate string `json:"tracestate,omitempty"` } @@ -2042,11 +2257,14 @@ type resumeSessionRequest struct { AvailableTools []string `json:"availableTools"` ExcludedTools []string `json:"excludedTools,omitempty"` ToolFilterPrecedence *rpc.OptionsUpdateToolFilterPrecedence `json:"toolFilterPrecedence,omitempty"` + ExcludedBuiltInAgents []string `json:"excludedBuiltinAgents,omitempty"` Provider *ProviderConfig `json:"provider,omitempty"` Capi *CapiSessionOptions `json:"capi,omitempty"` Providers []NamedProviderConfig `json:"providers,omitempty"` Models []ProviderModelConfig `json:"models,omitempty"` EnableSessionTelemetry *bool `json:"enableSessionTelemetry,omitempty"` + EnableCitations *bool `json:"enableCitations,omitempty"` + SessionLimits *rpc.SessionLimitsConfig `json:"sessionLimits,omitempty"` SkipCustomInstructions *bool `json:"skipCustomInstructions,omitempty"` CustomAgentsLocalOnly *bool `json:"customAgentsLocalOnly,omitempty"` CoauthorEnabled *bool `json:"coauthorEnabled,omitempty"` @@ -2072,6 +2290,7 @@ type resumeSessionRequest struct { ContinuePendingWork *bool `json:"continuePendingWork,omitempty"` Streaming *bool `json:"streaming,omitempty"` IncludeSubAgentStreamingEvents *bool `json:"includeSubAgentStreamingEvents,omitempty"` + EnableGitHubTelemetryForwarding *bool `json:"enableGitHubTelemetryForwarding,omitempty"` MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"` MCPOAuthTokenStorage string `json:"mcpOAuthTokenStorage,omitempty"` EnvValueMode string `json:"envValueMode,omitempty"` @@ -2084,6 +2303,7 @@ type resumeSessionRequest struct { DisabledSkills []string `json:"disabledSkills,omitempty"` InfiniteSessions *InfiniteSessionConfig `json:"infiniteSessions,omitempty"` LargeOutput *LargeToolOutputConfig `json:"largeOutput,omitempty"` + ToolSearch *ToolSearchConfig `json:"toolSearch,omitempty"` Memory *MemoryConfiguration `json:"memory,omitempty"` Commands []wireCommand `json:"commands,omitempty"` RequestElicitation *bool `json:"requestElicitation,omitempty"` @@ -2096,7 +2316,9 @@ type resumeSessionRequest struct { RequestExtensions *bool `json:"requestExtensions,omitempty"` ExtensionSDKPath *string `json:"extensionSdkPath,omitempty"` ExtensionInfo *ExtensionInfo `json:"extensionInfo,omitempty"` + CanvasProvider *CanvasProviderIdentity `json:"canvasProvider,omitempty"` ExpAssignments any `json:"expAssignments,omitempty"` + EnableManagedSettings *bool `json:"enableManagedSettings,omitempty"` Traceparent string `json:"traceparent,omitempty"` Tracestate string `json:"tracestate,omitempty"` } diff --git a/go/types_test.go b/go/types_test.go index f4132fa3d6..a76ebaad40 100644 --- a/go/types_test.go +++ b/go/types_test.go @@ -152,6 +152,28 @@ func TestCustomAgentConfig_JSONIncludesModel(t *testing.T) { } } +func TestCustomAgentConfig_JSONIncludesReasoningEffort(t *testing.T) { + cfg := CustomAgentConfig{ + Name: "reasoning-agent", + Prompt: "Think carefully.", + ReasoningEffort: "high", + } + + data, err := json.Marshal(cfg) + if err != nil { + t.Fatalf("failed to marshal CustomAgentConfig: %v", err) + } + + var decoded map[string]any + if err := json.Unmarshal(data, &decoded); err != nil { + t.Fatalf("failed to unmarshal CustomAgentConfig: %v", err) + } + + if decoded["reasoningEffort"] != "high" { + t.Errorf("expected reasoningEffort 'high', got %v", decoded["reasoningEffort"]) + } +} + func TestCustomAgentConfig_JSONIncludesEmptyTools(t *testing.T) { cfg := CustomAgentConfig{ Name: "no-tools-agent", @@ -203,6 +225,57 @@ func TestCustomAgentConfig_JSONOmitsNilTools(t *testing.T) { } } +func TestToolResult_JSONIncludesToolReferences(t *testing.T) { + result := ToolResult{ + TextResultForLLM: "found 2 tools", + ResultType: "success", + ToolReferences: []string{"get_weather", "check_status"}, + } + + data, err := json.Marshal(result) + if err != nil { + t.Fatalf("failed to marshal ToolResult: %v", err) + } + + var decoded map[string]any + if err := json.Unmarshal(data, &decoded); err != nil { + t.Fatalf("failed to unmarshal ToolResult: %v", err) + } + + rawRefs, present := decoded["toolReferences"] + if !present { + t.Fatal("expected toolReferences to be present") + } + refs, ok := rawRefs.([]any) + if !ok { + t.Fatalf("expected toolReferences array, got %T", rawRefs) + } + if len(refs) != 2 || refs[0] != "get_weather" || refs[1] != "check_status" { + t.Errorf("unexpected toolReferences: %v", refs) + } +} + +func TestToolResult_JSONOmitsNilToolReferences(t *testing.T) { + result := ToolResult{ + TextResultForLLM: "ok", + ResultType: "success", + } + + data, err := json.Marshal(result) + if err != nil { + t.Fatalf("failed to marshal ToolResult: %v", err) + } + + var decoded map[string]any + if err := json.Unmarshal(data, &decoded); err != nil { + t.Fatalf("failed to unmarshal ToolResult: %v", err) + } + + if _, present := decoded["toolReferences"]; present { + t.Errorf("expected toolReferences to be omitted for nil slice, got %v", decoded["toolReferences"]) + } +} + func TestCustomAgentConfig_JSONOmitsModelWhenEmpty(t *testing.T) { cfg := CustomAgentConfig{ Name: "no-model-agent", @@ -222,6 +295,9 @@ func TestCustomAgentConfig_JSONOmitsModelWhenEmpty(t *testing.T) { if _, present := decoded["model"]; present { t.Errorf("expected model to be omitted when empty, got %v", decoded["model"]) } + if _, present := decoded["reasoningEffort"]; present { + t.Errorf("expected reasoningEffort to be omitted when empty, got %v", decoded["reasoningEffort"]) + } } func TestTool_JSONIncludesEmptyParameters(t *testing.T) { diff --git a/go/zsession_events.go b/go/zsession_events.go index 75a22cc997..b3dd66ef77 100644 --- a/go/zsession_events.go +++ b/go/zsession_events.go @@ -9,6 +9,7 @@ import "github.com/github/copilot-sdk/go/rpc" type ( AbortData = rpc.AbortData AbortReason = rpc.AbortReason + AssistantIdleData = rpc.AssistantIdleData AssistantIntentData = rpc.AssistantIntentData AssistantMessageData = rpc.AssistantMessageData AssistantMessageDeltaData = rpc.AssistantMessageDeltaData @@ -18,7 +19,9 @@ type ( AssistantMessageToolRequestType = rpc.AssistantMessageToolRequestType AssistantReasoningData = rpc.AssistantReasoningData AssistantReasoningDeltaData = rpc.AssistantReasoningDeltaData + AssistantServerToolProgressData = rpc.AssistantServerToolProgressData AssistantStreamingDeltaData = rpc.AssistantStreamingDeltaData + AssistantToolCallDeltaData = rpc.AssistantToolCallDeltaData AssistantTurnEndData = rpc.AssistantTurnEndData AssistantTurnStartData = rpc.AssistantTurnStartData AssistantUsageAPIEndpoint = rpc.AssistantUsageAPIEndpoint @@ -31,13 +34,26 @@ type ( AttachmentExtensionContext = rpc.AttachmentExtensionContext AttachmentFile = rpc.AttachmentFile AttachmentFileLineRange = rpc.AttachmentFileLineRange + AttachmentGitHubActionsJob = rpc.AttachmentGitHubActionsJob + AttachmentGitHubCommit = rpc.AttachmentGitHubCommit + AttachmentGitHubFile = rpc.AttachmentGitHubFile + AttachmentGitHubFileDiff = rpc.AttachmentGitHubFileDiff + AttachmentGitHubFileDiffSide = rpc.AttachmentGitHubFileDiffSide AttachmentGitHubReference = rpc.AttachmentGitHubReference AttachmentGitHubReferenceType = rpc.AttachmentGitHubReferenceType + AttachmentGitHubRelease = rpc.AttachmentGitHubRelease + AttachmentGitHubRepository = rpc.AttachmentGitHubRepository + AttachmentGitHubSnippet = rpc.AttachmentGitHubSnippet + AttachmentGitHubTreeComparison = rpc.AttachmentGitHubTreeComparison + AttachmentGitHubTreeComparisonSide = rpc.AttachmentGitHubTreeComparisonSide + AttachmentGitHubURL = rpc.AttachmentGitHubURL AttachmentSelection = rpc.AttachmentSelection AttachmentSelectionDetails = rpc.AttachmentSelectionDetails AttachmentSelectionDetailsEnd = rpc.AttachmentSelectionDetailsEnd AttachmentSelectionDetailsStart = rpc.AttachmentSelectionDetailsStart AttachmentType = rpc.AttachmentType + AutoApprovalRecommendation = rpc.AutoApprovalRecommendation + AutoModeResolvedReasoningBucket = rpc.AutoModeResolvedReasoningBucket AutoModeSwitchCompletedData = rpc.AutoModeSwitchCompletedData AutoModeSwitchRequestedData = rpc.AutoModeSwitchRequestedData AutoModeSwitchResponse = rpc.AutoModeSwitchResponse @@ -86,26 +102,38 @@ type ( ExtensionsLoadedExtensionStatus = rpc.ExtensionsLoadedExtensionStatus ExternalToolCompletedData = rpc.ExternalToolCompletedData ExternalToolRequestedData = rpc.ExternalToolRequestedData + GitHubRepoRef = rpc.GitHubRepoRef HandoffRepository = rpc.HandoffRepository HandoffSourceType = rpc.HandoffSourceType + HeaderEntry = rpc.HeaderEntry HookEndData = rpc.HookEndData HookEndError = rpc.HookEndError HookProgressData = rpc.HookProgressData HookStartData = rpc.HookStartData + ManagedSettingsResolvedSource = rpc.ManagedSettingsResolvedSource MCPAppToolCallCompleteData = rpc.MCPAppToolCallCompleteData MCPAppToolCallCompleteError = rpc.MCPAppToolCallCompleteError MCPAppToolCallCompleteToolMeta = rpc.MCPAppToolCallCompleteToolMeta MCPAppToolCallCompleteToolMetaUI = rpc.MCPAppToolCallCompleteToolMetaUI + MCPHeadersRefreshCompletedData = rpc.MCPHeadersRefreshCompletedData + MCPHeadersRefreshCompletedOutcome = rpc.MCPHeadersRefreshCompletedOutcome + MCPHeadersRefreshRequiredData = rpc.MCPHeadersRefreshRequiredData + MCPHeadersRefreshRequiredReason = rpc.MCPHeadersRefreshRequiredReason MCPOauthCompletedData = rpc.MCPOauthCompletedData MCPOauthCompletionOutcome = rpc.MCPOauthCompletionOutcome + MCPOauthHTTPResponse = rpc.MCPOauthHTTPResponse + MCPOauthRequestReason = rpc.MCPOauthRequestReason MCPOauthRequiredData = rpc.MCPOauthRequiredData MCPOauthRequiredStaticClientConfig = rpc.MCPOauthRequiredStaticClientConfig MCPOauthRequiredStaticClientConfigGrantType = rpc.MCPOauthRequiredStaticClientConfigGrantType MCPOauthWwwAuthenticateParams = rpc.MCPOauthWwwAuthenticateParams + MCPPromptsListChangedData = rpc.MCPPromptsListChangedData + MCPResourcesListChangedData = rpc.MCPResourcesListChangedData MCPServersLoadedServer = rpc.MCPServersLoadedServer MCPServerSource = rpc.MCPServerSource MCPServerStatus = rpc.MCPServerStatus MCPServerTransport = rpc.MCPServerTransport + MCPToolsListChangedData = rpc.MCPToolsListChangedData ModelCallFailureBadRequestKind = rpc.ModelCallFailureBadRequestKind ModelCallFailureData = rpc.ModelCallFailureData ModelCallFailureRequestFingerprint = rpc.ModelCallFailureRequestFingerprint @@ -114,9 +142,11 @@ type ( OmittedBinaryResult = rpc.OmittedBinaryResult OmittedBinaryType = rpc.OmittedBinaryType PendingMessagesModifiedData = rpc.PendingMessagesModifiedData + PermissionAllowAllMode = rpc.PermissionAllowAllMode PermissionApproved = rpc.PermissionApproved PermissionApprovedForLocation = rpc.PermissionApprovedForLocation PermissionApprovedForSession = rpc.PermissionApprovedForSession + PermissionAutoApproval = rpc.PermissionAutoApproval PermissionCancelled = rpc.PermissionCancelled PermissionCompletedData = rpc.PermissionCompletedData PermissionDeniedByContentExclusionPolicy = rpc.PermissionDeniedByContentExclusionPolicy @@ -176,6 +206,7 @@ type ( ReasoningSummary = rpc.ReasoningSummary SamplingCompletedData = rpc.SamplingCompletedData SamplingRequestedData = rpc.SamplingRequestedData + SessionAutoModeResolvedData = rpc.SessionAutoModeResolvedData SessionAutopilotObjectiveChangedData = rpc.SessionAutopilotObjectiveChangedData SessionBackgroundTasksChangedData = rpc.SessionBackgroundTasksChangedData SessionBinaryAssetData = rpc.SessionBinaryAssetData @@ -199,6 +230,12 @@ type ( SessionHandoffData = rpc.SessionHandoffData SessionIdleData = rpc.SessionIdleData SessionInfoData = rpc.SessionInfoData + SessionLimitsConfig = rpc.SessionLimitsConfig + SessionLimitsExhaustedCompletedData = rpc.SessionLimitsExhaustedCompletedData + SessionLimitsExhaustedRequestedData = rpc.SessionLimitsExhaustedRequestedData + SessionLimitsExhaustedResponse = rpc.SessionLimitsExhaustedResponse + SessionLimitsExhaustedResponseAction = rpc.SessionLimitsExhaustedResponseAction + SessionManagedSettingsResolvedData = rpc.SessionManagedSettingsResolvedData SessionMCPServersLoadedData = rpc.SessionMCPServersLoadedData SessionMCPServerStatusChangedData = rpc.SessionMCPServerStatusChangedData SessionMode = rpc.SessionMode @@ -211,6 +248,7 @@ type ( SessionScheduleCancelledData = rpc.SessionScheduleCancelledData SessionScheduleCreatedData = rpc.SessionScheduleCreatedData SessionScheduleRearmedData = rpc.SessionScheduleRearmedData + SessionSessionLimitsChangedData = rpc.SessionSessionLimitsChangedData SessionShutdownData = rpc.SessionShutdownData SessionSkillsLoadedData = rpc.SessionSkillsLoadedData SessionSnapshotRewindData = rpc.SessionSnapshotRewindData @@ -220,6 +258,7 @@ type ( SessionTodosChangedData = rpc.SessionTodosChangedData SessionToolsUpdatedData = rpc.SessionToolsUpdatedData SessionTruncationData = rpc.SessionTruncationData + SessionUsageCheckpointData = rpc.SessionUsageCheckpointData SessionUsageInfoData = rpc.SessionUsageInfoData SessionWarningData = rpc.SessionWarningData SessionWorkspaceFileChangedData = rpc.SessionWorkspaceFileChangedData @@ -260,6 +299,7 @@ type ( ToolExecutionCompleteContentResourceLink = rpc.ToolExecutionCompleteContentResourceLink ToolExecutionCompleteContentResourceLinkIcon = rpc.ToolExecutionCompleteContentResourceLinkIcon ToolExecutionCompleteContentResourceLinkIconTheme = rpc.ToolExecutionCompleteContentResourceLinkIconTheme + ToolExecutionCompleteContentShellExit = rpc.ToolExecutionCompleteContentShellExit ToolExecutionCompleteContentTerminal = rpc.ToolExecutionCompleteContentTerminal ToolExecutionCompleteContentText = rpc.ToolExecutionCompleteContentText ToolExecutionCompleteContentType = rpc.ToolExecutionCompleteContentType @@ -282,6 +322,7 @@ type ( ToolExecutionPartialResultData = rpc.ToolExecutionPartialResultData ToolExecutionProgressData = rpc.ToolExecutionProgressData ToolExecutionStartData = rpc.ToolExecutionStartData + ToolExecutionStartShellToolInfo = rpc.ToolExecutionStartShellToolInfo ToolExecutionStartToolDescription = rpc.ToolExecutionStartToolDescription ToolExecutionStartToolDescriptionMeta = rpc.ToolExecutionStartToolDescriptionMeta ToolExecutionStartToolDescriptionMetaUI = rpc.ToolExecutionStartToolDescriptionMetaUI @@ -291,6 +332,7 @@ type ( UserInputRequestedData = rpc.UserInputRequestedData UserMessageAgentMode = rpc.UserMessageAgentMode UserMessageData = rpc.UserMessageData + UserMessageDelivery = rpc.UserMessageDelivery UserToolSessionApproval = rpc.UserToolSessionApproval UserToolSessionApprovalCommands = rpc.UserToolSessionApprovalCommands UserToolSessionApprovalCustomTool = rpc.UserToolSessionApprovalCustomTool @@ -301,6 +343,7 @@ type ( UserToolSessionApprovalMemory = rpc.UserToolSessionApprovalMemory UserToolSessionApprovalRead = rpc.UserToolSessionApprovalRead UserToolSessionApprovalWrite = rpc.UserToolSessionApprovalWrite + Verbosity = rpc.Verbosity WorkingDirectoryContext = rpc.WorkingDirectoryContext WorkingDirectoryContextHostType = rpc.WorkingDirectoryContextHostType WorkspaceFileChangedOperation = rpc.WorkspaceFileChangedOperation @@ -324,8 +367,24 @@ const ( AttachmentTypeDirectory = rpc.AttachmentTypeDirectory AttachmentTypeExtensionContext = rpc.AttachmentTypeExtensionContext AttachmentTypeFile = rpc.AttachmentTypeFile + AttachmentTypeGitHubActionsJob = rpc.AttachmentTypeGitHubActionsJob + AttachmentTypeGitHubCommit = rpc.AttachmentTypeGitHubCommit + AttachmentTypeGitHubFile = rpc.AttachmentTypeGitHubFile + AttachmentTypeGitHubFileDiff = rpc.AttachmentTypeGitHubFileDiff AttachmentTypeGitHubReference = rpc.AttachmentTypeGitHubReference + AttachmentTypeGitHubRelease = rpc.AttachmentTypeGitHubRelease + AttachmentTypeGitHubRepository = rpc.AttachmentTypeGitHubRepository + AttachmentTypeGitHubSnippet = rpc.AttachmentTypeGitHubSnippet + AttachmentTypeGitHubTreeComparison = rpc.AttachmentTypeGitHubTreeComparison + AttachmentTypeGitHubURL = rpc.AttachmentTypeGitHubURL AttachmentTypeSelection = rpc.AttachmentTypeSelection + AutoApprovalRecommendationApprove = rpc.AutoApprovalRecommendationApprove + AutoApprovalRecommendationError = rpc.AutoApprovalRecommendationError + AutoApprovalRecommendationExcluded = rpc.AutoApprovalRecommendationExcluded + AutoApprovalRecommendationRequireApproval = rpc.AutoApprovalRecommendationRequireApproval + AutoModeResolvedReasoningBucketHigh = rpc.AutoModeResolvedReasoningBucketHigh + AutoModeResolvedReasoningBucketLow = rpc.AutoModeResolvedReasoningBucketLow + AutoModeResolvedReasoningBucketMedium = rpc.AutoModeResolvedReasoningBucketMedium AutoModeSwitchResponseNo = rpc.AutoModeSwitchResponseNo AutoModeSwitchResponseYes = rpc.AutoModeSwitchResponseYes AutoModeSwitchResponseYesAlways = rpc.AutoModeSwitchResponseYesAlways @@ -368,8 +427,21 @@ const ( ExtensionsLoadedExtensionStatusStarting = rpc.ExtensionsLoadedExtensionStatusStarting HandoffSourceTypeLocal = rpc.HandoffSourceTypeLocal HandoffSourceTypeRemote = rpc.HandoffSourceTypeRemote + ManagedSettingsResolvedSourceDevice = rpc.ManagedSettingsResolvedSourceDevice + ManagedSettingsResolvedSourceNone = rpc.ManagedSettingsResolvedSourceNone + ManagedSettingsResolvedSourceServer = rpc.ManagedSettingsResolvedSourceServer + MCPHeadersRefreshCompletedOutcomeHeaders = rpc.MCPHeadersRefreshCompletedOutcomeHeaders + MCPHeadersRefreshCompletedOutcomeNone = rpc.MCPHeadersRefreshCompletedOutcomeNone + MCPHeadersRefreshCompletedOutcomeTimeout = rpc.MCPHeadersRefreshCompletedOutcomeTimeout + MCPHeadersRefreshRequiredReasonAuthFailed = rpc.MCPHeadersRefreshRequiredReasonAuthFailed + MCPHeadersRefreshRequiredReasonStartup = rpc.MCPHeadersRefreshRequiredReasonStartup + MCPHeadersRefreshRequiredReasonTtlExpired = rpc.MCPHeadersRefreshRequiredReasonTtlExpired MCPOauthCompletionOutcomeCancelled = rpc.MCPOauthCompletionOutcomeCancelled MCPOauthCompletionOutcomeToken = rpc.MCPOauthCompletionOutcomeToken + MCPOauthRequestReasonInitial = rpc.MCPOauthRequestReasonInitial + MCPOauthRequestReasonReauth = rpc.MCPOauthRequestReasonReauth + MCPOauthRequestReasonRefresh = rpc.MCPOauthRequestReasonRefresh + MCPOauthRequestReasonUpscope = rpc.MCPOauthRequestReasonUpscope MCPOauthRequiredStaticClientConfigGrantTypeClientCredentials = rpc.MCPOauthRequiredStaticClientConfigGrantTypeClientCredentials MCPServerSourceBuiltin = rpc.MCPServerSourceBuiltin MCPServerSourcePlugin = rpc.MCPServerSourcePlugin @@ -394,6 +466,9 @@ const ( OmittedBinaryOmittedReasonTooLarge = rpc.OmittedBinaryOmittedReasonTooLarge OmittedBinaryTypeImage = rpc.OmittedBinaryTypeImage OmittedBinaryTypeResource = rpc.OmittedBinaryTypeResource + PermissionAllowAllModeAuto = rpc.PermissionAllowAllModeAuto + PermissionAllowAllModeOff = rpc.PermissionAllowAllModeOff + PermissionAllowAllModeOn = rpc.PermissionAllowAllModeOn PermissionPromptRequestKindCommands = rpc.PermissionPromptRequestKindCommands PermissionPromptRequestKindCustomTool = rpc.PermissionPromptRequestKindCustomTool PermissionPromptRequestKindExtensionManagement = rpc.PermissionPromptRequestKindExtensionManagement @@ -442,13 +517,16 @@ const ( ReasoningSummaryDetailed = rpc.ReasoningSummaryDetailed ReasoningSummaryNone = rpc.ReasoningSummaryNone SessionEventTypeAbort = rpc.SessionEventTypeAbort + SessionEventTypeAssistantIdle = rpc.SessionEventTypeAssistantIdle SessionEventTypeAssistantIntent = rpc.SessionEventTypeAssistantIntent SessionEventTypeAssistantMessage = rpc.SessionEventTypeAssistantMessage SessionEventTypeAssistantMessageDelta = rpc.SessionEventTypeAssistantMessageDelta SessionEventTypeAssistantMessageStart = rpc.SessionEventTypeAssistantMessageStart SessionEventTypeAssistantReasoning = rpc.SessionEventTypeAssistantReasoning SessionEventTypeAssistantReasoningDelta = rpc.SessionEventTypeAssistantReasoningDelta + SessionEventTypeAssistantServerToolProgress = rpc.SessionEventTypeAssistantServerToolProgress SessionEventTypeAssistantStreamingDelta = rpc.SessionEventTypeAssistantStreamingDelta + SessionEventTypeAssistantToolCallDelta = rpc.SessionEventTypeAssistantToolCallDelta SessionEventTypeAssistantTurnEnd = rpc.SessionEventTypeAssistantTurnEnd SessionEventTypeAssistantTurnStart = rpc.SessionEventTypeAssistantTurnStart SessionEventTypeAssistantUsage = rpc.SessionEventTypeAssistantUsage @@ -469,14 +547,20 @@ const ( SessionEventTypeHookProgress = rpc.SessionEventTypeHookProgress SessionEventTypeHookStart = rpc.SessionEventTypeHookStart SessionEventTypeMCPAppToolCallComplete = rpc.SessionEventTypeMCPAppToolCallComplete + SessionEventTypeMCPHeadersRefreshCompleted = rpc.SessionEventTypeMCPHeadersRefreshCompleted + SessionEventTypeMCPHeadersRefreshRequired = rpc.SessionEventTypeMCPHeadersRefreshRequired SessionEventTypeMCPOauthCompleted = rpc.SessionEventTypeMCPOauthCompleted SessionEventTypeMCPOauthRequired = rpc.SessionEventTypeMCPOauthRequired + SessionEventTypeMCPPromptsListChanged = rpc.SessionEventTypeMCPPromptsListChanged + SessionEventTypeMCPResourcesListChanged = rpc.SessionEventTypeMCPResourcesListChanged + SessionEventTypeMCPToolsListChanged = rpc.SessionEventTypeMCPToolsListChanged SessionEventTypeModelCallFailure = rpc.SessionEventTypeModelCallFailure SessionEventTypePendingMessagesModified = rpc.SessionEventTypePendingMessagesModified SessionEventTypePermissionCompleted = rpc.SessionEventTypePermissionCompleted SessionEventTypePermissionRequested = rpc.SessionEventTypePermissionRequested SessionEventTypeSamplingCompleted = rpc.SessionEventTypeSamplingCompleted SessionEventTypeSamplingRequested = rpc.SessionEventTypeSamplingRequested + SessionEventTypeSessionAutoModeResolved = rpc.SessionEventTypeSessionAutoModeResolved SessionEventTypeSessionAutopilotObjectiveChanged = rpc.SessionEventTypeSessionAutopilotObjectiveChanged SessionEventTypeSessionBackgroundTasksChanged = rpc.SessionEventTypeSessionBackgroundTasksChanged SessionEventTypeSessionBinaryAsset = rpc.SessionEventTypeSessionBinaryAsset @@ -497,6 +581,9 @@ const ( SessionEventTypeSessionHandoff = rpc.SessionEventTypeSessionHandoff SessionEventTypeSessionIdle = rpc.SessionEventTypeSessionIdle SessionEventTypeSessionInfo = rpc.SessionEventTypeSessionInfo + SessionEventTypeSessionLimitsExhaustedCompleted = rpc.SessionEventTypeSessionLimitsExhaustedCompleted + SessionEventTypeSessionLimitsExhaustedRequested = rpc.SessionEventTypeSessionLimitsExhaustedRequested + SessionEventTypeSessionManagedSettingsResolved = rpc.SessionEventTypeSessionManagedSettingsResolved SessionEventTypeSessionMCPServersLoaded = rpc.SessionEventTypeSessionMCPServersLoaded SessionEventTypeSessionMCPServerStatusChanged = rpc.SessionEventTypeSessionMCPServerStatusChanged SessionEventTypeSessionModeChanged = rpc.SessionEventTypeSessionModeChanged @@ -508,6 +595,7 @@ const ( SessionEventTypeSessionScheduleCancelled = rpc.SessionEventTypeSessionScheduleCancelled SessionEventTypeSessionScheduleCreated = rpc.SessionEventTypeSessionScheduleCreated SessionEventTypeSessionScheduleRearmed = rpc.SessionEventTypeSessionScheduleRearmed + SessionEventTypeSessionSessionLimitsChanged = rpc.SessionEventTypeSessionSessionLimitsChanged SessionEventTypeSessionShutdown = rpc.SessionEventTypeSessionShutdown SessionEventTypeSessionSkillsLoaded = rpc.SessionEventTypeSessionSkillsLoaded SessionEventTypeSessionSnapshotRewind = rpc.SessionEventTypeSessionSnapshotRewind @@ -517,6 +605,7 @@ const ( SessionEventTypeSessionTodosChanged = rpc.SessionEventTypeSessionTodosChanged SessionEventTypeSessionToolsUpdated = rpc.SessionEventTypeSessionToolsUpdated SessionEventTypeSessionTruncation = rpc.SessionEventTypeSessionTruncation + SessionEventTypeSessionUsageCheckpoint = rpc.SessionEventTypeSessionUsageCheckpoint SessionEventTypeSessionUsageInfo = rpc.SessionEventTypeSessionUsageInfo SessionEventTypeSessionWarning = rpc.SessionEventTypeSessionWarning SessionEventTypeSessionWorkspaceFileChanged = rpc.SessionEventTypeSessionWorkspaceFileChanged @@ -536,6 +625,10 @@ const ( SessionEventTypeUserInputCompleted = rpc.SessionEventTypeUserInputCompleted SessionEventTypeUserInputRequested = rpc.SessionEventTypeUserInputRequested SessionEventTypeUserMessage = rpc.SessionEventTypeUserMessage + SessionLimitsExhaustedResponseActionAdd = rpc.SessionLimitsExhaustedResponseActionAdd + SessionLimitsExhaustedResponseActionCancel = rpc.SessionLimitsExhaustedResponseActionCancel + SessionLimitsExhaustedResponseActionSet = rpc.SessionLimitsExhaustedResponseActionSet + SessionLimitsExhaustedResponseActionUnset = rpc.SessionLimitsExhaustedResponseActionUnset SessionModeAutopilot = rpc.SessionModeAutopilot SessionModeInteractive = rpc.SessionModeInteractive SessionModePlan = rpc.SessionModePlan @@ -567,6 +660,7 @@ const ( ToolExecutionCompleteContentTypeImage = rpc.ToolExecutionCompleteContentTypeImage ToolExecutionCompleteContentTypeResource = rpc.ToolExecutionCompleteContentTypeResource ToolExecutionCompleteContentTypeResourceLink = rpc.ToolExecutionCompleteContentTypeResourceLink + ToolExecutionCompleteContentTypeShellExit = rpc.ToolExecutionCompleteContentTypeShellExit ToolExecutionCompleteContentTypeTerminal = rpc.ToolExecutionCompleteContentTypeTerminal ToolExecutionCompleteContentTypeText = rpc.ToolExecutionCompleteContentTypeText ToolExecutionCompleteToolDescriptionMetaUIVisibilityApp = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibilityApp @@ -577,6 +671,9 @@ const ( UserMessageAgentModeInteractive = rpc.UserMessageAgentModeInteractive UserMessageAgentModePlan = rpc.UserMessageAgentModePlan UserMessageAgentModeShell = rpc.UserMessageAgentModeShell + UserMessageDeliveryIdle = rpc.UserMessageDeliveryIdle + UserMessageDeliveryQueued = rpc.UserMessageDeliveryQueued + UserMessageDeliverySteering = rpc.UserMessageDeliverySteering UserToolSessionApprovalKindCommands = rpc.UserToolSessionApprovalKindCommands UserToolSessionApprovalKindCustomTool = rpc.UserToolSessionApprovalKindCustomTool UserToolSessionApprovalKindExtensionManagement = rpc.UserToolSessionApprovalKindExtensionManagement @@ -585,6 +682,9 @@ const ( UserToolSessionApprovalKindMemory = rpc.UserToolSessionApprovalKindMemory UserToolSessionApprovalKindRead = rpc.UserToolSessionApprovalKindRead UserToolSessionApprovalKindWrite = rpc.UserToolSessionApprovalKindWrite + VerbosityHigh = rpc.VerbosityHigh + VerbosityLow = rpc.VerbosityLow + VerbosityMedium = rpc.VerbosityMedium WorkingDirectoryContextHostTypeADO = rpc.WorkingDirectoryContextHostTypeADO WorkingDirectoryContextHostTypeGitHub = rpc.WorkingDirectoryContextHostTypeGitHub WorkspaceFileChangedOperationCreate = rpc.WorkspaceFileChangedOperationCreate diff --git a/java/README.md b/java/README.md index 28544b0143..525cb364dd 100644 --- a/java/README.md +++ b/java/README.md @@ -32,14 +32,14 @@ Replace `${copilot.sdk.version}` with the latest release from Maven Central. com.github copilot-sdk-java - 1.0.4 + 1.0.5-01 ``` ### Gradle ```groovy -implementation 'com.github:copilot-sdk-java:1.0.4' +implementation 'com.github:copilot-sdk-java:1.0.7-01' ``` #### Snapshot Builds @@ -58,7 +58,7 @@ Snapshot builds of the next development version are published to Maven Central S com.github copilot-sdk-java - 1.0.5-SNAPSHOT + 1.0.8-SNAPSHOT ``` @@ -67,7 +67,7 @@ Snapshot builds of the next development version are published to Maven Central S Replace `${copilot.sdk.version}` with the latest release from Maven Central. ```groovy -implementation 'com.github:copilot-sdk-java:1.0.5-SNAPSHOT' +implementation 'com.github:copilot-sdk-java:1.0.7-01-SNAPSHOT' ``` ## Quick Start @@ -132,6 +132,106 @@ Or run it directly from the repository: jbang https://github.com/github/copilot-sdk/blob/main/java/jbang-example.java ``` +## Annotation-based tools and `ToolInvocation` context + +When you define tools with `@CopilotTool`, parameters of type `ToolInvocation` are injected as runtime context and are not exposed in the tool schema. +`ToolInvocation` can appear before, between, or after schema-visible parameters. + +```java +import com.github.copilot.rpc.ToolInvocation; +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +class ProgressTools { + @CopilotTool("Reports the current phase and session") + public String reportProgress( + @CopilotToolParam("Current phase") String phase, + ToolInvocation invocation) { + return "phase=" + phase + ", sessionId=" + invocation.getSessionId(); + } +} +``` + +Position examples: + +```java +@CopilotTool("Invocation first") +public String report(ToolInvocation invocation, @CopilotToolParam("Phase") String phase) { ... } + +@CopilotTool("Invocation only") +public String onlyContext(ToolInvocation invocation) { ... } + +@CopilotTool("Invocation middle") +public String report(@CopilotToolParam("Phase") String phase, ToolInvocation invocation, @CopilotToolParam("Limit") int limit) { ... } +``` + +## Inline lambda tool definitions (experimental) + +For inline tool authoring at the session construction site, use `ToolDefinition.from(...)` with explicit parameter metadata: + +```java +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.rpc.ToolDefer; +import com.github.copilot.tool.Param; + +ToolDefinition search = ToolDefinition + .from( + "search_items", + "Searches indexed items by keyword", + Param.of(String.class, "keyword", "Search keyword"), + keyword -> "Searching for: " + keyword) + .skipPermission(true) + .defer(ToolDefer.AUTO); +``` + +### Parameter metadata with `Param.of(...)` + +`Param.of(type, name, description)` creates a required parameter. For optional parameters with defaults: + +```java +Param limit = Param.of(Integer.class, "limit", "Max results", false, "10"); +``` + +### Async handlers + +Use `fromAsync` for asynchronous tool handlers: + +```java +import java.util.concurrent.CompletableFuture; + +ToolDefinition fetchData = ToolDefinition.fromAsync( + "fetch_data", + "Fetches data from remote source", + Param.of(String.class, "url", "Data source URL"), + url -> CompletableFuture.supplyAsync(() -> fetchRemote(url)) +); +``` + +### ToolInvocation context injection + +Inline tools can access `ToolInvocation` runtime context using `fromWithToolInvocation`: + +```java +ToolDefinition reportPhase = ToolDefinition.fromWithToolInvocation( + "report_phase", + "Reports the current phase with invocation context", + Param.of(String.class, "phase", "The current phase"), + (phase, invocation) -> "phase=" + phase + ", toolCallId=" + invocation.getToolCallId() +); +``` + +For async with `ToolInvocation`, use `fromAsyncWithToolInvocation`. + +### Fluent option modifiers + +Chain fluent modifiers to set tool options: + +- `.skipPermission(boolean)` — bypass permission prompts +- `.defer(ToolDefer)` — control deferred execution (`AUTO`, `NEVER`) +- `.overridesBuiltInTool(boolean)` — shadow built-in tools + +For design context and decision rationale, see [ADR-006](docs/adr/adr-006-tool-definition-inline.md). + ## Memory Sessions can opt into persistent memory, allowing the agent to read and write memory across turns. Memory is configured per session and applies to both `createSession` and `resumeSession`. diff --git a/java/docs/adr/adr-005-tool-definition.md b/java/docs/adr/adr-005-tool-definition.md index d389ac134b..dc1eb36143 100644 --- a/java/docs/adr/adr-005-tool-definition.md +++ b/java/docs/adr/adr-005-tool-definition.md @@ -51,10 +51,10 @@ Explicit `ToolDefinition.create(name, description, schema, handler)` with a hand ### Option 2: Record-as-schema with generic factory -Define a record for the tool's arguments, annotate its components with `@Param`, and use a generic factory method to auto-generate the schema from the record's `RecordComponent[]` metadata: +Define a record for the tool's arguments and use a generic factory method to auto-generate the schema from the record's `RecordComponent[]` metadata. Because `@CopilotToolParam` targets `ElementType.PARAMETER` (method parameters only), it cannot be placed on record components; per-field descriptions are not supported in this option: ```java -record PhaseArgs(@Param("The phase to transition to") Phase phase) {} +record PhaseArgs(Phase phase) {} ToolDefinition.define("set_current_phase", "Sets the current phase of the agent.", @@ -76,18 +76,19 @@ ToolDefinition.define("set_current_phase", - Tool name and description are still explicit string arguments. - Requires a separate record class for every tool's args (even trivial single-param tools). - The handler is still an explicit lambda — the "tool" is not the method itself. +- Per-field descriptions cannot be provided: `@CopilotToolParam` targets method parameters only, not record components. - Nested or complex schemas (arrays of objects, polymorphic types) need additional mapping logic. - No analog in the broader Java ecosystem; Java developers are not accustomed to defining a record per function call. ### Option 3: Annotation-on-method (langchain4j-style) -Annotate existing Java methods with `@Tool` (or a Copilot-specific equivalent) and annotate parameters with `@P`/`@Param`. The framework discovers tools by scanning methods on a given object, auto-generates `ToolSpecification` / `ToolDefinition` from the method signature, and dispatches invocations directly to the annotated method. +Annotate existing Java methods with `@Tool` (or a Copilot-specific equivalent) and annotate parameters with `@P`/`@CopilotToolParam`. The framework discovers tools by scanning methods on a given object, auto-generates `ToolSpecification` / `ToolDefinition` from the method signature, and dispatches invocations directly to the annotated method. ```java class MyTools { @CopilotTool("Sets the current phase of the agent. Use this to report progress.") - String setCurrentPhase(@Param("The phase to transition to") Phase phase) { + String setCurrentPhase(@CopilotToolParam("The phase to transition to") Phase phase) { this.phase = phase; updateUi(); return "Phase set to " + phase; @@ -95,7 +96,7 @@ class MyTools { @CopilotTool(name = "report_intent", value = "Reports the agent's intent", overridesBuiltInTool = true) - String reportIntent(@Param("The intent") String intent) { + String reportIntent(@CopilotToolParam("The intent") String intent) { // ... } } @@ -110,7 +111,7 @@ This is the approach used by [langchain4j](https://github.com/langchain4j/langch **What the framework does automatically:** 1. **Name** — derived from `@CopilotTool(name=...)` or the method name (converted to snake_case). 2. **Description** — from `@CopilotTool("...")` or `@CopilotTool(value="...")`. -3. **Parameter schema** — generated by reflecting on method parameters: types map to JSON Schema types; `@Param` provides descriptions; `Optional` or `@Param(required=false)` marks optional params. +3. **Parameter schema** — generated by reflecting on method parameters: types map to JSON Schema types; `@CopilotToolParam` provides descriptions; `Optional` or `@CopilotToolParam(required=false)` marks optional params. 4. **Handler** — the method itself. The framework deserializes JSON arguments into the method's parameter types and invokes the method reflectively. The return value is serialized back to a string result. **Advantages:** @@ -127,8 +128,8 @@ This is the approach used by [langchain4j](https://github.com/langchain4j/langch - One-time scanning cost at registration time (negligible for typical tool counts). - Return type handling needs a policy: `String` → sent as-is; `void` → "Success"; other types → JSON-serialized. - Async story: methods could return `CompletableFuture` for async tools, or the framework could invoke synchronous methods on a configurable executor. -- New annotation(s) added to the public API surface (`@CopilotTool`, `@Param`). -- Requires `-parameters` javac flag for parameter name preservation (or explicit `@Param(name=...)` — same constraint as langchain4j). +- New annotation(s) added to the public API surface (`@CopilotTool`, `@CopilotToolParam`). +- Requires `-parameters` javac flag for parameter name preservation (or explicit `@CopilotToolParam(name=...)` — same constraint as langchain4j). ## Decision Outcome @@ -141,7 +142,7 @@ This is the approach used by [langchain4j](https://github.com/langchain4j/langch 2. **Minimum viable tool is one annotated method.** With Option 3, the absolute minimum code to define a tool is: ```java @CopilotTool("Gets the weather") - String getWeather(@Param("City") String city) { return weatherApi.get(city); } + String getWeather(@CopilotToolParam("City") String city) { return weatherApi.get(city); } ``` With Option 2, you need a record class *and* a lambda. With Option 1, you need a record class, a Map schema, *and* a lambda. @@ -180,18 +181,49 @@ final class MyTools$$CopilotToolMeta { Phase phase = invocation.getArgumentsAs(Phase.class); return CompletableFuture.completedFuture( instance.setCurrentPhase(phase)); - }, null, null, null) + }, null, null, null, null) ); } } ``` +The trailing constructor arguments are `overridesBuiltInTool`, `skipPermission`, `defer`, and `metadata` — all `null` here because none were set on the annotation. + At runtime, `ToolDefinition.fromObject(myTools)` loads the generated `$$CopilotToolMeta` class — zero reflection, zero dependency on `-parameters`. +### Host-defined metadata + +`@CopilotTool` also accepts an opaque `metadata` bag via nested annotations. Because annotation members can't express arbitrary maps, the representation is deliberately shallow: each entry maps a namespaced key to a boolean, a string, or a one-level map of named boolean flags. + +```java +@CopilotTool( + value = "Reports phase", + metadata = { + @CopilotTool.MetadataEntry( + key = "github.com/copilot:safeForTelemetry", + value = @CopilotTool.MetadataValue(flags = { + @CopilotTool.MetadataFlag(name = "name", value = true), + @CopilotTool.MetadataFlag(name = "inputsNames", value = false) + })) + }) +public String reportPhase(@CopilotToolParam("Phase") String phase) { + return phase; +} +``` + +The processor emits this as the `metadata` constructor argument: + +```java +Map.of("github.com/copilot:safeForTelemetry", + Map.of("name", true, "inputsNames", false)) +``` + +For richer values (numbers, arrays, deeper nesting), use the programmatic `ToolDefinition.createWithMetadata(...)` / `ToolDefinition.metadata(...)` API instead. + ### Compile-time validation Because the processor has full access to the source AST, it can emit compile errors for: -- Missing `@Param` on parameters (when descriptions are required by policy). +- Missing `@CopilotToolParam` on parameters (when descriptions are required by policy). - Unsupported parameter types (types without a clear JSON Schema mapping). - Duplicate tool names within the same class hierarchy. - Invalid annotation combinations (e.g., `overridesBuiltInTool` on a tool with `skipPermission`). @@ -217,14 +249,14 @@ Because the processor has full access to the source AST, it can emit compile err ## Consequences -- New public annotations: `@CopilotTool` and `@Param` (in `com.github.copilot.rpc` or a new `com.github.copilot.tool` package). +- New public annotations: `@CopilotTool` and `@CopilotToolParam` (in `com.github.copilot.rpc` or a new `com.github.copilot.tool` package). - New JSR 269 annotation processor that generates `$$CopilotToolMeta` companion classes at compile time. - New utility: `ToolDefinition.fromObject(Object)` / `ToolDefinition.fromClass(Class)` that loads the generated metadata class (falling back to runtime reflection if the processor was not run). - The existing `ToolDefinition.create(...)` / `ToolDefinition.createOverride(...)` APIs remain unchanged — they become the "low-level" path. - No `-parameters` javac flag requirement for users who run the annotation processor (which happens automatically when the SDK is on the compile classpath). - Async support: methods returning `CompletableFuture` are handled natively; synchronous methods are wrapped in `CompletableFuture.completedFuture(...)` (or dispatched to an executor, TBD). - GraalVM native-image compatibility without additional reflection configuration. -- **Experimental designation:** `@CopilotTool`, `@Param`, `ToolDefinition.fromObject(Object)`, and `ToolDefinition.fromClass(Class)` will all be annotated with `@CopilotExperimental`. This gates adoption behind an explicit opt-in (`-Acopilot.experimental.allowed=true`) until the API surface stabilizes, consistent with the policy established in ADR-004. +- **Experimental designation:** `@CopilotTool`, `@CopilotToolParam`, `ToolDefinition.fromObject(Object)`, and `ToolDefinition.fromClass(Class)` will all be annotated with `@CopilotExperimental`. This gates adoption behind an explicit opt-in (`-Acopilot.experimental.allowed=true`) until the API surface stabilizes, consistent with the policy established in ADR-004. ## Related work items diff --git a/java/docs/adr/adr-006-tool-definition-inline.md b/java/docs/adr/adr-006-tool-definition-inline.md new file mode 100644 index 0000000000..ad48527c10 --- /dev/null +++ b/java/docs/adr/adr-006-tool-definition-inline.md @@ -0,0 +1,118 @@ +# ADR-006: Inline tool definition with lambdas + +## Context and problem statement + +[ADR-005](adr-005-tool-definition.md) introduced an ergonomic Java tools API based on `@CopilotTool` method annotations, `@CopilotToolParam` parameter annotations, and `ToolDefinition.fromObject(...)` for reflection-based tool registration. That model works well when teams define tools as methods on a class. + +The next ergonomics goal is an inline style comparable to C# `CopilotTool.DefineTool(...)`, where developers can define a tool at the call site without creating a separate tool container class. + +For this decision, we evaluated two alternatives: + +* Method-reference registration (`ToolDefinition.from(tools::setCurrentPhase)`) +* Inline lambda registration (`ToolDefinition.from(..., phase -> ...)`) + +The key factor is metadata quality: tool name, description, parameter names, parameter descriptions, required/default semantics, and schema stability. + +## Considered options + +### Option 1: Method-reference API + +Example: + +```java +ToolDefinition setPhase = ToolDefinition.from(tools::setCurrentPhase); +``` + +In this model, metadata is sourced from existing method-level annotations (`@CopilotTool`, `@Param`) on the referenced method. + +Advantages: + +* Closest Java analog to C# method-group ergonomics +* High-quality metadata with minimal additional API surface +* Reuses ADR-005 metadata and invocation behavior directly + +Drawbacks: + +* Not truly inline: still requires a declared method (and usually annotations) elsewhere +* Does not solve the "define the whole tool at the call site" use case +* Method-reference resolution adds runtime/reflection complexity + +### Option 2: Inline lambda API with explicit metadata + +Example: + +```java +ToolDefinition setPhase = ToolDefinition.from( + "set_current_phase", + "Sets the current phase of the agent", + Param.of(String.class, "phase", "The phase to transition to"), + (String phase) -> { + currentPhase = phase; + return "Phase set to " + phase; + }); +``` + +In this model, handler logic is inline, and metadata is provided explicitly through `Param.of(...)` parameter definitions. + +Advantages: + +* True inline authoring at the session construction site +* No dependence on lambda parameter-name reflection or `-parameters` +* Deterministic metadata and schema generation +* Independent from annotation processing and generated companion classes + +Drawbacks: + +* Slightly more verbose than method-reference style because metadata is explicit +* Introduces new public API types for parameter definitions and typed lambda overloads +* Requires careful API design to stay concise for common one-parameter tools + +## Decision outcome + +Chosen: **Option 2 for ADR-006 scope** — inline lambda API with explicit metadata. + +Rationale: + +1. The primary requirement for this ADR is inline definition. Option 2 satisfies it directly; Option 1 does not. +1. Metadata quality is the critical requirement. Option 2 keeps metadata explicit and stable, instead of relying on fragile lambda introspection. +1. Option 2 can ship independently of method-reference support and without changes to annotation processing. +1. Option 2 preserves behavior parity with existing tool execution by delegating to `ToolDefinition` construction and current invocation semantics. + +Option 1 remains valuable and can be added independently as a separate ergonomic layer. It is not blocked by this decision. + +## Design constraints and non-goals + +Constraints for the inline lambda API: + +* Require explicit tool name and description. +* Require explicit parameter metadata (at minimum name and type, with optional description/required/default). +* Support both sync and async handlers (`R` and `CompletableFuture`). +* Keep result semantics aligned with existing behavior (`String` passthrough, `void` maps to `"Success"`, non-string objects serialized to JSON). +* Keep override/permission/defer flags available through options, consistent with existing `ToolDefinition` fields. + +Non-goals for this ADR: + +* Replacing `@CopilotTool`/`fromObject` APIs. +* Defining method-reference registration behavior in detail. +* Introducing compile-time code generation for lambda metadata. + +## Consequences + +The SDK now provides an explicit inline path for developers who prefer to keep tool declarations at session creation while preserving high-quality schema metadata. Implemented API families include: + +- `ToolDefinition.from(name, description, [params...], handler)` — sync handlers +- `ToolDefinition.fromAsync(name, description, [params...], asyncHandler)` — async handlers returning `CompletableFuture` +- `ToolDefinition.fromWithToolInvocation(...)` — sync with `ToolInvocation` context injection +- `ToolDefinition.fromAsyncWithToolInvocation(...)` — async with `ToolInvocation` context injection + +Parameter metadata is defined using `Param.of(type, name, description)` for required parameters and `Param.of(type, name, description, required, defaultValue)` for optional parameters with defaults. + +Fluent option modifiers (`.skipPermission(boolean)`, `.defer(ToolDefer)`, `.overridesBuiltInTool(boolean)`) allow post-construction customization. + +The annotation-driven API from [ADR-005](adr-005-tool-definition.md) remains the recommended path for larger tool surfaces where co-locating metadata with method implementations improves maintainability. For usage examples and complete API coverage, see the Java SDK README. + +## Related work items + +* #1682 +* #1792 +* #1810 diff --git a/java/docs/adr/adr-007-native-bundling-strategy.md b/java/docs/adr/adr-007-native-bundling-strategy.md new file mode 100644 index 0000000000..1322e199ef --- /dev/null +++ b/java/docs/adr/adr-007-native-bundling-strategy.md @@ -0,0 +1,384 @@ +# ADR-007: Native runtime bundling strategy — per-platform classifier JARs + +## Context and Problem Statement + +The Copilot SDK for Java currently has no embedded runtime. It depends on an externally provided runtime process (see epic [#1917](https://github.com/github/copilot-sdk/issues/1917)). The ongoing Rust port of the `copilot-agent-runtime` repository is reaching the point where the runtime can be consumed as a native shared library without requiring a Node.js process, making it practical to embed the runtime directly in the SDK JAR. + +### The runtime artifact + +The artifact to be embedded is `runtime.node`, a Rust [`cdylib`](#references) produced by the `src/runtime` crate in `github/copilot-agent-runtime` using the [napi-rs](#references) build toolchain. Despite the `.node` file extension (a naming convention of napi-rs), this is an ordinary platform-specific shared library (`.so` on Linux, `.dylib` on macOS, `.dll` on Windows). It exposes two front doors built over the same internal engine: + +- **[napi](#references) front door** — loaded by a Node.js process as a native addon (current CLI path). +- **[C ABI](#references) front door** — a fixed set of approximately 12 `extern "C"` lifecycle and transport entry points (`copilot_runtime_server_create`, `copilot_runtime_connection_open`, etc.) that any language can call in-process via [FFI](#references) ([JNA](#references) for Java, Python/cffi, C#/`DllImport`, Go/purego) **without a Node.js process**. All API methods travel as JSON-RPC data through this fixed transport; the export list never changes as the method set grows. + +The `cli-native.node` addon — a separate, smaller artifact that provides ICU4X text segmentation, Win32 API wrappers, and terminal UI helpers — is a CLI-only artifact used by the Ink/React terminal interface. It is **not needed** by the Java SDK. + +### Note on the active Rust migration + +As of 2026-07, the `runtime.node` binary is being built up iteratively as TypeScript runtime code is ported into it. It is **not** being reduced; it is growing with each port PR. The `embedded_host.rs` module in the runtime currently spawns a short-lived child process to service method bodies not yet ported to Rust. This internal Node.js dependency shrinks with each port PR and is expected to disappear entirely when the migration completes. The C ABI surface and loading mechanism described in this ADR are stable regardless of migration progress. + +### Platform dimensions + +The runtime must be built for each unique combination of OS, CPU architecture, and (on Linux) C runtime variant. The build system in `github/copilot-agent-runtime` produces eight Rust target triples: + +| Platform label | Rust triple | Constraint | +|---------------|-------------|------------| +| `linux-x64` | `x86_64-unknown-linux-gnu` | [glibc](#references) ≥ 2.28 (Debian 10+, Ubuntu 20.04+, RHEL 8+) | +| `linux-arm64` | `aarch64-unknown-linux-gnu` | glibc ≥ 2.28 | +| `linuxmusl-x64` | `x86_64-unknown-linux-musl` | dynamically links [musl libc](#references) (Alpine Linux) | +| `linuxmusl-arm64` | `aarch64-unknown-linux-musl` | dynamically links musl libc | +| `darwin-x64` | `x86_64-apple-darwin` | macOS, Intel | +| `darwin-arm64` | `aarch64-apple-darwin` | macOS, Apple Silicon | +| `win32-x64` | `x86_64-pc-windows-msvc` | [MSVC CRT](#references) statically linked (`+crt-static`) | +| `win32-arm64` | `aarch64-pc-windows-msvc` | MSVC CRT statically linked (`+crt-static`) | + +The GNU/Linux glibc minimum of 2.28 is enforced at build time via a Microsoft/vscode-linux-build-agent sysroot and verified post-build by `script/linux/verify-glibc-requirements.sh`. The musl binaries are **not** fully statically linked; they dynamically link musl libc (`-C target-feature=-crt-static` is explicitly set at build time). + +The **common case** (Windows × 2 + macOS × 2 + GNU/Linux × 2) requires **6 binaries**. Supporting Alpine Linux adds 2 more musl binaries for a total of **8**. + +### Platform selection is 100% deterministic + +The correct binary can be selected at runtime without any heuristics, using only standard Java and OS APIs: + +1. **OS**: `System.getProperty("os.name")` — distinguishes Windows, macOS, and Linux unambiguously. +2. **Architecture**: `System.getProperty("os.arch")` — `"amd64"` and `"x86_64"` both map to `x64`; `"aarch64"` and `"arm64"` both map to `arm64`. +3. **Linux libc variant**: Read the first 2 KB of `/proc/self/exe` and parse the [ELF](#references) PT_INTERP segment (the dynamic linker path). If the interpreter path contains `/ld-musl-` → musl; if it contains `/ld-linux-` → glibc. This requires no subprocess, no PATH lookup, and works inside containers. This is the same approach used by the `detect-libc` npm package (its primary, most reliable detection method). + +### Size baseline + +Measured from `github/copilot-agent-runtime` release `cli-1.0.69-2` (2026-07-06): + +| Platform | `runtime.node` (uncompressed) | Compressed (~40% deflate) | +|----------|------------------------------|--------------------------| +| `linux-x64` | 64.7 MB | ~25.9 MB | +| `linux-arm64` | 55.5 MB | ~22.2 MB | +| `linuxmusl-x64` | 64.4 MB | ~25.8 MB | +| `linuxmusl-arm64` | 55.3 MB | ~22.1 MB | +| `darwin-x64` | 57.3 MB | ~22.9 MB | +| `darwin-arm64` | 48.1 MB | ~19.2 MB | +| `win32-x64` | 55.9 MB | ~22.4 MB | +| `win32-arm64` | 48.4 MB | ~19.4 MB | + +The published Java SDK JAR (`copilot-sdk-java-1.0.6-preview.1.jar`) is currently **1.53 MB**. A monolithic JAR containing all 6 common-case native binaries would be approximately **132 MB** compressed; all 8 including musl would be approximately **180 MB** compressed. + +All native dependencies within the runtime (`rustls`/`aws-lc-rs` for TLS, `rusqlite` with `bundled` feature for SQLite, `zlib-rs` for compression) are statically compiled into the binary. There are no dependencies on system OpenSSL, libgit2, or libz. + +## Considered Options + +### Option 1: Monolithic JAR — all platform binaries in one artifact + +All 6 (or 8) `runtime.node` binaries are bundled inside the single `copilot-sdk-java` artifact. At runtime the SDK extracts and loads the one matching the current platform; the remaining 5–7 are carried silently. + +**Advantages:** +- Single `` in `pom.xml`; zero extra configuration for users. +- Familiar pattern: [ONNX Runtime](#references) (`onnxruntime-1.21.0.jar`, **130 MB**, all platforms) demonstrates this is an accepted norm in the Java ML ecosystem. + +**Drawbacks:** +- Every user downloads every platform regardless of their target. A developer on Apple Silicon downloads 105+ MB of Linux and Windows binaries they will never use. +- Build tooling (thin Docker layers, incremental CI caches, artifact registries) penalises large JARs. A single 132–180 MB JAR invalidates the entire cache whenever any platform's binary changes. +- Maven's dependency resolution has no mechanism to supply platform-appropriate variants automatically; platform selection must happen entirely at runtime inside the JAR. +- Conflicts with the principle that Maven artifacts should be reproducible and minimal. + +### Option 2: Per-platform classifier JARs ([DJL](#references) style) + +A small, pure-Java coordination artifact (`copilot-sdk-java`, ~1.5 MB) is published alongside separate per-platform native artifacts differentiated by Maven classifier: + +``` +com.github:copilot-sdk-java-runtime:VERSION:linux-x64 +com.github:copilot-sdk-java-runtime:VERSION:linux-arm64 +com.github:copilot-sdk-java-runtime:VERSION:linuxmusl-x64 +com.github:copilot-sdk-java-runtime:VERSION:linuxmusl-arm64 +com.github:copilot-sdk-java-runtime:VERSION:darwin-x64 +com.github:copilot-sdk-java-runtime:VERSION:darwin-arm64 +com.github:copilot-sdk-java-runtime:VERSION:win32-x64 +com.github:copilot-sdk-java-runtime:VERSION:win32-arm64 +``` + +Each classifier JAR contains only the `runtime.node` binary for that platform (~19–26 MB compressed) plus a small `.properties` metadata file. The coordination artifact selects and loads the matching native at startup. + +This is the same pattern used by DJL's PyTorch native artifacts (`pytorch-native-cpu-2.5.1-linux-x86_64.jar`, `pytorch-native-cpu-2.5.1-osx-aarch64.jar`, etc.), Netty's `netty-tcnative-boringssl-static` per-platform JARs, and others. + +Build tools can be configured to resolve the correct classifier automatically: + +- **Maven**: `${os.detected.classifier}` via [os-maven-plugin](#references). +- **Gradle**: variant-aware dependency resolution with attribute matching. +- **Uber-jar builds**: include all classifiers; the coordination artifact picks the right one at runtime. + +**Advantages:** +- Default download is the tiny coordination artifact (~1.5 MB) plus one platform JAR (~20–26 MB compressed) — approximately **22–28 MB total** vs. 132–180 MB for a monolithic JAR. +- Each platform JAR changes independently; CI caches and Docker layers for unchanged platforms are preserved across releases. +- Users building for a single known platform (most production deployments) pay exactly the cost of that platform. +- Follows well-established Maven ecosystem conventions; standard tooling ([os-maven-plugin](#references), Gradle variant resolution) handles classifier selection. +- Aligns with DJL's proven distribution strategy for large native ML runtimes. + +**Drawbacks:** +- Requires publishing 6–8 additional Maven artifacts per release. +- Users building portable über-JARs must explicitly include all classifiers they wish to support. +- Slightly more complex `pom.xml` / `build.gradle` for users who need cross-platform packaging. + +### Option 3: Download-on-demand (DJL thin placeholder style) + +The SDK ships a minimal placeholder that detects the current platform at runtime and downloads the correct `runtime.node` binary from a distribution endpoint (GitHub Releases or a CDN) on first use, caching it locally (e.g., `~/.copilot/runtime-cache/`). + +**Advantages:** +- Zero native binary content in any published Maven artifact; total download at `mvn install` is negligible. +- Identical user experience to the current "externally provided runtime" model during the download, which most CLI users already accept. + +**Drawbacks:** +- Requires internet access on first run. Offline environments (air-gapped enterprise, CI without outbound HTTP) break silently or require manual pre-seeding. +- Introduces a network dependency into an otherwise pure library artifact, which violates Maven Central's expectations for reproducible builds. +- Adds an operational concern: distribution endpoint availability, CDN costs, URL stability across versions. +- Makes JVM startup non-deterministic in latency (first run downloads 20–26 MB). +- Cannot be pre-warmed by dependency management tooling; no `mvn dependency:resolve` analogue works for a runtime download. + +## Decision Outcome + +**Chosen: Option 2 — per-platform classifier JARs and Option 1 - monolithic jar. Use `maven-assembly-plugin` to allow the creation of the monolithic jar.** + +### Rationale + +1. **User download cost matches actual need.** Most users run on one OS and architecture. Option 2 makes their download approximately 22–28 MB (coordination JAR + one platform JAR), versus 132–180 MB for Option 1 and an unbounded deferred network cost for Option 3. + +2. **Proven ecosystem pattern.** DJL, Netty, and others have established the per-classifier pattern as the correct Maven idiom for large native binaries. Build tooling already knows how to handle it; users and framework integrations (Spring Boot, Quarkus, Micronaut) are familiar with it. + +3. **Cache efficiency.** Individual platform JARs change only when that platform's binary changes. Unchanged platform JARs are never re-downloaded or re-cached by CI or developer machines. + +4. **No operational dependencies.** Unlike Option 3, no external download service is required at runtime. The artifact is self-contained once resolved by Maven/Gradle. + +5. **Size per platform is acceptable.** At ~20–26 MB compressed per platform, each classifier JAR is well within the range of routinely used native JARs in the Java ecosystem (DJL PyTorch osx-aarch64: 37 MB; ONNX Runtime per platform: ~20–30 MB before bundling). + +6. **Option 3 remains composable.** A download-on-demand fallback can be layered on top of Option 2 for users who prefer it without changing the primary distribution model. The coordination artifact can attempt classpath lookup first, then fall back to a cached download if no matching classifier JAR is present. + +7. See section [How can we do Option 2 and Option 1](#how-can-we-do-option-2-and-option-1) for more details. + +## Binding technology: JNA over Panama FFM + +A secondary decision within the scope of this ADR is *how* the coordination artifact calls the C ABI entry points once the correct `runtime.node` binary has been loaded. Two candidates were considered: [JNA](#references) and the [Foreign Function & Memory API](#references) (FFM, the product of [Project Panama](#references), final since Java 22 via [JEP 454](#references)). + +**Chosen: JNA.** FFM was considered and deliberately deferred, for the following reasons: + +1. **Java baseline.** The SDK supports Java 17, where FFM does not exist (it finalized in Java 22). A JNA-based binding is therefore required regardless; adopting FFM today would mean maintaining two parallel binding implementations, not replacing one with the other. + +2. **Consumer-side configuration burden.** FFM downcalls and upcalls are restricted operations under the JDK's integrity-by-default direction ([JEP 472](#references)). An FFM-based SDK would require every consumer to grant native access explicitly — `--enable-native-access=` (or `ALL-UNNAMED` for classpath applications) on the launcher, or an `Enable-Native-Access` manifest attribute. JNA requires no consumer-side configuration today. For an SDK, this flag becomes every downstream application's problem and a predictable source of support issues. (JNA is on the same enforcement trajectory eventually, as it uses JNI internally; this consideration buys time, not immunity.) + +3. **No realizable performance benefit.** FFM's principal advantage over JNA is the elimination of per-call reflective marshalling overhead. The C ABI surface here is a fixed set of ~12 entry points carrying JSON-RPC strings; JSON serialization/deserialization cost dominates the call path, and call frequency is bounded by agent-interaction rates rather than tight loops. The latency difference between JNA and FFM is expected to be unmeasurable in end-to-end SDK usage. This calculus would change only if the transport moved to a high-frequency or shared-memory framing model. + +4. **Upcall lifetime complexity.** The transport is bidirectional: the runtime delivers JSON-RPC responses and server-initiated requests back into Java from native threads. JNA's `Callback` mechanism handles foreign-thread attachment with well-established semantics. FFM upcall stubs require explicit `Arena` lifetime management, where a stub whose arena is closed while the Rust side still holds the function pointer results in a JVM crash. This shifts lifetime reasoning that JNA encapsulates onto the binding layer. + +5. **GraalVM native-image maturity.** JNA's behavior under GraalVM native-image is well established with mature reachability metadata. FFM support in native-image (particularly for upcalls) is newer and varies by GraalVM release. Plausible SDK consumers (e.g., Quarkus/Micronaut-based CLI tools) compile to native images, so this is a compatibility surface the SDK should not destabilize without verification. + +6. **FFM's safety advantages do not apply to this ABI shape.** FFM's `MemorySegment` bounds and lifetime checking pays off when Java code performs structural manipulation of native memory. This surface passes strings through a fixed transport; there is little structural memory work to make safe. + +### Preserving the FFM migration path + +FFM is regarded as the likely eventual binding technology: the JEP 472 endgame applies enforcement pressure to JNA as well, and a ~12-function stable C ABI makes a future migration inexpensive. To keep that path open at low cost: + +- The binding layer is abstracted behind a small internal interface (native load + downcall + upcall registration), so that an FFM implementation can be introduced later — for example, as a multi-release JAR selecting FFM on Java 22+ — without changes to the transport or API layers. +- The decision should be revisited when (a) the SDK's minimum Java baseline moves past 17, or (b) JDK releases begin enforcing `--illegal-native-access=deny` by default, whichever comes first. + +## How can we do Option 2 and Option 1 + +## How it works: classpath resource convention + platform detection + +### 1. Each classifier JAR uses a well-known resource path + +Each per-platform JAR (`copilot-sdk-java-runtime:VERSION:darwin-arm64`, etc.) places its binary under a deterministic path inside the JAR: + +``` +native/darwin-arm64/runtime.node +native/darwin-arm64/platform.properties +``` + +When `maven-assembly-plugin` creates the uber-jar, it unpacks all dependencies and merges them. The resulting uber-jar contains: + +``` +com/github/copilot/sdk/... (Java classes) +native/linux-x64/runtime.node +native/linux-arm64/runtime.node +native/linuxmusl-x64/runtime.node +native/linuxmusl-arm64/runtime.node +native/darwin-x64/runtime.node +native/darwin-arm64/runtime.node +native/win32-x64/runtime.node +native/win32-arm64/runtime.node +``` + +### 2. The coordination artifact selects at runtime via `getResourceAsStream` + +```java +public class NativeRuntimeLoader { + + public Path loadRuntime() { + String classifier = detectPlatformClassifier(); + String resourcePath = "native/" + classifier + "/runtime.node"; + + try (InputStream in = getClass().getClassLoader() + .getResourceAsStream(resourcePath)) { + if (in == null) { + throw new UnsupportedOperationException( + "No native runtime for platform: " + classifier); + } + Path cached = getCachePath(classifier); + if (!Files.exists(cached)) { + Files.createDirectories(cached.getParent()); + Files.copy(in, cached); + // Make executable on Unix + cached.toFile().setExecutable(true); + } + return cached; + } + } + + private String detectPlatformClassifier() { + String os = normalizeOs(System.getProperty("os.name")); + String arch = normalizeArch(System.getProperty("os.arch")); + String libc = "linux".equals(os) ? detectLinuxLibc() : ""; + + // Produces: "linux-x64", "linuxmusl-arm64", "darwin-arm64", "win32-x64", etc. + return (libc.isEmpty() ? os : os + libc) + "-" + arch; + } + + private String detectLinuxLibc() { + // Read ELF PT_INTERP from /proc/self/exe + // If interpreter contains "/ld-musl-" → "musl" + // Otherwise → "" (glibc is the default/unmarked case for "linux-") + // ... + } + + private Path getCachePath(String classifier) { + String version = getClass().getPackage().getImplementationVersion(); + return Path.of(System.getProperty("user.home"), + ".copilot", "runtime-cache", version, classifier, "runtime.node"); + } +} +``` + +### 3. JNA loads from the extracted path + +Once extracted to a known filesystem path, JNA loads it directly: + +```java +NativeLibrary lib = NativeLibrary.getInstance(extractedPath.toString()); +// Or via a mapped interface: +CopilotRuntime runtime = Native.load(extractedPath.toString(), CopilotRuntime.class); +``` + +### Key insight: the same code works in both modes + +The beauty is that `getResourceAsStream("native/darwin-arm64/runtime.node")` works identically whether: + +- The native lives in a **separate classifier JAR** on the classpath (normal dev dependency), OR +- It's been **merged into an uber-jar** by `maven-assembly-plugin` + +The classloader doesn't care which JAR file the resource came from — it searches the entire classpath. This means **zero code changes** between the two consumption models. + +--- + +## Assembly plugin configuration (consumer-side) + +A consumer building a portable uber-jar would configure: + +```xml + + maven-assembly-plugin + + + jar-with-dependencies + + + +``` + +With all classifier JARs declared as dependencies: + +```xml + + + com.github + copilot-sdk-java + ${copilot.version} + + + + com.github + copilot-sdk-java-runtime + ${copilot.version} + linux-x64 + + + com.github + copilot-sdk-java-runtime + ${copilot.version} + darwin-arm64 + + + +``` + +--- + +## Why this works cleanly + +| Concern | How it's handled | +|---------|-----------------| +| No resource path collisions | Each platform has its own subdirectory (`native//`) | +| Extraction only happens once | Cached to `~/.copilot/runtime-cache///` | +| Works without uber-jar too | Same `getResourceAsStream` call — classloader finds it in the separate JAR | +| Subset selection | Consumer declares only the classifiers they need; missing platforms get a clear error at runtime | +| JNA loading | `NativeLibrary.getInstance(path)` loads from an absolute filesystem path after extraction — no JNA platform-detection magic needed | + +The pattern is identical to how DJL's `LibUtils.loadLibrary()` works — detect platform, construct resource path, extract if needed, load via absolute path. + + +## Consequences + +- A new Maven module (`copilot-sdk-java-runtime` or similar) is introduced to hold the per-platform native JARs. The existing `copilot-sdk-java` coordination artifact depends on it. +- The coordination artifact gains a platform detection and native loading component that: + 1. Detects OS, architecture, and Linux libc variant deterministically as described above. + 2. Locates the matching `runtime.node` binary on the classpath (via `getResourceAsStream` from the classifier JAR). + 3. Extracts the binary to a temporary or cached location (e.g., `~/.copilot/runtime-cache/`) if not already present. + 4. Loads it via [JNA](#references) using the C ABI entry points, per the [binding technology decision](#binding-technology-jna-over-panama-ffm) above. The JNA-specific code is confined behind an internal binding interface to preserve a future FFM migration path. +- The release pipeline for `github/copilot-agent-runtime` must produce the per-platform `runtime.node` binaries as inputs to the Java SDK publish workflow. The per-platform `pkg-tarballs-` artifacts from the `publish-cli.yml` workflow are the authoritative source. +- Each release of `copilot-sdk-java` publishes 6 (or 8) classifier JARs to Maven Central alongside the coordination JAR. +- The version of the bundled `runtime.node` is recorded in the coordination JAR's manifest and queryable at runtime, enabling diagnostics and mismatch detection. +- `cli-native.node` is not bundled. It provides only terminal UI features (ICU4X text segmentation, Win32 APIs, OS desktop notifications) that are irrelevant to the Java SDK's programmatic API surface. + +## Related work items + +- https://github.com/github/copilot-sdk/issues/1917 — Epic: Embed Rust-based Copilot CLI Runtime and cease requiring Node.js +- https://devdiv.visualstudio.com/DevDiv/_workitems/edit/3028097 +- https://github.com/github/copilot-sdk/pull/1901 dotnet: in-process FFI runtime hosting (InProcess transport) +- https://github.com/github/copilot-sdk/pull/1915 Add in-process FFI transport for Rust and TypeScript SDKs + +### References + +| Term | Definition | Link | +|------|------------|------| +| **FFI** (Foreign Function Interface) | A mechanism by which code written in one language can call functions defined in another. In this ADR, Java calls into the Rust runtime shared library via JNA's FFI layer. | https://en.wikipedia.org/wiki/Foreign_function_interface | +| **JNA** (Java Native Access) | A Java library that provides easy access to native shared libraries without requiring the JNI boilerplate. Used here to call the `extern "C"` C ABI entry points exported by `runtime.node`. | https://github.com/java-native-access/jna | +| **napi-rs** | A Rust framework for building native Node.js addons using the Node-API (napi) stable ABI. Produces the `.node` file and generates TypeScript type declarations automatically. | https://napi.rs/ | +| **cdylib** | A Rust `crate-type` that produces a C-compatible dynamic shared library (`.so` / `.dylib` / `.dll`). Distinct from `dylib` (Rust-to-Rust only) and `staticlib`. | https://doc.rust-lang.org/reference/linkage.html | +| **napi (Node-API)** | A stable C ABI provided by Node.js for building native addons that remain binary-compatible across Node.js versions. `napi-rs` generates Rust code against this interface. | https://nodejs.org/api/n-api.html | +| **C ABI** (Application Binary Interface) | The low-level contract between a compiled binary and its callers: calling conventions, data type layouts, symbol naming. An `extern "C"` ABI uses C's conventions, making a library callable from any language that speaks C FFI. | https://en.wikipedia.org/wiki/Application_binary_interface | +| **ELF PT_INTERP** | A segment in an [ELF](https://man7.org/linux/man-pages/man5/elf.5.html) binary (the Linux/Unix executable format) that records the path of the dynamic linker/interpreter. On glibc systems this path is `/lib64/ld-linux-x86-64.so.2`; on musl systems it is `/lib/ld-musl-x86_64.so.1`. Inspecting it is the most reliable way to detect glibc vs. musl at runtime without executing a subprocess. | https://man7.org/linux/man-pages/man5/elf.5.html | +| **glibc** (GNU C Library) | The standard C runtime library on most mainstream Linux distributions (Debian, Ubuntu, RHEL, Fedora, SLES). Binaries linked against glibc require the same version or newer to be present at runtime. The `runtime.node` glibc build requires glibc ≥ 2.28. | https://www.gnu.org/software/libc/ | +| **musl libc** | An alternative C standard library optimised for static linking and used as the default libc on Alpine Linux. Not binary-compatible with glibc; a separate `runtime.node` build is required. | https://musl.libc.org/ | +| **MSVC CRT** (Microsoft Visual C++ Runtime) | The C runtime library shipped with Visual Studio. When compiled with `+crt-static` (as `runtime.node` is on Windows), it is statically linked into the binary and the end-user does not need to install the Visual C++ Redistributable. | https://learn.microsoft.com/en-us/cpp/c-runtime-library/c-run-time-library-reference | +| **Project Panama** | The OpenJDK project that produced the Foreign Function & Memory API as the modern, supported replacement for JNI-based native interop. | https://openjdk.org/projects/panama/ | +| **FFM** (Foreign Function & Memory API) | The `java.lang.foreign` API for calling native functions and managing native memory from Java, finalized in Java 22. Considered and deferred as the binding technology for this SDK; see [Binding technology](#binding-technology-jna-over-panama-ffm). | https://docs.oracle.com/en/java/javase/22/core/foreign-function-and-memory-api.html | +| **JEP 454** | The JDK Enhancement Proposal that finalized the FFM API in Java 22. | https://openjdk.org/jeps/454 | +| **JEP 472** | "Prepare to Restrict the Use of JNI" — part of the JDK's integrity-by-default direction under which native access (via JNI or FFM) requires explicit consumer opt-in (`--enable-native-access`). Drives both the FFM configuration-burden concern and the expectation that JNA itself will eventually require the same opt-in. | https://openjdk.org/jeps/472 | +| **DJL** (Deep Java Library) | Amazon's open-source Java framework for ML inference, used here as a reference for the per-platform classifier JAR distribution pattern. Its PyTorch native artifacts (`pytorch-native-cpu-*-.jar`) are the direct model for the proposed `copilot-sdk-java-runtime:VERSION:` artifacts. | https://djl.ai/ | +| **os-maven-plugin** | A Maven extension that detects the current OS and architecture and exposes them as properties (e.g., `${os.detected.classifier}`) so that `` values can be resolved at build time rather than hardcoded. | https://github.com/trustin/os-maven-plugin | +| **ONNX Runtime** | Microsoft's cross-platform ML inference runtime, used in this ADR as the size comparable for a monolithic all-platform JAR (~130 MB, Option 1). | https://onnxruntime.ai/ | + +Additional source references: + +- DJL native distribution pattern: https://github.com/deepjavalibrary/djl/tree/master/engines/pytorch/pytorch-native +- DJL `Platform.fromSystem()` (OS/arch detection): https://github.com/deepjavalibrary/djl/blob/master/api/src/main/java/ai/djl/util/Platform.java +- `detect-libc` npm package (ELF PT_INTERP libc detection): https://github.com/lovell/detect-libc +- `github/copilot-agent-runtime` C ABI front door (`cabi.rs`): `src/runtime/src/interop/cabi.rs` +- `github/copilot-agent-runtime` build target definitions: `script/build-runtime.ts` +- `github/copilot-agent-runtime` glibc sysroot and verification: `script/linux/install-sysroot.cjs`, `script/linux/verify-glibc-requirements.sh` +- ONNX Runtime Java on Maven Central (size comparable): https://repo1.maven.org/maven2/com/microsoft/onnxruntime/onnxruntime/1.21.0/ + diff --git a/java/jbang-example.java b/java/jbang-example.java index 971a6006cc..db49adf4cd 100644 --- a/java/jbang-example.java +++ b/java/jbang-example.java @@ -1,5 +1,5 @@ ///usr/bin/env jbang "$0" "$@" ; exit $? -//DEPS com.github:copilot-sdk-java:1.0.4 +//DEPS com.github:copilot-sdk-java:1.0.7-01 import com.github.copilot.CopilotClient; import com.github.copilot.generated.AssistantMessageEvent; import com.github.copilot.generated.SessionUsageInfoEvent; diff --git a/java/mvnw b/java/mvnw old mode 100644 new mode 100755 diff --git a/java/pom.xml b/java/pom.xml index 9cba6df463..ac95090b8b 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -7,7 +7,7 @@ com.github copilot-sdk-java - 1.0.5-SNAPSHOT + 1.0.8-SNAPSHOT jar GitHub Copilot SDK :: Java @@ -86,7 +86,7 @@ DO NOT EDIT MANUALLY. Updated by the update-copilot-dependency workflow. --> - ^1.0.65 + ^1.0.71 diff --git a/java/scripts/codegen/java.ts b/java/scripts/codegen/java.ts index c30836f7ac..1e5ff1d543 100644 --- a/java/scripts/codegen/java.ts +++ b/java/scripts/codegen/java.ts @@ -21,6 +21,12 @@ const REPO_ROOT = path.resolve(__dirname, "../.."); /** Event types to exclude from generation (internal/legacy types) */ const EXCLUDED_EVENT_TYPES = new Set(["session.import_legacy"]); +function isSchemaInternal(schema: JSONSchema7 | null | undefined): boolean { + return typeof schema === "object" && + schema !== null && + (schema as Record).visibility === "internal"; +} + const AUTO_GENERATED_HEADER = `// AUTO-GENERATED FILE - DO NOT EDIT`; const GENERATED_FROM_SESSION_EVENTS = `// Generated from: session-events.schema.json`; const GENERATED_FROM_API = `// Generated from: api.schema.json`; @@ -725,7 +731,7 @@ function extractEventVariants(schema: JSONSchema7): EventVariant[] { deprecated: (variant as unknown as Record).deprecated === true, }; }) - .filter((v) => !EXCLUDED_EVENT_TYPES.has(v.typeName)); + .filter((v) => !EXCLUDED_EVENT_TYPES.has(v.typeName) && !isSchemaInternal(v.dataSchema)); } async function generateSessionEvents(schemaPath: string): Promise { @@ -1315,6 +1321,7 @@ async function generateRpcTypes(schemaPath: string): Promise { server?: Record; session?: Record; clientSession?: Record; + clientGlobal?: Record; definitions?: Record; }; @@ -1343,18 +1350,28 @@ async function generateRpcTypes(schemaPath: string): Promise { if (schema.server) sections.push(["server", schema.server]); if (schema.session) sections.push(["session", schema.session]); if (schema.clientSession) sections.push(["clientSession", schema.clientSession]); + if (schema.clientGlobal) sections.push(["clientGlobal", schema.clientGlobal]); const generatedClasses = new Map(); const allFiles: string[] = []; - for (const [, sectionNode] of sections) { + for (const [sectionName, sectionNode] of sections) { const methods = collectRpcMethods(sectionNode); for (const [, method] of methods) { const className = rpcMethodToClassName(method.rpcMethod); // Generate params class — resolve $ref if params is a reference let paramsSchema = method.params as JSONSchema7 | null; - if (paramsSchema?.$ref) paramsSchema = resolveRef(paramsSchema) as JSONSchema7; + const paramsRefName = extractRefName(paramsSchema); + if (paramsRefName && sectionName === "clientGlobal") { + const resolvedParamsSchema = resolveRef(paramsSchema ?? undefined); + if (resolvedParamsSchema?.type === "object" && resolvedParamsSchema.properties) { + pendingStandaloneTypes.set(paramsRefName, resolvedParamsSchema); + } + paramsSchema = null; + } else if (paramsSchema?.$ref) { + paramsSchema = resolveRef(paramsSchema) as JSONSchema7; + } if (paramsSchema && typeof paramsSchema === "object" && paramsSchema.properties) { const paramsClassName = `${className}Params`; if (!generatedClasses.has(paramsClassName)) { @@ -1368,7 +1385,11 @@ async function generateRpcTypes(schemaPath: string): Promise { const resultRefName = extractRefName(resultSchema); if (resultSchema?.$ref) resultSchema = resolveRef(resultSchema) as JSONSchema7; if (resultSchema && typeof resultSchema === "object") { - if (resultSchema.properties && Object.keys(resultSchema.properties).length > 0) { + if ( + resultSchema.properties && + (Object.keys(resultSchema.properties).length > 0 || + (resultRefName && sectionName === "clientGlobal")) + ) { // Object with properties → generate a record class const resultClassName = `${className}Result`; if (!generatedClasses.has(resultClassName)) { @@ -1636,15 +1657,16 @@ function addWrapperResultImports(resultType: string, allImports: Set, pa } /** - * Return the params class name if the method has a params schema with properties - * other than sessionId (i.e. there are user-supplied parameters). + * Return the params class name if the method has a params schema with user-supplied properties. + * Session-scoped wrappers inject sessionId automatically, but server-scoped wrappers must let + * callers supply it explicitly. */ -function wrapperParamsClassName(method: RpcMethodNode): string | null { +function wrapperParamsClassName(method: RpcMethodNode, isSession: boolean): string | null { let params = method.params; if (params?.$ref) params = resolveRef(params) as JSONSchema7; if (!params || typeof params !== "object") return null; const props = params.properties ?? {}; - const userProps = Object.keys(props).filter((k) => k !== "sessionId"); + const userProps = Object.keys(props).filter((k) => !isSession || k !== "sessionId"); if (userProps.length === 0) return null; return rpcMethodToClassName(method.rpcMethod) + "Params"; } @@ -1667,7 +1689,7 @@ function generateApiMethod( sessionIdExpr: string ): { lines: string[]; needsMapper: boolean; needsExperimentalImport: boolean } { const resultClass = wrapperResultClassName(method); - const paramsClass = wrapperParamsClassName(method); + const paramsClass = wrapperParamsClassName(method, isSession); const hasSessionId = methodHasSessionId(method); const hasExtraParams = paramsClass !== null; let needsMapper = false; @@ -1775,7 +1797,7 @@ async function generateNamespaceApiFile( const methodLines: string[] = []; for (const [key, method] of tree.methods) { const resultClass = wrapperResultClassName(method); - const paramsClass = wrapperParamsClassName(method); + const paramsClass = wrapperParamsClassName(method, isSession); addWrapperResultImports(resultClass, allImports, packageName); if (paramsClass) allImports.add(`${packageName}.${paramsClass}`); @@ -1895,7 +1917,7 @@ async function generateRpcRootFile( const methodLines: string[] = []; for (const [key, method] of tree.methods) { const resultClass = wrapperResultClassName(method); - const paramsClass = wrapperParamsClassName(method); + const paramsClass = wrapperParamsClassName(method, isSession); addWrapperResultImports(resultClass, allImports, packageName); if (paramsClass) allImports.add(`${packageName}.${paramsClass}`); diff --git a/java/scripts/codegen/package-lock.json b/java/scripts/codegen/package-lock.json index 510d094976..372e3daab5 100644 --- a/java/scripts/codegen/package-lock.json +++ b/java/scripts/codegen/package-lock.json @@ -6,9 +6,9 @@ "": { "name": "copilot-sdk-java-codegen", "dependencies": { - "@github/copilot": "^1.0.65", + "@github/copilot": "^1.0.71", "json-schema": "^0.4.0", - "tsx": "^4.22.4" + "tsx": "^4.23.1" } }, "node_modules/@esbuild/aix-ppc64": { @@ -428,9 +428,9 @@ } }, "node_modules/@github/copilot": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.65.tgz", - "integrity": "sha512-J1XvLuOiVpiAi/E1MBICBymszCgdGLnZxokosXzGcmcjEVZd+QSDoW/kPRHq6oEyBT9SDASPcjCEZ9Q0rLJllg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.71.tgz", + "integrity": "sha512-F3axBi+sXSLYDJbxCBW36bM6MYKNC2rlyAf3Ivo/MjiHKKJW7j5AmaR1IRYS9Gt8r9mxOwWFM1cJFA+CuLaR8g==", "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "detect-libc": "^2.1.2" @@ -439,20 +439,20 @@ "copilot": "npm-loader.js" }, "optionalDependencies": { - "@github/copilot-darwin-arm64": "1.0.65", - "@github/copilot-darwin-x64": "1.0.65", - "@github/copilot-linux-arm64": "1.0.65", - "@github/copilot-linux-x64": "1.0.65", - "@github/copilot-linuxmusl-arm64": "1.0.65", - "@github/copilot-linuxmusl-x64": "1.0.65", - "@github/copilot-win32-arm64": "1.0.65", - "@github/copilot-win32-x64": "1.0.65" + "@github/copilot-darwin-arm64": "1.0.71", + "@github/copilot-darwin-x64": "1.0.71", + "@github/copilot-linux-arm64": "1.0.71", + "@github/copilot-linux-x64": "1.0.71", + "@github/copilot-linuxmusl-arm64": "1.0.71", + "@github/copilot-linuxmusl-x64": "1.0.71", + "@github/copilot-win32-arm64": "1.0.71", + "@github/copilot-win32-x64": "1.0.71" } }, "node_modules/@github/copilot-darwin-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.65.tgz", - "integrity": "sha512-NFc4xIstZNiIuAYkurQT5DVtbZjBoZ/z6yt/Ffcom7Y5QGjfpN4BFuekv9k+OADRioxxR99NgmhjbuNPWtQhNQ==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.71.tgz", + "integrity": "sha512-mEWzyqbqRAWgyU7i2uuSRoVPx/TwaFQX0nZmw0bc30aJ0BnO7cy2kYQyCHw8ykmf/tfxT0xauZ6k0BOFmWizzQ==", "cpu": [ "arm64" ], @@ -466,9 +466,9 @@ } }, "node_modules/@github/copilot-darwin-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.65.tgz", - "integrity": "sha512-0wtV22KmTa12VbqWRRkgvJcBz/oIbszfcIpyDWGc4MzbCVksajQ3TWVQ6c7Sdzj5RifCaYdkHAX2zuIYXYlLoQ==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.71.tgz", + "integrity": "sha512-Md9yEg406OBVBx3w4PeEj62TubulVLBcHleqmCoOoUmPgUxPZotUbrqz3rtbzADbXfrrD7JWvVsbd2UiNL194w==", "cpu": [ "x64" ], @@ -482,9 +482,9 @@ } }, "node_modules/@github/copilot-linux-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.65.tgz", - "integrity": "sha512-dOwdy/YbTXQN/+x2v4ZgiDycdRtWElyHxPuA6ail3yJDt0nagwn8OYAA/diBLPMAJuuBXiOZGvvb9fGRuh7Xgg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.71.tgz", + "integrity": "sha512-ykLJYOqBj3jRB5IJCDugLClAqbr7DmtTbUjlNY7+Jdq/n6i+d7xUQGclf1IWL5gnxbGQVAf+zkToD+sRM389Kg==", "cpu": [ "arm64" ], @@ -498,9 +498,9 @@ } }, "node_modules/@github/copilot-linux-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.65.tgz", - "integrity": "sha512-al/1a/l/GrpHtygTxt7PZspmv0eHBPdAZ5B31J7Hv/GRdVZM4STCC9dCIOSUFsOX2fhaKD8yLfz4HureSYs23g==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.71.tgz", + "integrity": "sha512-pC0FNHG+BBwZd6yZlM85kkAGN+uJhM6o+THi76N2GnnSxmw7+remb1mvYxdgRVbdCm+LBUIbCKRWJLuMwrfb6A==", "cpu": [ "x64" ], @@ -514,9 +514,9 @@ } }, "node_modules/@github/copilot-linuxmusl-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.65.tgz", - "integrity": "sha512-xccQeJSR45xyoaL7J5mZjtU++dmte+ZCDQkIlrpTn2yuMl2LWriBvorQ1P2MwVnXmIiW/GHi93B+lNtsybA9yw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.71.tgz", + "integrity": "sha512-hBmDljFTjacxqZTasCEy43H8EIzuXB/hHEBBCMFjhB9J00nIxsO6Dh0woTifKpx7knTYZdpTjjca3D0pAoZlUA==", "cpu": [ "arm64" ], @@ -530,9 +530,9 @@ } }, "node_modules/@github/copilot-linuxmusl-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.65.tgz", - "integrity": "sha512-RHPVUaqjSrhKHQ2EpfGKWErnV+R5elGIZaHXPKO10zpSaQD9b/C9u6nLigZnBuT/8sCaJpVrazPMwOYvYA62aw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.71.tgz", + "integrity": "sha512-CfTXU8pa5dxRz22xQzoi3TiG1PJo9+WR8PRDiPSdkIBSyPJ1NvX87DJmfXjTgeAfR+wkjt/p0keDCaBBVhNmUA==", "cpu": [ "x64" ], @@ -546,9 +546,9 @@ } }, "node_modules/@github/copilot-win32-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.65.tgz", - "integrity": "sha512-/vSE/t9Wm3eFSWpxlKyn/oL8OAVOB0yFO7ECxhgbtiqNrBd1tgpYh1k7IXBIWa/saxlV1+de6DEmPuQfx3Z0bg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.71.tgz", + "integrity": "sha512-+HI1DokixXhHUahj06Fw67ZAigBuXKC58BFma4UJOGrQsDgwOSbqeTQHCw6vuymzjKlg3sactfsCUTaefkjscQ==", "cpu": [ "arm64" ], @@ -562,9 +562,9 @@ } }, "node_modules/@github/copilot-win32-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.65.tgz", - "integrity": "sha512-wjVWXepET+SpFg8z8V43ZiTy6X1OerCb7yu3QZKNNJ3zY9z20goihPXQCDWkiJpGzszNSgfrsiqUzpUsC9qS0A==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.71.tgz", + "integrity": "sha512-02kXOBd9CwBbCaztuf71WYWn+uGapCuiaasomN4tcMH3HBVZ4gi3J0ZUoRcgcS80xh81uQyeBHbnUKzb/RE/9A==", "cpu": [ "x64" ], @@ -648,9 +648,9 @@ "license": "(AFL-2.1 OR BSD-3-Clause)" }, "node_modules/tsx": { - "version": "4.22.4", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz", - "integrity": "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==", + "version": "4.23.1", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz", + "integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==", "license": "MIT", "dependencies": { "esbuild": "~0.28.0" diff --git a/java/scripts/codegen/package.json b/java/scripts/codegen/package.json index 53d5b3ebab..32c609be41 100644 --- a/java/scripts/codegen/package.json +++ b/java/scripts/codegen/package.json @@ -7,8 +7,8 @@ "generate:java": "tsx java.ts" }, "dependencies": { - "@github/copilot": "^1.0.65", + "@github/copilot": "^1.0.71", "json-schema": "^0.4.0", - "tsx": "^4.22.4" + "tsx": "^4.23.1" } } diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantIdleEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantIdleEvent.java new file mode 100644 index 0000000000..3b79b8d50e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/AssistantIdleEvent.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "assistant.idle". Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AssistantIdleEvent extends SessionEvent { + + @Override + public String getType() { return "assistant.idle"; } + + @JsonProperty("data") + private AssistantIdleEventData data; + + public AssistantIdleEventData getData() { return data; } + public void setData(AssistantIdleEventData data) { this.data = data; } + + /** Data payload for {@link AssistantIdleEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record AssistantIdleEventData( + /** True when the preceding agentic loop was cancelled via abort signal */ + @JsonProperty("aborted") Boolean aborted + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java index e4680a54ce..fdbdc0afd7 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java @@ -47,6 +47,8 @@ public record AssistantMessageEventData( @JsonProperty("reasoningOpaque") String reasoningOpaque, /** Readable reasoning text from the model's extended thinking */ @JsonProperty("reasoningText") String reasoningText, + /** OpenAI-compatible wire field the provider used for reasoning (e.g. reasoning_content/reasoning). Populated only when non-canonical, so the dialect round-trips across turns. */ + @JsonProperty("reasoningWireField") String reasoningWireField, /** Encrypted reasoning content from OpenAI models. Session-bound and stripped on resume. */ @JsonProperty("encryptedContent") String encryptedContent, /** Generation phase for phased-output models (e.g., thinking vs. response phases) */ @@ -57,6 +59,8 @@ public record AssistantMessageEventData( @JsonProperty("interactionId") String interactionId, /** GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs */ @JsonProperty("requestId") String requestId, + /** Client-minted request id (x-request-id header) echoed by the server. Distinct from requestId (x-github-request-id) and serviceRequestId (x-copilot-service-request-id). */ + @JsonProperty("clientRequestId") String clientRequestId, /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */ @JsonProperty("serviceRequestId") String serviceRequestId, /** Provider's completion / response identifier; shared across all chunks of a single API call. Used to group multi-chunk assistant utterances. */ diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantServerToolProgressEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantServerToolProgressEvent.java new file mode 100644 index 0000000000..462a573b3e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/AssistantServerToolProgressEvent.java @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "assistant.server_tool_progress". Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AssistantServerToolProgressEvent extends SessionEvent { + + @Override + public String getType() { return "assistant.server_tool_progress"; } + + @JsonProperty("data") + private AssistantServerToolProgressEventData data; + + public AssistantServerToolProgressEventData getData() { return data; } + public void setData(AssistantServerToolProgressEventData data) { this.data = data; } + + /** Data payload for {@link AssistantServerToolProgressEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record AssistantServerToolProgressEventData( + /** Position of the hosted tool call in the response output. Stable across the call's lifecycle events (unlike the provider's per-event item id, which CAPI rotates), so the host keys the live in-progress row on it. */ + @JsonProperty("outputIndex") Long outputIndex, + /** Kind of hosted server tool that is running. Only `web_search` is emitted today. */ + @JsonProperty("kind") String kind, + /** Lifecycle status of the hosted call: `in_progress`, `searching`, or `completed`. */ + @JsonProperty("status") String status + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantToolCallDeltaEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantToolCallDeltaEvent.java new file mode 100644 index 0000000000..72b629c0c6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/AssistantToolCallDeltaEvent.java @@ -0,0 +1,47 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "assistant.tool_call_delta". Streaming tool-call input delta for incremental tool-call updates + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AssistantToolCallDeltaEvent extends SessionEvent { + + @Override + public String getType() { return "assistant.tool_call_delta"; } + + @JsonProperty("data") + private AssistantToolCallDeltaEventData data; + + public AssistantToolCallDeltaEventData getData() { return data; } + public void setData(AssistantToolCallDeltaEventData data) { this.data = data; } + + /** Data payload for {@link AssistantToolCallDeltaEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record AssistantToolCallDeltaEventData( + /** Tool call ID this delta belongs to, matching the corresponding assistant.message tool request */ + @JsonProperty("toolCallId") String toolCallId, + /** Name of the tool being invoked, when known from the stream */ + @JsonProperty("toolName") String toolName, + /** Tool call type, when known from the stream */ + @JsonProperty("toolType") AssistantMessageToolRequestType toolType, + /** Raw provider tool input fragment to append for this tool call. Function/tool-use providers stream serialized JSON argument text (so newlines inside JSON string values may appear as escaped `\n` until the accumulated JSON is parsed); custom tool calls stream raw custom input. */ + @JsonProperty("inputDelta") String inputDelta + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantTurnEndEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantTurnEndEvent.java index 28146b05bb..082f62b476 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantTurnEndEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantTurnEndEvent.java @@ -35,7 +35,9 @@ public final class AssistantTurnEndEvent extends SessionEvent { @JsonInclude(JsonInclude.Include.NON_NULL) public record AssistantTurnEndEventData( /** Identifier of the turn that has ended, matching the corresponding assistant.turn_start event */ - @JsonProperty("turnId") String turnId + @JsonProperty("turnId") String turnId, + /** Model identifier used for this turn, when known */ + @JsonProperty("model") String model ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantTurnStartEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantTurnStartEvent.java index 639ee013f4..a9c6b2932d 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantTurnStartEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantTurnStartEvent.java @@ -36,6 +36,8 @@ public final class AssistantTurnStartEvent extends SessionEvent { public record AssistantTurnStartEventData( /** Identifier for this turn within the agentic loop, typically a stringified turn number */ @JsonProperty("turnId") String turnId, + /** Model identifier used for this turn, when known */ + @JsonProperty("model") String model, /** CAPI interaction ID for correlating this turn with upstream telemetry */ @JsonProperty("interactionId") String interactionId ) { diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java index 72953adc49..62cf9cfe85 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java @@ -52,7 +52,7 @@ public record AssistantUsageEventData( /** Duration of the API call in milliseconds */ @JsonProperty("duration") Long duration, /** Time to first token in milliseconds. Only available for streaming requests */ - @JsonProperty("timeToFirstTokenMs") Long timeToFirstTokenMs, + @JsonProperty("timeToFirstTokenMs") Double timeToFirstTokenMs, /** Average inter-token latency in milliseconds. Only available for streaming requests */ @JsonProperty("interTokenLatencyMs") Double interTokenLatencyMs, /** What initiated this API call (e.g., "sub-agent", "mcp-sampling"); absent for user-initiated calls */ diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantUsageQuotaSnapshot.java b/java/src/generated/java/com/github/copilot/generated/AssistantUsageQuotaSnapshot.java index 974a7f272c..f32dacdee8 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantUsageQuotaSnapshot.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantUsageQuotaSnapshot.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `AssistantUsageQuotaSnapshot` type. + * Internal per-quota snapshot for assistant usage, including entitlement, consumed requests, overage, reset date, and remaining quota. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/AutoModeResolvedReasoningBucket.java b/java/src/generated/java/com/github/copilot/generated/AutoModeResolvedReasoningBucket.java new file mode 100644 index 0000000000..3034b0bf16 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/AutoModeResolvedReasoningBucket.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Coarse request-difficulty bucket for UX explainability + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum AutoModeResolvedReasoningBucket { + /** The {@code low} variant. */ + LOW("low"), + /** The {@code medium} variant. */ + MEDIUM("medium"), + /** The {@code high} variant. */ + HIGH("high"); + + private final String value; + AutoModeResolvedReasoningBucket(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static AutoModeResolvedReasoningBucket fromValue(String value) { + for (AutoModeResolvedReasoningBucket v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown AutoModeResolvedReasoningBucket value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvas.java b/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvas.java index b4805b0bbb..12518491e8 100644 --- a/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvas.java +++ b/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvas.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `CanvasRegistryChangedCanvas` type. + * A single canvas declaration in `session.canvas.registry_changed`, including provider IDs, display metadata, input schema, and actions. * * @since 1.0.0 */ @@ -32,6 +32,8 @@ public record CanvasRegistryChangedCanvas( @JsonProperty("displayName") String displayName, /** Short, single-sentence description shown to the agent in canvas catalogs. */ @JsonProperty("description") String description, + /** Host-local PNG path for the canvas icon, when supplied */ + @JsonProperty("icon") String icon, /** JSON Schema for canvas open input */ @JsonProperty("inputSchema") Object inputSchema, /** Actions the agent or host may invoke */ diff --git a/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvasAction.java b/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvasAction.java index b8e474e62c..99c390efb2 100644 --- a/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvasAction.java +++ b/java/src/generated/java/com/github/copilot/generated/CanvasRegistryChangedCanvasAction.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `CanvasRegistryChangedCanvasAction` type. + * A single action within a canvas declaration, with its name, optional description, and optional input schema. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/CommandsChangedCommand.java b/java/src/generated/java/com/github/copilot/generated/CommandsChangedCommand.java index 383f141fcb..76a30b920b 100644 --- a/java/src/generated/java/com/github/copilot/generated/CommandsChangedCommand.java +++ b/java/src/generated/java/com/github/copilot/generated/CommandsChangedCommand.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `CommandsChangedCommand` type. + * A single slash command available in the session, as listed by the `commands.changed` event. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/CustomAgentsUpdatedAgent.java b/java/src/generated/java/com/github/copilot/generated/CustomAgentsUpdatedAgent.java index 642be86944..c2f195e486 100644 --- a/java/src/generated/java/com/github/copilot/generated/CustomAgentsUpdatedAgent.java +++ b/java/src/generated/java/com/github/copilot/generated/CustomAgentsUpdatedAgent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `CustomAgentsUpdatedAgent` type. + * A single loaded custom agent in `session.custom_agents_updated`, with identity, source, tools, invocability, and model override. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ExtensionsLoadedExtension.java b/java/src/generated/java/com/github/copilot/generated/ExtensionsLoadedExtension.java index b45c72139d..d8c65f4555 100644 --- a/java/src/generated/java/com/github/copilot/generated/ExtensionsLoadedExtension.java +++ b/java/src/generated/java/com/github/copilot/generated/ExtensionsLoadedExtension.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ExtensionsLoadedExtension` type. + * A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/HeaderEntry.java b/java/src/generated/java/com/github/copilot/generated/HeaderEntry.java new file mode 100644 index 0000000000..14828d32e3 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/HeaderEntry.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Single HTTP header entry as a name/value pair. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record HeaderEntry( + /** HTTP response header name as observed by the runtime. */ + @JsonProperty("name") String name, + /** HTTP response header value as observed by the runtime. */ + @JsonProperty("value") String value +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/ManagedSettingsResolvedSource.java b/java/src/generated/java/com/github/copilot/generated/ManagedSettingsResolvedSource.java new file mode 100644 index 0000000000..1ffa100635 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/ManagedSettingsResolvedSource.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Which channel supplied the effective enterprise managed settings (highest-authority present layer wins wholesale) + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum ManagedSettingsResolvedSource { + /** The {@code server} variant. */ + SERVER("server"), + /** The {@code device} variant. */ + DEVICE("device"), + /** The {@code none} variant. */ + NONE("none"); + + private final String value; + ManagedSettingsResolvedSource(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static ManagedSettingsResolvedSource fromValue(String value) { + for (ManagedSettingsResolvedSource v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown ManagedSettingsResolvedSource value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMeta.java b/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMeta.java index 33b9a3725b..335f3694ad 100644 --- a/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMeta.java +++ b/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMeta.java @@ -21,7 +21,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record McpAppToolCallCompleteToolMeta( - /** Schema for the `McpAppToolCallCompleteToolMetaUI` type. */ + /** MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. */ @JsonProperty("ui") McpAppToolCallCompleteToolMetaUI ui ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMetaUI.java b/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMetaUI.java index eb960434ad..47708eaaa2 100644 --- a/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMetaUI.java +++ b/java/src/generated/java/com/github/copilot/generated/McpAppToolCallCompleteToolMetaUI.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `McpAppToolCallCompleteToolMetaUI` type. + * MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshCompletedEvent.java b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshCompletedEvent.java new file mode 100644 index 0000000000..a3ba903aea --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshCompletedEvent.java @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "mcp.headers_refresh_completed". MCP headers refresh request completion notification + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class McpHeadersRefreshCompletedEvent extends SessionEvent { + + @Override + public String getType() { return "mcp.headers_refresh_completed"; } + + @JsonProperty("data") + private McpHeadersRefreshCompletedEventData data; + + public McpHeadersRefreshCompletedEventData getData() { return data; } + public void setData(McpHeadersRefreshCompletedEventData data) { this.data = data; } + + /** Data payload for {@link McpHeadersRefreshCompletedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record McpHeadersRefreshCompletedEventData( + /** Request ID of the resolved headers refresh request */ + @JsonProperty("requestId") String requestId, + /** How the pending MCP headers refresh request resolved. */ + @JsonProperty("outcome") McpHeadersRefreshCompletedOutcome outcome + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshCompletedOutcome.java b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshCompletedOutcome.java new file mode 100644 index 0000000000..7980dd0a67 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshCompletedOutcome.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * How the pending MCP headers refresh request resolved. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum McpHeadersRefreshCompletedOutcome { + /** The {@code headers} variant. */ + HEADERS("headers"), + /** The {@code none} variant. */ + NONE("none"), + /** The {@code timeout} variant. */ + TIMEOUT("timeout"); + + private final String value; + McpHeadersRefreshCompletedOutcome(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static McpHeadersRefreshCompletedOutcome fromValue(String value) { + for (McpHeadersRefreshCompletedOutcome v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown McpHeadersRefreshCompletedOutcome value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshRequiredEvent.java b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshRequiredEvent.java new file mode 100644 index 0000000000..d8774bb326 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshRequiredEvent.java @@ -0,0 +1,47 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "mcp.headers_refresh_required". Dynamic headers refresh request for a remote MCP server + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class McpHeadersRefreshRequiredEvent extends SessionEvent { + + @Override + public String getType() { return "mcp.headers_refresh_required"; } + + @JsonProperty("data") + private McpHeadersRefreshRequiredEventData data; + + public McpHeadersRefreshRequiredEventData getData() { return data; } + public void setData(McpHeadersRefreshRequiredEventData data) { this.data = data; } + + /** Data payload for {@link McpHeadersRefreshRequiredEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record McpHeadersRefreshRequiredEventData( + /** Unique identifier for this headers refresh request; used to respond via session.mcp.headers.handlePendingHeadersRefreshRequest() */ + @JsonProperty("requestId") String requestId, + /** Display name of the remote MCP server requesting headers */ + @JsonProperty("serverName") String serverName, + /** URL of the remote MCP server requesting headers */ + @JsonProperty("serverUrl") String serverUrl, + /** Why dynamic headers are being requested. */ + @JsonProperty("reason") McpHeadersRefreshRequiredReason reason + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshRequiredReason.java b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshRequiredReason.java new file mode 100644 index 0000000000..86c8f8b2d6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpHeadersRefreshRequiredReason.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Why dynamic headers are being requested. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum McpHeadersRefreshRequiredReason { + /** The {@code startup} variant. */ + STARTUP("startup"), + /** The {@code ttl-expired} variant. */ + TTL_EXPIRED("ttl-expired"), + /** The {@code auth-failed} variant. */ + AUTH_FAILED("auth-failed"); + + private final String value; + McpHeadersRefreshRequiredReason(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static McpHeadersRefreshRequiredReason fromValue(String value) { + for (McpHeadersRefreshRequiredReason v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown McpHeadersRefreshRequiredReason value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpOauthHttpResponse.java b/java/src/generated/java/com/github/copilot/generated/McpOauthHttpResponse.java new file mode 100644 index 0000000000..bed8e0ac62 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpOauthHttpResponse.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record McpOauthHttpResponse( + /** HTTP status code returned with the auth challenge. */ + @JsonProperty("statusCode") Long statusCode, + /** HTTP response headers as observed by the runtime. Order and casing are transport-dependent, and duplicate header names may appear multiple times. */ + @JsonProperty("headers") List headers, + /** Complete UTF-8 response body for host-specific challenge handling, including an empty string for an empty body. Omitted when the complete body is not valid UTF-8; body read failures fail the HTTP operation rather than exposing a partial response. */ + @JsonProperty("body") String body +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpOauthRequestReason.java b/java/src/generated/java/com/github/copilot/generated/McpOauthRequestReason.java new file mode 100644 index 0000000000..2a6eec7063 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpOauthRequestReason.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Reason the runtime is requesting host-provided MCP OAuth credentials + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum McpOauthRequestReason { + /** The {@code initial} variant. */ + INITIAL("initial"), + /** The {@code refresh} variant. */ + REFRESH("refresh"), + /** The {@code reauth} variant. */ + REAUTH("reauth"), + /** The {@code upscope} variant. */ + UPSCOPE("upscope"); + + private final String value; + McpOauthRequestReason(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static McpOauthRequestReason fromValue(String value) { + for (McpOauthRequestReason v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown McpOauthRequestReason value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredEvent.java b/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredEvent.java index 3f6ef8ef60..f21f84cd4b 100644 --- a/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredEvent.java @@ -44,8 +44,12 @@ public record McpOauthRequiredEventData( @JsonProperty("staticClientConfig") McpOauthRequiredStaticClientConfig staticClientConfig, /** OAuth WWW-Authenticate parameters parsed from the auth challenge, if available */ @JsonProperty("wwwAuthenticateParams") McpOauthWWWAuthenticateParams wwwAuthenticateParams, + /** Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. Header order and casing are transport-dependent, and duplicate header names may appear multiple times. */ + @JsonProperty("httpResponse") McpOauthHttpResponse httpResponse, /** Raw OAuth protected-resource metadata document fetched for the MCP server, if available */ - @JsonProperty("resourceMetadata") String resourceMetadata + @JsonProperty("resourceMetadata") String resourceMetadata, + /** Why the runtime is requesting host-provided OAuth credentials. */ + @JsonProperty("reason") McpOauthRequestReason reason ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredStaticClientConfig.java b/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredStaticClientConfig.java index 764f8b7fc8..5f42ec90c4 100644 --- a/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredStaticClientConfig.java +++ b/java/src/generated/java/com/github/copilot/generated/McpOauthRequiredStaticClientConfig.java @@ -23,6 +23,8 @@ public record McpOauthRequiredStaticClientConfig( /** OAuth client ID for the server */ @JsonProperty("clientId") String clientId, + /** Optional OAuth client secret for confidential static clients, when the runtime can resolve one */ + @JsonProperty("clientSecret") String clientSecret, /** Whether this is a public OAuth client */ @JsonProperty("publicClient") Boolean publicClient, /** Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). */ diff --git a/java/src/generated/java/com/github/copilot/generated/McpOauthWWWAuthenticateParams.java b/java/src/generated/java/com/github/copilot/generated/McpOauthWWWAuthenticateParams.java index faa08e1e89..3e1fdb0d10 100644 --- a/java/src/generated/java/com/github/copilot/generated/McpOauthWWWAuthenticateParams.java +++ b/java/src/generated/java/com/github/copilot/generated/McpOauthWWWAuthenticateParams.java @@ -21,7 +21,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record McpOauthWWWAuthenticateParams( - /** Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter */ + /** Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter, if present */ @JsonProperty("resourceMetadataUrl") String resourceMetadataUrl, /** Requested OAuth scopes from the WWW-Authenticate scope parameter, if present */ @JsonProperty("scope") String scope, diff --git a/java/src/generated/java/com/github/copilot/generated/McpPromptsListChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/McpPromptsListChangedEvent.java new file mode 100644 index 0000000000..805328d3c1 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpPromptsListChangedEvent.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "mcp.prompts.list_changed". Payload identifying the MCP server associated with a list change. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class McpPromptsListChangedEvent extends SessionEvent { + + @Override + public String getType() { return "mcp.prompts.list_changed"; } + + @JsonProperty("data") + private McpPromptsListChangedEventData data; + + public McpPromptsListChangedEventData getData() { return data; } + public void setData(McpPromptsListChangedEventData data) { this.data = data; } + + /** Data payload for {@link McpPromptsListChangedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record McpPromptsListChangedEventData( + /** Name of the MCP server whose list changed */ + @JsonProperty("serverName") String serverName + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpResourcesListChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/McpResourcesListChangedEvent.java new file mode 100644 index 0000000000..f1a613b6fa --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpResourcesListChangedEvent.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "mcp.resources.list_changed". Payload identifying the MCP server associated with a list change. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class McpResourcesListChangedEvent extends SessionEvent { + + @Override + public String getType() { return "mcp.resources.list_changed"; } + + @JsonProperty("data") + private McpResourcesListChangedEventData data; + + public McpResourcesListChangedEventData getData() { return data; } + public void setData(McpResourcesListChangedEventData data) { this.data = data; } + + /** Data payload for {@link McpResourcesListChangedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record McpResourcesListChangedEventData( + /** Name of the MCP server whose list changed */ + @JsonProperty("serverName") String serverName + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/McpServersLoadedServer.java b/java/src/generated/java/com/github/copilot/generated/McpServersLoadedServer.java index 9c5d520813..1a2f05023e 100644 --- a/java/src/generated/java/com/github/copilot/generated/McpServersLoadedServer.java +++ b/java/src/generated/java/com/github/copilot/generated/McpServersLoadedServer.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `McpServersLoadedServer` type. + * A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/McpToolsListChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/McpToolsListChangedEvent.java new file mode 100644 index 0000000000..4255b8544f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/McpToolsListChangedEvent.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "mcp.tools.list_changed". Payload identifying the MCP server associated with a list change. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class McpToolsListChangedEvent extends SessionEvent { + + @Override + public String getType() { return "mcp.tools.list_changed"; } + + @JsonProperty("data") + private McpToolsListChangedEventData data; + + public McpToolsListChangedEventData getData() { return data; } + public void setData(McpToolsListChangedEventData data) { this.data = data; } + + /** Data payload for {@link McpToolsListChangedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record McpToolsListChangedEventData( + /** Name of the MCP server whose list changed */ + @JsonProperty("serverName") String serverName + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/PermissionAllowAllMode.java b/java/src/generated/java/com/github/copilot/generated/PermissionAllowAllMode.java new file mode 100644 index 0000000000..d05b936e6a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/PermissionAllowAllMode.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Allow-all mode for the session. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum PermissionAllowAllMode { + /** The {@code off} variant. */ + OFF("off"), + /** The {@code on} variant. */ + ON("on"), + /** The {@code auto} variant. */ + AUTO("auto"); + + private final String value; + PermissionAllowAllMode(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static PermissionAllowAllMode fromValue(String value) { + for (PermissionAllowAllMode v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown PermissionAllowAllMode value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionAutoModeResolvedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionAutoModeResolvedEvent.java new file mode 100644 index 0000000000..f79be388ec --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionAutoModeResolvedEvent.java @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Session event "session.auto_mode_resolved". Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionAutoModeResolvedEvent extends SessionEvent { + + @Override + public String getType() { return "session.auto_mode_resolved"; } + + @JsonProperty("data") + private SessionAutoModeResolvedEventData data; + + public SessionAutoModeResolvedEventData getData() { return data; } + public void setData(SessionAutoModeResolvedEventData data) { this.data = data; } + + /** Data payload for {@link SessionAutoModeResolvedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionAutoModeResolvedEventData( + /** The concrete model the session will use after any intent refinement */ + @JsonProperty("chosenModel") String chosenModel, + /** Coarse request-difficulty bucket, for explaining why a model was chosen ("picked X because this looks like high-reasoning work") */ + @JsonProperty("reasoningBucket") AutoModeResolvedReasoningBucket reasoningBucket, + /** Per-category classifier scores (0-1) behind the bucket: the granular HYDRA capability scores (reasoning, code_gen, debugging, tool_use), or the binary needs_reasoning/no_reasoning scores when HYDRA didn't run. Lets clients show a breakdown rather than just the bucket. */ + @JsonProperty("categoryScores") Map categoryScores, + /** The predicted classifier label (e.g. `needs_reasoning`), when available */ + @JsonProperty("predictedLabel") String predictedLabel, + /** Classifier confidence for the predicted label, when available */ + @JsonProperty("confidence") Double confidence, + /** Ordered candidate model list the router returned, when not a fallback */ + @JsonProperty("candidateModels") List candidateModels + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionBackgroundTasksChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionBackgroundTasksChangedEvent.java index dddb44b843..6058e18c34 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionBackgroundTasksChangedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionBackgroundTasksChangedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.background_tasks_changed". + * Session event "session.background_tasks_changed". Empty payload for `session.background_tasks_changed`, indicating background task state changed. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionCanvasClosedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionCanvasClosedEvent.java index 79fd365c2b..b660c0be66 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionCanvasClosedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionCanvasClosedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.canvas.closed". + * Session event "session.canvas.closed". Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionCanvasOpenedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionCanvasOpenedEvent.java index 84f87ffbc0..018e6a234d 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionCanvasOpenedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionCanvasOpenedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.canvas.opened". + * Session event "session.canvas.opened". Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @@ -42,6 +42,8 @@ public record SessionCanvasOpenedEventData( @JsonProperty("extensionName") String extensionName, /** Provider-local canvas identifier */ @JsonProperty("canvasId") String canvasId, + /** Host-local PNG path for the canvas icon, when supplied */ + @JsonProperty("icon") String icon, /** Rendered title */ @JsonProperty("title") String title, /** Provider-supplied status text */ diff --git a/java/src/generated/java/com/github/copilot/generated/SessionCanvasRegistryChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionCanvasRegistryChangedEvent.java index 95ba017630..0a6a9b62de 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionCanvasRegistryChangedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionCanvasRegistryChangedEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.canvas.registry_changed". + * Session event "session.canvas.registry_changed". Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java index f09e75f4cc..e92a3ac50f 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java @@ -34,6 +34,8 @@ public final class SessionCompactionStartEvent extends SessionEvent { @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public record SessionCompactionStartEventData( + /** Model identifier used for compaction, when known */ + @JsonProperty("model") String model, /** Token count from system message(s) at compaction start */ @JsonProperty("systemTokens") Long systemTokens, /** Token count from non-system messages (user, assistant, tool) at compaction start */ diff --git a/java/src/generated/java/com/github/copilot/generated/SessionCustomAgentsUpdatedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionCustomAgentsUpdatedEvent.java index e7bbad3580..6d7ed6611a 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionCustomAgentsUpdatedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionCustomAgentsUpdatedEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.custom_agents_updated". + * Session event "session.custom_agents_updated". Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionEvent.java index f92dbf2fae..d15da0c41c 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionEvent.java @@ -39,6 +39,7 @@ @JsonSubTypes.Type(value = SessionWarningEvent.class, name = "session.warning"), @JsonSubTypes.Type(value = SessionModelChangeEvent.class, name = "session.model_change"), @JsonSubTypes.Type(value = SessionModeChangedEvent.class, name = "session.mode_changed"), + @JsonSubTypes.Type(value = SessionSessionLimitsChangedEvent.class, name = "session.session_limits_changed"), @JsonSubTypes.Type(value = SessionPermissionsChangedEvent.class, name = "session.permissions_changed"), @JsonSubTypes.Type(value = SessionPlanChangedEvent.class, name = "session.plan_changed"), @JsonSubTypes.Type(value = SessionTodosChangedEvent.class, name = "session.todos_changed"), @@ -47,6 +48,7 @@ @JsonSubTypes.Type(value = SessionTruncationEvent.class, name = "session.truncation"), @JsonSubTypes.Type(value = SessionSnapshotRewindEvent.class, name = "session.snapshot_rewind"), @JsonSubTypes.Type(value = SessionShutdownEvent.class, name = "session.shutdown"), + @JsonSubTypes.Type(value = SessionUsageCheckpointEvent.class, name = "session.usage_checkpoint"), @JsonSubTypes.Type(value = SessionContextChangedEvent.class, name = "session.context_changed"), @JsonSubTypes.Type(value = SessionUsageInfoEvent.class, name = "session.usage_info"), @JsonSubTypes.Type(value = SessionCompactionStartEvent.class, name = "session.compaction_start"), @@ -56,13 +58,16 @@ @JsonSubTypes.Type(value = PendingMessagesModifiedEvent.class, name = "pending_messages.modified"), @JsonSubTypes.Type(value = AssistantTurnStartEvent.class, name = "assistant.turn_start"), @JsonSubTypes.Type(value = AssistantIntentEvent.class, name = "assistant.intent"), + @JsonSubTypes.Type(value = AssistantServerToolProgressEvent.class, name = "assistant.server_tool_progress"), @JsonSubTypes.Type(value = AssistantReasoningEvent.class, name = "assistant.reasoning"), @JsonSubTypes.Type(value = AssistantReasoningDeltaEvent.class, name = "assistant.reasoning_delta"), + @JsonSubTypes.Type(value = AssistantToolCallDeltaEvent.class, name = "assistant.tool_call_delta"), @JsonSubTypes.Type(value = AssistantStreamingDeltaEvent.class, name = "assistant.streaming_delta"), @JsonSubTypes.Type(value = AssistantMessageEvent.class, name = "assistant.message"), @JsonSubTypes.Type(value = AssistantMessageStartEvent.class, name = "assistant.message_start"), @JsonSubTypes.Type(value = AssistantMessageDeltaEvent.class, name = "assistant.message_delta"), @JsonSubTypes.Type(value = AssistantTurnEndEvent.class, name = "assistant.turn_end"), + @JsonSubTypes.Type(value = AssistantIdleEvent.class, name = "assistant.idle"), @JsonSubTypes.Type(value = AssistantUsageEvent.class, name = "assistant.usage"), @JsonSubTypes.Type(value = ModelCallFailureEvent.class, name = "model.call_failure"), @JsonSubTypes.Type(value = AbortEvent.class, name = "abort"), @@ -93,6 +98,8 @@ @JsonSubTypes.Type(value = SamplingCompletedEvent.class, name = "sampling.completed"), @JsonSubTypes.Type(value = McpOauthRequiredEvent.class, name = "mcp.oauth_required"), @JsonSubTypes.Type(value = McpOauthCompletedEvent.class, name = "mcp.oauth_completed"), + @JsonSubTypes.Type(value = McpHeadersRefreshRequiredEvent.class, name = "mcp.headers_refresh_required"), + @JsonSubTypes.Type(value = McpHeadersRefreshCompletedEvent.class, name = "mcp.headers_refresh_completed"), @JsonSubTypes.Type(value = SessionCustomNotificationEvent.class, name = "session.custom_notification"), @JsonSubTypes.Type(value = ExternalToolRequestedEvent.class, name = "external_tool.requested"), @JsonSubTypes.Type(value = ExternalToolCompletedEvent.class, name = "external_tool.completed"), @@ -101,6 +108,10 @@ @JsonSubTypes.Type(value = CommandCompletedEvent.class, name = "command.completed"), @JsonSubTypes.Type(value = AutoModeSwitchRequestedEvent.class, name = "auto_mode_switch.requested"), @JsonSubTypes.Type(value = AutoModeSwitchCompletedEvent.class, name = "auto_mode_switch.completed"), + @JsonSubTypes.Type(value = SessionLimitsExhaustedRequestedEvent.class, name = "session_limits_exhausted.requested"), + @JsonSubTypes.Type(value = SessionLimitsExhaustedCompletedEvent.class, name = "session_limits_exhausted.completed"), + @JsonSubTypes.Type(value = SessionAutoModeResolvedEvent.class, name = "session.auto_mode_resolved"), + @JsonSubTypes.Type(value = SessionManagedSettingsResolvedEvent.class, name = "session.managed_settings_resolved"), @JsonSubTypes.Type(value = CommandsChangedEvent.class, name = "commands.changed"), @JsonSubTypes.Type(value = CapabilitiesChangedEvent.class, name = "capabilities.changed"), @JsonSubTypes.Type(value = ExitPlanModeRequestedEvent.class, name = "exit_plan_mode.requested"), @@ -111,6 +122,9 @@ @JsonSubTypes.Type(value = SessionCustomAgentsUpdatedEvent.class, name = "session.custom_agents_updated"), @JsonSubTypes.Type(value = SessionMcpServersLoadedEvent.class, name = "session.mcp_servers_loaded"), @JsonSubTypes.Type(value = SessionMcpServerStatusChangedEvent.class, name = "session.mcp_server_status_changed"), + @JsonSubTypes.Type(value = McpToolsListChangedEvent.class, name = "mcp.tools.list_changed"), + @JsonSubTypes.Type(value = McpResourcesListChangedEvent.class, name = "mcp.resources.list_changed"), + @JsonSubTypes.Type(value = McpPromptsListChangedEvent.class, name = "mcp.prompts.list_changed"), @JsonSubTypes.Type(value = SessionExtensionsLoadedEvent.class, name = "session.extensions_loaded"), @JsonSubTypes.Type(value = SessionCanvasOpenedEvent.class, name = "session.canvas.opened"), @JsonSubTypes.Type(value = SessionCanvasRegistryChangedEvent.class, name = "session.canvas.registry_changed"), @@ -137,6 +151,7 @@ public abstract sealed class SessionEvent permits SessionWarningEvent, SessionModelChangeEvent, SessionModeChangedEvent, + SessionSessionLimitsChangedEvent, SessionPermissionsChangedEvent, SessionPlanChangedEvent, SessionTodosChangedEvent, @@ -145,6 +160,7 @@ public abstract sealed class SessionEvent permits SessionTruncationEvent, SessionSnapshotRewindEvent, SessionShutdownEvent, + SessionUsageCheckpointEvent, SessionContextChangedEvent, SessionUsageInfoEvent, SessionCompactionStartEvent, @@ -154,13 +170,16 @@ public abstract sealed class SessionEvent permits PendingMessagesModifiedEvent, AssistantTurnStartEvent, AssistantIntentEvent, + AssistantServerToolProgressEvent, AssistantReasoningEvent, AssistantReasoningDeltaEvent, + AssistantToolCallDeltaEvent, AssistantStreamingDeltaEvent, AssistantMessageEvent, AssistantMessageStartEvent, AssistantMessageDeltaEvent, AssistantTurnEndEvent, + AssistantIdleEvent, AssistantUsageEvent, ModelCallFailureEvent, AbortEvent, @@ -191,6 +210,8 @@ public abstract sealed class SessionEvent permits SamplingCompletedEvent, McpOauthRequiredEvent, McpOauthCompletedEvent, + McpHeadersRefreshRequiredEvent, + McpHeadersRefreshCompletedEvent, SessionCustomNotificationEvent, ExternalToolRequestedEvent, ExternalToolCompletedEvent, @@ -199,6 +220,10 @@ public abstract sealed class SessionEvent permits CommandCompletedEvent, AutoModeSwitchRequestedEvent, AutoModeSwitchCompletedEvent, + SessionLimitsExhaustedRequestedEvent, + SessionLimitsExhaustedCompletedEvent, + SessionAutoModeResolvedEvent, + SessionManagedSettingsResolvedEvent, CommandsChangedEvent, CapabilitiesChangedEvent, ExitPlanModeRequestedEvent, @@ -209,6 +234,9 @@ public abstract sealed class SessionEvent permits SessionCustomAgentsUpdatedEvent, SessionMcpServersLoadedEvent, SessionMcpServerStatusChangedEvent, + McpToolsListChangedEvent, + McpResourcesListChangedEvent, + McpPromptsListChangedEvent, SessionExtensionsLoadedEvent, SessionCanvasOpenedEvent, SessionCanvasRegistryChangedEvent, diff --git a/java/src/generated/java/com/github/copilot/generated/SessionExtensionsAttachmentsPushedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionExtensionsAttachmentsPushedEvent.java index 55a9f64577..72d0a9deff 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionExtensionsAttachmentsPushedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionExtensionsAttachmentsPushedEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.extensions.attachments_pushed". + * Session event "session.extensions.attachments_pushed". Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionExtensionsLoadedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionExtensionsLoadedEvent.java index 978162f03e..6ec3ec2746 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionExtensionsLoadedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionExtensionsLoadedEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.extensions_loaded". + * Session event "session.extensions_loaded". Payload of `session.extensions_loaded` listing discovered extensions and their statuses. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionLimitsConfig.java b/java/src/generated/java/com/github/copilot/generated/SessionLimitsConfig.java new file mode 100644 index 0000000000..e566d630b7 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionLimitsConfig.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Optional session limits. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionLimitsConfig( + /** Maximum AI Credits allowed across the session's current accounting window. */ + @JsonProperty("maxAiCredits") Double maxAiCredits +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedCompletedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedCompletedEvent.java new file mode 100644 index 0000000000..f23ae9a733 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedCompletedEvent.java @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "session_limits_exhausted.completed". Session limit exhaustion prompt completion notification. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionLimitsExhaustedCompletedEvent extends SessionEvent { + + @Override + public String getType() { return "session_limits_exhausted.completed"; } + + @JsonProperty("data") + private SessionLimitsExhaustedCompletedEventData data; + + public SessionLimitsExhaustedCompletedEventData getData() { return data; } + public void setData(SessionLimitsExhaustedCompletedEventData data) { this.data = data; } + + /** Data payload for {@link SessionLimitsExhaustedCompletedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionLimitsExhaustedCompletedEventData( + /** Request ID of the resolved request; clients should dismiss any UI for this request. */ + @JsonProperty("requestId") String requestId, + /** The user's selected session-limit action. */ + @JsonProperty("response") SessionLimitsExhaustedResponse response + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedRequestedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedRequestedEvent.java new file mode 100644 index 0000000000..3bde1f3347 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedRequestedEvent.java @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "session_limits_exhausted.requested". Session limit exhaustion notification requiring user action. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionLimitsExhaustedRequestedEvent extends SessionEvent { + + @Override + public String getType() { return "session_limits_exhausted.requested"; } + + @JsonProperty("data") + private SessionLimitsExhaustedRequestedEventData data; + + public SessionLimitsExhaustedRequestedEventData getData() { return data; } + public void setData(SessionLimitsExhaustedRequestedEventData data) { this.data = data; } + + /** Data payload for {@link SessionLimitsExhaustedRequestedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionLimitsExhaustedRequestedEventData( + /** Unique identifier for this request; used to respond via session.ui.handlePendingSessionLimitsExhausted(). */ + @JsonProperty("requestId") String requestId, + /** AI Credits already consumed in the current accounting window. */ + @JsonProperty("usedAiCredits") Double usedAiCredits, + /** Configured max AI Credits for the current accounting window. */ + @JsonProperty("maxAiCredits") Double maxAiCredits + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedResponse.java b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedResponse.java new file mode 100644 index 0000000000..5bbc7ffef6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedResponse.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * The user's selected action for an exhausted session limit. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionLimitsExhaustedResponse( + /** Action selected by the user. */ + @JsonProperty("action") SessionLimitsExhaustedResponseAction action, + /** AI Credits to add to the current max when action is 'add'. */ + @JsonProperty("additionalAiCredits") Double additionalAiCredits, + /** New absolute max AI Credits when action is 'set'. */ + @JsonProperty("maxAiCredits") Double maxAiCredits +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedResponseAction.java b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedResponseAction.java new file mode 100644 index 0000000000..706d3bf9df --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionLimitsExhaustedResponseAction.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * User action selected for an exhausted session limit. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionLimitsExhaustedResponseAction { + /** The {@code add} variant. */ + ADD("add"), + /** The {@code set} variant. */ + SET("set"), + /** The {@code unset} variant. */ + UNSET("unset"), + /** The {@code cancel} variant. */ + CANCEL("cancel"); + + private final String value; + SessionLimitsExhaustedResponseAction(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionLimitsExhaustedResponseAction fromValue(String value) { + for (SessionLimitsExhaustedResponseAction v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionLimitsExhaustedResponseAction value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionManagedSettingsResolvedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionManagedSettingsResolvedEvent.java new file mode 100644 index 0000000000..7cc495269f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionManagedSettingsResolvedEvent.java @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Session event "session.managed_settings_resolved". Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionManagedSettingsResolvedEvent extends SessionEvent { + + @Override + public String getType() { return "session.managed_settings_resolved"; } + + @JsonProperty("data") + private SessionManagedSettingsResolvedEventData data; + + public SessionManagedSettingsResolvedEventData getData() { return data; } + public void setData(SessionManagedSettingsResolvedEventData data) { this.data = data; } + + /** Data payload for {@link SessionManagedSettingsResolvedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionManagedSettingsResolvedEventData( + /** Which channel supplied the effective managed settings (the winning layer), or `none` when no policy is in force */ + @JsonProperty("source") ManagedSettingsResolvedSource source, + /** Whether the server (account/org) managed-settings layer was present */ + @JsonProperty("serverManaged") Boolean serverManaged, + /** Whether the device (MDM/plist/registry/file) managed-settings layer was present */ + @JsonProperty("deviceManaged") Boolean deviceManaged, + /** Whether managed policy could not be determined (e.g. a failed server fetch) and the session fell back to the fail-closed restriction. When true, restrictions such as disabling bypass-permissions are enforced even though `settings` may be absent. */ + @JsonProperty("failClosed") Boolean failClosed, + /** Whether enterprise policy disables bypass-permissions ("yolo") mode for this session. Deny-wins across layers, and forced on when `failClosed` is true. */ + @JsonProperty("bypassPermissionsDisabled") Boolean bypassPermissionsDisabled, + /** The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. */ + @JsonProperty("managedKeys") List managedKeys, + /** The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. */ + @JsonProperty("settings") Object settings + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionMcpServerStatusChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionMcpServerStatusChangedEvent.java index 6cbcca29fd..cb15f1d9e9 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionMcpServerStatusChangedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionMcpServerStatusChangedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.mcp_server_status_changed". + * Session event "session.mcp_server_status_changed". Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionMcpServersLoadedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionMcpServersLoadedEvent.java index 59ff2a1aaf..98ddc5b191 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionMcpServersLoadedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionMcpServersLoadedEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.mcp_servers_loaded". + * Session event "session.mcp_servers_loaded". Payload of `session.mcp_servers_loaded` listing MCP server status summaries. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionModelChangeEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionModelChangeEvent.java index da0279757d..f12b86d088 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionModelChangeEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionModelChangeEvent.java @@ -46,6 +46,10 @@ public record SessionModelChangeEventData( @JsonProperty("previousReasoningSummary") ReasoningSummary previousReasoningSummary, /** Reasoning summary mode after the model change, if applicable */ @JsonProperty("reasoningSummary") ReasoningSummary reasoningSummary, + /** Output verbosity level before the model change, if applicable */ + @JsonProperty("previousVerbosity") Verbosity previousVerbosity, + /** Output verbosity level after the model change, if applicable */ + @JsonProperty("verbosity") Verbosity verbosity, /** Context tier after the model change; null explicitly clears a previously selected tier */ @JsonProperty("contextTier") ContextTier contextTier, /** Reason the change happened, when not user-initiated. Currently `"rate_limit_auto_switch"` for changes triggered by the auto-mode-switch rate-limit recovery path. UI clients can use this to render contextual copy. */ diff --git a/java/src/generated/java/com/github/copilot/generated/SessionPermissionsChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionPermissionsChangedEvent.java index fe91df9d35..c1f82f5af7 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionPermissionsChangedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionPermissionsChangedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all boolean transition. + * Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all transition. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @@ -37,7 +37,11 @@ public record SessionPermissionsChangedEventData( /** Aggregate allow-all flag before the change */ @JsonProperty("previousAllowAllPermissions") Boolean previousAllowAllPermissions, /** Aggregate allow-all flag after the change */ - @JsonProperty("allowAllPermissions") Boolean allowAllPermissions + @JsonProperty("allowAllPermissions") Boolean allowAllPermissions, + /** Allow-all mode before the change */ + @JsonProperty("previousAllowAllPermissionMode") PermissionAllowAllMode previousAllowAllPermissionMode, + /** Allow-all mode after the change */ + @JsonProperty("allowAllPermissionMode") PermissionAllowAllMode allowAllPermissionMode ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java index b1cfda9338..6efac46f27 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java @@ -47,8 +47,12 @@ public record SessionResumeEventData( @JsonProperty("reasoningEffort") String reasoningEffort, /** Reasoning summary mode used for model calls, if applicable (e.g. "none", "concise", "detailed") */ @JsonProperty("reasoningSummary") ReasoningSummary reasoningSummary, + /** Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") */ + @JsonProperty("verbosity") Verbosity verbosity, /** Context tier currently selected at resume time; null when no tier is active */ @JsonProperty("contextTier") ContextTier contextTier, + /** Session limits currently configured at resume time; null when no limits are active */ + @JsonProperty("sessionLimits") SessionLimitsConfig sessionLimits, /** Updated working directory and git context at resume time */ @JsonProperty("context") WorkingDirectoryContext context, /** Whether the session was already in use by another client at resume time */ diff --git a/java/src/generated/java/com/github/copilot/generated/SessionSessionLimitsChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionSessionLimitsChangedEvent.java new file mode 100644 index 0000000000..1612aa74f0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionSessionLimitsChangedEvent.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "session.session_limits_changed". Session limits update details. Null clears the limits. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionSessionLimitsChangedEvent extends SessionEvent { + + @Override + public String getType() { return "session.session_limits_changed"; } + + @JsonProperty("data") + private SessionSessionLimitsChangedEventData data; + + public SessionSessionLimitsChangedEventData getData() { return data; } + public void setData(SessionSessionLimitsChangedEventData data) { this.data = data; } + + /** Data payload for {@link SessionSessionLimitsChangedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionSessionLimitsChangedEventData( + /** Current session limits, or null when no limits are active */ + @JsonProperty("sessionLimits") SessionLimitsConfig sessionLimits + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionSkillsLoadedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionSkillsLoadedEvent.java index b2ddd18ed3..efe356670a 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionSkillsLoadedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionSkillsLoadedEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.skills_loaded". + * Session event "session.skills_loaded". Payload of `session.skills_loaded` listing resolved skill metadata. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionStartEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionStartEvent.java index 2b36fa3e7b..4beb487c31 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionStartEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionStartEvent.java @@ -51,8 +51,12 @@ public record SessionStartEventData( @JsonProperty("reasoningEffort") String reasoningEffort, /** Reasoning summary mode used for model calls, if applicable (e.g. "none", "concise", "detailed") */ @JsonProperty("reasoningSummary") ReasoningSummary reasoningSummary, + /** Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") */ + @JsonProperty("verbosity") Verbosity verbosity, /** Context tier selected at session creation time for models with tiered context pricing; null when no tier is selected (e.g., non-tiered model) */ @JsonProperty("contextTier") ContextTier contextTier, + /** Session limits configured at session creation time, if any */ + @JsonProperty("sessionLimits") SessionLimitsConfig sessionLimits, /** Working directory and git context at session start */ @JsonProperty("context") WorkingDirectoryContext context, /** Whether the session was already in use by another client at start time */ diff --git a/java/src/generated/java/com/github/copilot/generated/SessionToolsUpdatedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionToolsUpdatedEvent.java index 2b0d94c260..f69954ee5e 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionToolsUpdatedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionToolsUpdatedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "session.tools_updated". + * Session event "session.tools_updated". Payload of `session.tools_updated` identifying the model whose resolved tools were updated. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/SessionUsageCheckpointEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionUsageCheckpointEvent.java new file mode 100644 index 0000000000..312cb196b4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/SessionUsageCheckpointEvent.java @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "session.usage_checkpoint". Durable session usage checkpoint for reconstructing aggregate accounting on resume + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionUsageCheckpointEvent extends SessionEvent { + + @Override + public String getType() { return "session.usage_checkpoint"; } + + @JsonProperty("data") + private SessionUsageCheckpointEventData data; + + public SessionUsageCheckpointEventData getData() { return data; } + public void setData(SessionUsageCheckpointEventData data) { this.data = data; } + + /** Data payload for {@link SessionUsageCheckpointEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionUsageCheckpointEventData( + /** Session-wide accumulated nano-AI units cost at checkpoint time */ + @JsonProperty("totalNanoAiu") Double totalNanoAiu, + /** Total number of premium API requests used at checkpoint time */ + @JsonProperty("totalPremiumRequests") Double totalPremiumRequests + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetric.java b/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetric.java index b7eb37fd90..1ba45d90b6 100644 --- a/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetric.java +++ b/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetric.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ShutdownModelMetric` type. + * Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetricTokenDetail.java b/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetricTokenDetail.java index fe18de6c69..cd0e67d702 100644 --- a/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetricTokenDetail.java +++ b/java/src/generated/java/com/github/copilot/generated/ShutdownModelMetricTokenDetail.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ShutdownModelMetricTokenDetail` type. + * A token-type entry in a shutdown model metric, storing the accumulated token count. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ShutdownTokenDetail.java b/java/src/generated/java/com/github/copilot/generated/ShutdownTokenDetail.java index 75db095c5f..dfc986e834 100644 --- a/java/src/generated/java/com/github/copilot/generated/ShutdownTokenDetail.java +++ b/java/src/generated/java/com/github/copilot/generated/ShutdownTokenDetail.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ShutdownTokenDetail` type. + * A session-wide shutdown token-type entry storing the accumulated token count. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/SkillInvokedEvent.java b/java/src/generated/java/com/github/copilot/generated/SkillInvokedEvent.java index a3bac49bc2..6ad04f9699 100644 --- a/java/src/generated/java/com/github/copilot/generated/SkillInvokedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SkillInvokedEvent.java @@ -37,6 +37,8 @@ public final class SkillInvokedEvent extends SessionEvent { public record SkillInvokedEventData( /** Name of the invoked skill */ @JsonProperty("name") String name, + /** Model identifier active when the skill was invoked, when known */ + @JsonProperty("model") String model, /** File path to the SKILL.md definition */ @JsonProperty("path") String path, /** Full content of the skill file, injected into the conversation for the model */ diff --git a/java/src/generated/java/com/github/copilot/generated/SkillsLoadedSkill.java b/java/src/generated/java/com/github/copilot/generated/SkillsLoadedSkill.java index a3db9697fe..d3196c6bbf 100644 --- a/java/src/generated/java/com/github/copilot/generated/SkillsLoadedSkill.java +++ b/java/src/generated/java/com/github/copilot/generated/SkillsLoadedSkill.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SkillsLoadedSkill` type. + * A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java index b4e82d2685..99d138b1e6 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java @@ -41,6 +41,8 @@ public record ToolExecutionCompleteEventData( @JsonProperty("success") Boolean success, /** Model identifier that generated this tool call */ @JsonProperty("model") String model, + /** FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels). Persisted as `{ ifc: ... }` so the label survives session resume, including model-visible failure results. Experimental. */ + @JsonProperty("mcpMeta") Object mcpMeta, /** CAPI interaction ID for correlating this tool execution with upstream telemetry */ @JsonProperty("interactionId") String interactionId, /** Whether this tool call was explicitly requested by the user rather than the assistant */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteResult.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteResult.java index 7459d5517f..f7f08d93c6 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteResult.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteResult.java @@ -35,6 +35,8 @@ public record ToolExecutionCompleteResult( /** Structured content (arbitrary JSON) returned verbatim by the MCP tool */ @JsonProperty("structuredContent") Object structuredContent, /** Provider-neutral source material this tool makes available to the model as citable content. Persisted so it survives session resume. Experimental. */ - @JsonProperty("citableSources") List citableSources + @JsonProperty("citableSources") List citableSources, + /** FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels) — persisted as `{ ifc: ... }` (only the `ifc` key, not the whole `_meta`). Persisted so the FIDES IFC label survives session resume: the engine rehydrates accumulated taint by replaying these on load. Populated for ingress sources when FIDES IFC is on. Experimental. */ + @JsonProperty("mcpMeta") Object mcpMeta ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMeta.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMeta.java index 563358cfa3..f9af397a79 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMeta.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMeta.java @@ -21,7 +21,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record ToolExecutionCompleteToolDescriptionMeta( - /** Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. */ + /** MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. */ @JsonProperty("ui") ToolExecutionCompleteToolDescriptionMetaUI ui ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMetaUI.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMetaUI.java index 9acf435bc7..1cbe17d498 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMetaUI.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteToolDescriptionMetaUI.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. + * MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMeta.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMeta.java index 6375222cc3..897f0ff397 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMeta.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMeta.java @@ -21,7 +21,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record ToolExecutionCompleteUIResourceMeta( - /** Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. */ + /** MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. */ @JsonProperty("ui") ToolExecutionCompleteUIResourceMetaUI ui ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUI.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUI.java index 3b9548a8ce..6679b85aec 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUI.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUI.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. + * MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. * * @since 1.0.0 */ @@ -21,9 +21,9 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record ToolExecutionCompleteUIResourceMetaUI( - /** Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. */ + /** CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. */ @JsonProperty("csp") ToolExecutionCompleteUIResourceMetaUICsp csp, - /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. */ + /** Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. */ @JsonProperty("permissions") ToolExecutionCompleteUIResourceMetaUIPermissions permissions, @JsonProperty("domain") String domain, @JsonProperty("prefersBorder") Boolean prefersBorder diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUICsp.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUICsp.java index 0ccb8a3dbc..41e799cf03 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUICsp.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUICsp.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. + * CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissions.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissions.java index 8b1fc5dc9a..d9adf5579d 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissions.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissions.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. + * Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. * * @since 1.0.0 */ @@ -21,13 +21,13 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record ToolExecutionCompleteUIResourceMetaUIPermissions( - /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. */ + /** Marker object for camera permission on an MCP Apps UI resource. */ @JsonProperty("camera") ToolExecutionCompleteUIResourceMetaUIPermissionsCamera camera, - /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. */ + /** Marker object for microphone permission on an MCP Apps UI resource. */ @JsonProperty("microphone") ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone microphone, - /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. */ + /** Marker object for geolocation permission on an MCP Apps UI resource. */ @JsonProperty("geolocation") ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation geolocation, - /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. */ + /** Marker object for clipboard-write permission on an MCP Apps UI resource. */ @JsonProperty("clipboardWrite") ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite clipboardWrite ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsCamera.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsCamera.java index 300967e8ce..9a02355350 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsCamera.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsCamera.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. + * Marker object for camera permission on an MCP Apps UI resource. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite.java index 485a6946ce..0c4e8dad1f 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. + * Marker object for clipboard-write permission on an MCP Apps UI resource. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation.java index 30ed9bb545..d681474737 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. + * Marker object for geolocation permission on an MCP Apps UI resource. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone.java index 1748ccb487..4caa88edeb 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. + * Marker object for microphone permission on an MCP Apps UI resource. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java index cd4e5a137d..b119a3eb0e 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java @@ -40,6 +40,8 @@ public record ToolExecutionStartEventData( @JsonProperty("toolName") String toolName, /** Arguments passed to the tool */ @JsonProperty("arguments") Object arguments, + /** Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. */ + @JsonProperty("shellToolInfo") ToolExecutionStartShellToolInfo shellToolInfo, /** Model identifier that generated this tool call */ @JsonProperty("model") String model, /** Name of the MCP server hosting this tool, when the tool is an MCP tool */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartShellToolInfo.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartShellToolInfo.java new file mode 100644 index 0000000000..88ac787fca --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartShellToolInfo.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Shell-aware path hints for a shell tool's command, captured at start time so consumers can snapshot a file's pre-image before the tool runs. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ToolExecutionStartShellToolInfo( + /** File paths the command may read or write, derived from the command at start time. Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. */ + @JsonProperty("possiblePaths") List possiblePaths, + /** Whether the command includes a file write redirection (e.g., > or >>). */ + @JsonProperty("hasWriteFileRedirection") Boolean hasWriteFileRedirection +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMeta.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMeta.java index 25296d1d3d..e93bf998a2 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMeta.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMeta.java @@ -21,7 +21,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record ToolExecutionStartToolDescriptionMeta( - /** Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. */ + /** MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. */ @JsonProperty("ui") ToolExecutionStartToolDescriptionMetaUI ui ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMetaUI.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMetaUI.java index c928a03f61..954edf2105 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMetaUI.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartToolDescriptionMetaUI.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. + * MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/UserMessageDelivery.java b/java/src/generated/java/com/github/copilot/generated/UserMessageDelivery.java new file mode 100644 index 0000000000..ab64a88592 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/UserMessageDelivery.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * How this user message was delivered to the agentic loop, relative to whether the loop was already running. This is the timing axis only; the message's origin (human vs. system/command/schedule/skill/etc.) is carried separately by `source`. A system-injected message has a delivery too — e.g. a background-task notification waking an idle agent is `idle`, the same mechanism as a human starting a fresh turn. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum UserMessageDelivery { + /** The {@code idle} variant. */ + IDLE("idle"), + /** The {@code steering} variant. */ + STEERING("steering"), + /** The {@code queued} variant. */ + QUEUED("queued"); + + private final String value; + UserMessageDelivery(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static UserMessageDelivery fromValue(String value) { + for (UserMessageDelivery v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown UserMessageDelivery value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java b/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java index 69f959ab65..5af4842430 100644 --- a/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "user.message". + * Session event "user.message". Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @@ -47,6 +47,8 @@ public record UserMessageEventData( @JsonProperty("nativeDocumentPathFallbackPaths") List nativeDocumentPathFallbackPaths, /** Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) */ @JsonProperty("source") String source, + /** How this message was delivered to the agentic loop relative to loop state (idle-start vs. steering/queued while busy). The timing axis; combine with `source` (origin) for the full picture. Used for telemetry attribution. */ + @JsonProperty("delivery") UserMessageDelivery delivery, /** The agent mode that was active when this message was sent */ @JsonProperty("agentMode") UserMessageAgentMode agentMode, /** True when this user message was auto-injected by autopilot's continuation loop rather than typed by the user; used to distinguish autopilot-driven turns in telemetry. */ diff --git a/java/src/generated/java/com/github/copilot/generated/Verbosity.java b/java/src/generated/java/com/github/copilot/generated/Verbosity.java new file mode 100644 index 0000000000..9db84f1857 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/Verbosity.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Output verbosity level used for supported model calls (e.g. "low", "medium", "high") + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum Verbosity { + /** The {@code low} variant. */ + LOW("low"), + /** The {@code medium} variant. */ + MEDIUM("medium"), + /** The {@code high} variant. */ + HIGH("high"); + + private final String value; + Verbosity(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static Verbosity fromValue(String value) { + for (Verbosity v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown Verbosity value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountAllUsers.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountAllUsers.java index a544b8a307..eecdad01ee 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountAllUsers.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountAllUsers.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `AccountAllUsers` type. + * Authenticated account entry returned by `account.getAllUsers`, with auth info and an optional associated token. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetCurrentAuthResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetCurrentAuthResult.java index 9cbcd4906d..eb577fcc25 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetCurrentAuthResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetCurrentAuthResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * Current authentication state + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaResult.java index 3685fbb8ad..6e5929dfd5 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.Map; import javax.annotation.processing.Generated; /** * Quota usage snapshots for the resolved user, keyed by quota type. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginParams.java index 6dd4266b29..bd8e697341 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Credentials to store after successful authentication + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginResult.java index 33d65f7dc0..1119835575 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLoginResult.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Result of a successful login; throws on failure + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutParams.java index 0d15fd1231..b5e93e1859 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * User to log out + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutResult.java index c26df8524b..296227e5b6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountLogoutResult.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Logout result indicating if more users remain + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountQuotaSnapshot.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountQuotaSnapshot.java index 88e7ba9c64..fe4baf3fd6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AccountQuotaSnapshot.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountQuotaSnapshot.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `AccountQuotaSnapshot` type. + * Quota usage snapshot for a Copilot quota type, including entitlement, used requests, overage, reset date, and remaining percentage. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AdaptiveThinkingSupport.java b/java/src/generated/java/com/github/copilot/generated/rpc/AdaptiveThinkingSupport.java new file mode 100644 index 0000000000..6ec806fb1a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AdaptiveThinkingSupport.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Resolved Anthropic adaptive-thinking capability for a model. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum AdaptiveThinkingSupport { + /** The {@code unsupported} variant. */ + UNSUPPORTED("unsupported"), + /** The {@code optional} variant. */ + OPTIONAL("optional"), + /** The {@code required} variant. */ + REQUIRED("required"); + + private final String value; + AdaptiveThinkingSupport(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static AdaptiveThinkingSupport fromValue(String value) { + for (AdaptiveThinkingSupport v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown AdaptiveThinkingSupport value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AgentDiscoveryPath.java b/java/src/generated/java/com/github/copilot/generated/rpc/AgentDiscoveryPath.java index 93a4bb1f6a..53d48904ff 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AgentDiscoveryPath.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AgentDiscoveryPath.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `AgentDiscoveryPath` type. + * Canonical directory where custom agents can be discovered or created, with scope, preference, and optional project path. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java b/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java index ce80893730..29813e30a0 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java @@ -15,7 +15,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `AgentInfo` type. + * Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/CommandsListResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/CommandsListResult.java new file mode 100644 index 0000000000..9873fa7ff9 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/CommandsListResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Slash commands available in the session, after applying any include/exclude filters. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommandsListResult( + /** Commands available in this session */ + @JsonProperty("commands") List commands +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java index aae84cad39..491dadad37 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java @@ -10,17 +10,23 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** - * Optional connection token presented by the SDK client during the handshake. + * Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record ConnectParams( /** Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN */ - @JsonProperty("token") String token + @JsonProperty("token") String token, + /** Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. */ + @JsonProperty("enableGitHubTelemetryForwarding") Boolean enableGitHubTelemetryForwarding ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ConnectResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/ConnectResult.java index d7184004c0..8c12b57a80 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ConnectResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ConnectResult.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Handshake result reporting the server's protocol version and package version on success. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ContextHeaviestMessage.java b/java/src/generated/java/com/github/copilot/generated/rpc/ContextHeaviestMessage.java new file mode 100644 index 0000000000..818841a3c7 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ContextHeaviestMessage.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A single large message currently in context. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ContextHeaviestMessage( + /** Stable identifier for this message within the snapshot. */ + @JsonProperty("id") String id, + /** Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. */ + @JsonProperty("label") String label, + /** Role of the chat message (`user`, `assistant`, or `tool`). */ + @JsonProperty("role") String role, + /** Token count currently in context for this individual message. */ + @JsonProperty("tokens") Long tokens +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsCollectedEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsCollectedEntry.java new file mode 100644 index 0000000000..9d8592220d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsCollectedEntry.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A file included in the redacted debug bundle. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record DebugCollectLogsCollectedEntry( + /** Relative path of the file in the staged bundle/archive. */ + @JsonProperty("bundlePath") String bundlePath, + /** Source category for this entry. */ + @JsonProperty("source") DebugCollectLogsSource source, + /** Redacted output size in bytes. */ + @JsonProperty("sizeBytes") Long sizeBytes +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsEntry.java new file mode 100644 index 0000000000..285b1ef6e0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsEntry.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A caller-provided server-local file or directory to include in the debug bundle. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record DebugCollectLogsEntry( + /** Kind of source path to include. */ + @JsonProperty("kind") DebugCollectLogsEntryKind kind, + /** Server-local source path to read. */ + @JsonProperty("path") String path, + /** Relative path to use inside the staged bundle/archive. */ + @JsonProperty("bundlePath") String bundlePath, + /** How text content from this entry should be redacted. Defaults to plain-text. */ + @JsonProperty("redaction") DebugCollectLogsRedaction redaction, + /** When true, collection fails if this entry cannot be read. Defaults to false, which records the entry in `skippedEntries`. */ + @JsonProperty("required") Boolean required +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsEntryKind.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsEntryKind.java new file mode 100644 index 0000000000..316b6dcd5a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsEntryKind.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Kind of caller-provided debug log entry. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum DebugCollectLogsEntryKind { + /** The {@code file} variant. */ + FILE("file"), + /** The {@code directory} variant. */ + DIRECTORY("directory"); + + private final String value; + DebugCollectLogsEntryKind(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static DebugCollectLogsEntryKind fromValue(String value) { + for (DebugCollectLogsEntryKind v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown DebugCollectLogsEntryKind value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsInclude.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsInclude.java new file mode 100644 index 0000000000..0cab63830b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsInclude.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Built-in session diagnostics to include in the bundle. Omitted fields default to true. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record DebugCollectLogsInclude( + /** Include the session event log (`events.jsonl`). Defaults to true. */ + @JsonProperty("events") Boolean events, + /** Include process logs for the session. Defaults to true. */ + @JsonProperty("processLogs") Boolean processLogs, + /** Include interactive shell logs written under the session's `shell-logs` directory. Defaults to true. */ + @JsonProperty("shellLogs") Boolean shellLogs, + /** Server-local path to the session's events.jsonl file. Internal callers normally omit this and let the runtime derive it from the session. */ + @JsonProperty("eventsPath") String eventsPath, + /** Server-local path to the current process log. When set, it is included as `process.log` and its directory is searched for prior logs from the same session. */ + @JsonProperty("currentProcessLogPath") String currentProcessLogPath, + /** Server-local process log directory to search when `currentProcessLogPath` is unavailable, useful for collecting logs for inactive sessions. */ + @JsonProperty("processLogDirectory") String processLogDirectory, + /** Maximum number of previous process logs to include. Defaults to 5. */ + @JsonProperty("previousProcessLogLimit") Long previousProcessLogLimit +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsRedaction.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsRedaction.java new file mode 100644 index 0000000000..5f57e37378 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsRedaction.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * How a collected debug entry should be redacted before being staged. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum DebugCollectLogsRedaction { + /** The {@code plain-text} variant. */ + PLAIN_TEXT("plain-text"), + /** The {@code events-jsonl} variant. */ + EVENTS_JSONL("events-jsonl"); + + private final String value; + DebugCollectLogsRedaction(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static DebugCollectLogsRedaction fromValue(String value) { + for (DebugCollectLogsRedaction v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown DebugCollectLogsRedaction value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsResultKind.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsResultKind.java new file mode 100644 index 0000000000..00986bd3fd --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsResultKind.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Destination kind that was written. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum DebugCollectLogsResultKind { + /** The {@code archive} variant. */ + ARCHIVE("archive"), + /** The {@code directory} variant. */ + DIRECTORY("directory"); + + private final String value; + DebugCollectLogsResultKind(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static DebugCollectLogsResultKind fromValue(String value) { + for (DebugCollectLogsResultKind v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown DebugCollectLogsResultKind value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsSkippedEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsSkippedEntry.java new file mode 100644 index 0000000000..a5a702bcda --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsSkippedEntry.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * An optional debug bundle entry that could not be included. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record DebugCollectLogsSkippedEntry( + /** Relative path requested for this bundle entry. */ + @JsonProperty("bundlePath") String bundlePath, + /** Server-local source path that could not be read. */ + @JsonProperty("path") String path, + /** Reason the entry was skipped. */ + @JsonProperty("reason") String reason +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsSource.java new file mode 100644 index 0000000000..989059f459 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DebugCollectLogsSource.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Source category for a collected debug bundle entry. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum DebugCollectLogsSource { + /** The {@code events} variant. */ + EVENTS("events"), + /** The {@code process-log} variant. */ + PROCESS_LOG("process-log"), + /** The {@code shell-log} variant. */ + SHELL_LOG("shell-log"), + /** The {@code additional} variant. */ + ADDITIONAL("additional"); + + private final String value; + DebugCollectLogsSource(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static DebugCollectLogsSource fromValue(String value) { + for (DebugCollectLogsSource v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown DebugCollectLogsSource value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredCanvas.java b/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredCanvas.java index e6e02745c8..0b0c518040 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredCanvas.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredCanvas.java @@ -26,6 +26,8 @@ public record DiscoveredCanvas( @JsonProperty("displayName") String displayName, /** Short, single-sentence description shown to the agent in canvas catalogs. */ @JsonProperty("description") String description, + /** Host-local PNG path for the canvas icon, when supplied */ + @JsonProperty("icon") String icon, /** JSON Schema for canvas open input */ @JsonProperty("inputSchema") Object inputSchema, /** Actions the agent or host may invoke on an open instance */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredMcpServer.java b/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredMcpServer.java index 60fa5271de..3262994c1f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredMcpServer.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/DiscoveredMcpServer.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `DiscoveredMcpServer` type. + * MCP server discovered by `mcp.discover`, with config source, optional plugin source, transport type, and enabled state. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/Extension.java b/java/src/generated/java/com/github/copilot/generated/rpc/Extension.java index 7bbdb5207a..4d3e357cd7 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/Extension.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/Extension.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `Extension` type. + * Discovered extension metadata, including source-qualified ID, name, discovery source, status, and optional process ID. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryClientInfo.java b/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryClientInfo.java new file mode 100644 index 0000000000..7d7a1eaf72 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryClientInfo.java @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Client environment metadata describing the process that produced a telemetry event. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record GitHubTelemetryClientInfo( + /** Copilot CLI version string. */ + @JsonProperty("cli_version") String cliVersion, + /** Operating system platform (e.g. darwin, linux, win32). */ + @JsonProperty("os_platform") String osPlatform, + /** Operating system version string. */ + @JsonProperty("os_version") String osVersion, + /** Operating system architecture (e.g. arm64, x64). */ + @JsonProperty("os_arch") String osArch, + /** Node.js runtime version string. */ + @JsonProperty("node_version") String nodeVersion, + /** Copilot subscription plan, when known. */ + @JsonProperty("copilot_plan") String copilotPlan, + /** Type of client. */ + @JsonProperty("client_type") String clientType, + /** Name of the client application. */ + @JsonProperty("client_name") String clientName, + /** Whether the user is a GitHub/Microsoft staff member. */ + @JsonProperty("is_staff") Boolean isStaff, + /** Stable machine identifier for the device. */ + @JsonProperty("dev_device_id") String devDeviceId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryEvent.java b/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryEvent.java new file mode 100644 index 0000000000..efbf920b4f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryEvent.java @@ -0,0 +1,46 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * A single telemetry event in the runtime's native GitHub-shaped telemetry format, forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing GitHubTelemetryNotification distinguishes standard from restricted events; the payload shape is identical for both. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record GitHubTelemetryEvent( + /** Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed). */ + @JsonProperty("kind") String kind, + /** Timestamp when the event was created (ISO 8601 format). */ + @JsonProperty("created_at") String createdAt, + /** Reference to the model call that produced this event. */ + @JsonProperty("model_call_id") String modelCallId, + /** String-valued properties as a map from key to value. */ + @JsonProperty("properties") Map properties, + /** Numeric metrics as a map from key to value. */ + @JsonProperty("metrics") Map metrics, + /** Experiment assignment context. */ + @JsonProperty("exp_assignment_context") String expAssignmentContext, + /** Feature flags enabled for this session, as a map from flag to value. */ + @JsonProperty("features") Map features, + /** Session identifier the event belongs to. */ + @JsonProperty("session_id") String sessionId, + /** Copilot tracking ID for user-level attribution. */ + @JsonProperty("copilot_tracking_id") String copilotTrackingId, + /** Client environment metadata. */ + @JsonProperty("client") GitHubTelemetryClientInfo client +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryNotification.java b/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryNotification.java new file mode 100644 index 0000000000..6059f1ff6c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/GitHubTelemetryNotification.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record GitHubTelemetryNotification( + /** Session the telemetry event belongs to, when it is session-scoped. Omitted for sessionless events (for example, `server.sendTelemetry` calls with no session id), which are still forwarded to opted-in connections. */ + @JsonProperty("sessionId") String sessionId, + /** Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route restricted events to first-party Microsoft stores only. */ + @JsonProperty("restricted") Boolean restricted, + /** The telemetry event, in the runtime's native GitHub-shaped telemetry format. */ + @JsonProperty("event") GitHubTelemetryEvent event +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HookInvokeRequest.java b/java/src/generated/java/com/github/copilot/generated/rpc/HookInvokeRequest.java new file mode 100644 index 0000000000..9ed02d28b0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HookInvokeRequest.java @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Runtime-owned wire payload for a server-to-client hook callback invocation. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record HookInvokeRequest( + @JsonProperty("sessionId") String sessionId, + @JsonProperty("hookType") HookType hookType, + @JsonProperty("input") Object input +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HookType.java b/java/src/generated/java/com/github/copilot/generated/rpc/HookType.java new file mode 100644 index 0000000000..006f8a7c1f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HookType.java @@ -0,0 +1,63 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Hook event name dispatched through the SDK callback transport. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum HookType { + /** The {@code preToolUse} variant. */ + PRETOOLUSE("preToolUse"), + /** The {@code preMcpToolCall} variant. */ + PREMCPTOOLCALL("preMcpToolCall"), + /** The {@code postToolUse} variant. */ + POSTTOOLUSE("postToolUse"), + /** The {@code postToolUseFailure} variant. */ + POSTTOOLUSEFAILURE("postToolUseFailure"), + /** The {@code userPromptSubmitted} variant. */ + USERPROMPTSUBMITTED("userPromptSubmitted"), + /** The {@code sessionStart} variant. */ + SESSIONSTART("sessionStart"), + /** The {@code sessionEnd} variant. */ + SESSIONEND("sessionEnd"), + /** The {@code postResult} variant. */ + POSTRESULT("postResult"), + /** The {@code prePRDescription} variant. */ + PREPRDESCRIPTION("prePRDescription"), + /** The {@code errorOccurred} variant. */ + ERROROCCURRED("errorOccurred"), + /** The {@code agentStop} variant. */ + AGENTSTOP("agentStop"), + /** The {@code subagentStart} variant. */ + SUBAGENTSTART("subagentStart"), + /** The {@code subagentStop} variant. */ + SUBAGENTSTOP("subagentStop"), + /** The {@code preCompact} variant. */ + PRECOMPACT("preCompact"), + /** The {@code permissionRequest} variant. */ + PERMISSIONREQUEST("permissionRequest"), + /** The {@code notification} variant. */ + NOTIFICATION("notification"); + + private final String value; + HookType(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static HookType fromValue(String value) { + for (HookType v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown HookType value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthSetCredentialsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/HooksInvokeResult.java similarity index 82% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthSetCredentialsResult.java rename to java/src/generated/java/com/github/copilot/generated/rpc/HooksInvokeResult.java index 41fbf68305..a111b7af4e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthSetCredentialsResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HooksInvokeResult.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Indicates whether the credential update succeeded. + * Optional output returned by an SDK callback hook. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,8 +23,7 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionAuthSetCredentialsResult( - /** Whether the operation succeeded */ - @JsonProperty("success") Boolean success +public record HooksInvokeResult( + @JsonProperty("output") Object output ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPlugin.java b/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPlugin.java index c274dfb1a2..b3487e7e31 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPlugin.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPlugin.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `InstalledPlugin` type. + * Installed plugin record from global state, with marketplace, version, install time, enabled state, cache path, and source. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPluginInfo.java b/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPluginInfo.java index 898c5438ed..2f4895690f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPluginInfo.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/InstalledPluginInfo.java @@ -25,6 +25,8 @@ public record InstalledPluginInfo( @JsonProperty("name") String name, /** Marketplace the plugin came from. Empty string ("") for direct repo / URL / local installs. */ @JsonProperty("marketplace") String marketplace, + /** Opaque, stable hash identifying a direct (non-marketplace) install source. Present only for direct repo / URL / local installs; absent for marketplace plugins. Same source yields the same id; distinct sources never collide. */ + @JsonProperty("directSourceId") String directSourceId, /** Installed version (when reported by the plugin manifest) */ @JsonProperty("version") String version, /** Whether the plugin is currently enabled for new sessions */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/InstructionDiscoveryPath.java b/java/src/generated/java/com/github/copilot/generated/rpc/InstructionDiscoveryPath.java index b47451bcd9..213b003c15 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/InstructionDiscoveryPath.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/InstructionDiscoveryPath.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `InstructionDiscoveryPath` type. + * Canonical file or directory where custom instructions can be discovered or created, with location, kind, preference, and project path. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java index 37d1ead1c6..2581375b33 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `InstructionSource` type. + * Loaded instruction source for a session, including path, content, category, location, applicability, and optional description. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestChunkRequest.java b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestChunkRequest.java new file mode 100644 index 0000000000..292033f927 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestChunkRequest.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A request body chunk or cancellation signal. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record LlmInferenceHttpRequestChunkRequest( + /** Matches the requestId from the originating httpRequestStart frame. */ + @JsonProperty("requestId") String requestId, + /** Body byte range. UTF-8 text when `binary` is absent or false; base64-encoded bytes when `binary` is true. May be empty. */ + @JsonProperty("data") String data, + /** When true, `data` is base64-encoded bytes. When absent or false, `data` is UTF-8 text. */ + @JsonProperty("binary") Boolean binary, + /** When true, this is the final body chunk for the request. The SDK may rely on having received an end-marked chunk before treating the request body as complete. */ + @JsonProperty("end") Boolean end, + /** When true, the runtime is cancelling the in-flight request (e.g. upstream consumer aborted). `data` is ignored. Implies end-of-request. */ + @JsonProperty("cancel") Boolean cancel, + /** Optional human-readable reason for the cancellation, propagated for logging. */ + @JsonProperty("cancelReason") String cancelReason +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestChunkResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestChunkResult.java new file mode 100644 index 0000000000..f866fa70c6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestChunkResult.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Acknowledgement. The SDK is free to ignore the ack and treat chunk delivery as fire-and-forget. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record LlmInferenceHttpRequestChunkResult() { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartRequest.java b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartRequest.java new file mode 100644 index 0000000000..a625e4253e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartRequest.java @@ -0,0 +1,44 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * The head of an outbound model-layer HTTP request. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record LlmInferenceHttpRequestStartRequest( + /** Opaque runtime-minted id, unique per in-flight request. The SDK uses this to correlate httpRequestChunk frames and to address its httpResponseStart / httpResponseChunk replies back to the runtime. */ + @JsonProperty("requestId") String requestId, + /** Id of the runtime session that triggered this request, when one is in scope. Absent for requests issued outside any session (e.g. startup model-catalog or capability resolution). This is a payload field — not a dispatch key — because the client-global API is registered process-wide rather than per session. */ + @JsonProperty("sessionId") String sessionId, + /** HTTP method, e.g. GET, POST. */ + @JsonProperty("method") String method, + /** Absolute request URL. */ + @JsonProperty("url") String url, + @JsonProperty("headers") Map> headers, + /** Transport the runtime would otherwise use for this request. `http` (the default when absent) covers plain HTTP and SSE responses; `websocket` indicates a full-duplex message channel where each body chunk maps to one WebSocket message and the `binary` flag distinguishes text from binary frames. The SDK consumer uses this to decide whether to service the request with an HTTP client or a WebSocket client. It is the one piece of request metadata the consumer cannot reliably infer from the URL or headers alone. */ + @JsonProperty("transport") LlmInferenceHttpRequestStartTransport transport, + /** Stable per-agent-instance id attributing this request to a specific agent trajectory. Present when the request originates from an agent turn; absent for requests issued outside any agent context (e.g. some SDK callers). A request with an `agentId` but no `parentAgentId` is a root-agent request; one carrying both is a subagent request. Sourced from the runtime's per-request agent context and surfaced on the envelope independently of transport, so it is available for both first-party (CAPI) and BYOK/custom-provider requests; on the CAPI transport the runtime derives the upstream `X-Agent-Task-Id` header from this same context. Consumers routing each provider call to a training trajectory should key on this rather than on lifecycle events, since it is available on the request path before sampling. */ + @JsonProperty("agentId") String agentId, + /** Id of the parent agent that spawned the agent issuing this request. Present only for subagent requests; absent for root-agent requests and non-agent requests. Combined with `agentId`, this lets consumers attribute a call to a child trajectory versus the root. Like `agentId`, it comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Parent-Agent-Id` header from this same context. */ + @JsonProperty("parentAgentId") String parentAgentId, + /** Coarse classification of the interaction that produced this request. Open string for forward-compatibility; known values include `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, and `conversation-user`. Absent when the runtime did not classify the request. Comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` header from this same context. */ + @JsonProperty("interactionType") String interactionType +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartResult.java new file mode 100644 index 0000000000..28016dcb87 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartResult.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Acknowledgement. Returning successfully simply means the SDK accepted the start frame; it does not imply the request will succeed. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record LlmInferenceHttpRequestStartResult() { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartTransport.java b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartTransport.java new file mode 100644 index 0000000000..1b5aa9a2d9 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/LlmInferenceHttpRequestStartTransport.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Transport the runtime would otherwise use for this request. `http` (the default when absent) covers plain HTTP and SSE responses; `websocket` indicates a full-duplex message channel where each body chunk maps to one WebSocket message and the `binary` flag distinguishes text from binary frames. The SDK consumer uses this to decide whether to service the request with an HTTP client or a WebSocket client. It is the one piece of request metadata the consumer cannot reliably infer from the URL or headers alone. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum LlmInferenceHttpRequestStartTransport { + /** The {@code http} variant. */ + HTTP("http"), + /** The {@code websocket} variant. */ + WEBSOCKET("websocket"); + + private final String value; + LlmInferenceHttpRequestStartTransport(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static LlmInferenceHttpRequestStartTransport fromValue(String value) { + for (LlmInferenceHttpRequestStartTransport v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown LlmInferenceHttpRequestStartTransport value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/LocalSessionMetadataValue.java b/java/src/generated/java/com/github/copilot/generated/rpc/LocalSessionMetadataValue.java index 80d0581990..c7970940a0 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/LocalSessionMetadataValue.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/LocalSessionMetadataValue.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `LocalSessionMetadataValue` type. + * Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/MarketplaceRefreshEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/MarketplaceRefreshEntry.java index c7b6819dcc..31d6310e14 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/MarketplaceRefreshEntry.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/MarketplaceRefreshEntry.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `MarketplaceRefreshEntry` type. + * Per-marketplace refresh result, including marketplace name, success flag, and optional failure error. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpAllowedServer.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpAllowedServer.java index 8474a916c2..1d0a17cc9b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpAllowedServer.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpAllowedServer.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `McpAllowedServer` type. + * MCP server allowed by policy, with server name and optional PII-free explanatory note. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpAppsResourceContent.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpAppsResourceContent.java index 25850f372a..0a0f977ffd 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpAppsResourceContent.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpAppsResourceContent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `McpAppsResourceContent` type. + * MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource metadata. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigAddParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigAddParams.java index 47ce176796..4c8baff2c4 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigAddParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigAddParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * MCP server name and configuration to add to user configuration. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigDisableParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigDisableParams.java index c5f743a8eb..81fab3e4c3 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigDisableParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigDisableParams.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * MCP server names to disable for new sessions. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigEnableParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigEnableParams.java index ae845ecf23..57e882acb2 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigEnableParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigEnableParams.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * MCP server names to enable for new sessions. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigListResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigListResult.java index 048496806f..8100818615 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigListResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigListResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.Map; import javax.annotation.processing.Generated; /** * User-configured MCP servers, keyed by server name. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigRemoveParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigRemoveParams.java index bd646cacaa..81a0aa0e21 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigRemoveParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigRemoveParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * MCP server name to remove from user configuration. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigUpdateParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigUpdateParams.java index b3134cfbf4..082d98318e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigUpdateParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpConfigUpdateParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * MCP server name and replacement configuration to write to user configuration. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverParams.java index 8c44ab7d29..a9e029da35 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Optional working directory used as context for MCP server discovery. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverResult.java index ed75dd92d3..e5131e36d6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpDiscoverResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * MCP servers discovered from user, workspace, plugin, and built-in sources. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java index 9f5e919106..51dbd2bd14 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `McpFilteredServer` type. + * MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpResource.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpResource.java new file mode 100644 index 0000000000..92302772ce --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpResource.java @@ -0,0 +1,47 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, MIME type, size, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record McpResource( + /** The resource URI (e.g. ui://... or file:///...) */ + @JsonProperty("uri") String uri, + /** The programmatic name of the resource */ + @JsonProperty("name") String name, + /** Optional human-readable display title */ + @JsonProperty("title") String title, + /** Optional description of what this resource represents */ + @JsonProperty("description") String description, + /** MIME type of the resource, if known */ + @JsonProperty("mimeType") String mimeType, + /** Resource size in bytes, when known */ + @JsonProperty("size") Long size, + /** Icons associated with this resource */ + @JsonProperty("icons") List icons, + /** Model/client annotations associated with this resource */ + @JsonProperty("annotations") McpResourceAnnotations annotations, + /** Resource-level metadata */ + @JsonProperty("_meta") Map meta, + /** Server-provided non-standard descriptor fields preserved from the MCP response */ + @JsonProperty("additionalProperties") Map additionalProperties +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceAnnotations.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceAnnotations.java new file mode 100644 index 0000000000..6cae65957a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceAnnotations.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Standard MCP resource annotations plus preserved non-standard annotation fields. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record McpResourceAnnotations( + /** Intended audience roles for this resource */ + @JsonProperty("audience") List audience, + /** Priority hint for model/client use */ + @JsonProperty("priority") Double priority, + /** Last-modified timestamp hint */ + @JsonProperty("lastModified") String lastModified, + /** Server-provided non-standard annotation fields preserved from the MCP response */ + @JsonProperty("additionalProperties") Map additionalProperties +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceContent.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceContent.java new file mode 100644 index 0000000000..4967286f15 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceContent.java @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * MCP resource content with URI, optional MIME type, text or base64 blob, and resource metadata. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record McpResourceContent( + /** The resource URI */ + @JsonProperty("uri") String uri, + /** MIME type of the content */ + @JsonProperty("mimeType") String mimeType, + /** Text content (e.g. HTML) */ + @JsonProperty("text") String text, + /** Base64-encoded binary content */ + @JsonProperty("blob") String blob, + /** Resource-level metadata (CSP, permissions, etc.) */ + @JsonProperty("_meta") Map meta +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceIcon.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceIcon.java new file mode 100644 index 0000000000..f5a8c68d34 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceIcon.java @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * A resource icon descriptor plus preserved non-standard icon fields. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record McpResourceIcon( + /** Icon URI */ + @JsonProperty("src") String src, + /** Icon MIME type, when known */ + @JsonProperty("mimeType") String mimeType, + /** Icon sizes hint */ + @JsonProperty("sizes") String sizes, + /** Theme hint for this icon */ + @JsonProperty("theme") String theme, + /** Server-provided non-standard icon fields preserved from the MCP response */ + @JsonProperty("additionalProperties") Map additionalProperties +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceTemplate.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceTemplate.java new file mode 100644 index 0000000000..14ffca372d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpResourceTemplate.java @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, name, and optional title, description, MIME type, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record McpResourceTemplate( + /** An RFC 6570 URI template for constructing resource URIs */ + @JsonProperty("uriTemplate") String uriTemplate, + /** The programmatic name of the resource template */ + @JsonProperty("name") String name, + /** Optional human-readable display title */ + @JsonProperty("title") String title, + /** Optional description of what this template is for */ + @JsonProperty("description") String description, + /** MIME type for resources matching this template, if uniform */ + @JsonProperty("mimeType") String mimeType, + /** Icons associated with resources matching this template */ + @JsonProperty("icons") List icons, + /** Model/client annotations associated with this template */ + @JsonProperty("annotations") McpResourceAnnotations annotations, + /** Resource-template-level metadata */ + @JsonProperty("_meta") Map meta, + /** Server-provided non-standard descriptor fields preserved from the MCP response */ + @JsonProperty("additionalProperties") Map additionalProperties +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpServer.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpServer.java index e410cf5642..382c54c40f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpServer.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpServer.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `McpServer` type. + * MCP server status entry, including config source/plugin source and any connection error. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpToolUi.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpToolUi.java new file mode 100644 index 0000000000..2f4436ca42 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpToolUi.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record McpToolUi( + /** URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use `session.mcp.resources.read` to fetch its HTML and resource metadata. */ + @JsonProperty("resourceUri") String resourceUri, + /** Tool visibility advertised by the server. When absent, MCP Apps defaults apply. */ + @JsonProperty("visibility") List visibility +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpToolUiVisibility.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpToolUiVisibility.java new file mode 100644 index 0000000000..9e73f0c90c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpToolUiVisibility.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Consumer allowed to call an MCP tool. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum McpToolUiVisibility { + /** The {@code model} variant. */ + MODEL("model"), + /** The {@code app} variant. */ + APP("app"); + + private final String value; + McpToolUiVisibility(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static McpToolUiVisibility fromValue(String value) { + for (McpToolUiVisibility v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown McpToolUiVisibility value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpTools.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpTools.java index 31373c1d18..37782f6d31 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpTools.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpTools.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `McpTools` type. + * MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery metadata. * * @since 1.0.0 */ @@ -24,6 +24,8 @@ public record McpTools( /** Tool name. */ @JsonProperty("name") String name, /** Tool description, when provided. */ - @JsonProperty("description") String description + @JsonProperty("description") String description, + /** Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` block was present without recognized fields. */ + @JsonProperty("ui") McpToolUi ui ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/Model.java b/java/src/generated/java/com/github/copilot/generated/rpc/Model.java index 0904519165..c55fc026f6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/Model.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/Model.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `Model` type. + * Copilot model metadata, including identifier, display name, capabilities, policy, billing, reasoning efforts, and picker categories. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java index 94a8188f16..f8298dd624 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java @@ -24,6 +24,10 @@ public record ModelBilling( /** Billing cost multiplier relative to the base rate */ @JsonProperty("multiplier") Double multiplier, /** Token-level pricing information for this model */ - @JsonProperty("tokenPrices") ModelBillingTokenPrices tokenPrices + @JsonProperty("tokenPrices") ModelBillingTokenPrices tokenPrices, + /** Whole-number percentage discount (0-100) applied to usage billed through this model. Populated for the synthetic `auto` model, where requests routed by auto-mode are billed at a reduced rate; absent for concrete models. */ + @JsonProperty("discountPercent") Long discountPercent, + /** Active server-driven promotion for this model, if any. Present when the model is being promoted with a time-boxed discount. */ + @JsonProperty("promo") ModelBillingPromo promo ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelBillingPromo.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBillingPromo.java new file mode 100644 index 0000000000..731e298355 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBillingPromo.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Active server-driven promotion for a model, including its discount and expiry. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ModelBillingPromo( + /** Stable identifier for the promotion campaign. */ + @JsonProperty("id") String id, + /** Percentage discount (0-100) applied while the promotion is active. May be fractional. */ + @JsonProperty("discountPercent") Double discountPercent, + /** UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. */ + @JsonProperty("endsAt") String endsAt, + /** Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. */ + @JsonProperty("message") String message +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesOverrideSupports.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesOverrideSupports.java index ec1da750d8..d210460d73 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesOverrideSupports.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesOverrideSupports.java @@ -24,6 +24,8 @@ public record ModelCapabilitiesOverrideSupports( /** Whether this model supports vision/image input */ @JsonProperty("vision") Boolean vision, /** Whether this model supports reasoning effort configuration */ - @JsonProperty("reasoningEffort") Boolean reasoningEffort + @JsonProperty("reasoningEffort") Boolean reasoningEffort, + /** Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). */ + @JsonProperty("adaptive_thinking") AdaptiveThinkingSupport adaptiveThinking ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesSupports.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesSupports.java index 91a98b423d..b66ba8aa7d 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesSupports.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelCapabilitiesSupports.java @@ -24,6 +24,8 @@ public record ModelCapabilitiesSupports( /** Whether this model supports vision/image input */ @JsonProperty("vision") Boolean vision, /** Whether this model supports reasoning effort configuration */ - @JsonProperty("reasoningEffort") Boolean reasoningEffort + @JsonProperty("reasoningEffort") Boolean reasoningEffort, + /** Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). */ + @JsonProperty("adaptive_thinking") AdaptiveThinkingSupport adaptiveThinking ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelsListResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelsListResult.java index 6c10eeeba4..5a88a01db2 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ModelsListResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelsListResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * List of Copilot models available to the resolved user, including capabilities and billing metadata. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/OpenCanvasInstance.java b/java/src/generated/java/com/github/copilot/generated/rpc/OpenCanvasInstance.java index 9495d21611..f38ba82c4f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/OpenCanvasInstance.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/OpenCanvasInstance.java @@ -29,6 +29,8 @@ public record OpenCanvasInstance( @JsonProperty("extensionName") String extensionName, /** Provider-local canvas identifier */ @JsonProperty("canvasId") String canvasId, + /** Host-local PNG path for the canvas icon, when supplied */ + @JsonProperty("icon") String icon, /** Rendered title */ @JsonProperty("title") String title, /** Provider-supplied status text */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicy.java b/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicy.java index 13360e808d..2864bbd99b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicy.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicy.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `OptionsUpdateAdditionalContentExclusionPolicy` type. + * Content-exclusion policy supplied to `session.options.update`, with rules, last-updated data, and scope. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRule.java b/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRule.java index af6917cb7d..135a7c7f85 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRule.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRule.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRule` type. + * Single content-exclusion rule supplied to `session.options.update`, with paths, match conditions, and source. * * @since 1.0.0 */ @@ -25,7 +25,7 @@ public record OptionsUpdateAdditionalContentExclusionPolicyRule( @JsonProperty("paths") List paths, @JsonProperty("ifAnyMatch") List ifAnyMatch, @JsonProperty("ifNoneMatch") List ifNoneMatch, - /** Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. */ + /** Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. */ @JsonProperty("source") OptionsUpdateAdditionalContentExclusionPolicyRuleSource source ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRuleSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRuleSource.java index 8befe476ec..a363722801 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRuleSource.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/OptionsUpdateAdditionalContentExclusionPolicyRuleSource.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. + * Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PendingPermissionRequest.java b/java/src/generated/java/com/github/copilot/generated/rpc/PendingPermissionRequest.java index de370ca5d6..7042864b01 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PendingPermissionRequest.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PendingPermissionRequest.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `PendingPermissionRequest` type. + * Pending permission prompt reconstructed from event history, with request ID and user-facing prompt details. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionRule.java b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionRule.java index 7980e0e832..8e7a6c769e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionRule.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionRule.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `PermissionRule` type. + * A permission approval or denial rule matched against a tool request, identified by a rule kind with an optional argument value. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsAllowAllMode.java b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsAllowAllMode.java new file mode 100644 index 0000000000..db24a2bad1 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsAllowAllMode.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Current or requested allow-all mode. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum PermissionsAllowAllMode { + /** The {@code off} variant. */ + OFF("off"), + /** The {@code on} variant. */ + ON("on"), + /** The {@code auto} variant. */ + AUTO("auto"); + + private final String value; + PermissionsAllowAllMode(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static PermissionsAllowAllMode fromValue(String value) { + for (PermissionsAllowAllMode v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown PermissionsAllowAllMode value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicy.java b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicy.java index 61108c16bb..249c7598d9 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicy.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicy.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. + * Content-exclusion policy supplied to `session.permissions.configure`, with rules, last-updated data, and scope. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRule.java b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRule.java index c6c7f649a9..b1afc50fcd 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRule.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRule.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRule` type. + * Single content-exclusion rule supplied to `session.permissions.configure`, with paths, match conditions, and source. * * @since 1.0.0 */ @@ -25,7 +25,7 @@ public record PermissionsConfigureAdditionalContentExclusionPolicyRule( @JsonProperty("paths") List paths, @JsonProperty("ifAnyMatch") List ifAnyMatch, @JsonProperty("ifNoneMatch") List ifNoneMatch, - /** Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. */ + /** Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. */ @JsonProperty("source") PermissionsConfigureAdditionalContentExclusionPolicyRuleSource source ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRuleSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRuleSource.java index a5d4a45f32..f592ae7991 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRuleSource.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PermissionsConfigureAdditionalContentExclusionPolicyRuleSource.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. + * Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PingParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/PingParams.java index 7eb9e06232..841688e1bd 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PingParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PingParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Optional message to echo back to the caller. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PingResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/PingResult.java index 021ebed853..3199f706d9 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PingResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PingResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.time.OffsetDateTime; import javax.annotation.processing.Generated; /** * Server liveness response, including the echoed message, current server timestamp, and protocol version. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/Plugin.java b/java/src/generated/java/com/github/copilot/generated/rpc/Plugin.java index b10cd31cf7..65268ab6e3 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/Plugin.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/Plugin.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `Plugin` type. + * Session plugin metadata, with name, marketplace, optional version, and enabled state. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PluginUpdateAllEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/PluginUpdateAllEntry.java index 548ee39314..dab44f1688 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PluginUpdateAllEntry.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PluginUpdateAllEntry.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `PluginUpdateAllEntry` type. + * Per-plugin result from updating all plugins, with versions, skills installed, success flag, and optional error. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesAddParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesAddParams.java index f33ade9a02..f4d00d7c16 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesAddParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesAddParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Marketplace source to register. + * Marketplace source and optional working directory for relative-path resolution. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -25,6 +25,8 @@ @JsonIgnoreProperties(ignoreUnknown = true) public record PluginsMarketplacesAddParams( /** Marketplace source. Accepts the same forms as the CLI: "owner/repo" or "owner/repo#ref" (GitHub), an http/https/ssh URL (optionally with #ref), a git scp-style URL (user@host:path), or a local path. The marketplace's own name (from its manifest) is used as the registration key. */ - @JsonProperty("source") String source + @JsonProperty("source") String source, + /** Working directory used to resolve relative local paths in `source`. Defaults to the server's current working directory. */ + @JsonProperty("workingDirectory") String workingDirectory ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PluginsUninstallParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/PluginsUninstallParams.java index 630bbd19e7..fb1fbeb8cf 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/PluginsUninstallParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PluginsUninstallParams.java @@ -25,6 +25,8 @@ @JsonIgnoreProperties(ignoreUnknown = true) public record PluginsUninstallParams( /** Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the fully-qualified spec. */ - @JsonProperty("name") String name + @JsonProperty("name") String name, + /** Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall when multiple installed plugins share the same name. */ + @JsonProperty("directSourceId") String directSourceId ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java b/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java index bfbc87f463..8767e91d0d 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `QueuePendingItems` type. + * User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java b/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java index d3d7b901fa..9b8b53c816 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.List; import javax.annotation.processing.Generated; /** @@ -25,10 +24,6 @@ public record SandboxConfigUserPolicyNetwork( /** Whether outbound network traffic is allowed at all. */ @JsonProperty("allowOutbound") Boolean allowOutbound, /** Whether traffic to local/loopback addresses is allowed. */ - @JsonProperty("allowLocalNetwork") Boolean allowLocalNetwork, - /** Hosts allowed in addition to the base policy. */ - @JsonProperty("allowedHosts") List allowedHosts, - /** Hosts explicitly blocked. */ - @JsonProperty("blockedHosts") List blockedHosts + @JsonProperty("allowLocalNetwork") Boolean allowLocalNetwork ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ScheduleEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/ScheduleEntry.java index 5ffd0a7cdd..b88a79cca1 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ScheduleEntry.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ScheduleEntry.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ScheduleEntry` type. + * Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesParams.java index d0f5003f9c..6616a3d6df 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesParams.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * Secret values to add to the redaction filter. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesResult.java index 61eb3fb63c..b2e3251c74 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SecretsAddFilterValuesResult.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Confirmation that the secret values were registered. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SendMessageItem.java b/java/src/generated/java/com/github/copilot/generated/rpc/SendMessageItem.java new file mode 100644 index 0000000000..bdb37cd9fd --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SendMessageItem.java @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * A single user message to append to the session as part of a `session.sendMessages` turn + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SendMessageItem( + /** The user message text */ + @JsonProperty("prompt") String prompt, + /** If provided, this is shown in the timeline instead of `prompt` */ + @JsonProperty("displayPrompt") String displayPrompt, + /** Optional attachments (files, directories, selections, blobs, GitHub references) to include with this message */ + @JsonProperty("attachments") List attachments, + /** If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. */ + @JsonProperty("billable") Boolean billable, + /** If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange */ + @JsonProperty("requiredTool") String requiredTool, + /** Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. */ + @JsonProperty("source") String source +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java index b750596b55..4b7cf718ee 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.List; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -28,40 +29,55 @@ public final class ServerAccountApi { /** * Optional GitHub token used to look up quota for a specific user instead of the global auth context. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture getQuota() { return caller.invoke("account.getQuota", java.util.Map.of(), AccountGetQuotaResult.class); } /** * Current authentication state + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture getCurrentAuth() { return caller.invoke("account.getCurrentAuth", java.util.Map.of(), AccountGetCurrentAuthResult.class); } /** * List of all authenticated users + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture> getAllUsers() { return caller.invoke("account.getAllUsers", java.util.Map.of(), RpcMapper.INSTANCE.getTypeFactory().constructCollectionType(List.class, AccountAllUsers.class)); } /** * Credentials to store after successful authentication + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture login(AccountLoginParams params) { return caller.invoke("account.login", params, AccountLoginResult.class); } /** * User to log out + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture logout(AccountLogoutParams params) { return caller.invoke("account.logout", params, AccountLogoutResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerCommandsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerCommandsApi.java new file mode 100644 index 0000000000..efa5317ea4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerCommandsApi.java @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code commands} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class ServerCommandsApi { + + private final RpcCaller caller; + + /** @param caller the RPC transport function */ + ServerCommandsApi(RpcCaller caller) { + this.caller = caller; + } + + /** + * Slash commands available in the session, after applying any include/exclude filters. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture list() { + return caller.invoke("commands.list", java.util.Map.of(), CommandsListResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpApi.java index 6ff26e80dd..b29c27fa4c 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -31,8 +32,11 @@ public final class ServerMcpApi { /** * Optional working directory used as context for MCP server discovery. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture discover(McpDiscoverParams params) { return caller.invoke("mcp.discover", params, McpDiscoverResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpConfigApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpConfigApi.java index ce5974f5b5..6d3510f515 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpConfigApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerMcpConfigApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,56 +28,77 @@ public final class ServerMcpConfigApi { /** * User-configured MCP servers, keyed by server name. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture list() { return caller.invoke("mcp.config.list", java.util.Map.of(), McpConfigListResult.class); } /** * MCP server name and configuration to add to user configuration. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture add(McpConfigAddParams params) { return caller.invoke("mcp.config.add", params, Void.class); } /** * MCP server name and replacement configuration to write to user configuration. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture update(McpConfigUpdateParams params) { return caller.invoke("mcp.config.update", params, Void.class); } /** * MCP server name to remove from user configuration. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture remove(McpConfigRemoveParams params) { return caller.invoke("mcp.config.remove", params, Void.class); } /** * MCP server names to enable for new sessions. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture enable(McpConfigEnableParams params) { return caller.invoke("mcp.config.enable", params, Void.class); } /** * MCP server names to disable for new sessions. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture disable(McpConfigDisableParams params) { return caller.invoke("mcp.config.disable", params, Void.class); } /** * Invokes {@code mcp.config.reload}. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture reload() { return caller.invoke("mcp.config.reload", java.util.Map.of(), Void.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java index c0515a06f4..64ccc62cde 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,8 +28,11 @@ public final class ServerModelsApi { /** * Optional GitHub token used to list models for a specific user instead of the global auth context. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture list() { return caller.invoke("models.list", java.util.Map.of(), ModelsListResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java index 3d8ced5848..47b239a0c0 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java @@ -38,7 +38,7 @@ public CompletableFuture list() { } /** - * Marketplace source to register. + * Marketplace source and optional working directory for relative-path resolution. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerRpc.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerRpc.java index 9b90cea4a9..033fe8bf3e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerRpc.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerRpc.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -42,6 +43,8 @@ public final class ServerRpc { public final ServerAgentsApi agents; /** API methods for the {@code instructions} namespace. */ public final ServerInstructionsApi instructions; + /** API methods for the {@code commands} namespace. */ + public final ServerCommandsApi commands; /** API methods for the {@code user} namespace. */ public final ServerUserApi user; /** API methods for the {@code runtime} namespace. */ @@ -71,6 +74,7 @@ public ServerRpc(RpcCaller caller) { this.skills = new ServerSkillsApi(caller); this.agents = new ServerAgentsApi(caller); this.instructions = new ServerInstructionsApi(caller); + this.commands = new ServerCommandsApi(caller); this.user = new ServerUserApi(caller); this.runtime = new ServerRuntimeApi(caller); this.sessionFs = new ServerSessionFsApi(caller); @@ -81,16 +85,22 @@ public ServerRpc(RpcCaller caller) { /** * Optional message to echo back to the caller. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture ping(PingParams params) { return caller.invoke("ping", params, PingResult.class); } /** - * Optional connection token presented by the SDK client during the handshake. + * Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture connect(ConnectParams params) { return caller.invoke("connect", params, ConnectResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerRuntimeApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerRuntimeApi.java index 9c98df9682..e57db70946 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerRuntimeApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerRuntimeApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,8 +28,11 @@ public final class ServerRuntimeApi { /** * Invokes {@code runtime.shutdown}. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture shutdown() { return caller.invoke("runtime.shutdown", java.util.Map.of(), Void.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSecretsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSecretsApi.java index 800722c858..7f17687818 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSecretsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSecretsApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,8 +28,11 @@ public final class ServerSecretsApi { /** * Secret values to add to the redaction filter. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture addFilterValues(SecretsAddFilterValuesParams params) { return caller.invoke("secrets.addFilterValues", params, SecretsAddFilterValuesResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionFsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionFsApi.java index 93022becf2..5f540897eb 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionFsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionFsApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,8 +28,11 @@ public final class ServerSessionFsApi { /** * Initial working directory, session-state path layout, and path conventions used to register the calling SDK client as the session filesystem provider. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture setProvider(SessionFsSetProviderParams params) { return caller.invoke("sessionFs.setProvider", params, SessionFsSetProviderResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java index 263c111d38..7e3b4d90d8 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java @@ -55,8 +55,8 @@ public CompletableFuture fork(SessionsForkParams params) { * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture connect() { - return caller.invoke("sessions.connect", java.util.Map.of(), SessionsConnectResult.class); + public CompletableFuture connect(SessionsConnectParams params) { + return caller.invoke("sessions.connect", params, SessionsConnectResult.class); } /** @@ -110,8 +110,8 @@ public CompletableFuture getLastForContext(Sess * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture getEventFilePath() { - return caller.invoke("sessions.getEventFilePath", java.util.Map.of(), SessionsGetEventFilePathResult.class); + public CompletableFuture getEventFilePath(SessionsGetEventFilePathParams params) { + return caller.invoke("sessions.getEventFilePath", params, SessionsGetEventFilePathResult.class); } /** @@ -143,8 +143,8 @@ public CompletableFuture checkInUse(SessionsCheckInUse * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture getPersistedRemoteSteerable() { - return caller.invoke("sessions.getPersistedRemoteSteerable", java.util.Map.of(), SessionsGetPersistedRemoteSteerableResult.class); + public CompletableFuture getPersistedRemoteSteerable(SessionsGetPersistedRemoteSteerableParams params) { + return caller.invoke("sessions.getPersistedRemoteSteerable", params, SessionsGetPersistedRemoteSteerableResult.class); } /** @@ -154,8 +154,8 @@ public CompletableFuture getPersisted * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture close() { - return caller.invoke("sessions.close", java.util.Map.of(), Void.class); + public CompletableFuture close(SessionsCloseParams params) { + return caller.invoke("sessions.close", params, Void.class); } /** @@ -187,8 +187,8 @@ public CompletableFuture pruneOld(SessionsPruneOldParams * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture save() { - return caller.invoke("sessions.save", java.util.Map.of(), Void.class); + public CompletableFuture save(SessionsSaveParams params) { + return caller.invoke("sessions.save", params, Void.class); } /** @@ -198,8 +198,8 @@ public CompletableFuture save() { * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture releaseLock() { - return caller.invoke("sessions.releaseLock", java.util.Map.of(), Void.class); + public CompletableFuture releaseLock(SessionsReleaseLockParams params) { + return caller.invoke("sessions.releaseLock", params, Void.class); } /** @@ -231,8 +231,8 @@ public CompletableFuture reloadPluginHooks(SessionsReloadPluginHooksParams * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture loadDeferredRepoHooks() { - return caller.invoke("sessions.loadDeferredRepoHooks", java.util.Map.of(), SessionsLoadDeferredRepoHooksResult.class); + public CompletableFuture loadDeferredRepoHooks(SessionsLoadDeferredRepoHooksParams params) { + return caller.invoke("sessions.loadDeferredRepoHooks", params, SessionsLoadDeferredRepoHooksResult.class); } /** @@ -253,8 +253,8 @@ public CompletableFuture setAdditionalPlugins(SessionsSetAdditionalPlugins * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture getBoardEntryCount() { - return caller.invoke("sessions.getBoardEntryCount", java.util.Map.of(), SessionsGetBoardEntryCountResult.class); + public CompletableFuture getBoardEntryCount(SessionsGetBoardEntryCountParams params) { + return caller.invoke("sessions.getBoardEntryCount", params, SessionsGetBoardEntryCountResult.class); } /** @@ -312,17 +312,6 @@ public CompletableFuture getRemoteControlS return caller.invoke("sessions.getRemoteControlStatus", java.util.Map.of(), SessionsGetRemoteControlStatusResult.class); } - /** - * Cursor and optional long-poll wait for polling runtime-spawned sessions. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture pollSpawnedSessions() { - return caller.invoke("sessions.pollSpawnedSessions", java.util.Map.of(), SessionsPollSpawnedSessionsResult.class); - } - /** * Params to attach an extension loader's tools to a session. * diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkill.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkill.java index 9752907e96..3498245262 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkill.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkill.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `ServerSkill` type. + * Server-side skill metadata, including name, description, source, enabled/invocable state, path, project path, and argument hint. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsApi.java index 8dc4b19112..a7328dd567 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsApi.java @@ -32,8 +32,11 @@ public final class ServerSkillsApi { /** * Optional project paths and additional skill directories to include in discovery. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture discover(SkillsDiscoverParams params) { return caller.invoke("skills.discover", params, SkillsDiscoverResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsConfigApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsConfigApi.java index e552227ccb..688288a118 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsConfigApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSkillsConfigApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,8 +28,11 @@ public final class ServerSkillsConfigApi { /** * Skill names to mark as disabled in global configuration, replacing any previous list. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture setDisabledSkills(SkillsConfigSetDisabledSkillsParams params) { return caller.invoke("skills.config.setDisabledSkills", params, Void.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerToolsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerToolsApi.java index 10e64747ef..2938010010 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerToolsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerToolsApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,8 +28,11 @@ public final class ServerToolsApi { /** * Optional model identifier whose tool overrides should be applied to the listing. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture list(ToolsListParams params) { return caller.invoke("tools.list", params, ToolsListResult.class); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerUserSettingsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerUserSettingsApi.java index 0f11436e32..665cfb107a 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerUserSettingsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerUserSettingsApi.java @@ -7,6 +7,7 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import java.util.concurrent.CompletableFuture; import javax.annotation.processing.Generated; @@ -27,10 +28,35 @@ public final class ServerUserSettingsApi { /** * Invokes {@code user.settings.reload}. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ + @CopilotExperimental public CompletableFuture reload() { return caller.invoke("user.settings.reload", java.util.Map.of(), Void.class); } + /** + * Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture get() { + return caller.invoke("user.settings.get", java.util.Map.of(), UserSettingsGetResult.class); + } + + /** + * Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture set(UserSettingsSetParams params) { + return caller.invoke("user.settings.set", params, UserSettingsSetResult.class); + } + } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCanvasOpenResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCanvasOpenResult.java index 1d4e0bdf53..7678d1d6a8 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCanvasOpenResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCanvasOpenResult.java @@ -32,6 +32,8 @@ public record SessionCanvasOpenResult( @JsonProperty("extensionName") String extensionName, /** Provider-local canvas identifier */ @JsonProperty("canvasId") String canvasId, + /** Host-local PNG path for the canvas icon, when supplied */ + @JsonProperty("icon") String icon, /** Rendered title */ @JsonProperty("title") String title, /** Provider-supplied status text */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionItem.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionItem.java new file mode 100644 index 0000000000..107e43d64e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionItem.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` (UTF-16 code units) in the composer with `insertText`; when the range is absent, the active token around the cursor is replaced. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionCompletionItem( + /** Text spliced into the composer when the item is accepted. */ + @JsonProperty("insertText") String insertText, + /** Start of the replacement range in `text`, in UTF-16 code units. */ + @JsonProperty("rangeStart") Long rangeStart, + /** End (exclusive) of the replacement range in `text`, in UTF-16 code units. */ + @JsonProperty("rangeEnd") Long rangeEnd, + /** Primary display label for the picker row. Falls back to `insertText` when absent. */ + @JsonProperty("label") String label, + /** Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the host's display kind. */ + @JsonProperty("kind") String kind +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsApi.java new file mode 100644 index 0000000000..6b9d8aa252 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsApi.java @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code completions} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionCompletionsApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionCompletionsApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getTriggerCharacters() { + return caller.invoke("session.completions.getTriggerCharacters", java.util.Map.of("sessionId", this.sessionId), SessionCompletionsGetTriggerCharactersResult.class); + } + + /** + * Request host-driven completions for the current composer input. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture request(SessionCompletionsRequestParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.completions.request", _p, SessionCompletionsRequestResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsGetTriggerCharactersParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsGetTriggerCharactersParams.java new file mode 100644 index 0000000000..6a40aa402e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsGetTriggerCharactersParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionCompletionsGetTriggerCharactersParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsGetTriggerCharactersResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsGetTriggerCharactersResult.java new file mode 100644 index 0000000000..03c28665e6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsGetTriggerCharactersResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionCompletionsGetTriggerCharactersResult( + /** Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. */ + @JsonProperty("triggerCharacters") List triggerCharacters +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsRequestParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsRequestParams.java new file mode 100644 index 0000000000..02ccd7b12e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsRequestParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request host-driven completions for the current composer input. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionCompletionsRequestParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** The full composed composer input. */ + @JsonProperty("text") String text, + /** Cursor offset within `text`, in UTF-16 code units. */ + @JsonProperty("offset") Long offset +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsRequestResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsRequestResult.java new file mode 100644 index 0000000000..ff450a8c9e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCompletionsRequestResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionCompletionsRequestResult( + /** Completion items in host-ranked order. */ + @JsonProperty("items") List items +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugApi.java new file mode 100644 index 0000000000..e0ca94374a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugApi.java @@ -0,0 +1,49 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code debug} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionDebugApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionDebugApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * Options for collecting a redacted session debug bundle. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture collectLogs(SessionDebugCollectLogsParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.debug.collectLogs", _p, SessionDebugCollectLogsResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugCollectLogsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugCollectLogsParams.java new file mode 100644 index 0000000000..2076e2ad7d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugCollectLogsParams.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Options for collecting a redacted session debug bundle. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionDebugCollectLogsParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Where the redacted bundle should be written. Use `archive` to produce a .tgz, or `directory` to stage redacted files for caller-managed upload/post-processing. */ + @JsonProperty("destination") Object destination, + /** Which built-in session diagnostics to include. Omitted fields default to true. */ + @JsonProperty("include") DebugCollectLogsInclude include, + /** Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. */ + @JsonProperty("additionalEntries") List additionalEntries +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugCollectLogsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugCollectLogsResult.java new file mode 100644 index 0000000000..623792b02b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionDebugCollectLogsResult.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Result of collecting a redacted debug bundle. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionDebugCollectLogsResult( + /** Destination kind that was written. */ + @JsonProperty("kind") DebugCollectLogsResultKind kind, + /** Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. */ + @JsonProperty("path") String path, + /** Files included in the redacted bundle. */ + @JsonProperty("entries") List entries, + /** Optional files or directories that could not be included. */ + @JsonProperty("skippedEntries") List skippedEntries +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogRegisterInterestParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogRegisterInterestParams.java index af0bca43ea..567156cc5e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogRegisterInterestParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogRegisterInterestParams.java @@ -26,7 +26,7 @@ public record SessionEventLogRegisterInterestParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates the full interactive OAuth flow to the consumer; when no interest is registered the runtime installs a browserless fallback that silently reuses cached tokens). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. */ + /** The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. */ @JsonProperty("eventType") String eventType ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsReaddirWithTypesEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsReaddirWithTypesEntry.java index f4c755951d..3afa7fe120 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsReaddirWithTypesEntry.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsReaddirWithTypesEntry.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SessionFsReaddirWithTypesEntry` type. + * Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderParams.java index 8003bdbb18..bcc1d964ef 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Initial working directory, session-state path layout, and path conventions used to register the calling SDK client as the session filesystem provider. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderResult.java index 222e160560..4809f53028 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSetProviderResult.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Indicates whether the calling client was registered as the session filesystem provider. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthApi.java similarity index 72% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthApi.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthApi.java index 253ee86931..93fb871501 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthApi.java @@ -12,12 +12,12 @@ import javax.annotation.processing.Generated; /** - * API methods for the {@code auth} namespace. + * API methods for the {@code gitHubAuth} namespace. * * @since 1.0.0 */ @javax.annotation.processing.Generated("copilot-sdk-codegen") -public final class SessionAuthApi { +public final class SessionGitHubAuthApi { private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; @@ -25,7 +25,7 @@ public final class SessionAuthApi { private final String sessionId; /** @param caller the RPC transport function */ - SessionAuthApi(RpcCaller caller, String sessionId) { + SessionGitHubAuthApi(RpcCaller caller, String sessionId) { this.caller = caller; this.sessionId = sessionId; } @@ -37,8 +37,8 @@ public final class SessionAuthApi { * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture getStatus() { - return caller.invoke("session.auth.getStatus", java.util.Map.of("sessionId", this.sessionId), SessionAuthGetStatusResult.class); + public CompletableFuture getStatus() { + return caller.invoke("session.gitHubAuth.getStatus", java.util.Map.of("sessionId", this.sessionId), SessionGitHubAuthGetStatusResult.class); } /** @@ -51,10 +51,10 @@ public CompletableFuture getStatus() { * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture setCredentials(SessionAuthSetCredentialsParams params) { + public CompletableFuture setCredentials(SessionGitHubAuthSetCredentialsParams params) { com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); _p.put("sessionId", this.sessionId); - return caller.invoke("session.auth.setCredentials", _p, SessionAuthSetCredentialsResult.class); + return caller.invoke("session.gitHubAuth.setCredentials", _p, SessionGitHubAuthSetCredentialsResult.class); } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthGetStatusParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthGetStatusParams.java new file mode 100644 index 0000000000..f959105c90 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthGetStatusParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionGitHubAuthGetStatusParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthGetStatusResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthGetStatusResult.java similarity index 97% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthGetStatusResult.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthGetStatusResult.java index c1bbbc4185..9357f00791 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthGetStatusResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthGetStatusResult.java @@ -23,7 +23,7 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionAuthGetStatusResult( +public record SessionGitHubAuthGetStatusResult( /** Whether the session has resolved authentication */ @JsonProperty("isAuthenticated") Boolean isAuthenticated, /** Authentication type */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthSetCredentialsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthSetCredentialsParams.java similarity index 65% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthSetCredentialsParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthSetCredentialsParams.java index 145b241aaf..1d41404d45 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthSetCredentialsParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthSetCredentialsParams.java @@ -23,10 +23,10 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionAuthSetCredentialsParams( +public record SessionGitHubAuthSetCredentialsParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime stores the value verbatim and uses it for outbound model/API requests; it does NOT re-validate or re-fetch the associated Copilot user response. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. */ + /** The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime installs the supplied value immediately for outbound model/API requests. When the credential carries a raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous install) so plan/quota/billing metadata regains fidelity; on resolution failure the verbatim credential remains installed. It does NOT otherwise validate the credential. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. */ @JsonProperty("credentials") Object credentials ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthSetCredentialsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthSetCredentialsResult.java new file mode 100644 index 0000000000..50715193a8 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionGitHubAuthSetCredentialsResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Indicates whether the credential update succeeded. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionGitHubAuthSetCredentialsResult( + /** Whether the operation succeeded */ + @JsonProperty("success") Boolean success, + /** Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). */ + @JsonProperty("copilotUserResolved") Boolean copilotUserResolved +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionInstalledPlugin.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionInstalledPlugin.java index 5d14285586..ee1bc71544 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionInstalledPlugin.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionInstalledPlugin.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SessionInstalledPlugin` type. + * Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsPollSpawnedSessionsEvent.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitsConfig.java similarity index 78% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionsPollSpawnedSessionsEvent.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitsConfig.java index 09b6ed1134..10b625f8a8 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsPollSpawnedSessionsEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitsConfig.java @@ -13,15 +13,15 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SessionsPollSpawnedSessionsEvent` type. + * Optional session limits. * * @since 1.0.0 */ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionsPollSpawnedSessionsEvent( - /** Session id of the newly-spawned session. */ - @JsonProperty("sessionId") String sessionId +public record SessionLimitsConfig( + /** Maximum AI Credits allowed across the session's current accounting window. */ + @JsonProperty("maxAiCredits") Double maxAiCredits ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java index 4246b11f82..172f6e5075 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java @@ -26,15 +26,21 @@ public final class SessionMcpApi { /** API methods for the {@code mcp.oauth} sub-namespace. */ public final SessionMcpOauthApi oauth; + /** API methods for the {@code mcp.headers} sub-namespace. */ + public final SessionMcpHeadersApi headers; /** API methods for the {@code mcp.apps} sub-namespace. */ public final SessionMcpAppsApi apps; + /** API methods for the {@code mcp.resources} sub-namespace. */ + public final SessionMcpResourcesApi resources; /** @param caller the RPC transport function */ SessionMcpApi(RpcCaller caller, String sessionId) { this.caller = caller; this.sessionId = sessionId; this.oauth = new SessionMcpOauthApi(caller, sessionId); + this.headers = new SessionMcpHeadersApi(caller, sessionId); this.apps = new SessionMcpAppsApi(caller, sessionId); + this.resources = new SessionMcpResourcesApi(caller, sessionId); } /** @@ -199,7 +205,7 @@ public CompletableFuture configureGitHub(Sessio } /** - * Server name and opaque configuration for an individual MCP server start. + * Server name and configuration for an individual MCP server start. *

* Note: the {@code sessionId} field in the params record is overridden * by the session-scoped wrapper; any value provided is ignored. @@ -215,7 +221,7 @@ public CompletableFuture startServer(SessionMcpStartServerParams params) { } /** - * Server name and opaque configuration for an individual MCP server restart. + * Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. *

* Note: the {@code sessionId} field in the params record is overridden * by the session-scoped wrapper; any value provided is ignored. diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersApi.java new file mode 100644 index 0000000000..45679f83a4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersApi.java @@ -0,0 +1,49 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code mcp.headers} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionMcpHeadersApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionMcpHeadersApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * MCP headers refresh request id and the host response. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture handlePendingHeadersRefreshRequest(SessionMcpHeadersHandlePendingHeadersRefreshRequestParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.mcp.headers.handlePendingHeadersRefreshRequest", _p, SessionMcpHeadersHandlePendingHeadersRefreshRequestResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersHandlePendingHeadersRefreshRequestParams.java similarity index 75% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersHandlePendingHeadersRefreshRequestParams.java index 9757a95388..77ce6f7329 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersHandlePendingHeadersRefreshRequestParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * MCP OAuth request id and optional provider response. + * MCP headers refresh request id and the host response. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,12 +23,12 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionMcpOauthRespondParams( +public record SessionMcpHeadersHandlePendingHeadersRefreshRequestParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** OAuth request identifier from mcp.oauth_required */ + /** Headers refresh request identifier from mcp.headers_refresh_required */ @JsonProperty("requestId") String requestId, - /** In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be serialized across the JSON-RPC boundary. */ - @JsonProperty("provider") Object provider + /** Host response: supply dynamic headers or decline this refresh. */ + @JsonProperty("result") Object result ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersHandlePendingHeadersRefreshRequestResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersHandlePendingHeadersRefreshRequestResult.java new file mode 100644 index 0000000000..a890713060 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpHeadersHandlePendingHeadersRefreshRequestResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Indicates whether the pending MCP headers refresh response was accepted. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpHeadersHandlePendingHeadersRefreshRequestResult( + /** Whether the response was accepted. False if the request was unknown, timed out, or already resolved. */ + @JsonProperty("success") Boolean success +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java index 7b5e93c416..7b7f7b82bd 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java @@ -30,22 +30,6 @@ public final class SessionMcpOauthApi { this.sessionId = sessionId; } - /** - * MCP OAuth request id and optional provider response. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture respond(SessionMcpOauthRespondParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.mcp.oauth.respond", _p, Void.class); - } - /** * Pending MCP OAuth request ID and host-provided token or cancellation response. *

diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesApi.java new file mode 100644 index 0000000000..c1a30e135d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesApi.java @@ -0,0 +1,81 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code mcp.resources} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionMcpResourcesApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionMcpResourcesApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * MCP server and resource URI to fetch. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture read(SessionMcpResourcesReadParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.mcp.resources.read", _p, SessionMcpResourcesReadResult.class); + } + + /** + * MCP server whose resources to enumerate. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture list(SessionMcpResourcesListParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.mcp.resources.list", _p, SessionMcpResourcesListResult.class); + } + + /** + * MCP server whose resource templates to enumerate. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture listTemplates(SessionMcpResourcesListTemplatesParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.mcp.resources.listTemplates", _p, SessionMcpResourcesListTemplatesResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsPollSpawnedSessionsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListParams.java similarity index 72% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionsPollSpawnedSessionsResult.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListParams.java index e5ca0c0857..bd8a9de64b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsPollSpawnedSessionsResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListParams.java @@ -11,11 +11,10 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.copilot.CopilotExperimental; -import java.util.List; import javax.annotation.processing.Generated; /** - * Batch of spawn events plus a cursor for follow-up polls. + * MCP server whose resources to enumerate. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -24,10 +23,12 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionsPollSpawnedSessionsResult( - /** Spawn events emitted since the supplied cursor. */ - @JsonProperty("events") List events, - /** Opaque cursor to pass back to receive only events after this batch. */ +public record SessionMcpResourcesListParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Name of the MCP server whose resources to enumerate */ + @JsonProperty("serverName") String serverName, + /** Opaque MCP pagination cursor from a prior `nextCursor` value */ @JsonProperty("cursor") String cursor ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListResult.java new file mode 100644 index 0000000000..b7e1042cfc --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListResult.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * One page of resources advertised by the named MCP server. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpResourcesListResult( + /** Resources advertised by the server (proxied MCP `resources/list`) */ + @JsonProperty("resources") List resources, + /** Opaque cursor for the next page, if the server has more resources */ + @JsonProperty("nextCursor") String nextCursor +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListTemplatesParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListTemplatesParams.java new file mode 100644 index 0000000000..a58252c766 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListTemplatesParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * MCP server whose resource templates to enumerate. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpResourcesListTemplatesParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Name of the MCP server whose resource templates to enumerate */ + @JsonProperty("serverName") String serverName, + /** Opaque MCP pagination cursor from a prior `nextCursor` value */ + @JsonProperty("cursor") String cursor +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListTemplatesResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListTemplatesResult.java new file mode 100644 index 0000000000..9cb3ff0569 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesListTemplatesResult.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * One page of resource templates advertised by the named MCP server. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpResourcesListTemplatesResult( + /** Resource templates advertised by the server (proxied MCP `resources/templates/list`) */ + @JsonProperty("resourceTemplates") List resourceTemplates, + /** Opaque cursor for the next page, if the server has more resource templates */ + @JsonProperty("nextCursor") String nextCursor +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesReadParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesReadParams.java new file mode 100644 index 0000000000..5c7b9d803b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesReadParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * MCP server and resource URI to fetch. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpResourcesReadParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Name of the MCP server hosting the resource */ + @JsonProperty("serverName") String serverName, + /** Resource URI */ + @JsonProperty("uri") String uri +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesReadResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesReadResult.java new file mode 100644 index 0000000000..7e85574ee5 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpResourcesReadResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Resource contents returned by the MCP server. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpResourcesReadResult( + /** Resource contents returned by the server */ + @JsonProperty("contents") List contents +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpRestartServerParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpRestartServerParams.java index 12035ae070..b517802562 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpRestartServerParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpRestartServerParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Server name and opaque configuration for an individual MCP server restart. + * Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -28,7 +28,7 @@ public record SessionMcpRestartServerParams( @JsonProperty("sessionId") String sessionId, /** Name of the MCP server to restart */ @JsonProperty("serverName") String serverName, - /** Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. */ + /** Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). */ @JsonProperty("config") Object config ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java index 6e866d64d7..e4c14e30e4 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Server name and opaque configuration for an individual MCP server start. + * Server name and configuration for an individual MCP server start. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -28,7 +28,7 @@ public record SessionMcpStartServerParams( @JsonProperty("sessionId") String sessionId, /** Name of the MCP server to start */ @JsonProperty("serverName") String serverName, - /** Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. */ + /** MCP server configuration (stdio process or remote HTTP/SSE) */ @JsonProperty("config") Object config ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataApi.java index 2223e56cd3..0b15df5d43 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataApi.java @@ -79,6 +79,33 @@ public CompletableFuture contextInfo(SessionMe return caller.invoke("session.metadata.contextInfo", _p, SessionMetadataContextInfoResult.class); } + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getContextAttribution() { + return caller.invoke("session.metadata.getContextAttribution", java.util.Map.of("sessionId", this.sessionId), SessionMetadataGetContextAttributionResult.class); + } + + /** + * Parameters for the heaviest-messages query. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getContextHeaviestMessages(SessionMetadataGetContextHeaviestMessagesParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.metadata.getContextHeaviestMessages", _p, SessionMetadataGetContextHeaviestMessagesResult.class); + } + /** * Updated working-directory/git context to record on the session. *

@@ -96,7 +123,7 @@ public CompletableFuture recordContextChange(SessionMetadataRecordContextC } /** - * Absolute path to set as the session's new working directory. + * Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. *

* Note: the {@code sessionId} field in the params record is overridden * by the session-scoped wrapper; any value provided is ignored. diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextAttributionParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextAttributionParams.java new file mode 100644 index 0000000000..c0fc0e9120 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextAttributionParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMetadataGetContextAttributionParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextAttributionResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextAttributionResult.java new file mode 100644 index 0000000000..ef7fba44d9 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextAttributionResult.java @@ -0,0 +1,72 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Per-source attribution breakdown for the session's current context window, or null if uninitialized. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMetadataGetContextAttributionResult( + /** Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). */ + @JsonProperty("contextAttribution") SessionMetadataGetContextAttributionResultContextAttribution contextAttribution +) { + + /** Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionMetadataGetContextAttributionResultContextAttribution( + /** Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. */ + @JsonProperty("totalTokens") Long totalTokens, + /** Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. */ + @JsonProperty("entries") List entries, + /** Successful compaction history for the session. */ + @JsonProperty("compactions") SessionMetadataGetContextAttributionResultContextAttributionCompactions compactions + ) { + + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionMetadataGetContextAttributionResultContextAttributionEntriesItem( + /** Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. */ + @JsonProperty("kind") String kind, + /** Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. */ + @JsonProperty("id") String id, + /** Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. */ + @JsonProperty("label") String label, + /** Token count currently in context attributable to this entry. */ + @JsonProperty("tokens") Long tokens, + /** Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. */ + @JsonProperty("parentId") String parentId, + /** Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. */ + @JsonProperty("attributes") Map attributes + ) { + } + + /** Successful compaction history for the session. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionMetadataGetContextAttributionResultContextAttributionCompactions( + /** Number of successful compactions in this session. */ + @JsonProperty("count") Long count + ) { + } + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextHeaviestMessagesParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextHeaviestMessagesParams.java new file mode 100644 index 0000000000..cacdd4ccb5 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextHeaviestMessagesParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for the heaviest-messages query. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMetadataGetContextHeaviestMessagesParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Maximum number of messages to return, most-expensive first. Omit for the server default. */ + @JsonProperty("limit") Long limit +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextHeaviestMessagesResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextHeaviestMessagesResult.java new file mode 100644 index 0000000000..90b5c3160f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataGetContextHeaviestMessagesResult.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * The heaviest individual messages in the session's context window, most-expensive first. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMetadataGetContextHeaviestMessagesResult( + /** Total token count of the current context window, so callers can compute each message's share without a second call. */ + @JsonProperty("totalTokens") Long totalTokens, + /** Heaviest messages, most-expensive first. */ + @JsonProperty("messages") List messages +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryParams.java index 99ab15b9ba..968cf5d8b6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Absolute path to set as the session's new working directory. + * Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryResult.java index 477ba62bea..b0dff14ed1 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSetWorkingDirectoryResult.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. + * Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSnapshotResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSnapshotResult.java index 908409dec1..6c29e07b6e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSnapshotResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMetadataSnapshotResult.java @@ -51,6 +51,8 @@ public record SessionMetadataSnapshotResult( @JsonProperty("currentMode") MetadataSnapshotCurrentMode currentMode, /** Currently selected model identifier, if any */ @JsonProperty("selectedModel") String selectedModel, + /** Current session limits, or null when no limits are active */ + @JsonProperty("sessionLimits") SessionLimitsConfig sessionLimits, /** Public-facing workspace metadata for this session, or null if the session has no associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, internal flags). */ @JsonProperty("workspace") SessionMetadataSnapshotResultWorkspace workspace ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListResult.java index f3fd591f62..8951499ef4 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListResult.java @@ -28,6 +28,8 @@ public record SessionModelListResult( /** Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). */ @JsonProperty("list") List list, + /** Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. */ + @JsonProperty("modelPriceCategories") List modelPriceCategories, /** Per-quota snapshots returned alongside the model list, keyed by quota type. */ @JsonProperty("quotaSnapshots") Map quotaSnapshots ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelPriceCategory.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelPriceCategory.java new file mode 100644 index 0000000000..295f6a01f0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelPriceCategory.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Cost-category metadata for a CAPI model. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionModelPriceCategory( + @JsonProperty("id") String id, + @JsonProperty("priceCategory") ModelPickerPriceCategory priceCategory +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java index b0b69ff25e..580ab3bab2 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java @@ -32,6 +32,8 @@ public record SessionModelSwitchToParams( @JsonProperty("reasoningEffort") String reasoningEffort, /** Reasoning summary mode to request for supported model clients */ @JsonProperty("reasoningSummary") ReasoningSummary reasoningSummary, + /** Output verbosity level to request for supported models */ + @JsonProperty("verbosity") Verbosity verbosity, /** Override individual model capabilities resolved by the runtime */ @JsonProperty("modelCapabilities") ModelCapabilitiesOverride modelCapabilities, /** Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java index 4479a3175a..fb8c25b3da 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java @@ -36,6 +36,8 @@ public record SessionOptionsUpdateParams( @JsonProperty("reasoningEffort") String reasoningEffort, /** Reasoning summary mode for supported model clients. */ @JsonProperty("reasoningSummary") OptionsUpdateReasoningSummary reasoningSummary, + /** Output verbosity level for supported models. */ + @JsonProperty("verbosity") Verbosity verbosity, /** Identifier of the client driving the session. */ @JsonProperty("clientName") String clientName, /** Identifier sent to LSP-style integrations. */ @@ -56,6 +58,10 @@ public record SessionOptionsUpdateParams( @JsonProperty("availableTools") List availableTools, /** Denylist of tool names for this session. */ @JsonProperty("excludedTools") List excludedTools, + /** Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. */ + @JsonProperty("includedBuiltinAgents") List includedBuiltinAgents, + /** Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. */ + @JsonProperty("excludedBuiltinAgents") List excludedBuiltinAgents, /** Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. */ @JsonProperty("toolFilterPrecedence") OptionsUpdateToolFilterPrecedence toolFilterPrecedence, /** Whether shell-script safety heuristics are enabled. */ @@ -70,6 +76,8 @@ public record SessionOptionsUpdateParams( @JsonProperty("logInteractiveShells") Boolean logInteractiveShells, /** How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). */ @JsonProperty("envValueMode") OptionsUpdateEnvValueMode envValueMode, + /** Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. */ + @JsonProperty("allowAllMcpServerInstructions") Boolean allowAllMcpServerInstructions, /** Additional directories to search for skills. */ @JsonProperty("skillDirectories") List skillDirectories, /** Skill IDs that should be excluded from this session. */ @@ -127,6 +135,8 @@ public record SessionOptionsUpdateParams( /** Whether to enable skill directory scanning and loading. Falls back to enableConfigDiscovery when unset. */ @JsonProperty("enableSkills") Boolean enableSkills, /** Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. */ - @JsonProperty("contextTier") OptionsUpdateContextTier contextTier + @JsonProperty("contextTier") OptionsUpdateContextTier contextTier, + /** Optional session limits. Pass null to clear the session limits. */ + @JsonProperty("sessionLimits") SessionLimitsConfig sessionLimits ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateResult.java index a13e0d0d5e..3d7d274610 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateResult.java @@ -25,6 +25,8 @@ @JsonIgnoreProperties(ignoreUnknown = true) public record SessionOptionsUpdateResult( /** Whether the operation succeeded */ - @JsonProperty("success") Boolean success + @JsonProperty("success") Boolean success, + /** Number of hooks loaded from installed plugins, returned when installedPlugins is updated */ + @JsonProperty("pluginHookCount") Long pluginHookCount ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java index bbac10accd..aba3177083 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java @@ -103,7 +103,7 @@ public CompletableFuture setApproveAll(Se } /** - * Whether to enable full allow-all permissions for the session. + * Allow-all mode to apply for the session. *

* Note: the {@code sessionId} field in the params record is overridden * by the session-scoped wrapper; any value provided is ignored. diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsGetAllowAllResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsGetAllowAllResult.java index 772d9a0deb..28d9915df2 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsGetAllowAllResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsGetAllowAllResult.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Current full allow-all permission state. + * Current allow-all permission mode. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -25,6 +25,8 @@ @JsonIgnoreProperties(ignoreUnknown = true) public record SessionPermissionsGetAllowAllResult( /** Whether full allow-all permissions are currently active */ - @JsonProperty("enabled") Boolean enabled + @JsonProperty("enabled") Boolean enabled, + /** Current allow-all mode */ + @JsonProperty("mode") PermissionsAllowAllMode mode ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllParams.java index 4a553ffcf0..7bde47bc81 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Whether to enable full allow-all permissions for the session. + * Allow-all mode to apply for the session. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -26,8 +26,12 @@ public record SessionPermissionsSetAllowAllParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** Whether to enable full allow-all permissions */ + /** Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM auto-approval; `off` disables both. */ + @JsonProperty("mode") PermissionsAllowAllMode mode, + /** Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. */ @JsonProperty("enabled") Boolean enabled, + /** Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. */ + @JsonProperty("model") String model, /** Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. */ @JsonProperty("source") PermissionsSetAllowAllSource source ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllResult.java index ed14e554ba..9b14d8f6ad 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsSetAllowAllResult.java @@ -26,7 +26,9 @@ public record SessionPermissionsSetAllowAllResult( /** Whether the operation succeeded */ @JsonProperty("success") Boolean success, - /** Authoritative allow-all state after the mutation */ - @JsonProperty("enabled") Boolean enabled + /** Authoritative full allow-all state after the mutation */ + @JsonProperty("enabled") Boolean enabled, + /** Authoritative allow-all mode after the mutation */ + @JsonProperty("mode") PermissionsAllowAllMode mode ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java index 4f36674d58..c150b75679 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java @@ -29,8 +29,10 @@ public final class SessionRpc { private final RpcCaller caller; private final String sessionId; - /** API methods for the {@code auth} namespace. */ - public final SessionAuthApi auth; + /** API methods for the {@code gitHubAuth} namespace. */ + public final SessionGitHubAuthApi gitHubAuth; + /** API methods for the {@code debug} namespace. */ + public final SessionDebugApi debug; /** API methods for the {@code canvas} namespace. */ public final SessionCanvasApi canvas; /** API methods for the {@code model} namespace. */ @@ -43,6 +45,8 @@ public final class SessionRpc { public final SessionPlanApi plan; /** API methods for the {@code workspaces} namespace. */ public final SessionWorkspacesApi workspaces; + /** API methods for the {@code completions} namespace. */ + public final SessionCompletionsApi completions; /** API methods for the {@code instructions} namespace. */ public final SessionInstructionsApi instructions; /** API methods for the {@code fleet} namespace. */ @@ -77,6 +81,8 @@ public final class SessionRpc { public final SessionPermissionsApi permissions; /** API methods for the {@code metadata} namespace. */ public final SessionMetadataApi metadata; + /** API methods for the {@code settings} namespace. */ + public final SessionSettingsApi settings; /** API methods for the {@code shell} namespace. */ public final SessionShellApi shell; /** API methods for the {@code history} namespace. */ @@ -89,6 +95,8 @@ public final class SessionRpc { public final SessionUsageApi usage; /** API methods for the {@code remote} namespace. */ public final SessionRemoteApi remote; + /** API methods for the {@code visibility} namespace. */ + public final SessionVisibilityApi visibility; /** API methods for the {@code schedule} namespace. */ public final SessionScheduleApi schedule; @@ -101,13 +109,15 @@ public final class SessionRpc { public SessionRpc(RpcCaller caller, String sessionId) { this.caller = caller; this.sessionId = sessionId; - this.auth = new SessionAuthApi(caller, sessionId); + this.gitHubAuth = new SessionGitHubAuthApi(caller, sessionId); + this.debug = new SessionDebugApi(caller, sessionId); this.canvas = new SessionCanvasApi(caller, sessionId); this.model = new SessionModelApi(caller, sessionId); this.mode = new SessionModeApi(caller, sessionId); this.name = new SessionNameApi(caller, sessionId); this.plan = new SessionPlanApi(caller, sessionId); this.workspaces = new SessionWorkspacesApi(caller, sessionId); + this.completions = new SessionCompletionsApi(caller, sessionId); this.instructions = new SessionInstructionsApi(caller, sessionId); this.fleet = new SessionFleetApi(caller, sessionId); this.agent = new SessionAgentApi(caller, sessionId); @@ -125,12 +135,14 @@ public SessionRpc(RpcCaller caller, String sessionId) { this.ui = new SessionUiApi(caller, sessionId); this.permissions = new SessionPermissionsApi(caller, sessionId); this.metadata = new SessionMetadataApi(caller, sessionId); + this.settings = new SessionSettingsApi(caller, sessionId); this.shell = new SessionShellApi(caller, sessionId); this.history = new SessionHistoryApi(caller, sessionId); this.queue = new SessionQueueApi(caller, sessionId); this.eventLog = new SessionEventLogApi(caller, sessionId); this.usage = new SessionUsageApi(caller, sessionId); this.remote = new SessionRemoteApi(caller, sessionId); + this.visibility = new SessionVisibilityApi(caller, sessionId); this.schedule = new SessionScheduleApi(caller, sessionId); } @@ -161,6 +173,22 @@ public CompletableFuture send(SessionSendParams params) { return caller.invoke("session.send", _p, SessionSendResult.class); } + /** + * Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture sendMessages(SessionSendMessagesParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.sendMessages", _p, SessionSendMessagesResult.class); + } + /** * Parameters for aborting the current turn *

diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesParams.java new file mode 100644 index 0000000000..2d66b4fe16 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesParams.java @@ -0,0 +1,48 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSendMessagesParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. */ + @JsonProperty("messages") List messages, + /** How to deliver the messages. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. */ + @JsonProperty("mode") SendMode mode, + /** If true, adds the messages to the front of the queue instead of the end */ + @JsonProperty("prepend") Boolean prepend, + /** The UI mode the agent was in when these messages were sent. Defaults to the session's current mode. */ + @JsonProperty("agentMode") SendAgentMode agentMode, + /** Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. */ + @JsonProperty("requestHeaders") Map requestHeaders, + /** W3C Trace Context traceparent header for distributed tracing of this agent turn */ + @JsonProperty("traceparent") String traceparent, + /** W3C Trace Context tracestate header for distributed tracing */ + @JsonProperty("tracestate") String tracestate, + /** If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. */ + @JsonProperty("wait") Boolean wait_ +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesResult.java new file mode 100644 index 0000000000..aeb556ba0f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Result of sending zero or more user messages + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSendMessagesResult( + /** Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. */ + @JsonProperty("messageIds") List messageIds +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsApi.java new file mode 100644 index 0000000000..dd4acfdb53 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsApi.java @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code settings} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionSettingsApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionSettingsApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture snapshot() { + return caller.invoke("session.settings.snapshot", java.util.Map.of("sessionId", this.sessionId), SessionSettingsSnapshotResult.class); + } + + /** + * Named Rust-owned settings predicate to evaluate for this session. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture evaluatePredicate(SessionSettingsEvaluatePredicateParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.settings.evaluatePredicate", _p, SessionSettingsEvaluatePredicateResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsBuiltInToolAvailabilitySnapshot.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsBuiltInToolAvailabilitySnapshot.java new file mode 100644 index 0000000000..98e6df29fa --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsBuiltInToolAvailabilitySnapshot.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Availability of built-in job tools surfaced to boundary consumers. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsBuiltInToolAvailabilitySnapshot( + @JsonProperty("reportProgress") Boolean reportProgress, + @JsonProperty("createPullRequest") Boolean createPullRequest +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsEvaluatePredicateParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsEvaluatePredicateParams.java new file mode 100644 index 0000000000..a7c1663e28 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsEvaluatePredicateParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Named Rust-owned settings predicate to evaluate for this session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsEvaluatePredicateParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Predicate name. The runtime owns the raw feature-flag names and composition logic. */ + @JsonProperty("name") SessionSettingsPredicateName name, + /** Tool name for tool-scoped predicates such as trivial-change handling. */ + @JsonProperty("toolName") String toolName +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsEvaluatePredicateResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsEvaluatePredicateResult.java new file mode 100644 index 0000000000..1f4a7ed320 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsEvaluatePredicateResult.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of evaluating a Rust-owned settings predicate. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsEvaluatePredicateResult( + @JsonProperty("enabled") Boolean enabled +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsJobSnapshot.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsJobSnapshot.java new file mode 100644 index 0000000000..463660d8a1 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsJobSnapshot.java @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Redacted job settings for a session. The job nonce is excluded. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsJobSnapshot( + @JsonProperty("eventType") String eventType, + @JsonProperty("isTriggerJob") Boolean isTriggerJob, + @JsonProperty("builtInToolAvailability") SessionSettingsBuiltInToolAvailabilitySnapshot builtInToolAvailability +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsModelSnapshot.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsModelSnapshot.java new file mode 100644 index 0000000000..ce515c74db --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsModelSnapshot.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Redacted model routing settings for a session. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsModelSnapshot( + @JsonProperty("model") String model, + @JsonProperty("defaultReasoningEffort") String defaultReasoningEffort, + @JsonProperty("instanceId") String instanceId, + @JsonProperty("callbackUrl") String callbackUrl +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsOnlineEvaluationSnapshot.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsOnlineEvaluationSnapshot.java new file mode 100644 index 0000000000..b1a5be6f3a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsOnlineEvaluationSnapshot.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Online-evaluation settings safe to expose across the SDK boundary. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsOnlineEvaluationSnapshot( + @JsonProperty("disableOnlineEvaluation") Boolean disableOnlineEvaluation, + @JsonProperty("enableOnlineEvaluationOutputFile") Boolean enableOnlineEvaluationOutputFile +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsPredicateName.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsPredicateName.java new file mode 100644 index 0000000000..6c99c214a8 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsPredicateName.java @@ -0,0 +1,69 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names are intentionally not part of the contract. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionSettingsPredicateName { + /** The {@code securityToolsEnabled} variant. */ + SECURITYTOOLSENABLED("securityToolsEnabled"), + /** The {@code thirdPartySecurityPromptEnabled} variant. */ + THIRDPARTYSECURITYPROMPTENABLED("thirdPartySecurityPromptEnabled"), + /** The {@code parallelValidationEnabled} variant. */ + PARALLELVALIDATIONENABLED("parallelValidationEnabled"), + /** The {@code runtimeTimingTelemetryEnabled} variant. */ + RUNTIMETIMINGTELEMETRYENABLED("runtimeTimingTelemetryEnabled"), + /** The {@code coAuthorHookEnabled} variant. */ + COAUTHORHOOKENABLED("coAuthorHookEnabled"), + /** The {@code chronicleEnabled} variant. */ + CHRONICLEENABLED("chronicleEnabled"), + /** The {@code contentExclusionSelfFetchEnabled} variant. */ + CONTENTEXCLUSIONSELFFETCHENABLED("contentExclusionSelfFetchEnabled"), + /** The {@code capClaudeOpusTokenLimitsEnabled} variant. */ + CAPCLAUDEOPUSTOKENLIMITSENABLED("capClaudeOpusTokenLimitsEnabled"), + /** The {@code codeReviewFeatureEnabled} variant. */ + CODEREVIEWFEATUREENABLED("codeReviewFeatureEnabled"), + /** The {@code ccaUseTsAutofindEnabled} variant. */ + CCAUSETSAUTOFINDENABLED("ccaUseTsAutofindEnabled"), + /** The {@code dependencyCheckerEnabled} variant. */ + DEPENDENCYCHECKERENABLED("dependencyCheckerEnabled"), + /** The {@code dependabotCheckerEnabled} variant. */ + DEPENDABOTCHECKERENABLED("dependabotCheckerEnabled"), + /** The {@code codeqlCheckerEnabled} variant. */ + CODEQLCHECKERENABLED("codeqlCheckerEnabled"), + /** The {@code trivialChangeEnabled} variant. */ + TRIVIALCHANGEENABLED("trivialChangeEnabled"), + /** The {@code trivialChangeSkipEnabled} variant. */ + TRIVIALCHANGESKIPENABLED("trivialChangeSkipEnabled"), + /** The {@code trivialChangeEnabledForCodeReview} variant. */ + TRIVIALCHANGEENABLEDFORCODEREVIEW("trivialChangeEnabledForCodeReview"), + /** The {@code trivialChangeSkipEnabledForCodeReview} variant. */ + TRIVIALCHANGESKIPENABLEDFORCODEREVIEW("trivialChangeSkipEnabledForCodeReview"), + /** The {@code trivialChangeEnabledForTool} variant. */ + TRIVIALCHANGEENABLEDFORTOOL("trivialChangeEnabledForTool"), + /** The {@code trivialChangeSkipEnabledForTool} variant. */ + TRIVIALCHANGESKIPENABLEDFORTOOL("trivialChangeSkipEnabledForTool"); + + private final String value; + SessionSettingsPredicateName(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionSettingsPredicateName fromValue(String value) { + for (SessionSettingsPredicateName v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionSettingsPredicateName value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsRepoSnapshot.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsRepoSnapshot.java new file mode 100644 index 0000000000..960853c527 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsRepoSnapshot.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Redacted repository and GitHub host settings for a session. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsRepoSnapshot( + @JsonProperty("name") String name, + @JsonProperty("id") Double id, + @JsonProperty("branch") String branch, + @JsonProperty("commit") String commit, + @JsonProperty("readWrite") Boolean readWrite, + @JsonProperty("ownerName") String ownerName, + @JsonProperty("ownerId") Double ownerId, + @JsonProperty("serverUrl") String serverUrl, + @JsonProperty("host") String host, + @JsonProperty("hostProtocol") String hostProtocol, + @JsonProperty("secretScanningUrl") String secretScanningUrl, + @JsonProperty("prCommitCount") Double prCommitCount +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsSnapshotParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsSnapshotParams.java new file mode 100644 index 0000000000..8bad931529 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsSnapshotParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsSnapshotParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsSnapshotResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsSnapshotResult.java new file mode 100644 index 0000000000..0851474d64 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsSnapshotResult.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsSnapshotResult( + @JsonProperty("version") String version, + @JsonProperty("clientName") String clientName, + @JsonProperty("timeoutMs") Double timeoutMs, + @JsonProperty("startTimeMs") Double startTimeMs, + @JsonProperty("repo") SessionSettingsRepoSnapshot repo, + @JsonProperty("model") SessionSettingsModelSnapshot model, + @JsonProperty("validation") SessionSettingsValidationSnapshot validation, + @JsonProperty("job") SessionSettingsJobSnapshot job, + @JsonProperty("onlineEvaluation") SessionSettingsOnlineEvaluationSnapshot onlineEvaluation +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsValidationSnapshot.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsValidationSnapshot.java new file mode 100644 index 0000000000..375cfdfec1 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSettingsValidationSnapshot.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Redacted validation and memory-tool settings for a session. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSettingsValidationSnapshot( + @JsonProperty("timeout") Double timeout, + @JsonProperty("dependabotTimeout") Double dependabotTimeout, + @JsonProperty("codeqlEnabled") Boolean codeqlEnabled, + @JsonProperty("codeReviewEnabled") Boolean codeReviewEnabled, + @JsonProperty("codeReviewModel") String codeReviewModel, + @JsonProperty("advisoryEnabled") Boolean advisoryEnabled, + @JsonProperty("secretScanningEnabled") Boolean secretScanningEnabled, + @JsonProperty("memoryStoreEnabled") Boolean memoryStoreEnabled, + @JsonProperty("memoryVoteEnabled") Boolean memoryVoteEnabled +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionToolsUpdateSubagentSettingsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionToolsUpdateSubagentSettingsParams.java index 44758350bd..d8c0c64fd0 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionToolsUpdateSubagentSettingsParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionToolsUpdateSubagentSettingsParams.java @@ -39,7 +39,11 @@ public record SessionToolsUpdateSubagentSettingsParamsSubagents( /** Per-agent settings keyed by subagent agent_type */ @JsonProperty("agents") Map agents, /** Names of subagents the user has turned off; they cannot be dispatched */ - @JsonProperty("disabledSubagents") List disabledSubagents + @JsonProperty("disabledSubagents") List disabledSubagents, + /** Maximum number of subagents that can run concurrently; applies to usage-based billing users only */ + @JsonProperty("maxConcurrency") Long maxConcurrency, + /** Maximum subagent nesting depth; applies to usage-based billing users only */ + @JsonProperty("maxDepth") Long maxDepth ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiApi.java index 63d90266ef..b3e16d7c27 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiApi.java @@ -126,6 +126,22 @@ public CompletableFuture handlePendi return caller.invoke("session.ui.handlePendingAutoModeSwitch", _p, SessionUiHandlePendingAutoModeSwitchResult.class); } + /** + * Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture handlePendingSessionLimitsExhausted(SessionUiHandlePendingSessionLimitsExhaustedParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.ui.handlePendingSessionLimitsExhausted", _p, SessionUiHandlePendingSessionLimitsExhaustedResult.class); + } + /** * Request ID of a pending `exit_plan_mode.requested` event and the user's response. *

diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingExitPlanModeParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingExitPlanModeParams.java index 87eccd1e24..2142a98f3b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingExitPlanModeParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingExitPlanModeParams.java @@ -28,7 +28,7 @@ public record SessionUiHandlePendingExitPlanModeParams( @JsonProperty("sessionId") String sessionId, /** The unique request ID from the exit_plan_mode.requested event */ @JsonProperty("requestId") String requestId, - /** Schema for the `UIExitPlanModeResponse` type. */ + /** User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. */ @JsonProperty("response") UIExitPlanModeResponse response ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingSessionLimitsExhaustedParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingSessionLimitsExhaustedParams.java new file mode 100644 index 0000000000..93ff195373 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingSessionLimitsExhaustedParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionUiHandlePendingSessionLimitsExhaustedParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** The unique request ID from the session_limits_exhausted.requested event */ + @JsonProperty("requestId") String requestId, + /** The selected session-limit action. */ + @JsonProperty("response") UISessionLimitsExhaustedResponse response +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingSessionLimitsExhaustedResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingSessionLimitsExhaustedResult.java new file mode 100644 index 0000000000..79eeeebbf1 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingSessionLimitsExhaustedResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Indicates whether the pending UI request was resolved by this call. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionUiHandlePendingSessionLimitsExhaustedResult( + /** True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. */ + @JsonProperty("success") Boolean success +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingUserInputParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingUserInputParams.java index 2240354381..999a8738db 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingUserInputParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionUiHandlePendingUserInputParams.java @@ -28,7 +28,7 @@ public record SessionUiHandlePendingUserInputParams( @JsonProperty("sessionId") String sessionId, /** The unique request ID from the user_input.requested event */ @JsonProperty("requestId") String requestId, - /** Schema for the `UIUserInputResponse` type. */ + /** User response for a pending user-input request, with answer text and whether it was typed freeform. */ @JsonProperty("response") UIUserInputResponse response ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityApi.java new file mode 100644 index 0000000000..54f38c2614 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityApi.java @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code visibility} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionVisibilityApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionVisibilityApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture get() { + return caller.invoke("session.visibility.get", java.util.Map.of("sessionId", this.sessionId), SessionVisibilityGetResult.class); + } + + /** + * Desired sharing status for the session. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture set(SessionVisibilitySetParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.visibility.set", _p, SessionVisibilitySetResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthGetStatusParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityGetParams.java similarity index 96% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthGetStatusParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityGetParams.java index 8875f6f241..e3c4a23709 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAuthGetStatusParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityGetParams.java @@ -23,7 +23,7 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionAuthGetStatusParams( +public record SessionVisibilityGetParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityGetResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityGetResult.java new file mode 100644 index 0000000000..86c37cf6f6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityGetResult.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Current sharing status and shareable GitHub URL for a session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionVisibilityGetResult( + /** Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. */ + @JsonProperty("synced") Boolean synced, + /** Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). */ + @JsonProperty("status") SessionVisibilityStatus status, + /** Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. */ + @JsonProperty("shareUrl") String shareUrl +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilitySetParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilitySetParams.java new file mode 100644 index 0000000000..c5287ac7c4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilitySetParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Desired sharing status for the session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionVisibilitySetParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. */ + @JsonProperty("status") SessionVisibilityStatus status +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilitySetResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilitySetResult.java new file mode 100644 index 0000000000..dda88be426 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilitySetResult.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Effective sharing status and shareable GitHub URL after updating session visibility. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionVisibilitySetResult( + /** Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. */ + @JsonProperty("synced") Boolean synced, + /** Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). */ + @JsonProperty("status") SessionVisibilityStatus status, + /** Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. */ + @JsonProperty("shareUrl") String shareUrl +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityStatus.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityStatus.java new file mode 100644 index 0000000000..46ba78511d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionVisibilityStatus.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Sharing status for a synced session. "repo" makes the session visible to anyone with read access to the repository; "unshared" restricts it to the creator and collaborators. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionVisibilityStatus { + /** The {@code repo} variant. */ + REPO("repo"), + /** The {@code unshared} variant. */ + UNSHARED("unshared"); + + private final String value; + SessionVisibilityStatus(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionVisibilityStatus fromValue(String value) { + for (SessionVisibilityStatus v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionVisibilityStatus value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenProgress.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenProgress.java index 44d1aa0de7..8509295cbd 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenProgress.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenProgress.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SessionsOpenProgress` type. + * `sessions.open` handoff progress update with step, status, and optional message. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/Skill.java b/java/src/generated/java/com/github/copilot/generated/rpc/Skill.java index 5b1cea9b76..4ad4116871 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/Skill.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/Skill.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `Skill` type. + * Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SkillDiscoveryPath.java b/java/src/generated/java/com/github/copilot/generated/rpc/SkillDiscoveryPath.java index 4d2e90a5d9..feea2794ff 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SkillDiscoveryPath.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SkillDiscoveryPath.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SkillDiscoveryPath` type. + * Canonical directory where skills can be discovered or created, with scope, preference, and optional project path. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsConfigSetDisabledSkillsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsConfigSetDisabledSkillsParams.java index 0711192d1a..1ba81d7b74 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsConfigSetDisabledSkillsParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsConfigSetDisabledSkillsParams.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * Skill names to mark as disabled in global configuration, replacing any previous list. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverParams.java index 787e9278be..85cf09fadb 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverParams.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * Optional project paths and additional skill directories to include in discovery. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverResult.java index d0544b1c35..588e9760c6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsDiscoverResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * Skills discovered across global and project sources. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsInvokedSkill.java b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsInvokedSkill.java index 697e18fa4c..a020c89ecf 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SkillsInvokedSkill.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SkillsInvokedSkill.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SkillsInvokedSkill` type. + * Skill invocation record with name, path, content, allowed tools, and turn number. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandAgentPromptResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandAgentPromptResult.java index 48a6c08a6f..4c454a55a9 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandAgentPromptResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandAgentPromptResult.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SlashCommandAgentPromptResult` type. + * Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. * * @since 1.0.0 */ @@ -40,6 +40,10 @@ public final class SlashCommandAgentPromptResult extends SlashCommandInvocationR @JsonProperty("mode") private SessionMode mode; + /** Optional user-facing notice to show before the prompt is submitted */ + @JsonProperty("notice") + private String notice; + /** True when the invocation mutated user runtime settings; consumers caching settings should refresh */ @JsonProperty("runtimeSettingsChanged") private Boolean runtimeSettingsChanged; @@ -53,6 +57,9 @@ public final class SlashCommandAgentPromptResult extends SlashCommandInvocationR public SessionMode getMode() { return mode; } public void setMode(SessionMode mode) { this.mode = mode; } + public String getNotice() { return notice; } + public void setNotice(String notice) { this.notice = notice; } + public Boolean getRuntimeSettingsChanged() { return runtimeSettingsChanged; } public void setRuntimeSettingsChanged(Boolean runtimeSettingsChanged) { this.runtimeSettingsChanged = runtimeSettingsChanged; } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandCompletedResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandCompletedResult.java index 8c6ef74be8..b2a1970a36 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandCompletedResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandCompletedResult.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SlashCommandCompletedResult` type. + * Slash-command invocation result indicating completion, with optional message and settings-change flag. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInfo.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInfo.java index 61b2e933f3..9a725ececf 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInfo.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInfo.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SlashCommandInfo` type. + * Slash-command metadata with name, aliases, description, kind, input hint, execution allowance, and schedulability. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInput.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInput.java index dcfc2a36e7..f0df784489 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInput.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInput.java @@ -10,6 +10,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import javax.annotation.processing.Generated; /** @@ -23,6 +24,8 @@ public record SlashCommandInput( /** Hint to display when command input has not been provided */ @JsonProperty("hint") String hint, + /** Optional literal choices the input accepts, each with a human-facing description; clients may render these as selectable options */ + @JsonProperty("choices") List choices, /** When true, the command requires non-empty input; clients should render the input hint as required */ @JsonProperty("required") Boolean required, /** Optional completion hint for the input (e.g. 'directory' for filesystem path completion) */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInputChoice.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInputChoice.java new file mode 100644 index 0000000000..2afc510159 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInputChoice.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A literal choice the command input accepts, with a human-facing description + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SlashCommandInputChoice( + /** The literal choice value (e.g. 'on', 'off', 'show') */ + @JsonProperty("name") String name, + /** Human-readable description shown alongside the choice */ + @JsonProperty("description") String description +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResult.java index 265f24e669..336c0eda84 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResult.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Result of invoking the slash command (text output, prompt to send to the agent, or completion). + * Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandOption.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandOption.java index 317ec970f8..00d8b423e5 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandOption.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandOption.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SlashCommandSelectSubcommandOption` type. + * Selectable slash-command subcommand option with name, description, and optional group label. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandResult.java index 512c46355b..5c151954b2 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandSelectSubcommandResult.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SlashCommandSelectSubcommandResult` type. + * Slash-command invocation result asking the client to present subcommand options for a parent command. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandTextResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandTextResult.java index 4aaab6969b..5f232e8b9c 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandTextResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SlashCommandTextResult.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `SlashCommandTextResult` type. + * Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/Tool.java b/java/src/generated/java/com/github/copilot/generated/rpc/Tool.java index e4b1361c87..51fe65e6b0 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/Tool.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/Tool.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `Tool` type. + * Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListParams.java index 384aeb5cbc..caee391eaf 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListParams.java @@ -10,12 +10,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** * Optional model identifier whose tool overrides should be applied to the listing. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListResult.java index 41e933377a..099628aed7 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ToolsListResult.java @@ -10,13 +10,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; import java.util.List; import javax.annotation.processing.Generated; /** * Built-in tools available for the requested model, with their parameters and instructions. + * + * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java b/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java index 50e2011427..d74d1b5042 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `UIExitPlanModeResponse` type. + * User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UISessionLimitsExhaustedResponse.java b/java/src/generated/java/com/github/copilot/generated/rpc/UISessionLimitsExhaustedResponse.java new file mode 100644 index 0000000000..53991d9d7f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UISessionLimitsExhaustedResponse.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * The user's selected action for an exhausted session limit. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record UISessionLimitsExhaustedResponse( + /** Action selected by the user. */ + @JsonProperty("action") UISessionLimitsExhaustedResponseAction action, + /** AI Credits to add to the current max when action is 'add'. */ + @JsonProperty("additionalAiCredits") Double additionalAiCredits, + /** New absolute max AI Credits when action is 'set'. */ + @JsonProperty("maxAiCredits") Double maxAiCredits +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UISessionLimitsExhaustedResponseAction.java b/java/src/generated/java/com/github/copilot/generated/rpc/UISessionLimitsExhaustedResponseAction.java new file mode 100644 index 0000000000..6f4e48e6f3 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UISessionLimitsExhaustedResponseAction.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * User action selected for an exhausted session limit. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum UISessionLimitsExhaustedResponseAction { + /** The {@code add} variant. */ + ADD("add"), + /** The {@code set} variant. */ + SET("set"), + /** The {@code unset} variant. */ + UNSET("unset"), + /** The {@code cancel} variant. */ + CANCEL("cancel"); + + private final String value; + UISessionLimitsExhaustedResponseAction(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static UISessionLimitsExhaustedResponseAction fromValue(String value) { + for (UISessionLimitsExhaustedResponseAction v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown UISessionLimitsExhaustedResponseAction value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UIUserInputResponse.java b/java/src/generated/java/com/github/copilot/generated/rpc/UIUserInputResponse.java index d4ce9899dd..9abc82505d 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/UIUserInputResponse.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UIUserInputResponse.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `UIUserInputResponse` type. + * User response for a pending user-input request, with answer text and whether it was typed freeform. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetric.java b/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetric.java index 7e34f43b38..1b66120cf4 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetric.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetric.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `UsageMetricsModelMetric` type. + * Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetricTokenDetail.java b/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetricTokenDetail.java index e47a45fde9..90af60c84c 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetricTokenDetail.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsModelMetricTokenDetail.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `UsageMetricsModelMetricTokenDetail` type. + * Per-model token-detail entry containing the accumulated token count for one token type. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsTokenDetail.java b/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsTokenDetail.java index 55d0b81c8d..32149bfa79 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsTokenDetail.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UsageMetricsTokenDetail.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `UsageMetricsTokenDetail` type. + * Session-wide token-detail entry containing the accumulated token count for one token type. * * @since 1.0.0 */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingMetadata.java b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingMetadata.java new file mode 100644 index 0000000000..fb6412f20e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingMetadata.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A single user setting's effective value alongside its default, so consumers can render settings left at their default. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record UserSettingMetadata( + /** The effective value: the user's value if set, otherwise the default. */ + @JsonProperty("value") Object value, + /** The centrally-known default for this setting (null when no default is registered). */ + @JsonProperty("default") Object default_, + /** True when the user has not set an explicit value for this setting (i.e. it is left at its default). Reflects whether the user has overridden the key, not whether the effective value happens to equal the default — a key explicitly set to a value identical to the default still reports false. */ + @JsonProperty("isDefault") Boolean isDefault +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsGetResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsGetResult.java new file mode 100644 index 0000000000..c94e90fcc6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsGetResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record UserSettingsGetResult( + /** Every known user setting keyed by setting name, each with its effective value, default, and whether it is at the default. */ + @JsonProperty("settings") Map settings +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsSetParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsSetParams.java new file mode 100644 index 0000000000..ba19886c24 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsSetParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record UserSettingsSetParams( + /** Partial user settings to write, as a free-form object keyed by setting name */ + @JsonProperty("settings") Object settings +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsSetResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsSetResult.java new file mode 100644 index 0000000000..c5ab98621a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UserSettingsSetResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Outcome of writing user settings. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record UserSettingsSetResult( + /** Top-level keys whose write landed in settings.json but is shadowed by a value still present in the legacy config.json (config.json wins on read). The write does not take effect until the legacy value is removed. */ + @JsonProperty("shadowedKeys") List shadowedKeys +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/Verbosity.java b/java/src/generated/java/com/github/copilot/generated/rpc/Verbosity.java new file mode 100644 index 0000000000..188ce23b41 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/Verbosity.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Output verbosity level for supported models + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum Verbosity { + /** The {@code low} variant. */ + LOW("low"), + /** The {@code medium} variant. */ + MEDIUM("medium"), + /** The {@code high} variant. */ + HIGH("high"); + + private final String value; + Verbosity(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static Verbosity fromValue(String value) { + for (Verbosity v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown Verbosity value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/WorkspacesCheckpoints.java b/java/src/generated/java/com/github/copilot/generated/rpc/WorkspacesCheckpoints.java index 07de034a96..c3696236c3 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/WorkspacesCheckpoints.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/WorkspacesCheckpoints.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Schema for the `WorkspacesCheckpoints` type. + * Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. * * @since 1.0.0 */ diff --git a/java/src/main/java/com/github/copilot/CopilotClient.java b/java/src/main/java/com/github/copilot/CopilotClient.java index 1a49941895..7244c8c0a5 100644 --- a/java/src/main/java/com/github/copilot/CopilotClient.java +++ b/java/src/main/java/com/github/copilot/CopilotClient.java @@ -17,6 +17,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; @@ -25,8 +26,10 @@ import com.github.copilot.rpc.CreateSessionResponse; import com.github.copilot.generated.rpc.SessionOptionsUpdateParams; import com.github.copilot.generated.rpc.SessionInstalledPlugin; -import com.github.copilot.generated.rpc.ConnectParams; +import com.github.copilot.generated.rpc.ConnectResult; +import com.github.copilot.generated.rpc.GitHubTelemetryNotification; import com.github.copilot.generated.rpc.ServerRpc; +import com.github.copilot.generated.rpc.SessionEventLogRegisterInterestParams; import com.github.copilot.rpc.DeleteSessionResponse; import com.github.copilot.rpc.GetAuthStatusResponse; import com.github.copilot.rpc.GetLastSessionIdResponse; @@ -257,6 +260,14 @@ private Connection startCoreBody() { llmAdapter.registerHandlers(rpc); } + // Register the GitHub telemetry forwarding handler when configured. + Function> onGitHubTelemetry = this.options + .getOnGitHubTelemetry(); + if (onGitHubTelemetry != null) { + GitHubTelemetryAdapter telemetryAdapter = new GitHubTelemetryAdapter(onGitHubTelemetry); + telemetryAdapter.registerHandlers(rpc); + } + // Verify protocol version verifyProtocolVersion(connection); LoggingHelpers.logTiming(LOG, Level.FINE, @@ -295,11 +306,20 @@ private void verifyProtocolVersion(Connection connection) throws Exception { Integer serverVersion; try { - // Try the new 'connect' RPC which supports connection tokens - var connectParams = new ConnectParams(effectiveConnectionToken); - var connectResponse = connection.rpc - .invoke("connect", connectParams, com.github.copilot.generated.rpc.ConnectResult.class) - .get(30, TimeUnit.SECONDS); + // Try the new 'connect' RPC which supports connection tokens. + var connectParams = new HashMap(); + if (effectiveConnectionToken != null) { + connectParams.put("token", effectiveConnectionToken); + } + // Opt into GitHub telemetry forwarding at the connection level when a handler + // is registered, so the runtime can forward the first session's un-replayable + // start event. Also sent on session create/resume for backward compatibility + // with servers that read the flag there instead. + if (this.options.getOnGitHubTelemetry() != null) { + connectParams.put("enableGitHubTelemetryForwarding", true); + } + var connectResponse = connection.rpc.invoke("connect", connectParams, ConnectResult.class).get(30, + TimeUnit.SECONDS); serverVersion = connectResponse.protocolVersion() != null ? connectResponse.protocolVersion().intValue() : null; @@ -578,6 +598,13 @@ public CompletableFuture createSession(SessionConfig config) { request.setSystemMessage(extracted.wireSystemMessage()); } + // Opt this session into GitHub telemetry forwarding when a + // connection-level handler is registered (mirrors the runtime's + // hand-written capability flag, not part of the codegen'd contract). + if (options.getOnGitHubTelemetry() != null) { + request.setEnableGitHubTelemetryForwarding(true); + } + // Empty mode: validate availableTools and set toolFilterPrecedence if (options.getMode() == CopilotClientMode.EMPTY) { if (config.getAvailableTools() == null) { @@ -638,20 +665,27 @@ public CompletableFuture createSession(SessionConfig config) { ? preRegisteredSessionHolder[0] : initializeSession.apply(returnedId); registeredIdHolder[0] = returnedId; + CompletableFuture interest = config.getOnMcpAuthRequest() != null + ? session.getRpc().eventLog.registerInterest( + new SessionEventLogRegisterInterestParams(returnedId, "mcp.oauth_required")) + : CompletableFuture.completedFuture(null); session.setWorkspacePath(response.workspacePath()); session.setCapabilities(response.capabilities()); session.setOpenCanvases(response.openCanvases()); - return updateSessionOptionsForMode(session, config.getSkipCustomInstructions().orElse(null), - config.getCustomAgentsLocalOnly().orElse(null), - config.getCoauthorEnabled().orElse(null), - config.getManageScheduleEnabled().orElse(null)).thenApply(v -> { - LoggingHelpers.logTiming(LOG, Level.FINE, - "CopilotClient.createSession complete. Elapsed={Elapsed}, SessionId=" - + session.getSessionId(), - totalNanos); - return session; - }); + return interest.thenCompose(interestResult -> { + logMcpAuthInterestRegistration(interestResult); + return updateSessionOptionsForMode(session, config.getSkipCustomInstructions().orElse(null), + config.getCustomAgentsLocalOnly().orElse(null), + config.getCoauthorEnabled().orElse(null), + config.getManageScheduleEnabled().orElse(null)); + }).thenApply(v -> { + LoggingHelpers.logTiming(LOG, Level.FINE, + "CopilotClient.createSession complete. Elapsed={Elapsed}, SessionId=" + + session.getSessionId(), + totalNanos); + return session; + }); }).exceptionally(ex -> { if (registeredIdHolder[0] != null) { sessions.remove(registeredIdHolder[0]); @@ -665,6 +699,12 @@ public CompletableFuture createSession(SessionConfig config) { }); } + private static void logMcpAuthInterestRegistration(Object interestResult) { + if (interestResult != null && LOG.isLoggable(Level.FINEST)) { + LOG.finest("MCP OAuth event interest registered"); + } + } + /** * Resumes an existing Copilot session. *

@@ -714,12 +754,18 @@ public CompletableFuture resumeSession(String sessionId, ResumeS if (extracted.transformCallbacks() != null) { session.registerTransformCallbacks(extracted.transformCallbacks()); } - var request = SessionRequestBuilder.buildResumeRequest(sessionId, config); if (extracted.wireSystemMessage() != config.getSystemMessage()) { request.setSystemMessage(extracted.wireSystemMessage()); } + // Opt this session into GitHub telemetry forwarding when a + // connection-level handler is registered (mirrors the runtime's + // hand-written capability flag, not part of the codegen'd contract). + if (options.getOnGitHubTelemetry() != null) { + request.setEnableGitHubTelemetryForwarding(true); + } + // Empty mode: validate availableTools and set toolFilterPrecedence for resume // path if (options.getMode() == CopilotClientMode.EMPTY) { @@ -766,6 +812,17 @@ public CompletableFuture resumeSession(String sessionId, ResumeS "CopilotClient.resumeSession session resume request completed. Elapsed={Elapsed}, SessionId=" + sessionId, rpcNanos); + String returnedId = response.sessionId(); + String interestSessionId = returnedId != null ? returnedId : sessionId; + CompletableFuture interest = config.getOnMcpAuthRequest() != null + ? session.getRpc().eventLog.registerInterest(new SessionEventLogRegisterInterestParams( + interestSessionId, "mcp.oauth_required")) + : CompletableFuture.completedFuture(null); + return interest.thenApply(interestResult -> { + logMcpAuthInterestRegistration(interestResult); + return response; + }); + }).thenCompose(response -> { session.setWorkspacePath(response.workspacePath()); session.setCapabilities(response.capabilities()); session.setOpenCanvases(response.openCanvases()); @@ -864,11 +921,12 @@ CompletableFuture updateSessionOptionsForMode(CopilotSession session, Bool return CompletableFuture.completedFuture(null); } - var params = new SessionOptionsUpdateParams(null, // sessionId — set by SessionOptionsApi + var params = new SessionOptionsUpdateParams(null, // sessionId - set by SessionOptionsApi null, // model null, // modelCapabilitiesOverrides null, // reasoningEffort null, // reasoningSummary + null, // verbosity null, // clientName null, // lspClientName null, // integrationId @@ -879,6 +937,8 @@ CompletableFuture updateSessionOptionsForMode(CopilotSession session, Bool null, // workingDirectory null, // availableTools null, // excludedTools + null, // includedBuiltinAgents + null, // excludedBuiltinAgents null, // toolFilterPrecedence null, // enableScriptSafety null, // shellInitProfile @@ -886,6 +946,7 @@ CompletableFuture updateSessionOptionsForMode(CopilotSession session, Bool null, // sandboxConfig null, // logInteractiveShells null, // envValueMode + null, // allowAllMcpServerInstructions null, // skillDirectories null, // disabledSkills null, // enableOnDemandInstructionDiscovery @@ -914,7 +975,8 @@ CompletableFuture updateSessionOptionsForMode(CopilotSession session, Bool null, // enableHostGitOperations null, // enableSessionStore null, // enableSkills - null // contextTier + null, // contextTier + null // sessionLimits ); return session.getRpc().options.update(params).thenCompose(result -> { diff --git a/java/src/main/java/com/github/copilot/CopilotRequestContext.java b/java/src/main/java/com/github/copilot/CopilotRequestContext.java index 0948a24c28..610fb56c6d 100644 --- a/java/src/main/java/com/github/copilot/CopilotRequestContext.java +++ b/java/src/main/java/com/github/copilot/CopilotRequestContext.java @@ -22,6 +22,12 @@ public final class CopilotRequestContext { private final String requestId; @Nullable private final String sessionId; + @Nullable + private final String agentId; + @Nullable + private final String parentAgentId; + @Nullable + private final String interactionType; private final CopilotRequestTransport transport; private final String url; private final Map> headers; @@ -29,20 +35,25 @@ public final class CopilotRequestContext { private LlmWebSocketResponseBridge webSocketResponse; - CopilotRequestContext(String requestId, @Nullable String sessionId, CopilotRequestTransport transport, String url, - Map> headers, CompletableFuture cancellation) { + CopilotRequestContext(String requestId, @Nullable String sessionId, @Nullable String agentId, + @Nullable String parentAgentId, @Nullable String interactionType, CopilotRequestTransport transport, + String url, Map> headers, CompletableFuture cancellation) { this.requestId = requestId; this.sessionId = sessionId; + this.agentId = agentId; + this.parentAgentId = parentAgentId; + this.interactionType = interactionType; this.transport = transport; this.url = url; this.headers = headers; this.cancellation = cancellation; } - private CopilotRequestContext(String requestId, @Nullable String sessionId, CopilotRequestTransport transport, + private CopilotRequestContext(String requestId, @Nullable String sessionId, @Nullable String agentId, + @Nullable String parentAgentId, @Nullable String interactionType, CopilotRequestTransport transport, String url, Map> headers, CompletableFuture cancellation, LlmWebSocketResponseBridge webSocketResponse) { - this(requestId, sessionId, transport, url, headers, cancellation); + this(requestId, sessionId, agentId, parentAgentId, interactionType, transport, url, headers, cancellation); this.webSocketResponse = webSocketResponse; } @@ -68,6 +79,39 @@ public String sessionId() { return sessionId; } + /** + * Gets the stable per-agent-instance id for the agent trajectory that issued + * this request, or {@code null} when no agent is in scope. + * + * @return the agent id, or {@code null} + */ + @Nullable + public String agentId() { + return agentId; + } + + /** + * Gets the id of the parent agent when this request was issued by a subagent, + * or {@code null} for root-agent and non-agent requests. + * + * @return the parent agent id, or {@code null} + */ + @Nullable + public String parentAgentId() { + return parentAgentId; + } + + /** + * Gets the runtime classification for the interaction that produced this + * request, or {@code null} when the runtime did not classify it. + * + * @return the interaction type, or {@code null} + */ + @Nullable + public String interactionType() { + return interactionType; + } + /** * Gets the transport the runtime would otherwise use. * @@ -103,8 +147,8 @@ public Map> headers() { * @return the copied context */ public CopilotRequestContext withUrl(String url) { - return new CopilotRequestContext(requestId, sessionId, transport, url, headers, cancellation, - webSocketResponse); + return new CopilotRequestContext(requestId, sessionId, agentId, parentAgentId, interactionType, transport, url, + headers, cancellation, webSocketResponse); } /** @@ -115,8 +159,8 @@ public CopilotRequestContext withUrl(String url) { * @return the copied context */ public CopilotRequestContext withHeaders(Map> headers) { - return new CopilotRequestContext(requestId, sessionId, transport, url, headers, cancellation, - webSocketResponse); + return new CopilotRequestContext(requestId, sessionId, agentId, parentAgentId, interactionType, transport, url, + headers, cancellation, webSocketResponse); } /** diff --git a/java/src/main/java/com/github/copilot/CopilotSession.java b/java/src/main/java/com/github/copilot/CopilotSession.java index 90f76b6df5..4826b3309f 100644 --- a/java/src/main/java/com/github/copilot/CopilotSession.java +++ b/java/src/main/java/com/github/copilot/CopilotSession.java @@ -33,6 +33,7 @@ import com.github.copilot.generated.rpc.SessionCommandsHandlePendingCommandParams; import com.github.copilot.generated.rpc.SessionLogParams; import com.github.copilot.generated.rpc.SessionLogLevel; +import com.github.copilot.generated.rpc.SessionMcpOauthHandlePendingRequestParams; import com.github.copilot.generated.rpc.ModelCapabilitiesOverride; import com.github.copilot.generated.rpc.ModelCapabilitiesOverrideLimits; import com.github.copilot.generated.rpc.ModelCapabilitiesOverrideSupports; @@ -49,6 +50,7 @@ import com.github.copilot.generated.CommandExecuteEvent; import com.github.copilot.generated.ElicitationRequestedEvent; import com.github.copilot.generated.ExternalToolRequestedEvent; +import com.github.copilot.generated.McpOauthRequiredEvent; import com.github.copilot.generated.PermissionRequestedEvent; import com.github.copilot.generated.SessionCanvasClosedEvent; import com.github.copilot.generated.SessionCanvasOpenedEvent; @@ -79,6 +81,10 @@ import com.github.copilot.rpc.HookInvocation; import com.github.copilot.rpc.InputOptions; import com.github.copilot.rpc.MessageOptions; +import com.github.copilot.rpc.McpAuthHandler; +import com.github.copilot.rpc.McpAuthInvocation; +import com.github.copilot.rpc.McpAuthRequest; +import com.github.copilot.rpc.McpAuthResult; import com.github.copilot.rpc.PermissionHandler; import com.github.copilot.rpc.PermissionInvocation; import com.github.copilot.rpc.PermissionRequest; @@ -152,6 +158,13 @@ public final class CopilotSession implements AutoCloseable { private static final Logger LOG = Logger.getLogger(CopilotSession.class.getName()); private static final ObjectMapper MAPPER = JsonRpcClient.getObjectMapper(); + /** + * Fixed name of the runtime's built-in tool-search tool. A client can replace + * its behavior by registering a tool with this exact name and + * {@code overridesBuiltInTool} set to {@code true}. + */ + private static final String TOOL_SEARCH_TOOL_NAME = "tool_search_tool"; + /** * The current active session ID. Initialized to the pre-generated value and may * be updated after session.create / session.resume if the server returns a @@ -171,6 +184,7 @@ public final class CopilotSession implements AutoCloseable { private final Map commandHandlers = new ConcurrentHashMap<>(); private final Map bearerTokenProviders = new ConcurrentHashMap<>(); private final AtomicReference permissionHandler = new AtomicReference<>(); + private final AtomicReference mcpAuthHandler = new AtomicReference<>(); private final AtomicReference userInputHandler = new AtomicReference<>(); private final AtomicReference elicitationHandler = new AtomicReference<>(); private final AtomicReference exitPlanModeHandler = new AtomicReference<>(); @@ -839,6 +853,20 @@ private void handleBroadcastEventAsync(SessionEvent event) { } executePermissionAndRespondAsync(data.requestId(), MAPPER.convertValue(data.permissionRequest(), PermissionRequest.class), handler); + } else if (event instanceof McpOauthRequiredEvent authEvent) { + var data = authEvent.getData(); + if (data == null || data.requestId() == null) { + return; + } + McpAuthHandler handler = mcpAuthHandler.get(); + if (handler == null) { + LOG.warning(() -> "Received MCP OAuth request without a registered MCP auth handler. SessionId=" + + sessionId + ", RequestId=" + data.requestId()); + return; + } + executeMcpAuthAndRespondAsync(new McpAuthRequest(data.requestId(), data.serverName(), data.serverUrl(), + data.reason(), data.wwwAuthenticateParams(), data.resourceMetadata(), data.staticClientConfig()), + handler); } else if (event instanceof CommandExecuteEvent cmdEvent) { var data = cmdEvent.getData(); if (data == null || data.requestId() == null || data.commandName() == null) { @@ -877,6 +905,32 @@ private void handleBroadcastEventAsync(SessionEvent event) { } } + /** + * Populates the invocation's available-tools snapshot when it targets the + * built-in tool-search tool, so an override can filter the live catalog without + * issuing its own RPC. The snapshot is fetched only for that tool to avoid a + * round-trip on every ordinary tool call; a failed fetch leaves the snapshot + * {@code null} rather than failing the tool. Shared by both server-to-client + * tool dispatch paths ({@link RpcHandlerDispatcher} and + * {@link #executeToolAndRespondAsync}). + * + * @param toolName + * the name of the tool being invoked + * @param invocation + * the invocation to populate in place + */ + void populateToolSearchMetadata(String toolName, com.github.copilot.rpc.ToolInvocation invocation) { + if (!TOOL_SEARCH_TOOL_NAME.equals(toolName)) { + return; + } + try { + var metadata = getRpc().tools.getCurrentMetadata().join(); + invocation.setAvailableTools(metadata.tools()); + } catch (Exception e) { + LOG.log(Level.FINE, "Failed to fetch tool metadata for tool search", e); + } + } + /** * Executes a tool handler and sends the result back via * {@code session.tools.handlePendingToolCall}. @@ -891,6 +945,8 @@ private void executeToolAndRespondAsync(String requestId, String toolName, Strin var invocation = new com.github.copilot.rpc.ToolInvocation().setSessionId(sessionId) .setToolCallId(toolCallId).setToolName(toolName).setArguments(argumentsNode); + populateToolSearchMetadata(toolName, invocation); + tool.handler().invoke(invocation).thenAccept(result -> { try { ToolResultObject toolResult; @@ -1006,6 +1062,58 @@ private void executePermissionAndRespondAsync(String requestId, PermissionReques } } + private void executeMcpAuthAndRespondAsync(McpAuthRequest request, McpAuthHandler handler) { + Runnable task = () -> { + try { + var invocation = new McpAuthInvocation().setSessionId(sessionId); + handler.handle(request, invocation) + .thenAccept(result -> sendMcpAuthResponse(request.requestId(), result)).exceptionally(ex -> { + sendMcpAuthResponse(request.requestId(), McpAuthResult.cancelled()); + return null; + }); + } catch (Exception e) { + LOG.log(Level.WARNING, "Error executing MCP auth handler for requestId=" + request.requestId(), e); + sendMcpAuthResponse(request.requestId(), McpAuthResult.cancelled()); + } + }; + try { + if (executor != null) { + CompletableFuture.runAsync(task, executor); + } else { + CompletableFuture.runAsync(task); + } + } catch (RejectedExecutionException e) { + LOG.log(Level.WARNING, + "Executor rejected MCP auth task for requestId=" + request.requestId() + "; running inline", e); + task.run(); + } + } + + private void sendMcpAuthResponse(String requestId, McpAuthResult result) { + try { + Object response; + if (result == null || result.isCancelled() || result.token() == null) { + response = Map.of("kind", "cancelled"); + } else { + var token = result.token(); + var tokenResponse = new java.util.HashMap(); + tokenResponse.put("kind", "token"); + tokenResponse.put("accessToken", token.accessToken()); + if (token.tokenType() != null) { + tokenResponse.put("tokenType", token.tokenType()); + } + if (token.expiresIn() != null) { + tokenResponse.put("expiresIn", token.expiresIn()); + } + response = tokenResponse; + } + getRpc().mcp.oauth.handlePendingRequest( + new SessionMcpOauthHandlePendingRequestParams(sessionId, requestId, response)); + } catch (Exception e) { + LOG.log(Level.WARNING, "Error sending MCP auth response for requestId=" + requestId, e); + } + } + /** * Registers custom tool handlers for this session. *

@@ -1269,6 +1377,10 @@ void registerPermissionHandler(PermissionHandler handler) { permissionHandler.set(handler); } + void registerMcpAuthHandler(McpAuthHandler handler) { + mcpAuthHandler.set(handler); + } + /** * Handles a permission request from the Copilot CLI. *

@@ -1487,7 +1599,7 @@ private void updateOpenCanvasesFromEvent(SessionEvent event) { return; } upsertOpenCanvas(new OpenCanvasInstance(data.instanceId(), data.extensionId(), data.extensionName(), - data.canvasId(), data.title(), data.status(), data.url(), data.input())); + data.canvasId(), data.icon(), data.title(), data.status(), data.url(), data.input())); } } @@ -1833,12 +1945,12 @@ public CompletableFuture abort() { * preserved. * *

{@code
-     * session.setModel("gpt-4.1").get();
+     * session.setModel("gpt-5.4").get();
      * session.setModel("claude-sonnet-4.6", "high").get();
      * }
* * @param model - * the model ID to switch to (e.g., {@code "gpt-4.1"}) + * the model ID to switch to (e.g., {@code "gpt-5.4"}) * @param reasoningEffort * reasoning effort level (e.g., {@code "low"}, {@code "medium"}, * {@code "high"}, {@code "xhigh"}); {@code null} to use default @@ -1850,7 +1962,7 @@ public CompletableFuture abort() { public CompletableFuture setModel(String model, String reasoningEffort) { ensureNotTerminated(); return getRpc().model - .switchTo(new SessionModelSwitchToParams(sessionId, model, reasoningEffort, null, null, null)) + .switchTo(new SessionModelSwitchToParams(sessionId, model, reasoningEffort, null, null, null, null)) .thenApply(r -> null); } @@ -1868,7 +1980,7 @@ public CompletableFuture setModel(String model, String reasoningEffort) { * } * * @param model - * the model ID to switch to (e.g., {@code "gpt-4.1"}) + * the model ID to switch to (e.g., {@code "gpt-5.4"}) * @param reasoningEffort * reasoning effort level (e.g., {@code "low"}, {@code "medium"}, * {@code "high"}, {@code "xhigh"}); {@code null} to use default @@ -1893,7 +2005,7 @@ public CompletableFuture setModel(String model, String reasoningEffort, * preserved. * * @param model - * the model ID to switch to (e.g., {@code "gpt-4.1"}) + * the model ID to switch to (e.g., {@code "gpt-5.4"}) * @param reasoningEffort * reasoning effort level; {@code null} to use default * @param reasoningSummary @@ -1918,7 +2030,7 @@ public CompletableFuture setModel(String model, String reasoningEffort, St if (modelCapabilities.getSupports() != null) { var s = modelCapabilities.getSupports(); supports = new ModelCapabilitiesOverrideSupports(s.getVision().orElse(null), - s.getReasoningEffort().orElse(null)); + s.getReasoningEffort().orElse(null), null); } ModelCapabilitiesOverrideLimits limits = null; if (modelCapabilities.getLimits() != null) { @@ -1931,7 +2043,7 @@ public CompletableFuture setModel(String model, String reasoningEffort, St ? null : com.github.copilot.generated.rpc.ReasoningSummary.fromValue(reasoningSummary); return getRpc().model.switchTo(new SessionModelSwitchToParams(sessionId, model, reasoningEffort, - generatedReasoningSummary, generatedCapabilities, null)).thenApply(r -> null); + generatedReasoningSummary, null, generatedCapabilities, null)).thenApply(r -> null); } /** @@ -1941,11 +2053,11 @@ public CompletableFuture setModel(String model, String reasoningEffort, St * preserved. * *
{@code
-     * session.setModel("gpt-4.1").get();
+     * session.setModel("gpt-5.4").get();
      * }
* * @param model - * the model ID to switch to (e.g., {@code "gpt-4.1"}) + * the model ID to switch to (e.g., {@code "gpt-5.4"}) * @return a future that completes when the model switch is acknowledged * @throws IllegalStateException * if this session has been terminated diff --git a/java/src/main/java/com/github/copilot/GitHubTelemetryAdapter.java b/java/src/main/java/com/github/copilot/GitHubTelemetryAdapter.java new file mode 100644 index 0000000000..1fdb2a4737 --- /dev/null +++ b/java/src/main/java/com/github/copilot/GitHubTelemetryAdapter.java @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.generated.rpc.GitHubTelemetryNotification; + +/** + * Bridges the runtime's {@code gitHubTelemetry.event} client-global + * notification to a consumer's async {@code onGitHubTelemetry} callback. The + * notification carries per-session GitHub (hydro) telemetry the runtime + * forwards to connections that opted into telemetry forwarding. + */ +final class GitHubTelemetryAdapter { + + private static final Logger LOG = Logger.getLogger(GitHubTelemetryAdapter.class.getName()); + private static final ObjectMapper MAPPER = JsonRpcClient.getObjectMapper(); + + private final Function> callback; + + GitHubTelemetryAdapter(Function> callback) { + this.callback = callback; + } + + void registerHandlers(JsonRpcClient rpc) { + rpc.registerMethodHandler("gitHubTelemetry.event", (rpcId, params) -> handleEvent(params)); + } + + private void handleEvent(JsonNode params) { + try { + GitHubTelemetryNotification notification = MAPPER.treeToValue(params, GitHubTelemetryNotification.class); + if (notification != null) { + CompletableFuture result = callback.apply(notification); + if (result != null) { + result.whenComplete((unused, error) -> { + if (error != null) { + LOG.log(Level.WARNING, "Error handling gitHubTelemetry.event notification", error); + } + }); + } + } + } catch (Exception e) { + LOG.log(Level.WARNING, "Error handling gitHubTelemetry.event notification", e); + } + } +} diff --git a/java/src/main/java/com/github/copilot/JsonRpcClient.java b/java/src/main/java/com/github/copilot/JsonRpcClient.java index a7cd0e120d..5303c4f500 100644 --- a/java/src/main/java/com/github/copilot/JsonRpcClient.java +++ b/java/src/main/java/com/github/copilot/JsonRpcClient.java @@ -70,7 +70,8 @@ static ObjectMapper createObjectMapper() { mapper.registerModule(new JavaTimeModule()); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL); + mapper.setDefaultPropertyInclusion( + JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS)); return mapper; } diff --git a/java/src/main/java/com/github/copilot/LlmInferenceAdapter.java b/java/src/main/java/com/github/copilot/LlmInferenceAdapter.java index 9087df6c1f..3e741a56bc 100644 --- a/java/src/main/java/com/github/copilot/LlmInferenceAdapter.java +++ b/java/src/main/java/com/github/copilot/LlmInferenceAdapter.java @@ -65,6 +65,9 @@ private LlmInferenceExchange getOrCreateExchange(String requestId) { private void handleRequestStart(JsonRpcClient rpc, String rpcId, JsonNode params) { String requestId = params.get("requestId").asText(); String sessionId = textOrNull(params, "sessionId"); + String agentId = textOrNull(params, "agentId"); + String parentAgentId = textOrNull(params, "parentAgentId"); + String interactionType = textOrNull(params, "interactionType"); String method = textOrNull(params, "method"); String url = textOrNull(params, "url"); CopilotRequestTransport transport = CopilotRequestTransport.fromWire(textOrNull(params, "transport")); @@ -74,8 +77,8 @@ private void handleRequestStart(JsonRpcClient rpc, String rpcId, JsonNode params // body — rather than dropping those frames. LlmInferenceExchange exchange = getOrCreateExchange(requestId); exchange.setMethod(method); - exchange.setContext( - new CopilotRequestContext(requestId, sessionId, transport, url, headers, exchange.cancellation())); + exchange.setContext(new CopilotRequestContext(requestId, sessionId, agentId, parentAgentId, interactionType, + transport, url, headers, exchange.cancellation())); // Return from httpRequestStart immediately (after registering state) so the // runtime's RPC reply is not gated on the consumer's I/O. The actual handler diff --git a/java/src/main/java/com/github/copilot/RpcHandlerDispatcher.java b/java/src/main/java/com/github/copilot/RpcHandlerDispatcher.java index 9a42a8e22d..d2dff958dc 100644 --- a/java/src/main/java/com/github/copilot/RpcHandlerDispatcher.java +++ b/java/src/main/java/com/github/copilot/RpcHandlerDispatcher.java @@ -162,6 +162,8 @@ private void handleToolCall(JsonRpcClient rpc, String requestId, JsonNode params var invocation = new ToolInvocation().setSessionId(sessionId).setToolCallId(toolCallId) .setToolName(toolName).setArguments(arguments); + session.populateToolSearchMetadata(toolName, invocation); + tool.handler().invoke(invocation).thenAccept(result -> { try { ToolResultObject toolResult; diff --git a/java/src/main/java/com/github/copilot/SessionRequestBuilder.java b/java/src/main/java/com/github/copilot/SessionRequestBuilder.java index 6000bdef82..57d9a46a21 100644 --- a/java/src/main/java/com/github/copilot/SessionRequestBuilder.java +++ b/java/src/main/java/com/github/copilot/SessionRequestBuilder.java @@ -116,11 +116,14 @@ static CreateSessionRequest buildCreateRequest(SessionConfig config, String sess request.setSystemMessage(config.getSystemMessage()); request.setAvailableTools(config.getAvailableTools()); request.setExcludedTools(config.getExcludedTools()); + request.setExcludedBuiltInAgents(config.getExcludedBuiltInAgents()); request.setProvider(config.getProvider()); request.setCapi(config.getCapi()); request.setProviders(config.getProviders()); request.setModels(config.getModels()); config.getEnableSessionTelemetry().ifPresent(request::setEnableSessionTelemetry); + config.getEnableCitations().ifPresent(request::setEnableCitations); + request.setSessionLimits(config.getSessionLimits()); if (config.getOnUserInputRequest() != null) { request.setRequestUserInput(true); } @@ -142,6 +145,7 @@ static CreateSessionRequest buildCreateRequest(SessionConfig config, String sess request.setInstructionDirectories(config.getInstructionDirectories()); request.setPluginDirectories(config.getPluginDirectories()); request.setLargeOutput(config.getLargeOutput()); + request.setToolSearch(config.getToolSearch()); request.setMemory(config.getMemory()); request.setDisabledSkills(config.getDisabledSkills()); request.setConfigDirectory(config.getConfigDirectory()); @@ -182,6 +186,7 @@ static CreateSessionRequest buildCreateRequest(SessionConfig config, String sess request.setRemoteSession(config.getRemoteSession()); request.setCloud(config.getCloud()); request.setExpAssignments(config.getExpAssignments()); + config.getEnableManagedSettings().ifPresent(request::setEnableManagedSettings); return request; } @@ -232,11 +237,14 @@ static ResumeSessionRequest buildResumeRequest(String sessionId, ResumeSessionCo request.setSystemMessage(config.getSystemMessage()); request.setAvailableTools(config.getAvailableTools()); request.setExcludedTools(config.getExcludedTools()); + request.setExcludedBuiltInAgents(config.getExcludedBuiltInAgents()); request.setProvider(config.getProvider()); request.setCapi(config.getCapi()); request.setProviders(config.getProviders()); request.setModels(config.getModels()); config.getEnableSessionTelemetry().ifPresent(request::setEnableSessionTelemetry); + config.getEnableCitations().ifPresent(request::setEnableCitations); + request.setSessionLimits(config.getSessionLimits()); if (config.getOnUserInputRequest() != null) { request.setRequestUserInput(true); } @@ -274,6 +282,7 @@ static ResumeSessionRequest buildResumeRequest(String sessionId, ResumeSessionCo request.setInstructionDirectories(config.getInstructionDirectories()); request.setPluginDirectories(config.getPluginDirectories()); request.setLargeOutput(config.getLargeOutput()); + request.setToolSearch(config.getToolSearch()); request.setMemory(config.getMemory()); request.setDisabledSkills(config.getDisabledSkills()); request.setInfiniteSessions(config.getInfiniteSessions()); @@ -300,6 +309,7 @@ static ResumeSessionRequest buildResumeRequest(String sessionId, ResumeSessionCo request.setGitHubToken(config.getGitHubToken()); request.setRemoteSession(config.getRemoteSession()); request.setExpAssignments(config.getExpAssignments()); + config.getEnableManagedSettings().ifPresent(request::setEnableManagedSettings); return request; } @@ -323,6 +333,9 @@ static void configureSession(CopilotSession session, SessionConfig config) { if (config.getOnPermissionRequest() != null) { session.registerPermissionHandler(config.getOnPermissionRequest()); } + if (config.getOnMcpAuthRequest() != null) { + session.registerMcpAuthHandler(config.getOnMcpAuthRequest()); + } if (config.getOnUserInputRequest() != null) { session.registerUserInputHandler(config.getOnUserInputRequest()); } @@ -370,6 +383,9 @@ static void configureSession(CopilotSession session, ResumeSessionConfig config) if (config.getOnPermissionRequest() != null) { session.registerPermissionHandler(config.getOnPermissionRequest()); } + if (config.getOnMcpAuthRequest() != null) { + session.registerMcpAuthHandler(config.getOnMcpAuthRequest()); + } if (config.getOnUserInputRequest() != null) { session.registerUserInputHandler(config.getOnUserInputRequest()); } diff --git a/java/src/main/java/com/github/copilot/package-info.java b/java/src/main/java/com/github/copilot/package-info.java index 71025f07af..0e0b2cf824 100644 --- a/java/src/main/java/com/github/copilot/package-info.java +++ b/java/src/main/java/com/github/copilot/package-info.java @@ -31,7 +31,7 @@ * try (var client = new CopilotClient()) { * client.start().get(); * - * var session = client.createSession(new SessionConfig().setModel("gpt-4.1")).get(); + * var session = client.createSession(new SessionConfig().setModel("gpt-5.4")).get(); * * session.on(AssistantMessageEvent.class, msg -> { * System.out.println(msg.getData().content()); diff --git a/java/src/main/java/com/github/copilot/rpc/CopilotClientOptions.java b/java/src/main/java/com/github/copilot/rpc/CopilotClientOptions.java index e9f59aa646..0d4494d738 100644 --- a/java/src/main/java/com/github/copilot/rpc/CopilotClientOptions.java +++ b/java/src/main/java/com/github/copilot/rpc/CopilotClientOptions.java @@ -11,11 +11,14 @@ import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; +import java.util.function.Function; import java.util.function.Supplier; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonIgnore; +import com.github.copilot.CopilotExperimental; import com.github.copilot.CopilotRequestHandler; +import com.github.copilot.generated.rpc.GitHubTelemetryNotification; import java.util.Optional; import java.util.OptionalInt; @@ -57,6 +60,7 @@ public class CopilotClientOptions { private CopilotClientMode mode = CopilotClientMode.COPILOT_CLI; private Supplier>> onListModels; private CopilotRequestHandler requestHandler; + private Function> onGitHubTelemetry; private int port; private TelemetryConfig telemetry; private Integer sessionIdleTimeoutSeconds; @@ -484,6 +488,44 @@ public CopilotClientOptions setRequestHandler(CopilotRequestHandler requestHandl return this; } + /** + * Gets the connection-level GitHub telemetry forwarding handler. + * + *

+ * Experimental: this option may change or be removed without notice. + * + * @return the async telemetry handler, or {@code null} if not set + */ + @JsonIgnore + @CopilotExperimental + public Function> getOnGitHubTelemetry() { + return onGitHubTelemetry; + } + + /** + * Sets a connection-level handler for GitHub telemetry forwarding + * (experimental). + * + *

+ * When provided, the client opts every session it creates or resumes into + * telemetry forwarding, and the runtime forwards each per-session telemetry + * event to this handler via the {@code gitHubTelemetry.event} notification. The + * handler returns a {@link CompletableFuture} that completes when asynchronous + * processing is finished. + * + * @param onGitHubTelemetry + * the async telemetry handler (must not be {@code null}) + * @return this options instance for method chaining + * @throws IllegalArgumentException + * if {@code onGitHubTelemetry} is {@code null} + */ + @CopilotExperimental + public CopilotClientOptions setOnGitHubTelemetry( + Function> onGitHubTelemetry) { + this.onGitHubTelemetry = Objects.requireNonNull(onGitHubTelemetry, "onGitHubTelemetry must not be null"); + return this; + } + /** * Gets the TCP port for the CLI server. * @@ -720,6 +762,7 @@ public CopilotClientOptions clone() { copy.logLevel = this.logLevel; copy.onListModels = this.onListModels; copy.requestHandler = this.requestHandler; + copy.onGitHubTelemetry = this.onGitHubTelemetry; copy.port = this.port; copy.remote = this.remote; copy.sessionIdleTimeoutSeconds = this.sessionIdleTimeoutSeconds; diff --git a/java/src/main/java/com/github/copilot/rpc/CreateSessionRequest.java b/java/src/main/java/com/github/copilot/rpc/CreateSessionRequest.java index 8fc966c6f1..f2ce097a13 100644 --- a/java/src/main/java/com/github/copilot/rpc/CreateSessionRequest.java +++ b/java/src/main/java/com/github/copilot/rpc/CreateSessionRequest.java @@ -13,6 +13,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.github.copilot.CopilotExperimental; +import com.github.copilot.generated.rpc.SessionLimitsConfig; /** * Internal request object for creating a new session. @@ -57,6 +58,9 @@ public final class CreateSessionRequest { @JsonProperty("excludedTools") private List excludedTools; + @JsonProperty("excludedBuiltinAgents") + private List excludedBuiltInAgents; + @JsonProperty("toolFilterPrecedence") private String toolFilterPrecedence; @@ -74,6 +78,12 @@ public final class CreateSessionRequest { @JsonProperty("enableSessionTelemetry") private Boolean enableSessionTelemetry; + @JsonProperty("enableCitations") + private Boolean enableCitations; + + @JsonProperty("sessionLimits") + private SessionLimitsConfig sessionLimits; + @JsonProperty("requestPermission") private Boolean requestPermission; @@ -92,6 +102,9 @@ public final class CreateSessionRequest { @JsonProperty("includeSubAgentStreamingEvents") private Boolean includeSubAgentStreamingEvents; + @JsonProperty("enableGitHubTelemetryForwarding") + private Boolean enableGitHubTelemetryForwarding; + @JsonProperty("mcpServers") private Map mcpServers; @@ -125,6 +138,9 @@ public final class CreateSessionRequest { @JsonProperty("largeOutput") private LargeToolOutputConfig largeOutput; + @JsonProperty("toolSearch") + private ToolSearchConfig toolSearch; + @JsonProperty("memory") private MemoryConfiguration memory; @@ -199,6 +215,10 @@ public final class CreateSessionRequest { @JsonProperty("expAssignments") private JsonNode expAssignments; + @JsonProperty("enableManagedSettings") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Boolean enableManagedSettings; + /** Gets the model name. @return the model */ public String getModel() { return model; @@ -304,6 +324,18 @@ public void setExcludedTools(List excludedTools) { this.excludedTools = excludedTools; } + /** Gets excluded built-in agents. @return the built-in agent names */ + public List getExcludedBuiltInAgents() { + return excludedBuiltInAgents == null ? null : Collections.unmodifiableList(excludedBuiltInAgents); + } + + /** + * Sets excluded built-in agents. @param excludedBuiltInAgents the agent names + */ + public void setExcludedBuiltInAgents(List excludedBuiltInAgents) { + this.excludedBuiltInAgents = excludedBuiltInAgents; + } + /** Gets the tool filter precedence. @return the precedence value */ public String getToolFilterPrecedence() { return toolFilterPrecedence; @@ -373,6 +405,26 @@ public void setEnableSessionTelemetry(boolean enableSessionTelemetry) { this.enableSessionTelemetry = enableSessionTelemetry; } + /** Gets enable citations flag. @return the flag */ + public Boolean getEnableCitations() { + return enableCitations; + } + + /** Sets enable citations flag. @param enableCitations the flag */ + public void setEnableCitations(boolean enableCitations) { + this.enableCitations = enableCitations; + } + + /** Gets the session limits. @return the session limits */ + public SessionLimitsConfig getSessionLimits() { + return sessionLimits; + } + + /** Sets the session limits. @param sessionLimits the session limits */ + public void setSessionLimits(SessionLimitsConfig sessionLimits) { + this.sessionLimits = sessionLimits; + } + /** * Clears the enableSessionTelemetry setting, reverting to the default behavior. */ @@ -575,6 +627,16 @@ public void setLargeOutput(LargeToolOutputConfig largeOutput) { this.largeOutput = largeOutput; } + /** Gets tool-search config. @return the tool-search config */ + public ToolSearchConfig getToolSearch() { + return toolSearch; + } + + /** Sets tool-search config. @param toolSearch the tool-search config */ + public void setToolSearch(ToolSearchConfig toolSearch) { + this.toolSearch = toolSearch; + } + /** Gets memory config. @return the memory config */ public MemoryConfiguration getMemory() { return memory; @@ -778,6 +840,27 @@ public void clearIncludeSubAgentStreamingEvents() { this.includeSubAgentStreamingEvents = null; } + /** Gets the GitHub telemetry forwarding flag. @return the flag */ + public Boolean getEnableGitHubTelemetryForwarding() { + return enableGitHubTelemetryForwarding; + } + + /** + * Sets the GitHub telemetry forwarding flag. @param + * enableGitHubTelemetryForwarding the flag + */ + public void setEnableGitHubTelemetryForwarding(boolean enableGitHubTelemetryForwarding) { + this.enableGitHubTelemetryForwarding = enableGitHubTelemetryForwarding; + } + + /** + * Clears the enableGitHubTelemetryForwarding setting, reverting to the default + * behavior. + */ + public void clearEnableGitHubTelemetryForwarding() { + this.enableGitHubTelemetryForwarding = null; + } + /** Gets the commands wire definitions. @return the commands */ public List getCommands() { return commands == null ? null : Collections.unmodifiableList(commands); @@ -900,4 +983,27 @@ public JsonNode getExpAssignments() { public void setExpAssignments(JsonNode expAssignments) { this.expAssignments = expAssignments; } + + /** + * Gets the self-fetch managed settings flag. @return the flag, or {@code null} + * if not set + */ + public Boolean getEnableManagedSettings() { + return enableManagedSettings; + } + + /** + * Sets the self-fetch managed settings flag. @param enableManagedSettings the + * flag + */ + public void setEnableManagedSettings(boolean enableManagedSettings) { + this.enableManagedSettings = enableManagedSettings; + } + + /** + * Clears the enableManagedSettings setting, reverting to the default behavior. + */ + public void clearEnableManagedSettings() { + this.enableManagedSettings = null; + } } diff --git a/java/src/main/java/com/github/copilot/rpc/CustomAgentConfig.java b/java/src/main/java/com/github/copilot/rpc/CustomAgentConfig.java index 5136f77786..3604a1ef5d 100644 --- a/java/src/main/java/com/github/copilot/rpc/CustomAgentConfig.java +++ b/java/src/main/java/com/github/copilot/rpc/CustomAgentConfig.java @@ -63,6 +63,9 @@ public class CustomAgentConfig { @JsonProperty("model") private String model; + @JsonProperty("reasoningEffort") + private String reasoningEffort; + /** * Gets the unique identifier name for this agent. * @@ -282,4 +285,28 @@ public CustomAgentConfig setModel(String model) { this.model = model; return this; } + + /** + * Gets the reasoning effort level for this agent's model. + * + * @return the reasoning effort level, or {@code null} if not set + */ + public String getReasoningEffort() { + return reasoningEffort; + } + + /** + * Sets the reasoning effort level for this agent's model. + *

+ * When omitted, no per-agent override is sent and the backend chooses its + * default. The parent session effort is not inherited. + * + * @param reasoningEffort + * the reasoning effort level + * @return this config for method chaining + */ + public CustomAgentConfig setReasoningEffort(String reasoningEffort) { + this.reasoningEffort = reasoningEffort; + return this; + } } diff --git a/java/src/main/java/com/github/copilot/rpc/McpAuthHandler.java b/java/src/main/java/com/github/copilot/rpc/McpAuthHandler.java new file mode 100644 index 0000000000..55c6a6f180 --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/McpAuthHandler.java @@ -0,0 +1,26 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import java.util.concurrent.CompletableFuture; + +/** + * Handles MCP OAuth requests from the runtime. + * + * @since 1.0.0 + */ +@FunctionalInterface +public interface McpAuthHandler { + /** + * Handles an MCP OAuth request. + * + * @param request + * the MCP OAuth request details + * @param invocation + * the invocation context with session information + * @return a future resolving to token data or cancellation + */ + CompletableFuture handle(McpAuthRequest request, McpAuthInvocation invocation); +} diff --git a/java/src/main/java/com/github/copilot/rpc/McpAuthInvocation.java b/java/src/main/java/com/github/copilot/rpc/McpAuthInvocation.java new file mode 100644 index 0000000000..c7a80a96d3 --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/McpAuthInvocation.java @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +/** + * Context for an MCP OAuth request invocation. + * + * @since 1.0.0 + */ +public class McpAuthInvocation { + + private String sessionId; + + /** + * Gets the session ID. + * + * @return the session ID + */ + public String getSessionId() { + return sessionId; + } + + /** + * Sets the session ID. + * + * @param sessionId + * the session ID + * @return this instance for method chaining + */ + public McpAuthInvocation setSessionId(String sessionId) { + this.sessionId = sessionId; + return this; + } +} diff --git a/java/src/main/java/com/github/copilot/rpc/McpAuthRequest.java b/java/src/main/java/com/github/copilot/rpc/McpAuthRequest.java new file mode 100644 index 0000000000..a672685557 --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/McpAuthRequest.java @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import com.github.copilot.generated.McpOauthRequiredStaticClientConfig; +import com.github.copilot.generated.McpOauthRequestReason; +import com.github.copilot.generated.McpOauthWWWAuthenticateParams; + +/** + * MCP OAuth request that the SDK host can satisfy with a host-acquired token. + * + * @since 1.0.0 + */ +public record McpAuthRequest(String requestId, String serverName, String serverUrl, McpOauthRequestReason reason, + McpOauthWWWAuthenticateParams wwwAuthenticateParams, String resourceMetadata, + McpOauthRequiredStaticClientConfig staticClientConfig) { +} diff --git a/java/src/main/java/com/github/copilot/rpc/McpAuthResult.java b/java/src/main/java/com/github/copilot/rpc/McpAuthResult.java new file mode 100644 index 0000000000..6b7fda34f9 --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/McpAuthResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +/** + * Result returned by an MCP auth request handler. + * + * @since 1.0.0 + */ +public record McpAuthResult(boolean isCancelled, McpAuthToken token) { + /** + * Creates a token result. + * + * @param token + * the host-provided OAuth token data + * @return token result + */ + public static McpAuthResult token(McpAuthToken token) { + return new McpAuthResult(false, token); + } + + /** + * Creates a cancellation result. + * + * @return cancellation result + */ + public static McpAuthResult cancelled() { + return new McpAuthResult(true, null); + } +} diff --git a/java/src/main/java/com/github/copilot/rpc/McpAuthToken.java b/java/src/main/java/com/github/copilot/rpc/McpAuthToken.java new file mode 100644 index 0000000000..3cf6748fbf --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/McpAuthToken.java @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +/** + * Host-provided OAuth token data for a pending MCP OAuth request. + * + * @since 1.0.0 + */ +public record McpAuthToken(String accessToken, String tokenType, Long expiresIn) { +} diff --git a/java/src/main/java/com/github/copilot/rpc/ParamCoercion.java b/java/src/main/java/com/github/copilot/rpc/ParamCoercion.java new file mode 100644 index 0000000000..fc82742546 --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/ParamCoercion.java @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import java.util.Map; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.tool.Param; + +/** + * Internal runtime helper: coerces raw invocation arguments to the typed values + * declared by {@link Param} descriptors. + * + *

+ * Reuses the SDK-configured {@link ObjectMapper} for complex type conversions, + * matching the coercion policy applied by existing ergonomic tooling. No + * bespoke conversion paths are introduced. + * + *

+ * Package-private: not part of the public API. + */ +class ParamCoercion { + + /** Utility class; do not instantiate. */ + private ParamCoercion() { + } + + /** + * Coerces the named argument from an invocation argument map to the Java type + * declared by {@code param}. + * + *

+ * Resolution order: + *

    + *
  1. If the argument is present, convert it to {@code T} via + * {@link ObjectMapper#convertValue}.
  2. + *
  3. If absent and a default value is set, parse the string default via + * {@link #coerceDefault}.
  4. + *
  5. If absent and the parameter is optional ({@code required=false}), return + * an empty Optional variant or {@code null}.
  6. + *
  7. If absent and required, throw {@link IllegalArgumentException} with the + * parameter name.
  8. + *
+ * + * @param + * the target Java type + * @param args + * the invocation argument map; may be {@code null} for zero-argument + * tools + * @param param + * the parameter descriptor + * @param mapper + * the configured {@link ObjectMapper} for complex type conversion + * @return the coerced argument value + * @throws IllegalArgumentException + * if a required parameter is missing or coercion fails + */ + @SuppressWarnings("unchecked") + static T coerce(Map args, Param param, ObjectMapper mapper) { + Object raw = (args != null) ? args.get(param.name()) : null; + + if (raw == null) { + if (param.hasDefaultValue()) { + return coerceDefault(param, mapper); + } else if (!param.required()) { + return (T) emptyOptionalOrNull(param.type()); + } else { + throw new IllegalArgumentException( + "Required parameter '" + param.name() + "' is missing from tool invocation"); + } + } + + Class type = param.type(); + + // Handle Optional* types explicitly before delegating to ObjectMapper + if (type == java.util.OptionalInt.class) { + try { + return (T) java.util.OptionalInt.of(((Number) raw).intValue()); + } catch (ClassCastException ex) { + throw new IllegalArgumentException("Parameter '" + param.name() + + "' expected a numeric value for OptionalInt, got: " + raw.getClass().getSimpleName(), ex); + } + } + if (type == java.util.OptionalLong.class) { + try { + return (T) java.util.OptionalLong.of(((Number) raw).longValue()); + } catch (ClassCastException ex) { + throw new IllegalArgumentException("Parameter '" + param.name() + + "' expected a numeric value for OptionalLong, got: " + raw.getClass().getSimpleName(), ex); + } + } + if (type == java.util.OptionalDouble.class) { + try { + return (T) java.util.OptionalDouble.of(((Number) raw).doubleValue()); + } catch (ClassCastException ex) { + throw new IllegalArgumentException("Parameter '" + param.name() + + "' expected a numeric value for OptionalDouble, got: " + raw.getClass().getSimpleName(), ex); + } + } + + try { + return mapper.convertValue(raw, type); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException( + "Failed to coerce parameter '" + param.name() + "' to type " + type.getSimpleName(), ex); + } + } + + /** + * Parses a {@link Param}'s string default value into the declared Java type. + * + *

+ * Handles primitives, boxed types, {@link String}, {@link Boolean}, and enums + * explicitly, mirroring the validation logic in {@link Param}. The + * {@link ObjectMapper#readValue} fallback exists as a safety net but is not + * expected to be reached in practice, since {@link Param} construction rejects + * defaults for non-primitive/boxed/String/Boolean/enum types. + * + * @param + * the target Java type + * @param param + * the parameter descriptor carrying the default value + * @param mapper + * the configured {@link ObjectMapper} used as fallback for complex + * types + * @return the parsed default value + * @throws IllegalArgumentException + * if parsing fails + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + static T coerceDefault(Param param, ObjectMapper mapper) { + String defaultValue = param.defaultValue(); + Class type = param.type(); + try { + if (type == String.class) { + return type.cast(defaultValue); + } + if (type == Integer.class || type == int.class) { + return (T) Integer.valueOf(defaultValue); + } + if (type == Long.class || type == long.class) { + return (T) Long.valueOf(defaultValue); + } + if (type == Double.class || type == double.class) { + return (T) Double.valueOf(defaultValue); + } + if (type == Float.class || type == float.class) { + return (T) Float.valueOf(defaultValue); + } + if (type == Short.class || type == short.class) { + return (T) Short.valueOf(defaultValue); + } + if (type == Byte.class || type == byte.class) { + return (T) Byte.valueOf(defaultValue); + } + if (type == Boolean.class || type == boolean.class) { + return (T) Boolean.valueOf(defaultValue); + } + if (type.isEnum()) { + Class enumType = (Class) type; + return type.cast(Enum.valueOf(enumType, defaultValue)); + } + // Fallback: let ObjectMapper parse the JSON-encoded default string + return mapper.readValue(defaultValue, type); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("Failed to apply default value '" + defaultValue + "' for parameter '" + + param.name() + "' of type " + type.getSimpleName(), ex); + } + } + + /** + * Returns an empty Optional variant for Optional primitive types, or + * {@code null} for all other types. + * + * @param type + * the declared parameter type + * @return {@link java.util.OptionalInt#empty()}, + * {@link java.util.OptionalLong#empty()}, + * {@link java.util.OptionalDouble#empty()}, or {@code null} + */ + static Object emptyOptionalOrNull(Class type) { + if (type == java.util.OptionalInt.class) { + return java.util.OptionalInt.empty(); + } + if (type == java.util.OptionalLong.class) { + return java.util.OptionalLong.empty(); + } + if (type == java.util.OptionalDouble.class) { + return java.util.OptionalDouble.empty(); + } + return null; + } +} diff --git a/java/src/main/java/com/github/copilot/rpc/ParamSchema.java b/java/src/main/java/com/github/copilot/rpc/ParamSchema.java new file mode 100644 index 0000000000..ee025eb2cc --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/ParamSchema.java @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.tool.Param; + +/** + * Internal runtime helper: maps {@link Param} metadata to JSON Schema + * {@code Map} objects. + * + *

+ * This class is a simplified runtime counterpart to the compile-time + * {@code SchemaGenerator}. It operates on {@code java.lang.reflect.Class} + * values instead of {@code javax.lang.model} mirrors, and produces {@link Map} + * instances rather than Java source-code literals. Unlike + * {@code SchemaGenerator}, it does not inspect generics or object members + * (records/POJOs) and therefore produces flat type mappings only (no + * {@code additionalProperties} or nested object {@code properties}). It does + * produce {@code items} for plain Java arrays via component-type recursion. + * + *

+ * Package-private: not part of the public API. + */ +class ParamSchema { + + /** Utility class; do not instantiate. */ + private ParamSchema() { + } + + /** + * Builds a JSON Schema {@code Map} from zero or more {@link Param} descriptors. + * + *

+ * Validation applied: + *

    + *
  • Each {@link Param} must be non-null.
  • + *
  • Parameter names must be unique; duplicates throw + * {@link IllegalArgumentException} with the tool name and duplicate name.
  • + *
+ * + * @param toolName + * the tool name, included in exception messages for clarity + * @param mapper + * the configured {@link ObjectMapper} used to coerce default values + * into their typed form for the schema + * @param params + * zero or more parameter descriptors + * @return a JSON Schema object map with {@code type=object}, + * {@code properties}, and {@code required} keys + * @throws IllegalArgumentException + * if a null param or duplicate parameter names are found + */ + static Map buildSchema(String toolName, ObjectMapper mapper, Param... params) { + if (params == null || params.length == 0) { + return Map.of("type", "object", "properties", Map.of(), "required", List.of()); + } + + // Validate: no null params, no duplicate names + Set seen = new HashSet<>(); + for (Param param : params) { + if (param == null) { + throw new IllegalArgumentException("A Param descriptor is null for tool '" + toolName + "'"); + } + if (!seen.add(param.name())) { + throw new IllegalArgumentException( + "Duplicate parameter name '" + param.name() + "' in tool '" + toolName + "'"); + } + } + + List requiredNames = new ArrayList<>(); + Map properties = new LinkedHashMap<>(); + + for (Param param : params) { + Map typeSchema = forType(param.type()); + Map enriched = new LinkedHashMap<>(typeSchema); + enriched.put("description", param.description()); + if (param.hasDefaultValue()) { + enriched.put("default", ParamCoercion.coerceDefault(param, mapper)); + } + properties.put(param.name(), Collections.unmodifiableMap(enriched)); + if (param.required()) { + requiredNames.add(param.name()); + } + } + + return Map.of("type", "object", "properties", Collections.unmodifiableMap(properties), "required", + Collections.unmodifiableList(requiredNames)); + } + + /** + * Maps a Java {@link Class} to a flat JSON Schema type descriptor. + * + *

+ * Covers primitives, boxed types, strings, UUIDs, date-time types, enums, + * collections, arrays, and maps. Does not resolve generic type parameters (e.g. + * {@code List} item schemas or {@code Map} additionalProperties) — + * those require the compile-time {@code SchemaGenerator} which operates on + * {@code TypeMirror}. + * + * @param type + * the Java type to map + * @return a JSON Schema type map (e.g. {@code Map.of("type", "string")}) + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + static Map forType(Class type) { + // Integer types + if (type == int.class || type == Integer.class || type == long.class || type == Long.class || type == byte.class + || type == Byte.class || type == short.class || type == Short.class) { + return Map.of("type", "integer"); + } + // Floating-point types + if (type == double.class || type == Double.class || type == float.class || type == Float.class) { + return Map.of("type", "number"); + } + // Boolean + if (type == boolean.class || type == Boolean.class) { + return Map.of("type", "boolean"); + } + // Char → string + if (type == char.class || type == Character.class) { + return Map.of("type", "string"); + } + // String + if (type == String.class) { + return Map.of("type", "string"); + } + // UUID + if (type == java.util.UUID.class) { + return Map.of("type", "string", "format", "uuid"); + } + // Optional primitive types + if (type == java.util.OptionalInt.class || type == java.util.OptionalLong.class) { + return Map.of("type", "integer"); + } + if (type == java.util.OptionalDouble.class) { + return Map.of("type", "number"); + } + // Date-time types + if (type == java.time.OffsetDateTime.class || type == java.time.LocalDateTime.class + || type == java.time.Instant.class || type == java.time.ZonedDateTime.class) { + return Map.of("type", "string", "format", "date-time"); + } + if (type == java.time.LocalDate.class) { + return Map.of("type", "string", "format", "date"); + } + if (type == java.time.LocalTime.class) { + return Map.of("type", "string", "format", "time"); + } + // JsonNode / Object → any (no type constraint) + if (type == com.fasterxml.jackson.databind.JsonNode.class || type == Object.class) { + return Map.of(); + } + // Enum types + if (type.isEnum()) { + Class enumType = (Class) type; + List constants = Arrays.stream(enumType.getEnumConstants()).map(Enum::name) + .collect(Collectors.toList()); + return Map.of("type", "string", "enum", Collections.unmodifiableList(constants)); + } + // List / Collection / Set → array (raw element type) + if (java.util.List.class.isAssignableFrom(type) || java.util.Collection.class.isAssignableFrom(type) + || java.util.Set.class.isAssignableFrom(type)) { + return Map.of("type", "array"); + } + // Plain array → array with items schema derived from component type + if (type.isArray()) { + Map itemsSchema = forType(type.getComponentType()); + return Map.of("type", "array", "items", itemsSchema); + } + // Map → object + if (java.util.Map.class.isAssignableFrom(type)) { + return Map.of("type", "object"); + } + // POJO / record → object + return Map.of("type", "object"); + } +} diff --git a/java/src/main/java/com/github/copilot/rpc/ResumeSessionConfig.java b/java/src/main/java/com/github/copilot/rpc/ResumeSessionConfig.java index e3e79eab01..6f3c315658 100644 --- a/java/src/main/java/com/github/copilot/rpc/ResumeSessionConfig.java +++ b/java/src/main/java/com/github/copilot/rpc/ResumeSessionConfig.java @@ -8,6 +8,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.function.Consumer; import com.fasterxml.jackson.annotation.JsonInclude; @@ -16,7 +17,7 @@ import com.github.copilot.CopilotExperimental; import com.github.copilot.generated.SessionEvent; -import java.util.Optional; +import com.github.copilot.generated.rpc.SessionLimitsConfig; /** * Configuration for resuming an existing Copilot session. @@ -46,11 +47,14 @@ public class ResumeSessionConfig { private SystemMessageConfig systemMessage; private List availableTools; private List excludedTools; + private List excludedBuiltInAgents; private ProviderConfig provider; private CapiSessionOptions capi; private List providers; private List models; private Boolean enableSessionTelemetry; + private Boolean enableCitations; + private SessionLimitsConfig sessionLimits; private Boolean skipCustomInstructions; private Boolean customAgentsLocalOnly; private Boolean coauthorEnabled; @@ -60,6 +64,7 @@ public class ResumeSessionConfig { private String contextTier; private ModelCapabilitiesOverride modelCapabilities; private PermissionHandler onPermissionRequest; + private McpAuthHandler onMcpAuthRequest; private UserInputHandler onUserInputRequest; private SessionHooks hooks; private String workingDirectory; @@ -85,6 +90,7 @@ public class ResumeSessionConfig { private List instructionDirectories; private List pluginDirectories; private LargeToolOutputConfig largeOutput; + private ToolSearchConfig toolSearch; private MemoryConfiguration memory; private List disabledSkills; private InfiniteSessionConfig infiniteSessions; @@ -97,6 +103,7 @@ public class ResumeSessionConfig { private String gitHubToken; private String remoteSession; private JsonNode expAssignments; + private Boolean enableManagedSettings; /** * Gets the AI model to use. @@ -238,6 +245,30 @@ public ResumeSessionConfig setExcludedTools(List excludedTools) { return this; } + /** + * Gets the built-in agent names excluded from the resumed session. + * + * @return the list of excluded built-in agent names + */ + public List getExcludedBuiltInAgents() { + return excludedBuiltInAgents == null ? null : Collections.unmodifiableList(excludedBuiltInAgents); + } + + /** + * Sets the built-in agent names to exclude from the resumed session. + *

+ * Excluded built-in agents are hidden from discovery and cannot be selected or + * invoked unless a custom agent with the same name is configured. + * + * @param excludedBuiltInAgents + * the built-in agent names to exclude + * @return this config instance for method chaining + */ + public ResumeSessionConfig setExcludedBuiltInAgents(List excludedBuiltInAgents) { + this.excludedBuiltInAgents = excludedBuiltInAgents != null ? new ArrayList<>(excludedBuiltInAgents) : null; + return this; + } + /** * Gets the custom API provider configuration. * @@ -382,6 +413,65 @@ public ResumeSessionConfig clearEnableSessionTelemetry() { return this; } + /** + * Gets whether native model citations are enabled. + * + * @return an {@link java.util.Optional} containing whether citations are + * enabled, or {@link java.util.Optional#empty()} for the default + */ + @CopilotExperimental + @JsonIgnore + public Optional getEnableCitations() { + return Optional.ofNullable(enableCitations); + } + + /** + * Enables or disables native model citations for supported providers. + * + * @param enableCitations + * whether to enable citations + * @return this config instance for method chaining + */ + @CopilotExperimental + public ResumeSessionConfig setEnableCitations(boolean enableCitations) { + this.enableCitations = enableCitations; + return this; + } + + /** + * Clears the enableCitations setting, reverting to the default behavior. + * + * @return this instance for method chaining + */ + @CopilotExperimental + public ResumeSessionConfig clearEnableCitations() { + this.enableCitations = null; + return this; + } + + /** + * Gets the limits for this session's current accounting window. + * + * @return the session limits, or {@code null} if not set + */ + @CopilotExperimental + public SessionLimitsConfig getSessionLimits() { + return sessionLimits; + } + + /** + * Sets limits for this session's current accounting window. + * + * @param sessionLimits + * the session limits + * @return this config instance for method chaining + */ + @CopilotExperimental + public ResumeSessionConfig setSessionLimits(SessionLimitsConfig sessionLimits) { + this.sessionLimits = sessionLimits; + return this; + } + /** * Gets whether custom instruction file loading is suppressed. * @@ -635,6 +725,28 @@ public ResumeSessionConfig setOnPermissionRequest(PermissionHandler onPermission return this; } + /** + * Gets the MCP OAuth request handler. + * + * @return the handler, or {@code null} if not set + */ + @JsonIgnore + public McpAuthHandler getOnMcpAuthRequest() { + return onMcpAuthRequest; + } + + /** + * Sets the MCP OAuth request handler. + * + * @param onMcpAuthRequest + * the handler + * @return this config instance for method chaining + */ + public ResumeSessionConfig setOnMcpAuthRequest(McpAuthHandler onMcpAuthRequest) { + this.onMcpAuthRequest = onMcpAuthRequest; + return this; + } + /** * Gets the user input request handler. * @@ -1336,6 +1448,27 @@ public ResumeSessionConfig setLargeOutput(LargeToolOutputConfig largeOutput) { return this; } + /** + * Gets the tool-search configuration. + * + * @return the tool-search config, or {@code null} for the runtime default + */ + public ToolSearchConfig getToolSearch() { + return toolSearch; + } + + /** + * Sets the tool-search configuration. + * + * @param toolSearch + * the tool-search config + * @return this config for method chaining + */ + public ResumeSessionConfig setToolSearch(ToolSearchConfig toolSearch) { + this.toolSearch = toolSearch; + return this; + } + /** * Gets the configuration for session memory. * @@ -1635,6 +1768,36 @@ public ResumeSessionConfig setExpAssignments(JsonNode expAssignments) { return this; } + /** + * Gets whether the runtime self-fetches enterprise managed settings at session + * bootstrap on resume. + * + * @return an {@link java.util.Optional} containing {@code true} to opt into + * self-fetching managed settings, or {@link java.util.Optional#empty()} + * to use the default behavior + */ + @JsonIgnore + public Optional getEnableManagedSettings() { + return Optional.ofNullable(enableManagedSettings); + } + + /** + * Opts the runtime into self-fetching enterprise managed settings on resume. + *

+ * See {@link SessionConfig#setEnableManagedSettings(boolean)} for details. + * Re-supply on resume so the runtime re-applies the managed-settings self-fetch + * after a CLI process restart. Serialized on the wire as + * {@code enableManagedSettings}. + * + * @param enableManagedSettings + * {@code true} to opt into self-fetching managed settings + * @return this config for method chaining + */ + public ResumeSessionConfig setEnableManagedSettings(boolean enableManagedSettings) { + this.enableManagedSettings = enableManagedSettings; + return this; + } + /** * Creates a shallow clone of this {@code ResumeSessionConfig} instance. *

@@ -1655,11 +1818,16 @@ public ResumeSessionConfig clone() { copy.systemMessage = this.systemMessage; copy.availableTools = this.availableTools != null ? new ArrayList<>(this.availableTools) : null; copy.excludedTools = this.excludedTools != null ? new ArrayList<>(this.excludedTools) : null; + copy.excludedBuiltInAgents = this.excludedBuiltInAgents != null + ? new ArrayList<>(this.excludedBuiltInAgents) + : null; copy.provider = this.provider; copy.capi = this.capi; copy.providers = this.providers != null ? new ArrayList<>(this.providers) : null; copy.models = this.models != null ? new ArrayList<>(this.models) : null; copy.enableSessionTelemetry = this.enableSessionTelemetry; + copy.enableCitations = this.enableCitations; + copy.sessionLimits = this.sessionLimits; copy.reasoningEffort = this.reasoningEffort; copy.reasoningSummary = this.reasoningSummary; copy.contextTier = this.contextTier; @@ -1691,18 +1859,21 @@ public ResumeSessionConfig clone() { : null; copy.pluginDirectories = this.pluginDirectories != null ? new ArrayList<>(this.pluginDirectories) : null; copy.largeOutput = this.largeOutput; + copy.toolSearch = this.toolSearch; copy.memory = this.memory; copy.disabledSkills = this.disabledSkills != null ? new ArrayList<>(this.disabledSkills) : null; copy.infiniteSessions = this.infiniteSessions; copy.onEvent = this.onEvent; copy.commands = this.commands != null ? new ArrayList<>(this.commands) : null; copy.onElicitationRequest = this.onElicitationRequest; + copy.onMcpAuthRequest = this.onMcpAuthRequest; copy.onExitPlanMode = this.onExitPlanMode; copy.onAutoModeSwitch = this.onAutoModeSwitch; copy.enableMcpApps = this.enableMcpApps; copy.gitHubToken = this.gitHubToken; copy.remoteSession = this.remoteSession; copy.expAssignments = this.expAssignments; + copy.enableManagedSettings = this.enableManagedSettings; return copy; } } diff --git a/java/src/main/java/com/github/copilot/rpc/ResumeSessionRequest.java b/java/src/main/java/com/github/copilot/rpc/ResumeSessionRequest.java index 2b25875d7f..ab848118e6 100644 --- a/java/src/main/java/com/github/copilot/rpc/ResumeSessionRequest.java +++ b/java/src/main/java/com/github/copilot/rpc/ResumeSessionRequest.java @@ -13,6 +13,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.github.copilot.CopilotExperimental; +import com.github.copilot.generated.rpc.SessionLimitsConfig; /** * Internal request object for resuming an existing session. @@ -59,6 +60,9 @@ public final class ResumeSessionRequest { @JsonProperty("excludedTools") private List excludedTools; + @JsonProperty("excludedBuiltinAgents") + private List excludedBuiltInAgents; + @JsonProperty("toolFilterPrecedence") private String toolFilterPrecedence; @@ -76,6 +80,12 @@ public final class ResumeSessionRequest { @JsonProperty("enableSessionTelemetry") private Boolean enableSessionTelemetry; + @JsonProperty("enableCitations") + private Boolean enableCitations; + + @JsonProperty("sessionLimits") + private SessionLimitsConfig sessionLimits; + @JsonProperty("requestPermission") private Boolean requestPermission; @@ -135,6 +145,9 @@ public final class ResumeSessionRequest { @JsonProperty("includeSubAgentStreamingEvents") private Boolean includeSubAgentStreamingEvents; + @JsonProperty("enableGitHubTelemetryForwarding") + private Boolean enableGitHubTelemetryForwarding; + @JsonProperty("mcpServers") private Map mcpServers; @@ -165,6 +178,9 @@ public final class ResumeSessionRequest { @JsonProperty("largeOutput") private LargeToolOutputConfig largeOutput; + @JsonProperty("toolSearch") + private ToolSearchConfig toolSearch; + @JsonProperty("memory") private MemoryConfiguration memory; @@ -201,6 +217,10 @@ public final class ResumeSessionRequest { @JsonProperty("expAssignments") private JsonNode expAssignments; + @JsonProperty("enableManagedSettings") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Boolean enableManagedSettings; + /** Gets the session ID. @return the session ID */ public String getSessionId() { return sessionId; @@ -309,6 +329,18 @@ public void setExcludedTools(List excludedTools) { this.excludedTools = excludedTools; } + /** Gets excluded built-in agents. @return the built-in agent names */ + public List getExcludedBuiltInAgents() { + return excludedBuiltInAgents == null ? null : Collections.unmodifiableList(excludedBuiltInAgents); + } + + /** + * Sets excluded built-in agents. @param excludedBuiltInAgents the agent names + */ + public void setExcludedBuiltInAgents(List excludedBuiltInAgents) { + this.excludedBuiltInAgents = excludedBuiltInAgents; + } + /** Gets the tool filter precedence. @return the precedence value */ public String getToolFilterPrecedence() { return toolFilterPrecedence; @@ -378,6 +410,26 @@ public void setEnableSessionTelemetry(boolean enableSessionTelemetry) { this.enableSessionTelemetry = enableSessionTelemetry; } + /** Gets enable citations flag. @return the flag */ + public Boolean getEnableCitations() { + return enableCitations; + } + + /** Sets enable citations flag. @param enableCitations the flag */ + public void setEnableCitations(boolean enableCitations) { + this.enableCitations = enableCitations; + } + + /** Gets the session limits. @return the session limits */ + public SessionLimitsConfig getSessionLimits() { + return sessionLimits; + } + + /** Sets the session limits. @param sessionLimits the session limits */ + public void setSessionLimits(SessionLimitsConfig sessionLimits) { + this.sessionLimits = sessionLimits; + } + /** * Clears the enableSessionTelemetry setting, reverting to the default behavior. */ @@ -663,6 +715,27 @@ public void clearIncludeSubAgentStreamingEvents() { this.includeSubAgentStreamingEvents = null; } + /** Gets the GitHub telemetry forwarding flag. @return the flag */ + public Boolean getEnableGitHubTelemetryForwarding() { + return enableGitHubTelemetryForwarding; + } + + /** + * Sets the GitHub telemetry forwarding flag. @param + * enableGitHubTelemetryForwarding the flag + */ + public void setEnableGitHubTelemetryForwarding(boolean enableGitHubTelemetryForwarding) { + this.enableGitHubTelemetryForwarding = enableGitHubTelemetryForwarding; + } + + /** + * Clears the enableGitHubTelemetryForwarding setting, reverting to the default + * behavior. + */ + public void clearEnableGitHubTelemetryForwarding() { + this.enableGitHubTelemetryForwarding = null; + } + /** Gets MCP servers. @return the servers map */ public Map getMcpServers() { return mcpServers == null ? null : Collections.unmodifiableMap(mcpServers); @@ -770,6 +843,16 @@ public void setLargeOutput(LargeToolOutputConfig largeOutput) { this.largeOutput = largeOutput; } + /** Gets tool-search config. @return the tool-search config */ + public ToolSearchConfig getToolSearch() { + return toolSearch; + } + + /** Sets tool-search config. @param toolSearch the tool-search config */ + public void setToolSearch(ToolSearchConfig toolSearch) { + this.toolSearch = toolSearch; + } + /** Gets memory config. @return the memory config */ public MemoryConfiguration getMemory() { return memory; @@ -915,4 +998,27 @@ public JsonNode getExpAssignments() { public void setExpAssignments(JsonNode expAssignments) { this.expAssignments = expAssignments; } + + /** + * Gets the self-fetch managed settings flag. @return the flag, or {@code null} + * if not set + */ + public Boolean getEnableManagedSettings() { + return enableManagedSettings; + } + + /** + * Sets the self-fetch managed settings flag. @param enableManagedSettings the + * flag + */ + public void setEnableManagedSettings(boolean enableManagedSettings) { + this.enableManagedSettings = enableManagedSettings; + } + + /** + * Clears the enableManagedSettings setting, reverting to the default behavior. + */ + public void clearEnableManagedSettings() { + this.enableManagedSettings = null; + } } diff --git a/java/src/main/java/com/github/copilot/rpc/SessionConfig.java b/java/src/main/java/com/github/copilot/rpc/SessionConfig.java index 38b357e7e3..e611f66c89 100644 --- a/java/src/main/java/com/github/copilot/rpc/SessionConfig.java +++ b/java/src/main/java/com/github/copilot/rpc/SessionConfig.java @@ -8,6 +8,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.function.Consumer; import com.fasterxml.jackson.annotation.JsonInclude; @@ -16,7 +17,7 @@ import com.github.copilot.CopilotExperimental; import com.github.copilot.generated.SessionEvent; -import java.util.Optional; +import com.github.copilot.generated.rpc.SessionLimitsConfig; /** * Configuration for creating a new Copilot session. @@ -50,16 +51,20 @@ public class SessionConfig { private SystemMessageConfig systemMessage; private List availableTools; private List excludedTools; + private List excludedBuiltInAgents; private ProviderConfig provider; private CapiSessionOptions capi; private List providers; private List models; private Boolean enableSessionTelemetry; + private Boolean enableCitations; + private SessionLimitsConfig sessionLimits; private Boolean skipCustomInstructions; private Boolean customAgentsLocalOnly; private Boolean coauthorEnabled; private Boolean manageScheduleEnabled; private PermissionHandler onPermissionRequest; + private McpAuthHandler onMcpAuthRequest; private UserInputHandler onUserInputRequest; private SessionHooks hooks; private String workingDirectory; @@ -75,6 +80,7 @@ public class SessionConfig { private List instructionDirectories; private List pluginDirectories; private LargeToolOutputConfig largeOutput; + private ToolSearchConfig toolSearch; private MemoryConfiguration memory; private List disabledSkills; private String configDirectory; @@ -98,6 +104,7 @@ public class SessionConfig { private String remoteSession; private CloudSessionOptions cloud; private JsonNode expAssignments; + private Boolean enableManagedSettings; /** * Gets the custom session ID. @@ -336,6 +343,30 @@ public SessionConfig setExcludedTools(List excludedTools) { return this; } + /** + * Gets the built-in agent names excluded from this session. + * + * @return the list of excluded built-in agent names + */ + public List getExcludedBuiltInAgents() { + return excludedBuiltInAgents == null ? null : Collections.unmodifiableList(excludedBuiltInAgents); + } + + /** + * Sets the built-in agent names to exclude from this session. + *

+ * Excluded built-in agents are hidden from discovery and cannot be selected or + * invoked unless a custom agent with the same name is configured. + * + * @param excludedBuiltInAgents + * the built-in agent names to exclude + * @return this config instance for method chaining + */ + public SessionConfig setExcludedBuiltInAgents(List excludedBuiltInAgents) { + this.excludedBuiltInAgents = excludedBuiltInAgents != null ? new ArrayList<>(excludedBuiltInAgents) : null; + return this; + } + /** * Gets the custom API provider configuration. * @@ -484,6 +515,65 @@ public SessionConfig clearEnableSessionTelemetry() { return this; } + /** + * Gets whether native model citations are enabled. + * + * @return an {@link java.util.Optional} containing whether citations are + * enabled, or {@link java.util.Optional#empty()} for the default + */ + @CopilotExperimental + @JsonIgnore + public Optional getEnableCitations() { + return Optional.ofNullable(enableCitations); + } + + /** + * Enables or disables native model citations for supported providers. + * + * @param enableCitations + * whether to enable citations + * @return this config instance for method chaining + */ + @CopilotExperimental + public SessionConfig setEnableCitations(boolean enableCitations) { + this.enableCitations = enableCitations; + return this; + } + + /** + * Clears the enableCitations setting, reverting to the default behavior. + * + * @return this instance for method chaining + */ + @CopilotExperimental + public SessionConfig clearEnableCitations() { + this.enableCitations = null; + return this; + } + + /** + * Gets the limits for this session's current accounting window. + * + * @return the session limits, or {@code null} if not set + */ + @CopilotExperimental + public SessionLimitsConfig getSessionLimits() { + return sessionLimits; + } + + /** + * Sets limits for this session's current accounting window. + * + * @param sessionLimits + * the session limits + * @return this config instance for method chaining + */ + @CopilotExperimental + public SessionConfig setSessionLimits(SessionLimitsConfig sessionLimits) { + this.sessionLimits = sessionLimits; + return this; + } + /** * Gets whether custom instruction file loading is suppressed. * @@ -678,6 +768,31 @@ public SessionConfig setOnPermissionRequest(PermissionHandler onPermissionReques return this; } + /** + * Gets the MCP OAuth request handler. + * + * @return the handler, or {@code null} if not set + */ + @JsonIgnore + public McpAuthHandler getOnMcpAuthRequest() { + return onMcpAuthRequest; + } + + /** + * Sets the MCP OAuth request handler. + *

+ * When provided, the SDK can satisfy MCP server OAuth requests with + * host-provided token data or cancellation. + * + * @param onMcpAuthRequest + * the handler + * @return this config instance for method chaining + */ + public SessionConfig setOnMcpAuthRequest(McpAuthHandler onMcpAuthRequest) { + this.onMcpAuthRequest = onMcpAuthRequest; + return this; + } + /** * Gets the user input request handler. * @@ -1016,6 +1131,28 @@ public SessionConfig setLargeOutput(LargeToolOutputConfig largeOutput) { return this; } + /** + * Gets the tool-search override configuration. + * + * @return the tool-search config, or {@code null} for the runtime default + */ + public ToolSearchConfig getToolSearch() { + return toolSearch; + } + + /** + * Sets the tool-search override configuration. When {@code null}, the runtime + * default tool-search behavior applies. + * + * @param toolSearch + * the tool-search config + * @return this config instance for method chaining + */ + public SessionConfig setToolSearch(ToolSearchConfig toolSearch) { + this.toolSearch = toolSearch; + return this; + } + /** * Gets the configuration for session memory. * @@ -1763,6 +1900,38 @@ public SessionConfig setExpAssignments(JsonNode expAssignments) { return this; } + /** + * Gets whether the runtime self-fetches enterprise managed settings at session + * bootstrap. + * + * @return an {@link java.util.Optional} containing {@code true} to opt into + * self-fetching managed settings, or {@link java.util.Optional#empty()} + * to use the default behavior + */ + @JsonIgnore + public Optional getEnableManagedSettings() { + return Optional.ofNullable(enableManagedSettings); + } + + /** + * Opts the runtime into self-fetching enterprise managed settings + * (bypass-permissions policy) at session bootstrap. + *

+ * When {@code true}, the runtime self-fetches enterprise managed settings using + * the session's {@link #getGitHubToken() gitHubToken}. Requires + * {@code gitHubToken} to be set; if omitted, the runtime is expected to reject + * session creation (fail-closed). When unset, behaves exactly as before. + * Serialized on the wire as {@code enableManagedSettings}. + * + * @param enableManagedSettings + * {@code true} to opt into self-fetching managed settings + * @return this config instance for method chaining + */ + public SessionConfig setEnableManagedSettings(boolean enableManagedSettings) { + this.enableManagedSettings = enableManagedSettings; + return this; + } + /** * Creates a shallow clone of this {@code SessionConfig} instance. *

@@ -1787,11 +1956,16 @@ public SessionConfig clone() { copy.systemMessage = this.systemMessage; copy.availableTools = this.availableTools != null ? new ArrayList<>(this.availableTools) : null; copy.excludedTools = this.excludedTools != null ? new ArrayList<>(this.excludedTools) : null; + copy.excludedBuiltInAgents = this.excludedBuiltInAgents != null + ? new ArrayList<>(this.excludedBuiltInAgents) + : null; copy.provider = this.provider; copy.capi = this.capi; copy.providers = this.providers != null ? new ArrayList<>(this.providers) : null; copy.models = this.models != null ? new ArrayList<>(this.models) : null; copy.enableSessionTelemetry = this.enableSessionTelemetry; + copy.enableCitations = this.enableCitations; + copy.sessionLimits = this.sessionLimits; copy.skipCustomInstructions = this.skipCustomInstructions; copy.customAgentsLocalOnly = this.customAgentsLocalOnly; copy.coauthorEnabled = this.coauthorEnabled; @@ -1813,6 +1987,7 @@ public SessionConfig clone() { : null; copy.pluginDirectories = this.pluginDirectories != null ? new ArrayList<>(this.pluginDirectories) : null; copy.largeOutput = this.largeOutput; + copy.toolSearch = this.toolSearch; copy.memory = this.memory; copy.disabledSkills = this.disabledSkills != null ? new ArrayList<>(this.disabledSkills) : null; copy.configDirectory = this.configDirectory; @@ -1829,6 +2004,7 @@ public SessionConfig clone() { copy.onEvent = this.onEvent; copy.commands = this.commands != null ? new ArrayList<>(this.commands) : null; copy.onElicitationRequest = this.onElicitationRequest; + copy.onMcpAuthRequest = this.onMcpAuthRequest; copy.onExitPlanMode = this.onExitPlanMode; copy.onAutoModeSwitch = this.onAutoModeSwitch; copy.enableMcpApps = this.enableMcpApps; @@ -1836,6 +2012,7 @@ public SessionConfig clone() { copy.remoteSession = this.remoteSession; copy.cloud = this.cloud; copy.expAssignments = this.expAssignments; + copy.enableManagedSettings = this.enableManagedSettings; return copy; } } diff --git a/java/src/main/java/com/github/copilot/rpc/ToolDefer.java b/java/src/main/java/com/github/copilot/rpc/ToolDefer.java index 1955f02ec8..ba888ca972 100644 --- a/java/src/main/java/com/github/copilot/rpc/ToolDefer.java +++ b/java/src/main/java/com/github/copilot/rpc/ToolDefer.java @@ -21,6 +21,27 @@ */ public enum ToolDefer { + /** + * No deferral preference set. This is an annotation-only sentinel used + * as the default for {@code @CopilotTool(defer = ToolDefer.NONE)}. + *

+ * This constant must not be passed to {@link ToolDefinition} factory + * methods. The annotation processor and {@code ToolDefinition.fromObject()} + * must map {@code NONE} to a {@code null} field reference so that + * {@code @JsonInclude(NON_NULL)} on {@link ToolDefinition} omits the + * {@code defer} key from the JSON-RPC wire payload entirely (matching the + * nullable/optional semantics used by all other SDKs). + *

+ * As a secondary safety net, {@link #getValue()} returns {@code null} for this + * constant. Note that this alone does not cause field omission: if a + * non-null {@code NONE} reference reaches a {@link ToolDefinition} field, + * Jackson's {@code @JsonInclude(NON_NULL)} will still emit the field (as + * {@code "defer": null}) because the field reference itself is not null. The + * primary protection is mapping {@code NONE} to a null field reference before + * constructing the {@link ToolDefinition}. + */ + NONE(""), + /** The tool can be deferred and surfaced through tool search. */ AUTO("auto"), @@ -35,12 +56,18 @@ public enum ToolDefer { /** * Returns the JSON value for this deferral mode. + *

+ * Returns {@code null} for {@link #NONE} to avoid emitting an empty string + * ({@code "defer": ""}) if this sentinel accidentally reaches serialization. + * With {@code null}, the worst-case leak becomes {@code "defer": null} rather + * than an invalid empty string. * - * @return the string value used in JSON serialization + * @return the string value used in JSON serialization, or {@code null} for + * {@link #NONE} */ @JsonValue public String getValue() { - return value; + return this == NONE ? null : value; } /** diff --git a/java/src/main/java/com/github/copilot/rpc/ToolDefinition.java b/java/src/main/java/com/github/copilot/rpc/ToolDefinition.java index 23b7fe30d0..ccf0ef5309 100644 --- a/java/src/main/java/com/github/copilot/rpc/ToolDefinition.java +++ b/java/src/main/java/com/github/copilot/rpc/ToolDefinition.java @@ -4,11 +4,26 @@ package com.github.copilot.rpc; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.github.copilot.CopilotExperimental; +import com.github.copilot.tool.Param; /** * Defines a tool that can be invoked by the AI assistant. @@ -60,6 +75,9 @@ * controls whether the tool may be deferred (loaded lazily via tool * search) rather than always pre-loaded; {@code null} lets the * runtime decide + * @param metadata + * opaque, host-defined metadata; keys are namespaced and not part of + * the stable public API; {@code null} when unset * @see SessionConfig#setTools(java.util.List) * @see ToolHandler * @since 1.0.0 @@ -68,7 +86,36 @@ public record ToolDefinition(@JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("parameters") Object parameters, @JsonIgnore ToolHandler handler, @JsonProperty("overridesBuiltInTool") Boolean overridesBuiltInTool, - @JsonProperty("skipPermission") Boolean skipPermission, @JsonProperty("defer") ToolDefer defer) { + @JsonProperty("skipPermission") Boolean skipPermission, @JsonProperty("defer") ToolDefer defer, + @JsonProperty("metadata") Map metadata) { + + /** + * Creates a tool definition without a {@code metadata} bag. + *

+ * Convenience overload equivalent to the canonical constructor with + * {@code metadata} set to {@code null}. + * + * @param name + * the unique name of the tool + * @param description + * a description of what the tool does + * @param parameters + * the JSON Schema for the tool's parameters + * @param handler + * the handler function to execute when invoked + * @param overridesBuiltInTool + * whether this tool overrides a built-in tool; {@code null} for the + * default + * @param skipPermission + * whether the tool may run without a permission check; {@code null} + * for the default + * @param defer + * the deferral mode; {@code null} lets the runtime decide + */ + public ToolDefinition(String name, String description, Object parameters, ToolHandler handler, + Boolean overridesBuiltInTool, Boolean skipPermission, ToolDefer defer) { + this(name, description, parameters, handler, overridesBuiltInTool, skipPermission, defer, null); + } /** * Creates a tool definition with a JSON schema for parameters. @@ -88,7 +135,7 @@ public record ToolDefinition(@JsonProperty("name") String name, @JsonProperty("d */ public static ToolDefinition create(String name, String description, Map schema, ToolHandler handler) { - return new ToolDefinition(name, description, schema, handler, null, null, null); + return new ToolDefinition(name, description, schema, handler, null, null, null, null); } /** @@ -112,7 +159,7 @@ public static ToolDefinition create(String name, String description, Map schema, ToolHandler handler) { - return new ToolDefinition(name, description, schema, handler, true, null, null); + return new ToolDefinition(name, description, schema, handler, true, null, null, null); } /** @@ -135,7 +182,7 @@ public static ToolDefinition createOverride(String name, String description, Map */ public static ToolDefinition createSkipPermission(String name, String description, Map schema, ToolHandler handler) { - return new ToolDefinition(name, description, schema, handler, null, true, null); + return new ToolDefinition(name, description, schema, handler, null, true, null, null); } /** @@ -161,6 +208,708 @@ public static ToolDefinition createSkipPermission(String name, String descriptio */ public static ToolDefinition createWithDefer(String name, String description, Map schema, ToolHandler handler, ToolDefer defer) { - return new ToolDefinition(name, description, schema, handler, null, null, defer); + return new ToolDefinition(name, description, schema, handler, null, null, defer, null); + } + + /** + * Creates a tool definition with opaque, host-defined metadata. + *

+ * Use this factory method to attach namespaced metadata to the tool. The keys + * are not part of the stable public API; specific keys may be recognized to + * inform host-specific behavior. + * + * @param name + * the unique name of the tool + * @param description + * a description of what the tool does + * @param schema + * the JSON Schema as a {@code Map} + * @param handler + * the handler function to execute when invoked + * @param metadata + * the opaque metadata map + * @return a new tool definition with the metadata set + * @since 1.0.7 + */ + public static ToolDefinition createWithMetadata(String name, String description, Map schema, + ToolHandler handler, Map metadata) { + return new ToolDefinition(name, description, schema, handler, null, null, null, metadata); + } + + /** + * Discovers tool definitions from an object whose methods are annotated with + * {@code @CopilotTool}. Requires that the {@code CopilotToolProcessor} + * annotation processor ran at compile time (generating the + * {@code $$CopilotToolMeta} companion class). + * + * @param instance + * the object containing {@code @CopilotTool}-annotated methods + * @return list of tool definitions with working invocation handlers + * @throws IllegalStateException + * if the generated {@code $$CopilotToolMeta} class is not found + * (annotation processor did not run) + * @since 1.0.6 + */ + @CopilotExperimental + public static List fromObject(Object instance) { + if (instance == null) { + throw new IllegalArgumentException("instance must not be null"); + } + Class clazz = instance.getClass(); + return loadDefinitions(clazz, instance); + } + + /** + * Discovers tool definitions from a class with static + * {@code @CopilotTool}-annotated methods. Requires that the + * {@code CopilotToolProcessor} annotation processor ran at compile time + * (generating the {@code $$CopilotToolMeta} companion class). + * + * @param clazz + * the class containing static {@code @CopilotTool}-annotated methods + * @return list of tool definitions with working invocation handlers + * @throws IllegalStateException + * if the generated {@code $$CopilotToolMeta} class is not found + * (annotation processor did not run) + * @since 1.0.6 + */ + @CopilotExperimental + public static List fromClass(Class clazz) { + if (clazz == null) { + throw new IllegalArgumentException("clazz must not be null"); + } + List instanceMethods = Arrays.stream(clazz.getDeclaredMethods()) + .filter(m -> m.isAnnotationPresent(com.github.copilot.tool.CopilotTool.class)) + .filter(m -> !Modifier.isStatic(m.getModifiers())).map(Method::getName).collect(Collectors.toList()); + if (!instanceMethods.isEmpty()) { + throw new IllegalArgumentException( + "fromClass() requires all @CopilotTool methods to be static, but found instance methods: " + + instanceMethods + ". Use fromObject(new " + clazz.getSimpleName() + "()) instead."); + } + return loadDefinitions(clazz, null); + } + + // ------------------------------------------------------------------ + // Fluent copy-style modifier methods for lambda-defined tools + // ------------------------------------------------------------------ + + /** + * Returns a copy with the {@code overridesBuiltInTool} flag set. + * + * @param value + * {@code true} to indicate this tool intentionally overrides a + * built-in CLI tool with the same name + * @return a new {@code ToolDefinition} with the flag applied + * @since 1.0.6 + */ + @CopilotExperimental + public ToolDefinition overridesBuiltInTool(boolean value) { + return new ToolDefinition(name, description, parameters, handler, value, skipPermission, defer, metadata); + } + + /** + * Returns a copy with the {@code skipPermission} flag set. + * + * @param value + * {@code true} to skip the permission request for this tool + * invocation + * @return a new {@code ToolDefinition} with the flag applied + * @since 1.0.6 + */ + @CopilotExperimental + public ToolDefinition skipPermission(boolean value) { + return new ToolDefinition(name, description, parameters, handler, overridesBuiltInTool, value, defer, metadata); + } + + /** + * Returns a copy with the {@code defer} mode set. + * + * @param value + * the deferral mode; use {@link ToolDefer#AUTO} to allow deferral or + * {@link ToolDefer#NEVER} to force the tool to always be pre-loaded + * @return a new {@code ToolDefinition} with the defer mode applied + * @since 1.0.6 + */ + @CopilotExperimental + public ToolDefinition defer(ToolDefer value) { + return new ToolDefinition(name, description, parameters, handler, overridesBuiltInTool, skipPermission, value, + metadata); + } + + /** + * Returns a copy with the opaque {@code metadata} bag set. + * + * @param value + * the opaque, host-defined metadata; keys are namespaced and not + * part of the stable public API + * @return a new {@code ToolDefinition} with the metadata applied + * @since 1.0.7 + */ + @CopilotExperimental + public ToolDefinition metadata(Map value) { + return new ToolDefinition(name, description, parameters, handler, overridesBuiltInTool, skipPermission, defer, + value); + } + + // ------------------------------------------------------------------ + // from(...) — sync, no ToolInvocation + // ------------------------------------------------------------------ + + /** + * Creates a tool definition with a zero-argument synchronous handler. + * + *

+ * The handler is a {@link Supplier} that returns the tool result. + * + *

Example

+ * + *
{@code
+     * ToolDefinition ping = ToolDefinition.from("ping", "Returns a simple pong response", () -> "pong");
+     * }
+ * + * @param + * the return type of the handler + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param handler + * the zero-argument sync handler + * @return a new tool definition + * @throws IllegalArgumentException + * if {@code name} or {@code description} is blank, or if + * {@code handler} is null + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition from(String name, String description, Supplier handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper); + ToolHandler toolHandler = invocation -> { + R result = handler.get(); + return CompletableFuture.completedFuture(formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + /** + * Creates a tool definition with a one-argument synchronous handler. + * + *

Example

+ * + *
{@code
+     * ToolDefinition greet = ToolDefinition.from("greet", "Greets a user by name",
+     * 		Param.of(String.class, "name", "The user's name"), name -> "Hello, " + name + "!");
+     * }
+ * + * @param + * the type of the first parameter + * @param + * the return type of the handler + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param p1 + * the first parameter descriptor + * @param handler + * the one-argument sync handler + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition from(String name, String description, Param p1, Function handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper, p1); + ToolHandler toolHandler = invocation -> { + T1 arg1 = ParamCoercion.coerce(invocation.getArguments(), p1, mapper); + R result = handler.apply(arg1); + return CompletableFuture.completedFuture(formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + /** + * Creates a tool definition with a two-argument synchronous handler. + * + *

Example

+ * + *
{@code
+     * ToolDefinition add = ToolDefinition.from("add", "Adds two integers", Param.of(Integer.class, "a", "First number"),
+     * 		Param.of(Integer.class, "b", "Second number"), (a, b) -> a + b);
+     * }
+ * + * @param + * the type of the first parameter + * @param + * the type of the second parameter + * @param + * the return type of the handler + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param p1 + * the first parameter descriptor + * @param p2 + * the second parameter descriptor + * @param handler + * the two-argument sync handler + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition from(String name, String description, Param p1, Param p2, + BiFunction handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper, p1, p2); + ToolHandler toolHandler = invocation -> { + T1 arg1 = ParamCoercion.coerce(invocation.getArguments(), p1, mapper); + T2 arg2 = ParamCoercion.coerce(invocation.getArguments(), p2, mapper); + R result = handler.apply(arg1, arg2); + return CompletableFuture.completedFuture(formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + // ------------------------------------------------------------------ + // fromAsync(...) — async, no ToolInvocation + // ------------------------------------------------------------------ + + /** + * Creates a tool definition with a zero-argument asynchronous handler. + * + *

+ * The handler is a {@link Supplier} returning a {@link CompletableFuture}. + * + *

Example

+ * + *
{@code
+     * ToolDefinition ping = ToolDefinition.fromAsync("ping", "Returns a pong response asynchronously",
+     * 		() -> CompletableFuture.completedFuture("pong"));
+     * }
+ * + * @param + * the return type wrapped in {@link CompletableFuture} + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param handler + * the zero-argument async handler + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition fromAsync(String name, String description, + Supplier> handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper); + ToolHandler toolHandler = invocation -> { + CompletableFuture future = handler.get(); + if (future == null) { + return CompletableFuture.failedFuture( + new NullPointerException("Async handler for tool '" + name + "' returned a null future")); + } + return future.thenApply(result -> formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + /** + * Creates a tool definition with a one-argument asynchronous handler. + * + *

Example

+ * + *
{@code
+     * ToolDefinition greet = ToolDefinition.fromAsync("greet_async", "Greets a user by name asynchronously",
+     * 		Param.of(String.class, "name", "The user's name"),
+     * 		name -> CompletableFuture.completedFuture("Hello, " + name + "!"));
+     * }
+ * + * @param + * the type of the first parameter + * @param + * the return type wrapped in {@link CompletableFuture} + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param p1 + * the first parameter descriptor + * @param handler + * the one-argument async handler + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition fromAsync(String name, String description, Param p1, + Function> handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper, p1); + ToolHandler toolHandler = invocation -> { + T1 arg1 = ParamCoercion.coerce(invocation.getArguments(), p1, mapper); + CompletableFuture future = handler.apply(arg1); + if (future == null) { + return CompletableFuture.failedFuture( + new NullPointerException("Async handler for tool '" + name + "' returned a null future")); + } + return future.thenApply(result -> formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + /** + * Creates a tool definition with a two-argument asynchronous handler. + * + * @param + * the type of the first parameter + * @param + * the type of the second parameter + * @param + * the return type wrapped in {@link CompletableFuture} + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param p1 + * the first parameter descriptor + * @param p2 + * the second parameter descriptor + * @param handler + * the two-argument async handler + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition fromAsync(String name, String description, Param p1, Param p2, + BiFunction> handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper, p1, p2); + ToolHandler toolHandler = invocation -> { + T1 arg1 = ParamCoercion.coerce(invocation.getArguments(), p1, mapper); + T2 arg2 = ParamCoercion.coerce(invocation.getArguments(), p2, mapper); + CompletableFuture future = handler.apply(arg1, arg2); + if (future == null) { + return CompletableFuture.failedFuture( + new NullPointerException("Async handler for tool '" + name + "' returned a null future")); + } + return future.thenApply(result -> formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + // ------------------------------------------------------------------ + // fromWithToolInvocation(...) — sync, with ToolInvocation context + // ------------------------------------------------------------------ + + /** + * Creates a tool definition with a zero-argument synchronous handler that + * receives the {@link ToolInvocation} context. + * + *

Example

+ * + *
{@code
+     * ToolDefinition sessionInfo = ToolDefinition.fromWithToolInvocation("session_info", "Return the current session id",
+     * 		invocation -> "sessionId=" + invocation.getSessionId());
+     * }
+ * + * @param + * the return type of the handler + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param handler + * a function accepting the {@link ToolInvocation} context + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition fromWithToolInvocation(String name, String description, + Function handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper); + ToolHandler toolHandler = invocation -> { + R result = handler.apply(invocation); + return CompletableFuture.completedFuture(formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + /** + * Creates a tool definition with a one-argument synchronous handler that also + * receives the {@link ToolInvocation} context. + * + *

Example

+ * + *
{@code
+     * ToolDefinition reportPhase = ToolDefinition.fromWithToolInvocation("report_phase",
+     * 		"Report the current phase along with invocation context", Param.of(String.class, "phase", "Current phase"),
+     * 		(phase, invocation) -> "phase=" + phase + ", toolCallId=" + invocation.getToolCallId());
+     * }
+ * + * @param + * the type of the first parameter + * @param + * the return type of the handler + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param p1 + * the first parameter descriptor + * @param handler + * a function accepting the typed argument and the + * {@link ToolInvocation} context + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition fromWithToolInvocation(String name, String description, Param p1, + BiFunction handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper, p1); + ToolHandler toolHandler = invocation -> { + T1 arg1 = ParamCoercion.coerce(invocation.getArguments(), p1, mapper); + R result = handler.apply(arg1, invocation); + return CompletableFuture.completedFuture(formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + // ------------------------------------------------------------------ + // fromAsyncWithToolInvocation(...) — async, with ToolInvocation context + // ------------------------------------------------------------------ + + /** + * Creates a tool definition with a zero-argument asynchronous handler that + * receives the {@link ToolInvocation} context. + * + *

Example

+ * + *
{@code
+     * ToolDefinition sessionInfo = ToolDefinition.fromAsyncWithToolInvocation("session_info_async",
+     * 		"Return the current session id asynchronously",
+     * 		invocation -> CompletableFuture.completedFuture("sessionId=" + invocation.getSessionId()));
+     * }
+ * + * @param + * the return type wrapped in {@link CompletableFuture} + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param handler + * a function accepting the {@link ToolInvocation} context, returning + * a {@link CompletableFuture} + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition fromAsyncWithToolInvocation(String name, String description, + Function> handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper); + ToolHandler toolHandler = invocation -> { + CompletableFuture future = handler.apply(invocation); + if (future == null) { + return CompletableFuture.failedFuture( + new NullPointerException("Async handler for tool '" + name + "' returned a null future")); + } + return future.thenApply(result -> formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + /** + * Creates a tool definition with a one-argument asynchronous handler that also + * receives the {@link ToolInvocation} context. + * + *

Example

+ * + *
{@code
+     * ToolDefinition reportPhase = ToolDefinition.fromAsyncWithToolInvocation("report_phase_async",
+     * 		"Report the current phase with invocation context asynchronously",
+     * 		Param.of(String.class, "phase", "The current phase"), (phase, invocation) -> CompletableFuture
+     * 				.completedFuture("phase=" + phase + ", toolCallId=" + invocation.getToolCallId()));
+     * }
+ * + * @param + * the type of the first parameter + * @param + * the return type wrapped in {@link CompletableFuture} + * @param name + * the unique name of the tool (must not be blank) + * @param description + * a description of what the tool does (must not be blank) + * @param p1 + * the first parameter descriptor + * @param handler + * a function accepting the typed argument and the + * {@link ToolInvocation} context, returning a + * {@link CompletableFuture} + * @return a new tool definition + * @throws IllegalArgumentException + * if validation fails + * @since 1.0.6 + */ + @CopilotExperimental + public static ToolDefinition fromAsyncWithToolInvocation(String name, String description, Param p1, + BiFunction> handler) { + requireNonBlankToolName(name); + requireNonBlankDescription(description); + requireNonNullHandler(handler, name); + final ObjectMapper mapper = getConfiguredMapper(); + Map schema = ParamSchema.buildSchema(name, mapper, p1); + ToolHandler toolHandler = invocation -> { + T1 arg1 = ParamCoercion.coerce(invocation.getArguments(), p1, mapper); + CompletableFuture future = handler.apply(arg1, invocation); + if (future == null) { + return CompletableFuture.failedFuture( + new NullPointerException("Async handler for tool '" + name + "' returned a null future")); + } + return future.thenApply(result -> formatResult(result, mapper)); + }; + return new ToolDefinition(name, description, schema, toolHandler, null, null, null, null); + } + + // ------------------------------------------------------------------ + // Internal helpers: result formatting, validation + // ------------------------------------------------------------------ + + /** + * Formats a handler return value according to the tool result contract: + *
    + *
  • {@link String} — returned as-is
  • + *
  • {@code null} — mapped to {@code "Success"} (covers handlers that return + * null to indicate a successful no-value result)
  • + *
  • any other value — JSON-serialized via {@link ObjectMapper}
  • + *
+ */ + private static Object formatResult(Object result, ObjectMapper mapper) { + if (result == null) { + return "Success"; + } + if (result instanceof String) { + return result; + } + if (result instanceof ToolResultObject) { + return result; + } + try { + return mapper.writeValueAsString(result); + } catch (com.fasterxml.jackson.core.JsonProcessingException ex) { + throw new IllegalStateException("Failed to serialize tool result to JSON", ex); + } + } + + // ------------------------------------------------------------------ + // Validation helpers + // ------------------------------------------------------------------ + + private static void requireNonBlankToolName(String name) { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("Tool name must not be null or blank"); + } + } + + private static void requireNonBlankDescription(String description) { + if (description == null || description.isBlank()) { + throw new IllegalArgumentException("Tool description must not be null or blank"); + } + } + + private static void requireNonNullHandler(Object handler, String toolName) { + if (handler == null) { + throw new IllegalArgumentException("handler must not be null for tool '" + toolName + "'"); + } + } + + @SuppressWarnings("unchecked") + private static List loadDefinitions(Class clazz, Object instance) { + String metaClassName = clazz.getName() + "$$CopilotToolMeta"; + try { + Class metaClass = Class.forName(metaClassName, true, clazz.getClassLoader()); + var provider = (com.github.copilot.tool.CopilotToolMetadataProvider) metaClass + .getDeclaredConstructor().newInstance(); + return provider.definitions(instance, getConfiguredMapper()); + } catch (ClassNotFoundException e) { + throw new IllegalStateException("Generated class " + metaClassName + " not found. " + + "Ensure the CopilotToolProcessor annotation processor ran during compilation. " + + "Add the copilot-sdk-java dependency to your annotation processor path.", e); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Failed to invoke " + metaClassName + ".definitions()", e); + } + } + + /** + * Returns the SDK-configured ObjectMapper for tool argument/result + * serialization. Configuration mirrors + * {@code JsonRpcClient.createObjectMapper()}. + */ + private static ObjectMapper getConfiguredMapper() { + return ConfiguredMapperHolder.INSTANCE; + } + + /** + * Lazy holder for the configured ObjectMapper (thread-safe, initialized on + * first access). + */ + private static final class ConfiguredMapperHolder { + static final ObjectMapper INSTANCE = createMapper(); + + private static ObjectMapper createMapper() { + // Configuration must match JsonRpcClient.createObjectMapper() + var mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL); + return mapper; + } } } diff --git a/java/src/main/java/com/github/copilot/rpc/ToolInvocation.java b/java/src/main/java/com/github/copilot/rpc/ToolInvocation.java index dddfdd06f0..efe24fd6ae 100644 --- a/java/src/main/java/com/github/copilot/rpc/ToolInvocation.java +++ b/java/src/main/java/com/github/copilot/rpc/ToolInvocation.java @@ -4,6 +4,7 @@ package com.github.copilot.rpc; +import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonInclude; @@ -11,6 +12,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.generated.rpc.CurrentToolMetadata; /** * Represents a tool invocation request from the AI assistant. @@ -18,6 +20,12 @@ * When the assistant invokes a tool, this object contains the context including * the session ID, tool call ID, tool name, and arguments parsed from the * assistant's request. + *

+ * In annotation-based tools, methods annotated with + * {@link com.github.copilot.tool.CopilotTool} may declare a + * {@code ToolInvocation} parameter in any position (before, between, or after + * schema-visible parameters). It is always injected as runtime context and is + * never included in the tool's JSON schema. * * @see ToolHandler * @see ToolDefinition @@ -34,6 +42,7 @@ public final class ToolInvocation { private String toolCallId; private String toolName; private JsonNode argumentsNode; + private List availableTools; /** * Gets the session ID where the tool was invoked. @@ -168,4 +177,35 @@ public ToolInvocation setArguments(JsonNode arguments) { this.argumentsNode = arguments; return this; } + + /** + * Gets a snapshot of the session's currently initialized tools. + *

+ * The SDK populates this only when the invocation targets the built-in + * tool-search tool ({@code "tool_search_tool"}), so a tool-search override can + * rank or filter the live catalog — including MCP tools configured in settings + * — without issuing its own RPC. It is {@code null} for every other tool + * invocation. + * + * @return the available tools snapshot, or {@code null} if not applicable + * @since 1.0.7 + */ + public List getAvailableTools() { + return availableTools; + } + + /** + * Sets the available tools snapshot. + *

+ * Note: This method is intended for internal SDK use. Users + * typically do not need to call this method directly. + * + * @param availableTools + * the available tools snapshot + * @return this invocation for method chaining + */ + public ToolInvocation setAvailableTools(List availableTools) { + this.availableTools = availableTools; + return this; + } } diff --git a/java/src/main/java/com/github/copilot/rpc/ToolResultObject.java b/java/src/main/java/com/github/copilot/rpc/ToolResultObject.java index e55ff9ab6e..2e101acbd7 100644 --- a/java/src/main/java/com/github/copilot/rpc/ToolResultObject.java +++ b/java/src/main/java/com/github/copilot/rpc/ToolResultObject.java @@ -31,7 +31,7 @@ *

Example: Custom Result

* *
{@code
- * return new ToolResultObject("success", "Result text", null, null, null, null);
+ * return new ToolResultObject("success", "Result text", null, null, null, null, null);
  * }
* * @param resultType @@ -46,6 +46,8 @@ * the session log text * @param toolTelemetry * the tool telemetry data + * @param toolReferences + * names of tools returned by a tool-search tool * @see ToolHandler * @see ToolBinaryResult * @since 1.0.0 @@ -55,7 +57,33 @@ public record ToolResultObject(@JsonProperty("resultType") String resultType, @JsonProperty("textResultForLlm") String textResultForLlm, @JsonProperty("binaryResultsForLlm") List binaryResultsForLlm, @JsonProperty("error") String error, @JsonProperty("sessionLog") String sessionLog, - @JsonProperty("toolTelemetry") Map toolTelemetry) { + @JsonProperty("toolTelemetry") Map toolTelemetry, + @JsonProperty("toolReferences") List toolReferences) { + + /** + * Creates a result without tool references. + *

+ * Provided for source and binary compatibility with callers written or compiled + * before the {@code toolReferences} component was added. Delegates to the + * canonical constructor with {@code toolReferences} set to {@code null}. + * + * @param resultType + * the result type ("success" or "error"), defaults to "success" + * @param textResultForLlm + * the text result to be sent to the LLM + * @param binaryResultsForLlm + * the list of binary results to be sent to the LLM + * @param error + * the error message, or {@code null} if successful + * @param sessionLog + * the session log text + * @param toolTelemetry + * the tool telemetry data + */ + public ToolResultObject(String resultType, String textResultForLlm, List binaryResultsForLlm, + String error, String sessionLog, Map toolTelemetry) { + this(resultType, textResultForLlm, binaryResultsForLlm, error, sessionLog, toolTelemetry, null); + } /** * Creates a success result with the given text. @@ -65,7 +93,7 @@ public record ToolResultObject(@JsonProperty("resultType") String resultType, * @return a success result */ public static ToolResultObject success(String textResultForLlm) { - return new ToolResultObject("success", textResultForLlm, null, null, null, null); + return new ToolResultObject("success", textResultForLlm, null, null, null, null, null); } /** @@ -76,7 +104,7 @@ public static ToolResultObject success(String textResultForLlm) { * @return an error result */ public static ToolResultObject error(String error) { - return new ToolResultObject("error", null, null, error, null, null); + return new ToolResultObject("error", null, null, error, null, null, null); } /** @@ -89,7 +117,7 @@ public static ToolResultObject error(String error) { * @return an error result */ public static ToolResultObject error(String textResultForLlm, String error) { - return new ToolResultObject("error", textResultForLlm, null, error, null, null); + return new ToolResultObject("error", textResultForLlm, null, error, null, null, null); } /** @@ -106,6 +134,6 @@ public static ToolResultObject error(String textResultForLlm, String error) { * @return a failure result */ public static ToolResultObject failure(String textResultForLlm, String error) { - return new ToolResultObject("failure", textResultForLlm, null, error, null, null); + return new ToolResultObject("failure", textResultForLlm, null, error, null, null, null); } } diff --git a/java/src/main/java/com/github/copilot/rpc/ToolSearchConfig.java b/java/src/main/java/com/github/copilot/rpc/ToolSearchConfig.java new file mode 100644 index 0000000000..dd27ddf868 --- /dev/null +++ b/java/src/main/java/com/github/copilot/rpc/ToolSearchConfig.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +package com.github.copilot.rpc; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Overrides the runtime's built-in tool-search behavior. + *

+ * Tool search defers tools to keep the model's active tool set small. To + * override the tool-search tool's implementation, register a tool named + * {@code "tool_search_tool"} with {@code overridesBuiltInTool} set to + * {@code true}. + * + * @since 1.3.0 + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ToolSearchConfig { + + @JsonProperty("enabled") + private Boolean enabled; + + @JsonProperty("deferThreshold") + private Integer deferThreshold; + + /** + * Gets whether tool search is enabled. + * + * @return {@code true} if enabled, {@code false} if disabled, or {@code null} + * for the runtime default + */ + public Boolean getEnabled() { + return enabled; + } + + /** + * Toggle that enables or disables tool search. + * + * @param enabled + * {@code true} to enable, {@code false} to disable + * @return this config for method chaining + */ + public ToolSearchConfig setEnabled(Boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Gets the tool count above which MCP and external tools are deferred behind + * tool search. + * + * @return the defer threshold, or {@code null} for the runtime default (30) + */ + public Integer getDeferThreshold() { + return deferThreshold; + } + + /** + * Sets the tool count above which MCP and external tools are deferred behind + * tool search. Defaults to the runtime default (30) when unset. + * + * @param deferThreshold + * the threshold value + * @return this config for method chaining + */ + public ToolSearchConfig setDeferThreshold(Integer deferThreshold) { + this.deferThreshold = deferThreshold; + return this; + } +} diff --git a/java/src/main/java/com/github/copilot/rpc/package-info.java b/java/src/main/java/com/github/copilot/rpc/package-info.java index edc7dedcfc..83772cd048 100644 --- a/java/src/main/java/com/github/copilot/rpc/package-info.java +++ b/java/src/main/java/com/github/copilot/rpc/package-info.java @@ -80,7 +80,7 @@ *

Usage Example

* *
{@code
- * var config = new SessionConfig().setModel("gpt-4.1").setStreaming(true)
+ * var config = new SessionConfig().setModel("gpt-5.4").setStreaming(true)
  * 		.setSystemMessage(new SystemMessageConfig().setMode(SystemMessageMode.APPEND)
  * 				.setContent("Be concise in your responses."))
  * 		.setTools(List.of(ToolDefinition.create("my_tool", "Description", schema, handler)));
diff --git a/java/src/main/java/com/github/copilot/tool/CopilotTool.java b/java/src/main/java/com/github/copilot/tool/CopilotTool.java
new file mode 100644
index 0000000000..db9e3ca62d
--- /dev/null
+++ b/java/src/main/java/com/github/copilot/tool/CopilotTool.java
@@ -0,0 +1,136 @@
+/*---------------------------------------------------------------------------------------------
+ *  Copyright (c) Microsoft Corporation. All rights reserved.
+ *--------------------------------------------------------------------------------------------*/
+
+package com.github.copilot.tool;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import com.github.copilot.CopilotExperimental;
+import com.github.copilot.rpc.ToolDefer;
+
+/**
+ * Marks a method as a Copilot tool. The annotated method will be exposed to the
+ * model as a callable tool during a session.
+ *
+ * 

+ * Example usage: + * + *

+ * @CopilotTool("Get weather for a location")
+ * public CompletableFuture<String> getWeather(
+ * 		@CopilotToolParam(value = "City name", required = true) String location) {
+ * 	return CompletableFuture.completedFuture("Sunny in " + location);
+ * }
+ * 
+ * + * @since 1.0.2 + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@CopilotExperimental +public @interface CopilotTool { + + /** Tool description (sent to the model). */ + String value(); + + /** Tool name. Defaults to method name converted to snake_case. */ + String name() default ""; + + /** Whether this tool overrides a built-in tool. */ + boolean overridesBuiltInTool() default false; + + /** Whether to skip permission checks. */ + boolean skipPermission() default false; + + /** Defer configuration for this tool. */ + ToolDefer defer() default ToolDefer.NONE; + + /** + * Opaque, host-defined metadata for this tool. Keys are namespaced and not part + * of the stable public API; specific keys may be recognized to inform + * host-specific behavior. + * + *

+ * Because annotation members cannot express arbitrary maps, this uses a + * deliberately shallow representation: each {@link MetadataEntry} maps a string + * key to a single {@link MetadataValue} that is either a boolean, a string, or + * a one-level map of named boolean {@link MetadataFlag flags}. Numbers, arrays, + * and deeper nesting are not supported here; use the programmatic + * {@code ToolDefinition.createWithMetadata(...)} / + * {@code ToolDefinition.metadata(...)} API for richer values. + * + *

+ * Example emitted shape: + * + *

+     * Map.of("github.com/copilot:safeForTelemetry", Map.of("name", true, "inputsNames", false))
+     * 
+ */ + MetadataEntry[] metadata() default {}; + + /** + * A single metadata key/value pair. Used only as a member value of + * {@link CopilotTool#metadata()}. + */ + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({}) + @interface MetadataEntry { + + /** The namespaced metadata key. */ + String key(); + + /** The value associated with {@link #key()}. */ + MetadataValue value(); + } + + /** + * A metadata value. Exactly one representation is intended per value: a map of + * named boolean {@link #flags()} (when non-empty), otherwise a {@link #str()} + * (when non-empty), otherwise a {@link #bool()}. + */ + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({}) + @interface MetadataValue { + + /** + * Scalar boolean value. Used when {@link #flags()} and {@link #str()} are + * unset. + */ + boolean bool() default false; + + /** + * Scalar string value. Used when {@link #flags()} is empty and this is + * non-empty. + */ + String str() default ""; + + /** + * Object-like value: a one-level map of named boolean flags. Takes precedence + * when non-empty. + */ + MetadataFlag[] flags() default {}; + } + + /** + * A single named boolean flag within a {@link MetadataValue#flags()} map. + */ + @Documented + @Retention(RetentionPolicy.RUNTIME) + @Target({}) + @interface MetadataFlag { + + /** The flag name (map key). */ + String name(); + + /** The flag value. */ + boolean value(); + } +} diff --git a/java/src/main/java/com/github/copilot/tool/CopilotToolMetadataProvider.java b/java/src/main/java/com/github/copilot/tool/CopilotToolMetadataProvider.java new file mode 100644 index 0000000000..25194626e8 --- /dev/null +++ b/java/src/main/java/com/github/copilot/tool/CopilotToolMetadataProvider.java @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import java.util.List; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.CopilotExperimental; +import com.github.copilot.rpc.ToolDefinition; + +/** + * Contract for classes that provide {@link ToolDefinition} metadata for + * {@code @CopilotTool}-annotated methods. + * + *

+ * The {@link CopilotToolProcessor} annotation processor generates an + * implementation of this interface as a {@code $$CopilotToolMeta} companion + * class. Users may also implement this interface directly for full manual + * control over tool registration without using annotation processing. + * + * @param + * the tool class whose methods are described by this provider + * @since 1.0.2 + */ +@CopilotExperimental +public interface CopilotToolMetadataProvider { + + /** + * Returns tool definitions for the given instance. + * + * @param instance + * the object containing tool methods, or {@code null} for static + * methods + * @param mapper + * the SDK-configured {@link ObjectMapper} for argument + * deserialization + * @return list of tool definitions with working invocation handlers + */ + List definitions(T instance, ObjectMapper mapper); +} diff --git a/java/src/main/java/com/github/copilot/tool/CopilotToolParam.java b/java/src/main/java/com/github/copilot/tool/CopilotToolParam.java new file mode 100644 index 0000000000..0b667d9d71 --- /dev/null +++ b/java/src/main/java/com/github/copilot/tool/CopilotToolParam.java @@ -0,0 +1,50 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.github.copilot.CopilotExperimental; + +/** + * Annotates a parameter of a {@link CopilotTool}-annotated method to provide + * metadata about the parameter that is sent to the model. + * + *

+ * Example usage: + * + *

+ * @CopilotTool("Search for issues")
+ * public CompletableFuture<String> searchIssues(
+ * 		@CopilotToolParam(value = "Search query", required = true) String query,
+ * 		@CopilotToolParam(value = "Max results", required = false, defaultValue = "10") int limit) {
+ * 	// ...
+ * }
+ * 
+ * + * @since 1.0.2 + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +@CopilotExperimental +public @interface CopilotToolParam { + + /** Parameter description (sent to the model). */ + String value() default ""; + + /** Parameter name override. Defaults to the actual parameter name. */ + String name() default ""; + + /** Whether this parameter is required. Default true. */ + boolean required() default true; + + /** Optional default value when the argument is omitted. */ + String defaultValue() default ""; +} diff --git a/java/src/main/java/com/github/copilot/tool/CopilotToolProcessor.java b/java/src/main/java/com/github/copilot/tool/CopilotToolProcessor.java new file mode 100644 index 0000000000..03af4a7cd9 --- /dev/null +++ b/java/src/main/java/com/github/copilot/tool/CopilotToolProcessor.java @@ -0,0 +1,862 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.Modifier; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +import com.github.copilot.CopilotExperimental; + +/** + * JSR 269 annotation processor that finds {@link CopilotTool}-annotated methods + * and generates {@code $$CopilotToolMeta} companion classes containing tool + * definitions, JSON Schema, and invocation lambdas. + * + *

+ * For a class {@code com.example.MyTools} containing {@code @CopilotTool} + * methods, this processor generates + * {@code com.example.MyTools$$CopilotToolMeta} in the same package. + * + * @since 1.0.2 + */ +@SupportedAnnotationTypes("com.github.copilot.tool.CopilotTool") +@SupportedSourceVersion(SourceVersion.RELEASE_17) +@CopilotExperimental +public class CopilotToolProcessor extends AbstractProcessor { + + private static final String TOOL_INVOCATION_TYPE = "com.github.copilot.rpc.ToolInvocation"; + + private final SchemaGenerator schemaGenerator = new SchemaGenerator(); + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + List annotatedElements = getCopilotToolAnnotatedElements(roundEnv); + for (Element element : annotatedElements) { + if (element.getKind() != ElementKind.METHOD) { + continue; + } + ExecutableElement method = (ExecutableElement) element; + + // Validate: private methods are not allowed + if (method.getModifiers().contains(Modifier.PRIVATE)) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@CopilotTool methods must not be private", method); + continue; + } + + // Validate @CopilotToolParam conflicts + int toolInvocationParamCount = 0; + for (VariableElement param : method.getParameters()) { + if (isToolInvocationType(param.asType())) { + toolInvocationParamCount++; + if (param.getAnnotation(CopilotToolParam.class) != null) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@CopilotToolParam is not supported on ToolInvocation parameters because ToolInvocation is injected runtime context and not part of the tool schema", + param); + } + continue; + } + CopilotToolParam paramAnnotation = param.getAnnotation(CopilotToolParam.class); + if (paramAnnotation != null && paramAnnotation.required() + && !paramAnnotation.defaultValue().isEmpty()) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@CopilotToolParam cannot have both required=true and a non-empty defaultValue", param); + } + if (paramAnnotation != null && !paramAnnotation.defaultValue().isEmpty()) { + String defaultValidationError = validateDefaultValueCompatibility(param.asType(), + paramAnnotation.defaultValue()); + if (defaultValidationError != null) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, defaultValidationError, param); + } + } + if (paramAnnotation != null && !paramAnnotation.required() && paramAnnotation.defaultValue().isEmpty() + && param.asType().getKind().isPrimitive()) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@CopilotToolParam(required=false) primitive parameters must provide defaultValue or use a boxed/Optional type", + param); + } + } + if (toolInvocationParamCount > 1) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@CopilotTool methods may declare at most one ToolInvocation parameter; ToolInvocation is injected runtime context and not part of the tool schema", + method); + } + + // Validate single-record wrapper parameter metadata + List schemaParameters = getSchemaParameters(method.getParameters()); + if (schemaParameters.size() == 1) { + VariableElement singleParam = schemaParameters.get(0); + if (isRecord(singleParam.asType())) { + CopilotToolParam paramAnnotation = singleParam.getAnnotation(CopilotToolParam.class); + if (paramAnnotation != null) { + if (!paramAnnotation.defaultValue().isEmpty()) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@CopilotToolParam(defaultValue=...) is not supported on single-record tool parameters; use record component defaults or a non-record parameter", + singleParam); + } + if (!paramAnnotation.name().isEmpty() || !paramAnnotation.value().isEmpty() + || !paramAnnotation.required()) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@CopilotToolParam name/value/required are not supported on single-record tool parameters; annotate record components instead", + singleParam); + } + } + } + } + } + + // Group methods by enclosing type + Map> methodsByClass = new LinkedHashMap<>(); + for (Element element : annotatedElements) { + if (element.getKind() != ElementKind.METHOD) { + continue; + } + ExecutableElement method = (ExecutableElement) element; + if (method.getModifiers().contains(Modifier.PRIVATE)) { + continue; + } + TypeElement enclosingType = (TypeElement) method.getEnclosingElement(); + methodsByClass.computeIfAbsent(enclosingType, k -> new ArrayList<>()).add(method); + } + + // Generate $$CopilotToolMeta for each class + for (Map.Entry> entry : methodsByClass.entrySet()) { + generateMetaClass(entry.getKey(), entry.getValue()); + } + + return false; + } + + private List getCopilotToolAnnotatedElements(RoundEnvironment roundEnv) { + TypeElement copilotToolType = processingEnv.getElementUtils() + .getTypeElement("com.github.copilot.tool.CopilotTool"); + if (copilotToolType != null) { + return new ArrayList<>(roundEnv.getElementsAnnotatedWith(copilotToolType)); + } + return new ArrayList<>(roundEnv.getElementsAnnotatedWith(CopilotTool.class)); + } + + private void generateMetaClass(TypeElement classElement, List methods) { + String packageName = processingEnv.getElementUtils().getPackageOf(classElement).getQualifiedName().toString(); + String simpleClassName = classElement.getSimpleName().toString(); + String metaClassName = simpleClassName + "$$CopilotToolMeta"; + String qualifiedMetaClassName = packageName.isEmpty() ? metaClassName : packageName + "." + metaClassName; + + try { + JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(qualifiedMetaClassName, classElement); + try (PrintWriter out = new PrintWriter(sourceFile.openWriter())) { + writeMetaClass(out, packageName, simpleClassName, metaClassName, methods); + } + } catch (IOException e) { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "Failed to generate " + metaClassName + ": " + e.getMessage(), classElement); + } + } + + private void writeMetaClass(PrintWriter out, String packageName, String simpleClassName, String metaClassName, + List methods) { + out.println("// GENERATED by CopilotToolProcessor — do not edit"); + + if (!packageName.isEmpty()) { + out.println("package " + packageName + ";"); + out.println(); + } + + out.println("import com.github.copilot.rpc.ToolDefinition;"); + out.println("import com.github.copilot.rpc.ToolDefer;"); + out.println("import com.github.copilot.tool.CopilotToolMetadataProvider;"); + out.println("import com.fasterxml.jackson.databind.ObjectMapper;"); + out.println("import java.util.*;"); + out.println("import java.util.concurrent.CompletableFuture;"); + out.println(); + + out.println("public final class " + metaClassName + " implements CopilotToolMetadataProvider<" + simpleClassName + + "> {"); + out.println(); + + // Helper method for adding description/default to schema maps + if (needsWithMetaHelper(methods)) { + out.println( + " private static Map withMeta(Map base, String description, Object defaultValue) {"); + out.println(" var result = new LinkedHashMap(base);"); + out.println(" if (description != null) result.put(\"description\", description);"); + out.println(" if (defaultValue != null) result.put(\"default\", defaultValue);"); + out.println(" return Collections.unmodifiableMap(result);"); + out.println(" }"); + out.println(); + } + + // definitions method + out.println(" @Override"); + out.println(" @SuppressWarnings({\"unchecked\", \"rawtypes\"})"); + out.println( + " public List definitions(" + simpleClassName + " instance, ObjectMapper mapper) {"); + out.println(" return List.of("); + + for (int i = 0; i < methods.size(); i++) { + ExecutableElement method = methods.get(i); + writeToolDefinition(out, method); + if (i < methods.size() - 1) { + out.println(","); + } else { + out.println(); + } + } + + out.println(" );"); + out.println(" }"); + out.println("}"); + } + + private boolean needsWithMetaHelper(List methods) { + for (ExecutableElement method : methods) { + for (VariableElement param : method.getParameters()) { + CopilotToolParam paramAnnotation = param.getAnnotation(CopilotToolParam.class); + if (paramAnnotation != null + && (!paramAnnotation.value().isEmpty() || !paramAnnotation.defaultValue().isEmpty())) { + return true; + } + } + } + return false; + } + + private void writeToolDefinition(PrintWriter out, ExecutableElement method) { + CopilotTool annotation = method.getAnnotation(CopilotTool.class); + String toolName = annotation.name().isEmpty() + ? toSnakeCase(method.getSimpleName().toString()) + : annotation.name(); + String description = annotation.value(); + boolean overridesBuiltIn = annotation.overridesBuiltInTool(); + boolean skipPermission = annotation.skipPermission(); + com.github.copilot.rpc.ToolDefer defer = annotation.defer(); + + // Generate schema with @CopilotToolParam metadata (descriptions, names, + // defaults) + String schemaSource = generateSchemaWithParamMetadata(method.getParameters()); + + // Generate invocation lambda + String lambdaBody = generateLambdaBody(method); + + // Use the record constructor directly so all flags apply independently + String overridesArg = overridesBuiltIn ? "Boolean.TRUE" : "null"; + String skipPermArg = skipPermission ? "Boolean.TRUE" : "null"; + String deferArg = defer != com.github.copilot.rpc.ToolDefer.NONE ? "ToolDefer." + defer.name() : "null"; + + out.println(" new ToolDefinition("); + out.println(" \"" + escapeJava(toolName) + "\","); + out.println(" \"" + escapeJava(description) + "\","); + out.println(" " + schemaSource + ","); + out.println(" invocation -> {"); + out.println(" " + lambdaBody); + out.println(" },"); + out.println(" " + overridesArg + ","); + out.println(" " + skipPermArg + ","); + out.println(" " + deferArg + ","); + out.println(" " + metadataSource(annotation)); + out.print(" )"); + } + + /** + * Converts the {@code @CopilotTool(metadata = ...)} entries into a Java source + * literal. Returns {@code "null"} when no metadata is present, otherwise a + * {@code Map.of(...)} expression. + */ + private String metadataSource(CopilotTool annotation) { + CopilotTool.MetadataEntry[] entries = annotation.metadata(); + if (entries.length == 0) { + return "null"; + } + List parts = new ArrayList<>(); + for (CopilotTool.MetadataEntry entry : entries) { + parts.add("\"" + escapeJava(entry.key()) + "\", " + metadataValueSource(entry.value())); + } + return "Map.of(" + String.join(", ", parts) + ")"; + } + + /** + * Converts a single {@link CopilotTool.MetadataValue} into a Java source + * literal. A non-empty {@code flags} map takes precedence, then a non-empty + * {@code str}, otherwise the {@code bool} scalar. + */ + private String metadataValueSource(CopilotTool.MetadataValue value) { + CopilotTool.MetadataFlag[] flags = value.flags(); + if (flags.length > 0) { + List flagParts = new ArrayList<>(); + for (CopilotTool.MetadataFlag flag : flags) { + flagParts.add("\"" + escapeJava(flag.name()) + "\", " + flag.value()); + } + return "Map.of(" + String.join(", ", flagParts) + ")"; + } + if (!value.str().isEmpty()) { + return "\"" + escapeJava(value.str()) + "\""; + } + return String.valueOf(value.bool()); + } + + private String generateSchemaWithParamMetadata(List parameters) { + List schemaParameters = getSchemaParameters(parameters); + + if (schemaParameters.isEmpty()) { + return "Map.of(\"type\", \"object\", \"properties\", Map.of(), \"required\", List.of())"; + } + if (schemaParameters.size() == 1 && isRecord(schemaParameters.get(0).asType())) { + return schemaGenerator.generateSchemaSource(schemaParameters.get(0).asType(), processingEnv.getTypeUtils(), + processingEnv.getElementUtils()); + } + + List propertyEntries = new ArrayList<>(); + List requiredNames = new ArrayList<>(); + + for (VariableElement param : schemaParameters) { + String paramName = getParamName(param); + TypeMirror paramType = param.asType(); + CopilotToolParam paramAnnotation = param.getAnnotation(CopilotToolParam.class); + + // Generate the type schema for this parameter + String typeSchema = schemaGenerator.generateSchemaSource(paramType, processingEnv.getTypeUtils(), + processingEnv.getElementUtils()); + + // Build property schema with description and default if present + String propertySchema = buildPropertySchema(typeSchema, paramAnnotation, paramType); + + // Cast to Map via raw type for consistent Map.ofEntries typing + propertyEntries.add("Map.entry(\"" + paramName + "\", (Map)(Map) " + propertySchema + ")"); + + // Determine if required (Optional* types are never required) + boolean isOptionalType = paramType.getKind() == TypeKind.DECLARED && Set + .of("java.util.Optional", "java.util.OptionalInt", "java.util.OptionalLong", + "java.util.OptionalDouble") + .contains(((TypeElement) ((DeclaredType) paramType).asElement()).getQualifiedName().toString()); + if (!isOptionalType && (paramAnnotation == null || paramAnnotation.required())) { + requiredNames.add("\"" + paramName + "\""); + } + } + + String properties = "Map.ofEntries(" + String.join(", ", propertyEntries) + ")"; + String required = "List.of(" + String.join(", ", requiredNames) + ")"; + + return "Map.of(\"type\", \"object\", \"properties\", " + properties + ", \"required\", " + required + ")"; + } + + private List getSchemaParameters(List parameters) { + List filtered = new ArrayList<>(); + for (VariableElement param : parameters) { + if (!isToolInvocationType(param.asType())) { + filtered.add(param); + } + } + return filtered; + } + + private boolean isToolInvocationType(TypeMirror type) { + return TOOL_INVOCATION_TYPE.equals(processingEnv.getTypeUtils().erasure(type).toString()); + } + + private String buildPropertySchema(String typeSchema, CopilotToolParam paramAnnotation, TypeMirror paramType) { + if (paramAnnotation == null) { + return typeSchema; + } + + String desc = paramAnnotation.value(); + String defaultValue = paramAnnotation.defaultValue(); + + boolean hasDescription = !desc.isEmpty(); + boolean hasDefault = !defaultValue.isEmpty(); + + if (!hasDescription && !hasDefault) { + return typeSchema; + } + + // Use the withMeta helper method in the generated class + String descArg = hasDescription ? "\"" + escapeJava(desc) + "\"" : "null"; + String defaultArg = hasDefault ? generateDefaultLiteral(paramType, defaultValue) : "null"; + + return "withMeta(" + typeSchema + ", " + descArg + ", " + defaultArg + ")"; + } + + private String generateLambdaBody(ExecutableElement method) { + List params = method.getParameters(); + List schemaParameters = getSchemaParameters(params); + StringBuilder sb = new StringBuilder(); + + // Generate argument extraction + if (!schemaParameters.isEmpty()) { + // Check if single-record-parameter shortcut applies + if (schemaParameters.size() == 1 && isRecord(schemaParameters.get(0).asType())) { + String typeName = getTypeString(schemaParameters.get(0).asType()); + String paramName = schemaParameters.get(0).getSimpleName().toString(); + sb.append(" ").append(typeName).append(" ").append(paramName) + .append(" = mapper.convertValue(invocation.getArguments(), ").append(typeName) + .append(".class);\n"); + } else { + sb.append("Map args = invocation.getArguments();\n"); + for (VariableElement param : schemaParameters) { + String paramName = getParamName(param); + String varName = param.getSimpleName().toString(); + TypeMirror paramType = param.asType(); + + // Handle default values + CopilotToolParam paramAnnotation = param.getAnnotation(CopilotToolParam.class); + boolean hasDefault = paramAnnotation != null && !paramAnnotation.defaultValue().isEmpty(); + + if (hasDefault) { + String defaultValue = paramAnnotation.defaultValue(); + sb.append(" Object ").append(varName).append("Raw = args.containsKey(\"") + .append(paramName).append("\") ? args.get(\"").append(paramName).append("\") : ") + .append(generateDefaultLiteral(paramType, defaultValue)).append(";\n"); + sb.append(" ").append(getTypeString(paramType)).append(" ").append(varName) + .append(" = ").append(generateArgExtraction(varName + "Raw", paramType)).append(";\n"); + } else if (isOptionalType(paramType)) { + generateOptionalExtraction(sb, paramName, varName, paramType); + } else { + sb.append(" ").append(getTypeString(paramType)).append(" ").append(varName) + .append(" = ").append(generateArgExtractionFromMap(paramName, paramType)).append(";\n"); + } + } + } + } + + // Generate method invocation based on return type + TypeMirror returnType = method.getReturnType(); + String callTarget = method.getModifiers().contains(Modifier.STATIC) + ? ((TypeElement) method.getEnclosingElement()).getQualifiedName().toString() + : "instance"; + String methodCall = callTarget + "." + method.getSimpleName() + "(" + generateArgList(params) + ")"; + + if (returnType.getKind() == TypeKind.VOID) { + sb.append(" ").append(methodCall).append(";\n"); + sb.append(" return CompletableFuture.completedFuture(\"Success\");"); + } else if (isCompletableFuture(returnType)) { + TypeMirror typeArg = getCompletableFutureTypeArg(returnType); + if (typeArg != null && isStringType(typeArg)) { + // CompletableFuture -> CompletableFuture via thenApply + sb.append(" return ").append(methodCall).append(".thenApply(r -> (Object) r);"); + } else { + // CompletableFuture -> serialize to JSON + sb.append(" return ").append(methodCall) + .append(".thenApply(r -> { try { return (Object) mapper.writeValueAsString(r); }") + .append(" catch (Exception e) { throw new RuntimeException(e); } });"); + } + } else if (isStringType(returnType)) { + sb.append(" return CompletableFuture.completedFuture(").append(methodCall).append(");"); + } else { + sb.append(" try { return CompletableFuture.completedFuture(mapper.writeValueAsString(") + .append(methodCall).append(")); } catch (Exception e) { throw new RuntimeException(e); }"); + } + + return sb.toString(); + } + + private String generateArgList(List params) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < params.size(); i++) { + if (i > 0) { + sb.append(", "); + } + if (isToolInvocationType(params.get(i).asType())) { + sb.append("invocation"); + } else { + sb.append(params.get(i).getSimpleName().toString()); + } + } + return sb.toString(); + } + + private String generateArgExtractionFromMap(String paramName, TypeMirror type) { + if (type.getKind().isPrimitive()) { + return generatePrimitiveExtraction("args.get(\"" + paramName + "\")", type); + } + if (type.getKind() == TypeKind.ARRAY) { + return generateGenericTypeReferenceConversion("args.get(\"" + paramName + "\")", type); + } + if (type.getKind() == TypeKind.DECLARED) { + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + String qualifiedName = typeElement.getQualifiedName().toString(); + if ("java.lang.String".equals(qualifiedName)) { + return "(String) args.get(\"" + paramName + "\")"; + } + if (isBoxedNumeric(qualifiedName)) { + return generateBoxedNumericExtraction("args.get(\"" + paramName + "\")", qualifiedName); + } + if ("java.lang.Boolean".equals(qualifiedName)) { + return "(Boolean) args.get(\"" + paramName + "\")"; + } + if (hasTypeArguments(type)) { + return generateGenericTypeReferenceConversion("args.get(\"" + paramName + "\")", type); + } + // Complex types: enums, records, POJOs + return "mapper.convertValue(args.get(\"" + paramName + "\"), " + qualifiedName + ".class)"; + } + return "(Object) args.get(\"" + paramName + "\")"; + } + + private String generateArgExtraction(String varExpr, TypeMirror type) { + if (type.getKind().isPrimitive()) { + return generatePrimitiveExtraction(varExpr, type); + } + if (type.getKind() == TypeKind.ARRAY) { + return generateGenericTypeReferenceConversion(varExpr, type); + } + if (type.getKind() == TypeKind.DECLARED) { + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + String qualifiedName = typeElement.getQualifiedName().toString(); + if ("java.lang.String".equals(qualifiedName)) { + return "(String) " + varExpr; + } + if (isBoxedNumeric(qualifiedName)) { + return generateBoxedNumericExtraction(varExpr, qualifiedName); + } + if ("java.lang.Boolean".equals(qualifiedName)) { + return "(Boolean) " + varExpr; + } + if (hasTypeArguments(type)) { + return generateGenericTypeReferenceConversion(varExpr, type); + } + return "mapper.convertValue(" + varExpr + ", " + qualifiedName + ".class)"; + } + return "(Object) " + varExpr; + } + + private boolean hasTypeArguments(TypeMirror type) { + return type.getKind() == TypeKind.DECLARED && !((DeclaredType) type).getTypeArguments().isEmpty(); + } + + private String generateGenericTypeReferenceConversion(String expr, TypeMirror type) { + return "mapper.convertValue(" + expr + ", new com.fasterxml.jackson.core.type.TypeReference<" + type + + ">() {})"; + } + + private String generatePrimitiveExtraction(String expr, TypeMirror type) { + switch (type.getKind()) { + case INT : + return "((Number) " + expr + ").intValue()"; + case LONG : + return "((Number) " + expr + ").longValue()"; + case DOUBLE : + return "((Number) " + expr + ").doubleValue()"; + case FLOAT : + return "((Number) " + expr + ").floatValue()"; + case SHORT : + return "((Number) " + expr + ").shortValue()"; + case BYTE : + return "((Number) " + expr + ").byteValue()"; + case BOOLEAN : + return "(Boolean) " + expr; + case CHAR : + return "((String) " + expr + ").charAt(0)"; + default : + return "(" + type + ") " + expr; + } + } + + private boolean isOptionalType(TypeMirror type) { + if (type.getKind() != TypeKind.DECLARED) { + return false; + } + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + String name = typeElement.getQualifiedName().toString(); + return "java.util.Optional".equals(name) || "java.util.OptionalInt".equals(name) + || "java.util.OptionalLong".equals(name) || "java.util.OptionalDouble".equals(name); + } + + private void generateOptionalExtraction(StringBuilder sb, String paramName, String varName, TypeMirror paramType) { + TypeElement typeElement = (TypeElement) ((DeclaredType) paramType).asElement(); + String qualifiedName = typeElement.getQualifiedName().toString(); + + sb.append(" Object ").append(varName).append("Raw = args.get(\"").append(paramName) + .append("\");\n"); + + switch (qualifiedName) { + case "java.util.OptionalInt" : + sb.append(" java.util.OptionalInt ").append(varName).append(" = ").append(varName) + .append("Raw != null ? java.util.OptionalInt.of(((Number) ").append(varName) + .append("Raw).intValue()) : java.util.OptionalInt.empty();\n"); + break; + case "java.util.OptionalLong" : + sb.append(" java.util.OptionalLong ").append(varName).append(" = ").append(varName) + .append("Raw != null ? java.util.OptionalLong.of(((Number) ").append(varName) + .append("Raw).longValue()) : java.util.OptionalLong.empty();\n"); + break; + case "java.util.OptionalDouble" : + sb.append(" java.util.OptionalDouble ").append(varName).append(" = ").append(varName) + .append("Raw != null ? java.util.OptionalDouble.of(((Number) ").append(varName) + .append("Raw).doubleValue()) : java.util.OptionalDouble.empty();\n"); + break; + default : + // java.util.Optional — unwrap the type argument + List typeArgs = ((DeclaredType) paramType).getTypeArguments(); + if (!typeArgs.isEmpty()) { + TypeMirror innerType = typeArgs.get(0); + String innerExtraction = generateArgExtraction(varName + "Raw", innerType); + sb.append(" java.util.Optional ").append(varName).append(" = ").append(varName) + .append("Raw != null ? java.util.Optional.of(").append(innerExtraction) + .append(") : java.util.Optional.empty();\n"); + } else { + sb.append(" java.util.Optional ").append(varName).append(" = ").append(varName) + .append("Raw != null ? java.util.Optional.of(").append(varName) + .append("Raw) : java.util.Optional.empty();\n"); + } + break; + } + } + + private boolean isBoxedNumeric(String qualifiedName) { + return "java.lang.Integer".equals(qualifiedName) || "java.lang.Long".equals(qualifiedName) + || "java.lang.Double".equals(qualifiedName) || "java.lang.Float".equals(qualifiedName) + || "java.lang.Short".equals(qualifiedName) || "java.lang.Byte".equals(qualifiedName); + } + + private String generateBoxedNumericExtraction(String expr, String qualifiedName) { + switch (qualifiedName) { + case "java.lang.Integer" : + return "((Number) " + expr + ").intValue()"; + case "java.lang.Long" : + return "((Number) " + expr + ").longValue()"; + case "java.lang.Double" : + return "((Number) " + expr + ").doubleValue()"; + case "java.lang.Float" : + return "((Number) " + expr + ").floatValue()"; + case "java.lang.Short" : + return "((Number) " + expr + ").shortValue()"; + case "java.lang.Byte" : + return "((Number) " + expr + ").byteValue()"; + default : + return "(" + qualifiedName + ") " + expr; + } + } + + private String generateDefaultLiteral(TypeMirror type, String defaultValue) { + if (type.getKind().isPrimitive()) { + switch (type.getKind()) { + case INT : + case LONG : + case SHORT : + case BYTE : + return defaultValue; + case DOUBLE : + case FLOAT : + return defaultValue; + case BOOLEAN : + return defaultValue; + case CHAR : + return "\"" + escapeJava(defaultValue) + "\""; + default : + return "\"" + escapeJava(defaultValue) + "\""; + } + } + if (type.getKind() == TypeKind.DECLARED) { + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + String qualifiedName = typeElement.getQualifiedName().toString(); + if ("java.lang.String".equals(qualifiedName)) { + return "\"" + escapeJava(defaultValue) + "\""; + } + if (isBoxedNumeric(qualifiedName) || "java.lang.Boolean".equals(qualifiedName)) { + return defaultValue; + } + } + return "\"" + escapeJava(defaultValue) + "\""; + } + + private String validateDefaultValueCompatibility(TypeMirror type, String defaultValue) { + if (type.getKind().isPrimitive()) { + return validatePrimitiveDefault(type.getKind(), defaultValue); + } + if (type.getKind() == TypeKind.DECLARED) { + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + String qualifiedName = typeElement.getQualifiedName().toString(); + if ("java.lang.String".equals(qualifiedName)) { + return null; + } + if ("java.lang.Boolean".equals(qualifiedName)) { + return validateBooleanDefault(defaultValue); + } + if ("java.lang.Character".equals(qualifiedName)) { + return validateCharacterDefault(defaultValue); + } + if (isBoxedNumeric(qualifiedName)) { + return validatePrimitiveDefault(boxedTypeKind(qualifiedName), defaultValue); + } + } + return null; + } + + private String validatePrimitiveDefault(TypeKind kind, String defaultValue) { + try { + switch (kind) { + case INT : + Integer.parseInt(defaultValue); + return null; + case LONG : + Long.parseLong(defaultValue); + return null; + case SHORT : + Short.parseShort(defaultValue); + return null; + case BYTE : + Byte.parseByte(defaultValue); + return null; + case DOUBLE : + Double.parseDouble(defaultValue); + return null; + case FLOAT : + Float.parseFloat(defaultValue); + return null; + case BOOLEAN : + return validateBooleanDefault(defaultValue); + case CHAR : + return validateCharacterDefault(defaultValue); + default : + return null; + } + } catch (NumberFormatException ex) { + return "@CopilotToolParam defaultValue '" + defaultValue + "' is not valid for " + kind.name().toLowerCase() + + " parameters"; + } + } + + private String validateBooleanDefault(String defaultValue) { + if ("true".equalsIgnoreCase(defaultValue) || "false".equalsIgnoreCase(defaultValue)) { + return null; + } + return "@CopilotToolParam defaultValue '" + defaultValue + "' is not valid for boolean parameters"; + } + + private String validateCharacterDefault(String defaultValue) { + return defaultValue != null && defaultValue.length() == 1 + ? null + : "@CopilotToolParam defaultValue '" + defaultValue + "' is not valid for char parameters"; + } + + private TypeKind boxedTypeKind(String qualifiedName) { + switch (qualifiedName) { + case "java.lang.Integer" : + return TypeKind.INT; + case "java.lang.Long" : + return TypeKind.LONG; + case "java.lang.Double" : + return TypeKind.DOUBLE; + case "java.lang.Float" : + return TypeKind.FLOAT; + case "java.lang.Short" : + return TypeKind.SHORT; + case "java.lang.Byte" : + return TypeKind.BYTE; + default : + return TypeKind.NONE; + } + } + + private String getParamName(VariableElement param) { + CopilotToolParam paramAnnotation = param.getAnnotation(CopilotToolParam.class); + if (paramAnnotation != null && !paramAnnotation.name().isEmpty()) { + return paramAnnotation.name(); + } + return param.getSimpleName().toString(); + } + + private String getTypeString(TypeMirror type) { + if (type.getKind().isPrimitive()) { + return type.toString(); + } + if (type.getKind() == TypeKind.DECLARED) { + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + return typeElement.getQualifiedName().toString(); + } + return type.toString(); + } + + private boolean isRecord(TypeMirror type) { + if (type.getKind() != TypeKind.DECLARED) { + return false; + } + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + return typeElement.getKind() == ElementKind.RECORD; + } + + private boolean isCompletableFuture(TypeMirror type) { + if (type.getKind() != TypeKind.DECLARED) { + return false; + } + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + return "java.util.concurrent.CompletableFuture".equals(typeElement.getQualifiedName().toString()); + } + + private TypeMirror getCompletableFutureTypeArg(TypeMirror type) { + if (type.getKind() != TypeKind.DECLARED) { + return null; + } + DeclaredType declaredType = (DeclaredType) type; + List typeArgs = declaredType.getTypeArguments(); + if (typeArgs.isEmpty()) { + return null; + } + return typeArgs.get(0); + } + + private boolean isStringType(TypeMirror type) { + if (type.getKind() != TypeKind.DECLARED) { + return false; + } + TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); + return "java.lang.String".equals(typeElement.getQualifiedName().toString()); + } + + /** + * Converts a camelCase method name to snake_case. + * + * @param name + * the method name + * @return the snake_case tool name + */ + static String toSnakeCase(String name) { + if (name == null || name.isEmpty()) { + return name; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (Character.isUpperCase(c)) { + if (i > 0) { + sb.append('_'); + } + sb.append(Character.toLowerCase(c)); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + private static String escapeJava(String s) { + if (s == null) { + return ""; + } + return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\t", + "\\t"); + } +} diff --git a/java/src/main/java/com/github/copilot/tool/Param.java b/java/src/main/java/com/github/copilot/tool/Param.java new file mode 100644 index 0000000000..bbe188ce05 --- /dev/null +++ b/java/src/main/java/com/github/copilot/tool/Param.java @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import java.util.Objects; + +import com.github.copilot.CopilotExperimental; + +/** + * Runtime parameter metadata for lambda-defined tools. + * + *

+ * Each {@code Param} instance describes a single parameter that a tool accepts, + * including its Java type, wire name, description, whether it is required, and + * an optional default value. Instances are immutable; fluent mutators return + * new copies. + * + *

Example Usage

+ * + *
{@code
+ * Param query = Param.of(String.class, "query", "Search query text");
+ *
+ * Param limit = Param.of(Integer.class, "limit", "Max results", false, "10");
+ * }
+ * + * @param + * the Java type of the parameter value + * @since 1.0.6 + */ +@CopilotExperimental +public final class Param { + + private final Class type; + private final String name; + private final String description; + private final boolean required; + private final String defaultValue; + + private Param(Class type, String name, String description, boolean required, String defaultValue) { + this.type = Objects.requireNonNull(type, "type"); + this.name = requireNonBlank(name, "name"); + this.description = requireNonBlank(description, "description"); + this.defaultValue = defaultValue == null ? "" : defaultValue; + this.required = required; + + if (this.required && !this.defaultValue.isEmpty()) { + throw new IllegalArgumentException("required=true cannot be combined with a non-empty defaultValue"); + } + + validateDefaultValue(type, this.defaultValue); + } + + /** + * Creates a required parameter with no default value. + * + * @param + * the parameter type + * @param type + * the Java class of the parameter + * @param name + * the wire name sent to the model (must not be blank) + * @param description + * a human-readable description (must not be blank) + * @return a new {@code Param} instance + * @throws NullPointerException + * if {@code type} is null + * @throws IllegalArgumentException + * if {@code name} or {@code description} is blank + */ + public static Param of(Class type, String name, String description) { + return new Param<>(type, name, description, true, ""); + } + + /** + * Creates a parameter with explicit required/default settings. + * + * @param + * the parameter type + * @param type + * the Java class of the parameter + * @param name + * the wire name sent to the model (must not be blank) + * @param description + * a human-readable description (must not be blank) + * @param required + * whether the parameter is required + * @param defaultValue + * the default value as a string, or {@code null}/empty for none + * @return a new {@code Param} instance + * @throws NullPointerException + * if {@code type} is null + * @throws IllegalArgumentException + * if validation fails + */ + public static Param of(Class type, String name, String description, boolean required, + String defaultValue) { + return new Param<>(type, name, description, required, defaultValue); + } + + /** + * Returns a copy with a different name. + * + * @param name + * the new parameter name + * @return a new {@code Param} with the updated name + */ + public Param name(String name) { + return new Param<>(this.type, name, this.description, this.required, this.defaultValue); + } + + /** + * Returns a copy with a different description. + * + * @param description + * the new description + * @return a new {@code Param} with the updated description + */ + public Param description(String description) { + return new Param<>(this.type, this.name, description, this.required, this.defaultValue); + } + + /** + * Returns a copy with a different required flag. + * + * @param required + * whether the parameter is required + * @return a new {@code Param} with the updated required flag + */ + public Param required(boolean required) { + return new Param<>(this.type, this.name, this.description, required, this.defaultValue); + } + + /** + * Returns an optional copy with the given default value. Setting a default + * implicitly makes the parameter optional ({@code required=false}). + * + * @param defaultValue + * the default value as a string + * @return a new {@code Param} with the default applied and required set to + * false + */ + public Param defaultValue(String defaultValue) { + return new Param<>(this.type, this.name, this.description, false, defaultValue); + } + + /** Returns the Java type of this parameter. */ + public Class type() { + return type; + } + + /** Returns the wire name of this parameter. */ + public String name() { + return name; + } + + /** Returns the human-readable description. */ + public String description() { + return description; + } + + /** Returns whether this parameter is required. */ + public boolean required() { + return required; + } + + /** Returns the default value string, or empty if none. */ + public String defaultValue() { + return defaultValue; + } + + /** Returns {@code true} if a non-empty default value is set. */ + public boolean hasDefaultValue() { + return !defaultValue.isEmpty(); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Param other)) { + return false; + } + return required == other.required && Objects.equals(type, other.type) && Objects.equals(name, other.name) + && Objects.equals(description, other.description) && Objects.equals(defaultValue, other.defaultValue); + } + + @Override + public int hashCode() { + return Objects.hash(type, name, description, required, defaultValue); + } + + @Override + public String toString() { + return "Param[name=" + name + ", type=" + type.getSimpleName() + ", required=" + required + "]"; + } + + // ------------------------------------------------------------------ + // Internal validation helpers + // ------------------------------------------------------------------ + + private static String requireNonBlank(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must not be null or blank"); + } + return value; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void validateDefaultValue(Class type, String defaultValue) { + if (defaultValue == null || defaultValue.isEmpty()) { + return; + } + + try { + if (type == String.class) { + return; + } + if (type == Integer.class || type == int.class) { + Integer.parseInt(defaultValue); + return; + } + if (type == Long.class || type == long.class) { + Long.parseLong(defaultValue); + return; + } + if (type == Double.class || type == double.class) { + Double.parseDouble(defaultValue); + return; + } + if (type == Float.class || type == float.class) { + Float.parseFloat(defaultValue); + return; + } + if (type == Short.class || type == short.class) { + Short.parseShort(defaultValue); + return; + } + if (type == Byte.class || type == byte.class) { + Byte.parseByte(defaultValue); + return; + } + if (type == Boolean.class || type == boolean.class) { + if (!"true".equalsIgnoreCase(defaultValue) && !"false".equalsIgnoreCase(defaultValue)) { + throw new IllegalArgumentException("must be 'true' or 'false'"); + } + return; + } + if (type.isEnum()) { + Class enumType = (Class) type; + Enum.valueOf(enumType, defaultValue); + return; + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException( + "defaultValue '" + defaultValue + "' is not valid for type " + type.getSimpleName(), ex); + } + + throw new IllegalArgumentException( + "defaultValue is not supported for type " + type.getName() + " without a custom coercion policy"); + } +} diff --git a/java/src/main/java/com/github/copilot/tool/SchemaGenerator.java b/java/src/main/java/com/github/copilot/tool/SchemaGenerator.java new file mode 100644 index 0000000000..59336a1e02 --- /dev/null +++ b/java/src/main/java/com/github/copilot/tool/SchemaGenerator.java @@ -0,0 +1,392 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.RecordComponentElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.Elements; +import javax.lang.model.util.Types; + +import com.github.copilot.CopilotExperimental; + +/** + * Compile-time utility that maps {@code javax.lang.model} types to JSON Schema + * represented as Java source code literals ({@code Map.of(...)} expressions). + * + *

+ * This class is invoked by the annotation processor and operates exclusively + * with the {@code javax.lang.model} API. It does NOT use + * {@code java.lang.reflect}. + * + * @since 1.0.2 + */ +@CopilotExperimental +public class SchemaGenerator { + + /** + * Given a {@link TypeMirror} from the annotation processing environment, + * returns a {@code String} containing Java source code for a {@code Map} + * literal representing the JSON Schema of that type. + * + * @param type + * the type to generate schema for + * @param typeUtils + * the {@link Types} utility from the processing environment + * @param elementUtils + * the {@link Elements} utility from the processing environment + * @return a Java source code string representing the JSON Schema + */ + public String generateSchemaSource(TypeMirror type, Types typeUtils, Elements elementUtils) { + return generateSchema(type, typeUtils, elementUtils); + } + + /** + * Generates the full "parameters" schema source for a method's parameters. + * Produces a + * {@code Map.of("type", "object", "properties", Map.of(...), "required", List.of(...))}. + * + * @param parameters + * the method parameters to generate schema for + * @param typeUtils + * the {@link Types} utility from the processing environment + * @param elementUtils + * the {@link Elements} utility from the processing environment + * @return a Java source code string representing the parameters JSON Schema + */ + public String generateParametersSchemaSource(List parameters, Types typeUtils, + Elements elementUtils) { + if (parameters.isEmpty()) { + return "Map.of(\"type\", \"object\", \"properties\", Map.of(), \"required\", List.of())"; + } + + List propertyEntries = new ArrayList<>(); + List requiredNames = new ArrayList<>(); + + for (VariableElement param : parameters) { + String paramName = param.getSimpleName().toString(); + TypeMirror paramType = param.asType(); + + boolean isOptional = isOptionalType(paramType); + String schema; + if (isOptional) { + schema = generateSchema(unwrapOptional(paramType, typeUtils), typeUtils, elementUtils); + } else { + schema = generateSchema(paramType, typeUtils, elementUtils); + } + + propertyEntries.add("Map.entry(\"" + paramName + "\", " + schema + ")"); + + if (!isOptional) { + CopilotToolParam paramAnnotation = param.getAnnotation(CopilotToolParam.class); + if (paramAnnotation == null || paramAnnotation.required()) { + requiredNames.add("\"" + paramName + "\""); + } + } + } + + String properties = "Map.ofEntries(" + String.join(", ", propertyEntries) + ")"; + String required = "List.of(" + String.join(", ", requiredNames) + ")"; + + return "Map.of(\"type\", \"object\", \"properties\", " + properties + ", \"required\", " + required + ")"; + } + + private String generateSchema(TypeMirror type, Types typeUtils, Elements elementUtils) { + // Handle primitive types + if (type.getKind().isPrimitive()) { + return generatePrimitiveSchema(type.getKind()); + } + + // Handle array types + if (type.getKind() == TypeKind.ARRAY) { + ArrayType arrayType = (ArrayType) type; + TypeMirror componentType = arrayType.getComponentType(); + String itemsSchema = generateSchema(componentType, typeUtils, elementUtils); + return "Map.of(\"type\", \"array\", \"items\", " + itemsSchema + ")"; + } + + // Handle declared types (classes, interfaces, enums, records) + if (type.getKind() == TypeKind.DECLARED) { + return generateDeclaredTypeSchema((DeclaredType) type, typeUtils, elementUtils); + } + + // Fallback: any + return "Map.of()"; + } + + private String generatePrimitiveSchema(TypeKind kind) { + switch (kind) { + case INT : + case LONG : + case BYTE : + case SHORT : + return "Map.of(\"type\", \"integer\")"; + case DOUBLE : + case FLOAT : + return "Map.of(\"type\", \"number\")"; + case BOOLEAN : + return "Map.of(\"type\", \"boolean\")"; + case CHAR : + return "Map.of(\"type\", \"string\")"; + default : + return "Map.of()"; + } + } + + private String generateDeclaredTypeSchema(DeclaredType type, Types typeUtils, Elements elementUtils) { + TypeElement typeElement = (TypeElement) type.asElement(); + String qualifiedName = typeElement.getQualifiedName().toString(); + + // String + if ("java.lang.String".equals(qualifiedName)) { + return "Map.of(\"type\", \"string\")"; + } + + // Boxed primitives + if ("java.lang.Integer".equals(qualifiedName) || "java.lang.Long".equals(qualifiedName) + || "java.lang.Byte".equals(qualifiedName) || "java.lang.Short".equals(qualifiedName)) { + return "Map.of(\"type\", \"integer\")"; + } + if ("java.lang.Double".equals(qualifiedName) || "java.lang.Float".equals(qualifiedName)) { + return "Map.of(\"type\", \"number\")"; + } + if ("java.lang.Boolean".equals(qualifiedName)) { + return "Map.of(\"type\", \"boolean\")"; + } + if ("java.lang.Character".equals(qualifiedName)) { + return "Map.of(\"type\", \"string\")"; + } + + // UUID + if ("java.util.UUID".equals(qualifiedName)) { + return "Map.of(\"type\", \"string\", \"format\", \"uuid\")"; + } + + // Date-time types (ISO-8601 format hints for the model) + if ("java.time.OffsetDateTime".equals(qualifiedName) || "java.time.LocalDateTime".equals(qualifiedName) + || "java.time.Instant".equals(qualifiedName) || "java.time.ZonedDateTime".equals(qualifiedName)) { + return "Map.of(\"type\", \"string\", \"format\", \"date-time\")"; + } + if ("java.time.LocalDate".equals(qualifiedName)) { + return "Map.of(\"type\", \"string\", \"format\", \"date\")"; + } + if ("java.time.LocalTime".equals(qualifiedName)) { + return "Map.of(\"type\", \"string\", \"format\", \"time\")"; + } + + // JsonNode (any) + if ("com.fasterxml.jackson.databind.JsonNode".equals(qualifiedName)) { + return "Map.of()"; + } + + // Object (any) + if ("java.lang.Object".equals(qualifiedName)) { + return "Map.of()"; + } + + // Optional types + if ("java.util.Optional".equals(qualifiedName)) { + List typeArgs = type.getTypeArguments(); + if (!typeArgs.isEmpty()) { + return generateSchema(typeArgs.get(0), typeUtils, elementUtils); + } + return "Map.of()"; + } + if ("java.util.OptionalInt".equals(qualifiedName)) { + return "Map.of(\"type\", \"integer\")"; + } + if ("java.util.OptionalDouble".equals(qualifiedName)) { + return "Map.of(\"type\", \"number\")"; + } + if ("java.util.OptionalLong".equals(qualifiedName)) { + return "Map.of(\"type\", \"integer\")"; + } + + // List / Collection + if (isCollectionType(qualifiedName)) { + List typeArgs = type.getTypeArguments(); + if (!typeArgs.isEmpty()) { + String itemsSchema = generateSchema(typeArgs.get(0), typeUtils, elementUtils); + return "Map.of(\"type\", \"array\", \"items\", " + itemsSchema + ")"; + } + return "Map.of(\"type\", \"array\")"; + } + + // Map + if (isMapType(qualifiedName)) { + List typeArgs = type.getTypeArguments(); + if (typeArgs.size() == 2) { + TypeMirror valueType = typeArgs.get(1); + if (valueType.getKind() == TypeKind.DECLARED) { + TypeElement valueElement = (TypeElement) ((DeclaredType) valueType).asElement(); + String valueQName = valueElement.getQualifiedName().toString(); + if ("java.lang.Object".equals(valueQName)) { + return "Map.of(\"type\", \"object\")"; + } + } + String valueSchema = generateSchema(valueType, typeUtils, elementUtils); + return "Map.of(\"type\", \"object\", \"additionalProperties\", " + valueSchema + ")"; + } + return "Map.of(\"type\", \"object\")"; + } + + // Enum types + if (typeElement.getKind() == ElementKind.ENUM) { + List constants = typeElement.getEnclosedElements().stream() + .filter(e -> e.getKind() == ElementKind.ENUM_CONSTANT) + .map(e -> "\"" + e.getSimpleName().toString() + "\"").collect(Collectors.toList()); + return "Map.of(\"type\", \"string\", \"enum\", List.of(" + String.join(", ", constants) + "))"; + } + + // Record types + if (typeElement.getKind() == ElementKind.RECORD) { + return generateRecordSchema(typeElement, typeUtils, elementUtils); + } + + // POJO / class types — treat as object with fields + if (typeElement.getKind() == ElementKind.CLASS) { + return generateClassSchema(typeElement, typeUtils, elementUtils); + } + + // Sealed interfaces — oneOf via permitted subclasses + if (typeElement.getKind() == ElementKind.INTERFACE) { + return generateSealedSchema(typeElement, typeUtils, elementUtils); + } + + return "Map.of()"; + } + + private String generateRecordSchema(TypeElement typeElement, Types typeUtils, Elements elementUtils) { + List propertyEntries = new ArrayList<>(); + List requiredNames = new ArrayList<>(); + + for (Element enclosed : typeElement.getEnclosedElements()) { + if (enclosed.getKind() == ElementKind.RECORD_COMPONENT) { + RecordComponentElement component = (RecordComponentElement) enclosed; + String name = component.getSimpleName().toString(); + TypeMirror componentType = component.asType(); + + boolean isOptional = isOptionalType(componentType); + String schema; + if (isOptional) { + schema = generateSchema(unwrapOptional(componentType, typeUtils), typeUtils, elementUtils); + } else { + schema = generateSchema(componentType, typeUtils, elementUtils); + requiredNames.add("\"" + name + "\""); + } + + propertyEntries.add("Map.entry(\"" + name + "\", " + schema + ")"); + } + } + + String properties = "Map.ofEntries(" + String.join(", ", propertyEntries) + ")"; + String required = "List.of(" + String.join(", ", requiredNames) + ")"; + + return "Map.of(\"type\", \"object\", \"properties\", " + properties + ", \"required\", " + required + ")"; + } + + private String generateClassSchema(TypeElement typeElement, Types typeUtils, Elements elementUtils) { + List propertyEntries = new ArrayList<>(); + List requiredNames = new ArrayList<>(); + + for (Element enclosed : typeElement.getEnclosedElements()) { + if (enclosed.getKind() == ElementKind.FIELD) { + VariableElement field = (VariableElement) enclosed; + // Skip static fields + if (field.getModifiers().contains(javax.lang.model.element.Modifier.STATIC)) { + continue; + } + String name = field.getSimpleName().toString(); + TypeMirror fieldType = field.asType(); + + boolean isOptional = isOptionalType(fieldType); + String schema; + if (isOptional) { + schema = generateSchema(unwrapOptional(fieldType, typeUtils), typeUtils, elementUtils); + } else { + schema = generateSchema(fieldType, typeUtils, elementUtils); + requiredNames.add("\"" + name + "\""); + } + + propertyEntries.add("Map.entry(\"" + name + "\", " + schema + ")"); + } + } + + if (propertyEntries.isEmpty()) { + return "Map.of(\"type\", \"object\")"; + } + + String properties = "Map.ofEntries(" + String.join(", ", propertyEntries) + ")"; + String required = "List.of(" + String.join(", ", requiredNames) + ")"; + + return "Map.of(\"type\", \"object\", \"properties\", " + properties + ", \"required\", " + required + ")"; + } + + private String generateSealedSchema(TypeElement typeElement, Types typeUtils, Elements elementUtils) { + List permittedSubclasses = typeElement.getPermittedSubclasses(); + if (permittedSubclasses != null && !permittedSubclasses.isEmpty()) { + List schemas = permittedSubclasses.stream().map(sub -> generateSchema(sub, typeUtils, elementUtils)) + .collect(Collectors.toList()); + return "Map.of(\"oneOf\", List.of(" + String.join(", ", schemas) + "))"; + } + return "Map.of(\"type\", \"object\")"; + } + + private boolean isOptionalType(TypeMirror type) { + if (type.getKind() != TypeKind.DECLARED) { + return false; + } + DeclaredType declaredType = (DeclaredType) type; + TypeElement element = (TypeElement) declaredType.asElement(); + String name = element.getQualifiedName().toString(); + return "java.util.Optional".equals(name) || "java.util.OptionalInt".equals(name) + || "java.util.OptionalDouble".equals(name) || "java.util.OptionalLong".equals(name); + } + + private TypeMirror unwrapOptional(TypeMirror type, Types typeUtils) { + if (type.getKind() != TypeKind.DECLARED) { + return type; + } + DeclaredType declaredType = (DeclaredType) type; + TypeElement element = (TypeElement) declaredType.asElement(); + String name = element.getQualifiedName().toString(); + + if ("java.util.Optional".equals(name)) { + List typeArgs = declaredType.getTypeArguments(); + if (!typeArgs.isEmpty()) { + return typeArgs.get(0); + } + } + if ("java.util.OptionalInt".equals(name)) { + return typeUtils.getPrimitiveType(TypeKind.INT); + } + if ("java.util.OptionalDouble".equals(name)) { + return typeUtils.getPrimitiveType(TypeKind.DOUBLE); + } + if ("java.util.OptionalLong".equals(name)) { + return typeUtils.getPrimitiveType(TypeKind.LONG); + } + return type; + } + + private boolean isCollectionType(String qualifiedName) { + return "java.util.List".equals(qualifiedName) || "java.util.Collection".equals(qualifiedName) + || "java.util.Set".equals(qualifiedName); + } + + private boolean isMapType(String qualifiedName) { + return "java.util.Map".equals(qualifiedName); + } +} diff --git a/java/src/main/java/module-info.java b/java/src/main/java/module-info.java index 9f48b3747b..38bc1f93d5 100644 --- a/java/src/main/java/module-info.java +++ b/java/src/main/java/module-info.java @@ -19,11 +19,13 @@ exports com.github.copilot.generated; exports com.github.copilot.generated.rpc; exports com.github.copilot.rpc; + exports com.github.copilot.tool; opens com.github.copilot to com.fasterxml.jackson.databind; opens com.github.copilot.generated to com.fasterxml.jackson.databind; opens com.github.copilot.generated.rpc to com.fasterxml.jackson.databind; opens com.github.copilot.rpc to com.fasterxml.jackson.databind; - provides javax.annotation.processing.Processor with com.github.copilot.CopilotExperimentalProcessor; + provides javax.annotation.processing.Processor + with com.github.copilot.CopilotExperimentalProcessor, com.github.copilot.tool.CopilotToolProcessor; } diff --git a/java/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/java/src/main/resources/META-INF/services/javax.annotation.processing.Processor index 1e7feda8ca..3b2e17d2f9 100644 --- a/java/src/main/resources/META-INF/services/javax.annotation.processing.Processor +++ b/java/src/main/resources/META-INF/services/javax.annotation.processing.Processor @@ -1 +1,2 @@ com.github.copilot.CopilotExperimentalProcessor +com.github.copilot.tool.CopilotToolProcessor diff --git a/java/src/test/java/com/github/copilot/ClientOptionsE2ETest.java b/java/src/test/java/com/github/copilot/ClientOptionsE2ETest.java new file mode 100644 index 0000000000..45056afdb4 --- /dev/null +++ b/java/src/test/java/com/github/copilot/ClientOptionsE2ETest.java @@ -0,0 +1,302 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.generated.rpc.SessionLimitsConfig; +import com.github.copilot.rpc.CopilotClientOptions; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.ProviderConfig; +import com.github.copilot.rpc.ResumeSessionConfig; +import com.github.copilot.rpc.SessionConfig; + +class ClientOptionsE2ETest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void testShouldForwardAdvancedSessionCreationOptionsToTheCli() throws Exception { + try (var fake = FakeStdioCli.create()) { + var workDir = fake.path("create-work"); + var configDir = fake.path("create-config"); + + try (var client = fake.createClient()) { + var session = client.createSession(new SessionConfig().setSessionId("java-create-session") + .setClientName("java-e2e-client").setModel("gpt-5-mini").setReasoningEffort("low") + .setReasoningSummary("none").setContextTier("long_context") + .setAvailableTools(java.util.List.of("bash")).setExcludedTools(java.util.List.of("grep")) + .setExcludedBuiltInAgents(java.util.List.of("explore")).setEnableSessionTelemetry(true) + .setEnableCitations(true).setSessionLimits(new SessionLimitsConfig(42.0)) + .setWorkingDirectory(workDir.toString()).setStreaming(true) + .setIncludeSubAgentStreamingEvents(true).setConfigDirectory(configDir.toString()) + .setEnableConfigDiscovery(false).setSkipEmbeddingRetrieval(true) + .setOrganizationCustomInstructions("Use Java parity instructions.") + .setEnableOnDemandInstructionDiscovery(false).setEnableFileHooks(true) + .setEnableHostGitOperations(false).setEnableSessionStore(true).setEnableSkills(false) + .setEmbeddingCacheStorage("in-memory").setGitHubToken("java-session-token") + .setRemoteSession("export").setSkipCustomInstructions(true).setCustomAgentsLocalOnly(false) + .setCoauthorEnabled(true).setManageScheduleEnabled(true) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(30, TimeUnit.SECONDS); + session.close(); + } + + var create = fake.capturedRequest("session.create").path("params"); + assertEquals("java-create-session", create.path("sessionId").asText()); + assertEquals("java-e2e-client", create.path("clientName").asText()); + assertEquals("gpt-5-mini", create.path("model").asText()); + assertEquals("low", create.path("reasoningEffort").asText()); + assertEquals("none", create.path("reasoningSummary").asText()); + assertEquals("long_context", create.path("contextTier").asText()); + assertEquals("bash", create.path("availableTools").get(0).asText()); + assertEquals("grep", create.path("excludedTools").get(0).asText()); + assertEquals("explore", create.path("excludedBuiltinAgents").get(0).asText()); + assertTrue(create.path("enableSessionTelemetry").asBoolean()); + assertTrue(create.path("enableCitations").asBoolean()); + assertEquals(42.0, create.path("sessionLimits").path("maxAiCredits").asDouble()); + assertEquals(workDir.toString(), create.path("workingDirectory").asText()); + assertTrue(create.path("streaming").asBoolean()); + assertTrue(create.path("includeSubAgentStreamingEvents").asBoolean()); + assertEquals(configDir.toString(), create.path("configDir").asText()); + assertFalse(create.path("enableConfigDiscovery").asBoolean()); + assertTrue(create.path("skipEmbeddingRetrieval").asBoolean()); + assertEquals("Use Java parity instructions.", create.path("organizationCustomInstructions").asText()); + assertFalse(create.path("enableOnDemandInstructionDiscovery").asBoolean()); + assertTrue(create.path("enableFileHooks").asBoolean()); + assertFalse(create.path("enableHostGitOperations").asBoolean()); + assertTrue(create.path("enableSessionStore").asBoolean()); + assertFalse(create.path("enableSkills").asBoolean()); + assertEquals("in-memory", create.path("embeddingCacheStorage").asText()); + assertEquals("java-session-token", create.path("gitHubToken").asText()); + assertEquals("export", create.path("remoteSession").asText()); + assertEquals("direct", create.path("envValueMode").asText()); + assertTrue(create.path("requestPermission").asBoolean()); + + var update = fake.capturedRequest("session.options.update").path("params"); + assertEquals("java-create-session", update.path("sessionId").asText()); + assertTrue(update.path("skipCustomInstructions").asBoolean()); + assertFalse(update.path("customAgentsLocalOnly").asBoolean()); + assertTrue(update.path("coauthorEnabled").asBoolean()); + assertTrue(update.path("manageScheduleEnabled").asBoolean()); + } + } + + @Test + void testShouldForwardSingularProviderConfigurationOnSessionCreation() throws Exception { + try (var fake = FakeStdioCli.create()) { + try (var client = fake.createClient()) { + var session = client.createSession(new SessionConfig() + .setProvider(new ProviderConfig().setType("openai").setWireApi("responses") + .setTransport("websockets").setBaseUrl("https://models.example.test/v1") + .setApiKey("provider-key").setModelId("base-model").setWireModel("wire-model") + .setMaxPromptTokens(1000).setMaxOutputTokens(2000) + .setHeaders(Map.of("x-provider", "java"))) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(30, TimeUnit.SECONDS); + session.close(); + } + + var provider = fake.capturedRequest("session.create").path("params").path("provider"); + assertEquals("openai", provider.path("type").asText()); + assertEquals("responses", provider.path("wireApi").asText()); + assertEquals("websockets", provider.path("transport").asText()); + assertEquals("https://models.example.test/v1", provider.path("baseUrl").asText()); + assertEquals("provider-key", provider.path("apiKey").asText()); + assertEquals("base-model", provider.path("modelId").asText()); + assertEquals("wire-model", provider.path("wireModel").asText()); + assertEquals(1000, provider.path("maxPromptTokens").asInt()); + assertEquals(2000, provider.path("maxOutputTokens").asInt()); + assertEquals("java", provider.path("headers").path("x-provider").asText()); + } + } + + @Test + void testShouldForwardAdvancedSessionResumeOptionsToTheCli() throws Exception { + try (var fake = FakeStdioCli.create()) { + var workDir = fake.path("resume-work"); + var configDir = fake.path("resume-config"); + + try (var client = fake.createClient()) { + client.createSession(new SessionConfig().setSessionId("java-resume-session") + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(30, TimeUnit.SECONDS); + var session = client.resumeSession("java-resume-session", + new ResumeSessionConfig().setClientName("java-resume-client").setModel("gpt-5-mini") + .setReasoningEffort("medium").setReasoningSummary("none").setContextTier("long_context") + .setEnableCitations(true).setSessionLimits(new SessionLimitsConfig(84.0)) + .setWorkingDirectory(workDir.toString()).setConfigDirectory(configDir.toString()) + .setEnableConfigDiscovery(false).setSkipEmbeddingRetrieval(true) + .setOrganizationCustomInstructions("Use resumed Java instructions.") + .setEnableOnDemandInstructionDiscovery(false).setEnableFileHooks(true) + .setEnableHostGitOperations(false).setEnableSessionStore(true).setEnableSkills(false) + .setEmbeddingCacheStorage("in-memory").setGitHubToken("java-resume-token") + .setRemoteSession("export").setSkipCustomInstructions(false) + .setCustomAgentsLocalOnly(true).setCoauthorEnabled(false).setManageScheduleEnabled(true) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(30, TimeUnit.SECONDS); + session.close(); + } + + var resume = fake.capturedRequest("session.resume").path("params"); + assertEquals("java-resume-session", resume.path("sessionId").asText()); + assertEquals("java-resume-client", resume.path("clientName").asText()); + assertEquals("gpt-5-mini", resume.path("model").asText()); + assertEquals("medium", resume.path("reasoningEffort").asText()); + assertEquals("none", resume.path("reasoningSummary").asText()); + assertEquals("long_context", resume.path("contextTier").asText()); + assertTrue(resume.path("enableCitations").asBoolean()); + assertEquals(84.0, resume.path("sessionLimits").path("maxAiCredits").asDouble()); + assertEquals(workDir.toString(), resume.path("workingDirectory").asText()); + assertEquals(configDir.toString(), resume.path("configDir").asText()); + assertFalse(resume.path("enableConfigDiscovery").asBoolean()); + assertTrue(resume.path("skipEmbeddingRetrieval").asBoolean()); + assertEquals("Use resumed Java instructions.", resume.path("organizationCustomInstructions").asText()); + assertFalse(resume.path("enableOnDemandInstructionDiscovery").asBoolean()); + assertTrue(resume.path("enableFileHooks").asBoolean()); + assertFalse(resume.path("enableHostGitOperations").asBoolean()); + assertTrue(resume.path("enableSessionStore").asBoolean()); + assertFalse(resume.path("enableSkills").asBoolean()); + assertEquals("in-memory", resume.path("embeddingCacheStorage").asText()); + assertEquals("java-resume-token", resume.path("gitHubToken").asText()); + assertEquals("export", resume.path("remoteSession").asText()); + assertEquals("direct", resume.path("envValueMode").asText()); + assertTrue(resume.path("requestPermission").asBoolean()); + + var update = fake.capturedRequest("session.options.update").path("params"); + assertEquals("java-resume-session", update.path("sessionId").asText()); + assertFalse(update.path("skipCustomInstructions").asBoolean()); + assertTrue(update.path("customAgentsLocalOnly").asBoolean()); + assertFalse(update.path("coauthorEnabled").asBoolean()); + assertTrue(update.path("manageScheduleEnabled").asBoolean()); + } + } + + private record FakeStdioCli(Path dir, Path script, Path capture, Path workDir) implements AutoCloseable { + + static FakeStdioCli create() throws IOException { + var dir = Files.createTempDirectory("java-fake-copilot-cli-"); + var script = dir.resolve("fake-copilot-cli.js"); + var capture = dir.resolve("capture.json"); + var workDir = dir.resolve("work"); + Files.createDirectories(workDir); + Files.writeString(capture, "{\"requests\":[]}"); + Files.writeString(script, FAKE_STDIO_CLI_SCRIPT); + return new FakeStdioCli(dir, script, capture, workDir); + } + + CopilotClient createClient() { + var options = new CopilotClientOptions().setCliPath(script.toString()) + .setCliArgs(new String[]{"--capture-file", capture.toString()}).setCwd(workDir.toString()) + .setUseLoggedInUser(false); + return new CopilotClient(options); + } + + Path path(String name) throws IOException { + var path = workDir.resolve(name); + Files.createDirectories(path); + return path; + } + + JsonNode capturedRequest(String method) throws IOException { + for (JsonNode request : MAPPER.readTree(Files.readString(capture)).path("requests")) { + if (method.equals(request.path("method").asText())) { + return request; + } + } + fail("Expected captured request for " + method + " in " + Files.readString(capture)); + return null; + } + + @Override + public void close() throws IOException { + if (Files.exists(dir)) { + try (var paths = Files.walk(dir)) { + paths.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException ignored) { + } + }); + } + } + } + } + + private static final String FAKE_STDIO_CLI_SCRIPT = """ + const fs = require('fs'); + + const captureFileIndex = process.argv.indexOf('--capture-file'); + const captureFile = process.argv[captureFileIndex + 1]; + const capture = { requests: [] }; + fs.writeFileSync(captureFile, JSON.stringify(capture)); + + let buffer = Buffer.alloc(0); + + function persist() { + fs.writeFileSync(captureFile, JSON.stringify(capture)); + } + + function send(message) { + const body = Buffer.from(JSON.stringify(message), 'utf8'); + process.stdout.write(`Content-Length: ${body.length}\\r\\n\\r\\n`); + process.stdout.write(body); + } + + function resultFor(message) { + switch (message.method) { + case 'connect': + return { ok: true, protocolVersion: 3, version: 'fake' }; + case 'llmInference.setProvider': + return {}; + case 'session.create': + return { sessionId: message.params?.sessionId ?? 'fake-session', openCanvases: [] }; + case 'session.resume': + return { sessionId: message.params?.sessionId ?? 'fake-session', openCanvases: [] }; + case 'session.options.update': + return { success: true }; + default: + return {}; + } + } + + function handle(message) { + capture.requests.push({ method: message.method, params: message.params ?? null }); + persist(); + send({ jsonrpc: '2.0', id: message.id, result: resultFor(message) }); + } + + process.stdin.on('data', chunk => { + buffer = Buffer.concat([buffer, chunk]); + while (true) { + const headerEnd = buffer.indexOf('\\r\\n\\r\\n'); + if (headerEnd < 0) { + return; + } + const header = buffer.subarray(0, headerEnd).toString('utf8'); + const match = /Content-Length:\\s*(\\d+)/i.exec(header); + if (!match) { + throw new Error(`Missing Content-Length in ${header}`); + } + const length = Number(match[1]); + const bodyStart = headerEnd + 4; + if (buffer.length < bodyStart + length) { + return; + } + const body = buffer.subarray(bodyStart, bodyStart + length).toString('utf8'); + buffer = buffer.subarray(bodyStart + length); + handle(JSON.parse(body)); + } + }); + """; +} diff --git a/java/src/test/java/com/github/copilot/ConfigCloneTest.java b/java/src/test/java/com/github/copilot/ConfigCloneTest.java index 462997f050..6986ef7f0e 100644 --- a/java/src/test/java/com/github/copilot/ConfigCloneTest.java +++ b/java/src/test/java/com/github/copilot/ConfigCloneTest.java @@ -16,6 +16,7 @@ import org.junit.jupiter.api.Test; import com.github.copilot.generated.SessionEvent; +import com.github.copilot.generated.rpc.SessionLimitsConfig; import com.github.copilot.rpc.AutoModeSwitchResponse; import com.github.copilot.rpc.CopilotClientOptions; import com.github.copilot.rpc.DefaultAgentConfig; @@ -171,6 +172,21 @@ void sessionConfigAgentAndOnEventCloned() { assertSame(handler, cloned.getOnEvent()); } + @Test + void sessionConfigSessionPolicyOptionsCloned() { + var sessionLimits = new SessionLimitsConfig(30.0); + var excludedAgents = new ArrayList<>(List.of("explore")); + SessionConfig original = new SessionConfig().setExcludedBuiltInAgents(excludedAgents).setEnableCitations(true) + .setSessionLimits(sessionLimits); + + SessionConfig cloned = original.clone(); + excludedAgents.add("task"); + + assertEquals(List.of("explore"), cloned.getExcludedBuiltInAgents()); + assertTrue(cloned.getEnableCitations().orElse(false)); + assertSame(sessionLimits, cloned.getSessionLimits()); + } + @Test void resumeSessionConfigCloneBasic() { ResumeSessionConfig original = new ResumeSessionConfig(); @@ -208,6 +224,21 @@ void resumeSessionConfigAgentAndOnEventCloned() { assertSame(handler, cloned.getOnEvent()); } + @Test + void resumeSessionConfigSessionPolicyOptionsCloned() { + var sessionLimits = new SessionLimitsConfig(30.0); + var excludedAgents = new ArrayList<>(List.of("explore")); + ResumeSessionConfig original = new ResumeSessionConfig().setExcludedBuiltInAgents(excludedAgents) + .setEnableCitations(true).setSessionLimits(sessionLimits); + + ResumeSessionConfig cloned = original.clone(); + excludedAgents.add("task"); + + assertEquals(List.of("explore"), cloned.getExcludedBuiltInAgents()); + assertTrue(cloned.getEnableCitations().orElse(false)); + assertSame(sessionLimits, cloned.getSessionLimits()); + } + @Test void messageOptionsCloneBasic() { MessageOptions original = new MessageOptions(); diff --git a/java/src/test/java/com/github/copilot/CopilotRequestSessionIdE2ETest.java b/java/src/test/java/com/github/copilot/CopilotRequestSessionIdE2ETest.java index daf524945e..3025c64c39 100644 --- a/java/src/test/java/com/github/copilot/CopilotRequestSessionIdE2ETest.java +++ b/java/src/test/java/com/github/copilot/CopilotRequestSessionIdE2ETest.java @@ -10,6 +10,7 @@ import static com.github.copilot.CopilotRequestTestSupport.setupCapiAuth; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -68,6 +69,7 @@ void threadsSessionIdForCapiAndByok() throws Exception { assertFalse(capiInference.isEmpty(), "Expected at least one intercepted inference request"); for (InterceptedRequest r : capiInference) { assertEquals(capiSessionId, r.sessionId(), "CAPI inference request must carry the session id"); + assertAgentMetadata(r); } assertTrue(assistantText(capiResult).contains("OK from the synthetic"), "Expected synthetic content in CAPI assistant reply, got " + assistantText(capiResult)); @@ -91,10 +93,18 @@ void threadsSessionIdForCapiAndByok() throws Exception { assertTrue(byokInference.size() > before, "Expected at least one intercepted BYOK inference request"); for (InterceptedRequest r : byokInference.subList(before, byokInference.size())) { assertEquals(byokSessionId, r.sessionId(), "BYOK inference request must carry the session id"); + assertAgentMetadata(r); } assertNotEquals(capiSessionId, byokSessionId, "Expected per-session ids to differ between turns"); assertTrue(assistantText(byokResult).contains("OK from the synthetic"), "Expected synthetic content in BYOK assistant reply, got " + assistantText(byokResult)); } } + + private static void assertAgentMetadata(InterceptedRequest request) { + assertNotNull(request.agentId(), "Inference request must carry an agent id"); + assertFalse(request.agentId().isEmpty(), "Inference request must carry an agent id"); + assertNotNull(request.interactionType(), "Inference request must carry an interaction type"); + assertFalse(request.interactionType().isEmpty(), "Inference request must carry an interaction type"); + } } diff --git a/java/src/test/java/com/github/copilot/CopilotRequestTestSupport.java b/java/src/test/java/com/github/copilot/CopilotRequestTestSupport.java index 3b01734bd9..ecbf92068f 100644 --- a/java/src/test/java/com/github/copilot/CopilotRequestTestSupport.java +++ b/java/src/test/java/com/github/copilot/CopilotRequestTestSupport.java @@ -122,6 +122,58 @@ static String sseBody(String text, String respId) { return sb.toString(); } + /** + * Builds a complete Anthropic Messages SSE body (message_start … message_stop) + * for a streaming {@code /messages} response. The buffered JSON message is only + * valid for a non-streaming request; a streaming request expects named SSE + * events or the runtime fails to finalize the message. + */ + static String anthropicMessageSseBody(String text) { + Map startMessage = new LinkedHashMap<>(); + startMessage.put("id", "msg_stub_1"); + startMessage.put("type", "message"); + startMessage.put("role", "assistant"); + startMessage.put("model", "claude-sonnet-4.5"); + startMessage.put("content", List.of()); + startMessage.put("stop_reason", null); + startMessage.put("stop_sequence", null); + startMessage.put("usage", Map.of("input_tokens", 5, "output_tokens", 1)); + Map messageStart = new LinkedHashMap<>(); + messageStart.put("type", "message_start"); + messageStart.put("message", startMessage); + + Map contentBlockStart = new LinkedHashMap<>(); + contentBlockStart.put("type", "content_block_start"); + contentBlockStart.put("index", 0); + contentBlockStart.put("content_block", Map.of("type", "text", "text", "")); + + Map contentBlockDelta = new LinkedHashMap<>(); + contentBlockDelta.put("type", "content_block_delta"); + contentBlockDelta.put("index", 0); + contentBlockDelta.put("delta", Map.of("type", "text_delta", "text", text)); + + Map contentBlockStop = new LinkedHashMap<>(); + contentBlockStop.put("type", "content_block_stop"); + contentBlockStop.put("index", 0); + + Map messageDeltaDelta = new LinkedHashMap<>(); + messageDeltaDelta.put("stop_reason", "end_turn"); + messageDeltaDelta.put("stop_sequence", null); + Map messageDelta = new LinkedHashMap<>(); + messageDelta.put("type", "message_delta"); + messageDelta.put("delta", messageDeltaDelta); + messageDelta.put("usage", Map.of("output_tokens", 7)); + + StringBuilder sb = new StringBuilder(); + sb.append(sse("message_start", messageStart)); + sb.append(sse("content_block_start", contentBlockStart)); + sb.append(sse("content_block_delta", contentBlockDelta)); + sb.append(sse("content_block_stop", contentBlockStop)); + sb.append(sse("message_delta", messageDelta)); + sb.append(sse("message_stop", Map.of("type", "message_stop"))); + return sb.toString(); + } + // --- Synthetic response builders for the CopilotRequestHandler send override // --- @@ -190,6 +242,22 @@ static HttpResponse buildInferenceResponse(String url, String bodyT return sseResponse(sb.toString()); } + if (u.endsWith("/messages")) { + if (stream) { + return sseResponse(anthropicMessageSseBody(text)); + } + Map body = new LinkedHashMap<>(); + body.put("id", "msg_stub_1"); + body.put("type", "message"); + body.put("role", "assistant"); + body.put("model", "claude-sonnet-4.5"); + body.put("content", List.of(Map.of("type", "text", "text", text))); + body.put("stop_reason", "end_turn"); + body.put("stop_sequence", null); + body.put("usage", Map.of("input_tokens", 5, "output_tokens", 7)); + return jsonResponse(json(body)); + } + return jsonResponse(json(chatCompletion(text))); } @@ -405,7 +473,8 @@ static String assistantText(AssistantMessageEvent event) { } /** A single request the handler intercepted. */ - record InterceptedRequest(String url, String sessionId) { + record InterceptedRequest(String url, String sessionId, String agentId, String parentAgentId, + String interactionType, String body) { } /** @@ -440,9 +509,11 @@ List inferenceRequests() { protected HttpResponse sendRequest(HttpRequest request, CopilotRequestContext ctx) throws Exception { String url = request.uri().toString(); - records.add(new InterceptedRequest(url, ctx.sessionId())); + String body = requestBodyText(request); + records.add(new InterceptedRequest(url, ctx.sessionId(), ctx.agentId(), ctx.parentAgentId(), + ctx.interactionType(), body)); if (isInferenceUrl(url)) { - return buildInferenceResponse(url, requestBodyText(request), text); + return buildInferenceResponse(url, body, text); } return buildNonInferenceResponse(url); } diff --git a/java/src/test/java/com/github/copilot/CopilotSessionTest.java b/java/src/test/java/com/github/copilot/CopilotSessionTest.java index 44a7373ec7..eb061b029d 100644 --- a/java/src/test/java/com/github/copilot/CopilotSessionTest.java +++ b/java/src/test/java/com/github/copilot/CopilotSessionTest.java @@ -756,8 +756,27 @@ void testShouldGetLastSessionId() throws Exception { ctx.configureForTest("session", "should_get_last_session_id"); try (CopilotClient client = ctx.createClient()) { - CopilotSession session = client - .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); + CopilotSession session = null; + for (int attempt = 1; attempt <= 2; attempt++) { + CompletableFuture createFuture = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)); + try { + session = createFuture.get(45, TimeUnit.SECONDS); + break; + } catch (java.util.concurrent.TimeoutException e) { + createFuture.cancel(true); + if (attempt == 2) { + throw e; + } + } catch (java.util.concurrent.ExecutionException e) { + if (e.getCause() instanceof java.util.concurrent.TimeoutException && attempt < 2) { + createFuture.cancel(true); + continue; + } + throw e; + } + } + assertNotNull(session, "Session should be created"); session.sendAndWait(new MessageOptions().setPrompt("Say hello")).get(60, TimeUnit.SECONDS); String sessionId = session.getSessionId(); diff --git a/java/src/test/java/com/github/copilot/DataObjectCoverageTest.java b/java/src/test/java/com/github/copilot/DataObjectCoverageTest.java index ece824234b..f38a038368 100644 --- a/java/src/test/java/com/github/copilot/DataObjectCoverageTest.java +++ b/java/src/test/java/com/github/copilot/DataObjectCoverageTest.java @@ -186,7 +186,7 @@ void postToolUseHookInputSessionIdRoundTrip() { assertEquals("session-xyz", input.getSessionId()); } - // ===== CustomAgentConfig model field ===== + // ===== CustomAgentConfig model fields ===== @Test void customAgentConfigModelGetterAndSetter() { @@ -227,6 +227,36 @@ void customAgentConfigModelOmittedWhenNull() throws Exception { assertFalse(json.contains("\"model\"")); } + @Test + void customAgentConfigReasoningEffortGetterAndFluentSetter() { + var cfg = new CustomAgentConfig(); + assertNull(cfg.getReasoningEffort()); + + var result = cfg.setReasoningEffort("high"); + assertSame(cfg, result); + assertEquals("high", cfg.getReasoningEffort()); + } + + @Test + void customAgentConfigReasoningEffortSerializationRoundTrip() throws Exception { + var mapper = JsonRpcClient.getObjectMapper(); + var cfg = new CustomAgentConfig().setName("reasoning-agent").setReasoningEffort("high"); + + var json = mapper.writeValueAsString(cfg); + assertTrue(json.contains("\"reasoningEffort\":\"high\"")); + + var deserialized = mapper.readValue(json, CustomAgentConfig.class); + assertEquals("high", deserialized.getReasoningEffort()); + } + + @Test + void customAgentConfigReasoningEffortOmittedWhenNull() throws Exception { + var mapper = JsonRpcClient.getObjectMapper(); + var json = mapper.writeValueAsString(new CustomAgentConfig().setName("default-agent")); + + assertFalse(json.contains("\"reasoningEffort\"")); + } + // ===== PermissionRequestResult setRules ===== @Test diff --git a/java/src/test/java/com/github/copilot/E2ETestContext.java b/java/src/test/java/com/github/copilot/E2ETestContext.java index 4089e10ff7..f524b33dab 100644 --- a/java/src/test/java/com/github/copilot/E2ETestContext.java +++ b/java/src/test/java/com/github/copilot/E2ETestContext.java @@ -288,6 +288,8 @@ public Map getEnvironment() { env.put("GH_CONFIG_DIR", homeDir.toString()); env.put("XDG_CONFIG_HOME", homeDir.toString()); env.put("XDG_STATE_HOME", homeDir.toString()); + env.put("COPILOT_MCP_APPS", "true"); + env.put("MCP_APPS", "true"); // Configure CONNECT proxy for HTTPS interception if available String connectUrl = proxy.getConnectProxyUrl(); @@ -379,6 +381,24 @@ public void setCopilotUserByToken(String token, String login, String copilotPlan proxy.setCopilotUserByToken(token, login, copilotPlan, apiUrl, telemetryUrl, analyticsTrackingId); } + /** + * Configures the proxy to return a raw Copilot user response for a given token. + * + * @param token + * the GitHub token + * @param response + * the raw response object to return for the token + * @throws IOException + * if the request fails + * @throws InterruptedException + * if the request is interrupted + */ + public void setCopilotUserByToken(String token, Map response) + throws IOException, InterruptedException { + ensureProxyAlive(); + proxy.setCopilotUserByToken(token, response); + } + /** * Initializes the proxy state without loading a snapshot. *

@@ -438,7 +458,6 @@ private static Path findRepoRoot() throws IOException { } private static String getCliPath(Path repoRoot) throws IOException { - // Try environment variable first (explicit override) String envPath = System.getenv("COPILOT_CLI_PATH"); if (envPath != null && !envPath.isEmpty()) { return envPath; diff --git a/java/src/test/java/com/github/copilot/ForwardCompatibilityTest.java b/java/src/test/java/com/github/copilot/ForwardCompatibilityTest.java index 40166307e3..9163ae1357 100644 --- a/java/src/test/java/com/github/copilot/ForwardCompatibilityTest.java +++ b/java/src/test/java/com/github/copilot/ForwardCompatibilityTest.java @@ -56,6 +56,22 @@ void parse_unknownEventType_returnsUnknownSessionEvent() throws Exception { assertEquals("future.feature_from_server", result.getType()); } + @Test + void parse_internalEventType_returnsUnknownSessionEvent() throws Exception { + String json = """ + { + "id": "12345678-1234-1234-1234-123456789abc", + "timestamp": "2026-06-15T10:30:00Z", + "type": "session.memory_changed", + "data": {} + } + """; + SessionEvent result = MAPPER.readValue(json, SessionEvent.class); + + assertInstanceOf(UnknownSessionEvent.class, result); + assertEquals("session.memory_changed", result.getType()); + } + @Test void parse_unknownEventType_preservesOriginalType() throws Exception { String json = """ diff --git a/java/src/test/java/com/github/copilot/GitHubTelemetryForwardingIT.java b/java/src/test/java/com/github/copilot/GitHubTelemetryForwardingIT.java new file mode 100644 index 0000000000..d41c5f97dc --- /dev/null +++ b/java/src/test/java/com/github/copilot/GitHubTelemetryForwardingIT.java @@ -0,0 +1,59 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +import com.github.copilot.generated.rpc.GitHubTelemetryNotification; +import com.github.copilot.rpc.CopilotClientOptions; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.SessionConfig; + +/** + * Failsafe integration test that verifies the live CLI forwards GitHub + * telemetry notifications during session creation. + */ +@AllowCopilotExperimental +class GitHubTelemetryForwardingIT { + + @Test + void forwardsGitHubTelemetryForALiveSession() throws Exception { + var notifications = new CopyOnWriteArrayList(); + var firstNotification = new CompletableFuture(); + + try (E2ETestContext ctx = E2ETestContext.create()) { + var options = new CopilotClientOptions().setOnGitHubTelemetry(notification -> { + notifications.add(notification); + firstNotification.complete(notification); + return CompletableFuture.completedFuture(null); + }); + + try (CopilotClient client = ctx.createClient(options); + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(30, TimeUnit.SECONDS)) { + + GitHubTelemetryNotification notification = firstNotification.get(30, TimeUnit.SECONDS); + + assertFalse(notifications.isEmpty(), "Expected at least one GitHub telemetry notification"); + assertNotNull(notification, "Expected a GitHub telemetry notification"); + assertNotNull(notification.sessionId(), "Telemetry notification sessionId must be present"); + assertTrue(!notification.sessionId().isBlank(), "Telemetry notification sessionId must be non-empty"); + assertNotNull(notification.restricted(), "Telemetry notification restricted flag must be present"); + assertNotNull(notification.event(), "Telemetry notification event must be present"); + assertNotNull(notification.event().kind(), "Telemetry event kind must be present"); + assertTrue(!notification.event().kind().isBlank(), "Telemetry event kind must be non-empty"); + } + } + } +} diff --git a/java/src/test/java/com/github/copilot/GitHubTelemetryTest.java b/java/src/test/java/com/github/copilot/GitHubTelemetryTest.java new file mode 100644 index 0000000000..8e35bd9a92 --- /dev/null +++ b/java/src/test/java/com/github/copilot/GitHubTelemetryTest.java @@ -0,0 +1,308 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.github.copilot.generated.rpc.GitHubTelemetryNotification; +import com.github.copilot.rpc.CopilotClientOptions; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.ResumeSessionConfig; +import com.github.copilot.rpc.SessionConfig; + +/** + * Exercises the hand-written GitHub telemetry forwarding surface: the + * {@code gitHubTelemetry.event} notification adapter, the + * {@code enableGitHubTelemetryForwarding} capability flag on the connect + * handshake and the create/resume requests, and the {@code onGitHubTelemetry} + * client option. + */ +@AllowCopilotExperimental +class GitHubTelemetryTest { + + private record SocketPair(JsonRpcClient client, Socket serverSide, + ServerSocket serverSocket) implements AutoCloseable { + + @Override + public void close() throws Exception { + client.close(); + serverSide.close(); + serverSocket.close(); + } + } + + private SocketPair createSocketPair() throws Exception { + var serverSocket = new ServerSocket(0); + var clientSocket = new Socket("localhost", serverSocket.getLocalPort()); + var serverSide = serverSocket.accept(); + var client = JsonRpcClient.fromSocket(clientSocket); + return new SocketPair(client, serverSide, serverSocket); + } + + private void writeRpcMessage(OutputStream out, String json) throws IOException { + byte[] content = json.getBytes(StandardCharsets.UTF_8); + String header = "Content-Length: " + content.length + "\r\n\r\n"; + out.write(header.getBytes(StandardCharsets.UTF_8)); + out.write(content); + out.flush(); + } + + @Test + void adapterDispatchesNotificationToHandlerWithTypedPayload() throws Exception { + try (var pair = createSocketPair()) { + var received = new CompletableFuture(); + Function> handler = notification -> { + received.complete(notification); + return CompletableFuture.completedFuture(null); + }; + new GitHubTelemetryAdapter(handler).registerHandlers(pair.client()); + + String notification = """ + { + "jsonrpc": "2.0", + "method": "gitHubTelemetry.event", + "params": { + "sessionId": "sess-123", + "restricted": true, + "event": { + "kind": "tool_call_executed", + "created_at": "2024-01-01T00:00:00Z", + "model_call_id": "call-9", + "properties": { "tool": "shell" }, + "metrics": { "duration_ms": 42.5 }, + "exp_assignment_context": "ctx", + "features": { "flag_a": "on" }, + "session_id": "sess-123", + "copilot_tracking_id": "track-1", + "client": { + "cli_version": "1.2.3", + "os_platform": "win32", + "os_version": "10", + "os_arch": "x64", + "node_version": "20.0.0", + "is_staff": false + } + } + } + } + """; + writeRpcMessage(pair.serverSide().getOutputStream(), notification); + + GitHubTelemetryNotification result = received.get(5, TimeUnit.SECONDS); + assertEquals("sess-123", result.sessionId()); + assertTrue(result.restricted()); + + var event = result.event(); + assertNotNull(event); + assertEquals("tool_call_executed", event.kind()); + assertEquals("2024-01-01T00:00:00Z", event.createdAt()); + assertEquals("call-9", event.modelCallId()); + assertEquals("shell", event.properties().get("tool")); + assertEquals(42.5, event.metrics().get("duration_ms")); + assertEquals("ctx", event.expAssignmentContext()); + assertEquals("on", event.features().get("flag_a")); + assertEquals("sess-123", event.sessionId()); + assertEquals("track-1", event.copilotTrackingId()); + + var client = event.client(); + assertNotNull(client); + assertEquals("1.2.3", client.cliVersion()); + assertEquals("win32", client.osPlatform()); + assertEquals("x64", client.osArch()); + assertEquals("20.0.0", client.nodeVersion()); + assertEquals(Boolean.FALSE, client.isStaff()); + } + } + + @Test + void clientOptsSessionsIntoForwardingAndReceivesEvents() throws Exception { + var received = new CompletableFuture(); + Function> handler = notification -> { + received.complete(notification); + return CompletableFuture.completedFuture(null); + }; + + try (var server = new FakeRuntimeServer(); + var client = new CopilotClient( + new CopilotClientOptions().setCliUrl(server.url()).setOnGitHubTelemetry(handler))) { + + client.start().get(15, TimeUnit.SECONDS); + + // Connecting must opt into telemetry forwarding at the connection level so + // the runtime can forward the first session's un-replayable start event. + JsonNode connectParams = server.awaitConnect(); + assertTrue(connectParams.path("enableGitHubTelemetryForwarding").asBoolean(), + "connect request should carry enableGitHubTelemetryForwarding=true"); + + // Creating a session must opt it into telemetry forwarding. + client.createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(15, + TimeUnit.SECONDS); + JsonNode createParams = server.awaitCreate(); + assertTrue(createParams.path("enableGitHubTelemetryForwarding").asBoolean(), + "create request should carry enableGitHubTelemetryForwarding=true"); + + // The adapter registered on connect should forward server-pushed events. + server.sendTelemetry(Map.of("sessionId", "sess-xyz", "restricted", false, "event", + Map.of("kind", "session_started", "session_id", "sess-xyz"))); + GitHubTelemetryNotification event = received.get(5, TimeUnit.SECONDS); + assertEquals("sess-xyz", event.sessionId()); + assertFalse(event.restricted()); + assertEquals("session_started", event.event().kind()); + + // Resuming a session must opt it in as well. + client.resumeSession("resume-1", + new ResumeSessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(15, TimeUnit.SECONDS); + JsonNode resumeParams = server.awaitResume(); + assertTrue(resumeParams.path("enableGitHubTelemetryForwarding").asBoolean(), + "resume request should carry enableGitHubTelemetryForwarding=true"); + } + } + + @Test + void clientOmitsForwardingWhenNoHandler() throws Exception { + try (var server = new FakeRuntimeServer(); + var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url()))) { + + client.start().get(15, TimeUnit.SECONDS); + + JsonNode connectParams = server.awaitConnect(); + assertFalse(connectParams.has("enableGitHubTelemetryForwarding"), + "connect request should omit the flag when no handler is registered"); + + client.createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(15, + TimeUnit.SECONDS); + JsonNode createParams = server.awaitCreate(); + assertFalse(createParams.has("enableGitHubTelemetryForwarding"), + "create request should omit the flag when no handler is registered"); + + client.resumeSession("resume-1", + new ResumeSessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(15, TimeUnit.SECONDS); + JsonNode resumeParams = server.awaitResume(); + assertFalse(resumeParams.has("enableGitHubTelemetryForwarding"), + "resume request should omit the flag when no handler is registered"); + } + } + + @Test + void optionsRetainAndCloneTelemetryHandler() { + Function> handler = n -> CompletableFuture + .completedFuture(null); + var options = new CopilotClientOptions().setOnGitHubTelemetry(handler); + assertSame(handler, options.getOnGitHubTelemetry()); + + var copy = options.clone(); + assertSame(handler, copy.getOnGitHubTelemetry()); + } + + /** + * A minimal in-process JSON-RPC runtime that answers the connect/create/resume + * handshake so a real {@link CopilotClient} can be driven over a socket, and + * can push {@code gitHubTelemetry.event} notifications back to the client. + */ + private static final class FakeRuntimeServer implements AutoCloseable { + + private final ServerSocket serverSocket; + private final Thread acceptThread; + private final CompletableFuture ready = new CompletableFuture<>(); + private final CompletableFuture connectParams = new CompletableFuture<>(); + private final CompletableFuture createParams = new CompletableFuture<>(); + private final CompletableFuture resumeParams = new CompletableFuture<>(); + + FakeRuntimeServer() throws IOException { + serverSocket = new ServerSocket(0); + acceptThread = new Thread(this::acceptLoop, "fake-runtime-accept"); + acceptThread.setDaemon(true); + acceptThread.start(); + } + + String url() { + return "127.0.0.1:" + serverSocket.getLocalPort(); + } + + JsonNode awaitConnect() throws Exception { + return connectParams.get(15, TimeUnit.SECONDS); + } + + JsonNode awaitCreate() throws Exception { + return createParams.get(15, TimeUnit.SECONDS); + } + + JsonNode awaitResume() throws Exception { + return resumeParams.get(15, TimeUnit.SECONDS); + } + + void sendTelemetry(Object params) throws Exception { + ready.get(15, TimeUnit.SECONDS).notify("gitHubTelemetry.event", params); + } + + private void acceptLoop() { + try { + Socket socket = serverSocket.accept(); + JsonRpcClient server = JsonRpcClient.fromSocket(socket); + server.registerMethodHandler("connect", (id, params) -> { + connectParams.complete(params); + respond(server, id, Map.of("protocolVersion", 2)); + }); + server.registerMethodHandler("session.create", (id, params) -> { + createParams.complete(params); + respond(server, id, Map.of("sessionId", params.path("sessionId").asText("created"), "workspacePath", + "/workspace")); + }); + server.registerMethodHandler("session.resume", (id, params) -> { + resumeParams.complete(params); + respond(server, id, Map.of("sessionId", params.path("sessionId").asText("resume-1"), + "workspacePath", "/workspace")); + }); + server.registerMethodHandler("session.destroy", (id, params) -> respond(server, id, Map.of())); + server.registerMethodHandler("runtime.shutdown", (id, params) -> respond(server, id, Map.of())); + ready.complete(server); + } catch (IOException e) { + ready.completeExceptionally(e); + connectParams.completeExceptionally(e); + createParams.completeExceptionally(e); + resumeParams.completeExceptionally(e); + } + } + + private static void respond(JsonRpcClient server, String id, Object result) { + if (id == null) { + return; + } + try { + server.sendResponse(id, result); + } catch (IOException e) { + // Connection torn down (e.g. client closing); ignore. + } + } + + @Override + public void close() throws Exception { + JsonRpcClient server = ready.getNow(null); + if (server != null) { + server.close(); + } + serverSocket.close(); + } + } +} diff --git a/java/src/test/java/com/github/copilot/HooksTest.java b/java/src/test/java/com/github/copilot/HooksTest.java index 4608848f19..329883581e 100644 --- a/java/src/test/java/com/github/copilot/HooksTest.java +++ b/java/src/test/java/com/github/copilot/HooksTest.java @@ -221,6 +221,8 @@ void testDenyToolExecutionWhenPreToolUseReturnsDeny() throws Exception { // The response should be defined assertNotNull(response, "Response should not be null"); + + assertEquals(originalContent, Files.readString(testFile), "Denied preToolUse hook should block file edits"); } } } diff --git a/java/src/test/java/com/github/copilot/McpAuthInterestRegistrationTest.java b/java/src/test/java/com/github/copilot/McpAuthInterestRegistrationTest.java new file mode 100644 index 0000000000..06ac08a2a4 --- /dev/null +++ b/java/src/test/java/com/github/copilot/McpAuthInterestRegistrationTest.java @@ -0,0 +1,299 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.copilot.generated.McpOauthRequiredEvent; +import com.github.copilot.rpc.CloudSessionOptions; +import com.github.copilot.rpc.CloudSessionRepository; +import com.github.copilot.rpc.CopilotClientOptions; +import com.github.copilot.rpc.McpAuthResult; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.ResumeSessionConfig; +import com.github.copilot.rpc.SessionConfig; + +class McpAuthInterestRegistrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void mcpOauthRequiredEventExposesOptionalResourceMetadata() throws Exception { + var data = MAPPER.readValue(""" + { + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp", + "wwwAuthenticateParams": { + "resourceMetadataUrl": "https://example.com/.well-known/oauth-protected-resource" + }, + "resourceMetadata": "{\\"resource\\":\\"https://example.com/mcp\\"}", + "staticClientConfig": { + "clientId": "static-client", + "clientSecret": "static-secret", + "grantType": "client_credentials", + "publicClient": false + } + } + """, McpOauthRequiredEvent.McpOauthRequiredEventData.class); + + assertEquals("{\"resource\":\"https://example.com/mcp\"}", data.resourceMetadata()); + assertNotNull(data.wwwAuthenticateParams()); + assertNotNull(data.staticClientConfig()); + assertEquals("static-secret", data.staticClientConfig().clientSecret()); + + var withoutMetadata = MAPPER.readValue(""" + { + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp" + } + """, McpOauthRequiredEvent.McpOauthRequiredEventData.class); + + assertNull(withoutMetadata.resourceMetadata()); + assertNull(withoutMetadata.wwwAuthenticateParams()); + } + + @Test + void createSessionRegistersMcpAuthInterestOnlyWhenHandlerConfigured() throws Exception { + try (var server = new RecordingRuntime(); + var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url()))) { + try (var session = client.createSession( + new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setOnEvent(event -> { + })).get()) { + assertNotNull(session); + } + + assertNoMcpAuthInterest(server.requests()); + assertTrue(server.requests().stream().anyMatch(request -> "session.create".equals(request.method()) + && request.params().path("requestPermission").asBoolean())); + + server.clearRequests(); + + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> { + assertNotNull(request); + assertNotNull(invocation); + return java.util.concurrent.CompletableFuture + .completedFuture(McpAuthResult.cancelled()); + })) + .get()) { + assertNotNull(session); + } + + List requests = server.requests(); + assertEquals("session.create", requests.get(0).method()); + assertEquals("session.eventLog.registerInterest", requests.get(1).method()); + assertEquals("mcp.oauth_required", requests.get(1).params().path("eventType").asText()); + } + } + + @Test + void cloudCreateSessionRegistersMcpAuthInterestAfterCreateOnlyWhenHandlerConfigured() throws Exception { + try (var server = new RecordingRuntime(); + var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url()))) { + var cloud = new CloudSessionOptions().setRepository( + new CloudSessionRepository().setOwner("github").setName("copilot-sdk").setBranch("main")); + + try (var session = client + .createSession( + new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setCloud(cloud)) + .get()) { + assertNotNull(session); + } + + assertNoMcpAuthInterest(server.requests()); + server.clearRequests(); + + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setCloud(cloud).setOnMcpAuthRequest((request, invocation) -> { + assertNotNull(request); + assertNotNull(invocation); + return java.util.concurrent.CompletableFuture + .completedFuture(McpAuthResult.cancelled()); + })) + .get()) { + assertNotNull(session); + } + + List requests = server.requests(); + assertEquals("session.create", requests.get(0).method()); + assertEquals("session.eventLog.registerInterest", requests.get(1).method()); + assertEquals("mcp.oauth_required", requests.get(1).params().path("eventType").asText()); + } + } + + @Test + void resumeSessionRegistersMcpAuthInterestOnlyWhenHandlerConfigured() throws Exception { + try (var server = new RecordingRuntime(); + var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url()))) { + try (var session = client.resumeSession("session-without-auth", new ResumeSessionConfig() + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setOnEvent(event -> { + })).get()) { + assertNotNull(session); + } + + assertNoMcpAuthInterest(server.requests()); + assertTrue(server.requests().stream().anyMatch(request -> "session.resume".equals(request.method()) + && request.params().path("requestPermission").asBoolean())); + + server.clearRequests(); + + try (var session = client.resumeSession("session-with-auth", + new ResumeSessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> { + assertNotNull(request); + assertNotNull(invocation); + return java.util.concurrent.CompletableFuture + .completedFuture(McpAuthResult.cancelled()); + })) + .get()) { + assertNotNull(session); + } + + List requests = server.requests(); + assertEquals("session.resume", requests.get(0).method()); + assertEquals("session.eventLog.registerInterest", requests.get(1).method()); + assertEquals("mcp.oauth_required", requests.get(1).params().path("eventType").asText()); + } + } + + private static void assertNoMcpAuthInterest(List requests) { + assertFalse(requests.stream().anyMatch(request -> "session.eventLog.registerInterest".equals(request.method()) + && "mcp.oauth_required".equals(request.params().path("eventType").asText()))); + } + + private record RpcRequest(String method, JsonNode params) { + } + + private static final class RecordingRuntime implements AutoCloseable { + private final ServerSocket listener; + private final Thread thread; + private final List requests = new CopyOnWriteArrayList<>(); + private volatile boolean running = true; + + RecordingRuntime() throws Exception { + listener = new ServerSocket(0); + thread = new Thread(this::run, "mcp-auth-interest-test-runtime"); + thread.setDaemon(true); + thread.start(); + } + + String url() { + return "127.0.0.1:" + listener.getLocalPort(); + } + + List requests() { + return List.copyOf(requests); + } + + void clearRequests() { + requests.clear(); + } + + @Override + public void close() throws Exception { + running = false; + listener.close(); + thread.join(2000); + } + + private void run() { + try (Socket socket = listener.accept()) { + var in = socket.getInputStream(); + var out = socket.getOutputStream(); + while (running) { + JsonNode message = readMessage(in); + if (message == null) { + return; + } + String method = message.path("method").asText(); + requests.add(new RpcRequest(method, message.path("params").deepCopy())); + sendResponse(out, message.path("id").asLong(), resultFor(method, message.path("params"))); + } + } catch (Exception ex) { + if (running) { + throw new RuntimeException(ex); + } + } + } + + private static JsonNode resultFor(String method, JsonNode params) { + ObjectNode result = MAPPER.createObjectNode(); + switch (method) { + case "connect" -> { + result.put("ok", true); + result.put("protocolVersion", 3); + result.put("version", "test"); + } + case "session.create", "session.resume" -> { + String sessionId = params.path("sessionId").asText("server-assigned-session"); + if (sessionId.isEmpty()) { + sessionId = "server-assigned-session"; + } + result.put("sessionId", sessionId); + result.putNull("workspacePath"); + result.putNull("capabilities"); + } + case "session.eventLog.registerInterest" -> result.put("id", "interest-1"); + case "session.options.update" -> result.put("success", true); + case "session.skills.reload", "session.destroy" -> { + } + default -> throw new IllegalStateException("Unexpected RPC method " + method); + } + return result; + } + + private static JsonNode readMessage(java.io.InputStream in) throws Exception { + StringBuilder header = new StringBuilder(); + int b; + while ((b = in.read()) != -1) { + header.append((char) b); + if (header.toString().endsWith("\r\n\r\n")) { + break; + } + } + if (b == -1) { + return null; + } + int contentLength = 0; + for (String line : header.toString().split("\r\n")) { + int colon = line.indexOf(':'); + if (colon > 0 && "Content-Length".equals(line.substring(0, colon))) { + contentLength = Integer.parseInt(line.substring(colon + 1).trim()); + } + } + byte[] body = in.readNBytes(contentLength); + return MAPPER.readTree(body); + } + + private static void sendResponse(OutputStream out, long id, JsonNode result) throws Exception { + ObjectNode response = MAPPER.createObjectNode(); + response.put("jsonrpc", "2.0"); + response.put("id", id); + response.set("result", result); + byte[] body = MAPPER.writeValueAsBytes(response); + out.write(("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.UTF_8)); + out.write(body); + out.flush(); + } + } +} diff --git a/java/src/test/java/com/github/copilot/McpOAuthE2ETest.java b/java/src/test/java/com/github/copilot/McpOAuthE2ETest.java new file mode 100644 index 0000000000..f234337eaf --- /dev/null +++ b/java/src/test/java/com/github/copilot/McpOAuthE2ETest.java @@ -0,0 +1,380 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.generated.McpOauthRequestReason; +import com.github.copilot.generated.rpc.SessionMcpAppsCallToolParams; +import com.github.copilot.generated.rpc.McpServerStatus; +import com.github.copilot.generated.rpc.SessionMcpListToolsParams; +import com.github.copilot.generated.rpc.SessionMcpOauthHandlePendingRequestParams; +import com.github.copilot.rpc.McpAuthInvocation; +import com.github.copilot.rpc.McpAuthRequest; +import com.github.copilot.rpc.McpAuthResult; +import com.github.copilot.rpc.McpAuthToken; +import com.github.copilot.rpc.McpHttpServerConfig; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.SessionConfig; + +public class McpOAuthE2ETest { + private static final String EXPECTED_TOKEN = "sdk-host-token"; + private static final String REFRESH_TOKEN = EXPECTED_TOKEN + "-refresh"; + private static final String UPSCOPE_TOKEN = EXPECTED_TOKEN + "-upscope"; + private static final String REAUTH_TOKEN = EXPECTED_TOKEN + "-reauth"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static E2ETestContext ctx; + + @BeforeAll + static void setup() throws Exception { + ctx = E2ETestContext.create(); + } + + @AfterAll + static void teardown() throws Exception { + if (ctx != null) { + ctx.close(); + } + } + + @Test + void testShouldSatisfyMcpOauthUsingHostProvidedToken() throws Exception { + try (var oauthServer = OAuthMcpServer.start(ctx.getRepoRoot())) { + var serverName = "oauth-protected-mcp"; + var observedRequest = new java.util.concurrent.atomic.AtomicReference(); + var observedInvocation = new java.util.concurrent.atomic.AtomicReference(); + + try (var client = ctx.createClient(); + var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> { + observedRequest.set(request); + observedInvocation.set(invocation); + return java.util.concurrent.CompletableFuture.completedFuture( + McpAuthResult.token(new McpAuthToken(EXPECTED_TOKEN, "Bearer", 3600L))); + }).setMcpServers(Map.of(serverName, new McpHttpServerConfig() + .setUrl(oauthServer.url() + "/mcp").setTools(List.of("*"))))) + .get()) { + waitForMcpServerStatus(session, serverName, McpServerStatus.CONNECTED, observedRequest); + assertNotNull(observedInvocation.get(), "MCP auth invocation should be provided"); + assertEquals(session.getSessionId(), observedInvocation.get().getSessionId()); + var tools = session.getRpc().mcp.listTools(new SessionMcpListToolsParams(null, serverName)).get(30, + TimeUnit.SECONDS); + assertTrue(tools.tools().stream().anyMatch(tool -> "whoami".equals(tool.name()))); + } + + var request = observedRequest.get(); + assertNotNull(request, "MCP auth handler should be invoked"); + assertEquals(serverName, request.serverName()); + assertEquals(oauthServer.url() + "/mcp", request.serverUrl()); + assertEquals(McpOauthRequestReason.INITIAL, request.reason()); + assertNotNull(request.wwwAuthenticateParams()); + assertEquals(oauthServer.url() + "/.well-known/oauth-protected-resource", + request.wwwAuthenticateParams().resourceMetadataUrl()); + assertEquals("mcp.read", request.wwwAuthenticateParams().scope()); + assertEquals("invalid_token", request.wwwAuthenticateParams().error()); + assertEquals(oauthServer.url() + "/mcp", + MAPPER.readTree(request.resourceMetadata()).path("resource").asText()); + + var requests = oauthServer.requests(); + assertTrue(requests.stream().anyMatch(record -> record.authorization() == null)); + assertTrue( + requests.stream().anyMatch(record -> ("Bearer " + EXPECTED_TOKEN).equals(record.authorization()))); + } + } + + @Test + void testShouldRequestReplacementTokensAcrossMcpOauthLifecycle() throws Exception { + try (var oauthServer = OAuthMcpServer.start(ctx.getRepoRoot())) { + var serverName = "oauth-lifecycle-mcp"; + var observedReasons = new CopyOnWriteArrayList(); + var refreshCount = new java.util.concurrent.atomic.AtomicInteger(); + + try (var client = ctx.createClient(); + var session = client.createSession(new SessionConfig().setEnableMcpApps(true) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> { + assertNotNull(invocation); + observedReasons.add(request.reason()); + var result = switch (request.reason()) { + case REFRESH -> { + assertNotNull(request.wwwAuthenticateParams()); + assertNull(request.wwwAuthenticateParams().resourceMetadataUrl()); + assertEquals("invalid_token", request.wwwAuthenticateParams().error()); + if (refreshCount.incrementAndGet() > 1) { + yield McpAuthResult.cancelled(); + } + yield McpAuthResult.token(new McpAuthToken(REFRESH_TOKEN, null, null)); + } + case UPSCOPE -> { + assertNotNull(request.wwwAuthenticateParams()); + assertEquals(oauthServer.url() + "/.well-known/oauth-protected-resource", + request.wwwAuthenticateParams().resourceMetadataUrl()); + assertEquals("mcp.write", request.wwwAuthenticateParams().scope()); + assertEquals("insufficient_scope", request.wwwAuthenticateParams().error()); + yield McpAuthResult.token(new McpAuthToken(UPSCOPE_TOKEN, null, null)); + } + case REAUTH -> McpAuthResult.token(new McpAuthToken(REAUTH_TOKEN, null, null)); + default -> McpAuthResult.token(new McpAuthToken(EXPECTED_TOKEN, null, null)); + }; + return java.util.concurrent.CompletableFuture.completedFuture(result); + }).setMcpServers(Map.of(serverName, new McpHttpServerConfig() + .setUrl(oauthServer.url() + "/mcp").setTools(List.of("*"))))) + .get()) { + waitForMcpServerStatus(session, serverName, McpServerStatus.CONNECTED, + new java.util.concurrent.atomic.AtomicReference<>()); + callWhoami(session, serverName, "refresh"); + callWhoami(session, serverName, "upscope"); + callWhoami(session, serverName, "reauth"); + } + + assertEquals(List.of(McpOauthRequestReason.INITIAL, McpOauthRequestReason.REFRESH, + McpOauthRequestReason.UPSCOPE, McpOauthRequestReason.REFRESH, McpOauthRequestReason.REAUTH), + observedReasons); + + var requests = oauthServer.requests(); + assertTrue( + requests.stream().anyMatch(record -> ("Bearer " + REFRESH_TOKEN).equals(record.authorization()))); + assertTrue( + requests.stream().anyMatch(record -> ("Bearer " + UPSCOPE_TOKEN).equals(record.authorization()))); + assertTrue(requests.stream().anyMatch(record -> ("Bearer " + REAUTH_TOKEN).equals(record.authorization()))); + } + } + + @Test + void testShouldCancelPendingMcpOauthRequest() throws Exception { + try (var oauthServer = OAuthMcpServer.start(ctx.getRepoRoot())) { + var serverName = "oauth-cancelled-mcp"; + var observedRequest = new java.util.concurrent.atomic.AtomicReference(); + + try (var client = ctx.createClient(); + var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> { + assertNotNull(invocation); + observedRequest.set(request); + return java.util.concurrent.CompletableFuture + .completedFuture(McpAuthResult.cancelled()); + }).setMcpServers(Map.of(serverName, new McpHttpServerConfig() + .setUrl(oauthServer.url() + "/mcp").setTools(List.of("*"))))) + .get()) { + waitForMcpServerStatus(session, serverName, McpServerStatus.NEEDS_AUTH, observedRequest); + + // Race: session.create kicks off the MCP connection, but the SDK + // registers its `mcp.oauth_required` interest only after create + // returns. If the initial 401 wins, the runtime records + // `needs-auth` without invoking the host callback. A later auth + // retry (interest now registered) fires the callback with the same + // INITIAL reason. Wait for the callback instead of sampling it the + // instant `needs-auth` appears, which is what made this test flaky. + var request = waitForAuthRequest(observedRequest); + assertEquals(serverName, request.serverName()); + assertEquals(McpOauthRequestReason.INITIAL, request.reason()); + } + } + } + + @Test + void testShouldResolvePendingMcpOauthRequestThroughRpc() throws Exception { + try (var oauthServer = OAuthMcpServer.start(ctx.getRepoRoot())) { + var serverName = "oauth-direct-rpc-mcp"; + var observedRequest = new AtomicReference(); + var pendingHandlerResult = new CompletableFuture(); + + try (var client = ctx.createClient(); + var session = client.createSession(new SessionConfig().setEnableMcpApps(true) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> { + assertNotNull(invocation); + observedRequest.set(request); + return pendingHandlerResult; + }).setMcpServers(Map.of(serverName, new McpHttpServerConfig() + .setUrl(oauthServer.url() + "/mcp").setTools(List.of("*"))))) + .get()) { + var connected = CompletableFuture.runAsync(() -> { + try { + waitForMcpServerStatus(session, serverName, McpServerStatus.CONNECTED, observedRequest); + } catch (Exception ex) { + throw new CompletionException(ex); + } + }); + + var request = waitForAuthRequest(observedRequest); + assertEquals(serverName, request.serverName()); + assertEquals(oauthServer.url() + "/mcp", request.serverUrl()); + assertEquals(McpOauthRequestReason.INITIAL, request.reason()); + assertNotNull(request.wwwAuthenticateParams()); + assertEquals(oauthServer.url() + "/.well-known/oauth-protected-resource", + request.wwwAuthenticateParams().resourceMetadataUrl()); + assertEquals("mcp.read", request.wwwAuthenticateParams().scope()); + assertEquals("invalid_token", request.wwwAuthenticateParams().error()); + + var handled = session.getRpc().mcp.oauth.handlePendingRequest( + new SessionMcpOauthHandlePendingRequestParams(null, request.requestId(), Map.of("kind", "token", + "accessToken", EXPECTED_TOKEN, "tokenType", "Bearer", "expiresIn", 3600L))) + .get(30, TimeUnit.SECONDS); + assertTrue(handled.success()); + + pendingHandlerResult.complete(McpAuthResult.cancelled()); + connected.get(60, TimeUnit.SECONDS); + var tools = session.getRpc().mcp.listTools(new SessionMcpListToolsParams(null, serverName)).get(30, + TimeUnit.SECONDS); + assertTrue(tools.tools().stream().anyMatch(tool -> "whoami".equals(tool.name()))); + } finally { + pendingHandlerResult.complete(McpAuthResult.cancelled()); + } + + var requests = oauthServer.requests(); + assertTrue( + requests.stream().anyMatch(record -> ("Bearer " + EXPECTED_TOKEN).equals(record.authorization()))); + } + } + + private static void callWhoami(CopilotSession session, String serverName, String scenario) throws Exception { + var result = session.getRpc().mcp.apps.callTool( + new SessionMcpAppsCallToolParams(null, serverName, "whoami", Map.of("scenario", scenario), serverName)) + .get(30, TimeUnit.SECONDS); + var content = result.path("content"); + assertEquals(1, content.size()); + assertEquals("oauth-test-user", content.get(0).path("text").asText()); + } + + private static void waitForMcpServerStatus(CopilotSession session, String serverName, McpServerStatus status, + java.util.concurrent.atomic.AtomicReference observedRequest) + throws Exception { + var deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); + var lastStatus = ""; + while (System.nanoTime() < deadline) { + var result = session.getRpc().mcp.list().get(5, TimeUnit.SECONDS); + var server = result.servers().stream().filter(candidate -> serverName.equals(candidate.name())).findFirst(); + if (server.isPresent()) { + lastStatus = String.valueOf(server.get().status()); + } + if (server.isPresent() && status.equals(server.get().status())) { + return; + } + Thread.sleep(200); + } + fail(serverName + " did not reach " + status + "; last status was " + lastStatus + "; auth handler invoked=" + + (observedRequest.get() != null)); + } + + private static McpAuthRequest waitForAuthRequest(AtomicReference observedRequest) throws Exception { + var deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + while (System.nanoTime() < deadline) { + var request = observedRequest.get(); + if (request != null) { + return request; + } + Thread.sleep(100); + } + throw new AssertionError("Timed out waiting for MCP OAuth request"); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + private record OAuthMcpRequest(String authorization) { + } + + private record OAuthMcpServer(Process process, String url) implements AutoCloseable { + static OAuthMcpServer start(Path repoRoot) throws Exception { + var script = repoRoot.resolve("test").resolve("harness").resolve("test-mcp-oauth-server.mjs"); + var processBuilder = new ProcessBuilder(resolveExecutable("node"), script.toString()); + processBuilder.environment().put("EXPECTED_TOKEN", EXPECTED_TOKEN); + var process = processBuilder.start(); + var stderr = new StringBuilder(); + Thread stderrThread = new Thread(() -> { + try (var reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { + reader.lines().forEach(stderr::append); + } catch (IOException ex) { + stderr.append(ex.getMessage()); + } + }); + stderrThread.setDaemon(true); + stderrThread.start(); + try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { + var deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + if (reader.ready()) { + var line = reader.readLine(); + if (line != null && line.startsWith("Listening: ")) { + return new OAuthMcpServer(process, line.substring("Listening: ".length())); + } + } + Thread.sleep(50); + } + } + process.destroyForcibly(); + throw new AssertionError("Timed out waiting for OAuth MCP server: " + stderr); + } + + List requests() throws Exception { + var client = HttpClient.newHttpClient(); + var response = client.send(HttpRequest.newBuilder(URI.create(url + "/__requests")) + .timeout(Duration.ofSeconds(10)).GET().build(), HttpResponse.BodyHandlers.ofString()); + assertEquals(200, response.statusCode()); + return MAPPER.readValue(response.body(), new TypeReference>() { + }); + } + + private static String resolveExecutable(String executable) { + var path = System.getenv("PATH"); + if (path == null || path.isBlank()) { + throw new IllegalStateException("PATH is not configured; cannot find " + executable); + } + + var extensions = isWindows() + ? System.getenv().getOrDefault("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";") + : new String[]{""}; + for (var directory : path.split(java.util.regex.Pattern.quote(File.pathSeparator))) { + if (directory.isBlank()) { + continue; + } + for (var extension : extensions) { + var candidate = Path.of(directory).resolve(executable + extension).toAbsolutePath().normalize(); + if (Files.isRegularFile(candidate) && Files.isExecutable(candidate)) { + return candidate.toString(); + } + } + } + throw new IllegalStateException("Could not find " + executable + " on PATH."); + } + + private static boolean isWindows() { + return System.getProperty("os.name", "").toLowerCase(java.util.Locale.ROOT).contains("win"); + } + + @Override + public void close() { + process.destroyForcibly(); + } + } +} diff --git a/java/src/test/java/com/github/copilot/McpOAuthResumeE2ETest.java b/java/src/test/java/com/github/copilot/McpOAuthResumeE2ETest.java new file mode 100644 index 0000000000..19c15ed595 --- /dev/null +++ b/java/src/test/java/com/github/copilot/McpOAuthResumeE2ETest.java @@ -0,0 +1,76 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import com.github.copilot.generated.AssistantMessageEvent; +import com.github.copilot.rpc.McpAuthResult; +import com.github.copilot.rpc.MessageOptions; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.ResumeSessionConfig; +import com.github.copilot.rpc.SessionConfig; + +class McpOAuthResumeE2ETest { + + private static final String SNAPSHOT = "resumes_a_persisted_session_from_a_new_client_when_an_mcp_oauth_handler_is_configured"; + + private static E2ETestContext ctx; + + @BeforeAll + static void setup() throws Exception { + ctx = E2ETestContext.create(); + } + + @AfterAll + static void teardown() throws Exception { + if (ctx != null) { + ctx.close(); + } + } + + @Test + @Tag("isolated-resume") + void resumesAPersistedSessionFromANewClientWhenAnMcpOauthHandlerIsConfigured() throws Exception { + ctx.configureForTest("session", SNAPSHOT); + + String sessionId; + try (var client = ctx.createClient(); + var session = client + .createSession( + new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> CompletableFuture + .completedFuture(McpAuthResult.cancelled()))) + .get(30, TimeUnit.SECONDS)) { + sessionId = session.getSessionId(); + + AssistantMessageEvent response = session.sendAndWait(new MessageOptions().setPrompt("What is 1+1?"), 60_000) + .get(90, TimeUnit.SECONDS); + assertNotNull(response); + assertTrue(response.getData().content().contains("2"), + "Response should contain 2: " + response.getData().content()); + } + + try (var client = ctx.createClient(); + var session = client + .resumeSession(sessionId, + new ResumeSessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setOnMcpAuthRequest((request, invocation) -> CompletableFuture + .completedFuture(McpAuthResult.cancelled()))) + .get(30, TimeUnit.SECONDS)) { + assertEquals(sessionId, session.getSessionId()); + } + } +} diff --git a/java/src/test/java/com/github/copilot/PerSessionAuthTest.java b/java/src/test/java/com/github/copilot/PerSessionAuthTest.java index 1b0c419c30..9e5cd1b324 100644 --- a/java/src/test/java/com/github/copilot/PerSessionAuthTest.java +++ b/java/src/test/java/com/github/copilot/PerSessionAuthTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import com.github.copilot.generated.rpc.SessionAuthGetStatusResult; +import com.github.copilot.generated.rpc.SessionGitHubAuthGetStatusResult; import com.github.copilot.rpc.CopilotClientOptions; import com.github.copilot.rpc.PermissionHandler; import com.github.copilot.rpc.SessionConfig; @@ -73,7 +73,7 @@ void shouldAuthenticateWithGitHubToken() throws Exception { .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); try { - SessionAuthGetStatusResult authStatus = session.getRpc().auth.getStatus().get(); + SessionGitHubAuthGetStatusResult authStatus = session.getRpc().gitHubAuth.getStatus().get(); assertTrue(authStatus.isAuthenticated(), "Expected session to be authenticated"); assertEquals("alice", authStatus.login()); @@ -94,8 +94,8 @@ void shouldIsolateAuthBetweenSessions() throws Exception { .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); try { - SessionAuthGetStatusResult statusA = sessionA.getRpc().auth.getStatus().get(); - SessionAuthGetStatusResult statusB = sessionB.getRpc().auth.getStatus().get(); + SessionGitHubAuthGetStatusResult statusA = sessionA.getRpc().gitHubAuth.getStatus().get(); + SessionGitHubAuthGetStatusResult statusB = sessionB.getRpc().gitHubAuth.getStatus().get(); assertTrue(statusA.isAuthenticated(), "Expected session A to be authenticated"); assertEquals("alice", statusA.login()); @@ -131,7 +131,7 @@ void shouldBeUnauthenticatedWithoutToken() throws Exception { .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); try { - SessionAuthGetStatusResult authStatus = session.getRpc().auth.getStatus().get(); + SessionGitHubAuthGetStatusResult authStatus = session.getRpc().gitHubAuth.getStatus().get(); // With no global or per-session token, there is no identity at all. assertNull(authStatus.login(), "Expected no login without per-session token"); diff --git a/java/src/test/java/com/github/copilot/PreMcpToolCallHookTest.java b/java/src/test/java/com/github/copilot/PreMcpToolCallHookTest.java index 5da0d2002f..392e2cc759 100644 --- a/java/src/test/java/com/github/copilot/PreMcpToolCallHookTest.java +++ b/java/src/test/java/com/github/copilot/PreMcpToolCallHookTest.java @@ -14,7 +14,6 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import com.fasterxml.jackson.databind.JsonNode; @@ -55,21 +54,25 @@ static void teardown() throws Exception { } } + private McpStdioServerConfig createMetaEchoServer() { + var harnessDir = ctx.getRepoRoot().resolve("test").resolve("harness"); + return new McpStdioServerConfig().setCommand("node") + .setArgs(List.of(harnessDir.resolve("test-mcp-meta-echo-server.mjs").toString())) + .setWorkingDirectory(harnessDir.toString()).setTools(List.of("*")); + } + /** * Verifies that preMcpToolCall hook can set metadata on the MCP request. * * @see Snapshot: pre_mcp_tool_call_hook/should_set_meta_via_premcptoolcall_hook */ - @Disabled("Requires snapshot: pre_mcp_tool_call_hook/should_set_meta_via_premcptoolcall_hook") @Test void testShouldSetMetaViaPreMcpToolCallHook() throws Exception { ctx.configureForTest("pre_mcp_tool_call_hook", "should_set_meta_via_premcptoolcall_hook"); var hookInputs = new java.util.ArrayList(); - var mcpServers = new HashMap(); - mcpServers.put("meta-echo", new McpStdioServerConfig().setCommand("npx").setArgs(List.of("-y", "mcp-meta-echo")) - .setTools(List.of("*")).setWorkingDirectory(ctx.getWorkDir().toString())); + mcpServers.put("meta-echo", createMetaEchoServer()); var hooks = new SessionHooks().setOnPreMcpToolCall((input, invocation) -> { hookInputs.add(input); @@ -97,6 +100,7 @@ void testShouldSetMetaViaPreMcpToolCallHook() throws Exception { // Verify the response contains the injected metadata String content = response.getData().content(); + assertTrue(content.contains("injected"), "Response should contain injected metadata: " + content); assertTrue(content.contains("by-hook"), "Response should contain injected metadata: " + content); session.close(); @@ -109,17 +113,17 @@ void testShouldSetMetaViaPreMcpToolCallHook() throws Exception { * @see Snapshot: * pre_mcp_tool_call_hook/should_replace_meta_via_premcptoolcall_hook */ - @Disabled("Requires snapshot: pre_mcp_tool_call_hook/should_replace_meta_via_premcptoolcall_hook") @Test void testShouldReplaceMetaViaPreMcpToolCallHook() throws Exception { ctx.configureForTest("pre_mcp_tool_call_hook", "should_replace_meta_via_premcptoolcall_hook"); + var hookInputs = new java.util.ArrayList(); var mcpServers = new HashMap(); - mcpServers.put("meta-echo", new McpStdioServerConfig().setCommand("npx").setArgs(List.of("-y", "mcp-meta-echo")) - .setTools(List.of("*")).setWorkingDirectory(ctx.getWorkDir().toString())); + mcpServers.put("meta-echo", createMetaEchoServer()); var hooks = new SessionHooks().setOnPreMcpToolCall((input, invocation) -> { - JsonNode metaNode = MAPPER.valueToTree(Map.of("replaced", "true", "original", "gone")); + hookInputs.add(input); + JsonNode metaNode = MAPPER.valueToTree(Map.of("completely", "replaced")); return CompletableFuture.completedFuture(PreMcpToolCallHookOutput.withMeta(metaNode)); }); @@ -132,9 +136,13 @@ void testShouldReplaceMetaViaPreMcpToolCallHook() throws Exception { .get(60, TimeUnit.SECONDS); assertNotNull(response); + assertFalse(hookInputs.isEmpty(), "Should have received preMcpToolCall hook calls"); + assertEquals("meta-echo", hookInputs.get(0).getServerName()); + assertEquals("echo_meta", hookInputs.get(0).getToolName()); // Verify the response contains the replaced metadata String content = response.getData().content(); + assertTrue(content.contains("completely"), "Response should contain replaced metadata: " + content); assertTrue(content.contains("replaced"), "Response should contain replaced metadata: " + content); session.close(); @@ -147,17 +155,16 @@ void testShouldReplaceMetaViaPreMcpToolCallHook() throws Exception { * @see Snapshot: * pre_mcp_tool_call_hook/should_remove_meta_via_premcptoolcall_hook */ - @Disabled("Requires snapshot: pre_mcp_tool_call_hook/should_remove_meta_via_premcptoolcall_hook") @Test void testShouldRemoveMetaViaPreMcpToolCallHook() throws Exception { ctx.configureForTest("pre_mcp_tool_call_hook", "should_remove_meta_via_premcptoolcall_hook"); + var hookInputs = new java.util.ArrayList(); var mcpServers = new HashMap(); - mcpServers.put("meta-echo", new McpStdioServerConfig().setCommand("npx").setArgs(List.of("-y", "mcp-meta-echo")) - .setTools(List.of("*")).setWorkingDirectory(ctx.getWorkDir().toString())); + mcpServers.put("meta-echo", createMetaEchoServer()); var hooks = new SessionHooks().setOnPreMcpToolCall((input, invocation) -> { - // Return output with null metaToUse to remove metadata + hookInputs.add(input); return CompletableFuture.completedFuture(PreMcpToolCallHookOutput.removeMeta()); }); @@ -170,6 +177,14 @@ void testShouldRemoveMetaViaPreMcpToolCallHook() throws Exception { .get(60, TimeUnit.SECONDS); assertNotNull(response); + assertFalse(hookInputs.isEmpty(), "Should have received preMcpToolCall hook calls"); + assertEquals("meta-echo", hookInputs.get(0).getServerName()); + assertEquals("echo_meta", hookInputs.get(0).getToolName()); + + String content = response.getData().content(); + assertTrue(content.contains("\"meta\":null") || content.contains("\"meta\": null"), + "Response should contain removed metadata: " + content); + assertTrue(content.contains("test-remove"), "Response should contain tool value: " + content); session.close(); } diff --git a/java/src/test/java/com/github/copilot/RpcServerE2ETest.java b/java/src/test/java/com/github/copilot/RpcServerE2ETest.java new file mode 100644 index 0000000000..2393f334b2 --- /dev/null +++ b/java/src/test/java/com/github/copilot/RpcServerE2ETest.java @@ -0,0 +1,596 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.github.copilot.generated.rpc.AccountQuotaSnapshot; +import com.github.copilot.generated.rpc.AgentsDiscoverParams; +import com.github.copilot.generated.rpc.AgentsGetDiscoveryPathsParams; +import com.github.copilot.generated.rpc.InstructionsDiscoverParams; +import com.github.copilot.generated.rpc.InstructionsGetDiscoveryPathsParams; +import com.github.copilot.generated.rpc.LlmInferenceHttpResponseChunkError; +import com.github.copilot.generated.rpc.LlmInferenceHttpResponseChunkParams; +import com.github.copilot.generated.rpc.LlmInferenceHttpResponseStartParams; +import com.github.copilot.generated.rpc.LocalSessionMetadataValue; +import com.github.copilot.generated.rpc.McpDiscoverParams; +import com.github.copilot.generated.rpc.PingParams; +import com.github.copilot.generated.rpc.SecretsAddFilterValuesParams; +import com.github.copilot.generated.rpc.ServerSkill; +import com.github.copilot.generated.rpc.SessionContext; +import com.github.copilot.generated.rpc.SessionFsSetProviderCapabilities; +import com.github.copilot.generated.rpc.SessionFsSetProviderConventions; +import com.github.copilot.generated.rpc.SessionFsSetProviderParams; +import com.github.copilot.generated.rpc.SessionsBulkDeleteParams; +import com.github.copilot.generated.rpc.SessionsCheckInUseParams; +import com.github.copilot.generated.rpc.SessionsCloseParams; +import com.github.copilot.generated.rpc.SessionsConnectParams; +import com.github.copilot.generated.rpc.SessionsEnrichMetadataParams; +import com.github.copilot.generated.rpc.SessionsFindByPrefixParams; +import com.github.copilot.generated.rpc.SessionsFindByTaskIdParams; +import com.github.copilot.generated.rpc.SessionsGetEventFilePathParams; +import com.github.copilot.generated.rpc.SessionsGetLastForContextParams; +import com.github.copilot.generated.rpc.SessionsGetPersistedRemoteSteerableParams; +import com.github.copilot.generated.rpc.SessionsLoadDeferredRepoHooksParams; +import com.github.copilot.generated.rpc.SessionsPruneOldParams; +import com.github.copilot.generated.rpc.SessionsReleaseLockParams; +import com.github.copilot.generated.rpc.SessionsReloadPluginHooksParams; +import com.github.copilot.generated.rpc.SessionsSaveParams; +import com.github.copilot.generated.rpc.SessionsSetAdditionalPluginsParams; +import com.github.copilot.generated.rpc.SkillsConfigSetDisabledSkillsParams; +import com.github.copilot.generated.rpc.SkillsDiscoverParams; +import com.github.copilot.generated.rpc.SkillsGetDiscoveryPathsParams; +import com.github.copilot.generated.rpc.ToolsListParams; +import com.github.copilot.rpc.CopilotClientOptions; +import com.github.copilot.rpc.InfiniteSessionConfig; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.SessionConfig; + +class RpcServerE2ETest { + + private static final long TIMEOUT_SECONDS = 30; + private static final long SESSION_PERSISTENCE_TIMEOUT_MILLIS = 30_000; + private static E2ETestContext ctx; + + @BeforeAll + static void setup() throws Exception { + ctx = E2ETestContext.create(); + } + + @AfterAll + static void teardown() throws Exception { + if (ctx != null) { + ctx.close(); + } + } + + @Test + void testShouldCallRpcPingWithTypedParamsAndResult() throws Exception { + ctx.configureForTest("rpc_server", "should_call_rpc_ping_with_typed_params_and_result"); + + try (var client = ctx.createClient()) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + var result = client.getRpc().ping(new PingParams("typed rpc test")).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertEquals("pong: typed rpc test", result.message()); + assertNotNull(result.timestamp()); + assertNotNull(result.protocolVersion()); + assertTrue(result.protocolVersion() >= 0); + } + } + + @Test + void testShouldRejectLlmInferenceResponseFramesForMissingRequest() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var requestId = "missing-llm-inference-request"; + + var start = client.getRpc().llmInference + .httpResponseStart(new LlmInferenceHttpResponseStartParams(requestId, 200L, "OK", + Map.of("content-type", List.of("text/event-stream")))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertFalse(start.accepted()); + + var chunk = client.getRpc().llmInference + .httpResponseChunk( + new LlmInferenceHttpResponseChunkParams(requestId, "data: {}\n\n", false, false, null)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertFalse(chunk.accepted()); + + var error = client.getRpc().llmInference.httpResponseChunk(new LlmInferenceHttpResponseChunkParams( + requestId, "", null, true, + new LlmInferenceHttpResponseChunkError("No pending LLM inference request.", "missing_request"))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertFalse(error.accepted()); + } + } + + @Test + void testShouldCallRpcModelsListWithTypedResult() throws Exception { + ctx.configureForTest("rpc_server", "should_call_rpc_models_list_with_typed_result"); + var token = "rpc-models-token"; + configureAuthenticatedUser(token, null); + + try (var client = createAuthenticatedClient(token)) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + var result = client.getRpc().models.list().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertNotNull(result.models()); + assertTrue(result.models().stream().anyMatch(model -> "claude-sonnet-4.5".equals(model.id()))); + result.models().forEach(model -> { + assertFalse(model.id().isBlank()); + assertFalse(model.name().isBlank()); + }); + } + } + + @Test + void testShouldCallRpcAccountGetQuotaWhenAuthenticated() throws Exception { + ctx.configureForTest("rpc_server", "should_call_rpc_account_get_quota_when_authenticated"); + var token = "rpc-quota-token"; + configureAuthenticatedUser(token, Map.of("chat", Map.of("entitlement", 100, "overage_count", 2, + "overage_permitted", true, "percent_remaining", 75, "timestamp_utc", "2026-04-30T00:00:00Z"))); + + try (var client = createAuthenticatedClient(token)) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + var result = client.getRpc().account.getQuota().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertNotNull(result.quotaSnapshots()); + var chatQuota = result.quotaSnapshots().get("chat"); + assertNotNull(chatQuota); + assertQuota(chatQuota); + } + } + + @Test + void testShouldCallRpcToolsListWithTypedResult() throws Exception { + ctx.configureForTest("rpc_server", "should_call_rpc_tools_list_with_typed_result"); + + try (var client = ctx.createClient()) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + var result = client.getRpc().tools.list(new ToolsListParams(null)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertNotNull(result.tools()); + assertFalse(result.tools().isEmpty()); + result.tools().forEach(tool -> assertFalse(tool.name().isBlank())); + } + } + + @Test + void testShouldCallRpcSessionFsSetProviderWithTypedResult() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + var result = client.getRpc().sessionFs + .setProvider(new SessionFsSetProviderParams(ctx.getWorkDir().toString(), + ctx.getWorkDir().resolve("session-state").toString(), currentPathConventions(), + new SessionFsSetProviderCapabilities(true))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertTrue(result.success()); + } + } + + @Test + void testShouldAddSecretFilterValues() throws Exception { + ctx.initializeProxy(); + var env = new HashMap<>(ctx.getEnvironment()); + env.put("COPILOT_ENABLE_SECRET_FILTERING", "true"); + + try (var client = ctx.createClient(new CopilotClientOptions().setEnvironment(env))) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var secret = "rpc-secret-" + UUID.randomUUID().toString().replace("-", ""); + + var result = client.getRpc().secrets.addFilterValues(new SecretsAddFilterValuesParams(List.of(secret))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertTrue(result.ok()); + } + } + + @Test + void testShouldListFindAndInspectPersistedSessionState() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + var requestedSessionId = UUID.randomUUID().toString(); + var workingDirectory = createUniqueWorkDirectory("server-rpc-list"); + var missingTaskId = "missing-task-" + UUID.randomUUID().toString().replace("-", ""); + var missingSessionId = UUID.randomUUID().toString(); + + try (var session = client.createSession(persistedSessionConfig(requestedSessionId, workingDirectory)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + var sessionId = session.getSessionId(); + session.log("SERVER_RPC_LIST_READY").get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + saveSession(client, sessionId); + assertNull(client.getRpc().sessions.close(new SessionsCloseParams(sessionId)).get(TIMEOUT_SECONDS, + TimeUnit.SECONDS)); + + var listed = client.getRpc().sessions.list().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(listed.sessions()); + + var byPrefix = client.getRpc().sessions + .findByPrefix(new SessionsFindByPrefixParams(sessionId.substring(0, 8))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertTrue(byPrefix.sessionId() == null || sessionId.equals(byPrefix.sessionId())); + + var byTaskId = client.getRpc().sessions.findByTaskId(new SessionsFindByTaskIdParams(missingTaskId)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNull(byTaskId.sessionId()); + + var lastForContext = client.getRpc().sessions + .getLastForContext(new SessionsGetLastForContextParams( + new SessionContext(workingDirectory.toString(), null, null, null, null))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertTrue(lastForContext.sessionId() == null || sessionId.equals(lastForContext.sessionId())); + + var eventFile = client.getRpc().sessions.getEventFilePath(new SessionsGetEventFilePathParams(sessionId)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertTrue(eventFile.filePath().endsWith("events.jsonl")); + + var remoteSteerable = client.getRpc().sessions + .getPersistedRemoteSteerable(new SessionsGetPersistedRemoteSteerableParams(sessionId)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNull(remoteSteerable.remoteSteerable()); + + var sizes = client.getRpc().sessions.getSizes().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(sizes.sizes()); + if (sizes.sizes().containsKey(sessionId)) { + assertTrue(sizes.sizes().get(sessionId) >= 0); + } + + var inUse = client.getRpc().sessions + .checkInUse(new SessionsCheckInUseParams(List.of(sessionId, missingSessionId))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(inUse.inUse()); + assertFalse(inUse.inUse().contains(missingSessionId)); + } + } + } + + @Test + void testShouldEnrichBasicSessionMetadata() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + var requestedSessionId = UUID.randomUUID().toString(); + var workingDirectory = createUniqueWorkDirectory("server-rpc-enrich"); + + try (var session = client.createSession(persistedSessionConfig(requestedSessionId, workingDirectory)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + var sessionId = session.getSessionId(); + session.log("SERVER_RPC_ENRICH_READY").get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + saveSession(client, sessionId); + + var now = OffsetDateTime.now().toString(); + var basic = new LocalSessionMetadataValue(sessionId, now, now, null, "Basic metadata", null, false, + null, new SessionContext(workingDirectory.toString(), null, null, null, null), null); + + var result = client.getRpc().sessions.enrichMetadata(new SessionsEnrichMetadataParams(List.of(basic))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertNotNull(result.sessions()); + assertEquals(1, result.sessions().size()); + var enriched = result.sessions().get(0); + assertEquals(sessionId, enriched.sessionId()); + assertNotNull(enriched.context()); + assertTrue(pathsEqual(workingDirectory.toString(), enriched.context().cwd())); + assertFalse(enriched.isRemote()); + } + } + } + + @Test + void testShouldCloseActiveSessionAndReleaseLock() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + var requestedSessionId = UUID.randomUUID().toString(); + var workingDirectory = createUniqueWorkDirectory("server-rpc-close"); + + try (var session = client.createSession(persistedSessionConfig(requestedSessionId, workingDirectory)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + var sessionId = session.getSessionId(); + session.log("SERVER_RPC_CLOSE_READY").get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + saveSession(client, sessionId); + + var close = client.getRpc().sessions.close(new SessionsCloseParams(sessionId)).get(TIMEOUT_SECONDS, + TimeUnit.SECONDS); + assertNull(close); + + var release = client.getRpc().sessions.releaseLock(new SessionsReleaseLockParams(sessionId)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNull(release); + + var inUse = client.getRpc().sessions.checkInUse(new SessionsCheckInUseParams(List.of(sessionId))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertFalse(inUse.inUse().contains(sessionId)); + } + } + } + + @Test + void testShouldPruneDryRunAndBulkDeletePersistedSession() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + var requestedSessionId = UUID.randomUUID().toString(); + var missingSessionId = UUID.randomUUID().toString(); + var workingDirectory = createUniqueWorkDirectory("server-rpc-delete"); + + var session = client.createSession(persistedSessionConfig(requestedSessionId, workingDirectory)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + try { + var sessionId = session.getSessionId(); + saveSession(client, sessionId); + client.getRpc().sessions.close(new SessionsCloseParams(sessionId)).get(TIMEOUT_SECONDS, + TimeUnit.SECONDS); + + var prune = client.getRpc().sessions.pruneOld(new SessionsPruneOldParams(0L, true, true, List.of())) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertTrue(prune.dryRun()); + assertNotNull(prune.candidates()); + assertNotNull(prune.deleted()); + assertFalse(prune.deleted().contains(sessionId)); + assertFalse(prune.candidates().contains(missingSessionId)); + assertNotNull(prune.freedBytes()); + assertTrue(prune.freedBytes() >= 0); + + var delete = client.getRpc().sessions + .bulkDelete(new SessionsBulkDeleteParams(List.of(sessionId, missingSessionId))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertTrue(delete.freedBytes().containsKey(sessionId)); + assertTrue(delete.freedBytes().get(sessionId) >= 0); + if (delete.freedBytes().containsKey(missingSessionId)) { + assertEquals(0L, delete.freedBytes().get(missingSessionId)); + } + + waitForSessionAbsent(client, sessionId); + } finally { + session.close(); + } + } + } + + @Test + void testShouldSetAdditionalPluginsAndReloadDeferredHooks() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNull(client.getRpc().sessions.setAdditionalPlugins(new SessionsSetAdditionalPluginsParams(List.of())) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + var requestedSessionId = UUID.randomUUID().toString(); + var workingDirectory = createUniqueWorkDirectory("server-rpc-hooks"); + + try (var session = client.createSession( + persistedSessionConfig(requestedSessionId, workingDirectory).setEnableConfigDiscovery(false)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + var sessionId = session.getSessionId(); + var reload = client.getRpc().sessions + .reloadPluginHooks(new SessionsReloadPluginHooksParams(sessionId, true)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNull(reload); + + var loaded = client.getRpc().sessions + .loadDeferredRepoHooks(new SessionsLoadDeferredRepoHooksParams(sessionId)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(loaded.startupPrompts()); + assertEquals(0L, loaded.hookCount()); + assertTrue(loaded.startupPrompts().isEmpty()); + } finally { + client.getRpc().sessions.setAdditionalPlugins(new SessionsSetAdditionalPluginsParams(List.of())) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + } + } + + @Test + void testShouldReportImplementedErrorWhenConnectingUnknownRemoteSession() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var remoteSessionId = "remote-" + UUID.randomUUID().toString().replace("-", ""); + + var ex = assertThrows(Exception.class, () -> client.getRpc().sessions + .connect(new SessionsConnectParams(remoteSessionId)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + var text = ex.toString(); + assertFalse(text.toLowerCase().contains("unhandled method sessions.connect")); + assertTrue(text.toLowerCase().contains("session")); + } + } + + @Test + void testShouldDiscoverServerMcpSkillsAgentsAndInstructions() throws Exception { + ctx.configureForTest("rpc_server", "should_discover_server_mcp_and_skills"); + + try (var client = ctx.createClient()) { + client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var workDir = ctx.getWorkDir().toString(); + var skillName = "server-rpc-skill-" + UUID.randomUUID().toString().replace("-", ""); + var skillDirectory = createSkillDirectory(skillName, "Skill discovered by server-scoped RPC tests."); + + var mcp = client.getRpc().mcp.discover(new McpDiscoverParams(workDir)).get(TIMEOUT_SECONDS, + TimeUnit.SECONDS); + assertNotNull(mcp.servers()); + + var skills = client.getRpc().skills + .discover(new SkillsDiscoverParams(null, List.of(skillDirectory.toString()), null)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var discoveredSkill = findSkill(skills.skills(), skillName); + assertEquals("Skill discovered by server-scoped RPC tests.", discoveredSkill.description()); + assertTrue(discoveredSkill.enabled()); + assertTrue(discoveredSkill.path().replace('\\', '/').endsWith(skillName + "/SKILL.md")); + + var skillPaths = client.getRpc().skills + .getDiscoveryPaths(new SkillsGetDiscoveryPathsParams(List.of(workDir), true)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var projectSkillPath = skillPaths.paths().stream().filter( + path -> pathsEqual(workDir, path.projectPath()) && Boolean.TRUE.equals(path.preferredForCreation())) + .findFirst().orElseThrow(() -> new AssertionError("Expected project skill discovery path")); + assertFalse(projectSkillPath.path().isBlank()); + + var agents = client.getRpc().agents.discover(new AgentsDiscoverParams(List.of(workDir), true)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(agents.agents()); + agents.agents().forEach(agent -> assertFalse(agent.name().isBlank())); + + var agentPaths = client.getRpc().agents + .getDiscoveryPaths(new AgentsGetDiscoveryPathsParams(List.of(workDir), true)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var projectAgentPath = agentPaths.paths().stream().filter( + path -> pathsEqual(workDir, path.projectPath()) && Boolean.TRUE.equals(path.preferredForCreation())) + .findFirst().orElseThrow(() -> new AssertionError("Expected project agent discovery path")); + assertFalse(projectAgentPath.path().isBlank()); + + var instructions = client.getRpc().instructions + .discover(new InstructionsDiscoverParams(List.of(workDir), true)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(instructions.sources()); + instructions.sources().forEach(source -> { + assertFalse(source.id().isBlank()); + assertFalse(source.label().isBlank()); + assertFalse(source.sourcePath().isBlank()); + }); + + var instructionPaths = client.getRpc().instructions + .getDiscoveryPaths(new InstructionsGetDiscoveryPathsParams(List.of(workDir), true)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertFalse(instructionPaths.paths().isEmpty()); + assertTrue(instructionPaths.paths().stream().anyMatch(path -> pathsEqual(workDir, path.projectPath()))); + instructionPaths.paths().forEach(path -> assertFalse(path.path().isBlank())); + + try { + client.getRpc().skills.config + .setDisabledSkills(new SkillsConfigSetDisabledSkillsParams(List.of(skillName))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var disabledSkills = client.getRpc().skills + .discover(new SkillsDiscoverParams(null, List.of(skillDirectory.toString()), null)) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + var disabledSkill = findSkill(disabledSkills.skills(), skillName); + assertFalse(disabledSkill.enabled()); + } finally { + client.getRpc().skills.config.setDisabledSkills(new SkillsConfigSetDisabledSkillsParams(List.of())) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + } + } + + private static CopilotClient createAuthenticatedClient(String token) throws Exception { + return ctx.createClient(new CopilotClientOptions().setGitHubToken(token)); + } + + private static void configureAuthenticatedUser(String token, Map quotaSnapshots) throws Exception { + var user = new HashMap(); + user.put("login", "rpc-user"); + user.put("copilot_plan", "individual_pro"); + user.put("endpoints", Map.of("api", ctx.getProxyUrl(), "telemetry", "https://localhost:1/telemetry")); + user.put("analytics_tracking_id", "rpc-user-tracking-id"); + if (quotaSnapshots != null) { + user.put("quota_snapshots", quotaSnapshots); + } + ctx.setCopilotUserByToken(token, user); + } + + private static void assertQuota(AccountQuotaSnapshot chatQuota) { + assertEquals(100L, chatQuota.entitlementRequests()); + assertEquals(25L, chatQuota.usedRequests()); + assertEquals(75.0, chatQuota.remainingPercentage()); + assertEquals(2.0, chatQuota.overage()); + assertTrue(chatQuota.usageAllowedWithExhaustedQuota()); + assertTrue(chatQuota.overageAllowedWithExhaustedQuota()); + assertEquals(OffsetDateTime.parse("2026-04-30T00:00:00Z"), chatQuota.resetDate()); + } + + private static SessionFsSetProviderConventions currentPathConventions() { + return isWindows() ? SessionFsSetProviderConventions.WINDOWS : SessionFsSetProviderConventions.POSIX; + } + + private static Path createUniqueWorkDirectory(String prefix) throws Exception { + var directory = ctx.getWorkDir().resolve(prefix + "-" + UUID.randomUUID().toString().replace("-", "")); + Files.createDirectories(directory); + return directory; + } + + private static SessionConfig persistedSessionConfig(String sessionId, Path workingDirectory) { + return new SessionConfig().setSessionId(sessionId).setWorkingDirectory(workingDirectory.toString()) + .setInfiniteSessions(new InfiniteSessionConfig().setEnabled(true)) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL); + } + + private static void saveSession(CopilotClient client, String sessionId) throws Exception { + var save = client.getRpc().sessions.save(new SessionsSaveParams(sessionId)).get(TIMEOUT_SECONDS, + TimeUnit.SECONDS); + assertNull(save); + } + + private static void waitForSessionAbsent(CopilotClient client, String sessionId) throws Exception { + var deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(SESSION_PERSISTENCE_TIMEOUT_MILLIS); + do { + var list = client.getRpc().sessions.list().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNotNull(list.sessions()); + var present = list.sessions().stream() + .anyMatch(session -> session instanceof Map map && sessionId.equals(map.get("sessionId"))); + if (!present) { + return; + } + Thread.sleep(100); + } while (System.nanoTime() < deadline); + + throw new AssertionError("Timed out waiting for session '" + sessionId + "' to be removed."); + } + + private static Path createSkillDirectory(String skillName, String description) throws Exception { + var skillsDir = ctx.getWorkDir().resolve("server-rpc-skills") + .resolve(UUID.randomUUID().toString().replace("-", "")); + var skillSubdir = skillsDir.resolve(skillName); + Files.createDirectories(skillSubdir); + Files.writeString(skillSubdir.resolve("SKILL.md"), "---\nname: " + skillName + "\ndescription: " + description + + "\n---\n\n# " + skillName + "\n\nThis skill is used by RPC E2E tests.\n"); + return skillsDir; + } + + private static ServerSkill findSkill(List skills, String name) { + return skills.stream().filter(skill -> name.equals(skill.name())).findFirst() + .orElseThrow(() -> new AssertionError("Expected to discover skill " + name)); + } + + private static boolean pathsEqual(String expected, String actual) { + if (actual == null) { + return false; + } + + var expectedPath = Path.of(expected).toAbsolutePath().normalize().toString(); + var actualPath = Path.of(actual).toAbsolutePath().normalize().toString(); + return isWindows() ? expectedPath.equalsIgnoreCase(actualPath) : expectedPath.equals(actualPath); + } + + private static boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("win"); + } +} diff --git a/java/src/test/java/com/github/copilot/RpcServerMiscE2ETest.java b/java/src/test/java/com/github/copilot/RpcServerMiscE2ETest.java new file mode 100644 index 0000000000..1db801d841 --- /dev/null +++ b/java/src/test/java/com/github/copilot/RpcServerMiscE2ETest.java @@ -0,0 +1,132 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.github.copilot.generated.rpc.AccountAllUsers; +import com.github.copilot.generated.rpc.AccountLoginParams; +import com.github.copilot.generated.rpc.AccountLogoutParams; +import com.github.copilot.generated.rpc.UserSettingMetadata; +import com.github.copilot.generated.rpc.UserSettingsSetParams; +import com.github.copilot.rpc.CopilotClientOptions; + +class RpcServerMiscE2ETest { + + private static E2ETestContext ctx; + + @BeforeAll + static void setup() throws Exception { + ctx = E2ETestContext.create(); + } + + @AfterAll + static void teardown() throws Exception { + if (ctx != null) { + ctx.close(); + } + } + + @Test + void testShouldGetSetAndClearUserSettings() throws Exception { + ctx.configureForTest("rpc_server_misc", "should_get_set_and_clear_user_settings"); + + try (var client = ctx.createClient()) { + client.start().get(30, TimeUnit.SECONDS); + var before = client.getRpc().user.settings.get().get(30, TimeUnit.SECONDS); + var entry = before.settings().entrySet().stream().filter(e -> isBooleanSetting(e.getValue())).findFirst() + .orElseThrow(() -> new AssertionError("Expected at least one boolean user setting")); + var key = entry.getKey(); + var original = settingBoolean(entry.getValue()); + var updated = !original; + + var set = client.getRpc().user.settings.set(new UserSettingsSetParams(Map.of(key, updated))).get(30, + TimeUnit.SECONDS); + assertTrue(set.shadowedKeys().isEmpty()); + client.getRpc().user.settings.reload().get(30, TimeUnit.SECONDS); + var afterSet = client.getRpc().user.settings.get().get(30, TimeUnit.SECONDS); + assertEquals(updated, settingBoolean(afterSet.settings().get(key))); + assertFalse(afterSet.settings().get(key).isDefault()); + + var clearSettings = new HashMap(); + clearSettings.put(key, null); + var clear = client.getRpc().user.settings.set(new UserSettingsSetParams(clearSettings)).get(30, + TimeUnit.SECONDS); + assertTrue(clear.shadowedKeys().isEmpty()); + client.getRpc().user.settings.reload().get(30, TimeUnit.SECONDS); + var afterClear = client.getRpc().user.settings.get().get(30, TimeUnit.SECONDS); + assertTrue(afterClear.settings().get(key).isDefault()); + } + } + + @Test + void testShouldLoginListGetCurrentAuthAndLogoutAccount() throws Exception { + ctx.configureForTest("rpc_server_misc", "should_login_list_getcurrentauth_and_logout_account"); + var token = "java-account-token"; + var login = "java-account-user"; + ctx.setCopilotUserByToken(token, login, "individual_pro", ctx.getProxyUrl(), "https://localhost:1/telemetry", + "java-account-tracking-id"); + + var env = new HashMap<>(ctx.getEnvironment()); + env.put("GH_TOKEN", ""); + env.put("GITHUB_TOKEN", ""); + env.put("COPILOT_SDK_AUTH_TOKEN", ""); + + try (var client = new CopilotClient( + new CopilotClientOptions().setCliPath(ctx.getCliPath()).setCwd(ctx.getWorkDir().toString()) + .setEnvironment(env).setGitHubToken("").setUseLoggedInUser(false))) { + client.start().get(30, TimeUnit.SECONDS); + + var initial = client.getRpc().account.getCurrentAuth().get(30, TimeUnit.SECONDS); + assertNull(initial.authInfo()); + + var loginResult = client.getRpc().account.login(new AccountLoginParams("https://github.com", login, token)) + .get(30, TimeUnit.SECONDS); + assertNotNull(loginResult); + + var current = client.getRpc().account.getCurrentAuth().get(30, TimeUnit.SECONDS); + assertNull(current.authErrors()); + assertInstanceOf(Map.class, current.authInfo()); + @SuppressWarnings("unchecked") + var authInfo = (Map) current.authInfo(); + assertEquals(login, authInfo.get("login")); + assertEquals("https://github.com", authInfo.get("host")); + + var users = client.getRpc().account.getAllUsers().get(30, TimeUnit.SECONDS); + users.stream().filter(user -> accountLogin(user).equals(login)).findFirst() + .ifPresent(user -> assertEquals(token, user.token())); + + var logout = client.getRpc().account.logout(new AccountLogoutParams(authInfo)).get(30, TimeUnit.SECONDS); + assertFalse(logout.hasMoreUsers()); + assertNull(client.getRpc().account.getCurrentAuth().get(30, TimeUnit.SECONDS).authInfo()); + } + } + + private static boolean isBooleanSetting(UserSettingMetadata metadata) { + return metadata.value() instanceof Boolean || metadata.default_() instanceof Boolean; + } + + private static boolean settingBoolean(UserSettingMetadata metadata) { + if (metadata.value() instanceof Boolean value) { + return value; + } + return (Boolean) metadata.default_(); + } + + private static String accountLogin(AccountAllUsers user) { + if (user.authInfo() instanceof Map authInfo) { + return String.valueOf(authInfo.get("login")); + } + return ""; + } +} diff --git a/java/src/test/java/com/github/copilot/RpcSessionStateExtrasE2ETest.java b/java/src/test/java/com/github/copilot/RpcSessionStateExtrasE2ETest.java new file mode 100644 index 0000000000..83365455e7 --- /dev/null +++ b/java/src/test/java/com/github/copilot/RpcSessionStateExtrasE2ETest.java @@ -0,0 +1,155 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.github.copilot.generated.rpc.NamedProviderConfig; +import com.github.copilot.generated.rpc.ProviderConfigType; +import com.github.copilot.generated.rpc.ProviderConfigWireApi; +import com.github.copilot.generated.rpc.ProviderModelConfig; +import com.github.copilot.generated.rpc.SessionCompletionsRequestParams; +import com.github.copilot.generated.rpc.SessionMetadataGetContextHeaviestMessagesParams; +import com.github.copilot.generated.rpc.SessionModelSwitchToParams; +import com.github.copilot.generated.rpc.SessionProviderAddParams; +import com.github.copilot.generated.rpc.SessionToolsUpdateSubagentSettingsParams; +import com.github.copilot.generated.rpc.SessionVisibilitySetParams; +import com.github.copilot.generated.rpc.SessionVisibilityStatus; +import com.github.copilot.generated.rpc.SubagentSettingsEntry; +import com.github.copilot.generated.rpc.SubagentSettingsEntryContextTier; +import com.github.copilot.rpc.MessageOptions; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.SessionConfig; + +class RpcSessionStateExtrasE2ETest { + + private static E2ETestContext ctx; + + @BeforeAll + static void setup() throws Exception { + ctx = E2ETestContext.create(); + } + + @AfterAll + static void teardown() throws Exception { + if (ctx != null) { + ctx.close(); + } + } + + @Test + void testShouldAddByokProviderAndModelAtRuntime() throws Exception { + ctx.configureForTest("rpc_session_state_extras", "should_add_byok_provider_and_model_at_runtime"); + + try (var client = ctx.createClient()) { + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get()) { + var result = session.getRpc().provider.add(new SessionProviderAddParams(null, + List.of(new NamedProviderConfig("java-e2e-provider", ProviderConfigType.OPENAI, + ProviderConfigWireApi.COMPLETIONS, null, "https://models.example.test/v1", + "provider-key", null, null, Map.of("x-provider", "java"), null)), + List.of(new ProviderModelConfig("small", "java-e2e-provider", null, null, "Java Added Model", + 4096.0, null, null, null)))) + .get(30, TimeUnit.SECONDS); + assertEquals(1, result.models().size()); + + var selectionId = "java-e2e-provider/small"; + session.getRpc().model + .switchTo(new SessionModelSwitchToParams(null, selectionId, null, null, null, null, null)) + .get(30, TimeUnit.SECONDS); + var current = session.getRpc().model.getCurrent().get(30, TimeUnit.SECONDS); + assertEquals(selectionId, current.modelId()); + } + } + } + + @Test + void testShouldReturnEmptyCompletionsWhenHostDoesNotProvideThem() throws Exception { + ctx.configureForTest("rpc_session_state_extras", + "should_return_empty_completions_when_host_does_not_provide_them"); + + try (var client = ctx.createClient()) { + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get()) { + var result = session.getRpc().completions + .request(new SessionCompletionsRequestParams(null, "Use @ to mention context", 5L)) + .get(30, TimeUnit.SECONDS); + assertTrue(result.items().isEmpty()); + } + } + } + + @Test + void testShouldReportVisibilityAsUnsyncedForLocalSession() throws Exception { + ctx.configureForTest("rpc_session_state_extras", "should_report_visibility_as_unsynced_for_local_session"); + + try (var client = ctx.createClient()) { + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get()) { + var set = session.getRpc().visibility + .set(new SessionVisibilitySetParams(null, SessionVisibilityStatus.UNSHARED)) + .get(30, TimeUnit.SECONDS); + assertFalse(set.synced()); + assertNull(set.status()); + assertNull(set.shareUrl()); + + var get = session.getRpc().visibility.get().get(30, TimeUnit.SECONDS); + assertFalse(get.synced()); + assertNull(get.status()); + assertNull(get.shareUrl()); + } + } + } + + @Test + void testShouldGetContextAttributionAndHeaviestMessagesAfterTurn() throws Exception { + ctx.configureForTest("rpc_session_state_extras", + "should_get_context_attribution_and_heaviest_messages_after_turn"); + + try (var client = ctx.createClient()) { + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get()) { + var answer = session.sendAndWait(new MessageOptions().setPrompt("Say CONTEXT_METADATA_OK exactly.")) + .get(60, TimeUnit.SECONDS); + assertTrue(answer.getData().content().contains("CONTEXT_METADATA_OK")); + + var attribution = session.getRpc().metadata.getContextAttribution().get(30, TimeUnit.SECONDS); + assertNotNull(attribution.contextAttribution()); + var heaviest = session.getRpc().metadata + .getContextHeaviestMessages(new SessionMetadataGetContextHeaviestMessagesParams(null, 5L)) + .get(30, TimeUnit.SECONDS); + assertTrue(heaviest.totalTokens() >= 0); + } + } + } + + @Test + void testShouldUpdateAndClearLiveSubagentSettings() throws Exception { + ctx.configureForTest("rpc_session_state_extras", "should_update_and_clear_live_subagent_settings"); + + try (var client = ctx.createClient()) { + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get()) { + session.getRpc().tools.updateSubagentSettings(new SessionToolsUpdateSubagentSettingsParams(null, + new SessionToolsUpdateSubagentSettingsParams.SessionToolsUpdateSubagentSettingsParamsSubagents( + Map.of("general-purpose", + new SubagentSettingsEntry("gpt-5-mini", "low", + SubagentSettingsEntryContextTier.LONG_CONTEXT)), + List.of("legacy-agent"), null, null))) + .get(30, TimeUnit.SECONDS); + session.getRpc().tools.updateSubagentSettings(new SessionToolsUpdateSubagentSettingsParams(null, null)) + .get(30, TimeUnit.SECONDS); + } + } + } +} diff --git a/java/src/test/java/com/github/copilot/RpcTasksAndHandlersE2ETest.java b/java/src/test/java/com/github/copilot/RpcTasksAndHandlersE2ETest.java new file mode 100644 index 0000000000..89b283339e --- /dev/null +++ b/java/src/test/java/com/github/copilot/RpcTasksAndHandlersE2ETest.java @@ -0,0 +1,72 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.github.copilot.generated.rpc.SessionMcpHeadersHandlePendingHeadersRefreshRequestParams; +import com.github.copilot.generated.rpc.SessionUiHandlePendingSessionLimitsExhaustedParams; +import com.github.copilot.generated.rpc.UISessionLimitsExhaustedResponse; +import com.github.copilot.generated.rpc.UISessionLimitsExhaustedResponseAction; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.SessionConfig; + +class RpcTasksAndHandlersE2ETest { + + private static E2ETestContext ctx; + + @BeforeAll + static void setup() throws Exception { + ctx = E2ETestContext.create(); + } + + @AfterAll + static void teardown() throws Exception { + if (ctx != null) { + ctx.close(); + } + } + + @Test + void testShouldReturnExpectedResultsForMissingPendingHandlerRequestIds() throws Exception { + ctx.initializeProxy(); + + try (var client = ctx.createClient()) { + try (var session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get()) { + var sessionLimits = session.getRpc().ui + .handlePendingSessionLimitsExhausted( + new SessionUiHandlePendingSessionLimitsExhaustedParams(null, + "missing-session-limits-request", + new UISessionLimitsExhaustedResponse( + UISessionLimitsExhaustedResponseAction.UNSET, null, null))) + .get(30, TimeUnit.SECONDS); + assertFalse(sessionLimits.success()); + + var headersRefresh = session.getRpc().mcp.headers + .handlePendingHeadersRefreshRequest( + new SessionMcpHeadersHandlePendingHeadersRefreshRequestParams(null, + "missing-headers-refresh-request", + Map.of("kind", "headers", "headers", Map.of("x-refresh", "missing")))) + .get(30, TimeUnit.SECONDS); + assertFalse(headersRefresh.success()); + + var noHeadersRefresh = session.getRpc().mcp.headers + .handlePendingHeadersRefreshRequest( + new SessionMcpHeadersHandlePendingHeadersRefreshRequestParams(null, + "missing-headers-refresh-none-request", Map.of("kind", "none"))) + .get(30, TimeUnit.SECONDS); + assertFalse(noHeadersRefresh.success()); + } + } + } +} diff --git a/java/src/test/java/com/github/copilot/RpcWrappersTest.java b/java/src/test/java/com/github/copilot/RpcWrappersTest.java index 9a3559d66d..7493c6e470 100644 --- a/java/src/test/java/com/github/copilot/RpcWrappersTest.java +++ b/java/src/test/java/com/github/copilot/RpcWrappersTest.java @@ -205,7 +205,7 @@ void sessionRpc_model_switchTo_merges_sessionId_with_extra_params() { var session = new SessionRpc(stub, "sess-xyz"); // switchTo takes extra params beyond sessionId - var switchParams = new SessionModelSwitchToParams(null, "gpt-5", null, null, null, null); + var switchParams = new SessionModelSwitchToParams(null, "gpt-5", null, null, null, null, null); session.model.switchTo(switchParams); assertEquals(1, stub.calls.size()); diff --git a/java/src/test/java/com/github/copilot/SessionCanvasSnapshotTest.java b/java/src/test/java/com/github/copilot/SessionCanvasSnapshotTest.java index 00db1d01c3..f50138b3b4 100644 --- a/java/src/test/java/com/github/copilot/SessionCanvasSnapshotTest.java +++ b/java/src/test/java/com/github/copilot/SessionCanvasSnapshotTest.java @@ -118,7 +118,7 @@ void getOpenCanvasesReturnsImmutableCopy() { var canvases = session.getOpenCanvases(); assertThrows(UnsupportedOperationException.class, - () -> canvases.add(new OpenCanvasInstance("x", "ext", null, "c", null, null, null, null))); + () -> canvases.add(new OpenCanvasInstance("x", "ext", null, "c", null, null, null, null, null))); // The returned list is a point-in-time snapshot, not a live view: a // subsequent event must not change the previously-returned list. @@ -133,9 +133,9 @@ void getOpenCanvasesReturnsImmutableCopy() { @Test void setOpenCanvasesSeedsAndFiltersNulls() { var seed = new java.util.ArrayList(); - seed.add(new OpenCanvasInstance("inst-1", "ext", null, "canvas-a", null, null, null, null)); + seed.add(new OpenCanvasInstance("inst-1", "ext", null, "canvas-a", null, null, null, null, null)); seed.add(null); - seed.add(new OpenCanvasInstance("inst-2", "ext", null, "canvas-b", null, null, null, null)); + seed.add(new OpenCanvasInstance("inst-2", "ext", null, "canvas-b", null, null, null, null, null)); session.setOpenCanvases(seed); @@ -195,8 +195,8 @@ void resumeSessionResponseDeserializesOpenCanvases() throws Exception { private static SessionCanvasOpenedEvent openedEvent(String instanceId, String canvasId) { var event = new SessionCanvasOpenedEvent(); - event.setData(new SessionCanvasOpenedEventData(instanceId, "ext-id", "Ext Name", canvasId, "Title", "ok", null, - null)); + event.setData(new SessionCanvasOpenedEventData(instanceId, "ext-id", "Ext Name", canvasId, null, "Title", "ok", + null, null)); return event; } diff --git a/java/src/test/java/com/github/copilot/SessionConfigE2ETest.java b/java/src/test/java/com/github/copilot/SessionConfigE2ETest.java index dbae0fe9f9..925fd6d873 100644 --- a/java/src/test/java/com/github/copilot/SessionConfigE2ETest.java +++ b/java/src/test/java/com/github/copilot/SessionConfigE2ETest.java @@ -4,10 +4,16 @@ package com.github.copilot; +import static com.github.copilot.CopilotRequestTestSupport.SYNTHETIC_TEXT; +import static com.github.copilot.CopilotRequestTestSupport.newLlmClient; +import static com.github.copilot.CopilotRequestTestSupport.setupCapiAuth; import static org.junit.jupiter.api.Assertions.*; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -16,6 +22,10 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.generated.rpc.SessionLimitsConfig; +import com.github.copilot.rpc.BlobAttachment; import com.github.copilot.rpc.MessageOptions; import com.github.copilot.rpc.PermissionHandler; import com.github.copilot.rpc.ProviderConfig; @@ -27,6 +37,8 @@ */ public class SessionConfigE2ETest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static E2ETestContext ctx; @BeforeAll @@ -150,6 +162,258 @@ void testShouldUseProviderModelIdAsWireModel() throws Exception { } } + @Test + void testShouldApplySessionLimitsOnCreate() throws Exception { + ctx.configureForTest("session_config", "should_apply_session_limits_on_create"); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session = client + .createSession(new SessionConfig().setSessionLimits(new SessionLimitsConfig(30.0)) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(); + + try { + Map exchange = sendAndGetNextExchange(session, + "Acknowledge the current session limits."); + + assertSessionLimitsStatus(exchange, "30 AI credits"); + } finally { + session.close(); + } + } + } + + @Test + void testShouldApplySessionLimitsOnResume() throws Exception { + ctx.configureForTest("session_config", "should_apply_session_limits_on_resume"); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session1 = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); + CopilotSession session2 = client.resumeSession(session1.getSessionId(), + new ResumeSessionConfig().setSessionLimits(new SessionLimitsConfig(30.0)) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(); + + try { + Map exchange = sendAndGetNextExchange(session2, + "Acknowledge the current session limits."); + + assertSessionLimitsStatus(exchange, "30 AI credits"); + } finally { + session2.close(); + session1.close(); + } + } + } + + @Test + void testShouldApplyExcludedBuiltInAgentsOnCreate() throws Exception { + ctx.configureForTest("session_config", "should_apply_excluded_built_in_agents_on_create"); + + final String excludedAgent = "explore"; + final String prompt = "What is 1+1?"; + + try (CopilotClient client = ctx.createClient()) { + CopilotSession baselineSession = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); + try { + Map baselineExchange = sendAndGetNextExchange(baselineSession, prompt); + assertTrue(getTaskAgentTypes(baselineExchange).contains(excludedAgent)); + } finally { + baselineSession.close(); + } + + CopilotSession excludedSession = client + .createSession(new SessionConfig().setExcludedBuiltInAgents(List.of(excludedAgent)) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(); + + try { + List agentTypes = getTaskAgentTypes(sendAndGetNextExchange(excludedSession, prompt)); + + assertFalse(agentTypes.isEmpty(), "Expected task tool agent types"); + assertFalse(agentTypes.contains(excludedAgent), "Expected excluded built-in agent to be omitted"); + } finally { + excludedSession.close(); + } + } + } + + @Test + void testShouldApplyExcludedBuiltInAgentsOnResume() throws Exception { + ctx.configureForTest("session_config", "should_apply_excluded_built_in_agents_on_resume"); + + final String excludedAgent = "explore"; + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session1 = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); + CopilotSession session2 = client.resumeSession(session1.getSessionId(), + new ResumeSessionConfig().setExcludedBuiltInAgents(List.of(excludedAgent)) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(); + + try { + List agentTypes = getTaskAgentTypes(sendAndGetNextExchange(session2, "What is 1+1?")); + + assertFalse(agentTypes.isEmpty(), "Expected task tool agent types"); + assertFalse(agentTypes.contains(excludedAgent), "Expected excluded built-in agent to be omitted"); + } finally { + session2.close(); + session1.close(); + } + } + } + + @Test + void testShouldEnableCitationsForAnthropicFileAttachmentsOnCreate() throws Exception { + setupCapiAuth(ctx); + var handler = new CopilotRequestTestSupport.RecordingRequestHandler(SYNTHETIC_TEXT); + + try (CopilotClient client = newLlmClient(ctx, handler)) { + CopilotSession session = client.createSession(new SessionConfig().setModel("claude-sonnet-4.5") + .setEnableCitations(true).setProvider(createAnthropicProvider()) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); + + try { + session.sendAndWait(new MessageOptions().setPrompt("Summarize the attached PDF with citations enabled.") + .setAttachments(List.of(createPdfAttachment()))).get(60, TimeUnit.SECONDS); + + assertAnthropicDocumentCitationsEnabled(singleInferenceRequestBody(handler)); + } finally { + session.close(); + } + } + } + + @Test + void testShouldEnableCitationsForAnthropicFileAttachmentsOnResume() throws Exception { + setupCapiAuth(ctx); + var handler = new CopilotRequestTestSupport.RecordingRequestHandler(SYNTHETIC_TEXT); + + try (CopilotClient client = newLlmClient(ctx, handler)) { + CopilotSession session1 = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(); + CopilotSession session2 = client.resumeSession(session1.getSessionId(), + new ResumeSessionConfig().setModel("claude-sonnet-4.5").setEnableCitations(true) + .setProvider(createAnthropicProvider()) + .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)) + .get(); + + try { + session2.sendAndWait( + new MessageOptions().setPrompt("Summarize the attached PDF with citations enabled.") + .setAttachments(List.of(createPdfAttachment()))) + .get(60, TimeUnit.SECONDS); + + assertAnthropicDocumentCitationsEnabled(singleInferenceRequestBody(handler)); + } finally { + session2.close(); + session1.close(); + } + } + } + + private Map sendAndGetNextExchange(CopilotSession session, String prompt) throws Exception { + int existingCount = ctx.getExchanges().size(); + session.sendAndWait(new MessageOptions().setPrompt(prompt)).get(60, TimeUnit.SECONDS); + + List> exchanges = ctx.getExchanges(); + assertTrue(exchanges.size() > existingCount, "Expected at least one new exchange"); + return exchanges.get(existingCount); + } + + private static void assertSessionLimitsStatus(Map exchange, String expectedRemaining) { + String content = null; + for (Object message : getRequestMessages(exchange)) { + if (message instanceof Map messageMap && "user".equals(messageMap.get("role"))) { + Object messageContent = messageMap.get("content"); + if (messageContent instanceof String text && text.contains("")) { + content = text; + break; + } + } + } + + assertNotNull(content, "Expected session limits status user message"); + assertTrue(content.contains("Remaining session limits: " + expectedRemaining + ".")); + assertTrue(content.contains("Be frugal; avoid optional exploration and unnecessary tool calls.")); + } + + private static List getTaskAgentTypes(Map exchange) { + Object toolsObj = getRequest(exchange).get("tools"); + assertInstanceOf(List.class, toolsObj, "Expected request tools"); + + JsonNode parameters = null; + for (Object toolObj : (List) toolsObj) { + if (toolObj instanceof Map toolMap && toolMap.get("function") instanceof Map functionMap + && "task".equals(functionMap.get("name"))) { + parameters = MAPPER.valueToTree(functionMap.get("parameters")); + break; + } + } + + assertNotNull(parameters, "Expected task tool parameters"); + JsonNode enumValues = parameters.path("properties").path("agent_type").path("enum"); + assertTrue(enumValues.isArray(), "Expected task agent_type enum"); + + List values = new ArrayList<>(); + enumValues.forEach(value -> { + if (value.isTextual()) { + values.add(value.asText()); + } + }); + return values; + } + + private static List getRequestMessages(Map exchange) { + Object messages = getRequest(exchange).get("messages"); + assertInstanceOf(List.class, messages, "Expected request messages"); + return (List) messages; + } + + private static Map getRequest(Map exchange) { + Object request = exchange.get("request"); + assertInstanceOf(Map.class, request, "Expected exchange request"); + return (Map) request; + } + + private static BlobAttachment createPdfAttachment() { + String pdfText = "%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n"; + return new BlobAttachment() + .setData(Base64.getEncoder().encodeToString(pdfText.getBytes(StandardCharsets.US_ASCII))) + .setDisplayName("citation-source.pdf").setMimeType("application/pdf"); + } + + private static ProviderConfig createAnthropicProvider() { + return new ProviderConfig().setType("anthropic").setBaseUrl("https://anthropic-citations.invalid/v1") + .setApiKey("test-provider-key").setModelId("claude-sonnet-4.5").setWireModel("claude-sonnet-4.5"); + } + + private static String singleInferenceRequestBody(CopilotRequestTestSupport.RecordingRequestHandler handler) { + List requests = handler.inferenceRequests(); + assertEquals(1, requests.size(), "Expected one intercepted inference request"); + return requests.get(0).body(); + } + + private static void assertAnthropicDocumentCitationsEnabled(String requestBody) throws Exception { + JsonNode root = MAPPER.readTree(requestBody); + List documentBlocks = new ArrayList<>(); + for (JsonNode message : root.path("messages")) { + for (JsonNode block : message.path("content")) { + if ("document".equals(block.path("type").asText())) { + documentBlocks.add(block); + } + } + } + + assertEquals(1, documentBlocks.size(), "Expected one Anthropic document block"); + JsonNode documentBlock = documentBlocks.get(0); + assertEquals("citation-source.pdf", documentBlock.path("title").asText()); + assertTrue(documentBlock.path("citations").path("enabled").asBoolean(false)); + } + @SuppressWarnings("unchecked") private static String getSystemMessage(Map exchange) { // The exchange structure is: { request: { messages: [...] }, response: ..., diff --git a/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java b/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java index 3ca56b817d..1cf3ceff1f 100644 --- a/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java +++ b/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java @@ -180,7 +180,7 @@ void testHandlerReceivesCorrectEventData() { SessionStartEvent startEvent = createSessionStartEvent(); startEvent.setData(new SessionStartEvent.SessionStartEventData("my-session-123", null, null, null, null, null, - null, null, null, null, null, null, null)); + null, null, null, null, null, null, null, null, null)); dispatchEvent(startEvent); AssistantMessageEvent msgEvent = createAssistantMessageEvent("Test content"); @@ -857,7 +857,7 @@ private SessionStartEvent createSessionStartEvent() { private SessionStartEvent createSessionStartEvent(String sessionId) { var event = new SessionStartEvent(); var data = new SessionStartEvent.SessionStartEventData(sessionId, null, null, null, null, null, null, null, - null, null, null, null, null); + null, null, null, null, null, null, null); event.setData(data); return event; } @@ -865,7 +865,7 @@ private SessionStartEvent createSessionStartEvent(String sessionId) { private AssistantMessageEvent createAssistantMessageEvent(String content) { var event = new AssistantMessageEvent(); var data = new AssistantMessageEvent.AssistantMessageEventData(null, null, content, null, null, null, null, - null, null, null, null, null, null, null, null, null, null); + null, null, null, null, null, null, null, null, null, null, null, null); event.setData(data); return event; } diff --git a/java/src/test/java/com/github/copilot/SessionRequestBuilderTest.java b/java/src/test/java/com/github/copilot/SessionRequestBuilderTest.java index 5849a6b884..bf192e98a3 100644 --- a/java/src/test/java/com/github/copilot/SessionRequestBuilderTest.java +++ b/java/src/test/java/com/github/copilot/SessionRequestBuilderTest.java @@ -13,6 +13,7 @@ import org.junit.jupiter.api.Test; import com.fasterxml.jackson.databind.JsonNode; +import com.github.copilot.generated.rpc.SessionLimitsConfig; import com.github.copilot.rpc.AutoModeSwitchResponse; import com.github.copilot.rpc.CloudSessionOptions; import com.github.copilot.rpc.CloudSessionRepository; @@ -160,6 +161,19 @@ void testBuildCreateRequestForwardsExplicitMcpOAuthTokenStorage() { assertEquals("persistent", request.getMcpOAuthTokenStorage()); } + @Test + void testBuildCreateRequestForwardsSessionPolicyOptions() { + var sessionLimits = new SessionLimitsConfig(30.0); + var config = new SessionConfig().setExcludedBuiltInAgents(List.of("explore")).setEnableCitations(true) + .setSessionLimits(sessionLimits); + + CreateSessionRequest request = SessionRequestBuilder.buildCreateRequest(config, "session-policy"); + + assertEquals(List.of("explore"), request.getExcludedBuiltInAgents()); + assertTrue(request.getEnableCitations()); + assertSame(sessionLimits, request.getSessionLimits()); + } + @Test void testBuildCreateRequestNullConfigHasNullMcpOAuthTokenStorage() { CreateSessionRequest request = SessionRequestBuilder.buildCreateRequest(null); @@ -324,6 +338,19 @@ void testBuildResumeRequestForwardsExplicitMcpOAuthTokenStorage() { assertEquals("persistent", request.getMcpOAuthTokenStorage()); } + @Test + void testBuildResumeRequestForwardsSessionPolicyOptions() { + var sessionLimits = new SessionLimitsConfig(30.0); + var config = new ResumeSessionConfig().setExcludedBuiltInAgents(List.of("explore")).setEnableCitations(true) + .setSessionLimits(sessionLimits); + + ResumeSessionRequest request = SessionRequestBuilder.buildResumeRequest("sid-policy", config); + + assertEquals(List.of("explore"), request.getExcludedBuiltInAgents()); + assertTrue(request.getEnableCitations()); + assertSame(sessionLimits, request.getSessionLimits()); + } + @Test void testBuildResumeRequestNullConfigHasNullMcpOAuthTokenStorage() { ResumeSessionRequest request = SessionRequestBuilder.buildResumeRequest("sid-14", null); diff --git a/java/src/test/java/com/github/copilot/SubagentHooksE2ETest.java b/java/src/test/java/com/github/copilot/SubagentHooksE2ETest.java new file mode 100644 index 0000000000..c2ad45ff24 --- /dev/null +++ b/java/src/test/java/com/github/copilot/SubagentHooksE2ETest.java @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.InputStream; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +import com.github.copilot.rpc.CopilotClientOptions; +import com.github.copilot.rpc.MessageOptions; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.PostToolUseHookOutput; +import com.github.copilot.rpc.PreToolUseHookOutput; +import com.github.copilot.rpc.SessionConfig; +import com.github.copilot.rpc.SessionHooks; + +public class SubagentHooksE2ETest { + + private static final String SNAPSHOT_NAME = "should_invoke_pretooluse_and_posttooluse_hooks_for_sub_agent_tool_calls"; + + @Test + void shouldInvokePreToolUseAndPostToolUseHooksForSubAgentToolCalls() throws Exception { + try (E2ETestContext ctx = E2ETestContext.create()) { + ctx.configureForTest("subagent_hooks", SNAPSHOT_NAME); + + ConcurrentLinkedQueue hookLog = new ConcurrentLinkedQueue<>(); + RecordingForwardingRequestHandler requestHandler = new RecordingForwardingRequestHandler(); + HashMap env = new HashMap<>(ctx.getEnvironment()); + env.put("COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS", "true"); + + try (CopilotClient client = ctx + .createClient(new CopilotClientOptions().setEnvironment(env).setRequestHandler(requestHandler))) { + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setHooks(new SessionHooks().setOnPreToolUse((input, invocation) -> { + hookLog.add(new HookEntry("pre", input.getToolName(), input.getSessionId())); + return CompletableFuture.completedFuture(PreToolUseHookOutput.allow()); + }).setOnPostToolUse((input, invocation) -> { + hookLog.add(new HookEntry("post", input.getToolName(), input.getSessionId())); + return CompletableFuture.completedFuture((PostToolUseHookOutput) null); + }))) + .get(); + try { + Files.writeString(ctx.getWorkDir().resolve("subagent-test.txt"), "Hello from subagent test!"); + session.sendAndWait(new MessageOptions() + .setPrompt("Use the task tool to spawn an explore agent that reads the file " + + "subagent-test.txt in the current directory and reports its contents. " + + "You must use the task tool.")) + .get(120, TimeUnit.SECONDS); + + HookEntry taskPre = hookLog.stream() + .filter(h -> h.kind().equals("pre") && h.toolName().equals("task")).findFirst() + .orElse(null); + assertNotNull(taskPre, "preToolUse should fire for the parent's 'task' tool call"); + + List viewPre = hookLog.stream() + .filter(h -> h.kind().equals("pre") && h.toolName().equals("view")).toList(); + List viewPost = hookLog.stream() + .filter(h -> h.kind().equals("post") && h.toolName().equals("view")).toList(); + assertFalse(viewPre.isEmpty(), "preToolUse should fire for the sub-agent's 'view' tool call"); + assertFalse(viewPost.isEmpty(), "postToolUse should fire for the sub-agent's 'view' tool call"); + assertNotEquals(taskPre.sessionId(), viewPre.get(0).sessionId(), + "Sub-agent tool hooks should have a different sessionId than parent tool hooks"); + assertSubagentRequestMetadata(requestHandler.inferenceRequests()); + } finally { + session.close(); + } + } + } + } + + private static void assertSubagentRequestMetadata(List records) { + assertFalse(records.isEmpty(), "request handler should observe inference requests"); + RequestRecord subagentRequest = records.stream() + .filter(r -> r.parentAgentId() != null && !r.parentAgentId().isEmpty()).findFirst().orElse(null); + assertNotNull(subagentRequest, "sub-agent inference request should carry a parentAgentId"); + assertFalse(subagentRequest.agentId() == null || subagentRequest.agentId().isEmpty(), + "sub-agent inference request should carry an agentId"); + assertFalse(subagentRequest.interactionType() == null || subagentRequest.interactionType().isEmpty(), + "sub-agent inference request should carry an interactionType"); + assertNotEquals(subagentRequest.parentAgentId(), subagentRequest.agentId()); + } + + private static boolean isInferenceUrl(String url) { + String u = url.toLowerCase(); + return u.endsWith("/chat/completions") || u.endsWith("/responses") || u.endsWith("/v1/messages") + || u.endsWith("/messages"); + } + + private record HookEntry(String kind, String toolName, String sessionId) { + } + + private record RequestRecord(String url, String agentId, String parentAgentId, String interactionType) { + } + + private static final class RecordingForwardingRequestHandler extends CopilotRequestHandler { + private final ConcurrentLinkedQueue records = new ConcurrentLinkedQueue<>(); + + List inferenceRequests() { + return records.stream().filter(r -> isInferenceUrl(r.url())).toList(); + } + + @Override + protected HttpResponse sendRequest(HttpRequest request, CopilotRequestContext ctx) + throws Exception { + records.add(new RequestRecord(request.uri().toString(), ctx.agentId(), ctx.parentAgentId(), + ctx.interactionType())); + return super.sendRequest(request, ctx); + } + } +} diff --git a/java/src/test/java/com/github/copilot/ToolDefinitionTest.java b/java/src/test/java/com/github/copilot/ToolDefinitionTest.java index 614e6ab4fa..66c9f9ec86 100644 --- a/java/src/test/java/com/github/copilot/ToolDefinitionTest.java +++ b/java/src/test/java/com/github/copilot/ToolDefinitionTest.java @@ -59,4 +59,73 @@ void testDeferNeverIsSerialized() throws Exception { assertEquals("never", json.get("defer").asText()); } + + @Test + void testMetadataIsSerialized() throws Exception { + Map metadata = Map.of("github.com/copilot:safeForTelemetry", + Map.of("name", true, "inputsNames", false)); + ToolDefinition tool = ToolDefinition.createWithMetadata("my_tool", "A tool", schema(), + invocation -> CompletableFuture.completedFuture("ok"), metadata); + + ObjectNode json = (ObjectNode) MAPPER.readTree(MAPPER.writeValueAsString(tool)); + + assertTrue(json.has("metadata")); + assertTrue(json.get("metadata").has("github.com/copilot:safeForTelemetry")); + } + + @Test + void testMetadataOmittedWhenNull() throws Exception { + ToolDefinition tool = ToolDefinition.create("my_tool", "A tool", schema(), + invocation -> CompletableFuture.completedFuture("ok")); + + ObjectNode json = (ObjectNode) MAPPER.readTree(MAPPER.writeValueAsString(tool)); + + assertFalse(json.has("metadata")); + } + + @Test + void testSevenArgConstructorLeavesMetadataNull() throws Exception { + ToolDefinition tool = new ToolDefinition("my_tool", "A tool", schema(), + invocation -> CompletableFuture.completedFuture("ok"), null, null, null); + + assertNull(tool.metadata()); + + ObjectNode json = (ObjectNode) MAPPER.readTree(MAPPER.writeValueAsString(tool)); + + assertFalse(json.has("metadata")); + } + + @Test + void testMetadataCopyMethodSerializes() throws Exception { + Map metadata = Map.of("github.com/copilot:safeForTelemetry", + Map.of("name", true, "inputsNames", false)); + ToolDefinition tool = ToolDefinition + .create("my_tool", "A tool", schema(), invocation -> CompletableFuture.completedFuture("ok")) + .metadata(metadata); + + assertEquals(metadata, tool.metadata()); + + ObjectNode json = (ObjectNode) MAPPER.readTree(MAPPER.writeValueAsString(tool)); + + assertTrue(json.get("metadata").has("github.com/copilot:safeForTelemetry")); + } + + @Test + void testChainingFlagsPreservesMetadata() throws Exception { + Map metadata = Map.of("github.com/copilot:safeForTelemetry", Map.of("name", true)); + + ToolDefinition metadataFirst = ToolDefinition + .create("my_tool", "A tool", schema(), invocation -> CompletableFuture.completedFuture("ok")) + .metadata(metadata).overridesBuiltInTool(true).skipPermission(true).defer(ToolDefer.NEVER); + + ToolDefinition flagsFirst = ToolDefinition + .create("my_tool", "A tool", schema(), invocation -> CompletableFuture.completedFuture("ok")) + .overridesBuiltInTool(true).skipPermission(true).defer(ToolDefer.NEVER).metadata(metadata); + + assertEquals(metadata, metadataFirst.metadata()); + assertEquals(metadata, flagsFirst.metadata()); + assertEquals(Boolean.TRUE, flagsFirst.overridesBuiltInTool()); + assertEquals(Boolean.TRUE, flagsFirst.skipPermission()); + assertEquals(ToolDefer.NEVER, flagsFirst.defer()); + } } diff --git a/java/src/test/java/com/github/copilot/ToolResultObjectSerializationTest.java b/java/src/test/java/com/github/copilot/ToolResultObjectSerializationTest.java new file mode 100644 index 0000000000..3f08cae943 --- /dev/null +++ b/java/src/test/java/com/github/copilot/ToolResultObjectSerializationTest.java @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.jupiter.api.Test; + +import com.github.copilot.rpc.ToolResultObject; + +/** + * Verifies JSON (de)serialization of the {@code toolReferences} field on + * {@link ToolResultObject}, including that it is omitted when {@code null} (via + * {@code @JsonInclude(NON_NULL)}) and preserved by the backward-compatible + * six-argument constructor. + */ +class ToolResultObjectSerializationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void serializesToolReferences() { + var result = new ToolResultObject("success", "found 2 tools", null, null, null, null, + List.of("get_weather", "check_status")); + + JsonNode node = MAPPER.valueToTree(result); + + assertEquals("found 2 tools", node.get("textResultForLlm").asText()); + JsonNode refs = node.get("toolReferences"); + assertNotNull(refs); + assertTrue(refs.isArray()); + assertEquals(2, refs.size()); + assertEquals("get_weather", refs.get(0).asText()); + assertEquals("check_status", refs.get(1).asText()); + } + + @Test + void omitsToolReferencesWhenNull() { + JsonNode node = MAPPER.valueToTree(ToolResultObject.success("ok")); + + assertFalse(node.has("toolReferences")); + } + + @Test + void sixArgConstructorLeavesToolReferencesNull() { + var result = new ToolResultObject("success", "ok", null, null, null, null); + + assertNull(result.toolReferences()); + assertFalse(MAPPER.valueToTree(result).has("toolReferences")); + } + + @Test + void deserializesToolReferences() throws Exception { + String json = "{\"resultType\":\"success\",\"textResultForLlm\":\"x\"," + + "\"toolReferences\":[\"alpha\",\"beta\"]}"; + + ToolResultObject result = MAPPER.readValue(json, ToolResultObject.class); + + assertEquals(List.of("alpha", "beta"), result.toolReferences()); + } +} diff --git a/java/src/test/java/com/github/copilot/ToolResultsTest.java b/java/src/test/java/com/github/copilot/ToolResultsTest.java index 54216d9216..8278fdf28f 100644 --- a/java/src/test/java/com/github/copilot/ToolResultsTest.java +++ b/java/src/test/java/com/github/copilot/ToolResultsTest.java @@ -68,7 +68,7 @@ void testShouldHandleToolResultWithRejectedResultType() throws Exception { toolHandlerCalled[0] = true; return CompletableFuture.completedFuture(new ToolResultObject("rejected", "Deployment rejected: policy violation - production deployments require approval", null, - null, null, null)); + null, null, null, null)); }); try (CopilotClient client = ctx.createClient()) { @@ -116,7 +116,7 @@ void testShouldHandleToolResultWithDeniedResultType() throws Exception { (invocation) -> { toolHandlerCalled[0] = true; return CompletableFuture.completedFuture(new ToolResultObject("denied", - "Access denied: insufficient permissions to read secrets", null, null, null, null)); + "Access denied: insufficient permissions to read secrets", null, null, null, null, null)); }); try (CopilotClient client = ctx.createClient()) { diff --git a/java/src/test/java/com/github/copilot/e2e/ErgonomicTestTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/e2e/ErgonomicTestTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..56b8b281e6 --- /dev/null +++ b/java/src/test/java/com/github/copilot/e2e/ErgonomicTestTools$$CopilotToolMeta.java @@ -0,0 +1,68 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output. +package com.github.copilot.e2e; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class ErgonomicTestTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(ErgonomicTestTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition("set_current_phase", "Sets the current phase of the agent", + Map.of("type", "object", "properties", + Map.ofEntries(Map.entry("phase", + (Map) (Map) withMeta(Map.of("type", "string"), + "The phase to transition to", null))), + "required", List.of("phase")), + invocation -> { + Map args = invocation.getArguments(); + String phase = (String) args.get("phase"); + return CompletableFuture.completedFuture(instance.setCurrentPhase(phase)); + }, null, null, null, null), + new ToolDefinition( + "search_items", "Search for items by keyword", Map + .of("type", "object", "properties", + Map.ofEntries(Map.entry("keyword", + (Map) (Map) withMeta(Map.of("type", "string"), + "Search keyword", null))), + "required", List.of("keyword")), + invocation -> { + Map args = invocation.getArguments(); + String keyword = (String) args.get("keyword"); + return CompletableFuture.completedFuture(instance.searchItems(keyword)); + }, null, null, null, null), + new ToolDefinition("get_status", "Returns the current status", + Map.of("type", "object", "properties", Map.of(), "required", List.of()), invocation -> { + return CompletableFuture.completedFuture(instance.getStatus()); + }, null, null, null, null), + new ToolDefinition("combine_values", "Combines two values into a single string", Map.of( + "type", "object", "properties", Map + .ofEntries( + Map.entry("value1", + (Map) (Map) withMeta(Map.of("type", "string"), + "First value", null)), + Map.entry("value2", + (Map) (Map) withMeta(Map.of("type", "string"), + "Second value", null))), + "required", List.of("value1", "value2")), invocation -> { + Map args = invocation.getArguments(); + String value1 = (String) args.get("value1"); + String value2 = (String) args.get("value2"); + return CompletableFuture.completedFuture(instance.combineValues(value1, value2)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/e2e/ErgonomicTestTools.java b/java/src/test/java/com/github/copilot/e2e/ErgonomicTestTools.java new file mode 100644 index 0000000000..15b2c087ab --- /dev/null +++ b/java/src/test/java/com/github/copilot/e2e/ErgonomicTestTools.java @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.e2e; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Tool fixture for the ergonomic {@code @CopilotTool} E2E integration test. + * + *

+ * This class exercises the annotation-based tool definition API, producing + * identical wire-level tool schemas to the low-level + * {@code ToolDefinition.create()} API. + */ +class ErgonomicTestTools { + + String currentPhase; + + @CopilotTool("Sets the current phase of the agent") + public String setCurrentPhase(@CopilotToolParam("The phase to transition to") String phase) { + currentPhase = phase; + return "Phase set to " + phase; + } + + @CopilotTool("Search for items by keyword") + public String searchItems(@CopilotToolParam("Search keyword") String keyword) { + return "Found: " + keyword + " -> item_alpha, item_beta"; + } + + @CopilotTool("Returns the current status") + public String getStatus() { + return "Status: OK"; + } + + @CopilotTool("Combines two values into a single string") + public String combineValues(@CopilotToolParam("First value") String value1, + @CopilotToolParam("Second value") String value2) { + return "combined: " + value1 + " + " + value2; + } +} diff --git a/java/src/test/java/com/github/copilot/e2e/ErgonomicToolDefinitionIT.java b/java/src/test/java/com/github/copilot/e2e/ErgonomicToolDefinitionIT.java new file mode 100644 index 0000000000..412acd4c46 --- /dev/null +++ b/java/src/test/java/com/github/copilot/e2e/ErgonomicToolDefinitionIT.java @@ -0,0 +1,245 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.e2e; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.github.copilot.CopilotClient; +import com.github.copilot.CopilotSession; +import com.github.copilot.E2ETestContext; +import com.github.copilot.generated.AssistantMessageEvent; +import com.github.copilot.rpc.MessageOptions; +import com.github.copilot.rpc.PermissionHandler; +import com.github.copilot.rpc.SessionConfig; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.rpc.ToolSet; +import com.github.copilot.tool.Param; + +/** + * Failsafe integration test for the ergonomic {@code @CopilotTool} + + * {@code ToolDefinition.fromObject()} API. + * + *

+ * This test proves that the ergonomic annotation-based API produces identical + * wire behavior to the low-level {@code ToolDefinition.create()} API tested in + * {@code LowLevelToolDefinitionIT}. + * + * @see Snapshot: tools/ergonomic_tool_definition + */ +class ErgonomicToolDefinitionIT { + + private static E2ETestContext ctx; + + @BeforeAll + static void setup() throws Exception { + ctx = E2ETestContext.create(); + } + + @AfterAll + static void teardown() throws Exception { + if (ctx != null) { + ctx.close(); + } + } + + @Test + void ergonomicToolDefinition() throws Exception { + ctx.configureForTest("tools", "ergonomic_tool_definition"); + + ErgonomicTestTools tools = new ErgonomicTestTools(); + List toolDefs = ToolDefinition.fromObject(tools); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setAvailableTools(new ToolSet().addCustom("*").addBuiltIn("web_fetch")).setTools(toolDefs)) + .get(30, TimeUnit.SECONDS); + + try { + AssistantMessageEvent response = session.sendAndWait(new MessageOptions().setPrompt( + "First, set the current phase to 'analyzing'. Then search for items with keyword 'copilot'. Report the phase and search results."), + 60_000).get(90, TimeUnit.SECONDS); + + assertNotNull(response, "Expected a response from the assistant"); + String content = response.getData().content().toLowerCase(); + assertTrue(content.contains("analyzing"), + "Response should contain the updated phase: " + response.getData().content()); + assertTrue(content.contains("item_alpha") || content.contains("item_beta"), + "Response should contain search results: " + response.getData().content()); + assertTrue("analyzing".equals(tools.currentPhase), + "Expected currentPhase to be 'analyzing' but was: " + tools.currentPhase); + } finally { + session.close(); + } + } + } + + @Test + void ergonomicToolArity0() throws Exception { + ctx.configureForTest("tools", "ergonomic_tool_arity0"); + + ErgonomicTestTools tools = new ErgonomicTestTools(); + List toolDefs = ToolDefinition.fromObject(tools); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setAvailableTools(new ToolSet().addCustom("*")).setTools(toolDefs)) + .get(30, TimeUnit.SECONDS); + + try { + AssistantMessageEvent response = session + .sendAndWait(new MessageOptions().setPrompt("Call get_status and tell me the result."), 60_000) + .get(90, TimeUnit.SECONDS); + + assertNotNull(response, "Expected a response from the assistant"); + String content = response.getData().content().toLowerCase(); + assertTrue(content.contains("ok"), + "Response should mention the status: " + response.getData().content()); + } finally { + session.close(); + } + } + } + + @Test + void ergonomicToolArity2() throws Exception { + ctx.configureForTest("tools", "ergonomic_tool_arity2"); + + ErgonomicTestTools tools = new ErgonomicTestTools(); + List toolDefs = ToolDefinition.fromObject(tools); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setAvailableTools(new ToolSet().addCustom("*")).setTools(toolDefs)) + .get(30, TimeUnit.SECONDS); + + try { + AssistantMessageEvent response = session.sendAndWait( + new MessageOptions().setPrompt( + "Call combine_values with 'alpha' and 'beta', then report the combined result."), + 60_000).get(90, TimeUnit.SECONDS); + + assertNotNull(response, "Expected a response from the assistant"); + String content = response.getData().content().toLowerCase(); + assertTrue(content.contains("alpha") && content.contains("beta"), + "Response should contain the combined values: " + response.getData().content()); + } finally { + session.close(); + } + } + } + + @Test + void lambdaToolArity0() throws Exception { + ctx.configureForTest("tools", "ergonomic_tool_arity0"); + + ToolDefinition getStatus = ToolDefinition.from("get_status", "Returns the current status", () -> "Status: OK"); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setAvailableTools(new ToolSet().addCustom("*")).setTools(List.of(getStatus))) + .get(30, TimeUnit.SECONDS); + + try { + AssistantMessageEvent response = session + .sendAndWait(new MessageOptions().setPrompt("Call get_status and tell me the result."), 60_000) + .get(90, TimeUnit.SECONDS); + + assertNotNull(response, "Expected a response from the assistant"); + String content = response.getData().content().toLowerCase(); + assertTrue(content.contains("ok"), + "Response should mention the status: " + response.getData().content()); + } finally { + session.close(); + } + } + } + + @Test + void lambdaToolArity2() throws Exception { + ctx.configureForTest("tools", "ergonomic_tool_arity2"); + + ToolDefinition combineValues = ToolDefinition.from("combine_values", "Combines two values into a single string", + Param.of(String.class, "value1", "First value"), Param.of(String.class, "value2", "Second value"), + (v1, v2) -> "combined: " + v1 + " + " + v2); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setAvailableTools(new ToolSet().addCustom("*")).setTools(List.of(combineValues))) + .get(30, TimeUnit.SECONDS); + + try { + AssistantMessageEvent response = session.sendAndWait( + new MessageOptions().setPrompt( + "Call combine_values with 'alpha' and 'beta', then report the combined result."), + 60_000).get(90, TimeUnit.SECONDS); + + assertNotNull(response, "Expected a response from the assistant"); + String content = response.getData().content().toLowerCase(); + assertTrue(content.contains("alpha") && content.contains("beta"), + "Response should contain the combined values: " + response.getData().content()); + } finally { + session.close(); + } + } + } + + @Test + void lambdaToolDefinition() throws Exception { + ctx.configureForTest("tools", "ergonomic_tool_definition"); + + class LambdaTools { + String currentPhase; + } + LambdaTools tools = new LambdaTools(); + + ToolDefinition setCurrentPhase = ToolDefinition.from("set_current_phase", "Sets the current phase of the agent", + Param.of(String.class, "phase", "The phase to transition to"), phase -> { + tools.currentPhase = phase; + return "Phase set to " + phase; + }); + + ToolDefinition searchItems = ToolDefinition.from("search_items", "Search for items by keyword", + Param.of(String.class, "keyword", "Search keyword"), + keyword -> "Found: " + keyword + " -> item_alpha, item_beta"); + + try (CopilotClient client = ctx.createClient()) { + CopilotSession session = client + .createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL) + .setAvailableTools(new ToolSet().addCustom("*").addBuiltIn("web_fetch")) + .setTools(List.of(setCurrentPhase, searchItems))) + .get(30, TimeUnit.SECONDS); + + try { + AssistantMessageEvent response = session.sendAndWait(new MessageOptions().setPrompt( + "First, set the current phase to 'analyzing'. Then search for items with keyword 'copilot'. Report the phase and search results."), + 60_000).get(90, TimeUnit.SECONDS); + + assertNotNull(response, "Expected a response from the assistant"); + String content = response.getData().content().toLowerCase(); + assertTrue(content.contains("analyzing"), + "Response should contain the updated phase: " + response.getData().content()); + assertTrue(content.contains("item_alpha") || content.contains("item_beta"), + "Response should contain search results: " + response.getData().content()); + assertTrue("analyzing".equals(tools.currentPhase), + "Expected currentPhase to be 'analyzing' but was: " + tools.currentPhase); + } finally { + session.close(); + } + } + } +} diff --git a/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java b/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java index b5e83f17dc..2b6b0164d5 100644 --- a/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java +++ b/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java @@ -321,11 +321,12 @@ void sessionModelGetCurrentParams_record() { @Test void sessionModelSwitchToParams_record() { - var params = new SessionModelSwitchToParams("sess-32", "claude-sonnet-4.5", "high", null, null, null); + var params = new SessionModelSwitchToParams("sess-32", "claude-sonnet-4.5", "high", null, null, null, null); assertEquals("sess-32", params.sessionId()); assertEquals("claude-sonnet-4.5", params.modelId()); assertEquals("high", params.reasoningEffort()); assertNull(params.reasoningSummary()); + assertNull(params.verbosity()); assertNull(params.modelCapabilities()); } @@ -799,11 +800,12 @@ void mcpDiscoverResult_nested() { @Test void modelsListResult_nested() { - var supports = new ModelCapabilitiesSupports(true, false); + var supports = new ModelCapabilitiesSupports(true, false, null); var limits = new ModelCapabilitiesLimits(100000L, 8192L, 128000L, null); var capabilities = new ModelCapabilities(supports, limits); var policy = new ModelPolicy(ModelPolicyState.ENABLED, null); - var billing = new ModelBilling(1.0, null); + var promo = new ModelBillingPromo("summer-2026", 25.0, "2026-08-01T00:00:00Z", "Summer discount"); + var billing = new ModelBilling(1.0, null, null, promo); var modelItem = new Model("gpt-5", "GPT-5", capabilities, policy, billing, null, null, null, null); var result = new ModelsListResult(List.of(modelItem)); @@ -815,6 +817,10 @@ void modelsListResult_nested() { assertEquals(100000L, result.models().get(0).capabilities().limits().maxPromptTokens()); assertEquals(ModelPolicyState.ENABLED, result.models().get(0).policy().state()); assertEquals(Double.valueOf(1.0), result.models().get(0).billing().multiplier()); + assertEquals("summer-2026", result.models().get(0).billing().promo().id()); + assertEquals(Double.valueOf(25.0), result.models().get(0).billing().promo().discountPercent()); + assertEquals("2026-08-01T00:00:00Z", result.models().get(0).billing().promo().endsAt()); + assertEquals("Summer discount", result.models().get(0).billing().promo().message()); } @Test @@ -834,9 +840,9 @@ void toolsListResult_nested() { void sessionModelSwitchToParams_nested_records() { var limitsVision = new ModelCapabilitiesOverrideLimitsVision(List.of("image/png", "image/jpeg"), 10L, 5000000L); var limits = new ModelCapabilitiesOverrideLimits(100000L, 8192L, 128000L, limitsVision); - var supports = new ModelCapabilitiesOverrideSupports(true, true); + var supports = new ModelCapabilitiesOverrideSupports(true, true, null); var capabilities = new ModelCapabilitiesOverride(supports, limits); - var params = new SessionModelSwitchToParams("sess-m", "gpt-5", null, null, capabilities, null); + var params = new SessionModelSwitchToParams("sess-m", "gpt-5", null, null, null, capabilities, null); assertEquals("gpt-5", params.modelId()); assertNotNull(params.modelCapabilities()); diff --git a/java/src/test/java/com/github/copilot/rpc/ParamCoercionTest.java b/java/src/test/java/com/github/copilot/rpc/ParamCoercionTest.java new file mode 100644 index 0000000000..8ad4ee8306 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/ParamCoercionTest.java @@ -0,0 +1,362 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Map; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.tool.Param; + +/** + * Unit tests for {@link ParamCoercion} — runtime argument coercion from raw + * invocation maps to typed Java values declared by {@link Param} descriptors. + */ +class ParamCoercionTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + // ── coerce: present argument, simple types ─────────────────────────────────── + + @Test + void coerce_stringArg_passedThrough() { + Param p = Param.of(String.class, "msg", "A message"); + String result = ParamCoercion.coerce(Map.of("msg", "hello"), p, MAPPER); + assertEquals("hello", result); + } + + @Test + void coerce_integerArgFromNumber() { + Param p = Param.of(Integer.class, "n", "A number"); + Integer result = ParamCoercion.coerce(Map.of("n", 42), p, MAPPER); + assertEquals(42, result); + } + + @Test + void coerce_longArgFromNumber() { + Param p = Param.of(Long.class, "id", "An identifier"); + Long result = ParamCoercion.coerce(Map.of("id", 123456789L), p, MAPPER); + assertEquals(123456789L, result); + } + + @Test + void coerce_doubleArgFromNumber() { + Param p = Param.of(Double.class, "price", "A price"); + Double result = ParamCoercion.coerce(Map.of("price", 19.99), p, MAPPER); + assertEquals(19.99, result, 0.001); + } + + @Test + void coerce_floatArgFromNumber() { + Param p = Param.of(Float.class, "rate", "A rate"); + Float result = ParamCoercion.coerce(Map.of("rate", 3.14), p, MAPPER); + assertEquals(3.14f, result, 0.01f); + } + + @Test + void coerce_booleanArgFromBoolean() { + Param p = Param.of(Boolean.class, "flag", "A flag"); + Boolean result = ParamCoercion.coerce(Map.of("flag", true), p, MAPPER); + assertEquals(true, result); + } + + // Note: enum coercion via mapper.convertValue requires the enum's package to be + // opened to com.fasterxml.jackson.databind. In the SDK module, + // com.github.copilot.tool + // is not opened to Jackson (only com.github.copilot.rpc is). User-defined enums + // will + // be outside the SDK module and fully accessible. Enum default coercion is + // tested via + // coerceDefault_enum which uses Enum.valueOf directly. + + @Test + void coerce_enumFromString_viaCoerceDefault() { + Param p = Param.of(TestMode.class, "mode", "Mode", false, "FAST"); + TestMode result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(TestMode.FAST, result); + } + + // ── coerce: Optional primitive types ───────────────────────────────────────── + + @Test + void coerce_optionalInt_fromNumber() { + Param p = Param.of(OptionalInt.class, "count", "Count", false, ""); + OptionalInt result = ParamCoercion.coerce(Map.of("count", 7), p, MAPPER); + assertEquals(OptionalInt.of(7), result); + } + + @Test + void coerce_optionalLong_fromNumber() { + Param p = Param.of(OptionalLong.class, "ts", "Timestamp", false, ""); + OptionalLong result = ParamCoercion.coerce(Map.of("ts", 999L), p, MAPPER); + assertEquals(OptionalLong.of(999L), result); + } + + @Test + void coerce_optionalDouble_fromNumber() { + Param p = Param.of(OptionalDouble.class, "ratio", "Ratio", false, ""); + OptionalDouble result = ParamCoercion.coerce(Map.of("ratio", 2.5), p, MAPPER); + assertEquals(OptionalDouble.of(2.5), result); + } + + @Test + void coerce_optionalInt_nonNumeric_throwsIllegalArgument() { + Param p = Param.of(OptionalInt.class, "count", "Count", false, ""); + assertThrows(IllegalArgumentException.class, + () -> ParamCoercion.coerce(Map.of("count", "not_a_number"), p, MAPPER)); + } + + @Test + void coerce_optionalLong_nonNumeric_throwsIllegalArgument() { + Param p = Param.of(OptionalLong.class, "ts", "Timestamp", false, ""); + assertThrows(IllegalArgumentException.class, () -> ParamCoercion.coerce(Map.of("ts", "abc"), p, MAPPER)); + } + + @Test + void coerce_optionalDouble_nonNumeric_throwsIllegalArgument() { + Param p = Param.of(OptionalDouble.class, "ratio", "Ratio", false, ""); + assertThrows(IllegalArgumentException.class, () -> ParamCoercion.coerce(Map.of("ratio", "xyz"), p, MAPPER)); + } + + // ── coerce: missing argument — required ────────────────────────────────────── + + @Test + void coerce_requiredMissing_throwsWithParamName() { + Param p = Param.of(String.class, "query", "Search query"); + var ex = assertThrows(IllegalArgumentException.class, () -> ParamCoercion.coerce(Map.of(), p, MAPPER)); + assertTrue(ex.getMessage().contains("query")); + } + + @Test + void coerce_requiredMissing_nullArgs_throws() { + Param p = Param.of(String.class, "name", "A name"); + var ex = assertThrows(IllegalArgumentException.class, () -> ParamCoercion.coerce(null, p, MAPPER)); + assertTrue(ex.getMessage().contains("name")); + } + + // ── coerce: missing argument — optional with default ───────────────────────── + + @Test + void coerce_optionalWithStringDefault_usesDefault() { + Param p = Param.of(String.class, "mode", "Mode", false, "normal"); + String result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals("normal", result); + } + + @Test + void coerce_optionalWithIntegerDefault_usesDefault() { + Param p = Param.of(Integer.class, "limit", "Limit", false, "25"); + Integer result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(25, result); + } + + @Test + void coerce_optionalWithLongDefault_usesDefault() { + Param p = Param.of(Long.class, "offset", "Offset", false, "100"); + Long result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(100L, result); + } + + @Test + void coerce_optionalWithDoubleDefault_usesDefault() { + Param p = Param.of(Double.class, "threshold", "Threshold", false, "0.75"); + Double result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(0.75, result, 0.001); + } + + @Test + void coerce_optionalWithFloatDefault_usesDefault() { + Param p = Param.of(Float.class, "rate", "Rate", false, "1.5"); + Float result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(1.5f, result, 0.01f); + } + + @Test + void coerce_optionalWithShortDefault_usesDefault() { + Param p = Param.of(Short.class, "level", "Level", false, "3"); + Short result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals((short) 3, result); + } + + @Test + void coerce_optionalWithByteDefault_usesDefault() { + Param p = Param.of(Byte.class, "code", "Code", false, "7"); + Byte result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals((byte) 7, result); + } + + @Test + void coerce_optionalWithBooleanDefault_usesDefault() { + Param p = Param.of(Boolean.class, "verbose", "Verbose", false, "true"); + Boolean result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(true, result); + } + + @Test + void coerce_optionalWithEnumDefault_usesDefault() { + Param p = Param.of(TestMode.class, "mode", "Mode", false, "SLOW"); + TestMode result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(TestMode.SLOW, result); + } + + // ── coerce: missing argument — optional without default ────────────────────── + + @Test + void coerce_optionalNoDefault_returnsNull() { + Param p = Param.of(String.class, "title", "Title", false, ""); + String result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertNull(result); + } + + @Test + void coerce_optionalNoDefault_optionalInt_returnsEmpty() { + Param p = Param.of(OptionalInt.class, "n", "Number", false, ""); + OptionalInt result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(OptionalInt.empty(), result); + } + + @Test + void coerce_optionalNoDefault_optionalLong_returnsEmpty() { + Param p = Param.of(OptionalLong.class, "ts", "Timestamp", false, ""); + OptionalLong result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(OptionalLong.empty(), result); + } + + @Test + void coerce_optionalNoDefault_optionalDouble_returnsEmpty() { + Param p = Param.of(OptionalDouble.class, "ratio", "Ratio", false, ""); + OptionalDouble result = ParamCoercion.coerce(Map.of(), p, MAPPER); + assertEquals(OptionalDouble.empty(), result); + } + + // ── coerce: type conversion via ObjectMapper ───────────────────────────────── + + @Test + void coerce_integerFromStringViaMapper() { + // ObjectMapper can convert "42" string to Integer + Param p = Param.of(Integer.class, "n", "A number"); + Integer result = ParamCoercion.coerce(Map.of("n", "42"), p, MAPPER); + assertEquals(42, result); + } + + @Test + void coerce_booleanFromStringViaMapper() { + Param p = Param.of(Boolean.class, "flag", "A flag"); + Boolean result = ParamCoercion.coerce(Map.of("flag", "true"), p, MAPPER); + assertEquals(true, result); + } + + @Test + void coerce_incompatibleType_throwsWithParamName() { + Param p = Param.of(Integer.class, "count", "Count"); + var ex = assertThrows(IllegalArgumentException.class, + () -> ParamCoercion.coerce(Map.of("count", "not_a_number"), p, MAPPER)); + assertTrue(ex.getMessage().contains("count")); + } + + // ── coerceDefault: direct tests ────────────────────────────────────────────── + + @Test + void coerceDefault_string() { + Param p = Param.of(String.class, "s", "A string", false, "hello"); + assertEquals("hello", ParamCoercion.coerceDefault(p, MAPPER)); + } + + @Test + void coerceDefault_integer() { + Param p = Param.of(Integer.class, "n", "A num", false, "99"); + assertEquals(99, ParamCoercion.coerceDefault(p, MAPPER)); + } + + @Test + void coerceDefault_long() { + Param p = Param.of(Long.class, "id", "An id", false, "12345"); + assertEquals(12345L, ParamCoercion.coerceDefault(p, MAPPER)); + } + + @Test + void coerceDefault_double() { + Param p = Param.of(Double.class, "d", "A double", false, "3.14"); + assertEquals(3.14, ParamCoercion.coerceDefault(p, MAPPER), 0.001); + } + + @Test + void coerceDefault_float() { + Param p = Param.of(Float.class, "f", "A float", false, "2.5"); + assertEquals(2.5f, ParamCoercion.coerceDefault(p, MAPPER), 0.01f); + } + + @Test + void coerceDefault_short() { + Param p = Param.of(Short.class, "s", "A short", false, "10"); + assertEquals((short) 10, ParamCoercion.coerceDefault(p, MAPPER)); + } + + @Test + void coerceDefault_byte() { + Param p = Param.of(Byte.class, "b", "A byte", false, "5"); + assertEquals((byte) 5, ParamCoercion.coerceDefault(p, MAPPER)); + } + + @Test + void coerceDefault_booleanTrue() { + Param p = Param.of(Boolean.class, "v", "Verbose", false, "true"); + assertEquals(true, ParamCoercion.coerceDefault(p, MAPPER)); + } + + @Test + void coerceDefault_booleanFalse() { + Param p = Param.of(Boolean.class, "v", "Verbose", false, "false"); + assertEquals(false, ParamCoercion.coerceDefault(p, MAPPER)); + } + + @Test + void coerceDefault_enum() { + Param p = Param.of(TestMode.class, "m", "Mode", false, "FAST"); + assertEquals(TestMode.FAST, ParamCoercion.coerceDefault(p, MAPPER)); + } + + // ── emptyOptionalOrNull: direct tests ──────────────────────────────────────── + + @Test + void emptyOptionalOrNull_optionalInt_returnsEmpty() { + assertEquals(OptionalInt.empty(), ParamCoercion.emptyOptionalOrNull(OptionalInt.class)); + } + + @Test + void emptyOptionalOrNull_optionalLong_returnsEmpty() { + assertEquals(OptionalLong.empty(), ParamCoercion.emptyOptionalOrNull(OptionalLong.class)); + } + + @Test + void emptyOptionalOrNull_optionalDouble_returnsEmpty() { + assertEquals(OptionalDouble.empty(), ParamCoercion.emptyOptionalOrNull(OptionalDouble.class)); + } + + @Test + void emptyOptionalOrNull_string_returnsNull() { + assertNull(ParamCoercion.emptyOptionalOrNull(String.class)); + } + + @Test + void emptyOptionalOrNull_integer_returnsNull() { + assertNull(ParamCoercion.emptyOptionalOrNull(Integer.class)); + } + + // ── Test helper types ──────────────────────────────────────────────────────── + + enum TestMode { + FAST, SLOW, NORMAL + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/ParamSchemaTest.java b/java/src/test/java/com/github/copilot/rpc/ParamSchemaTest.java new file mode 100644 index 0000000000..27d76a91a5 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/ParamSchemaTest.java @@ -0,0 +1,436 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; +import java.util.Set; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.tool.Param; + +/** + * Unit tests for {@link ParamSchema} — runtime JSON Schema generation from + * {@link Param} descriptors. + */ +class ParamSchemaTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + // ── buildSchema: empty / zero params ───────────────────────────────────────── + + @Test + void buildSchema_nullParams_returnsEmptySchema() { + Map schema = ParamSchema.buildSchema("tool", MAPPER, (Param[]) null); + assertEquals("object", schema.get("type")); + assertTrue(((Map) schema.get("properties")).isEmpty()); + assertTrue(((List) schema.get("required")).isEmpty()); + } + + @Test + void buildSchema_emptyArray_returnsEmptySchema() { + Map schema = ParamSchema.buildSchema("tool", MAPPER); + assertEquals("object", schema.get("type")); + assertTrue(((Map) schema.get("properties")).isEmpty()); + assertTrue(((List) schema.get("required")).isEmpty()); + } + + // ── buildSchema: validation ────────────────────────────────────────────────── + + @Test + void buildSchema_nullParamElement_throwsWithToolName() { + Param p1 = Param.of(String.class, "a", "First"); + var ex = assertThrows(IllegalArgumentException.class, + () -> ParamSchema.buildSchema("my_tool", MAPPER, p1, null)); + assertTrue(ex.getMessage().contains("my_tool")); + } + + @Test + void buildSchema_duplicateNames_throwsWithToolNameAndParamName() { + Param p1 = Param.of(String.class, "name", "First name"); + Param p2 = Param.of(String.class, "name", "Second name"); + var ex = assertThrows(IllegalArgumentException.class, + () -> ParamSchema.buildSchema("greeting", MAPPER, p1, p2)); + assertTrue(ex.getMessage().contains("name")); + assertTrue(ex.getMessage().contains("greeting")); + } + + // ── buildSchema: required / optional semantics ─────────────────────────────── + + @Test + void buildSchema_requiredParam_appearsInRequiredList() { + Param p = Param.of(String.class, "query", "Search query"); + Map schema = ParamSchema.buildSchema("search", MAPPER, p); + @SuppressWarnings("unchecked") + List required = (List) schema.get("required"); + assertTrue(required.contains("query")); + } + + @Test + void buildSchema_optionalParam_notInRequiredList() { + Param p = Param.of(Integer.class, "limit", "Max results", false, "10"); + Map schema = ParamSchema.buildSchema("list", MAPPER, p); + @SuppressWarnings("unchecked") + List required = (List) schema.get("required"); + assertTrue(required.isEmpty()); + } + + @Test + void buildSchema_mixedRequiredAndOptional_onlyRequiredInList() { + Param pReq = Param.of(String.class, "query", "Search query"); + Param pOpt = Param.of(Integer.class, "limit", "Max", false, "20"); + Map schema = ParamSchema.buildSchema("search", MAPPER, pReq, pOpt); + @SuppressWarnings("unchecked") + List required = (List) schema.get("required"); + assertEquals(1, required.size()); + assertEquals("query", required.get(0)); + } + + // ── buildSchema: description and default in property ───────────────────────── + + @Test + void buildSchema_paramDescription_appearsInPropertySchema() { + Param p = Param.of(String.class, "msg", "A message to send"); + Map schema = ParamSchema.buildSchema("send", MAPPER, p); + @SuppressWarnings("unchecked") + Map props = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + Map msgSchema = (Map) props.get("msg"); + assertEquals("A message to send", msgSchema.get("description")); + } + + @Test + void buildSchema_paramDefault_appearsInPropertySchema() { + Param p = Param.of(Integer.class, "count", "Item count", false, "5"); + Map schema = ParamSchema.buildSchema("items", MAPPER, p); + @SuppressWarnings("unchecked") + Map props = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + Map countSchema = (Map) props.get("count"); + assertEquals(5, countSchema.get("default")); + } + + @Test + void buildSchema_stringDefault_appearsAsString() { + Param p = Param.of(String.class, "mode", "Operating mode", false, "fast"); + Map schema = ParamSchema.buildSchema("run", MAPPER, p); + @SuppressWarnings("unchecked") + Map props = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + Map modeSchema = (Map) props.get("mode"); + assertEquals("fast", modeSchema.get("default")); + } + + @Test + void buildSchema_booleanDefault_appearsAsBoolean() { + Param p = Param.of(Boolean.class, "verbose", "Verbose mode", false, "true"); + Map schema = ParamSchema.buildSchema("run", MAPPER, p); + @SuppressWarnings("unchecked") + Map props = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + Map verboseSchema = (Map) props.get("verbose"); + assertEquals(true, verboseSchema.get("default")); + } + + // ── buildSchema: multiple params preserve order ────────────────────────────── + + @Test + void buildSchema_multipleParams_orderPreservedInProperties() { + Param p1 = Param.of(String.class, "alpha", "First"); + Param p2 = Param.of(String.class, "beta", "Second"); + Param p3 = Param.of(String.class, "gamma", "Third"); + Map schema = ParamSchema.buildSchema("ordered", MAPPER, p1, p2, p3); + @SuppressWarnings("unchecked") + Map props = (Map) schema.get("properties"); + List keys = List.copyOf(props.keySet()); + assertEquals(List.of("alpha", "beta", "gamma"), keys); + } + + // ── forType: primitive and boxed integer types ─────────────────────────────── + + @Test + void forType_int_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(int.class)); + } + + @Test + void forType_Integer_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(Integer.class)); + } + + @Test + void forType_long_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(long.class)); + } + + @Test + void forType_Long_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(Long.class)); + } + + @Test + void forType_short_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(short.class)); + } + + @Test + void forType_Short_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(Short.class)); + } + + @Test + void forType_byte_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(byte.class)); + } + + @Test + void forType_Byte_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(Byte.class)); + } + + // ── forType: floating-point types ──────────────────────────────────────────── + + @Test + void forType_double_returnsNumber() { + assertEquals(Map.of("type", "number"), ParamSchema.forType(double.class)); + } + + @Test + void forType_Double_returnsNumber() { + assertEquals(Map.of("type", "number"), ParamSchema.forType(Double.class)); + } + + @Test + void forType_float_returnsNumber() { + assertEquals(Map.of("type", "number"), ParamSchema.forType(float.class)); + } + + @Test + void forType_Float_returnsNumber() { + assertEquals(Map.of("type", "number"), ParamSchema.forType(Float.class)); + } + + // ── forType: boolean ───────────────────────────────────────────────────────── + + @Test + void forType_boolean_returnsBoolean() { + assertEquals(Map.of("type", "boolean"), ParamSchema.forType(boolean.class)); + } + + @Test + void forType_Boolean_returnsBoolean() { + assertEquals(Map.of("type", "boolean"), ParamSchema.forType(Boolean.class)); + } + + // ── forType: char / Character ──────────────────────────────────────────────── + + @Test + void forType_char_returnsString() { + assertEquals(Map.of("type", "string"), ParamSchema.forType(char.class)); + } + + @Test + void forType_Character_returnsString() { + assertEquals(Map.of("type", "string"), ParamSchema.forType(Character.class)); + } + + // ── forType: String ────────────────────────────────────────────────────────── + + @Test + void forType_String_returnsString() { + assertEquals(Map.of("type", "string"), ParamSchema.forType(String.class)); + } + + // ── forType: UUID ──────────────────────────────────────────────────────────── + + @Test + void forType_UUID_returnsStringWithUuidFormat() { + Map schema = ParamSchema.forType(UUID.class); + assertEquals("string", schema.get("type")); + assertEquals("uuid", schema.get("format")); + } + + // ── forType: Optional primitive types ──────────────────────────────────────── + + @Test + void forType_OptionalInt_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(OptionalInt.class)); + } + + @Test + void forType_OptionalLong_returnsInteger() { + assertEquals(Map.of("type", "integer"), ParamSchema.forType(OptionalLong.class)); + } + + @Test + void forType_OptionalDouble_returnsNumber() { + assertEquals(Map.of("type", "number"), ParamSchema.forType(OptionalDouble.class)); + } + + // ── forType: date-time types ───────────────────────────────────────────────── + + @Test + void forType_OffsetDateTime_returnsDateTimeFormat() { + Map schema = ParamSchema.forType(OffsetDateTime.class); + assertEquals("string", schema.get("type")); + assertEquals("date-time", schema.get("format")); + } + + @Test + void forType_LocalDateTime_returnsDateTimeFormat() { + Map schema = ParamSchema.forType(LocalDateTime.class); + assertEquals("string", schema.get("type")); + assertEquals("date-time", schema.get("format")); + } + + @Test + void forType_Instant_returnsDateTimeFormat() { + Map schema = ParamSchema.forType(Instant.class); + assertEquals("string", schema.get("type")); + assertEquals("date-time", schema.get("format")); + } + + @Test + void forType_ZonedDateTime_returnsDateTimeFormat() { + Map schema = ParamSchema.forType(ZonedDateTime.class); + assertEquals("string", schema.get("type")); + assertEquals("date-time", schema.get("format")); + } + + @Test + void forType_LocalDate_returnsDateFormat() { + Map schema = ParamSchema.forType(LocalDate.class); + assertEquals("string", schema.get("type")); + assertEquals("date", schema.get("format")); + } + + @Test + void forType_LocalTime_returnsTimeFormat() { + Map schema = ParamSchema.forType(LocalTime.class); + assertEquals("string", schema.get("type")); + assertEquals("time", schema.get("format")); + } + + // ── forType: JsonNode / Object → any ───────────────────────────────────────── + + @Test + void forType_JsonNode_returnsEmptySchema() { + assertTrue(ParamSchema.forType(JsonNode.class).isEmpty()); + } + + @Test + void forType_Object_returnsEmptySchema() { + assertTrue(ParamSchema.forType(Object.class).isEmpty()); + } + + // ── forType: enums ─────────────────────────────────────────────────────────── + + @Test + void forType_enum_returnsStringWithEnumValues() { + Map schema = ParamSchema.forType(TestColor.class); + assertEquals("string", schema.get("type")); + @SuppressWarnings("unchecked") + List values = (List) schema.get("enum"); + assertNotNull(values); + assertEquals(List.of("RED", "GREEN", "BLUE"), values); + } + + // ── forType: collections ───────────────────────────────────────────────────── + + @Test + void forType_List_returnsArray() { + assertEquals(Map.of("type", "array"), ParamSchema.forType(List.class)); + } + + @Test + void forType_Set_returnsArray() { + assertEquals(Map.of("type", "array"), ParamSchema.forType(Set.class)); + } + + @Test + void forType_Collection_returnsArray() { + assertEquals(Map.of("type", "array"), ParamSchema.forType(Collection.class)); + } + + // ── forType: arrays ────────────────────────────────────────────────────────── + + @Test + void forType_stringArray_returnsArrayWithStringItems() { + Map schema = ParamSchema.forType(String[].class); + assertEquals("array", schema.get("type")); + @SuppressWarnings("unchecked") + Map items = (Map) schema.get("items"); + assertEquals("string", items.get("type")); + } + + @Test + void forType_intArray_returnsArrayWithIntegerItems() { + Map schema = ParamSchema.forType(int[].class); + assertEquals("array", schema.get("type")); + @SuppressWarnings("unchecked") + Map items = (Map) schema.get("items"); + assertEquals("integer", items.get("type")); + } + + @Test + void forType_doubleArray_returnsArrayWithNumberItems() { + Map schema = ParamSchema.forType(double[].class); + assertEquals("array", schema.get("type")); + @SuppressWarnings("unchecked") + Map items = (Map) schema.get("items"); + assertEquals("number", items.get("type")); + } + + // ── forType: Map ───────────────────────────────────────────────────────────── + + @Test + void forType_Map_returnsObject() { + assertEquals(Map.of("type", "object"), ParamSchema.forType(Map.class)); + } + + // ── forType: POJO / record fallback ────────────────────────────────────────── + + @Test + void forType_record_returnsObject() { + assertEquals(Map.of("type", "object"), ParamSchema.forType(TestRecord.class)); + } + + @Test + void forType_pojo_returnsObject() { + assertEquals(Map.of("type", "object"), ParamSchema.forType(TestPojo.class)); + } + + // ── Test helper types ──────────────────────────────────────────────────────── + + enum TestColor { + RED, GREEN, BLUE + } + + record TestRecord(String name, int value) { + } + + static class TestPojo { + String field; + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/RecordInvocationArgs.java b/java/src/test/java/com/github/copilot/rpc/RecordInvocationArgs.java new file mode 100644 index 0000000000..99cfe47066 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/RecordInvocationArgs.java @@ -0,0 +1,8 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +public record RecordInvocationArgs(String query, int limit) { +} diff --git a/java/src/test/java/com/github/copilot/rpc/ToolDefinitionFromObjectTest.java b/java/src/test/java/com/github/copilot/rpc/ToolDefinitionFromObjectTest.java new file mode 100644 index 0000000000..afa3d42511 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/ToolDefinitionFromObjectTest.java @@ -0,0 +1,498 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.github.copilot.AllowCopilotExperimental; +import com.github.copilot.rpc.fixtures.ArgCoercionTools; +import com.github.copilot.rpc.fixtures.DateTimeTools; +import com.github.copilot.rpc.fixtures.DefaultValueTools; +import com.github.copilot.rpc.fixtures.InvocationAwareTools; +import com.github.copilot.rpc.fixtures.MultiReturnTools; +import com.github.copilot.rpc.fixtures.OptionalParamTools; +import com.github.copilot.rpc.fixtures.OverrideTools; +import com.github.copilot.rpc.fixtures.SimpleTools; +import com.github.copilot.rpc.fixtures.StaticInvocationTools; +import com.github.copilot.rpc.fixtures.StaticTools; + +/** + * End-to-end tests for {@link ToolDefinition#fromObject(Object)}. + *

+ * These tests use hand-written {@code $$CopilotToolMeta} companion classes + * under {@code com.github.copilot.rpc.fixtures} that mimic + * {@link com.github.copilot.tool.CopilotToolProcessor} output. + */ +@AllowCopilotExperimental +class ToolDefinitionFromObjectTest { + + // ── Test 1: Basic end-to-end ──────────────────────────────────────────────── + + @Test + void fromObject_returnsCorrectNumberOfTools() { + var tools = ToolDefinition.fromObject(new SimpleTools()); + assertEquals(2, tools.size()); + } + + @Test + void fromObject_toolNamesAndDescriptions() { + var tools = ToolDefinition.fromObject(new SimpleTools()); + var tool1 = findTool(tools, "greet_user"); + assertNotNull(tool1); + assertEquals("Greets a user by name", tool1.description()); + + var tool2 = findTool(tools, "add_numbers"); + assertNotNull(tool2); + assertEquals("Adds two numbers together", tool2.description()); + } + + @Test + void fromObject_toolParameterSchema() { + var tools = ToolDefinition.fromObject(new SimpleTools()); + var tool = findTool(tools, "greet_user"); + assertNotNull(tool); + @SuppressWarnings("unchecked") + var schema = (Map) tool.parameters(); + assertEquals("object", schema.get("type")); + @SuppressWarnings("unchecked") + var properties = (Map) schema.get("properties"); + assertTrue(properties.containsKey("name")); + @SuppressWarnings("unchecked") + var required = (List) schema.get("required"); + assertTrue(required.contains("name")); + } + + @Test + void fromObject_handlerInvocation() throws Exception { + var instance = new SimpleTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "greet_user"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("greet_user", Map.of("name", "Alice"))).get(); + assertEquals("Hello, Alice!", result); + } + + @Test + void fromObject_toolMetadata() { + var tools = ToolDefinition.fromObject(new SimpleTools()); + + var withMetadata = findTool(tools, "greet_user"); + assertNotNull(withMetadata); + assertNotNull(withMetadata.metadata()); + assertEquals(Map.of("github.com/copilot:safeForTelemetry", Map.of("name", true, "inputsNames", false)), + withMetadata.metadata()); + + var withoutMetadata = findTool(tools, "add_numbers"); + assertNotNull(withoutMetadata); + assertNull(withoutMetadata.metadata()); + } + + // ── Test 2: Handler return type patterns ──────────────────────────────────── + + @Test + void fromObject_stringReturn() throws Exception { + var tools = ToolDefinition.fromObject(new MultiReturnTools()); + var tool = findTool(tools, "string_method"); + assertNotNull(tool); + var result = tool.handler().invoke(createInvocation("string_method", Map.of())).get(); + assertEquals("hello", result); + } + + @Test + void fromObject_voidReturn() throws Exception { + var tools = ToolDefinition.fromObject(new MultiReturnTools()); + var tool = findTool(tools, "void_method"); + assertNotNull(tool); + var result = tool.handler().invoke(createInvocation("void_method", Map.of())).get(); + assertEquals("Success", result); + } + + @Test + void fromObject_asyncReturn() throws Exception { + var tools = ToolDefinition.fromObject(new MultiReturnTools()); + var tool = findTool(tools, "async_method"); + assertNotNull(tool); + var result = tool.handler().invoke(createInvocation("async_method", Map.of())).get(); + assertEquals("async result", result); + } + + // ── Test 3: Argument coercion ─────────────────────────────────────────────── + + @Test + void fromObject_argumentCoercion() throws Exception { + var instance = new ArgCoercionTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "mixed_args"); + assertNotNull(tool); + + var result = tool.handler().invoke( + createInvocation("mixed_args", Map.of("text", "hello", "count", 5, "flag", true, "color", "RED"))) + .get(); + assertEquals("hello-5-true-RED", result); + } + + // ── Test 4: Default value ─────────────────────────────────────────────────── + + @Test + void fromObject_defaultValue() throws Exception { + var instance = new DefaultValueTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "with_default"); + assertNotNull(tool); + + // Omit "count" key — should use default value 42 + var result = tool.handler().invoke(createInvocation("with_default", Map.of("label", "test"))).get(); + assertEquals("test:42", result); + } + + // ── Test 5: Error case — missing generated class ──────────────────────────── + + @Test + void fromObject_throwsOnMissingMetaClass() { + // A class that was never processed by CopilotToolProcessor + var ex = assertThrows(IllegalStateException.class, () -> ToolDefinition.fromObject("a plain String")); + assertTrue(ex.getMessage().contains("not found")); + assertTrue(ex.getMessage().contains("CopilotToolProcessor")); + } + + // ── Test 5b: fromClass rejects instance methods ───────────────────────────── + + @Test + void fromClass_throwsOnInstanceMethods() { + // SimpleTools has instance (non-static) @CopilotTool methods + var ex = assertThrows(IllegalArgumentException.class, () -> ToolDefinition.fromClass(SimpleTools.class)); + assertTrue(ex.getMessage().contains("fromClass()")); + assertTrue(ex.getMessage().contains("static")); + assertTrue(ex.getMessage().contains("fromObject")); + } + + // ── Test 6: java.time argument ────────────────────────────────────────────── + + @Test + void fromObject_javaTimeArgument() throws Exception { + var instance = new DateTimeTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "schedule_event"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("schedule_event", Map.of("when", "2024-06-15T10:30:00"))) + .get(); + assertEquals("Scheduled at 2024-06-15T10:30", result); + } + + // ── Test 7: Override tool ──────────────────────────────────────────────────── + + @Test + void fromObject_overrideTool() { + var tools = ToolDefinition.fromObject(new OverrideTools()); + var tool = findTool(tools, "grep"); + assertNotNull(tool); + assertEquals(Boolean.TRUE, tool.overridesBuiltInTool()); + } + + // ── Test 8: ToolDefer.NONE → null mapping (defer absent from JSON) ────────── + + @Test + void fromObject_deferNone_absentFromJson() throws Exception { + var tools = ToolDefinition.fromObject(new SimpleTools()); + var tool = findTool(tools, "greet_user"); + assertNotNull(tool); + // The defer field should be null (NONE maps to null) + assertNull(tool.defer()); + + // Serialize to JSON and verify "defer" key is absent + var mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL); + + String json = mapper.writeValueAsString(tool); + var node = (ObjectNode) mapper.readTree(json); + assertFalse(node.has("defer"), "defer key should be absent from JSON, got: " + json); + } + + // ── Test 9: fromClass with static methods invokes handler without NPE ───── + + @Test + void fromClass_staticToolInvocation() throws Exception { + var tools = ToolDefinition.fromClass(StaticTools.class); + assertEquals(1, tools.size()); + var tool = findTool(tools, "greet"); + assertNotNull(tool); + + // This should NOT throw NPE — static methods don't need an instance + var result = tool.handler().invoke(createInvocation("greet", Map.of("name", "World"))).get(); + assertEquals("Hi, World!", result); + } + + // ── Test 10: Optional parameter handling ──────────────────────────────────── + + @Test + void fromObject_optionalStringPresent() throws Exception { + var instance = new OptionalParamTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "greet_with_title"); + assertNotNull(tool); + + var result = tool.handler() + .invoke(createInvocation("greet_with_title", Map.of("name", "Alice", "title", "Dr."))).get(); + assertEquals("Dr. Alice", result); + } + + @Test + void fromObject_optionalStringAbsent() throws Exception { + var instance = new OptionalParamTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "greet_with_title"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("greet_with_title", Map.of("name", "Alice"))).get(); + assertEquals("Alice", result); + } + + @Test + void fromObject_optionalIntPresent() throws Exception { + var instance = new OptionalParamTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "multiply"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("multiply", Map.of("base", 5, "factor", 3))).get(); + assertEquals("15", result); + } + + @Test + void fromObject_optionalIntAbsent() throws Exception { + var instance = new OptionalParamTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "multiply"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("multiply", Map.of("base", 5))).get(); + assertEquals("5", result); + } + + @Test + void fromObject_optionalDoublePresent() throws Exception { + var instance = new OptionalParamTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "scale"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("scale", Map.of("value", 2.0, "ratio", 3.5))).get(); + assertEquals("7.0", result); + } + + @Test + void fromObject_optionalLongPresent() throws Exception { + var instance = new OptionalParamTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "offset"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("offset", Map.of("base", 100, "delta", 50))).get(); + assertEquals("150", result); + } + + @Test + void fromObject_optionalLongAbsent() throws Exception { + var instance = new OptionalParamTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "offset"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("offset", Map.of("base", 100))).get(); + assertEquals("100", result); + } + + // ── Test 11: ToolInvocation injection ─────────────────────────────────────── + + @Test + void fromObject_toolInvocationInjection_instanceMethod() throws Exception { + var instance = new InvocationAwareTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "report_progress"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("report_progress", Map.of("phase", "analyzing")) + .setSessionId("session-123").setToolCallId("call-456")).get(); + assertEquals("phase=analyzing,sessionId=session-123,toolCallId=call-456,toolName=report_progress", result); + } + + @Test + void fromObject_toolInvocationInjection_schemaExcludesToolInvocation() { + var tools = ToolDefinition.fromObject(new InvocationAwareTools()); + var tool = findTool(tools, "report_progress"); + assertNotNull(tool); + + @SuppressWarnings("unchecked") + var schema = (Map) tool.parameters(); + @SuppressWarnings("unchecked") + var properties = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + var required = (List) schema.get("required"); + + assertTrue(properties.containsKey("phase")); + assertFalse(properties.containsKey("invocation")); + assertEquals(List.of("phase"), required); + } + + @Test + void fromObject_toolInvocationInjection_asyncMethod() throws Exception { + var instance = new InvocationAwareTools(); + var tools = ToolDefinition.fromObject(instance); + var tool = findTool(tools, "report_progress_async"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("report_progress_async", Map.of("phase", "planning")) + .setSessionId("session-789").setToolCallId("call-012")).get(); + assertEquals("async phase=planning,sessionId=session-789,toolCallId=call-012,toolName=report_progress_async", + result); + } + + @Test + void fromClass_toolInvocationInjection_staticMethod() throws Exception { + var tools = ToolDefinition.fromClass(StaticInvocationTools.class); + var tool = findTool(tools, "report_static"); + assertNotNull(tool); + + var result = tool.handler().invoke(createInvocation("report_static", Map.of("phase", "completed")) + .setSessionId("session-321").setToolCallId("call-654")).get(); + assertEquals("phase=completed,sessionId=session-321,toolCallId=call-654,toolName=report_static", result); + } + + @Test + void fromObject_toolInvocationInjection_firstParameter() throws Exception { + var tools = ToolDefinition.fromObject(new InvocationAwareTools()); + var tool = findTool(tools, "report_progress_first"); + assertNotNull(tool); + + @SuppressWarnings("unchecked") + var schema = (Map) tool.parameters(); + @SuppressWarnings("unchecked") + var properties = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + var required = (List) schema.get("required"); + + assertTrue(properties.containsKey("phase")); + assertFalse(properties.containsKey("invocation")); + assertEquals(List.of("phase"), required); + + var result = tool.handler().invoke(createInvocation("report_progress_first", Map.of("phase", "starting")) + .setSessionId("session-first").setToolCallId("call-first")).get(); + assertEquals( + "first phase=starting,sessionId=session-first,toolCallId=call-first,toolName=report_progress_first", + result); + } + + @Test + void fromObject_toolInvocationInjection_onlyParameter() throws Exception { + var tools = ToolDefinition.fromObject(new InvocationAwareTools()); + var tool = findTool(tools, "only_context"); + assertNotNull(tool); + + @SuppressWarnings("unchecked") + var schema = (Map) tool.parameters(); + @SuppressWarnings("unchecked") + var properties = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + var required = (List) schema.get("required"); + + assertTrue(properties.isEmpty()); + assertTrue(required.isEmpty()); + + var result = tool.handler().invoke( + createInvocation("only_context", Map.of()).setSessionId("session-only").setToolCallId("call-only")) + .get(); + assertEquals("only sessionId=session-only,toolCallId=call-only,toolName=only_context", result); + } + + @Test + void fromObject_toolInvocationInjection_middleParameter() throws Exception { + var tools = ToolDefinition.fromObject(new InvocationAwareTools()); + var tool = findTool(tools, "report_progress_middle"); + assertNotNull(tool); + + @SuppressWarnings("unchecked") + var schema = (Map) tool.parameters(); + @SuppressWarnings("unchecked") + var properties = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + var required = (List) schema.get("required"); + + assertTrue(properties.containsKey("phase")); + assertTrue(properties.containsKey("limit")); + assertFalse(properties.containsKey("invocation")); + assertEquals(List.of("phase", "limit"), required); + + var result = tool.handler() + .invoke(createInvocation("report_progress_middle", Map.of("phase", "running", "limit", 7)) + .setSessionId("session-middle").setToolCallId("call-middle")) + .get(); + assertEquals( + "middle phase=running,limit=7,sessionId=session-middle,toolCallId=call-middle,toolName=report_progress_middle", + result); + } + + @Test + void fromObject_toolInvocationInjection_singleRecordAndInvocation() throws Exception { + var tools = ToolDefinition.fromObject(new InvocationAwareTools()); + var tool = findTool(tools, "report_progress_with_record"); + assertNotNull(tool); + + @SuppressWarnings("unchecked") + var schema = (Map) tool.parameters(); + @SuppressWarnings("unchecked") + var properties = (Map) schema.get("properties"); + @SuppressWarnings("unchecked") + var required = (List) schema.get("required"); + + assertTrue(properties.containsKey("query")); + assertTrue(properties.containsKey("limit")); + assertFalse(properties.containsKey("args")); + assertFalse(properties.containsKey("invocation")); + assertEquals(List.of("query", "limit"), required); + + var result = tool.handler() + .invoke(createInvocation("report_progress_with_record", Map.of("query", "logs", "limit", 3)) + .setSessionId("session-record").setToolCallId("call-record")) + .get(); + assertEquals( + "record query=logs,limit=3,sessionId=session-record,toolCallId=call-record,toolName=report_progress_with_record", + result); + } + + // ── Helpers ───────────────────────────────────────────────────────────────── + + private static ToolDefinition findTool(List tools, String name) { + return tools.stream().filter(t -> name.equals(t.name())).findFirst().orElse(null); + } + + private static ToolInvocation createInvocation(String toolName, Map args) { + ObjectNode argsNode = JsonNodeFactory.instance.objectNode(); + ObjectMapper mapper = new ObjectMapper(); + argsNode.setAll((ObjectNode) mapper.valueToTree(args)); + return new ToolInvocation().setToolName(toolName).setArguments(argsNode); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/ToolDefinitionLambdaTest.java b/java/src/test/java/com/github/copilot/rpc/ToolDefinitionLambdaTest.java new file mode 100644 index 0000000000..7f9ccaaba7 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/ToolDefinitionLambdaTest.java @@ -0,0 +1,613 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.copilot.AllowCopilotExperimental; +import com.github.copilot.tool.Param; + +/** + * Unit tests for {@link ToolDefinition#from}, {@link ToolDefinition#fromAsync}, + * {@link ToolDefinition#fromWithToolInvocation}, and + * {@link ToolDefinition#fromAsyncWithToolInvocation} lambda-tool factories, + * plus the fluent option-modifier methods + * ({@link ToolDefinition#overridesBuiltInTool}, + * {@link ToolDefinition#skipPermission}, {@link ToolDefinition#defer}). + * + *

+ * Tests are grouped by the Phase 4.4 contract: + *

    + *
  1. Successful inline definitions for arities 0–2 (sync and async).
  2. + *
  3. ToolInvocation context injection (sync and async).
  4. + *
  5. Option flag propagation.
  6. + *
  7. Required/default semantics.
  8. + *
  9. Error and validation paths.
  10. + *
  11. Schema structure.
  12. + *
  13. Result formatting (String, null, non-String).
  14. + *
  15. Argument coercion.
  16. + *
+ */ +@AllowCopilotExperimental +class ToolDefinitionLambdaTest { + + // ── Helpers ────────────────────────────────────────────────────────────────── + + private static ToolInvocation invocationOf(Map args) { + ObjectNode argsNode = JsonNodeFactory.instance.objectNode(); + for (Map.Entry e : args.entrySet()) { + Object v = e.getValue(); + if (v instanceof String s) { + argsNode.put(e.getKey(), s); + } else if (v instanceof Integer i) { + argsNode.put(e.getKey(), i); + } else if (v instanceof Long l) { + argsNode.put(e.getKey(), l); + } else if (v instanceof Double d) { + argsNode.put(e.getKey(), d); + } else if (v instanceof Boolean b) { + argsNode.put(e.getKey(), b); + } else if (v != null) { + argsNode.put(e.getKey(), v.toString()); + } + } + return new ToolInvocation().setArguments(argsNode); + } + + private static ToolInvocation invocationWithContext(String sessionId, String toolCallId, Map args) { + return invocationOf(args).setSessionId(sessionId).setToolCallId(toolCallId); + } + + @SuppressWarnings("unchecked") + private static Map schemaOf(ToolDefinition tool) { + return (Map) tool.parameters(); + } + + @SuppressWarnings("unchecked") + private static Map propertiesOf(ToolDefinition tool) { + return (Map) schemaOf(tool).get("properties"); + } + + @SuppressWarnings("unchecked") + private static List requiredOf(ToolDefinition tool) { + return (List) schemaOf(tool).get("required"); + } + + // ── Group 1: Successful inline definitions – arity 0, sync ─────────────────── + + @Test + void from_zeroArg_returnsNameAndDescription() { + ToolDefinition tool = ToolDefinition.from("ping", "Returns pong", () -> "pong"); + assertEquals("ping", tool.name()); + assertEquals("Returns pong", tool.description()); + } + + @Test + void from_zeroArg_invokesHandler() throws Exception { + ToolDefinition tool = ToolDefinition.from("ping", "Returns pong", () -> "pong"); + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("pong", result); + } + + @Test + void from_zeroArg_emptySchema() { + ToolDefinition tool = ToolDefinition.from("ping", "Returns pong", () -> "pong"); + assertTrue(propertiesOf(tool).isEmpty()); + assertTrue(requiredOf(tool).isEmpty()); + } + + // ── Group 1: Successful inline definitions – arity 1, sync ─────────────────── + + @Test + void from_oneArg_returnsNameAndDescription() { + Param nameParam = Param.of(String.class, "name", "The user's name"); + ToolDefinition tool = ToolDefinition.from("greet", "Greets a user", nameParam, n -> "Hello, " + n + "!"); + assertEquals("greet", tool.name()); + assertEquals("Greets a user", tool.description()); + } + + @Test + void from_oneArg_invokesHandler() throws Exception { + Param nameParam = Param.of(String.class, "name", "The user's name"); + ToolDefinition tool = ToolDefinition.from("greet", "Greets a user", nameParam, n -> "Hello, " + n + "!"); + Object result = tool.handler().invoke(invocationOf(Map.of("name", "Alice"))).get(); + assertEquals("Hello, Alice!", result); + } + + @Test + void from_oneArg_schemaContainsParam() { + Param nameParam = Param.of(String.class, "name", "The user's name"); + ToolDefinition tool = ToolDefinition.from("greet", "Greets a user", nameParam, n -> "Hello, " + n + "!"); + assertTrue(propertiesOf(tool).containsKey("name")); + assertTrue(requiredOf(tool).contains("name")); + } + + // ── Group 1: Successful inline definitions – arity 2, sync ─────────────────── + + @Test + void from_twoArg_invokesHandler() throws Exception { + Param paramA = Param.of(Integer.class, "a", "First number"); + Param paramB = Param.of(Integer.class, "b", "Second number"); + ToolDefinition tool = ToolDefinition.from("add", "Adds two integers", paramA, paramB, + (a, b) -> String.valueOf(a + b)); + Object result = tool.handler().invoke(invocationOf(Map.of("a", 3, "b", 4))).get(); + assertEquals("7", result); + } + + @Test + void from_twoArg_schemaBothParamsPresent() { + Param paramA = Param.of(Integer.class, "a", "First"); + Param paramB = Param.of(Integer.class, "b", "Second"); + ToolDefinition tool = ToolDefinition.from("add", "Adds two integers", paramA, paramB, (a, b) -> a + b); + assertTrue(propertiesOf(tool).containsKey("a")); + assertTrue(propertiesOf(tool).containsKey("b")); + assertTrue(requiredOf(tool).contains("a")); + assertTrue(requiredOf(tool).contains("b")); + } + + // ── Group 2: Async handlers (fromAsync) ────────────────────────────────────── + + @Test + void fromAsync_zeroArg_invokesHandler() throws Exception { + ToolDefinition tool = ToolDefinition.fromAsync("ping_async", "Async ping", + () -> CompletableFuture.completedFuture("pong")); + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("pong", result); + } + + @Test + void fromAsync_oneArg_invokesHandler() throws Exception { + Param nameParam = Param.of(String.class, "name", "Name to greet"); + ToolDefinition tool = ToolDefinition.fromAsync("greet_async", "Async greet", nameParam, + n -> CompletableFuture.completedFuture("Hi, " + n + "!")); + Object result = tool.handler().invoke(invocationOf(Map.of("name", "Bob"))).get(); + assertEquals("Hi, Bob!", result); + } + + @Test + void fromAsync_twoArg_invokesHandler() throws Exception { + Param paramA = Param.of(Integer.class, "a", "Left operand"); + Param paramB = Param.of(Integer.class, "b", "Right operand"); + ToolDefinition tool = ToolDefinition.fromAsync("add_async", "Async add", paramA, paramB, + (a, b) -> CompletableFuture.completedFuture(String.valueOf(a + b))); + Object result = tool.handler().invoke(invocationOf(Map.of("a", 10, "b", 5))).get(); + assertEquals("15", result); + } + + // ── Group 3: ToolInvocation context injection (sync) ───────────────────────── + + @Test + void fromWithToolInvocation_zeroArg_receivesContext() throws Exception { + ToolDefinition tool = ToolDefinition.fromWithToolInvocation("ctx_sync", "Returns session id", + inv -> "session=" + inv.getSessionId()); + Object result = tool.handler().invoke(invocationWithContext("sess-1", "call-1", Map.of())).get(); + assertEquals("session=sess-1", result); + } + + @Test + void fromWithToolInvocation_zeroArg_emptySchema() { + ToolDefinition tool = ToolDefinition.fromWithToolInvocation("ctx_sync", "Returns session id", + inv -> "session=" + inv.getSessionId()); + assertTrue(propertiesOf(tool).isEmpty()); + assertTrue(requiredOf(tool).isEmpty()); + } + + @Test + void fromWithToolInvocation_oneArg_receivesArgAndContext() throws Exception { + Param phaseParam = Param.of(String.class, "phase", "Current phase"); + ToolDefinition tool = ToolDefinition.fromWithToolInvocation("report", "Report phase", phaseParam, + (phase, inv) -> "phase=" + phase + ",callId=" + inv.getToolCallId()); + Object result = tool.handler().invoke(invocationWithContext("sess-2", "call-42", Map.of("phase", "analysis"))) + .get(); + assertEquals("phase=analysis,callId=call-42", result); + } + + @Test + void fromWithToolInvocation_oneArg_schemaExcludesInvocationParam() { + Param phaseParam = Param.of(String.class, "phase", "Current phase"); + ToolDefinition tool = ToolDefinition.fromWithToolInvocation("report", "Report phase", phaseParam, + (phase, inv) -> phase); + assertTrue(propertiesOf(tool).containsKey("phase")); + assertFalse(propertiesOf(tool).containsKey("invocation")); + assertEquals(List.of("phase"), requiredOf(tool)); + } + + // ── Group 4: Async ToolInvocation context injection ────────────────────────── + + @Test + void fromAsyncWithToolInvocation_zeroArg_receivesContext() throws Exception { + ToolDefinition tool = ToolDefinition.fromAsyncWithToolInvocation("ctx_async", "Async ctx", + inv -> CompletableFuture.completedFuture("callId=" + inv.getToolCallId())); + Object result = tool.handler().invoke(invocationWithContext("sess-3", "call-99", Map.of())).get(); + assertEquals("callId=call-99", result); + } + + @Test + void fromAsyncWithToolInvocation_oneArg_receivesArgAndContext() throws Exception { + Param phaseParam = Param.of(String.class, "phase", "Phase name"); + ToolDefinition tool = ToolDefinition.fromAsyncWithToolInvocation("report_async", "Async report", phaseParam, + (phase, inv) -> CompletableFuture.completedFuture("phase=" + phase + ",sess=" + inv.getSessionId())); + Object result = tool.handler().invoke(invocationWithContext("sess-4", "call-7", Map.of("phase", "planning"))) + .get(); + assertEquals("phase=planning,sess=sess-4", result); + } + + // ── Group 5: Option flag propagation ───────────────────────────────────────── + + @Test + void overridesBuiltInTool_setsFlag() { + ToolDefinition base = ToolDefinition.from("grep", "Custom grep", () -> "ok"); + assertNull(base.overridesBuiltInTool()); + ToolDefinition withOverride = base.overridesBuiltInTool(true); + assertEquals(Boolean.TRUE, withOverride.overridesBuiltInTool()); + } + + @Test + void overridesBuiltInTool_doesNotMutateOriginal() { + ToolDefinition base = ToolDefinition.from("grep", "Custom grep", () -> "ok"); + base.overridesBuiltInTool(true); + assertNull(base.overridesBuiltInTool(), "original must remain unchanged"); + } + + @Test + void skipPermission_setsFlag() { + ToolDefinition base = ToolDefinition.from("read_file", "Reads a file", () -> "contents"); + assertNull(base.skipPermission()); + ToolDefinition withSkip = base.skipPermission(true); + assertEquals(Boolean.TRUE, withSkip.skipPermission()); + } + + @Test + void skipPermission_doesNotMutateOriginal() { + ToolDefinition base = ToolDefinition.from("read_file", "Reads a file", () -> "contents"); + base.skipPermission(true); + assertNull(base.skipPermission(), "original must remain unchanged"); + } + + @Test + void defer_setsAutoMode() { + ToolDefinition base = ToolDefinition.from("search", "Searches things", () -> "results"); + assertNull(base.defer()); + ToolDefinition deferred = base.defer(ToolDefer.AUTO); + assertEquals(ToolDefer.AUTO, deferred.defer()); + } + + @Test + void defer_setsNeverMode() { + ToolDefinition base = ToolDefinition.from("must_preload", "Always preloaded", () -> "ok"); + ToolDefinition neverDeferred = base.defer(ToolDefer.NEVER); + assertEquals(ToolDefer.NEVER, neverDeferred.defer()); + } + + @Test + void defer_doesNotMutateOriginal() { + ToolDefinition base = ToolDefinition.from("search", "Searches things", () -> "results"); + base.defer(ToolDefer.AUTO); + assertNull(base.defer(), "original must remain unchanged"); + } + + @Test + void fluentModifiers_canBeChained() { + ToolDefinition tool = ToolDefinition.from("override_tool", "Overrides built-in", () -> "ok") + .overridesBuiltInTool(true).skipPermission(true).defer(ToolDefer.AUTO); + assertEquals(Boolean.TRUE, tool.overridesBuiltInTool()); + assertEquals(Boolean.TRUE, tool.skipPermission()); + assertEquals(ToolDefer.AUTO, tool.defer()); + } + + @Test + void fluentModifiers_preserveHandlerAndSchema() throws Exception { + Param p = Param.of(String.class, "msg", "A message"); + ToolDefinition tool = ToolDefinition.from("echo", "Echoes message", p, msg -> msg).skipPermission(true) + .overridesBuiltInTool(false); + assertNotNull(tool.handler()); + Object result = tool.handler().invoke(invocationOf(Map.of("msg", "hello"))).get(); + assertEquals("hello", result); + } + + // ── Group 6: Required/default semantics ────────────────────────────────────── + + @Test + void requiredParam_passedValue_usesProvidedValue() throws Exception { + Param p = Param.of(String.class, "word", "A word"); + ToolDefinition tool = ToolDefinition.from("echo", "Echoes", p, w -> w); + Object result = tool.handler().invoke(invocationOf(Map.of("word", "hello"))).get(); + assertEquals("hello", result); + } + + @Test + void requiredParam_missingFromInvocation_throwsIllegalArgumentException() { + Param p = Param.of(String.class, "word", "A required word"); + ToolDefinition tool = ToolDefinition.from("echo", "Echoes", p, w -> w); + var ex = assertThrows(IllegalArgumentException.class, () -> tool.handler().invoke(invocationOf(Map.of()))); + assertTrue(ex.getMessage().contains("word"), "Exception message should mention the missing parameter name"); + } + + @Test + void optionalParamWithDefault_absent_usesDefault() throws Exception { + Param p = Param.of(Integer.class, "limit", "Max results", false, "10"); + ToolDefinition tool = ToolDefinition.from("list", "Lists items", p, lim -> "limit=" + lim); + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("limit=10", result); + } + + @Test + void optionalParamWithDefault_provided_usesProvidedValue() throws Exception { + Param p = Param.of(Integer.class, "limit", "Max results", false, "10"); + ToolDefinition tool = ToolDefinition.from("list", "Lists items", p, lim -> "limit=" + lim); + Object result = tool.handler().invoke(invocationOf(Map.of("limit", 25))).get(); + assertEquals("limit=25", result); + } + + @Test + void optionalParamWithDefault_schemaNotInRequired() { + Param p = Param.of(Integer.class, "limit", "Max results", false, "10"); + ToolDefinition tool = ToolDefinition.from("list", "Lists items", p, lim -> "limit=" + lim); + assertFalse(requiredOf(tool).contains("limit")); + assertTrue(propertiesOf(tool).containsKey("limit")); + } + + @Test + void optionalParam_absent_noDefaultYieldsNull() throws Exception { + Param p = Param.of(String.class, "title", "Optional title", false, ""); + ToolDefinition tool = ToolDefinition.from("greet", "Greets", p, t -> t == null ? "(no title)" : t); + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("(no title)", result); + } + + @Test + void defaultValueAppearsInSchema() { + Param p = Param.of(Integer.class, "limit", "Max results", false, "5"); + ToolDefinition tool = ToolDefinition.from("list", "Lists items", p, lim -> lim.toString()); + @SuppressWarnings("unchecked") + Map limitPropSchema = (Map) propertiesOf(tool).get("limit"); + assertNotNull(limitPropSchema, "Schema must include 'limit' property"); + assertEquals(5, limitPropSchema.get("default"), "Default value must appear in schema"); + } + + // ── Group 7: Error / validation paths ──────────────────────────────────────── + + @Test + void from_nullName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.from(null, "desc", () -> "ok")); + } + + @Test + void from_blankName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.from(" ", "desc", () -> "ok")); + } + + @Test + void from_nullDescription_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.from("tool", null, () -> "ok")); + } + + @Test + void from_blankDescription_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.from("tool", "", () -> "ok")); + } + + @Test + void from_nullHandler_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, + () -> ToolDefinition.from("tool", "desc", (java.util.function.Supplier) null)); + } + + @Test + void from_oneArg_nullParam_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, + () -> ToolDefinition.from("tool", "desc", (Param) null, s -> s)); + } + + @Test + void from_twoArg_nullFirstParam_throwsIllegalArgumentException() { + Param p2 = Param.of(String.class, "b", "B param"); + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.from("tool", "desc", null, p2, (a, b) -> a)); + } + + @Test + void from_twoArg_nullSecondParam_throwsIllegalArgumentException() { + Param p1 = Param.of(String.class, "a", "A param"); + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.from("tool", "desc", p1, null, (a, b) -> a)); + } + + @Test + void from_twoArg_duplicateParamNames_throwsIllegalArgumentException() { + Param p1 = Param.of(String.class, "name", "Name 1"); + Param p2 = Param.of(String.class, "name", "Name 2"); + var ex = assertThrows(IllegalArgumentException.class, + () -> ToolDefinition.from("tool", "desc", p1, p2, (a, b) -> a + b)); + assertTrue(ex.getMessage().contains("name"), "error must mention the duplicate param name"); + assertTrue(ex.getMessage().contains("tool"), "error must mention the tool name"); + } + + @Test + void fromAsync_nullName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, + () -> ToolDefinition.fromAsync(null, "desc", () -> CompletableFuture.completedFuture("ok"))); + } + + @Test + void fromAsync_nullHandler_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.fromAsync("tool", "desc", + (java.util.function.Supplier>) null)); + } + + @Test + void fromWithToolInvocation_nullName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, + () -> ToolDefinition.fromWithToolInvocation(null, "desc", inv -> "ok")); + } + + @Test + void fromAsyncWithToolInvocation_nullDescription_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> ToolDefinition.fromAsyncWithToolInvocation("tool", null, + inv -> CompletableFuture.completedFuture("ok"))); + } + + // ── Group 8: Schema structure + // ───────────────────────────────────────────────── + + @Test + void schema_zeroArg_hasTypeObjectAndEmptyMaps() { + ToolDefinition tool = ToolDefinition.from("noop", "No-op", () -> "done"); + Map schema = schemaOf(tool); + assertEquals("object", schema.get("type")); + assertTrue(((Map) schema.get("properties")).isEmpty()); + assertTrue(((List) schema.get("required")).isEmpty()); + } + + @Test + void schema_oneArg_hasCorrectTypeForString() { + Param p = Param.of(String.class, "query", "Search query"); + ToolDefinition tool = ToolDefinition.from("search", "Searches", p, q -> q); + @SuppressWarnings("unchecked") + Map querySchema = (Map) propertiesOf(tool).get("query"); + assertNotNull(querySchema); + assertEquals("string", querySchema.get("type")); + assertEquals("Search query", querySchema.get("description")); + } + + @Test + void schema_oneArg_hasCorrectTypeForInteger() { + Param p = Param.of(Integer.class, "count", "Item count"); + ToolDefinition tool = ToolDefinition.from("count_items", "Counts items", p, c -> c.toString()); + @SuppressWarnings("unchecked") + Map countSchema = (Map) propertiesOf(tool).get("count"); + assertNotNull(countSchema); + assertEquals("integer", countSchema.get("type")); + } + + @Test + void schema_oneArg_hasCorrectTypeForBoolean() { + Param p = Param.of(Boolean.class, "enabled", "Whether enabled"); + ToolDefinition tool = ToolDefinition.from("toggle", "Toggles", p, e -> e.toString()); + @SuppressWarnings("unchecked") + Map enabledSchema = (Map) propertiesOf(tool).get("enabled"); + assertNotNull(enabledSchema); + assertEquals("boolean", enabledSchema.get("type")); + } + + @Test + void schema_oneArg_enumTypeHasStringAndEnumValues() { + Param p = Param.of(Color.class, "color", "A color"); + ToolDefinition tool = ToolDefinition.from("paint", "Paints with a color", p, c -> c.name()); + @SuppressWarnings("unchecked") + Map colorSchema = (Map) propertiesOf(tool).get("color"); + assertNotNull(colorSchema); + assertEquals("string", colorSchema.get("type")); + @SuppressWarnings("unchecked") + List enumValues = (List) colorSchema.get("enum"); + assertNotNull(enumValues); + assertTrue(enumValues.contains("RED")); + assertTrue(enumValues.contains("GREEN")); + assertTrue(enumValues.contains("BLUE")); + } + + // ── Group 9: Result formatting + // ──────────────────────────────────────────────── + + @Test + void resultFormatting_stringReturnedAsIs() throws Exception { + ToolDefinition tool = ToolDefinition.from("echo", "Echoes", () -> "plain text"); + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("plain text", result); + } + + @Test + void resultFormatting_nullMappedToSuccess() throws Exception { + ToolDefinition tool = ToolDefinition.from("noop", "No-op", () -> null); + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("Success", result); + } + + @Test + void resultFormatting_nonStringSerializedToJson() throws Exception { + Param p = Param.of(String.class, "key", "Key name"); + ToolDefinition tool = ToolDefinition.from("to_map", "Wraps in map", p, k -> Map.of("key", k, "value", 42)); + Object result = tool.handler().invoke(invocationOf(Map.of("key", "x"))).get(); + assertNotNull(result); + assertTrue(result instanceof String, "Non-String should be JSON-serialized to String"); + String json = (String) result; + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = mapper.readTree(json); + assertTrue(node.isObject(), "Result should be a JSON object"); + assertEquals("x", node.get("key").asText(), "JSON must contain key field with value 'x'"); + assertEquals(42, node.get("value").asInt(), "JSON must contain value field with value 42"); + } + + @Test + void resultFormatting_integerSerializedToJson() throws Exception { + ToolDefinition tool = ToolDefinition.from("forty_two", "Returns 42", () -> 42); + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("42", result); + } + + // ── Group 10: Argument coercion + // ─────────────────────────────────────────────── + + @Test + void coercion_stringArgPassedThrough() throws Exception { + Param p = Param.of(String.class, "msg", "A message"); + ToolDefinition tool = ToolDefinition.from("echo", "Echoes message", p, m -> m); + Object result = tool.handler().invoke(invocationOf(Map.of("msg", "hello world"))).get(); + assertEquals("hello world", result); + } + + @Test + void coercion_integerArgFromJsonNumber() throws Exception { + Param p = Param.of(Integer.class, "n", "An integer"); + ToolDefinition tool = ToolDefinition.from("double_it", "Doubles n", p, n -> String.valueOf(n * 2)); + Object result = tool.handler().invoke(invocationOf(Map.of("n", 7))).get(); + assertEquals("14", result); + } + + @Test + void coercion_booleanArg() throws Exception { + Param p = Param.of(Boolean.class, "flag", "A flag"); + ToolDefinition tool = ToolDefinition.from("flagged", "Reports flag", p, f -> f ? "yes" : "no"); + Object result = tool.handler().invoke(invocationOf(Map.of("flag", true))).get(); + assertEquals("yes", result); + } + + @Test + void coercion_enumArgFromString() throws Exception { + Param p = Param.of(Color.class, "color", "A color"); + ToolDefinition tool = ToolDefinition.from("paint", "Paints", p, c -> c.name().toLowerCase()); + Object result = tool.handler().invoke(invocationOf(Map.of("color", "GREEN"))).get(); + assertEquals("green", result); + } + + @Test + void coercion_defaultIntegerParsedCorrectly() throws Exception { + Param p = Param.of(Integer.class, "limit", "Max count", false, "99"); + ToolDefinition tool = ToolDefinition.from("bounded", "Bounded list", p, lim -> "got=" + lim); + // No argument provided — should use default 99 + Object result = tool.handler().invoke(invocationOf(Map.of())).get(); + assertEquals("got=99", result); + } + + // ── Inner types for test helpers + // ────────────────────────────────────────────── + + enum Color { + RED, GREEN, BLUE + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/ArgCoercionTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/ArgCoercionTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..5cc5ee87a5 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/ArgCoercionTools$$CopilotToolMeta.java @@ -0,0 +1,50 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class ArgCoercionTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(ArgCoercionTools instance, ObjectMapper mapper) { + return List + .of(new ToolDefinition("mixed_args", "Method with mixed argument types", Map.of( + "type", "object", "properties", Map + .ofEntries( + Map.entry("text", + (Map) (Map) withMeta(Map.of("type", "string"), + "Text input", null)), + Map.entry("count", + (Map) (Map) withMeta(Map.of("type", "integer"), + "A count", null)), + Map.entry("flag", + (Map) (Map) withMeta(Map.of("type", "boolean"), + "A flag", null)), + Map.entry("color", + (Map) (Map) withMeta(Map.of("type", "string", "enum", + List.of("RED", "GREEN", "BLUE")), "A color", null))), + "required", List.of("text", "count", "flag", "color")), invocation -> { + Map args = invocation.getArguments(); + String text = (String) args.get("text"); + int count = ((Number) args.get("count")).intValue(); + boolean flag = (Boolean) args.get("flag"); + ArgCoercionTools.Color color = ArgCoercionTools.Color.valueOf((String) args.get("color")); + return CompletableFuture.completedFuture(instance.mixedArgs(text, count, flag, color)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/ArgCoercionTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/ArgCoercionTools.java new file mode 100644 index 0000000000..f19af7bff7 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/ArgCoercionTools.java @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Fixture testing argument coercion with multiple types including an enum. + */ +public class ArgCoercionTools { + + public enum Color { + RED, GREEN, BLUE + } + + @CopilotTool("Method with mixed argument types") + public String mixedArgs(@CopilotToolParam("Text input") String text, @CopilotToolParam("A count") int count, + @CopilotToolParam("A flag") boolean flag, @CopilotToolParam("A color") Color color) { + return text + "-" + count + "-" + flag + "-" + color.name(); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/DateTimeTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/DateTimeTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..0c2b1f07e7 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/DateTimeTools$$CopilotToolMeta.java @@ -0,0 +1,38 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.time.LocalDateTime; +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class DateTimeTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(DateTimeTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition("schedule_event", "Schedule an event at a given time", + Map.of("type", "object", "properties", + Map.ofEntries(Map.entry("when", + (Map) (Map) withMeta(Map.of("type", "string", "format", "date-time"), + "When to schedule", null))), + "required", List.of("when")), + invocation -> { + Map args = invocation.getArguments(); + LocalDateTime when = mapper.convertValue(args.get("when"), LocalDateTime.class); + return CompletableFuture.completedFuture(instance.scheduleEvent(when)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/DateTimeTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/DateTimeTools.java new file mode 100644 index 0000000000..f0fdf9fdc8 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/DateTimeTools.java @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import java.time.LocalDateTime; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Fixture testing java.time argument deserialization via ObjectMapper with + * JavaTimeModule. + */ +public class DateTimeTools { + + @CopilotTool("Schedule an event at a given time") + public String scheduleEvent(@CopilotToolParam(value = "When to schedule", required = true) LocalDateTime when) { + return "Scheduled at " + when.getYear() + "-" + String.format("%02d", when.getMonthValue()) + "-" + + String.format("%02d", when.getDayOfMonth()) + "T" + String.format("%02d", when.getHour()) + ":" + + String.format("%02d", when.getMinute()); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/DefaultValueTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/DefaultValueTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..6cef2e03a0 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/DefaultValueTools$$CopilotToolMeta.java @@ -0,0 +1,45 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class DefaultValueTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(DefaultValueTools instance, ObjectMapper mapper) { + return List + .of(new ToolDefinition( + "with_default", "Method with a default value parameter", Map + .of("type", "object", "properties", + Map.ofEntries( + Map.entry("label", + (Map) (Map) withMeta(Map.of("type", "string"), + "A label", null)), + Map.entry("count", + (Map) (Map) withMeta(Map.of("type", "integer"), + "A count", 42))), + "required", List.of("label")), + invocation -> { + Map args = invocation.getArguments(); + String label = (String) args.get("label"); + Object countRaw = args.containsKey("count") ? args.get("count") : 42; + int count = ((Number) countRaw).intValue(); + return CompletableFuture.completedFuture(instance.withDefault(label, count)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/DefaultValueTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/DefaultValueTools.java new file mode 100644 index 0000000000..942ededd89 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/DefaultValueTools.java @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Fixture testing default parameter values. + */ +public class DefaultValueTools { + + @CopilotTool("Method with a default value parameter") + public String withDefault(@CopilotToolParam(value = "A label", required = true) String label, + @CopilotToolParam(value = "A count", required = false, defaultValue = "42") int count) { + return label + ":" + count; + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/InvocationAwareTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/InvocationAwareTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..e7c78608a0 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/InvocationAwareTools$$CopilotToolMeta.java @@ -0,0 +1,74 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output for ToolInvocation injection. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.RecordInvocationArgs; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public final class InvocationAwareTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(InvocationAwareTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition("report_progress", "Reports progress with invocation context", + Map.of("type", "object", "properties", + Map.ofEntries(Map.entry("phase", Map.of("type", "string", "description", "Current phase"))), + "required", List.of("phase")), + invocation -> { + Map args = invocation.getArguments(); + String phase = (String) args.get("phase"); + return CompletableFuture.completedFuture(instance.reportProgress(phase, invocation)); + }, null, null, null, null), + new ToolDefinition("report_progress_async", "Reports progress asynchronously with invocation context", + Map.of("type", "object", "properties", + Map.ofEntries( + Map.entry("phase", Map.of("type", "string", "description", "Current phase"))), + "required", List.of("phase")), + invocation -> { + Map args = invocation.getArguments(); + String phase = (String) args.get("phase"); + return instance.reportProgressAsync(phase, invocation).thenApply(r -> (Object) r); + }, null, null, null, null), + new ToolDefinition("report_progress_first", "Reports progress with invocation first", + Map.of("type", "object", "properties", + Map.ofEntries( + Map.entry("phase", Map.of("type", "string", "description", "Current phase"))), + "required", List.of("phase")), + invocation -> { + Map args = invocation.getArguments(); + String phase = (String) args.get("phase"); + return CompletableFuture.completedFuture(instance.reportProgressFirst(invocation, phase)); + }, null, null, null, null), + new ToolDefinition("only_context", "Reports context with invocation only", + Map.of("type", "object", "properties", Map.of(), "required", List.of()), + invocation -> CompletableFuture.completedFuture(instance.onlyContext(invocation)), null, null, + null, null), + new ToolDefinition("report_progress_middle", "Reports progress with invocation in the middle", Map.of( + "type", "object", "properties", + Map.ofEntries(Map.entry("phase", Map.of("type", "string", "description", "Current phase")), + Map.entry("limit", Map.of("type", "integer", "description", "Maximum items"))), + "required", List.of("phase", "limit")), invocation -> { + Map args = invocation.getArguments(); + String phase = (String) args.get("phase"); + int limit = ((Number) args.get("limit")).intValue(); + return CompletableFuture + .completedFuture(instance.reportProgressMiddle(phase, invocation, limit)); + }, null, null, null, null), + new ToolDefinition("report_progress_with_record", "Reports progress with record args and invocation", + Map.of("type", "object", "properties", + Map.ofEntries(Map.entry("query", Map.of("type", "string")), + Map.entry("limit", Map.of("type", "integer"))), + "required", List.of("query", "limit")), + invocation -> { + RecordInvocationArgs args = mapper.convertValue(invocation.getArguments(), + RecordInvocationArgs.class); + return CompletableFuture + .completedFuture(instance.reportProgressWithRecord(args, invocation)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/InvocationAwareTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/InvocationAwareTools.java new file mode 100644 index 0000000000..ac9c9bc78d --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/InvocationAwareTools.java @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import java.util.concurrent.CompletableFuture; + +import com.github.copilot.rpc.RecordInvocationArgs; +import com.github.copilot.rpc.ToolInvocation; +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Tool fixture for {@link ToolInvocation} runtime context injection. + */ +public class InvocationAwareTools { + + @CopilotTool("Reports progress with invocation context") + public String reportProgress(@CopilotToolParam("Current phase") String phase, ToolInvocation invocation) { + return "phase=" + phase + ",sessionId=" + invocation.getSessionId() + ",toolCallId=" + + invocation.getToolCallId() + ",toolName=" + invocation.getToolName(); + } + + @CopilotTool("Reports progress asynchronously with invocation context") + public CompletableFuture reportProgressAsync(@CopilotToolParam("Current phase") String phase, + ToolInvocation invocation) { + return CompletableFuture.completedFuture("async phase=" + phase + ",sessionId=" + invocation.getSessionId() + + ",toolCallId=" + invocation.getToolCallId() + ",toolName=" + invocation.getToolName()); + } + + @CopilotTool("Reports progress with invocation first") + public String reportProgressFirst(ToolInvocation invocation, @CopilotToolParam("Current phase") String phase) { + return "first phase=" + phase + ",sessionId=" + invocation.getSessionId() + ",toolCallId=" + + invocation.getToolCallId() + ",toolName=" + invocation.getToolName(); + } + + @CopilotTool("Reports context with invocation only") + public String onlyContext(ToolInvocation invocation) { + return "only sessionId=" + invocation.getSessionId() + ",toolCallId=" + invocation.getToolCallId() + + ",toolName=" + invocation.getToolName(); + } + + @CopilotTool("Reports progress with invocation in the middle") + public String reportProgressMiddle(@CopilotToolParam("Current phase") String phase, ToolInvocation invocation, + @CopilotToolParam("Maximum items") int limit) { + return "middle phase=" + phase + ",limit=" + limit + ",sessionId=" + invocation.getSessionId() + ",toolCallId=" + + invocation.getToolCallId() + ",toolName=" + invocation.getToolName(); + } + + @CopilotTool("Reports progress with record args and invocation") + public String reportProgressWithRecord(RecordInvocationArgs args, ToolInvocation invocation) { + return "record query=" + args.query() + ",limit=" + args.limit() + ",sessionId=" + invocation.getSessionId() + + ",toolCallId=" + invocation.getToolCallId() + ",toolName=" + invocation.getToolName(); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/MultiReturnTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/MultiReturnTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..571db8e7cb --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/MultiReturnTools$$CopilotToolMeta.java @@ -0,0 +1,29 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class MultiReturnTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(MultiReturnTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition("string_method", "Returns a string", + Map.of("type", "object", "properties", Map.of(), "required", List.of()), invocation -> { + return CompletableFuture.completedFuture(instance.stringMethod()); + }, null, null, null, null), new ToolDefinition("void_method", "Void method", + Map.of("type", "object", "properties", Map.of(), "required", List.of()), invocation -> { + instance.voidMethod(); + return CompletableFuture.completedFuture("Success"); + }, null, null, null, null), + new ToolDefinition("async_method", "Async method", + Map.of("type", "object", "properties", Map.of(), "required", List.of()), invocation -> { + return instance.asyncMethod().thenApply(r -> (Object) r); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/MultiReturnTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/MultiReturnTools.java new file mode 100644 index 0000000000..62a6a2500f --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/MultiReturnTools.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import java.util.concurrent.CompletableFuture; + +import com.github.copilot.tool.CopilotTool; + +/** + * Fixture testing different return type patterns. + */ +public class MultiReturnTools { + + @CopilotTool("Returns a string") + public String stringMethod() { + return "hello"; + } + + @CopilotTool("Void method") + public void voidMethod() { + // side-effect only + } + + @CopilotTool("Async method") + public CompletableFuture asyncMethod() { + return CompletableFuture.completedFuture("async result"); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/OptionalParamTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/OptionalParamTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..75fde6bb3c --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/OptionalParamTools$$CopilotToolMeta.java @@ -0,0 +1,101 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output for Optional parameters. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class OptionalParamTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(OptionalParamTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition( + "greet_with_title", "Greet with optional title", Map + .of("type", "object", "properties", + Map.ofEntries( + Map.entry("name", + (Map) (Map) withMeta(Map.of("type", "string"), "Name", + null)), + Map.entry("title", + (Map) (Map) withMeta(Map.of("type", "string"), + "Optional title", null))), + "required", List.of("name")), + invocation -> { + Map args = invocation.getArguments(); + String name = (String) args.get("name"); + Object titleRaw = args.get("title"); + Optional title = titleRaw != null ? Optional.of((String) titleRaw) : Optional.empty(); + return CompletableFuture.completedFuture(instance.greetWithTitle(name, title)); + }, null, null, null, null), + new ToolDefinition("multiply", "Multiply with optional factor", + Map.of("type", "object", "properties", + Map.ofEntries( + Map.entry("base", + (Map) (Map) withMeta(Map.of("type", "integer"), + "Base value", null)), + Map.entry("factor", + (Map) (Map) withMeta(Map.of("type", "integer"), + "Optional factor", null))), + "required", List.of("base")), + invocation -> { + Map args = invocation.getArguments(); + int base = ((Number) args.get("base")).intValue(); + Object factorRaw = args.get("factor"); + OptionalInt factor = factorRaw != null + ? OptionalInt.of(((Number) factorRaw).intValue()) + : OptionalInt.empty(); + return CompletableFuture.completedFuture(instance.multiply(base, factor)); + }, null, null, null, null), + new ToolDefinition("scale", "Scale with optional ratio", + Map.of("type", "object", "properties", + Map.ofEntries( + Map.entry("value", + (Map) (Map) withMeta(Map.of("type", "number"), "Value", + null)), + Map.entry("ratio", + (Map) (Map) withMeta(Map.of("type", "number"), + "Optional ratio", null))), + "required", List.of("value")), + invocation -> { + Map args = invocation.getArguments(); + double value = ((Number) args.get("value")).doubleValue(); + Object ratioRaw = args.get("ratio"); + OptionalDouble ratio = ratioRaw != null + ? OptionalDouble.of(((Number) ratioRaw).doubleValue()) + : OptionalDouble.empty(); + return CompletableFuture.completedFuture(instance.scale(value, ratio)); + }, null, null, null, null), + new ToolDefinition("offset", "Offset with optional delta", + Map.of("type", "object", "properties", + Map.ofEntries( + Map.entry("base", + (Map) (Map) withMeta(Map.of("type", "integer"), "Base", + null)), + Map.entry("delta", + (Map) (Map) withMeta(Map.of("type", "integer"), + "Optional delta", null))), + "required", List.of("base")), + invocation -> { + Map args = invocation.getArguments(); + long base = ((Number) args.get("base")).longValue(); + Object deltaRaw = args.get("delta"); + OptionalLong delta = deltaRaw != null + ? OptionalLong.of(((Number) deltaRaw).longValue()) + : OptionalLong.empty(); + return CompletableFuture.completedFuture(instance.offset(base, delta)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/OptionalParamTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/OptionalParamTools.java new file mode 100644 index 0000000000..2986cb1c7c --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/OptionalParamTools.java @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Tool fixture with Optional parameter types for testing correct argument + * extraction (null-check + wrapping instead of mapper.convertValue). + */ +public class OptionalParamTools { + + @CopilotTool("Greet with optional title") + public String greetWithTitle(@CopilotToolParam("Name") String name, + @CopilotToolParam("Optional title") Optional title) { + return title.map(t -> t + " " + name).orElse(name); + } + + @CopilotTool("Multiply with optional factor") + public String multiply(@CopilotToolParam("Base value") int base, + @CopilotToolParam("Optional factor") OptionalInt factor) { + return String.valueOf(base * factor.orElse(1)); + } + + @CopilotTool("Scale with optional ratio") + public String scale(@CopilotToolParam("Value") double value, + @CopilotToolParam("Optional ratio") OptionalDouble ratio) { + return String.valueOf(value * ratio.orElse(1.0)); + } + + @CopilotTool("Offset with optional delta") + public String offset(@CopilotToolParam("Base") long base, @CopilotToolParam("Optional delta") OptionalLong delta) { + return String.valueOf(base + delta.orElse(0L)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/OverrideTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/OverrideTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..2d37204f82 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/OverrideTools$$CopilotToolMeta.java @@ -0,0 +1,39 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class OverrideTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(OverrideTools instance, ObjectMapper mapper) { + return List + .of(new ToolDefinition( + "grep", "Custom grep implementation", Map + .of("type", "object", "properties", + Map.ofEntries(Map.entry("pattern", + (Map) (Map) withMeta(Map.of("type", "string"), + "Search pattern", null))), + "required", List.of("pattern")), + invocation -> { + Map args = invocation.getArguments(); + String pattern = (String) args.get("pattern"); + return CompletableFuture.completedFuture(instance.customGrep(pattern)); + }, Boolean.TRUE, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/OverrideTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/OverrideTools.java new file mode 100644 index 0000000000..9900830661 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/OverrideTools.java @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Fixture testing tool override flag. + */ +public class OverrideTools { + + @CopilotTool(value = "Custom grep implementation", name = "grep", overridesBuiltInTool = true) + public String customGrep(@CopilotToolParam(value = "Search pattern", required = true) String pattern) { + return "Found: " + pattern; + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/SimpleTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/SimpleTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..ac38d0cce2 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/SimpleTools$$CopilotToolMeta.java @@ -0,0 +1,53 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class SimpleTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(SimpleTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition("greet_user", "Greets a user by name", + Map.of("type", "object", "properties", Map.ofEntries(Map.entry("name", + (Map) (Map) withMeta(Map.of("type", "string"), "The user's name", null))), + "required", List.of("name")), + invocation -> { + Map args = invocation.getArguments(); + String name = (String) args.get("name"); + return CompletableFuture.completedFuture(instance.greetUser(name)); + }, null, null, null, + Map.of("github.com/copilot:safeForTelemetry", + Map.of("name", true, "inputsNames", false))), + new ToolDefinition("add_numbers", "Adds two numbers together", + Map.of("type", "object", "properties", + Map.ofEntries( + Map.entry("a", + (Map) (Map) withMeta(Map.of("type", "integer"), + "First number", null)), + Map.entry("b", + (Map) (Map) withMeta(Map.of("type", "integer"), + "Second number", null))), + "required", List.of("a", "b")), + invocation -> { + Map args = invocation.getArguments(); + int a = ((Number) args.get("a")).intValue(); + int b = ((Number) args.get("b")).intValue(); + return CompletableFuture.completedFuture(instance.addNumbers(a, b)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/SimpleTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/SimpleTools.java new file mode 100644 index 0000000000..814b3883c3 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/SimpleTools.java @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Simple tool fixture with basic String-returning methods. + */ +public class SimpleTools { + + @CopilotTool(value = "Greets a user by name", metadata = { + @CopilotTool.MetadataEntry(key = "github.com/copilot:safeForTelemetry", value = @CopilotTool.MetadataValue(flags = { + @CopilotTool.MetadataFlag(name = "name", value = true), + @CopilotTool.MetadataFlag(name = "inputsNames", value = false)}))}) + public String greetUser(@CopilotToolParam(value = "The user's name", required = true) String name) { + return "Hello, " + name + "!"; + } + + @CopilotTool("Adds two numbers together") + public String addNumbers(@CopilotToolParam(value = "First number") int a, + @CopilotToolParam(value = "Second number") int b) { + return String.valueOf(a + b); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/StaticInvocationTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticInvocationTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..2535d671e8 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticInvocationTools$$CopilotToolMeta.java @@ -0,0 +1,29 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output for static ToolInvocation injection. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public final class StaticInvocationTools$$CopilotToolMeta + implements + CopilotToolMetadataProvider { + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(StaticInvocationTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition("report_static", "Returns invocation context from a static tool", + Map.of("type", "object", "properties", + Map.ofEntries(Map.entry("phase", Map.of("type", "string", "description", "Current phase"))), + "required", List.of("phase")), + invocation -> { + Map args = invocation.getArguments(); + String phase = (String) args.get("phase"); + return CompletableFuture.completedFuture(StaticInvocationTools.reportStatic(phase, invocation)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/StaticInvocationTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticInvocationTools.java new file mode 100644 index 0000000000..a5cba003c1 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticInvocationTools.java @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import com.github.copilot.rpc.ToolInvocation; +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Static tool fixture for {@link ToolInvocation} runtime context injection. + */ +public class StaticInvocationTools { + + @CopilotTool("Returns invocation context from a static tool") + public static String reportStatic(@CopilotToolParam("Current phase") String phase, ToolInvocation invocation) { + return "phase=" + phase + ",sessionId=" + invocation.getSessionId() + ",toolCallId=" + + invocation.getToolCallId() + ",toolName=" + invocation.getToolName(); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/StaticTools$$CopilotToolMeta.java b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticTools$$CopilotToolMeta.java new file mode 100644 index 0000000000..a0c6e66855 --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticTools$$CopilotToolMeta.java @@ -0,0 +1,37 @@ +// Hand-written test fixture mimicking CopilotToolProcessor output for static methods. +package com.github.copilot.rpc.fixtures; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.copilot.rpc.ToolDefinition; +import com.github.copilot.tool.CopilotToolMetadataProvider; + +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public final class StaticTools$$CopilotToolMeta implements CopilotToolMetadataProvider { + + private static Map withMeta(Map base, String description, Object defaultValue) { + var result = new LinkedHashMap(base); + if (description != null) + result.put("description", description); + if (defaultValue != null) + result.put("default", defaultValue); + return Collections.unmodifiableMap(result); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public List definitions(StaticTools instance, ObjectMapper mapper) { + return List.of(new ToolDefinition("greet", "Returns a greeting for the given name", + Map.of("type", "object", "properties", Map.ofEntries(Map.entry("name", + (Map) (Map) withMeta(Map.of("type", "string"), "The name to greet", null))), + "required", List.of("name")), + invocation -> { + Map args = invocation.getArguments(); + String name = (String) args.get("name"); + // Mimics what the processor now generates for static methods: + // QualifiedClassName.method(...) instead of instance.method(...) + return CompletableFuture.completedFuture(StaticTools.greet(name)); + }, null, null, null, null)); + } +} diff --git a/java/src/test/java/com/github/copilot/rpc/fixtures/StaticTools.java b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticTools.java new file mode 100644 index 0000000000..9caef593df --- /dev/null +++ b/java/src/test/java/com/github/copilot/rpc/fixtures/StaticTools.java @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.rpc.fixtures; + +import com.github.copilot.tool.CopilotTool; +import com.github.copilot.tool.CopilotToolParam; + +/** + * Tool fixture with a static {@code @CopilotTool} method, used to test + * {@code ToolDefinition.fromClass()} invocation path. + */ +public class StaticTools { + + @CopilotTool("Returns a greeting for the given name") + public static String greet(@CopilotToolParam(value = "The name to greet", required = true) String name) { + return "Hi, " + name + "!"; + } +} diff --git a/java/src/test/java/com/github/copilot/tool/CopilotToolAnnotationTest.java b/java/src/test/java/com/github/copilot/tool/CopilotToolAnnotationTest.java new file mode 100644 index 0000000000..649a4bd6c4 --- /dev/null +++ b/java/src/test/java/com/github/copilot/tool/CopilotToolAnnotationTest.java @@ -0,0 +1,155 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.InputStream; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.CompletableFuture; + +import org.junit.jupiter.api.Test; + +import com.github.copilot.CopilotExperimental; +import com.github.copilot.rpc.ToolDefer; + +/** + * Unit tests for {@link CopilotTool} and {@link CopilotToolParam} annotations. + */ +public class CopilotToolAnnotationTest { + + // --- @CopilotTool attribute verification --- + + @Test + void copilotToolHasRuntimeRetention() { + Retention retention = CopilotTool.class.getAnnotation(Retention.class); + assertNotNull(retention); + assertEquals(RetentionPolicy.RUNTIME, retention.value()); + } + + @Test + void copilotToolTargetsMethod() { + Target target = CopilotTool.class.getAnnotation(Target.class); + assertNotNull(target); + assertArrayEquals(new ElementType[]{ElementType.METHOD}, target.value()); + } + + @Test + void copilotExperimentalTargetsTypeForAnnotationDeclarations() { + Target expTarget = CopilotExperimental.class.getAnnotation(Target.class); + assertNotNull(expTarget); + boolean includesType = false; + for (ElementType et : expTarget.value()) { + if (et == ElementType.TYPE) { + includesType = true; + break; + } + } + assertTrue(includesType, "@CopilotExperimental must target TYPE to be applicable to annotation declarations"); + } + + @Test + void copilotToolDeclaresCopilotExperimentalInClassFile() throws Exception { + String classFileResourcePath = "/" + CopilotTool.class.getName().replace('.', '/') + ".class"; + try (InputStream classFile = CopilotTool.class.getResourceAsStream(classFileResourcePath)) { + assertNotNull(classFile, "CopilotTool class file must be readable as a resource"); + String classFileText = new String(classFile.readAllBytes(), StandardCharsets.ISO_8859_1); + assertTrue(classFileText.contains("com/github/copilot/CopilotExperimental")); + } + } + + @Test + void copilotToolDefaultValues() throws Exception { + Method nameMethod = CopilotTool.class.getDeclaredMethod("name"); + assertEquals("", nameMethod.getDefaultValue()); + + Method overridesMethod = CopilotTool.class.getDeclaredMethod("overridesBuiltInTool"); + assertEquals(false, overridesMethod.getDefaultValue()); + + Method skipMethod = CopilotTool.class.getDeclaredMethod("skipPermission"); + assertEquals(false, skipMethod.getDefaultValue()); + + Method deferMethod = CopilotTool.class.getDeclaredMethod("defer"); + assertEquals(ToolDefer.NONE, deferMethod.getDefaultValue()); + } + + // --- @CopilotToolParam attribute verification --- + + @Test + void paramHasRuntimeRetention() { + Retention retention = CopilotToolParam.class.getAnnotation(Retention.class); + assertNotNull(retention); + assertEquals(RetentionPolicy.RUNTIME, retention.value()); + } + + @Test + void paramTargetsParameter() { + Target target = CopilotToolParam.class.getAnnotation(Target.class); + assertNotNull(target); + assertArrayEquals(new ElementType[]{ElementType.PARAMETER}, target.value()); + } + + @Test + void paramDefaultValues() throws Exception { + Method valueMethod = CopilotToolParam.class.getDeclaredMethod("value"); + assertEquals("", valueMethod.getDefaultValue()); + + Method nameMethod = CopilotToolParam.class.getDeclaredMethod("name"); + assertEquals("", nameMethod.getDefaultValue()); + + Method requiredMethod = CopilotToolParam.class.getDeclaredMethod("required"); + assertEquals(true, requiredMethod.getDefaultValue()); + + Method defaultValueMethod = CopilotToolParam.class.getDeclaredMethod("defaultValue"); + assertEquals("", defaultValueMethod.getDefaultValue()); + } + + // --- Applicability test --- + + @SuppressWarnings("unused") + static class SampleToolHolder { + + @CopilotTool(value = "Get weather for a location", name = "get_weather", defer = ToolDefer.AUTO) + public CompletableFuture getWeather( + @CopilotToolParam(value = "City name", required = true) String location, + @CopilotToolParam(value = "Temperature unit", required = false, defaultValue = "celsius") String unit) { + return CompletableFuture.completedFuture("Sunny in " + location); + } + } + + @Test + void annotationsAreAccessibleViaReflection() throws Exception { + Method method = SampleToolHolder.class.getDeclaredMethod("getWeather", String.class, String.class); + + CopilotTool toolAnnotation = method.getAnnotation(CopilotTool.class); + assertNotNull(toolAnnotation); + assertEquals("Get weather for a location", toolAnnotation.value()); + assertEquals("get_weather", toolAnnotation.name()); + assertFalse(toolAnnotation.overridesBuiltInTool()); + assertFalse(toolAnnotation.skipPermission()); + assertEquals(ToolDefer.AUTO, toolAnnotation.defer()); + + Parameter[] params = method.getParameters(); + assertEquals(2, params.length); + + CopilotToolParam locationParam = params[0].getAnnotation(CopilotToolParam.class); + assertNotNull(locationParam); + assertEquals("City name", locationParam.value()); + assertTrue(locationParam.required()); + assertEquals("", locationParam.defaultValue()); + + CopilotToolParam unitParam = params[1].getAnnotation(CopilotToolParam.class); + assertNotNull(unitParam); + assertEquals("Temperature unit", unitParam.value()); + assertFalse(unitParam.required()); + assertEquals("celsius", unitParam.defaultValue()); + } +} diff --git a/java/src/test/java/com/github/copilot/tool/CopilotToolProcessorTest.java b/java/src/test/java/com/github/copilot/tool/CopilotToolProcessorTest.java new file mode 100644 index 0000000000..574d3acaa0 --- /dev/null +++ b/java/src/test/java/com/github/copilot/tool/CopilotToolProcessorTest.java @@ -0,0 +1,1218 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.FilterWriter; +import java.io.IOException; +import java.io.Writer; +import java.net.URI; +import java.nio.file.Path; +import java.security.CodeSource; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.ForwardingJavaFileObject; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.StandardLocation; +import javax.tools.ToolProvider; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Tests that {@link CopilotToolProcessor} correctly generates + * {@code $$CopilotToolMeta} companion classes and emits compile errors for + * invalid usages. + */ +class CopilotToolProcessorTest { + + @TempDir + java.nio.file.Path tempDir; + + // ── Test: Basic generation ────────────────────────────────────────────────── + + @Test + void generatesMetaClass_withCorrectToolNames() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class MyTools { + @CopilotTool("Sets the current phase") + public String setCurrentPhase(@CopilotToolParam("The phase") String phase) { + return "done"; + } + @CopilotTool("Search for items") + public String searchItems(@CopilotToolParam("Keyword") String keyword) { + return "found"; + } + @CopilotTool(value = "Custom grep", name = "grep") + public String grepOverride(@CopilotToolParam("Query") String query) { + return "result"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.MyTools", source))); + + assertNoErrors(result); + // Verify generated source contains the expected tool names + String generated = result.getGeneratedSource("test.MyTools$$CopilotToolMeta"); + assertTrue(generated != null, "Expected $$CopilotToolMeta to be generated"); + assertTrue(generated.contains("\"set_current_phase\""), "Expected snake_case name: set_current_phase"); + assertTrue(generated.contains("\"search_items\""), "Expected snake_case name: search_items"); + assertTrue(generated.contains("\"grep\""), "Expected explicit name: grep"); + } + + // ── Test: Compile error for private methods ───────────────────────────────── + + @Test + void emitsError_forPrivateMethods() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + public class PrivateTools { + @CopilotTool("Private tool") + private String doSomething() { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.PrivateTools", source))); + + assertTrue(hasErrorContaining(result, "must not be private"), + "Expected compile error for private @CopilotTool method, got: " + result.diagnostics); + } + + // ── Test: Compile error for required + defaultValue conflict ───────────── + + @Test + void emitsError_forRequiredWithDefaultValue() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class ConflictTools { + @CopilotTool("Conflicting params") + public String doSomething(@CopilotToolParam(value = "desc", required = true, defaultValue = "hello") String param) { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.ConflictTools", source))); + + assertTrue(hasErrorContaining(result, "required=true"), + "Expected compile error for required+defaultValue conflict, got: " + result.diagnostics); + } + + @Test + void emitsError_forOptionalPrimitiveWithoutDefaultValue() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class OptionalPrimitiveTools { + @CopilotTool("Optional primitive") + public String doSomething(@CopilotToolParam(value = "Limit", required = false) int limit) { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.OptionalPrimitiveTools", source))); + + assertTrue(hasErrorContaining(result, "required=false"), + "Expected compile error for optional primitive without defaultValue, got: " + result.diagnostics); + } + + @Test + void emitsError_forSingleRecordWrapperDefaultValue() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class SingleRecordDefaultTools { + public record SearchArgs(String query, int limit) {} + @CopilotTool("Single record") + public String search(@CopilotToolParam(defaultValue = "fallback") SearchArgs req) { + return req.query(); + } + } + """; + + CompilationResult result = compileWithProcessor( + List.of(inMemorySource("test.SingleRecordDefaultTools", source))); + + assertTrue(hasErrorContaining(result, "single-record tool parameters"), + "Expected compile error for single-record wrapper defaultValue, got: " + result.diagnostics); + } + + @Test + void emitsError_forSingleRecordWrapperMetadataOverrides() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class SingleRecordMetaTools { + public record SearchArgs(String query, int limit) {} + @CopilotTool("Single record") + public String search(@CopilotToolParam(value = "Search input", required = false, name = "input") SearchArgs req) { + return req.query(); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.SingleRecordMetaTools", source))); + + assertTrue(hasErrorContaining(result, "name/value/required"), + "Expected compile error for single-record wrapper metadata overrides, got: " + result.diagnostics); + } + + // ── Test: Return type handling ────────────────────────────────────────────── + + @Test + void generatesCorrectCode_forStringReturnType() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class StringReturn { + @CopilotTool("Returns string") + public String doSomething(@CopilotToolParam("Input") String input) { + return input; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.StringReturn", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.StringReturn$$CopilotToolMeta"); + assertTrue(generated.contains("CompletableFuture.completedFuture(instance.doSomething("), + "Expected completedFuture wrapping for String return, got:\n" + generated); + } + + @Test + void generatesMetadata_withNestedFlags() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class MetaTools { + @CopilotTool(value = "Reports phase", metadata = { + @CopilotTool.MetadataEntry( + key = "github.com/copilot:safeForTelemetry", + value = @CopilotTool.MetadataValue(flags = { + @CopilotTool.MetadataFlag(name = "name", value = true), + @CopilotTool.MetadataFlag(name = "inputsNames", value = false) + })) + }) + public String reportPhase(@CopilotToolParam("Phase") String phase) { + return phase; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.MetaTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.MetaTools$$CopilotToolMeta"); + assertTrue(generated.contains("Map.of(\"github.com/copilot:safeForTelemetry\""), + "Expected typed metadata map, got:\n" + generated); + assertTrue(generated.contains("Map.of(\"name\", true, \"inputsNames\", false)"), + "Expected nested flag map, got:\n" + generated); + } + + @Test + void generatesNullMetadata_whenAbsent() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class PlainTools { + @CopilotTool("Plain tool") + public String doSomething(@CopilotToolParam("Input") String input) { + return input; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.PlainTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.PlainTools$$CopilotToolMeta"); + assertFalse(generated.contains("Map.of("), + "Expected no metadata map for a tool without metadata, got:\n" + generated); + assertTrue(generated.contains(" null\n )"), + "Expected metadata constructor argument to be null when metadata is absent, got:\n" + generated); + } + + @Test + void generatesMetadata_alongsideOtherFlags() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.rpc.ToolDefer; + import com.github.copilot.tool.CopilotToolParam; + public class ComboTools { + @CopilotTool(value = "Combo", name = "combo", overridesBuiltInTool = true, + skipPermission = true, defer = ToolDefer.NEVER, + metadata = { + @CopilotTool.MetadataEntry(key = "k", + value = @CopilotTool.MetadataValue(bool = true)) + }) + public String doSomething(@CopilotToolParam("Input") String input) { + return input; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.ComboTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.ComboTools$$CopilotToolMeta"); + assertTrue(generated.contains("Boolean.TRUE"), "Expected overrides/skip flags, got:\n" + generated); + assertTrue(generated.contains("ToolDefer.NEVER"), "Expected defer, got:\n" + generated); + assertTrue(generated.contains("Map.of(\"k\", true)"), + "Expected scalar bool metadata, got:\n" + generated); + } + + @Test + void generatesCorrectCode_forVoidReturnType() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class VoidReturn { + @CopilotTool("Void method") + public void doSomething(@CopilotToolParam("Input") String input) { + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.VoidReturn", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.VoidReturn$$CopilotToolMeta"); + assertTrue(generated.contains("instance.doSomething("), "Expected method call in generated code"); + assertTrue(generated.contains("CompletableFuture.completedFuture(\"Success\")"), + "Expected 'Success' return for void methods, got:\n" + generated); + } + + @Test + void generatesCorrectCode_forCompletableFutureStringReturnType() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + import java.util.concurrent.CompletableFuture; + public class AsyncReturn { + @CopilotTool("Async method") + public CompletableFuture doSomething(@CopilotToolParam("Input") String input) { + return CompletableFuture.completedFuture(input); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.AsyncReturn", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.AsyncReturn$$CopilotToolMeta"); + assertTrue(generated.contains("return instance.doSomething("), + "Expected direct return for CompletableFuture, got:\n" + generated); + assertTrue(generated.contains("thenApply(r -> (Object) r)"), + "Expected thenApply cast for CompletableFuture, got:\n" + generated); + } + + @Test + void generatesCorrectCode_forIntReturnType() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class IntReturn { + @CopilotTool("Returns int") + public int doSomething(@CopilotToolParam("Input") String input) { + return 42; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.IntReturn", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.IntReturn$$CopilotToolMeta"); + assertTrue(generated.contains("mapper.writeValueAsString(instance.doSomething("), + "Expected JSON serialization for int return type, got:\n" + generated); + } + + // ── Test: Argument coercion ───────────────────────────────────────────────── + + @Test + void generatesCorrectArgExtraction_forPrimitiveAndStringTypes() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class ArgTypes { + @CopilotTool("Mixed args") + public String doSomething( + @CopilotToolParam("Name") String name, + @CopilotToolParam("Count") int count, + @CopilotToolParam("Flag") boolean flag) { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.ArgTypes", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.ArgTypes$$CopilotToolMeta"); + assertTrue(generated.contains("(String) args.get(\"name\")"), + "Expected String cast for String param, got:\n" + generated); + assertTrue(generated.contains("((Number) args.get(\"count\")).intValue()"), + "Expected Number cast for int param, got:\n" + generated); + assertTrue(generated.contains("(Boolean) args.get(\"flag\")"), + "Expected Boolean cast for boolean param, got:\n" + generated); + } + + @Test + void generatesTypeReferenceConversion_forArrayParameters() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class ArrayArgs { + @CopilotTool("Array tool") + public String doSomething(@CopilotToolParam("Ids") String[] ids) { + return String.valueOf(ids.length); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.ArrayArgs", source))); + assertNoErrors(result); + + String generated = result.getGeneratedSource("test.ArrayArgs$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for ArrayArgs$$CopilotToolMeta"); + assertTrue(generated.contains("new com.fasterxml.jackson.core.type.TypeReference() {}"), + "Expected TypeReference-based conversion for String[] parameter, got:\n" + generated); + assertFalse( + generated.contains("String[] ids = (Object) args.get(\"ids\");") + || generated.contains("java.lang.String[] ids = (Object) args.get(\"ids\");"), + "Array parameter should no longer be assigned from raw Object, got:\n" + generated); + } + + @Test + void generatesTypeReferenceConversion_forGenericDeclaredParameters() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class GenericArgTypes { + public record MyRecord(String name) {} + @CopilotTool("Generic args") + public String doSomething( + @CopilotToolParam("Ids") java.util.List ids, + @CopilotToolParam("Values") java.util.Map values, + @CopilotToolParam("Records") java.util.List records) { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.GenericArgTypes", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.GenericArgTypes$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for GenericArgTypes$$CopilotToolMeta"); + + assertTrue( + generated.contains( + "new com.fasterxml.jackson.core.type.TypeReference>() {}"), + "Expected TypeReference for List, got:\n" + generated); + assertTrue(generated.contains( + "new com.fasterxml.jackson.core.type.TypeReference>() {}"), + "Expected TypeReference for Map, got:\n" + generated); + assertTrue(generated.contains( + "new com.fasterxml.jackson.core.type.TypeReference>() {}"), + "Expected TypeReference for List, got:\n" + generated); + assertFalse(generated.contains("java.util.List.class"), + "Generic declared params should not use raw List.class conversion, got:\n" + generated); + assertFalse(generated.contains("java.util.Map.class"), + "Generic declared params should not use raw Map.class conversion, got:\n" + generated); + } + + // ── Test: snake_case conversion ───────────────────────────────────────────── + + @Test + void snakeCaseConversion() { + assertEquals("set_current_phase", CopilotToolProcessor.toSnakeCase("setCurrentPhase")); + assertEquals("search_items", CopilotToolProcessor.toSnakeCase("searchItems")); + assertEquals("grep", CopilotToolProcessor.toSnakeCase("grep")); + assertEquals("get_u_r_l", CopilotToolProcessor.toSnakeCase("getURL")); + assertEquals("a", CopilotToolProcessor.toSnakeCase("a")); + assertEquals("", CopilotToolProcessor.toSnakeCase("")); + } + + // ── Test: Processor registration ──────────────────────────────────────────── + + @Test + void processorIsRegisteredInMetaInfServices() throws Exception { + var resource = getClass().getClassLoader() + .getResource("META-INF/services/javax.annotation.processing.Processor"); + assertTrue(resource != null, "META-INF/services/javax.annotation.processing.Processor should exist"); + String content = new String(resource.openStream().readAllBytes()); + assertTrue(content.contains("com.github.copilot.tool.CopilotToolProcessor"), + "Service file should contain CopilotToolProcessor"); + } + + // ── Test: Schema generation in generated code ─────────────────────────────── + + @Test + void generatesCorrectSchema() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class SchemaTools { + @CopilotTool("Search items") + public String search( + @CopilotToolParam(value = "Query", required = true) String query, + @CopilotToolParam(value = "Limit", required = false) Integer limit) { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.SchemaTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.SchemaTools$$CopilotToolMeta"); + // Verify the schema contains the expected keys + assertTrue(generated.contains("\"type\", \"object\""), "Expected object type in schema"); + assertTrue(generated.contains("\"properties\""), "Expected properties in schema"); + assertTrue(generated.contains("\"required\""), "Expected required in schema"); + assertTrue(generated.contains("\"query\""), "Expected query property"); + } + + @Test + void generatesFlattenedSchemaAndDirectRecordConversion_forSingleRecordParameter() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + public class RecordTool { + public record SearchArgs(String query, int limit) {} + @CopilotTool("Search items") + public String search(SearchArgs req) { + return req.query() + ":" + req.limit(); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.RecordTool", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.RecordTool$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for RecordTool$$CopilotToolMeta"); + assertTrue( + generated.contains("mapper.convertValue(invocation.getArguments(), test.RecordTool.SearchArgs.class)"), + "Expected direct convertValue(invocation.getArguments(), ...), got:\n" + generated); + assertFalse(generated.contains("Map args = invocation.getArguments();"), + "Single-record path should not declare local args map, got:\n" + generated); + assertFalse(generated.contains("Map.entry(\"req\""), + "Single-record schema should be flattened, not nested under wrapper param, got:\n" + generated); + assertTrue(generated.contains("\"query\""), + "Expected flattened record component in schema, got:\n" + generated); + } + + @Test + void supportsSingleRecordParameterNamedArgs_withoutLocalNameCollision() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + public class RecordToolArgs { + public record SearchArgs(String query) {} + @CopilotTool("Search items") + public String search(SearchArgs args) { + return args.query(); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.RecordToolArgs", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.RecordToolArgs$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for RecordToolArgs$$CopilotToolMeta"); + assertTrue(generated.contains( + "test.RecordToolArgs.SearchArgs args = mapper.convertValue(invocation.getArguments(), test.RecordToolArgs.SearchArgs.class);"), + "Expected args-named record param to compile with direct invocation mapping, got:\n" + generated); + assertFalse(generated.contains("Map args = invocation.getArguments();"), + "Single-record path should avoid local args map collision, got:\n" + generated); + } + + @Test + void supportsInjectedToolInvocation_forSchemaAndMethodCall() { + String source = """ + package test; + import com.github.copilot.rpc.ToolInvocation; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class InvocationAwareTools { + @CopilotTool("Reports progress") + public String report(@CopilotToolParam("Phase") String phase, ToolInvocation toolInvocation) { + return phase + ":" + toolInvocation.getSessionId(); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.InvocationAwareTools", source))); + assertNoErrors(result); + + String generated = result.getGeneratedSource("test.InvocationAwareTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for InvocationAwareTools$$CopilotToolMeta"); + assertTrue(generated.contains("Map.entry(\"phase\""), + "Expected normal parameter in schema, got:\n" + generated); + assertFalse(generated.contains("Map.entry(\"invocation\""), + "ToolInvocation must not appear in schema properties, got:\n" + generated); + assertFalse(generated.contains("Map.entry(\"toolInvocation\""), + "ToolInvocation must not appear in schema properties, got:\n" + generated); + assertTrue(generated.contains("required\", List.of(\"phase\")"), + "Expected only normal parameters in required list, got:\n" + generated); + assertFalse(generated.contains("args.get(\"toolInvocation\")"), + "ToolInvocation must not be read from invocation arguments, got:\n" + generated); + assertTrue(generated.contains("instance.report(phase, invocation)"), + "ToolInvocation parameter should be injected from runtime invocation, got:\n" + generated); + } + + @Test + void supportsInjectedToolInvocation_forStaticAndAsyncMethods() { + String source = """ + package test; + import com.github.copilot.rpc.ToolInvocation; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + import java.util.concurrent.CompletableFuture; + public class StaticInvocationAwareTools { + @CopilotTool("Reports progress statically") + public static String report(@CopilotToolParam("Phase") String phase, ToolInvocation toolInvocation) { + return phase + ":" + toolInvocation.getToolCallId(); + } + @CopilotTool("Reports progress asynchronously") + public CompletableFuture reportAsync(@CopilotToolParam("Phase") String phase, ToolInvocation toolInvocation) { + return CompletableFuture.completedFuture(phase + ":" + toolInvocation.getToolCallId()); + } + } + """; + + CompilationResult result = compileWithProcessor( + List.of(inMemorySource("test.StaticInvocationAwareTools", source))); + assertNoErrors(result); + + String generated = result.getGeneratedSource("test.StaticInvocationAwareTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for StaticInvocationAwareTools$$CopilotToolMeta"); + assertTrue(generated.contains("test.StaticInvocationAwareTools.report(phase, invocation)"), + "Expected static method call with injected invocation, got:\n" + generated); + assertTrue(generated.contains("return instance.reportAsync(phase, invocation).thenApply(r -> (Object) r);"), + "Expected async method call with injected invocation, got:\n" + generated); + } + + @Test + void supportsInjectedToolInvocation_whenItIsTheOnlyParameter() { + String source = """ + package test; + import com.github.copilot.rpc.ToolInvocation; + import com.github.copilot.tool.CopilotTool; + public class InvocationOnlyTools { + @CopilotTool("Reports invocation context only") + public String onlyContext(ToolInvocation invocation) { + return invocation.getSessionId(); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.InvocationOnlyTools", source))); + assertNoErrors(result); + + String generated = result.getGeneratedSource("test.InvocationOnlyTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for InvocationOnlyTools$$CopilotToolMeta"); + assertTrue(generated.contains("\"properties\", Map.of(), \"required\", List.of()"), + "Expected empty schema for invocation-only method, got:\n" + generated); + assertFalse(generated.contains("Map args = invocation.getArguments();"), + "Invocation-only method should not read argument map, got:\n" + generated); + assertTrue(generated.contains("instance.onlyContext(invocation)"), + "Invocation-only method should inject invocation directly, got:\n" + generated); + } + + @Test + void supportsInjectedToolInvocation_whenItAppearsFirstOrMiddle() { + String source = """ + package test; + import com.github.copilot.rpc.ToolInvocation; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class InvocationPositionTools { + @CopilotTool("Invocation first") + public String reportFirst(ToolInvocation invocation, @CopilotToolParam("Phase") String phase) { + return phase + ":" + invocation.getToolCallId(); + } + @CopilotTool("Invocation middle") + public String reportMiddle(@CopilotToolParam("Phase") String phase, ToolInvocation invocation, @CopilotToolParam("Limit") int limit) { + return phase + ":" + limit + ":" + invocation.getToolCallId(); + } + } + """; + + CompilationResult result = compileWithProcessor( + List.of(inMemorySource("test.InvocationPositionTools", source))); + assertNoErrors(result); + + String generated = result.getGeneratedSource("test.InvocationPositionTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for InvocationPositionTools$$CopilotToolMeta"); + assertTrue(generated.contains("instance.reportFirst(invocation, phase)"), + "Expected invocation to be passed in first position, got:\n" + generated); + assertTrue(generated.contains("instance.reportMiddle(phase, invocation, limit)"), + "Expected invocation to be passed in middle position, got:\n" + generated); + assertFalse(generated.contains("args.get(\"invocation\")"), + "ToolInvocation must not be read from invocation arguments, got:\n" + generated); + assertTrue(generated.contains("Map.entry(\"phase\""), + "Expected schema-visible phase parameter, got:\n" + generated); + assertTrue(generated.contains("Map.entry(\"limit\""), + "Expected schema-visible limit parameter, got:\n" + generated); + assertFalse(generated.contains("Map.entry(\"invocation\""), + "ToolInvocation must not appear in schema properties, got:\n" + generated); + } + + @Test + void supportsInjectedToolInvocation_withSingleRecordSchemaParameter() { + String source = """ + package test; + import com.github.copilot.rpc.ToolInvocation; + import com.github.copilot.tool.CopilotTool; + public class RecordInvocationTools { + public record SearchArgs(String query, int limit) {} + @CopilotTool("Record plus invocation") + public String report(SearchArgs args, ToolInvocation invocation) { + return args.query() + ":" + invocation.getSessionId(); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.RecordInvocationTools", source))); + assertNoErrors(result); + + String generated = result.getGeneratedSource("test.RecordInvocationTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for RecordInvocationTools$$CopilotToolMeta"); + assertTrue(generated.contains( + "test.RecordInvocationTools.SearchArgs args = mapper.convertValue(invocation.getArguments(), test.RecordInvocationTools.SearchArgs.class);"), + "Expected single-record conversion for schema-visible parameter, got:\n" + generated); + assertTrue(generated.contains("instance.report(args, invocation)"), + "Expected record + invocation method call order, got:\n" + generated); + assertFalse(generated.contains("Map.entry(\"args\""), + "Single-record schema should be flattened, got:\n" + generated); + assertFalse(generated.contains("args.get(\"invocation\")"), + "ToolInvocation must not be read from invocation arguments, got:\n" + generated); + } + + @Test + void emitsError_forDuplicateToolInvocationParameters() { + String source = """ + package test; + import com.github.copilot.rpc.ToolInvocation; + import com.github.copilot.tool.CopilotTool; + public class DuplicateInvocationTools { + @CopilotTool("Invalid duplicate ToolInvocation") + public String report(String phase, ToolInvocation first, ToolInvocation second) { + return phase; + } + } + """; + + CompilationResult result = compileWithProcessor( + List.of(inMemorySource("test.DuplicateInvocationTools", source))); + + assertTrue(hasErrorContaining(result, "at most one ToolInvocation parameter"), + "Expected compile error for duplicate ToolInvocation parameters, got: " + result.diagnostics); + } + + @Test + void emitsError_forParamAnnotatedToolInvocationParameter() { + String source = """ + package test; + import com.github.copilot.rpc.ToolInvocation; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class AnnotatedInvocationTools { + @CopilotTool("Invalid @CopilotToolParam on ToolInvocation") + public String report(@CopilotToolParam("Invocation context") ToolInvocation invocation) { + return invocation.getToolName(); + } + } + """; + + CompilationResult result = compileWithProcessor( + List.of(inMemorySource("test.AnnotatedInvocationTools", source))); + + assertTrue(hasErrorContaining(result, "@CopilotToolParam is not supported on ToolInvocation parameters"), + "Expected compile error for @CopilotToolParam ToolInvocation parameter, got: " + result.diagnostics); + } + + // ── Test: Typed default values in schema ──────────────────────────────────── + + @Test + void emitsTypedDefaultValuesInSchema() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class DefaultTools { + @CopilotTool("Tool with defaults") + public String doWork( + @CopilotToolParam(value = "Limit", required = false, defaultValue = "10") int limit, + @CopilotToolParam(value = "Enabled", required = false, defaultValue = "true") boolean enabled, + @CopilotToolParam(value = "Label", required = false, defaultValue = "hello") String label) { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.DefaultTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.DefaultTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for DefaultTools$$CopilotToolMeta"); + + // Numeric default should be an unquoted literal, not a string + assertTrue(generated.contains("withMeta(") && generated.contains(", 10)"), + "Expected numeric default 10 as typed literal, not string. Generated:\n" + generated); + // Boolean default should be an unquoted literal + assertTrue(generated.contains(", true)"), + "Expected boolean default true as typed literal, not string. Generated:\n" + generated); + // String default should remain a quoted string + assertTrue(generated.contains(", \"hello\")"), + "Expected string default \"hello\" as quoted string. Generated:\n" + generated); + } + + @Test + void rejectsMismatchedNumericDefaultForIntegralParameters() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class MismatchedDefaults { + @CopilotTool("Tool with bad default") + public String doWork(@CopilotToolParam(value = "Limit", required = false, defaultValue = "1.5") int limit) { + return String.valueOf(limit); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.MismatchedDefaults", source))); + assertTrue(hasErrorContaining(result, "not valid for int parameters"), + "Expected compile error for mismatched int defaultValue, got: " + result.diagnostics); + } + + // ── Test: package-private methods are allowed ─────────────────────────────── + + @Test + void allowsPackagePrivateMethods() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + public class PackagePrivateTools { + @CopilotTool("Package private tool") + String doSomething() { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.PackagePrivateTools", source))); + assertNoErrors(result); + } + + // ── Test: protected methods are allowed ───────────────────────────────────── + + @Test + void allowsProtectedMethods() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + public class ProtectedTools { + @CopilotTool("Protected tool") + protected String doSomething() { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.ProtectedTools", source))); + assertNoErrors(result); + } + + // ── Test: overridesBuiltInTool generates createOverride ───────────────────── + + @Test + void generatesCreateOverride_whenOverridesBuiltInTool() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + public class OverrideTools { + @CopilotTool(value = "Custom grep", name = "grep", overridesBuiltInTool = true) + public String grep(@CopilotToolParam("Query") String query) { + return "result"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.OverrideTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.OverrideTools$$CopilotToolMeta"); + assertTrue(generated.contains("new ToolDefinition("), "Expected record constructor, got:\n" + generated); + assertTrue(generated.contains("Boolean.TRUE"), + "Expected Boolean.TRUE for overridesBuiltInTool, got:\n" + generated); + } + + // ── Test: Combined flags all apply independently ──────────────────────────── + + @Test + void generatesCombinedFlags() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.rpc.ToolDefer; + public class CombinedTools { + @CopilotTool(value = "Combined", overridesBuiltInTool = true, skipPermission = true, defer = ToolDefer.AUTO) + public String doAll() { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.CombinedTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.CombinedTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected generated source for CombinedTools$$CopilotToolMeta"); + assertTrue(generated.contains("new ToolDefinition("), "Expected record constructor, got:\n" + generated); + // All three flags must be present — not silently dropped + assertTrue(generated.contains("Boolean.TRUE"), + "Expected Boolean.TRUE for override/skipPermission, got:\n" + generated); + assertTrue(generated.contains("ToolDefer.AUTO"), "Expected ToolDefer.AUTO, got:\n" + generated); + // Count Boolean.TRUE occurrences — should be 2 (overridesBuiltInTool + + // skipPermission) + long boolCount = generated.lines().filter(l -> l.contains("Boolean.TRUE")).count(); + assertEquals(2, boolCount, + "Expected 2 Boolean.TRUE lines (overridesBuiltInTool + skipPermission), got:\n" + generated); + } + + // ── Test: ToolDefer.NONE results in regular create ────────────────────────── + + @Test + void generatesCreate_whenDeferIsNone() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.rpc.ToolDefer; + public class DeferNoneTools { + @CopilotTool(value = "Simple tool", defer = ToolDefer.NONE) + public String doSomething() { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.DeferNoneTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.DeferNoneTools$$CopilotToolMeta"); + assertTrue(generated.contains("new ToolDefinition("), + "Expected record constructor for NONE, got:\n" + generated); + assertFalse(generated.contains("ToolDefer."), "Should NOT reference ToolDefer for NONE, got:\n" + generated); + } + + // ── Test: ToolDefer.AUTO results in createWithDefer ────────────────────────── + + @Test + void generatesCreateWithDefer_whenDeferIsAuto() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.rpc.ToolDefer; + public class DeferAutoTools { + @CopilotTool(value = "Deferrable tool", defer = ToolDefer.AUTO) + public String doSomething() { + return "done"; + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.DeferAutoTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.DeferAutoTools$$CopilotToolMeta"); + assertTrue(generated.contains("new ToolDefinition("), + "Expected record constructor for AUTO, got:\n" + generated); + assertTrue(generated.contains("ToolDefer.AUTO"), "Expected ToolDefer.AUTO argument, got:\n" + generated); + } + + // ── Test: Optional parameter extraction ───────────────────────────────────── + + @Test + void generatesCorrectOptionalExtraction() { + String source = """ + package test; + import com.github.copilot.tool.CopilotTool; + import com.github.copilot.tool.CopilotToolParam; + import java.util.Optional; + import java.util.OptionalInt; + import java.util.OptionalLong; + import java.util.OptionalDouble; + public class OptionalTools { + @CopilotTool("Tool with optional string") + public String withOptionalString(@CopilotToolParam("A name") Optional name) { + return name.orElse("default"); + } + @CopilotTool("Tool with optional int") + public String withOptionalInt(@CopilotToolParam("A count") OptionalInt count) { + return String.valueOf(count.orElse(0)); + } + @CopilotTool("Tool with optional long") + public String withOptionalLong(@CopilotToolParam("A timestamp") OptionalLong ts) { + return String.valueOf(ts.orElse(0L)); + } + @CopilotTool("Tool with optional double") + public String withOptionalDouble(@CopilotToolParam("A ratio") OptionalDouble ratio) { + return String.valueOf(ratio.orElse(0.0)); + } + } + """; + + CompilationResult result = compileWithProcessor(List.of(inMemorySource("test.OptionalTools", source))); + assertNoErrors(result); + String generated = result.getGeneratedSource("test.OptionalTools$$CopilotToolMeta"); + assertNotNull(generated, "Expected $$CopilotToolMeta to be generated"); + + // Optional should use null-check + Optional.of wrapping + assertTrue(generated.contains("Optional.of(") || generated.contains("java.util.Optional.of("), + "Expected Optional.of() wrapping for Optional, got:\n" + generated); + assertTrue(generated.contains("Optional.empty()") || generated.contains("java.util.Optional.empty()"), + "Expected Optional.empty() fallback, got:\n" + generated); + + // OptionalInt should use OptionalInt.of(((Number)...).intValue()) + assertTrue(generated.contains("OptionalInt.of(((Number)"), + "Expected OptionalInt.of(((Number)...).intValue()), got:\n" + generated); + assertTrue(generated.contains("OptionalInt.empty()"), + "Expected OptionalInt.empty() fallback, got:\n" + generated); + + // OptionalLong should use OptionalLong.of(((Number)...).longValue()) + assertTrue(generated.contains("OptionalLong.of(((Number)"), + "Expected OptionalLong.of(((Number)...).longValue()), got:\n" + generated); + assertTrue(generated.contains("OptionalLong.empty()"), + "Expected OptionalLong.empty() fallback, got:\n" + generated); + + // OptionalDouble should use OptionalDouble.of(((Number)...).doubleValue()) + assertTrue(generated.contains("OptionalDouble.of(((Number)"), + "Expected OptionalDouble.of(((Number)...).doubleValue()), got:\n" + generated); + assertTrue(generated.contains("OptionalDouble.empty()"), + "Expected OptionalDouble.empty() fallback, got:\n" + generated); + + // Should NOT use mapper.convertValue for Optional types + assertFalse(generated.contains("mapper.convertValue(args.get(\"name\"), java.util.Optional.class)"), + "Should NOT use mapper.convertValue for Optional, got:\n" + generated); + } + + // ── Helpers ───────────────────────────────────────────────────────────────── + + private CompilationResult compileWithProcessor(List sources) { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + + String classpath = resolveClasspath(); + List options = new ArrayList<>(); + options.add("-proc:full"); + options.addAll(List.of("-processor", "com.github.copilot.tool.CopilotToolProcessor")); + options.addAll(List.of("-classpath", classpath)); + options.addAll(List.of("-d", tempDir.toString())); + options.addAll(List.of("-s", tempDir.toString())); + // Allow experimental APIs during test compilation + options.add("-Acopilot.experimental.allowed=true"); + + try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) { + fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, List.of(tempDir.toFile())); + fileManager.setLocation(StandardLocation.CLASS_OUTPUT, List.of(tempDir.toFile())); + CollectingFileManager collectingFileManager = new CollectingFileManager(fileManager); + + JavaCompiler.CompilationTask task = compiler.getTask(null, collectingFileManager, diagnostics, options, + null, sources); + task.call(); + + List generatedSources = collectingFileManager.getGeneratedSources(); + if (generatedSources.isEmpty()) { + // Fallback for file-manager implementations that only materialize on disk. + collectGeneratedFiles(tempDir, generatedSources); + } + + return new CompilationResult(diagnostics.getDiagnostics(), generatedSources, tempDir); + } catch (Exception e) { + throw new RuntimeException("Compilation setup failed", e); + } + } + + private void collectGeneratedFiles(java.nio.file.Path dir, List files) { + try (var stream = java.nio.file.Files.walk(dir)) { + stream.filter(p -> p.toString().endsWith(".java")).forEach(p -> { + try { + files.add(java.nio.file.Files.readString(p)); + } catch (java.io.IOException e) { + // ignore read errors for generated file collection + } + }); + } catch (java.io.IOException e) { + // ignore walk errors + } + } + + private static String resolveClasspath() { + // Collect classpath entries from CodeSource of key classes needed for + // compiling both the source and the generated $$CopilotToolMeta code. + Set paths = new LinkedHashSet<>(); + + // Add system classpath entries (may include manifest-only jars) + String systemCp = System.getProperty("java.class.path", ""); + if (!systemCp.isEmpty()) { + for (String p : systemCp.split(java.util.regex.Pattern.quote(File.pathSeparator))) { + if (!p.isEmpty()) { + paths.add(p); + } + } + } + + // Also resolve CodeSource paths for key classes (SDK + Jackson + RPC types) + Class[] keyClasses = {CopilotTool.class, com.fasterxml.jackson.databind.ObjectMapper.class, + com.fasterxml.jackson.core.JsonFactory.class, com.fasterxml.jackson.annotation.JsonProperty.class, + com.github.copilot.rpc.ToolDefinition.class}; + for (Class cls : keyClasses) { + try { + CodeSource cs = cls.getProtectionDomain().getCodeSource(); + if (cs != null && cs.getLocation() != null) { + paths.add(Path.of(cs.getLocation().toURI()).toString()); + } + } catch (Exception e) { + // skip this class + } + } + + return paths.isEmpty() ? "." : String.join(File.pathSeparator, paths); + } + + private static JavaFileObject inMemorySource(String className, String code) { + return new SimpleJavaFileObject(URI.create("string:///" + className.replace('.', '/') + ".java"), + JavaFileObject.Kind.SOURCE) { + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return code; + } + }; + } + + private static void assertNoErrors(CompilationResult result) { + List> errors = result.diagnostics.stream() + .filter(d -> d.getKind() == Diagnostic.Kind.ERROR).toList(); + assertTrue(errors.isEmpty(), "Expected no errors, got: " + errors); + } + + private static boolean hasErrorContaining(CompilationResult result, String substring) { + return result.diagnostics.stream() + .anyMatch(d -> d.getKind() == Diagnostic.Kind.ERROR && d.getMessage(null).contains(substring)); + } + + private static class CompilationResult { + final List> diagnostics; + final List generatedSources; + final java.nio.file.Path outputDir; + + CompilationResult(List> diagnostics, List generatedSources, + java.nio.file.Path outputDir) { + this.diagnostics = diagnostics; + this.generatedSources = generatedSources; + this.outputDir = outputDir; + } + + String getGeneratedSource(String qualifiedName) { + String fileName = qualifiedName.replace('.', '/') + ".java"; + java.nio.file.Path filePath = outputDir.resolve(fileName); + try { + if (java.nio.file.Files.exists(filePath)) { + return java.nio.file.Files.readString(filePath); + } + } catch (java.io.IOException e) { + // fall through + } + // Also check in collected sources + String simpleName = qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1); + for (String source : generatedSources) { + if (source.contains("class " + simpleName)) { + return source; + } + } + return null; + } + } + + private static class CollectingFileManager extends ForwardingJavaFileManager { + private final Map generatedByClass = new LinkedHashMap<>(); + + CollectingFileManager(StandardJavaFileManager fileManager) { + super(fileManager); + } + + @Override + public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, + FileObject sibling) throws IOException { + JavaFileObject delegate = super.getJavaFileForOutput(location, className, kind, sibling); + if (kind != JavaFileObject.Kind.SOURCE) { + return delegate; + } + StringBuilder captured = new StringBuilder(); + generatedByClass.put(className, captured); + return new ForwardingJavaFileObject<>(delegate) { + @Override + public Writer openWriter() throws IOException { + Writer target = delegate.openWriter(); + return new FilterWriter(target) { + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + captured.append(cbuf, off, len); + super.write(cbuf, off, len); + } + + @Override + public void write(int c) throws IOException { + captured.append((char) c); + super.write(c); + } + + @Override + public void write(String str, int off, int len) throws IOException { + captured.append(str, off, off + len); + super.write(str, off, len); + } + }; + } + }; + } + + List getGeneratedSources() { + return generatedByClass.values().stream().map(StringBuilder::toString).toList(); + } + } +} diff --git a/java/src/test/java/com/github/copilot/tool/ParamTest.java b/java/src/test/java/com/github/copilot/tool/ParamTest.java new file mode 100644 index 0000000000..75f6e44222 --- /dev/null +++ b/java/src/test/java/com/github/copilot/tool/ParamTest.java @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Unit tests for {@link Param} runtime parameter metadata. + */ +public class ParamTest { + + // ------------------------------------------------------------------ + // Factory method: of(type, name, description) + // ------------------------------------------------------------------ + + @Test + void ofCreatesRequiredParamWithNoDefault() { + Param p = Param.of(String.class, "query", "Search query"); + assertEquals(String.class, p.type()); + assertEquals("query", p.name()); + assertEquals("Search query", p.description()); + assertTrue(p.required()); + assertEquals("", p.defaultValue()); + assertFalse(p.hasDefaultValue()); + } + + @Test + void ofFullFactoryCreatesOptionalParamWithDefault() { + Param p = Param.of(Integer.class, "limit", "Max results", false, "10"); + assertEquals(Integer.class, p.type()); + assertEquals("limit", p.name()); + assertEquals("Max results", p.description()); + assertFalse(p.required()); + assertEquals("10", p.defaultValue()); + assertTrue(p.hasDefaultValue()); + } + + // ------------------------------------------------------------------ + // Validation: blank name/description rejected + // ------------------------------------------------------------------ + + @Test + void rejectsNullName() { + var ex = assertThrows(IllegalArgumentException.class, () -> Param.of(String.class, null, "desc")); + assertTrue(ex.getMessage().contains("name")); + } + + @Test + void rejectsBlankName() { + var ex = assertThrows(IllegalArgumentException.class, () -> Param.of(String.class, " ", "desc")); + assertTrue(ex.getMessage().contains("name")); + } + + @Test + void rejectsNullDescription() { + var ex = assertThrows(IllegalArgumentException.class, () -> Param.of(String.class, "n", null)); + assertTrue(ex.getMessage().contains("description")); + } + + @Test + void rejectsBlankDescription() { + var ex = assertThrows(IllegalArgumentException.class, () -> Param.of(String.class, "n", "")); + assertTrue(ex.getMessage().contains("description")); + } + + // ------------------------------------------------------------------ + // Validation: required=true with non-empty default rejected + // ------------------------------------------------------------------ + + @Test + void rejectsRequiredWithNonEmptyDefault() { + var ex = assertThrows(IllegalArgumentException.class, () -> Param.of(String.class, "x", "desc", true, "val")); + assertTrue(ex.getMessage().contains("required=true")); + } + + @Test + void allowsRequiredWithEmptyDefault() { + Param p = Param.of(String.class, "x", "desc", true, ""); + assertTrue(p.required()); + assertFalse(p.hasDefaultValue()); + } + + @Test + void allowsRequiredWithNullDefault() { + Param p = Param.of(String.class, "x", "desc", true, null); + assertTrue(p.required()); + assertEquals("", p.defaultValue()); + } + + // ------------------------------------------------------------------ + // Validation: default value type checking + // ------------------------------------------------------------------ + + @Test + void validatesIntegerDefault() { + // valid + Param p = Param.of(Integer.class, "n", "num", false, "42"); + assertEquals("42", p.defaultValue()); + + // invalid + assertThrows(IllegalArgumentException.class, () -> Param.of(Integer.class, "n", "num", false, "abc")); + } + + @Test + void validatesLongDefault() { + Param p = Param.of(Long.class, "n", "num", false, "999999999999"); + assertEquals("999999999999", p.defaultValue()); + + assertThrows(IllegalArgumentException.class, () -> Param.of(Long.class, "n", "num", false, "notlong")); + } + + @Test + void validatesDoubleDefault() { + Param p = Param.of(Double.class, "d", "decimal", false, "3.14"); + assertEquals("3.14", p.defaultValue()); + + assertThrows(IllegalArgumentException.class, () -> Param.of(Double.class, "d", "decimal", false, "xyz")); + } + + @Test + void validatesFloatDefault() { + Param p = Param.of(Float.class, "f", "float val", false, "1.5"); + assertEquals("1.5", p.defaultValue()); + + assertThrows(IllegalArgumentException.class, () -> Param.of(Float.class, "f", "float val", false, "notfloat")); + } + + @Test + void validatesShortDefault() { + Param p = Param.of(Short.class, "s", "short val", false, "100"); + assertEquals("100", p.defaultValue()); + + assertThrows(IllegalArgumentException.class, () -> Param.of(Short.class, "s", "short val", false, "99999")); + } + + @Test + void validatesByteDefault() { + Param p = Param.of(Byte.class, "b", "byte val", false, "127"); + assertEquals("127", p.defaultValue()); + + assertThrows(IllegalArgumentException.class, () -> Param.of(Byte.class, "b", "byte val", false, "999")); + } + + @Test + void validatesBooleanDefault() { + Param p1 = Param.of(Boolean.class, "b", "flag", false, "true"); + assertEquals("true", p1.defaultValue()); + + Param p2 = Param.of(Boolean.class, "b", "flag", false, "FALSE"); + assertEquals("FALSE", p2.defaultValue()); + + assertThrows(IllegalArgumentException.class, () -> Param.of(Boolean.class, "b", "flag", false, "yes")); + } + + @Test + void validatesEnumDefault() { + Param p = Param.of(TestEnum.class, "e", "enum val", false, "ALPHA"); + assertEquals("ALPHA", p.defaultValue()); + + assertThrows(IllegalArgumentException.class, () -> Param.of(TestEnum.class, "e", "enum val", false, "INVALID")); + } + + @Test + void rejectsUnsupportedTypeWithDefault() { + assertThrows(IllegalArgumentException.class, () -> Param.of(Object.class, "o", "object", false, "something")); + } + + @Test + void allowsStringDefault() { + Param p = Param.of(String.class, "s", "string", false, "hello"); + assertEquals("hello", p.defaultValue()); + } + + // ------------------------------------------------------------------ + // Fluent mutators return new instances + // ------------------------------------------------------------------ + + @Test + void nameMutatorReturnsNewInstance() { + Param original = Param.of(String.class, "a", "desc"); + Param renamed = original.name("b"); + assertEquals("a", original.name()); + assertEquals("b", renamed.name()); + } + + @Test + void descriptionMutatorReturnsNewInstance() { + Param original = Param.of(String.class, "a", "desc1"); + Param updated = original.description("desc2"); + assertEquals("desc1", original.description()); + assertEquals("desc2", updated.description()); + } + + @Test + void requiredMutatorReturnsNewInstance() { + Param original = Param.of(String.class, "a", "desc"); + Param optional = original.required(false); + assertTrue(original.required()); + assertFalse(optional.required()); + } + + @Test + void defaultValueMutatorSetsOptional() { + Param original = Param.of(String.class, "a", "desc"); + Param withDefault = original.defaultValue("val"); + assertTrue(original.required()); + assertFalse(withDefault.required()); + assertEquals("val", withDefault.defaultValue()); + assertTrue(withDefault.hasDefaultValue()); + } + + // ------------------------------------------------------------------ + // equals / hashCode / toString + // ------------------------------------------------------------------ + + @Test + void equalParamsAreEqual() { + Param a = Param.of(String.class, "x", "desc"); + Param b = Param.of(String.class, "x", "desc"); + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + } + + @Test + void differentParamsAreNotEqual() { + Param a = Param.of(String.class, "x", "desc"); + Param b = Param.of(String.class, "y", "desc"); + assertNotEquals(a, b); + } + + @Test + void toStringContainsName() { + Param p = Param.of(String.class, "query", "Search"); + assertTrue(p.toString().contains("query")); + assertTrue(p.toString().contains("String")); + } + + // ------------------------------------------------------------------ + // Null type rejected + // ------------------------------------------------------------------ + + @Test + void rejectsNullType() { + assertThrows(NullPointerException.class, () -> Param.of(null, "n", "desc")); + } + + // ------------------------------------------------------------------ + // Test enum for validation tests + // ------------------------------------------------------------------ + + enum TestEnum { + ALPHA, BETA + } +} diff --git a/java/src/test/java/com/github/copilot/tool/SchemaGeneratorTest.java b/java/src/test/java/com/github/copilot/tool/SchemaGeneratorTest.java new file mode 100644 index 0000000000..00bb1d9699 --- /dev/null +++ b/java/src/test/java/com/github/copilot/tool/SchemaGeneratorTest.java @@ -0,0 +1,762 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +package com.github.copilot.tool; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.Elements; +import javax.lang.model.util.Types; +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.StandardLocation; +import javax.tools.ToolProvider; + +import org.junit.jupiter.api.Test; + +/** + * Tests for {@link SchemaGenerator} using the compilation-testing approach. A + * test annotation processor exercises SchemaGenerator during compilation of + * small source snippets. + */ +public class SchemaGeneratorTest { + + /** + * In-memory Java source file for compilation testing. + */ + private static class InMemorySource extends SimpleJavaFileObject { + + private final String code; + + InMemorySource(String className, String code) { + super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); + this.code = code; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { + return code; + } + } + + /** + * Test processor that captures schema generation results. + */ + @SupportedAnnotationTypes("*") + @SupportedSourceVersion(SourceVersion.RELEASE_17) + public static class SchemaCapturingProcessor extends AbstractProcessor { + + static final List capturedSchemas = new ArrayList<>(); + static final List capturedParameterSchemas = new ArrayList<>(); + + private Types typeUtils; + private Elements elementUtils; + + @Override + public synchronized void init(ProcessingEnvironment processingEnv) { + super.init(processingEnv); + this.typeUtils = processingEnv.getTypeUtils(); + this.elementUtils = processingEnv.getElementUtils(); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.processingOver()) { + return false; + } + + SchemaGenerator generator = new SchemaGenerator(); + + for (Element rootElement : roundEnv.getRootElements()) { + if (rootElement.getKind() == ElementKind.CLASS || rootElement.getKind() == ElementKind.RECORD + || rootElement.getKind() == ElementKind.INTERFACE + || rootElement.getKind() == ElementKind.ENUM) { + // Find methods named "schemaTarget" to capture schemas for their return type + for (Element enclosed : rootElement.getEnclosedElements()) { + if (enclosed.getKind() == ElementKind.METHOD) { + ExecutableElement method = (ExecutableElement) enclosed; + String methodName = method.getSimpleName().toString(); + if (methodName.startsWith("schemaTarget")) { + TypeMirror returnType = method.getReturnType(); + String schema = generator.generateSchemaSource(returnType, typeUtils, elementUtils); + capturedSchemas.add(methodName + "=" + schema); + } + if ("parametersTarget".equals(methodName)) { + List params = method.getParameters(); + String schema = generator.generateParametersSchemaSource(params, typeUtils, + elementUtils); + capturedParameterSchemas.add(schema); + } + } + } + + // For record/enum types, generate schema for the type itself + TypeElement typeElement = (TypeElement) rootElement; + String typeName = typeElement.getSimpleName().toString(); + if (typeName.startsWith("TestRecord") || typeName.startsWith("TestEnum") + || typeName.startsWith("TestSealed")) { + String schema = generator.generateSchemaSource(typeElement.asType(), typeUtils, elementUtils); + capturedSchemas.add(typeName + "=" + schema); + } + } + } + + return false; + } + } + + private static final Path CLASS_OUTPUT_DIR = Path.of("target", "test-schema-classes"); + + /** + * Creates a StandardJavaFileManager that writes compiled .class files to + * target/test-schema-classes/ instead of the working directory. + */ + private StandardJavaFileManager createFileManager(JavaCompiler compiler, + DiagnosticCollector diagnostics) throws IOException { + Files.createDirectories(CLASS_OUTPUT_DIR); + StandardJavaFileManager fm = compiler.getStandardFileManager(diagnostics, null, null); + fm.setLocation(StandardLocation.CLASS_OUTPUT, List.of(CLASS_OUTPUT_DIR.toFile())); + return fm; + } + + private List compileAndCapture(String... sources) { + return compileAndCapture(Arrays.asList(sources)); + } + + private List compileAndCapture(List sourceTexts) { + SchemaCapturingProcessor.capturedSchemas.clear(); + SchemaCapturingProcessor.capturedParameterSchemas.clear(); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + assertNotNull(compiler, "System Java compiler not available"); + + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + + List compilationUnits = new ArrayList<>(); + for (String sourceText : sourceTexts) { + // Extract class name from source + String className = extractClassName(sourceText); + compilationUnits.add(new InMemorySource(className, sourceText)); + } + + try (StandardJavaFileManager fm = createFileManager(compiler, diagnostics)) { + // Compile with the processor on classpath + JavaCompiler.CompilationTask task = compiler.getTask(null, // writer + fm, // file manager + diagnostics, // diagnostics + List.of("--add-modules", "ALL-MODULE-PATH"), // options + null, // annotation classes + compilationUnits); + + task.setProcessors(List.of(new SchemaCapturingProcessor())); + boolean success = task.call(); + + if (!success) { + // Try without module options for simpler environments + diagnostics = new DiagnosticCollector<>(); + try (StandardJavaFileManager fm2 = createFileManager(compiler, diagnostics)) { + task = compiler.getTask(null, fm2, diagnostics, null, null, compilationUnits); + task.setProcessors(List.of(new SchemaCapturingProcessor())); + success = task.call(); + } + } + + assertTrue(success, "Compilation failed: " + diagnostics.getDiagnostics()); + } catch (IOException e) { + fail("Failed to create file manager: " + e.getMessage()); + } + return new ArrayList<>(SchemaCapturingProcessor.capturedSchemas); + } + + private List compileAndCaptureParams(String source) { + SchemaCapturingProcessor.capturedSchemas.clear(); + SchemaCapturingProcessor.capturedParameterSchemas.clear(); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + assertNotNull(compiler, "System Java compiler not available"); + + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + + String className = extractClassName(source); + List compilationUnits = List.of(new InMemorySource(className, source)); + + try (StandardJavaFileManager fm = createFileManager(compiler, diagnostics)) { + JavaCompiler.CompilationTask task = compiler.getTask(null, fm, diagnostics, null, null, compilationUnits); + task.setProcessors(List.of(new SchemaCapturingProcessor())); + boolean success = task.call(); + + assertTrue(success, "Compilation failed: " + diagnostics.getDiagnostics()); + } catch (IOException e) { + fail("Failed to create file manager: " + e.getMessage()); + } + return new ArrayList<>(SchemaCapturingProcessor.capturedParameterSchemas); + } + + private String extractClassName(String source) { + // Simple extraction: find "class X", "record X", "enum X", or "interface X" + for (String keyword : new String[]{"class ", "record ", "enum ", "interface "}) { + int idx = source.indexOf(keyword); + if (idx >= 0) { + int start = idx + keyword.length(); + int end = start; + while (end < source.length() && Character.isJavaIdentifierPart(source.charAt(end))) { + end++; + } + return source.substring(start, end); + } + } + return "Unknown"; + } + + // --- Type mapping tests --- + + @Test + void stringType() { + String source = """ + public class TestStringHolder { + public String schemaTargetString() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetString", "Map.of(\"type\", \"string\")"); + } + + @Test + void intPrimitiveType() { + String source = """ + public class TestIntHolder { + public int schemaTargetInt() { return 0; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetInt", "Map.of(\"type\", \"integer\")"); + } + + @Test + void integerBoxedType() { + String source = """ + public class TestIntegerHolder { + public Integer schemaTargetInteger() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetInteger", "Map.of(\"type\", \"integer\")"); + } + + @Test + void longType() { + String source = """ + public class TestLongHolder { + public long schemaTargetLong() { return 0L; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetLong", "Map.of(\"type\", \"integer\")"); + } + + @Test + void doubleType() { + String source = """ + public class TestDoubleHolder { + public double schemaTargetDouble() { return 0.0; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetDouble", "Map.of(\"type\", \"number\")"); + } + + @Test + void floatType() { + String source = """ + public class TestFloatHolder { + public float schemaTargetFloat() { return 0.0f; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetFloat", "Map.of(\"type\", \"number\")"); + } + + @Test + void booleanPrimitiveType() { + String source = """ + public class TestBooleanHolder { + public boolean schemaTargetBoolean() { return false; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetBoolean", "Map.of(\"type\", \"boolean\")"); + } + + @Test + void booleanBoxedType() { + String source = """ + public class TestBooleanBoxedHolder { + public Boolean schemaTargetBooleanBoxed() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetBooleanBoxed", "Map.of(\"type\", \"boolean\")"); + } + + @Test + void byteBoxedType() { + String source = """ + public class TestByteHolder { + public Byte schemaTargetByte() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetByte", "Map.of(\"type\", \"integer\")"); + } + + @Test + void shortBoxedType() { + String source = """ + public class TestShortHolder { + public Short schemaTargetShort() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetShort", "Map.of(\"type\", \"integer\")"); + } + + @Test + void characterBoxedType() { + String source = """ + public class TestCharHolder { + public Character schemaTargetChar() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetChar", "Map.of(\"type\", \"string\")"); + } + + @Test + void stringArrayType() { + String source = """ + public class TestArrayHolder { + public String[] schemaTargetArray() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetArray", + "Map.of(\"type\", \"array\", \"items\", Map.of(\"type\", \"string\"))"); + } + + @Test + void enumType() { + String source = """ + public enum TestEnumColor { RED, GREEN, BLUE } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "TestEnumColor", + "Map.of(\"type\", \"string\", \"enum\", List.of(\"RED\", \"GREEN\", \"BLUE\"))"); + } + + @Test + void listOfStringType() { + String source = """ + import java.util.List; + public class TestListHolder { + public List schemaTargetList() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetList", + "Map.of(\"type\", \"array\", \"items\", Map.of(\"type\", \"string\"))"); + } + + @Test + void mapStringStringType() { + String source = """ + import java.util.Map; + public class TestMapHolder { + public Map schemaTargetMap() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetMap", + "Map.of(\"type\", \"object\", \"additionalProperties\", Map.of(\"type\", \"string\"))"); + } + + @Test + void mapStringObjectType() { + String source = """ + import java.util.Map; + public class TestMapObjectHolder { + public Map schemaTargetMapObject() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetMapObject", "Map.of(\"type\", \"object\")"); + } + + @Test + void mapStringBooleanType() { + String source = """ + import java.util.Map; + public class TestMapBoolHolder { + public Map schemaTargetMapBool() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetMapBool", + "Map.of(\"type\", \"object\", \"additionalProperties\", Map.of(\"type\", \"boolean\"))"); + } + + @Test + void mapStringLongType() { + String source = """ + import java.util.Map; + public class TestMapLongHolder { + public Map schemaTargetMapLong() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetMapLong", + "Map.of(\"type\", \"object\", \"additionalProperties\", Map.of(\"type\", \"integer\"))"); + } + + @Test + void optionalStringType() { + String source = """ + import java.util.Optional; + public class TestOptionalHolder { + public Optional schemaTargetOptional() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetOptional", "Map.of(\"type\", \"string\")"); + } + + @Test + void optionalIntType() { + String source = """ + import java.util.OptionalInt; + public class TestOptionalIntHolder { + public OptionalInt schemaTargetOptionalInt() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetOptionalInt", "Map.of(\"type\", \"integer\")"); + } + + @Test + void optionalLongType() { + String source = """ + import java.util.OptionalLong; + public class TestOptionalLongHolder { + public OptionalLong schemaTargetOptionalLong() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetOptionalLong", "Map.of(\"type\", \"integer\")"); + } + + @Test + void optionalDoubleType() { + String source = """ + import java.util.OptionalDouble; + public class TestOptionalDoubleHolder { + public OptionalDouble schemaTargetOptionalDouble() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetOptionalDouble", "Map.of(\"type\", \"number\")"); + } + + @Test + void uuidType() { + String source = """ + import java.util.UUID; + public class TestUuidHolder { + public UUID schemaTargetUuid() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetUuid", "Map.of(\"type\", \"string\", \"format\", \"uuid\")"); + } + + @Test + void offsetDateTimeType() { + String source = """ + import java.time.OffsetDateTime; + public class TestDateTimeHolder { + public OffsetDateTime schemaTargetDateTime() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetDateTime", + "Map.of(\"type\", \"string\", \"format\", \"date-time\")"); + } + + @Test + void localDateTimeType() { + String source = """ + import java.time.LocalDateTime; + public class TestLocalDateTimeHolder { + public LocalDateTime schemaTargetLocalDateTime() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetLocalDateTime", + "Map.of(\"type\", \"string\", \"format\", \"date-time\")"); + } + + @Test + void instantType() { + String source = """ + import java.time.Instant; + public class TestInstantHolder { + public Instant schemaTargetInstant() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetInstant", "Map.of(\"type\", \"string\", \"format\", \"date-time\")"); + } + + @Test + void zonedDateTimeType() { + String source = """ + import java.time.ZonedDateTime; + public class TestZonedDateTimeHolder { + public ZonedDateTime schemaTargetZonedDateTime() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetZonedDateTime", + "Map.of(\"type\", \"string\", \"format\", \"date-time\")"); + } + + @Test + void localDateType() { + String source = """ + import java.time.LocalDate; + public class TestLocalDateHolder { + public LocalDate schemaTargetLocalDate() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetLocalDate", "Map.of(\"type\", \"string\", \"format\", \"date\")"); + } + + @Test + void localTimeType() { + String source = """ + import java.time.LocalTime; + public class TestLocalTimeHolder { + public LocalTime schemaTargetLocalTime() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetLocalTime", "Map.of(\"type\", \"string\", \"format\", \"time\")"); + } + + @Test + void recordType() { + String source = """ + public record TestRecordPerson(String name, int age, boolean active) {} + """; + List schemas = compileAndCapture(source); + String expected = "Map.of(\"type\", \"object\", \"properties\", " + + "Map.ofEntries(Map.entry(\"name\", Map.of(\"type\", \"string\")), " + + "Map.entry(\"age\", Map.of(\"type\", \"integer\")), " + + "Map.entry(\"active\", Map.of(\"type\", \"boolean\"))), " + + "\"required\", List.of(\"name\", \"age\", \"active\"))"; + assertContainsSchema(schemas, "TestRecordPerson", expected); + } + + @Test + void recordWithOptionalField() { + String source = """ + import java.util.Optional; + public record TestRecordWithOptional(String name, Optional nickname) {} + """; + List schemas = compileAndCapture(source); + String expected = "Map.of(\"type\", \"object\", \"properties\", " + + "Map.ofEntries(Map.entry(\"name\", Map.of(\"type\", \"string\")), " + + "Map.entry(\"nickname\", Map.of(\"type\", \"string\"))), " + "\"required\", List.of(\"name\"))"; + assertContainsSchema(schemas, "TestRecordWithOptional", expected); + } + + @Test + void recordWithMoreThanTenFields() { + String source = """ + public record TestRecordLarge( + String f1, String f2, String f3, String f4, String f5, + String f6, String f7, String f8, String f9, String f10, + String f11) {} + """; + List schemas = compileAndCapture(source); + // Verify the schema contains all 11 fields and uses Map.ofEntries + String schema = schemas.stream().filter(s -> s.startsWith("TestRecordLarge=")).findFirst().orElse(""); + assertFalse(schema.isEmpty(), "Expected schema for TestRecordLarge"); + assertTrue(schema.contains("Map.ofEntries("), "Should use Map.ofEntries for >10 fields: " + schema); + assertTrue(schema.contains("Map.entry(\"f1\""), "Should have f1: " + schema); + assertTrue(schema.contains("Map.entry(\"f11\""), "Should have f11: " + schema); + // Verify the generated source expression is compilable by re-compiling it + String schemaExpr = schema.substring(schema.indexOf('=') + 1); + String validationSource = "import java.util.Map;\nimport java.util.List;\n" + + "public class LargeRecordValidation {\n" + " @SuppressWarnings(\"unchecked\")\n" + + " public Object schema() { return " + schemaExpr + "; }\n}\n"; + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + List units = List.of(new InMemorySource("LargeRecordValidation", validationSource)); + try (StandardJavaFileManager fm = createFileManager(compiler, diagnostics)) { + JavaCompiler.CompilationTask task = compiler.getTask(null, fm, diagnostics, null, null, units); + boolean success = task.call(); + assertTrue(success, "Generated schema for >10-field record does not compile: " + + diagnostics.getDiagnostics() + "\nSource:\n" + validationSource); + } catch (IOException e) { + fail("Failed to create file manager: " + e.getMessage()); + } + } + + @Test + void parametersSchema() { + String source = """ + public class TestParamsHolder { + public void parametersTarget(String query, int limit, boolean verbose) {} + } + """; + List paramSchemas = compileAndCaptureParams(source); + assertFalse(paramSchemas.isEmpty(), "Expected parameter schemas"); + String schema = paramSchemas.get(0); + assertTrue(schema.contains("\"type\", \"object\""), "Should be object type: " + schema); + assertTrue(schema.contains("Map.entry(\"query\", Map.of(\"type\", \"string\"))"), + "Should have query property: " + schema); + assertTrue(schema.contains("Map.entry(\"limit\", Map.of(\"type\", \"integer\"))"), + "Should have limit property: " + schema); + assertTrue(schema.contains("Map.entry(\"verbose\", Map.of(\"type\", \"boolean\"))"), + "Should have verbose property: " + schema); + assertTrue(schema.contains("\"required\", List.of("), "Should have required list: " + schema); + } + + @Test + void generatedSourceIsValidJava() { + // Verify that generated schema source code compiles when embedded in a method + // body + String source = """ + import java.util.List; + import java.util.Map; + import java.util.Optional; + public class TestValidJavaHolder { + public String schemaTargetStr() { return null; } + public List schemaTargetListStr() { return null; } + public Map schemaTargetMapStr() { return null; } + public Optional schemaTargetOpt() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertFalse(schemas.isEmpty()); + + // Build a Java source that uses the generated schema expressions + StringBuilder validationSource = new StringBuilder(); + validationSource.append("import java.util.Map;\n"); + validationSource.append("import java.util.List;\n"); + validationSource.append("public class SchemaValidation {\n"); + validationSource.append(" @SuppressWarnings(\"unchecked\")\n"); + validationSource.append(" public void validate() {\n"); + for (int i = 0; i < schemas.size(); i++) { + String schema = schemas.get(i); + String schemaExpr = schema.substring(schema.indexOf('=') + 1); + validationSource.append(" Object s" + i + " = " + schemaExpr + ";\n"); + } + validationSource.append(" }\n"); + validationSource.append("}\n"); + + // Compile the validation source to verify syntactic validity + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + List compilationUnits = List + .of(new InMemorySource("SchemaValidation", validationSource.toString())); + + try (StandardJavaFileManager fm = createFileManager(compiler, diagnostics)) { + JavaCompiler.CompilationTask task = compiler.getTask(null, fm, diagnostics, null, null, compilationUnits); + boolean success = task.call(); + + assertTrue(success, "Generated schema source code is not valid Java: " + diagnostics.getDiagnostics() + + "\nSource:\n" + validationSource); + } catch (IOException e) { + fail("Failed to create file manager: " + e.getMessage()); + } + } + + @Test + void nestedMapListType() { + String source = """ + import java.util.List; + import java.util.Map; + public class TestNestedHolder { + public Map> schemaTargetNestedMap() { return null; } + } + """; + List schemas = compileAndCapture(source); + String expected = "Map.of(\"type\", \"object\", \"additionalProperties\", " + + "Map.of(\"type\", \"array\", \"items\", Map.of(\"type\", \"string\")))"; + assertContainsSchema(schemas, "schemaTargetNestedMap", expected); + } + + @Test + void objectType() { + String source = """ + public class TestObjectHolder { + public Object schemaTargetObject() { return null; } + } + """; + List schemas = compileAndCapture(source); + assertContainsSchema(schemas, "schemaTargetObject", "Map.of()"); + } + + @Test + void sealedInterfaceType() { + String sealedInterface = """ + public sealed interface TestSealedShape permits TestSealedCircle, TestSealedRect {} + """; + String circle = """ + public record TestSealedCircle(double radius) implements TestSealedShape {} + """; + String rect = """ + public record TestSealedRect(double width, double height) implements TestSealedShape {} + """; + List schemas = compileAndCapture(sealedInterface, circle, rect); + String expected = "Map.of(\"oneOf\", List.of(" + "Map.of(\"type\", \"object\", \"properties\", " + + "Map.ofEntries(Map.entry(\"radius\", Map.of(\"type\", \"number\"))), " + + "\"required\", List.of(\"radius\")), " + "Map.of(\"type\", \"object\", \"properties\", " + + "Map.ofEntries(Map.entry(\"width\", Map.of(\"type\", \"number\")), " + + "Map.entry(\"height\", Map.of(\"type\", \"number\"))), " + + "\"required\", List.of(\"width\", \"height\"))))"; + assertContainsSchema(schemas, "TestSealedShape", expected); + } + + private void assertContainsSchema(List schemas, String methodName, String expectedSchema) { + String expected = methodName + "=" + expectedSchema; + assertTrue(schemas.stream().anyMatch(s -> s.equals(expected)), + "Expected schema '" + expected + "' not found in: " + schemas); + } +} diff --git a/nodejs/README.md b/nodejs/README.md index e9d83c6df9..52b3d28053 100644 --- a/nodejs/README.md +++ b/nodejs/README.md @@ -84,9 +84,11 @@ new CopilotClient(options?: CopilotClientOptions) **Options:** - `connection?: RuntimeConnection` - How to connect to the Copilot runtime. Construct via the factory functions on `RuntimeConnection`: - - `RuntimeConnection.forStdio({ path?, args? })` (default) — spawn the runtime and communicate over its stdin/stdout. - - `RuntimeConnection.forTcp({ port?, connectionToken?, path?, args? })` — spawn the runtime as a TCP server. + - `RuntimeConnection.forStdio({ path?, args?, env? })` (default) — spawn the runtime and communicate over its stdin/stdout. + - `RuntimeConnection.forTcp({ port?, connectionToken?, path?, args?, env? })` — spawn the runtime as a TCP server. - `RuntimeConnection.forUri(url, { connectionToken? })` — connect to an already-running runtime (mutually exclusive with `gitHubToken`/`useLoggedInUser`). There is no top-level `cliUrl` shortcut; use this factory for URL-based connections. + - `RuntimeConnection.forInProcess()` — host the runtime in-process over its native C ABI (FFI). **Experimental.** Because the runtime shares this process, `env`, `telemetry`, and `workingDirectory` are rejected with this transport; set them on the host process instead. + - The child-process transports (`forStdio`/`forTcp`) also accept a per-connection `env`. Set it there or via the top-level `env` option — not both (setting both throws). - `mode?: "empty" | "copilot-cli"` - Defaulting strategy. Use `"empty"` for multi-user server mode; defaults to `"copilot-cli"`. - `workingDirectory?: string` - Working directory for the runtime process (default: current process cwd). - `baseDirectory?: string` - Base directory for Copilot data (session state, config, etc.). Sets `COPILOT_HOME` on the spawned runtime. When not set, the runtime defaults to `~/.copilot`. Ignored when connecting via `RuntimeConnection.forUri`. diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 6cf1463a38..799053c0fa 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -9,7 +9,8 @@ "version": "0.0.0-dev", "license": "MIT", "dependencies": { - "@github/copilot": "^1.0.65", + "@github/copilot": "^1.0.71", + "koffi": "^3.1.0", "vscode-jsonrpc": "^8.2.1", "zod": "^4.3.6" }, @@ -699,9 +700,9 @@ } }, "node_modules/@github/copilot": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.65.tgz", - "integrity": "sha512-J1XvLuOiVpiAi/E1MBICBymszCgdGLnZxokosXzGcmcjEVZd+QSDoW/kPRHq6oEyBT9SDASPcjCEZ9Q0rLJllg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.71.tgz", + "integrity": "sha512-F3axBi+sXSLYDJbxCBW36bM6MYKNC2rlyAf3Ivo/MjiHKKJW7j5AmaR1IRYS9Gt8r9mxOwWFM1cJFA+CuLaR8g==", "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "detect-libc": "^2.1.2" @@ -710,20 +711,20 @@ "copilot": "npm-loader.js" }, "optionalDependencies": { - "@github/copilot-darwin-arm64": "1.0.65", - "@github/copilot-darwin-x64": "1.0.65", - "@github/copilot-linux-arm64": "1.0.65", - "@github/copilot-linux-x64": "1.0.65", - "@github/copilot-linuxmusl-arm64": "1.0.65", - "@github/copilot-linuxmusl-x64": "1.0.65", - "@github/copilot-win32-arm64": "1.0.65", - "@github/copilot-win32-x64": "1.0.65" + "@github/copilot-darwin-arm64": "1.0.71", + "@github/copilot-darwin-x64": "1.0.71", + "@github/copilot-linux-arm64": "1.0.71", + "@github/copilot-linux-x64": "1.0.71", + "@github/copilot-linuxmusl-arm64": "1.0.71", + "@github/copilot-linuxmusl-x64": "1.0.71", + "@github/copilot-win32-arm64": "1.0.71", + "@github/copilot-win32-x64": "1.0.71" } }, "node_modules/@github/copilot-darwin-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.65.tgz", - "integrity": "sha512-NFc4xIstZNiIuAYkurQT5DVtbZjBoZ/z6yt/Ffcom7Y5QGjfpN4BFuekv9k+OADRioxxR99NgmhjbuNPWtQhNQ==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.71.tgz", + "integrity": "sha512-mEWzyqbqRAWgyU7i2uuSRoVPx/TwaFQX0nZmw0bc30aJ0BnO7cy2kYQyCHw8ykmf/tfxT0xauZ6k0BOFmWizzQ==", "cpu": [ "arm64" ], @@ -737,9 +738,9 @@ } }, "node_modules/@github/copilot-darwin-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.65.tgz", - "integrity": "sha512-0wtV22KmTa12VbqWRRkgvJcBz/oIbszfcIpyDWGc4MzbCVksajQ3TWVQ6c7Sdzj5RifCaYdkHAX2zuIYXYlLoQ==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.71.tgz", + "integrity": "sha512-Md9yEg406OBVBx3w4PeEj62TubulVLBcHleqmCoOoUmPgUxPZotUbrqz3rtbzADbXfrrD7JWvVsbd2UiNL194w==", "cpu": [ "x64" ], @@ -753,9 +754,9 @@ } }, "node_modules/@github/copilot-linux-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.65.tgz", - "integrity": "sha512-dOwdy/YbTXQN/+x2v4ZgiDycdRtWElyHxPuA6ail3yJDt0nagwn8OYAA/diBLPMAJuuBXiOZGvvb9fGRuh7Xgg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.71.tgz", + "integrity": "sha512-ykLJYOqBj3jRB5IJCDugLClAqbr7DmtTbUjlNY7+Jdq/n6i+d7xUQGclf1IWL5gnxbGQVAf+zkToD+sRM389Kg==", "cpu": [ "arm64" ], @@ -769,9 +770,9 @@ } }, "node_modules/@github/copilot-linux-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.65.tgz", - "integrity": "sha512-al/1a/l/GrpHtygTxt7PZspmv0eHBPdAZ5B31J7Hv/GRdVZM4STCC9dCIOSUFsOX2fhaKD8yLfz4HureSYs23g==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.71.tgz", + "integrity": "sha512-pC0FNHG+BBwZd6yZlM85kkAGN+uJhM6o+THi76N2GnnSxmw7+remb1mvYxdgRVbdCm+LBUIbCKRWJLuMwrfb6A==", "cpu": [ "x64" ], @@ -785,9 +786,9 @@ } }, "node_modules/@github/copilot-linuxmusl-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.65.tgz", - "integrity": "sha512-xccQeJSR45xyoaL7J5mZjtU++dmte+ZCDQkIlrpTn2yuMl2LWriBvorQ1P2MwVnXmIiW/GHi93B+lNtsybA9yw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.71.tgz", + "integrity": "sha512-hBmDljFTjacxqZTasCEy43H8EIzuXB/hHEBBCMFjhB9J00nIxsO6Dh0woTifKpx7knTYZdpTjjca3D0pAoZlUA==", "cpu": [ "arm64" ], @@ -801,9 +802,9 @@ } }, "node_modules/@github/copilot-linuxmusl-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.65.tgz", - "integrity": "sha512-RHPVUaqjSrhKHQ2EpfGKWErnV+R5elGIZaHXPKO10zpSaQD9b/C9u6nLigZnBuT/8sCaJpVrazPMwOYvYA62aw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.71.tgz", + "integrity": "sha512-CfTXU8pa5dxRz22xQzoi3TiG1PJo9+WR8PRDiPSdkIBSyPJ1NvX87DJmfXjTgeAfR+wkjt/p0keDCaBBVhNmUA==", "cpu": [ "x64" ], @@ -817,9 +818,9 @@ } }, "node_modules/@github/copilot-win32-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.65.tgz", - "integrity": "sha512-/vSE/t9Wm3eFSWpxlKyn/oL8OAVOB0yFO7ECxhgbtiqNrBd1tgpYh1k7IXBIWa/saxlV1+de6DEmPuQfx3Z0bg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.71.tgz", + "integrity": "sha512-+HI1DokixXhHUahj06Fw67ZAigBuXKC58BFma4UJOGrQsDgwOSbqeTQHCw6vuymzjKlg3sactfsCUTaefkjscQ==", "cpu": [ "arm64" ], @@ -833,9 +834,9 @@ } }, "node_modules/@github/copilot-win32-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.65.tgz", - "integrity": "sha512-wjVWXepET+SpFg8z8V43ZiTy6X1OerCb7yu3QZKNNJ3zY9z20goihPXQCDWkiJpGzszNSgfrsiqUzpUsC9qS0A==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.71.tgz", + "integrity": "sha512-02kXOBd9CwBbCaztuf71WYWn+uGapCuiaasomN4tcMH3HBVZ4gi3J0ZUoRcgcS80xh81uQyeBHbnUKzb/RE/9A==", "cpu": [ "x64" ], @@ -921,6 +922,230 @@ "dev": true, "license": "MIT" }, + "node_modules/@koromix/koffi-darwin-arm64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-darwin-arm64/-/koffi-darwin-arm64-3.1.0.tgz", + "integrity": "sha512-VEt5r3fXTfbejr83PnuOP0H7s9Zmazcs+lofu96DOcRkistlMsn59wYyWiKpyAjs9PCgm0Ykh62ChZ3CGMmIOg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-darwin-x64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-darwin-x64/-/koffi-darwin-x64-3.1.0.tgz", + "integrity": "sha512-n/tVRB9xIzdXT5H3zZt8ueThgWTSDL+yU7PWnU8wbZPBSawP/otx3swQyd6nMOqj1bmHgSHopiKSBXRS9pllmg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-freebsd-arm64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-freebsd-arm64/-/koffi-freebsd-arm64-3.1.0.tgz", + "integrity": "sha512-vazoPYIhOAlXZksVIqDRMIID4VeUZKx8F3dR90hOobT2ATyOkqNS5dv5UCV7Q7DSq22lQTrdbvENBAhROzCp0w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-freebsd-ia32": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-freebsd-ia32/-/koffi-freebsd-ia32-3.1.0.tgz", + "integrity": "sha512-Vm7Uc97ru6RTSVmae2zCZZQeaizqVZ8WoU4+gG4H03Qe+WOj7kbKt/MxT7VBzdbPYIU5ZJeG/ZED1YlZyab6eQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-freebsd-x64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-freebsd-x64/-/koffi-freebsd-x64-3.1.0.tgz", + "integrity": "sha512-N+VuVWjoiYPy1Go5mRadZ3B6RM5Qz+eCLhj2LXrMlefbUJ+O4gg7teCUGvPGfBEHDgmSN4yYUrfQmdJC10vOYw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-linux-arm64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-linux-arm64/-/koffi-linux-arm64-3.1.0.tgz", + "integrity": "sha512-Wx5iOkeALe2ympLdiYwRpIg5qUkyQIv8N2foZ9rRker0uE7ZtXew2RRkbEgMir4b0yDYR1zyXd6B62GUzLtZ/g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-linux-ia32": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-linux-ia32/-/koffi-linux-ia32-3.1.0.tgz", + "integrity": "sha512-1DjYm1QehXU0dgn0uE+FGYOb3Of7GiTMqLS+ZI2gbl1b+h76sz4LRBvDVrQyAmSMVVU8/7696S21YgE/iBhBVg==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-linux-loong64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-linux-loong64/-/koffi-linux-loong64-3.1.0.tgz", + "integrity": "sha512-NOa0LdyltdESz3oeTqUH6MErHVoJOHoeXIsEp6xIMTUh4eKXEtlDQeoK6EYqo0DnBt83Xud95qLvi4Aw12pG4Q==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-linux-riscv64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-linux-riscv64/-/koffi-linux-riscv64-3.1.0.tgz", + "integrity": "sha512-Ye6kiXZCGxGtAIXSly6XuOP5tJZNYOZ2eVg33k1MilKrzimAy9Mpw4d6e9+Sfsc1jesgeNYs1sb5iaI8HS3ncA==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-linux-x64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-linux-x64/-/koffi-linux-x64-3.1.0.tgz", + "integrity": "sha512-3yQTOkQrMna4VX+yeyfYImBjLlGrItMpsWyfaW1uSiz/A6GRydqdwYH7DWnp4Z+RSGYZpsewkf7byMc8pOOQKA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-openbsd-ia32": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-openbsd-ia32/-/koffi-openbsd-ia32-3.1.0.tgz", + "integrity": "sha512-/cDoFHb9yx4+yoT3GUpnKnfi3W2drG+/Ewo0TTZaQHb4PsxnYYyT6V8+t4cL5XXbQcTTcOsZxpmBRrn0NBa3dA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-openbsd-x64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-openbsd-x64/-/koffi-openbsd-x64-3.1.0.tgz", + "integrity": "sha512-CoQdqgnKvWgTXXZlUst8cBRQEov7QsxlTN2WAsu9wez01Xe6gEcH/zYePANualzzCbnaELfe5P0rA80QkoDuPA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-win32-ia32": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-win32-ia32/-/koffi-win32-ia32-3.1.0.tgz", + "integrity": "sha512-WjrA+DEkpy0xEHu48+NSOboHhTnzkIfsFuq3d/WrSs+T9WflWRng3jC7mdJxmR4eHb6i6BqjW3k/U0mNUTjFPA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/@koromix/koffi-win32-x64": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@koromix/koffi-win32-x64/-/koffi-win32-x64-3.1.0.tgz", + "integrity": "sha512-tnK5+IkzQBauQAQSzuyjso8OOIQRlaTZS39xIWpfqVYDLVDIuLDQk/WwHcOrR5yxlDrZq9ygiebBTOfcJFia7w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", @@ -2592,6 +2817,32 @@ "json-buffer": "3.0.1" } }, + "node_modules/koffi": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/koffi/-/koffi-3.1.0.tgz", + "integrity": "sha512-0mCvdjTJBXioiaKNz0vajAEdWtfM5qyhVXSq+wQrrU3odzNvl/J7Cqna79QpNo9mfoKpQgGsyFFDRtDACCwGrQ==", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "url": "https://liberapay.com/Koromix" + }, + "optionalDependencies": { + "@koromix/koffi-darwin-arm64": "3.1.0", + "@koromix/koffi-darwin-x64": "3.1.0", + "@koromix/koffi-freebsd-arm64": "3.1.0", + "@koromix/koffi-freebsd-ia32": "3.1.0", + "@koromix/koffi-freebsd-x64": "3.1.0", + "@koromix/koffi-linux-arm64": "3.1.0", + "@koromix/koffi-linux-ia32": "3.1.0", + "@koromix/koffi-linux-loong64": "3.1.0", + "@koromix/koffi-linux-riscv64": "3.1.0", + "@koromix/koffi-linux-x64": "3.1.0", + "@koromix/koffi-openbsd-ia32": "3.1.0", + "@koromix/koffi-openbsd-x64": "3.1.0", + "@koromix/koffi-win32-ia32": "3.1.0", + "@koromix/koffi-win32-x64": "3.1.0" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", diff --git a/nodejs/package.json b/nodejs/package.json index d037ceefae..4f588640a8 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -56,7 +56,8 @@ "author": "GitHub", "license": "MIT", "dependencies": { - "@github/copilot": "^1.0.65", + "@github/copilot": "^1.0.71", + "koffi": "^3.1.0", "vscode-jsonrpc": "^8.2.1", "zod": "^4.3.6" }, diff --git a/nodejs/samples/package-lock.json b/nodejs/samples/package-lock.json index 34152796f4..89c74c1535 100644 --- a/nodejs/samples/package-lock.json +++ b/nodejs/samples/package-lock.json @@ -18,7 +18,8 @@ "version": "0.0.0-dev", "license": "MIT", "dependencies": { - "@github/copilot": "^1.0.65", + "@github/copilot": "^1.0.71", + "koffi": "^3.1.0", "vscode-jsonrpc": "^8.2.1", "zod": "^4.3.6" }, diff --git a/nodejs/src/client.ts b/nodejs/src/client.ts index 53686a6ca3..61f4a99416 100644 --- a/nodejs/src/client.ts +++ b/nodejs/src/client.ts @@ -33,9 +33,14 @@ import { registerClientGlobalApiHandlers, registerClientSessionApiHandlers, } from "./generated/rpc.js"; -import type { OpenCanvasInstance, SessionUpdateOptionsParams } from "./generated/rpc.js"; +import type { + GitHubTelemetryNotification, + OpenCanvasInstance, + SessionUpdateOptionsParams, +} from "./generated/rpc.js"; import { getSdkProtocolVersion } from "./sdkProtocolVersion.js"; import { CopilotSession } from "./session.js"; +import type { FfiRuntimeHost } from "./ffiRuntimeHost.js"; import { createSessionFsAdapter, type SessionFsProvider } from "./sessionFsProvider.js"; import { createCopilotRequestAdapter } from "./copilotRequestHandler.js"; import type { CopilotRequestHandler } from "./copilotRequestHandler.js"; @@ -54,6 +59,7 @@ import type { BearerTokenProvider, GetStatusResponse, InternalRuntimeConnection, + RuntimeConnection, LargeToolOutputConfig, MCPServerConfig, ModelInfo, @@ -469,6 +475,7 @@ class TeardownResilientStreamMessageWriter extends StreamMessageWriter { export class CopilotClient { private cliStartTimeout: ReturnType | null = null; private cliProcess: ChildProcess | null = null; + private ffiHost: FfiRuntimeHost | null = null; private connection: MessageConnection | null = null; private messageWriter: TeardownResilientStreamMessageWriter | null = null; private socket: Socket | null = null; @@ -514,7 +521,8 @@ export class CopilotClient { /** Connection-level session filesystem config, set via constructor option. */ private sessionFsConfig: SessionFsConfig | null = null; private requestHandler: CopilotRequestHandler | null = null; - private llmInferenceHandlers: import("./generated/rpc.js").ClientGlobalApiHandlers = {}; + private onGitHubTelemetry?: (notification: GitHubTelemetryNotification) => void | Promise; + private clientGlobalHandlers: import("./generated/rpc.js").ClientGlobalApiHandlers = {}; /** * Typed server-scoped RPC methods. @@ -558,6 +566,32 @@ export class CopilotClient { } } + /** + * Environment variable that overrides the transport when the caller does not set + * {@link CopilotClientOptions.connection}. Accepts `"inprocess"` or `"stdio"` + * (case-insensitive); unset preserves the default stdio transport. Any other value + * is an error. + */ + private static readonly DEFAULT_CONNECTION_ENV_VAR = "COPILOT_SDK_DEFAULT_CONNECTION"; + + /** + * Resolves the default {@link RuntimeConnection} for the no-connection case, + * honoring {@link CopilotClient.DEFAULT_CONNECTION_ENV_VAR}. + */ + private static resolveDefaultConnection(): RuntimeConnection { + const value = process.env[CopilotClient.DEFAULT_CONNECTION_ENV_VAR]; + if (!value || value.toLowerCase() === "stdio") { + return { kind: "stdio" }; + } + if (value.toLowerCase() === "inprocess") { + return { kind: "inprocess" }; + } + throw new Error( + `Invalid ${CopilotClient.DEFAULT_CONNECTION_ENV_VAR} value '${value}'. ` + + `Expected 'inprocess', 'stdio', or unset.` + ); + } + /** * Creates a new CopilotClient instance. * @@ -589,8 +623,10 @@ export class CopilotClient { // Resolve the connection mode. `_internalConnection` is set by // `joinSession()` to opt into the parent-process stdio path; consumers // should always go through the public `connection` field. - const conn: InternalRuntimeConnection = options._internalConnection ?? - options.connection ?? { kind: "stdio" }; + const conn: InternalRuntimeConnection = + options._internalConnection ?? + options.connection ?? + CopilotClient.resolveDefaultConnection(); if ( conn.kind === "uri" && @@ -600,6 +636,40 @@ export class CopilotClient { "gitHubToken and useLoggedInUser cannot be used with RuntimeConnection.forUri (external server manages its own auth)" ); } + if (conn.kind === "inprocess" && options.workingDirectory !== undefined) { + throw new Error( + "workingDirectory is not supported with RuntimeConnection.forInProcess(): the in-process " + + "transport hosts the runtime in this process, so honoring it would require mutating the " + + "shared process-global cwd. Change the host process's working directory before " + + "constructing the client instead." + ); + } + if (conn.kind === "inprocess" && options.env !== undefined) { + throw new Error( + "env is not supported with RuntimeConnection.forInProcess(): the in-process transport loads " + + "the native runtime into the shared host process, whose single environment block cannot " + + "carry per-client values. Set the variables on the host process environment instead." + ); + } + if (conn.kind === "inprocess" && options.telemetry !== undefined) { + throw new Error( + "telemetry is not supported with RuntimeConnection.forInProcess(): telemetry configuration " + + "is lowered to environment variables read by native runtime code running in the shared " + + "host process, so per-client telemetry cannot be honored in-process. Configure telemetry " + + "via the host process environment, or use a child-process transport." + ); + } + if ( + (conn.kind === "stdio" || conn.kind === "tcp") && + conn.env !== undefined && + options.env !== undefined + ) { + throw new Error( + "Set environment variables via either the client-level env option or the connection's env " + + "(RuntimeConnection.forStdio/forTcp), not both. Prefer the connection-level env for " + + "child-process transports." + ); + } if (conn.kind === "tcp" && conn.connectionToken !== undefined) { if (typeof conn.connectionToken !== "string" || conn.connectionToken.length === 0) { throw new Error("connectionToken must be a non-empty string"); @@ -634,9 +704,16 @@ export class CopilotClient { this.onGetTraceContext = options.onGetTraceContext; this.sessionFsConfig = options.sessionFs ?? null; this.requestHandler = options.requestHandler ?? null; - this.setupLlmInference(); - - const effectiveEnv = options.env ?? process.env; + this.onGitHubTelemetry = options.onGitHubTelemetry; + this.setupClientGlobalHandlers(); + + // Connection-level env (child-process transports only) takes precedence + // over the client-level env, which falls back to the ambient process env. + // The constructor guard above rejects setting both, so at most one of the + // first two is defined. Mirrors .NET/Python precedence. + const connEnv: Record | undefined = + conn.kind === "stdio" || conn.kind === "tcp" ? conn.env : undefined; + const effectiveEnv = connEnv ?? options.env ?? process.env; this.resolvedEnv = effectiveEnv; this.resolvedCliPath = conn.kind === "stdio" || conn.kind === "tcp" @@ -751,19 +828,35 @@ export class CopilotClient { session.clientSessionApis.sessionFs = createSessionFsAdapter(provider); } - private setupLlmInference(): void { - if (!this.requestHandler) { - return; - } - this.llmInferenceHandlers = { - llmInference: createCopilotRequestAdapter(this.requestHandler, () => { + private setupClientGlobalHandlers(): void { + const handlers: import("./generated/rpc.js").ClientGlobalApiHandlers = {}; + // `hooks.invoke` is a client-global RPC method whose payload carries a + // `sessionId`; route each invocation to the matching session's dispatcher. + handlers.hooks = { + invoke: async (params) => await this.handleHooksInvoke(params), + }; + if (this.requestHandler) { + handlers.llmInference = createCopilotRequestAdapter(this.requestHandler, () => { if (!this.connection) { return undefined; } this._rpc ??= createServerRpc(this.connection); return this._rpc; - }), - }; + }); + } + if (this.onGitHubTelemetry) { + const onGitHubTelemetry = this.onGitHubTelemetry; + handlers.gitHubTelemetry = { + event: async (notification) => { + try { + await onGitHubTelemetry(notification); + } catch { + // Ignore handler errors + } + }, + }; + } + this.clientGlobalHandlers = handlers; } /** @@ -793,7 +886,9 @@ export class CopilotClient { try { // Only start CLI server process if not connecting to external server - if (!this.isExternalServer) { + if (this.connectionConfig.kind === "inprocess") { + await this.startInProcessFfi(); + } else if (!this.isExternalServer) { await this.startCLIServer(); } @@ -856,6 +951,20 @@ export class CopilotClient { // Disconnect all active sessions with retry logic const activeSessions = [...this.sessions.values()]; + // TEMPORARY: over the in-process (FFI) transport the runtime shares this + // process, so a turn still running when the runtime disposes the session + // can leave that session's SQLite session.db handle open — it isn't + // reclaimed by terminating a child process, so the file stays locked + // (Windows) and the session-state directory can't be removed. Abort any + // in-flight turn first so it cancels and releases the handle. Best-effort + // and idempotent: a session with no active turn is a no-op. Scoped to + // in-process only: stdio/tcp runtimes run in a child process that we kill + // on shutdown (which frees the handle), and for external servers we don't + // own the runtime and aborting would cancel pending work other clients + // may still resume. Remove once the runtime cleans up fully on shutdown. + if (this.connectionConfig.kind === "inprocess") { + await Promise.allSettled(activeSessions.map((session) => session.abort())); + } for (const session of activeSessions) { const sessionId = session.sessionId; let lastError: Error | null = null; @@ -893,7 +1002,7 @@ export class CopilotClient { // Ask SDK-owned runtimes to flush and clean up before we tear down // their transport/process. External runtimes may be shared, so only // close our connection to them. - if (this.connection && this.cliProcess && !this.isExternalServer) { + if (this.connection && (this.cliProcess || this.ffiHost) && !this.isExternalServer) { const runtimeShutdownStart = Date.now(); const shutdownPromise = this.rpc.runtime.shutdown(); void shutdownPromise.catch(() => undefined); @@ -994,6 +1103,21 @@ export class CopilotClient { ); } } + // Tear down the in-process FFI host (closes the native connection and + // shuts down the native runtime host) for SDK-owned in-process runtimes. + if (this.ffiHost) { + const host = this.ffiHost; + this.ffiHost = null; + try { + host.dispose(); + } catch (error) { + errors.push( + new Error( + `Failed to dispose in-process runtime host: ${error instanceof Error ? error.message : String(error)}` + ) + ); + } + } if (this.cliStartTimeout) { clearTimeout(this.cliStartTimeout); this.cliStartTimeout = null; @@ -1096,6 +1220,16 @@ export class CopilotClient { this.cliProcess = null; } + // Tear down the in-process FFI host (if any). + if (this.ffiHost) { + try { + this.ffiHost.dispose(); + } catch { + // Ignore errors during force stop + } + this.ffiHost = null; + } + if (this.cliStartTimeout) { clearTimeout(this.cliStartTimeout); this.cliStartTimeout = null; @@ -1326,7 +1460,8 @@ export class CopilotClient { sessionId, this.connection!, undefined, - this.onGetTraceContext + this.onGetTraceContext, + { mcpAuthHandler: config.onMcpAuthRequest } ); s.registerTools(config.tools); s.registerCanvases(config.canvases); @@ -1391,12 +1526,15 @@ export class CopilotClient { overridesBuiltInTool: tool.overridesBuiltInTool, skipPermission: tool.skipPermission, defer: tool.defer, + metadata: tool.metadata, })), + toolSearch: config.toolSearch, canvases: config.canvases?.map((canvas) => canvas.declaration), requestCanvasRenderer: config.requestCanvasRenderer, requestExtensions: config.requestExtensions, extensionSdkPath: config.extensionSdkPath, extensionInfo: config.extensionInfo, + canvasProvider: config.canvasProvider, commands: config.commands?.map((cmd) => ({ name: cmd.name, description: cmd.description, @@ -1405,11 +1543,14 @@ export class CopilotClient { availableTools: toolFilterOptions.availableTools, excludedTools: toolFilterOptions.excludedTools, toolFilterPrecedence: toolFilterOptions.toolFilterPrecedence, + excludedBuiltinAgents: config.excludedBuiltinAgents, provider: bearerWireProvider, capi: config.capi, providers: bearerWireProviders, models: config.models, enableSessionTelemetry: config.enableSessionTelemetry, + enableCitations: config.enableCitations, + sessionLimits: config.sessionLimits, modelCapabilities: config.modelCapabilities, largeOutput: toWireLargeOutput(config.largeOutput), requestPermission: !!config.onPermissionRequest, @@ -1422,6 +1563,9 @@ export class CopilotClient { workingDirectory: config.workingDirectory, streaming: config.streaming, includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true, + ...(this.onGitHubTelemetry != null + ? { enableGitHubTelemetryForwarding: true } + : {}), mcpServers: toWireMcpServers(config.mcpServers), mcpOAuthTokenStorage: config.mcpOAuthTokenStorage, envValueMode: "direct", @@ -1448,6 +1592,7 @@ export class CopilotClient { remoteSession: config.remoteSession, cloud: config.cloud, expAssignments: config.expAssignments, + enableManagedSettings: config.enableManagedSettings, }); const { @@ -1473,6 +1618,12 @@ export class CopilotClient { session = initializeSession(returnedSessionId); registeredId = returnedSessionId; } + if (config.onMcpAuthRequest) { + await this.connection!.sendRequest("session.eventLog.registerInterest", { + sessionId: returnedSessionId, + eventType: "mcp.oauth_required", + }); + } session["_workspacePath"] = workspacePath; session.setCapabilities(capabilities); @@ -1522,7 +1673,8 @@ export class CopilotClient { sessionId, this.connection!, undefined, - this.onGetTraceContext + this.onGetTraceContext, + { mcpAuthHandler: config.onMcpAuthRequest } ); session.registerTools(config.tools); session.registerCanvases(config.canvases); @@ -1584,6 +1736,9 @@ export class CopilotClient { excludedTools: toolFilterOptions.excludedTools, toolFilterPrecedence: toolFilterOptions.toolFilterPrecedence, enableSessionTelemetry: config.enableSessionTelemetry, + excludedBuiltinAgents: config.excludedBuiltinAgents, + enableCitations: config.enableCitations, + sessionLimits: config.sessionLimits, tools: config.tools?.map((tool) => ({ name: tool.name, description: tool.description, @@ -1591,12 +1746,15 @@ export class CopilotClient { overridesBuiltInTool: tool.overridesBuiltInTool, skipPermission: tool.skipPermission, defer: tool.defer, + metadata: tool.metadata, })), + toolSearch: config.toolSearch, canvases: config.canvases?.map((canvas) => canvas.declaration), requestCanvasRenderer: config.requestCanvasRenderer, requestExtensions: config.requestExtensions, extensionSdkPath: config.extensionSdkPath, extensionInfo: config.extensionInfo, + canvasProvider: config.canvasProvider, commands: config.commands?.map((cmd) => ({ name: cmd.name, description: cmd.description, @@ -1628,6 +1786,9 @@ export class CopilotClient { enableSkills: config.enableSkills, streaming: config.streaming, includeSubAgentStreamingEvents: config.includeSubAgentStreamingEvents ?? true, + ...(this.onGitHubTelemetry != null + ? { enableGitHubTelemetryForwarding: true } + : {}), mcpServers: toWireMcpServers(config.mcpServers), mcpOAuthTokenStorage: config.mcpOAuthTokenStorage, envValueMode: "direct", @@ -1646,6 +1807,7 @@ export class CopilotClient { remoteSession: config.remoteSession, openCanvases: config.openCanvases, expAssignments: config.expAssignments, + enableManagedSettings: config.enableManagedSettings, }); const { workspacePath, capabilities, openCanvases } = response as { @@ -1657,6 +1819,12 @@ export class CopilotClient { session["_workspacePath"] = workspacePath; session.setCapabilities(capabilities); session.setOpenCanvases(openCanvases ?? []); + if (config.onMcpAuthRequest) { + await this.connection!.sendRequest("session.eventLog.registerInterest", { + sessionId, + eventType: "mcp.oauth_required", + }); + } await this.updateSessionOptionsForMode(session, config); } catch (e) { @@ -1803,9 +1971,18 @@ export class CopilotClient { let serverVersion: number | undefined; try { - const result = await raceAgainstExit( - this.internalRpc.connect({ token: this.effectiveConnectionToken }) - ); + const connectParams: { + token?: string; + enableGitHubTelemetryForwarding?: boolean; + } = { token: this.effectiveConnectionToken }; + // Opt in to GitHub telemetry forwarding at the connection level when a + // handler is registered (mirrors the runtime, which reads this flag on the + // `connect` handshake so the first session's un-replayable `session.start` + // event is forwarded). Also sent on session.create/resume for older CLIs. + if (this.onGitHubTelemetry != null) { + connectParams.enableGitHubTelemetryForwarding = true; + } + const result = await raceAgainstExit(this.internalRpc.connect(connectParams)); serverVersion = result.protocolVersion; } catch (err) { if ( @@ -2143,6 +2320,47 @@ export class CopilotClient { }; } + /** + * Builds the environment for the spawned runtime child process (stdio/TCP): applies + * the auth token, connection token, `COPILOT_HOME`, keychain setting, and telemetry + * variables on top of the effective env. Not used by the in-process (FFI) transport, + * whose worker inherits the host process's ambient environment + * (see {@link CopilotClient.startInProcessFfi}). + */ + private buildRuntimeEnv(): Record { + const env: Record = { ...this.resolvedEnv }; + delete env.NODE_DEBUG; + + if (this.options.gitHubToken) { + env.COPILOT_SDK_AUTH_TOKEN = this.options.gitHubToken; + } + if (this.effectiveConnectionToken) { + env.COPILOT_CONNECTION_TOKEN = this.effectiveConnectionToken; + } + if (this.options.baseDirectory) { + env.COPILOT_HOME = this.options.baseDirectory; + } + // In empty mode, disable the system keychain. Keytar reads from a + // process-wide store that's shared across sessions, which is unsafe + // for multi-tenant hosts. The runtime falls back to file-based + // credential storage scoped to COPILOT_HOME. + if (this.options.mode === "empty") { + env.COPILOT_DISABLE_KEYTAR = "1"; + } + if (this.options.telemetry) { + const t = this.options.telemetry; + env.COPILOT_OTEL_ENABLED = "true"; + if (t.otlpEndpoint !== undefined) env.OTEL_EXPORTER_OTLP_ENDPOINT = t.otlpEndpoint; + if (t.otlpProtocol !== undefined) env.OTEL_EXPORTER_OTLP_PROTOCOL = t.otlpProtocol; + if (t.filePath !== undefined) env.COPILOT_OTEL_FILE_EXPORTER_PATH = t.filePath; + if (t.exporterType !== undefined) env.COPILOT_OTEL_EXPORTER_TYPE = t.exporterType; + if (t.sourceName !== undefined) env.COPILOT_OTEL_SOURCE_NAME = t.sourceName; + if (t.captureContent !== undefined) + env.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT = String(t.captureContent); + } + return env; + } + /** * Start the CLI server process */ @@ -2189,30 +2407,9 @@ export class CopilotClient { args.push("--remote"); } - // Suppress debug/trace output that might pollute stdout - const envWithoutNodeDebug = { ...this.resolvedEnv }; - delete envWithoutNodeDebug.NODE_DEBUG; - - // Set auth token in environment if provided - if (this.options.gitHubToken) { - envWithoutNodeDebug.COPILOT_SDK_AUTH_TOKEN = this.options.gitHubToken; - } - - if (this.effectiveConnectionToken) { - envWithoutNodeDebug.COPILOT_CONNECTION_TOKEN = this.effectiveConnectionToken; - } - - if (this.options.baseDirectory) { - envWithoutNodeDebug.COPILOT_HOME = this.options.baseDirectory; - } - - // In empty mode, disable the system keychain. Keytar reads from a - // process-wide store that's shared across sessions, which is unsafe - // for multi-tenant hosts. The runtime falls back to file-based - // credential storage scoped to COPILOT_HOME. - if (this.options.mode === "empty") { - envWithoutNodeDebug.COPILOT_DISABLE_KEYTAR = "1"; - } + // Suppress debug/trace output that might pollute stdout, and apply the + // shared runtime env (auth token, connection token, COPILOT_HOME, telemetry). + const envWithoutNodeDebug = this.buildRuntimeEnv(); if (!this.resolvedCliPath) { throw new Error( @@ -2224,26 +2421,6 @@ export class CopilotClient { ); } - // Set OpenTelemetry environment variables if telemetry is configured - if (this.options.telemetry) { - const t = this.options.telemetry; - envWithoutNodeDebug.COPILOT_OTEL_ENABLED = "true"; - if (t.otlpEndpoint !== undefined) - envWithoutNodeDebug.OTEL_EXPORTER_OTLP_ENDPOINT = t.otlpEndpoint; - if (t.otlpProtocol !== undefined) - envWithoutNodeDebug.OTEL_EXPORTER_OTLP_PROTOCOL = t.otlpProtocol; - if (t.filePath !== undefined) - envWithoutNodeDebug.COPILOT_OTEL_FILE_EXPORTER_PATH = t.filePath; - if (t.exporterType !== undefined) - envWithoutNodeDebug.COPILOT_OTEL_EXPORTER_TYPE = t.exporterType; - if (t.sourceName !== undefined) - envWithoutNodeDebug.COPILOT_OTEL_SOURCE_NAME = t.sourceName; - if (t.captureContent !== undefined) - envWithoutNodeDebug.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT = String( - t.captureContent - ); - } - // Verify CLI exists before attempting to spawn if (!existsSync(this.resolvedCliPath)) { throw new Error( @@ -2380,12 +2557,120 @@ export class CopilotClient { return this.connectToParentProcessViaStdio(); case "stdio": return this.connectToChildProcessViaStdio(); + case "inprocess": + return this.connectViaFfi(); case "tcp": case "uri": return this.connectViaTcp(); } } + /** Starts the in-process FFI runtime with SDK-managed typed options. */ + private async startInProcessFfi(): Promise { + const entrypoint = this.resolveCliPathForFfi(); + // Load the FFI host lazily so the native `koffi` addon (and its + // platform-specific `koffi.node`) is only loaded on the in-process path; + // out-of-process (stdio/tcp) consumers never touch the native dependency. + // The transpiled output is per-file (not bundled), so this resolves the + // sibling module at runtime in both the ESM and CJS builds. + const { FfiRuntimeHost } = await import("./ffiRuntimeHost.js"); + const environment: Record = {}; + if (this.options.gitHubToken) { + environment.COPILOT_SDK_AUTH_TOKEN = this.options.gitHubToken; + } + if (this.options.baseDirectory) { + environment.COPILOT_HOME = this.options.baseDirectory; + } + if (this.options.mode === "empty") { + environment.COPILOT_DISABLE_KEYTAR = "1"; + } + + const args: string[] = []; + if (this.options.logLevel) { + args.push("--log-level", this.options.logLevel); + } + if (this.options.gitHubToken) { + args.push("--auth-token-env", "COPILOT_SDK_AUTH_TOKEN"); + } + if (!this.options.useLoggedInUser) { + args.push("--no-auto-login"); + } + if (this.options.sessionIdleTimeoutSeconds > 0) { + args.push("--session-idle-timeout", this.options.sessionIdleTimeoutSeconds.toString()); + } + if (this.options.enableRemoteSessions) { + args.push("--remote"); + } + + const host = FfiRuntimeHost.create( + entrypoint, + CopilotClient.getNapiPrebuildsFolder(entrypoint), + environment, + args + ); + this.ffiHost = host; + await host.start(); + } + + /** + * Connect to the in-process FFI runtime host over its receive/send streams, + * reusing the same `vscode-jsonrpc` framing as the stdio transport. + */ + private async connectViaFfi(): Promise { + if (!this.ffiHost) { + throw new Error("In-process FFI runtime host not started"); + } + this.messageWriter = new TeardownResilientStreamMessageWriter(this.ffiHost.sendStream); + this.connection = createMessageConnection( + new StreamMessageReader(this.ffiHost.receiveStream), + this.messageWriter + ); + + this.attachConnectionHandlers(); + this.connection.listen(); + } + + /** + * Resolves the CLI entrypoint used for in-process FFI hosting: `COPILOT_CLI_PATH` + * when set, otherwise the bundled platform-package entrypoint. + */ + private resolveCliPathForFfi(): string { + return this.resolvedEnv.COPILOT_CLI_PATH ?? getBundledCliPath(); + } + + /** + * Returns the napi prebuilds folder name for the current host — the + * `-` convention (e.g. `win32-x64`, `darwin-arm64`, + * `linux-x64`, `linuxmusl-x64`) under which the runtime ships + * `prebuilds//runtime.node`. + */ + private static getNapiPrebuildsFolder(entrypoint: string): string { + const arch = process.arch; + if (arch !== "x64" && arch !== "arm64") { + throw new Error(`Unsupported architecture '${arch}' for in-process FFI hosting.`); + } + let platform: string = process.platform; + if (platform === "linux" && CopilotClient.isMusl(entrypoint)) { + platform = "linuxmusl"; + } + return `${platform}-${arch}`; + } + + private static isMusl(entrypoint: string): boolean { + if (entrypoint.includes(`copilot-linuxmusl-${process.arch}`)) { + return true; + } + if (entrypoint.includes(`copilot-linux-${process.arch}`)) { + return false; + } + const report = process.report?.getReport(); + const header = + report && "header" in report + ? (report.header as { glibcVersionRuntime?: string }) + : undefined; + return header !== undefined && header.glibcVersionRuntime === undefined; + } + /** * Connect to child via stdio pipes */ @@ -2516,15 +2801,6 @@ export class CopilotClient { await this.handleAutoModeSwitchRequest(params) ); - this.connection.onRequest( - "hooks.invoke", - async (params: { - sessionId: string; - hookType: string; - input: unknown; - }): Promise<{ output?: unknown }> => await this.handleHooksInvoke(params) - ); - this.connection.onRequest( "systemMessage.transform", async (params: { @@ -2545,7 +2821,7 @@ export class CopilotClient { // Register client *global* API handlers (e.g. LLM inference) on the // same connection. These methods carry no implicit sessionId dispatch // — the runtime calls into a single handler for the whole connection. - registerClientGlobalApiHandlers(this.connection, this.llmInferenceHandlers); + registerClientGlobalApiHandlers(this.connection, this.clientGlobalHandlers); this.connection.onClose(() => { this.state = "disconnected"; @@ -2568,8 +2844,9 @@ export class CopilotClient { } const session = this.sessions.get((notification as { sessionId: string }).sessionId); + const event = (notification as { event: SessionEvent }).event; if (session) { - session._dispatchEvent((notification as { event: SessionEvent }).event); + session._dispatchEvent(event); } } diff --git a/nodejs/src/copilotRequestHandler.ts b/nodejs/src/copilotRequestHandler.ts index a949cecfd9..ccfe6591c6 100644 --- a/nodejs/src/copilotRequestHandler.ts +++ b/nodejs/src/copilotRequestHandler.ts @@ -33,6 +33,9 @@ type InternalContext = CopilotRequestContext & { [kBridge]: CopilotWebSocketResp export interface CopilotRequestContext { readonly requestId: string; readonly sessionId?: string; + readonly agentId?: string; + readonly parentAgentId?: string; + readonly interactionType?: string; readonly transport: "http" | "websocket"; url: string; headers: LlmInferenceHeaders; @@ -249,6 +252,9 @@ export class CopilotRequestHandler { const ctx: InternalContext = { requestId: exchange.requestId, sessionId: exchange.sessionId, + agentId: exchange.agentId, + parentAgentId: exchange.parentAgentId, + interactionType: exchange.interactionType, transport: exchange.transport, url: exchange.url, headers: exchange.headers, @@ -456,6 +462,9 @@ interface BodyQueueItem { class CopilotRequestExchange { readonly requestId: string; sessionId?: string; + agentId?: string; + parentAgentId?: string; + interactionType?: string; method = "GET"; url = ""; headers: LlmInferenceHeaders = {}; @@ -478,6 +487,9 @@ class CopilotRequestExchange { /** Fill in the request context once the matching start frame arrives. */ setContext(params: LlmInferenceHttpRequestStartRequest): void { this.sessionId = params.sessionId; + this.agentId = params.agentId; + this.parentAgentId = params.parentAgentId; + this.interactionType = params.interactionType; this.method = params.method; this.url = params.url; this.headers = params.headers; diff --git a/nodejs/src/ffiRuntimeHost.ts b/nodejs/src/ffiRuntimeHost.ts new file mode 100644 index 0000000000..a92aa1589a --- /dev/null +++ b/nodejs/src/ffiRuntimeHost.ts @@ -0,0 +1,341 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +/** + * Hosts the Copilot runtime in-process by loading the native `runtime.node` cdylib + * and speaking JSON-RPC over its C ABI (FFI) instead of spawning a CLI child process + * and communicating over stdio/TCP. + * + * The native `host_start` export spawns the CLI worker itself + * (`node --embedded-host` for a `.js` entrypoint, or ` + * --embedded-host` for a packaged binary), so the SDK never launches the worker + * directly. LSP `Content-Length:`-framed JSON-RPC bytes are pumped across the ABI: + * writes go to `connection_write`; inbound frames arrive on a native callback that + * feeds {@link FfiRuntimeHost.receiveStream}. The existing `vscode-jsonrpc` + * `StreamMessageReader`/`StreamMessageWriter` handle framing unchanged — this is a + * transport swap, not a new protocol. + */ + +import { existsSync } from "node:fs"; +import koffi from "koffi"; +import { dirname, join, resolve } from "node:path"; +import { PassThrough, Writable } from "node:stream"; + +const SYMBOL_PREFIX = "copilot_runtime_"; + +// A long, referenced no-op timer keeps the Node event loop alive while the in-process +// connection is open (see start()); the exact interval is irrelevant. +const KEEP_ALIVE_INTERVAL_MS = 1 << 30; + +type KoffiFunction = ReturnType["func"]>; +type KoffiType = ReturnType; +type KoffiRegisteredCallback = ReturnType; + +interface FfiLibrary { + hostStart: KoffiFunction; + hostShutdown: KoffiFunction; + connectionOpen: KoffiFunction; + connectionWrite: KoffiFunction; + connectionClose: KoffiFunction; + outboundCallbackType: KoffiType; +} + +let loadedLibraryPath: string | undefined; +let loadedLibrary: FfiLibrary | undefined; + +/** + * Loads the cdylib once per process and binds the C ABI exports. Loading a + * different library path in the same process is unsupported. + */ +function loadLibrary(libraryPath: string): FfiLibrary { + if (loadedLibrary) { + if (loadedLibraryPath !== libraryPath) { + throw new Error( + `An in-process FFI runtime library is already loaded from '${loadedLibraryPath}'; ` + + `loading a different library from '${libraryPath}' in the same process is not supported.` + ); + } + return loadedLibrary; + } + + const lib = koffi.load(libraryPath); + const outboundCallbackType = koffi.pointer( + koffi.proto( + `void ${SYMBOL_PREFIX}outbound(void *userData, uint8 *bytesPtr, size_t bytesLen)` + ) + ); + + loadedLibrary = { + hostStart: lib.func(`${SYMBOL_PREFIX}host_start`, "uint32", [ + "uint8*", + "size_t", + "uint8*", + "size_t", + ]), + hostShutdown: lib.func(`${SYMBOL_PREFIX}host_shutdown`, "bool", ["uint32"]), + connectionOpen: lib.func(`${SYMBOL_PREFIX}connection_open`, "uint32", [ + "uint32", + outboundCallbackType, + "void*", + "uint8*", + "size_t", + "uint8*", + "size_t", + "uint8*", + "size_t", + ]), + connectionWrite: lib.func(`${SYMBOL_PREFIX}connection_write`, "bool", [ + "uint32", + "uint8*", + "size_t", + ]), + connectionClose: lib.func(`${SYMBOL_PREFIX}connection_close`, "bool", ["uint32"]), + outboundCallbackType, + }; + loadedLibraryPath = libraryPath; + return loadedLibrary; +} + +function buildArgvJson(cliEntrypoint: string, args: readonly string[]): Buffer { + // A `.js` entrypoint is launched via node; the packaged single-file CLI binary + // embeds its own Node and is invoked directly. `--no-auto-update` pins the worker + // to the bundled pkg matching the loaded cdylib, instead of drifting to a newer + // version installed under the user's `~/.copilot/pkg` (which would cause ABI skew). + const argv = cliEntrypoint.toLowerCase().endsWith(".js") + ? ["node", cliEntrypoint, "--embedded-host", "--no-auto-update"] + : [cliEntrypoint, "--embedded-host", "--no-auto-update"]; + argv.push(...args); + return Buffer.from(JSON.stringify(argv), "utf8"); +} + +function buildEnvJson(environment?: Record): Buffer | null { + if (!environment) { + return null; + } + const obj: Record = {}; + for (const [key, value] of Object.entries(environment)) { + if (value !== undefined) { + obj[key] = value; + } + } + if (Object.keys(obj).length === 0) { + return null; + } + return Buffer.from(JSON.stringify(obj), "utf8"); +} + +export class FfiRuntimeHost { + private readonly lib: FfiLibrary; + private serverId = 0; + private connectionId = 0; + private disposed = false; + private outboundCallback: KoffiRegisteredCallback | undefined; + private keepAliveTimer: ReturnType | undefined; + + /** The stream JSON-RPC reads server→client frames from. */ + readonly receiveStream: PassThrough; + /** The stream JSON-RPC writes client→server frames to. */ + readonly sendStream: Writable; + + private constructor( + private readonly libraryPath: string, + private readonly cliEntrypoint: string, + private readonly environment: Record | undefined, + private readonly args: readonly string[] + ) { + this.lib = loadLibrary(libraryPath); + this.receiveStream = new PassThrough(); + this.sendStream = new Writable({ + // connection_write enqueues the frame into the runtime's inbound channel and + // returns immediately, so a synchronous FFI call is sufficient here. + write: (chunk: Buffer, _encoding, callback) => { + try { + this.writeFrame(chunk); + callback(); + } catch (error) { + callback(error as Error); + } + }, + }); + } + + /** + * Resolves the cdylib next to the given CLI entrypoint and prepares the FFI host. + * The cdylib is resolved as `prebuilds//runtime.node` relative to + * the entrypoint directory (the napi-rs `-` layout, e.g. + * `linux-x64`). Throws if it cannot be found. + */ + static create( + cliEntrypoint: string, + prebuildsFolder: string, + environment: Record | undefined, + args: readonly string[] + ): FfiRuntimeHost { + const fullEntrypoint = resolve(cliEntrypoint); + const distDir = dirname(fullEntrypoint); + const libraryPath = join(distDir, "prebuilds", prebuildsFolder, "runtime.node"); + if (!existsSync(libraryPath)) { + throw new Error(`FFI runtime library not found. Looked for '${libraryPath}'.`); + } + return new FfiRuntimeHost(libraryPath, fullEntrypoint, environment, args); + } + + /** + * Starts the in-process runtime: spawns the CLI worker via the native host, + * waits for readiness, and opens the FFI JSON-RPC connection. + */ + async start(): Promise { + const argvJson = buildArgvJson(this.cliEntrypoint, this.args); + const envJson = buildEnvJson(this.environment); + + // The native host spawns the CLI worker itself and has no cwd parameter, so the + // worker inherits this process's cwd. A custom working directory is intentionally + // unsupported for the in-process transport (rejected by the client constructor) + // rather than mutating the shared process-global cwd here. + + // host_start blocks until the worker connects back and signals readiness + // (up to ~30s); run it as an async FFI call so the Node event loop isn't blocked. + this.serverId = await new Promise((resolvePromise, rejectPromise) => { + this.lib.hostStart.async( + argvJson, + argvJson.length, + envJson, + envJson ? envJson.length : 0, + (error: Error | null, result: number) => { + if (error) { + rejectPromise(error); + } else { + resolvePromise(result); + } + } + ); + }); + if (!this.serverId) { + throw new Error( + `copilot_runtime_host_start failed (library '${this.libraryPath}', entrypoint '${this.cliEntrypoint}').` + ); + } + + this.outboundCallback = koffi.register( + (_userData: unknown, bytesPtr: unknown, bytesLen: number | bigint) => + this.feedInbound(bytesPtr, bytesLen), + this.lib.outboundCallbackType + ); + + this.connectionId = this.lib.connectionOpen( + this.serverId, + this.outboundCallback, + null, + null, + 0, + null, + 0, + null, + 0 + ); + if (!this.connectionId) { + this.unregisterCallback(); + this.lib.hostShutdown(this.serverId); + this.serverId = 0; + throw new Error("copilot_runtime_connection_open failed."); + } + + // The in-process transport has no socket/pipe handle to keep the Node event loop + // alive while the SDK is idle awaiting a server→client frame. koffi delivers the + // outbound callback on the loop but does not reference it, so hold one referenced + // timer for the lifetime of the connection. + this.keepAliveTimer = setInterval(() => {}, KEEP_ALIVE_INTERVAL_MS); + } + + private writeFrame(frame: Buffer): void { + if (this.disposed || !this.connectionId) { + throw new Error("The in-process runtime connection is closed."); + } + const ok = this.lib.connectionWrite(this.connectionId, frame, frame.length); + if (!ok) { + throw new Error("Failed to write a frame to the in-process runtime connection."); + } + } + + /** + * Native outbound (server→client) callback. koffi delivers it on the JS event loop + * via a threadsafe function, so the frame is decoded and written straight to + * {@link receiveStream}. The native pointer is only valid for this call, so the + * bytes are copied out before returning. + */ + private feedInbound(bytesPtr: unknown, bytesLen: number | bigint): void { + // An exception thrown across the native→JS (Node-API) boundary cannot propagate + // and would surface only as a DEP0168 "uncaught Node-API callback exception" + // warning, so catch and log it here instead of letting it escape. + try { + // A native outbound callback can still be delivered on the event loop after + // dispose() has ended receiveStream; writing then would throw + // ERR_STREAM_WRITE_AFTER_END. Drop late frames instead — the connection is + // gone and nothing is reading them. + if (this.disposed || this.receiveStream.writableEnded) { + return; + } + const length = Number(bytesLen); + if (!bytesPtr || length <= 0) { + return; + } + const bytes = koffi.decode( + bytesPtr, + koffi.array("uint8", length, "Typed") + ) as Uint8Array; + this.receiveStream.write(Buffer.from(bytes)); + } catch (error) { + console.error( + `In-process FFI inbound callback failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}` + ); + } + } + + private unregisterCallback(): void { + if (this.outboundCallback === undefined) { + return; + } + const callback = this.outboundCallback; + this.outboundCallback = undefined; + try { + koffi.unregister(callback); + } catch { + // Ignore teardown failures. + } + } + + /** Closes the FFI connection, shuts down the native host, and releases resources. */ + dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + + if (this.keepAliveTimer !== undefined) { + clearInterval(this.keepAliveTimer); + this.keepAliveTimer = undefined; + } + + try { + if (this.connectionId) { + this.lib.connectionClose(this.connectionId); + this.connectionId = 0; + } + } catch { + // Ignore teardown failures. + } + + try { + if (this.serverId) { + this.lib.hostShutdown(this.serverId); + this.serverId = 0; + } + } catch { + // Ignore teardown failures. + } + + this.receiveStream.end(); + this.unregisterCallback(); + } +} diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index 38f77412d9..255a769d55 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -5,7 +5,7 @@ import type { MessageConnection } from "vscode-jsonrpc/node.js"; -import type { AbortReason, Attachment, ContextTier, EmbeddedBlobResourceContents, EmbeddedTextResourceContents, McpServerSource, McpServerStatus, PermissionPromptRequest, PermissionRule, ReasoningSummary, SessionEvent, SessionMode, ShutdownType, SkillSource, UserToolSessionApproval } from "./session-events.js"; +import type { AbortReason, Attachment, ContextTier, EmbeddedBlobResourceContents, EmbeddedTextResourceContents, McpServerSource, McpServerStatus, PermissionPromptRequest, PermissionRule, ReasoningSummary, SessionEvent, SessionLimitsConfig, SessionMode, ShutdownType, SkillSource, UserToolSessionApproval, Verbosity } from "./session-events.js"; /** * Initial authentication info for the session. @@ -13,6 +13,7 @@ import type { AbortReason, Attachment, ContextTier, EmbeddedBlobResourceContents * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AuthInfo". */ +/** @experimental */ export type AuthInfo = | HMACAuthInfo | EnvAuthInfo @@ -21,6 +22,20 @@ export type AuthInfo = | UserAuthInfo | GhCliAuthInfo | ApiKeyAuthInfo; +/** + * Resolved Anthropic adaptive-thinking capability for a model. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AdaptiveThinkingSupport". + */ +/** @experimental */ +export type AdaptiveThinkingSupport = + /** The model does not accept thinking.type='adaptive' */ + | "unsupported" + /** The model accepts adaptive thinking but also accepts thinking.type='enabled' */ + | "optional" + /** The model only accepts adaptive thinking and rejects thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8) */ + | "required"; /** * Which tier this directory belongs to * @@ -187,6 +202,20 @@ export type AgentRegistrySpawnValidationErrorField = | "model" /** The permissionMode parameter */ | "permissionMode"; +/** + * Current or requested allow-all mode. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PermissionsAllowAllMode". + */ +/** @experimental */ +export type PermissionsAllowAllMode = + /** Permission requests follow the normal approval flow. */ + | "off" + /** Tool, path, and URL permission requests are automatically approved. */ + | "on" + /** Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. */ + | "auto"; /** * Authentication type * @@ -257,6 +286,7 @@ export type ConnectedRemoteSessionMetadataKind = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ContentFilterMode". */ +/** @experimental */ export type ContentFilterMode = /** Leave MCP tool result content unchanged. */ | "none" @@ -264,12 +294,91 @@ export type ContentFilterMode = | "markdown" /** Remove characters that can hide directives. */ | "hidden_characters"; +/** + * Source category for a collected debug bundle entry. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsSource". + */ +/** @experimental */ +export type DebugCollectLogsSource = + /** Session event log. */ + | "events" + /** Process log for the session. */ + | "process-log" + /** Interactive shell log for the session. */ + | "shell-log" + /** Caller-provided diagnostic entry. */ + | "additional"; +/** + * Destination for the redacted debug bundle. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsDestination". + */ +/** @experimental */ +export type DebugCollectLogsDestination = + | { + /** + * Absolute or server-relative path for the .tgz archive to create. + */ + outputPath: string; + /** + * When true, create the archive atomically without overwriting an existing file by appending ` (N)` before the extension as needed. Defaults to false. + */ + noOverwrite?: boolean; + kind: "archive"; + } + | { + /** + * Directory where redacted files should be staged. The directory is created if needed. + */ + outputDirectory: string; + kind: "directory"; + }; +/** + * Kind of caller-provided debug log entry. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsEntryKind". + */ +/** @experimental */ +export type DebugCollectLogsEntryKind = + /** Include a single server-local file. */ + | "file" + /** Include files from a server-local directory recursively. */ + | "directory"; +/** + * How a collected debug entry should be redacted before being staged. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsRedaction". + */ +/** @experimental */ +export type DebugCollectLogsRedaction = + /** Redact the file as plain UTF-8 log text. */ + | "plain-text" + /** Redact each non-empty line as a session event JSON object, falling back to plain-text redaction for malformed lines. */ + | "events-jsonl"; +/** + * Destination kind that was written. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsResultKind". + */ +/** @experimental */ +export type DebugCollectLogsResultKind = + /** A .tgz archive was written. */ + | "archive" + /** A directory containing redacted files was written. */ + | "directory"; /** * Server transport type: stdio, http, sse (deprecated), or memory * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "DiscoveredMcpServerType". */ +/** @experimental */ export type DiscoveredMcpServerType = /** Server communicates over stdio with a local child process. */ | "stdio" @@ -373,6 +482,7 @@ export type ExternalToolTextResultForLlmBinaryResultsForLlmType = export type ExternalToolTextResultForLlmContent = | ExternalToolTextResultForLlmContentText | ExternalToolTextResultForLlmContentTerminal + | ExternalToolTextResultForLlmContentShellExit | ExternalToolTextResultForLlmContentImage | ExternalToolTextResultForLlmContentAudio | ExternalToolTextResultForLlmContentResourceLink @@ -405,11 +515,53 @@ export type ExternalToolTextResultForLlmContentResourceDetails = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "FilterMapping". */ +/** @experimental */ export type FilterMapping = | { [k: string]: ContentFilterMode; } | ContentFilterMode; +/** + * Hook event name dispatched through the SDK callback transport. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HookType". + */ +/** @experimental */ +/** @internal */ +export type HookType = + /** Runs before a tool is invoked. */ + | "preToolUse" + /** Runs before an MCP tool is invoked. */ + | "preMcpToolCall" + /** Runs after a tool completes successfully. */ + | "postToolUse" + /** Runs after a tool fails. */ + | "postToolUseFailure" + /** Runs after the user submits a prompt. */ + | "userPromptSubmitted" + /** Runs when a session starts. */ + | "sessionStart" + /** Runs when a session ends. */ + | "sessionEnd" + /** Runs after an agent result is produced. */ + | "postResult" + /** Runs before a pull request description is generated. */ + | "prePRDescription" + /** Runs when the agent encounters an error. */ + | "errorOccurred" + /** Runs when the agent stops. */ + | "agentStop" + /** Runs when a subagent starts. */ + | "subagentStart" + /** Runs when a subagent stops. */ + | "subagentStop" + /** Runs before conversation context is compacted. */ + | "preCompact" + /** Runs when the agent requests permission. */ + | "permissionRequest" + /** Runs when the agent emits a notification. */ + | "notification"; /** * Source for direct repo installs (when marketplace is empty) * @@ -640,6 +792,7 @@ export type McpAppsSetHostContextDetailsPlatform = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfig". */ +/** @experimental */ export type McpServerConfig = McpServerConfigStdio | McpServerConfigHttp; /** * Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. @@ -647,6 +800,7 @@ export type McpServerConfig = McpServerConfigStdio | McpServerConfigHttp; * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerAuthConfig". */ +/** @experimental */ export type McpServerAuthConfig = boolean | McpServerAuthConfigRedirectPort; /** * Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) @@ -654,6 +808,7 @@ export type McpServerAuthConfig = boolean | McpServerAuthConfigRedirectPort; * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfigDeferTools". */ +/** @experimental */ export type McpServerConfigDeferTools = /** Tools may be deferred under certain conditions */ | "auto" @@ -665,6 +820,7 @@ export type McpServerConfigDeferTools = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfigHttpType". */ +/** @experimental */ export type McpServerConfigHttpType = /** Streamable HTTP transport. */ | "http" @@ -676,11 +832,44 @@ export type McpServerConfigHttpType = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfigHttpOauthGrantType". */ +/** @experimental */ export type McpServerConfigHttpOauthGrantType = /** Interactive browser-based authorization code flow with PKCE. */ | "authorization_code" /** Headless client credentials flow using the configured OAuth client. */ | "client_credentials"; +/** + * Host response: supply dynamic headers or decline this refresh. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpHeadersHandlePendingHeadersRefreshRequest". + */ +/** @experimental */ +export type McpHeadersHandlePendingHeadersRefreshRequest = + | { + /** + * Headers to overlay onto the MCP request. Dynamic headers override static config headers but do not replace SDK-managed request headers. + */ + headers: { + [k: string]: string | undefined; + }; + kind: "headers"; + } + | { + kind: "none"; + }; +/** + * Consumer allowed to call an MCP tool. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpToolUiVisibility". + */ +/** @experimental */ +export type McpToolUiVisibility = + /** The model may call the tool. */ + | "model" + /** An MCP App view may call the tool. */ + | "app"; /** * Host response to the pending OAuth request. * @@ -698,10 +887,6 @@ export type McpOauthPendingRequestResponse = * OAuth token type. Defaults to Bearer when omitted. */ tokenType?: string; - /** - * Refresh token supplied by the host, if available. - */ - refreshToken?: string; /** * Token lifetime in seconds, if known. */ @@ -749,6 +934,59 @@ export type McpSetEnvValueModeDetails = | "direct" /** Treat MCP server environment values as host-side references to resolve before launch. */ | "indirect"; +/** + * Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionContextAttribution". + */ +/** @experimental */ +export type SessionContextAttribution = { + /** + * Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + */ + totalTokens: number; + /** + * Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + */ + entries: { + /** + * Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + */ + kind: string; + /** + * Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + */ + id: string; + /** + * Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + */ + label: string; + /** + * Token count currently in context attributable to this entry. + */ + tokens: number; + /** + * Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + */ + parentId?: string; + /** + * Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + */ + attributes?: { + [k: string]: string | undefined; + }; + }[]; + /** + * Successful compaction history for the session. + */ + compactions: { + /** + * Number of successful compactions in this session. + */ + count: number; + }; +} | null; /** * Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). * @@ -842,6 +1080,7 @@ export type MetadataSnapshotRemoteMetadataTaskType = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelPolicyState". */ +/** @experimental */ export type ModelPolicyState = /** The model is enabled by policy. */ | "enabled" @@ -855,6 +1094,7 @@ export type ModelPolicyState = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelPickerCategory". */ +/** @experimental */ export type ModelPickerCategory = /** Lightweight model category optimized for faster, lower-cost interactions. */ | "lightweight" @@ -868,6 +1108,7 @@ export type ModelPickerCategory = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelPickerPriceCategory". */ +/** @experimental */ export type ModelPickerPriceCategory = /** Lowest relative token cost tier. */ | "low" @@ -1158,7 +1399,7 @@ export type ProviderEndpointTransport = /** WebSocket transport. */ | "websockets"; /** - * Schema for the `PushAttachment` type. + * Attachment union accepted by push input, covering files, directories, GitHub objects, blobs, snippets, and extension context. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PushAttachment". @@ -1169,6 +1410,15 @@ export type PushAttachment = | PushAttachmentDirectory | PushAttachmentSelection | PushAttachmentGitHubReference + | PushAttachmentGitHubCommit + | PushAttachmentGitHubRelease + | PushAttachmentGitHubActionsJob + | PushAttachmentGitHubRepository + | PushAttachmentGitHubFileDiff + | PushAttachmentGitHubTreeComparison + | PushAttachmentGitHubUrl + | PushAttachmentGitHubFile + | PushAttachmentGitHubSnippet | PushAttachmentBlob | ExtensionContextPushInput; /** @@ -1323,6 +1573,7 @@ export type SessionFsReaddirWithTypesEntryType = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionFsSetProviderConventions". */ +/** @experimental */ export type SessionFsSetProviderConventions = /** Paths use Windows path conventions. */ | "windows" @@ -1535,6 +1786,52 @@ export type SessionsOpenProgressStatus = | "in-progress" /** The step has completed successfully. */ | "complete"; +/** + * Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names are intentionally not part of the contract. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsPredicateName". + */ +/** @experimental */ +export type SessionSettingsPredicateName = + /** Whether the security-tools feature flag enables security tool wiring. */ + | "securityToolsEnabled" + /** Whether third-party security tools should receive the security prompt. */ + | "thirdPartySecurityPromptEnabled" + /** Whether validation may run in parallel. */ + | "parallelValidationEnabled" + /** Whether runtime timing telemetry is enabled. */ + | "runtimeTimingTelemetryEnabled" + /** Whether the co-author hook is enabled. */ + | "coAuthorHookEnabled" + /** Whether Chronicle integration is enabled. */ + | "chronicleEnabled" + /** Whether content-exclusion policy may self-fetch data. */ + | "contentExclusionSelfFetchEnabled" + /** Whether Claude Opus token-limit caps should be applied. */ + | "capClaudeOpusTokenLimitsEnabled" + /** Whether code-review behavior is enabled. */ + | "codeReviewFeatureEnabled" + /** Whether CCA should use the TypeScript autofind behavior. */ + | "ccaUseTsAutofindEnabled" + /** Whether the dependency checker is enabled. */ + | "dependencyCheckerEnabled" + /** Whether the Dependabot checker is enabled. */ + | "dependabotCheckerEnabled" + /** Whether the CodeQL checker is enabled. */ + | "codeqlCheckerEnabled" + /** Whether trivial-change handling is enabled. */ + | "trivialChangeEnabled" + /** Whether trivial-change skip behavior is enabled. */ + | "trivialChangeSkipEnabled" + /** Whether trivial-change handling is enabled for code review. */ + | "trivialChangeEnabledForCodeReview" + /** Whether trivial-change skip behavior is enabled for code review. */ + | "trivialChangeSkipEnabledForCodeReview" + /** Whether trivial-change handling is enabled for a specific tool. */ + | "trivialChangeEnabledForTool" + /** Whether trivial-change skip behavior is enabled for a specific tool. */ + | "trivialChangeSkipEnabledForTool"; /** * Which session sources to include. Defaults to `local` for backward compatibility. * @@ -1549,6 +1846,18 @@ export type SessionSource = | "remote" /** Return both local and remote sessions. */ | "all"; +/** + * Sharing status for a synced session. "repo" makes the session visible to anyone with read access to the repository; "unshared" restricts it to the creator and collaborators. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionVisibilityStatus". + */ +/** @experimental */ +export type SessionVisibilityStatus = + /** The session is visible to repository readers. */ + | "repo" + /** The session is restricted to its creator and collaborators. */ + | "unshared"; /** * Signal to send (default: SIGTERM) * @@ -1580,7 +1889,7 @@ export type SkillDiscoveryScope = /** A configured custom skill directory. */ | "custom"; /** - * Result of invoking the slash command (text output, prompt to send to the agent, or completion). + * Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SlashCommandInvocationResult". @@ -1609,6 +1918,14 @@ export type SubagentSettings = { * Names of subagents the user has turned off; they cannot be dispatched */ disabledSubagents?: string[]; + /** + * Maximum number of subagents that can run concurrently; applies to usage-based billing users only + */ + maxConcurrency?: number; + /** + * Maximum subagent nesting depth; applies to usage-based billing users only + */ + maxDepth?: number; } | null; /** * Context tier override for matching subagents @@ -1655,7 +1972,7 @@ export type TaskExecutionMode = /** The task is managed in the background. */ | "background"; /** - * Schema for the `TaskInfo` type. + * Tracked task union returned by task APIs, containing either an agent task or a shell task. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "TaskInfo". @@ -1697,7 +2014,7 @@ export type UIAutoModeSwitchResponse = /** Decline the automatic mode switch. */ | "no"; /** - * Schema for the `UIElicitationFieldValue` type. + * Submitted UI elicitation field value: string, number, boolean, or an array of strings. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UIElicitationFieldValue". @@ -1780,6 +2097,22 @@ export type UIExitPlanModeAction = | "autopilot" /** Exit plan mode and continue in autopilot mode with parallel subagent execution. */ | "autopilot_fleet"; +/** + * User action selected for an exhausted session limit. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UISessionLimitsExhaustedResponseAction". + */ +/** @experimental */ +export type UISessionLimitsExhaustedResponseAction = + /** Increase the current max by an exact AI Credits amount. */ + | "add" + /** Set a new absolute max AI Credits value. */ + | "set" + /** Remove the current session limit. */ + | "unset" + /** Leave the limit unchanged and cancel the blocked model request. */ + | "cancel"; /** * Type of change represented by this file diff. * @@ -1828,6 +2161,7 @@ export type WorkspacesWorkspaceDetailsHostType = * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountGetAllUsersResult". */ +/** @experimental */ export type AccountGetAllUsersResult = AccountAllUsers[]; /** @@ -1858,11 +2192,12 @@ export interface AbortResult { error?: string; } /** - * Schema for the `AccountAllUsers` type. + * Authenticated account entry returned by `account.getAllUsers`, with auth info and an optional associated token. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountAllUsers". */ +/** @experimental */ export interface AccountAllUsers { authInfo: AuthInfo; /** @@ -1871,11 +2206,12 @@ export interface AccountAllUsers { token?: string; } /** - * Schema for the `HMACAuthInfo` type. + * Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub host and HMAC secret. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "HMACAuthInfo". */ +/** @experimental */ export interface HMACAuthInfo { /** * HMAC-based authentication used by GitHub-internal services. @@ -1897,10 +2233,23 @@ export interface HMACAuthInfo { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "CopilotUserResponse". */ +/** @experimental */ export interface CopilotUserResponse { + /** + * GitHub login of the authenticated user. + */ login?: string; + /** + * Copilot access SKU identifier (e.g. `free_limited_copilot`, `copilot_for_business_seat_quota`) used to gate model and feature access. + */ access_type_sku?: string; + /** + * Opaque analytics tracking identifier for the user, forwarded from the Copilot API. + */ analytics_tracking_id?: string; + /** + * Date the Copilot seat was assigned to the user, if applicable. + */ assigned_date?: | ( | { @@ -1909,12 +2258,30 @@ export interface CopilotUserResponse { | string ) | null; + /** + * Whether the user is eligible to sign up for the free/limited Copilot tier. + */ can_signup_for_limited?: boolean; + /** + * Whether Copilot chat is enabled for the user. + */ chat_enabled?: boolean; + /** + * Copilot plan name for the user (e.g. `individual`, `business`, `enterprise`). + */ copilot_plan?: string; + /** + * Whether `.copilotignore` content-exclusion support is enabled for the user. + */ copilotignore_enabled?: boolean; endpoints?: CopilotUserResponseEndpoints; + /** + * Logins of the organizations the user belongs to. + */ organization_login_list?: string[]; + /** + * Organizations the user belongs to, each with an optional login and display name. + */ organization_list?: | ( | { @@ -1940,7 +2307,13 @@ export interface CopilotUserResponse { } | null)[] ) | null; + /** + * Whether the Codex agent is enabled for the user. + */ codex_agent_enabled?: boolean; + /** + * Whether MCP (Model Context Protocol) support is enabled for the user. + */ is_mcp_enabled?: | ( | { @@ -1949,29 +2322,67 @@ export interface CopilotUserResponse { | boolean ) | null; + /** + * Date the user's usage quota next resets, as a raw string from the Copilot API; see `quota_reset_date_utc` for the UTC-normalized value. + */ quota_reset_date?: string; quota_snapshots?: CopilotUserResponseQuotaSnapshots; + /** + * Whether the user's telemetry is subject to restricted-data handling. + */ restricted_telemetry?: boolean; + /** + * Whether the user is a GitHub/Microsoft staff member. + */ is_staff?: boolean; + /** + * Raw passthrough of the Copilot API `te` flag for the user (an opaque server-side eligibility signal surfaced in telemetry); not otherwise interpreted by the runtime. + */ + te?: boolean; + /** + * Whether the account is on usage-based (token/AI-credit) billing rather than a fixed premium-request quota. + */ token_based_billing?: boolean; + /** + * Whether the user is able to upgrade their Copilot plan. + */ can_upgrade_plan?: boolean; + /** + * UTC-normalized form of `quota_reset_date` (the date the user's usage quota next resets). + */ quota_reset_date_utc?: string; + /** + * Per-category quota allotments for free/limited-tier users, keyed by quota category. + */ limited_user_quotas?: { [k: string]: number | undefined; }; + /** + * Date the free/limited-tier user's quotas next reset, as a raw string from the Copilot API. + */ limited_user_reset_date?: string; + /** + * Per-category monthly quota allotments, keyed by quota category. + */ monthly_quotas?: { [k: string]: number | undefined; }; + /** + * Whether cloud session storage is enabled for the user. + */ cloud_session_storage_enabled?: boolean; + /** + * Whether CLI remote control is enabled for the user. + */ cli_remote_control_enabled?: boolean; } /** - * Schema for the `CopilotUserResponseEndpoints` type. + * Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "CopilotUserResponseEndpoints". */ +/** @experimental */ export interface CopilotUserResponseEndpoints { api?: string; "origin-tracker"?: string; @@ -1979,11 +2390,12 @@ export interface CopilotUserResponseEndpoints { telemetry?: string; } /** - * Schema for the `CopilotUserResponseQuotaSnapshots` type. + * Quota snapshot map from the raw Copilot user-response passthrough, with chat, completions, premium-interactions, and other entries. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "CopilotUserResponseQuotaSnapshots". */ +/** @experimental */ export interface CopilotUserResponseQuotaSnapshots { chat?: CopilotUserResponseQuotaSnapshotsChat; completions?: CopilotUserResponseQuotaSnapshotsCompletions; @@ -2006,71 +2418,183 @@ export interface CopilotUserResponseQuotaSnapshots { | undefined; } /** - * Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + * Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "CopilotUserResponseQuotaSnapshotsChat". */ +/** @experimental */ export interface CopilotUserResponseQuotaSnapshotsChat { + /** + * Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. + */ entitlement?: number; + /** + * Count of additional pay-per-request usage consumed this period beyond the entitlement. + */ overage_count?: number; + /** + * Whether usage may continue at pay-per-request rates once the entitlement is exhausted. + */ overage_permitted?: boolean; + /** + * Percentage of the entitlement remaining at the snapshot timestamp. + */ percent_remaining?: number; + /** + * Identifier of the quota bucket this snapshot describes. + */ quota_id?: string; + /** + * Amount of quota remaining at the snapshot timestamp. + */ quota_remaining?: number; + /** + * Remaining entitlement/quota amount at the snapshot timestamp. + */ remaining?: number; + /** + * Whether the entitlement for this category is unlimited. + */ unlimited?: boolean; + /** + * UTC timestamp when this snapshot was captured. + */ timestamp_utc?: string; + /** + * Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. + */ has_quota?: boolean; + /** + * Unix epoch time, in seconds, when this quota next resets. + */ quota_reset_at?: number; + /** + * Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. + */ token_based_billing?: boolean; } /** - * Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + * Completions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "CopilotUserResponseQuotaSnapshotsCompletions". */ +/** @experimental */ export interface CopilotUserResponseQuotaSnapshotsCompletions { + /** + * Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. + */ entitlement?: number; + /** + * Count of additional pay-per-request usage consumed this period beyond the entitlement. + */ overage_count?: number; + /** + * Whether usage may continue at pay-per-request rates once the entitlement is exhausted. + */ overage_permitted?: boolean; + /** + * Percentage of the entitlement remaining at the snapshot timestamp. + */ percent_remaining?: number; + /** + * Identifier of the quota bucket this snapshot describes. + */ quota_id?: string; + /** + * Amount of quota remaining at the snapshot timestamp. + */ quota_remaining?: number; + /** + * Remaining entitlement/quota amount at the snapshot timestamp. + */ remaining?: number; + /** + * Whether the entitlement for this category is unlimited. + */ unlimited?: boolean; + /** + * UTC timestamp when this snapshot was captured. + */ timestamp_utc?: string; + /** + * Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. + */ has_quota?: boolean; + /** + * Unix epoch time, in seconds, when this quota next resets. + */ quota_reset_at?: number; + /** + * Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. + */ token_based_billing?: boolean; } /** - * Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + * Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "CopilotUserResponseQuotaSnapshotsPremiumInteractions". */ +/** @experimental */ export interface CopilotUserResponseQuotaSnapshotsPremiumInteractions { + /** + * Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. + */ entitlement?: number; + /** + * Count of additional pay-per-request usage consumed this period beyond the entitlement. + */ overage_count?: number; + /** + * Whether usage may continue at pay-per-request rates once the entitlement is exhausted. + */ overage_permitted?: boolean; + /** + * Percentage of the entitlement remaining at the snapshot timestamp. + */ percent_remaining?: number; + /** + * Identifier of the quota bucket this snapshot describes. + */ quota_id?: string; + /** + * Amount of quota remaining at the snapshot timestamp. + */ quota_remaining?: number; + /** + * Remaining entitlement/quota amount at the snapshot timestamp. + */ remaining?: number; + /** + * Whether the entitlement for this category is unlimited. + */ unlimited?: boolean; + /** + * UTC timestamp when this snapshot was captured. + */ timestamp_utc?: string; + /** + * Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. + */ has_quota?: boolean; + /** + * Unix epoch time, in seconds, when this quota next resets. + */ quota_reset_at?: number; + /** + * Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. + */ token_based_billing?: boolean; } /** - * Schema for the `EnvAuthInfo` type. + * Authentication-info variant for a token sourced from an environment variable, with host, optional login, token, and env var name. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "EnvAuthInfo". */ +/** @experimental */ export interface EnvAuthInfo { /** * Personal access token (PAT) or server-to-server token sourced from an environment variable. @@ -2095,11 +2619,12 @@ export interface EnvAuthInfo { copilotUser?: CopilotUserResponse; } /** - * Schema for the `TokenAuthInfo` type. + * Authentication-info variant for SDK-configured token authentication, carrying host and the secret token value. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "TokenAuthInfo". */ +/** @experimental */ export interface TokenAuthInfo { /** * SDK-side token authentication; the host configured the token directly via the SDK. @@ -2116,11 +2641,12 @@ export interface TokenAuthInfo { copilotUser?: CopilotUserResponse; } /** - * Schema for the `CopilotApiTokenAuthInfo` type. + * Authentication-info variant for direct Copilot API token auth sourced from environment variables, with public GitHub host. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "CopilotApiTokenAuthInfo". */ +/** @experimental */ export interface CopilotApiTokenAuthInfo { /** * Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` environment-variable pair. The token itself is read from the environment by the runtime, not carried in this struct. @@ -2133,11 +2659,12 @@ export interface CopilotApiTokenAuthInfo { copilotUser?: CopilotUserResponse; } /** - * Schema for the `UserAuthInfo` type. + * Authentication-info variant for OAuth user auth, with host and login; the token remains in the runtime secret store. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UserAuthInfo". */ +/** @experimental */ export interface UserAuthInfo { /** * OAuth user authentication. The token itself is held in the runtime's secret token store (keyed by host+login) and is NOT carried in this struct. @@ -2154,11 +2681,12 @@ export interface UserAuthInfo { copilotUser?: CopilotUserResponse; } /** - * Schema for the `GhCliAuthInfo` type. + * Authentication-info variant for GitHub CLI credentials, carrying host, login, and the `gh auth token` value. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "GhCliAuthInfo". */ +/** @experimental */ export interface GhCliAuthInfo { /** * Authentication via the `gh` CLI's saved credentials. @@ -2179,11 +2707,12 @@ export interface GhCliAuthInfo { copilotUser?: CopilotUserResponse; } /** - * Schema for the `ApiKeyAuthInfo` type. + * Authentication-info variant for API-key authentication to a non-GitHub LLM provider, carrying the secret `apiKey` and host. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ApiKeyAuthInfo". */ +/** @experimental */ export interface ApiKeyAuthInfo { /** * API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). @@ -2205,6 +2734,7 @@ export interface ApiKeyAuthInfo { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountGetCurrentAuthResult". */ +/** @experimental */ export interface AccountGetCurrentAuthResult { authInfo?: AuthInfo; /** @@ -2213,6 +2743,7 @@ export interface AccountGetCurrentAuthResult { authErrors?: string[]; } +/** @experimental */ export interface AccountGetQuotaRequest { /** * GitHub token for per-user quota lookup. When provided, resolves this token to determine the user's quota instead of using the global auth. @@ -2225,6 +2756,7 @@ export interface AccountGetQuotaRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountGetQuotaResult". */ +/** @experimental */ export interface AccountGetQuotaResult { /** * Quota snapshots keyed by type (e.g., chat, completions, premium_interactions) @@ -2234,11 +2766,12 @@ export interface AccountGetQuotaResult { }; } /** - * Schema for the `AccountQuotaSnapshot` type. + * Quota usage snapshot for a Copilot quota type, including entitlement, used requests, overage, reset date, and remaining percentage. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountQuotaSnapshot". */ +/** @experimental */ export interface AccountQuotaSnapshot { /** * Whether the user has an unlimited usage entitlement @@ -2279,6 +2812,7 @@ export interface AccountQuotaSnapshot { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountLoginRequest". */ +/** @experimental */ export interface AccountLoginRequest { /** * GitHub host URL @@ -2299,6 +2833,7 @@ export interface AccountLoginRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountLoginResult". */ +/** @experimental */ export interface AccountLoginResult { /** * Whether the credential was persisted to a secure store (system keychain, or the config file when plaintext storage is enabled). False when no secure store was available and the token was not saved, so the consumer can decide how to proceed. @@ -2311,6 +2846,7 @@ export interface AccountLoginResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountLogoutRequest". */ +/** @experimental */ export interface AccountLogoutRequest { authInfo: AuthInfo; } @@ -2320,6 +2856,7 @@ export interface AccountLogoutRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AccountLogoutResult". */ +/** @experimental */ export interface AccountLogoutResult { /** * Whether other authenticated users remain after logout @@ -2327,7 +2864,7 @@ export interface AccountLogoutResult { hasMoreUsers: boolean; } /** - * Schema for the `AgentDiscoveryPath` type. + * Canonical directory where custom agents can be discovered or created, with scope, preference, and optional project path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AgentDiscoveryPath". @@ -2375,7 +2912,7 @@ export interface AgentGetCurrentResult { agent?: AgentInfo | null; } /** - * Schema for the `AgentInfo` type. + * Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AgentInfo". @@ -2728,12 +3265,13 @@ export interface AllowAllPermissionSetResult { */ success: boolean; /** - * Authoritative allow-all state after the mutation + * Authoritative full allow-all state after the mutation */ enabled: boolean; + mode?: PermissionsAllowAllMode; } /** - * Current full allow-all permission state. + * Current allow-all permission mode. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AllowAllPermissionState". @@ -2744,6 +3282,7 @@ export interface AllowAllPermissionState { * Whether full allow-all permissions are currently active */ enabled: boolean; + mode?: PermissionsAllowAllMode; } /** * Cancellation result for a user-requested shell command. @@ -2884,6 +3423,10 @@ export interface DiscoveredCanvas { * Short, single-sentence description shown to the agent in canvas catalogs. */ description: string; + /** + * Host-local PNG path for the canvas icon, when supplied + */ + icon?: string; inputSchema?: CanvasJsonSchema; /** * Actions the agent or host may invoke on an open instance @@ -2939,6 +3482,10 @@ export interface OpenCanvasInstance { * Provider-local canvas identifier */ canvasId: string; + /** + * Host-local PNG path for the canvas icon, when supplied + */ + icon?: string; /** * Rendered title */ @@ -3143,7 +3690,7 @@ export interface CommandList { commands: SlashCommandInfo[]; } /** - * Schema for the `SlashCommandInfo` type. + * Slash-command metadata with name, aliases, description, kind, input hint, execution allowance, and schedulability. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SlashCommandInfo". @@ -3189,6 +3736,10 @@ export interface SlashCommandInput { * Hint to display when command input has not been provided */ hint: string; + /** + * Optional literal choices the input accepts, each with a human-facing description; clients may render these as selectable options + */ + choices?: SlashCommandInputChoice[]; /** * When true, the command requires non-empty input; clients should render the input hint as required */ @@ -3199,6 +3750,23 @@ export interface SlashCommandInput { */ preserveMultilineInput?: boolean; } +/** + * A literal choice the command input accepts, with a human-facing description + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SlashCommandInputChoice". + */ +/** @experimental */ +export interface SlashCommandInputChoice { + /** + * The literal choice value (e.g. 'on', 'off', 'show') + */ + name: string; + /** + * Human-readable description shown alongside the choice + */ + description: string; +} /** * Pending command request ID and an optional error if the client handler failed. * @@ -3282,7 +3850,7 @@ export interface CommandsRespondToQueuedCommandRequest { result: QueuedCommandResult; } /** - * Schema for the `QueuedCommandHandled` type. + * Queued-command response indicating the host executed the command, with an optional flag to stop queue processing. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "QueuedCommandHandled". @@ -3299,7 +3867,7 @@ export interface QueuedCommandHandled { stopProcessingQueue?: boolean; } /** - * Schema for the `QueuedCommandNotHandled` type. + * Queued-command response indicating the host did not execute the command and the queue may continue. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "QueuedCommandNotHandled". @@ -3324,6 +3892,78 @@ export interface CommandsRespondToQueuedCommandResult { */ success: boolean; } +/** + * Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CompletionsGetTriggerCharactersResult". + */ +/** @experimental */ +export interface CompletionsGetTriggerCharactersResult { + /** + * Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. + */ + triggerCharacters: string[]; +} +/** + * Request host-driven completions for the current composer input. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CompletionsRequestRequest". + */ +/** @experimental */ +export interface CompletionsRequestRequest { + /** + * The full composed composer input. + */ + text: string; + /** + * Cursor offset within `text`, in UTF-16 code units. + */ + offset: number; +} +/** + * Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CompletionsRequestResult". + */ +/** @experimental */ +export interface CompletionsRequestResult { + /** + * Completion items in host-ranked order. + */ + items: SessionCompletionItem[]; +} +/** + * A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` (UTF-16 code units) in the composer with `insertText`; when the range is absent, the active token around the cursor is replaced. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionCompletionItem". + */ +/** @experimental */ +export interface SessionCompletionItem { + /** + * Text spliced into the composer when the item is accepted. + */ + insertText: string; + /** + * Start of the replacement range in `text`, in UTF-16 code units. + */ + rangeStart?: number; + /** + * End (exclusive) of the replacement range in `text`, in UTF-16 code units. + */ + rangeEnd?: number; + /** + * Primary display label for the picker row. Falls back to `insertText` when absent. + */ + label?: string; + /** + * Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the host's display kind. + */ + kind?: string; +} /** * Params to attach or detach an in-process ExtensionController delegate. * @@ -3430,17 +4070,22 @@ export interface ConnectRemoteSessionParams { sessionId: string; } /** - * Optional connection token presented by the SDK client during the handshake. + * Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ConnectRequest". */ +/** @experimental */ /** @internal */ export interface ConnectRequest { /** * Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN */ token?: string; + /** + * Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. + */ + enableGitHubTelemetryForwarding?: boolean; } /** * Handshake result reporting the server's protocol version and package version on success. @@ -3448,6 +4093,7 @@ export interface ConnectRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ConnectResult". */ +/** @experimental */ /** @internal */ export interface ConnectResult { /** @@ -3463,6 +4109,31 @@ export interface ConnectResult { */ version: string; } +/** + * A single large message currently in context. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ContextHeaviestMessage". + */ +/** @experimental */ +export interface ContextHeaviestMessage { + /** + * Stable identifier for this message within the snapshot. + */ + id: string; + /** + * Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. + */ + label: string; + /** + * Role of the chat message (`user`, `assistant`, or `tool`). + */ + role: string; + /** + * Token count currently in context for this individual message. + */ + tokens: number; +} /** * The currently selected model, reasoning effort, and context tier for the session. The context tier reflects `Session.getContextTier()`, restored from the session journal on resume. * @@ -3521,11 +4192,148 @@ export interface CurrentToolMetadata { deferLoading?: boolean; } /** - * Schema for the `DiscoveredMcpServer` type. + * A file included in the redacted debug bundle. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsCollectedEntry". + */ +/** @experimental */ +export interface DebugCollectLogsCollectedEntry { + /** + * Relative path of the file in the staged bundle/archive. + */ + bundlePath: string; + source: DebugCollectLogsSource; + /** + * Redacted output size in bytes. + */ + sizeBytes: number; +} +/** + * A caller-provided server-local file or directory to include in the debug bundle. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsEntry". + */ +/** @experimental */ +export interface DebugCollectLogsEntry { + kind: DebugCollectLogsEntryKind; + /** + * Server-local source path to read. + */ + path: string; + /** + * Relative path to use inside the staged bundle/archive. + */ + bundlePath: string; + redaction?: DebugCollectLogsRedaction; + /** + * When true, collection fails if this entry cannot be read. Defaults to false, which records the entry in `skippedEntries`. + */ + required?: boolean; +} +/** + * Built-in session diagnostics to include in the bundle. Omitted fields default to true. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsInclude". + */ +/** @experimental */ +export interface DebugCollectLogsInclude { + /** + * Include the session event log (`events.jsonl`). Defaults to true. + */ + events?: boolean; + /** + * Include process logs for the session. Defaults to true. + */ + processLogs?: boolean; + /** + * Include interactive shell logs written under the session's `shell-logs` directory. Defaults to true. + */ + shellLogs?: boolean; + /** + * Server-local path to the session's events.jsonl file. Internal callers normally omit this and let the runtime derive it from the session. + */ + eventsPath?: string; + /** + * Server-local path to the current process log. When set, it is included as `process.log` and its directory is searched for prior logs from the same session. + */ + currentProcessLogPath?: string; + /** + * Server-local process log directory to search when `currentProcessLogPath` is unavailable, useful for collecting logs for inactive sessions. + */ + processLogDirectory?: string; + /** + * Maximum number of previous process logs to include. Defaults to 5. + */ + previousProcessLogLimit?: number; +} +/** + * Options for collecting a redacted session debug bundle. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsRequest". + */ +/** @experimental */ +export interface DebugCollectLogsRequest { + destination: DebugCollectLogsDestination; + include?: DebugCollectLogsInclude; + /** + * Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. + */ + additionalEntries?: DebugCollectLogsEntry[]; +} +/** + * Result of collecting a redacted debug bundle. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsResult". + */ +/** @experimental */ +export interface DebugCollectLogsResult { + kind: DebugCollectLogsResultKind; + /** + * Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. + */ + path: string; + /** + * Files included in the redacted bundle. + */ + entries: DebugCollectLogsCollectedEntry[]; + /** + * Optional files or directories that could not be included. + */ + skippedEntries?: DebugCollectLogsSkippedEntry[]; +} +/** + * An optional debug bundle entry that could not be included. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "DebugCollectLogsSkippedEntry". + */ +/** @experimental */ +export interface DebugCollectLogsSkippedEntry { + /** + * Relative path requested for this bundle entry. + */ + bundlePath: string; + /** + * Server-local source path that could not be read. + */ + path?: string; + /** + * Reason the entry was skipped. + */ + reason: string; +} +/** + * MCP server discovered by `mcp.discover`, with config source, optional plugin source, transport type, and enabled state. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "DiscoveredMcpServer". */ +/** @experimental */ export interface DiscoveredMcpServer { /** * Server name (config key) @@ -3674,7 +4482,7 @@ export interface ExecuteCommandResult { error?: string; } /** - * Schema for the `Extension` type. + * Discovered extension metadata, including source-qualified ID, name, discovery source, status, and optional process ID. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "Extension". @@ -3796,6 +4604,10 @@ export interface ExternalToolTextResultForLlm { * Structured content blocks from the tool */ contents?: ExternalToolTextResultForLlmContent[]; + /** + * Tool references returned by a tool-search override: names of deferred tools to surface to the model. When set, the tool result is materialized as `tool_reference` content blocks (rather than plain text) so the model knows which deferred tools are now available. + */ + toolReferences?: string[]; } /** * Binary result returned by a tool for the model @@ -3867,6 +4679,39 @@ export interface ExternalToolTextResultForLlmContentTerminal { */ cwd?: string; } +/** + * Shell command exit metadata with optional output preview + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ExternalToolTextResultForLlmContentShellExit". + */ +/** @experimental */ +export interface ExternalToolTextResultForLlmContentShellExit { + /** + * Content block type discriminator + */ + type: "shell_exit"; + /** + * Shell id, as assigned by Copilot runtime + */ + shellId: string; + /** + * Exit code from the completed shell command + */ + exitCode: number; + /** + * Working directory where the shell command was executed + */ + cwd?: string; + /** + * Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. + */ + outputPreview?: string; + /** + * Whether outputPreview is known to be incomplete or truncated + */ + outputTruncated?: boolean; +} /** * Image content block with base64-encoded data * @@ -4052,63 +4897,182 @@ export interface FolderTrustCheckResult { trusted: boolean; } /** - * Pending external tool call request ID, with the tool result or an error describing why it failed. + * Client environment metadata describing the process that produced a telemetry event. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "HandlePendingToolCallRequest". + * via the `definition` "GitHubTelemetryClientInfo". */ /** @experimental */ -export interface HandlePendingToolCallRequest { +export interface GitHubTelemetryClientInfo { /** - * Request ID of the pending tool call + * Copilot CLI version string. */ - requestId: string; - result?: ExternalToolResult; + cli_version: string; /** - * Error message if the tool call failed + * Operating system platform (e.g. darwin, linux, win32). */ - error?: string; -} -/** - * Indicates whether the external tool call result was handled successfully. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "HandlePendingToolCallResult". - */ -/** @experimental */ -export interface HandlePendingToolCallResult { + os_platform: string; /** - * Whether the tool call result was handled successfully + * Operating system version string. */ - success: boolean; -} -/** - * Indicates whether an in-progress manual compaction was aborted. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "HistoryAbortManualCompactionResult". - */ -/** @experimental */ -export interface HistoryAbortManualCompactionResult { + os_version: string; /** - * Whether an in-progress manual compaction was aborted. False when no manual compaction was running, when its abort controller was already aborted, or when the session is remote. + * Operating system architecture (e.g. arm64, x64). */ - aborted: boolean; + os_arch: string; + /** + * Node.js runtime version string. + */ + node_version: string; + /** + * Copilot subscription plan, when known. + */ + copilot_plan?: string; + /** + * Type of client. + */ + client_type?: string; + /** + * Name of the client application. + */ + client_name?: string; + /** + * Whether the user is a GitHub/Microsoft staff member. + */ + is_staff?: boolean; + /** + * Stable machine identifier for the device. + */ + dev_device_id?: string; } /** - * Indicates whether an in-progress background compaction was cancelled. + * A single telemetry event in the runtime's native GitHub-shaped telemetry format, forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing GitHubTelemetryNotification distinguishes standard from restricted events; the payload shape is identical for both. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "HistoryCancelBackgroundCompactionResult". + * via the `definition` "GitHubTelemetryEvent". */ /** @experimental */ -export interface HistoryCancelBackgroundCompactionResult { +export interface GitHubTelemetryEvent { /** - * Whether an in-progress background compaction was cancelled. False when no compaction was running, when the session is remote, or when the underlying processor was unavailable. + * Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed). */ - cancelled: boolean; -} -/** + kind: string; + /** + * Timestamp when the event was created (ISO 8601 format). + */ + created_at?: string; + /** + * Reference to the model call that produced this event. + */ + model_call_id?: string; + /** + * String-valued properties as a map from key to value. + */ + properties: { + [k: string]: string | undefined; + }; + /** + * Numeric metrics as a map from key to value. + */ + metrics: { + [k: string]: number | undefined; + }; + /** + * Experiment assignment context. + */ + exp_assignment_context?: string; + /** + * Feature flags enabled for this session, as a map from flag to value. + */ + features?: { + [k: string]: string | undefined; + }; + /** + * Session identifier the event belongs to. + */ + session_id?: string; + /** + * Copilot tracking ID for user-level attribution. + */ + copilot_tracking_id?: string; + client?: GitHubTelemetryClientInfo; +} +/** + * Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "GitHubTelemetryNotification". + */ +/** @experimental */ +export interface GitHubTelemetryNotification { + /** + * Session the telemetry event belongs to, when it is session-scoped. Omitted for sessionless events (for example, `server.sendTelemetry` calls with no session id), which are still forwarded to opted-in connections. + */ + sessionId?: string; + /** + * Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route restricted events to first-party Microsoft stores only. + */ + restricted: boolean; + event: GitHubTelemetryEvent; +} +/** + * Pending external tool call request ID, with the tool result or an error describing why it failed. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HandlePendingToolCallRequest". + */ +/** @experimental */ +export interface HandlePendingToolCallRequest { + /** + * Request ID of the pending tool call + */ + requestId: string; + result?: ExternalToolResult; + /** + * Error message if the tool call failed + */ + error?: string; +} +/** + * Indicates whether the external tool call result was handled successfully. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HandlePendingToolCallResult". + */ +/** @experimental */ +export interface HandlePendingToolCallResult { + /** + * Whether the tool call result was handled successfully + */ + success: boolean; +} +/** + * Indicates whether an in-progress manual compaction was aborted. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryAbortManualCompactionResult". + */ +/** @experimental */ +export interface HistoryAbortManualCompactionResult { + /** + * Whether an in-progress manual compaction was aborted. False when no manual compaction was running, when its abort controller was already aborted, or when the session is remote. + */ + aborted: boolean; +} +/** + * Indicates whether an in-progress background compaction was cancelled. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryCancelBackgroundCompactionResult". + */ +/** @experimental */ +export interface HistoryCancelBackgroundCompactionResult { + /** + * Whether an in-progress background compaction was cancelled. False when no compaction was running, when the session is remote, or when the underlying processor was unavailable. + */ + cancelled: boolean; +} +/** * Post-compaction context window usage breakdown * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema @@ -4220,7 +5184,31 @@ export interface HistoryTruncateResult { eventsRemoved: number; } /** - * Schema for the `InstalledPlugin` type. + * Runtime-owned wire payload for a server-to-client hook callback invocation. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HookInvokeRequest". + */ +/** @experimental */ +/** @internal */ +export interface HookInvokeRequest { + sessionId: string; + hookType: HookType; + input: unknown; +} +/** + * Optional output returned by an SDK callback hook. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HookInvokeResponse". + */ +/** @experimental */ +/** @internal */ +export interface HookInvokeResponse { + output?: unknown; +} +/** + * Installed plugin record from global state, with marketplace, version, install time, enabled state, cache path, and source. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstalledPlugin". @@ -4254,7 +5242,7 @@ export interface InstalledPlugin { source?: InstalledPluginSource; } /** - * Schema for the `InstalledPluginSourceGitHub` type. + * Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstalledPluginSourceGitHub". @@ -4270,7 +5258,7 @@ export interface InstalledPluginSourceGitHub { path?: string; } /** - * Schema for the `InstalledPluginSourceUrl` type. + * Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstalledPluginSourceUrl". @@ -4286,7 +5274,7 @@ export interface InstalledPluginSourceUrl { path?: string; } /** - * Schema for the `InstalledPluginSourceLocal` type. + * Source descriptor for a direct local plugin install, with a local filesystem path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstalledPluginSourceLocal". @@ -4315,6 +5303,10 @@ export interface InstalledPluginInfo { * Marketplace the plugin came from. Empty string ("") for direct repo / URL / local installs. */ marketplace: string; + /** + * Opaque, stable hash identifying a direct (non-marketplace) install source. Present only for direct repo / URL / local installs; absent for marketplace plugins. Same source yields the same id; distinct sources never collide. + */ + directSourceId?: string; /** * Installed version (when reported by the plugin manifest) */ @@ -4325,7 +5317,7 @@ export interface InstalledPluginInfo { enabled: boolean; } /** - * Schema for the `InstructionDiscoveryPath` type. + * Canonical file or directory where custom instructions can be discovered or created, with location, kind, preference, and project path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstructionDiscoveryPath". @@ -4408,7 +5400,7 @@ export interface InstructionsGetSourcesResult { sources: InstructionSource[]; } /** - * Schema for the `InstructionSource` type. + * Loaded instruction source for a session, including path, content, category, location, applicability, and optional description. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstructionSource". @@ -4527,6 +5519,18 @@ export interface LlmInferenceHttpRequestStartRequest { url: string; headers: LlmInferenceHeaders; transport?: LlmInferenceHttpRequestStartTransport; + /** + * Stable per-agent-instance id attributing this request to a specific agent trajectory. Present when the request originates from an agent turn; absent for requests issued outside any agent context (e.g. some SDK callers). A request with an `agentId` but no `parentAgentId` is a root-agent request; one carrying both is a subagent request. Sourced from the runtime's per-request agent context and surfaced on the envelope independently of transport, so it is available for both first-party (CAPI) and BYOK/custom-provider requests; on the CAPI transport the runtime derives the upstream `X-Agent-Task-Id` header from this same context. Consumers routing each provider call to a training trajectory should key on this rather than on lifecycle events, since it is available on the request path before sampling. + */ + agentId?: string; + /** + * Id of the parent agent that spawned the agent issuing this request. Present only for subagent requests; absent for root-agent requests and non-agent requests. Combined with `agentId`, this lets consumers attribute a call to a child trajectory versus the root. Like `agentId`, it comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Parent-Agent-Id` header from this same context. + */ + parentAgentId?: string; + /** + * Coarse classification of the interaction that produced this request. Open string for forward-compatibility; known values include `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, and `conversation-user`. Absent when the runtime did not classify the request. Comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` header from this same context. + */ + interactionType?: string; } /** * Acknowledgement. Returning successfully simply means the SDK accepted the start frame; it does not imply the request will succeed. @@ -4641,7 +5645,7 @@ export interface LlmInferenceSetProviderResult { success: boolean; } /** - * Schema for the `LocalSessionMetadataValue` type. + * Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "LocalSessionMetadataValue". @@ -4854,7 +5858,7 @@ export interface MarketplaceListResult { marketplaces: MarketplaceInfo[]; } /** - * Schema for the `MarketplaceRefreshEntry` type. + * Per-marketplace refresh result, including marketplace name, success flag, and optional failure error. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "MarketplaceRefreshEntry". @@ -4905,7 +5909,7 @@ export interface MarketplaceRemoveResult { dependentPlugins?: string[]; } /** - * Schema for the `McpAllowedServer` type. + * MCP server allowed by policy, with server name and optional PII-free explanatory note. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpAllowedServer". @@ -5120,7 +6124,7 @@ export interface McpAppsReadResourceResult { contents: McpAppsResourceContent[]; } /** - * Schema for the `McpAppsResourceContent` type. + * MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource metadata. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpAppsResourceContent". @@ -5221,6 +6225,7 @@ export interface McpCancelSamplingExecutionResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigAddRequest". */ +/** @experimental */ export interface McpConfigAddRequest { /** * Unique name for the MCP server @@ -5234,6 +6239,7 @@ export interface McpConfigAddRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfigStdio". */ +/** @experimental */ export interface McpServerConfigStdio { /** * Tools to include. Defaults to all tools if not specified. @@ -5276,6 +6282,7 @@ export interface McpServerConfigStdio { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerAuthConfigRedirectPort". */ +/** @experimental */ export interface McpServerAuthConfigRedirectPort { /** * Fixed port for the OAuth redirect callback server. @@ -5288,6 +6295,7 @@ export interface McpServerAuthConfigRedirectPort { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServerConfigHttp". */ +/** @experimental */ export interface McpServerConfigHttp { /** * Tools to include. Defaults to all tools if not specified. @@ -5332,6 +6340,7 @@ export interface McpServerConfigHttp { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigDisableRequest". */ +/** @experimental */ export interface McpConfigDisableRequest { /** * Names of MCP servers to disable. Each server is added to the persisted disabled list so new sessions skip it. Already-disabled names are ignored. Active sessions keep their current connections until they end. @@ -5344,6 +6353,7 @@ export interface McpConfigDisableRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigEnableRequest". */ +/** @experimental */ export interface McpConfigEnableRequest { /** * Names of MCP servers to enable. Each server is removed from the persisted disabled list so new sessions spawn it. Unknown or already-enabled names are ignored. @@ -5356,6 +6366,7 @@ export interface McpConfigEnableRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigList". */ +/** @experimental */ export interface McpConfigList { /** * All MCP servers from user config, keyed by name @@ -5370,6 +6381,7 @@ export interface McpConfigList { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigRemoveRequest". */ +/** @experimental */ export interface McpConfigRemoveRequest { /** * Name of the MCP server to remove @@ -5382,6 +6394,7 @@ export interface McpConfigRemoveRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpConfigUpdateRequest". */ +/** @experimental */ export interface McpConfigUpdateRequest { /** * Name of the MCP server to update @@ -5439,6 +6452,7 @@ export interface McpDisableRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpDiscoverRequest". */ +/** @experimental */ export interface McpDiscoverRequest { /** * Working directory used as context for discovery (e.g., plugin resolution) @@ -5451,6 +6465,7 @@ export interface McpDiscoverRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpDiscoverResult". */ +/** @experimental */ export interface McpDiscoverResult { /** * MCP servers discovered from all sources @@ -5515,7 +6530,7 @@ export interface McpExecuteSamplingResult { [k: string]: unknown | undefined; } /** - * Schema for the `McpFilteredServer` type. + * MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpFilteredServer". @@ -5539,6 +6554,33 @@ export interface McpFilteredServer { */ enterpriseName?: string; } +/** + * MCP headers refresh request id and the host response. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpHeadersHandlePendingHeadersRefreshRequestRequest". + */ +/** @experimental */ +export interface McpHeadersHandlePendingHeadersRefreshRequestRequest { + /** + * Headers refresh request identifier from mcp.headers_refresh_required + */ + requestId: string; + result: McpHeadersHandlePendingHeadersRefreshRequest; +} +/** + * Indicates whether the pending MCP headers refresh response was accepted. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpHeadersHandlePendingHeadersRefreshRequestResult". + */ +/** @experimental */ +export interface McpHeadersHandlePendingHeadersRefreshRequestResult { + /** + * Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + */ + success: boolean; +} /** * Host-level state, omitted when no MCP host is initialized. * @@ -5663,7 +6705,7 @@ export interface McpListToolsResult { tools: McpTools[]; } /** - * Schema for the `McpTools` type. + * MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery metadata. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpTools". @@ -5678,6 +6720,24 @@ export interface McpTools { * Tool description, when provided. */ description?: string; + ui?: McpToolUi; +} +/** + * Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpToolUi". + */ +/** @experimental */ +export interface McpToolUi { + /** + * URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use `session.mcp.resources.read` to fetch its HTML and resource metadata. + */ + resourceUri?: string; + /** + * Tool visibility advertised by the server. When absent, MCP Apps defaults apply. + */ + visibility?: McpToolUiVisibility[]; } /** * Pending MCP OAuth request ID and host-provided token or cancellation response. @@ -5757,36 +6817,6 @@ export interface McpOauthLoginResult { */ authorizationUrl?: string; } -/** - * MCP OAuth request id and optional provider response. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpOauthRespondRequest". - */ -/** @experimental */ -/** @internal */ -export interface McpOauthRespondRequest { - /** - * OAuth request identifier from mcp.oauth_required - */ - requestId: string; - /** - * In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be serialized across the JSON-RPC boundary. - * - * @internal - */ - provider?: { - [k: string]: unknown | undefined; - }; -} -/** - * Empty result after recording the MCP OAuth response. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpOauthRespondResult". - */ -/** @experimental */ -export interface McpOauthRespondResult {} /** * Registration parameters for an external MCP client. * @@ -5857,26 +6887,301 @@ export interface McpRemoveGitHubResult { removed: boolean; } /** - * Server name and opaque configuration for an individual MCP server restart. + * An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, MIME type, size, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpRestartServerRequest". + * via the `definition` "McpResource". */ /** @experimental */ -/** @internal */ -export interface McpRestartServerRequest { +export interface McpResource { /** - * Name of the MCP server to restart + * The resource URI (e.g. ui://... or file:///...) + */ + uri: string; + /** + * The programmatic name of the resource + */ + name: string; + /** + * Optional human-readable display title + */ + title?: string; + /** + * Optional description of what this resource represents + */ + description?: string; + /** + * MIME type of the resource, if known + */ + mimeType?: string; + /** + * Resource size in bytes, when known + */ + size?: number; + /** + * Icons associated with this resource + */ + icons?: McpResourceIcon[]; + annotations?: McpResourceAnnotations; + /** + * Resource-level metadata + */ + _meta?: { + [k: string]: unknown | undefined; + }; + /** + * Server-provided non-standard descriptor fields preserved from the MCP response + */ + additionalProperties?: { + [k: string]: unknown | undefined; + }; +} +/** + * A resource icon descriptor plus preserved non-standard icon fields. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourceIcon". + */ +/** @experimental */ +export interface McpResourceIcon { + /** + * Icon URI + */ + src: string; + /** + * Icon MIME type, when known + */ + mimeType?: string; + /** + * Icon sizes hint + */ + sizes?: string; + /** + * Theme hint for this icon + */ + theme?: string; + /** + * Server-provided non-standard icon fields preserved from the MCP response + */ + additionalProperties?: { + [k: string]: unknown | undefined; + }; +} +/** + * Standard MCP resource annotations plus preserved non-standard annotation fields. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourceAnnotations". + */ +/** @experimental */ +export interface McpResourceAnnotations { + /** + * Intended audience roles for this resource + */ + audience?: string[]; + /** + * Priority hint for model/client use + */ + priority?: number; + /** + * Last-modified timestamp hint + */ + lastModified?: string; + /** + * Server-provided non-standard annotation fields preserved from the MCP response + */ + additionalProperties?: { + [k: string]: unknown | undefined; + }; +} +/** + * MCP resource content with URI, optional MIME type, text or base64 blob, and resource metadata. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourceContent". + */ +/** @experimental */ +export interface McpResourceContent { + /** + * The resource URI + */ + uri: string; + /** + * MIME type of the content + */ + mimeType?: string; + /** + * Text content (e.g. HTML) + */ + text?: string; + /** + * Base64-encoded binary content + */ + blob?: string; + /** + * Resource-level metadata (CSP, permissions, etc.) + */ + _meta?: { + [k: string]: unknown | undefined; + }; +} +/** + * MCP server whose resources to enumerate. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourcesListRequest". + */ +/** @experimental */ +export interface McpResourcesListRequest { + /** + * Name of the MCP server whose resources to enumerate */ serverName: string; /** - * Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. - * - * @internal + * Opaque MCP pagination cursor from a prior `nextCursor` value */ - config: { + cursor?: string; +} +/** + * One page of resources advertised by the named MCP server. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourcesListResult". + */ +/** @experimental */ +export interface McpResourcesListResult { + /** + * Resources advertised by the server (proxied MCP `resources/list`) + */ + resources: McpResource[]; + /** + * Opaque cursor for the next page, if the server has more resources + */ + nextCursor?: string; +} +/** + * MCP server whose resource templates to enumerate. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourcesListTemplatesRequest". + */ +/** @experimental */ +export interface McpResourcesListTemplatesRequest { + /** + * Name of the MCP server whose resource templates to enumerate + */ + serverName: string; + /** + * Opaque MCP pagination cursor from a prior `nextCursor` value + */ + cursor?: string; +} +/** + * One page of resource templates advertised by the named MCP server. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourcesListTemplatesResult". + */ +/** @experimental */ +export interface McpResourcesListTemplatesResult { + /** + * Resource templates advertised by the server (proxied MCP `resources/templates/list`) + */ + resourceTemplates: McpResourceTemplate[]; + /** + * Opaque cursor for the next page, if the server has more resource templates + */ + nextCursor?: string; +} +/** + * An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, name, and optional title, description, MIME type, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourceTemplate". + */ +/** @experimental */ +export interface McpResourceTemplate { + /** + * An RFC 6570 URI template for constructing resource URIs + */ + uriTemplate: string; + /** + * The programmatic name of the resource template + */ + name: string; + /** + * Optional human-readable display title + */ + title?: string; + /** + * Optional description of what this template is for + */ + description?: string; + /** + * MIME type for resources matching this template, if uniform + */ + mimeType?: string; + /** + * Icons associated with resources matching this template + */ + icons?: McpResourceIcon[]; + annotations?: McpResourceAnnotations; + /** + * Resource-template-level metadata + */ + _meta?: { [k: string]: unknown | undefined; }; + /** + * Server-provided non-standard descriptor fields preserved from the MCP response + */ + additionalProperties?: { + [k: string]: unknown | undefined; + }; +} +/** + * MCP server and resource URI to fetch. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourcesReadRequest". + */ +/** @experimental */ +export interface McpResourcesReadRequest { + /** + * Name of the MCP server hosting the resource + */ + serverName: string; + /** + * Resource URI + */ + uri: string; +} +/** + * Resource contents returned by the MCP server. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpResourcesReadResult". + */ +/** @experimental */ +export interface McpResourcesReadResult { + /** + * Resource contents returned by the server + */ + contents: McpResourceContent[]; +} +/** + * Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpRestartServerRequest". + */ +/** @experimental */ +export interface McpRestartServerRequest { + /** + * Name of the MCP server to restart + */ + serverName: string; + config?: McpServerConfig; } /** * Outcome of an MCP sampling execution: success result, failure error, or cancellation. @@ -5894,7 +7199,7 @@ export interface McpSamplingExecutionResult { error?: string; } /** - * Schema for the `McpServer` type. + * MCP server status entry, including config source/plugin source and any connection error. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpServer". @@ -5955,26 +7260,18 @@ export interface McpSetEnvValueModeResult { mode: McpSetEnvValueModeDetails; } /** - * Server name and opaque configuration for an individual MCP server start. + * Server name and configuration for an individual MCP server start. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpStartServerRequest". */ /** @experimental */ -/** @internal */ export interface McpStartServerRequest { /** * Name of the MCP server to start */ serverName: string; - /** - * Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. - * - * @internal - */ - config: { - [k: string]: unknown | undefined; - }; + config: McpServerConfig; } /** * MCP server startup filtering result. @@ -6033,6 +7330,49 @@ export interface MemoryConfiguration { */ enabled: boolean; } +/** + * Per-source attribution breakdown for the session's current context window, or null if uninitialized. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "MetadataContextAttributionResult". + */ +/** @experimental */ +export interface MetadataContextAttributionResult { + /** + * Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + */ + contextAttribution?: SessionContextAttribution | null; +} +/** + * Parameters for the heaviest-messages query. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "MetadataContextHeaviestMessagesRequest". + */ +/** @experimental */ +export interface MetadataContextHeaviestMessagesRequest { + /** + * Maximum number of messages to return, most-expensive first. Omit for the server default. + */ + limit?: number; +} +/** + * The heaviest individual messages in the session's context window, most-expensive first. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "MetadataContextHeaviestMessagesResult". + */ +/** @experimental */ +export interface MetadataContextHeaviestMessagesResult { + /** + * Total token count of the current context window, so callers can compute each message's share without a second call. + */ + totalTokens: number; + /** + * Heaviest messages, most-expensive first. + */ + messages: ContextHeaviestMessage[]; +} /** * Model identifier and token limits used to compute the context-info breakdown. * @@ -6171,7 +7511,7 @@ export interface SessionWorkingDirectoryContext { /** @experimental */ export interface MetadataRecordContextChangeResult {} /** - * Absolute path to set as the session's new working directory. + * Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "MetadataSetWorkingDirectoryRequest". @@ -6184,7 +7524,7 @@ export interface MetadataSetWorkingDirectoryRequest { workingDirectory: string; } /** - * Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. + * Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "MetadataSetWorkingDirectoryResult". @@ -6237,11 +7577,12 @@ export interface MetadataSnapshotRemoteMetadataRepository { branch: string; } /** - * Schema for the `Model` type. + * Copilot model metadata, including identifier, display name, capabilities, policy, billing, reasoning efforts, and picker categories. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "Model". */ +/** @experimental */ export interface Model { /** * Model identifier (e.g., "claude-sonnet-4.5") @@ -6271,6 +7612,7 @@ export interface Model { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelCapabilities". */ +/** @experimental */ export interface ModelCapabilities { supports?: ModelCapabilitiesSupports; limits?: ModelCapabilitiesLimits; @@ -6281,6 +7623,7 @@ export interface ModelCapabilities { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelCapabilitiesSupports". */ +/** @experimental */ export interface ModelCapabilitiesSupports { /** * Whether this model supports vision/image input @@ -6290,6 +7633,7 @@ export interface ModelCapabilitiesSupports { * Whether this model supports reasoning effort configuration */ reasoningEffort?: boolean; + adaptive_thinking?: AdaptiveThinkingSupport; } /** * Token limits for prompts, outputs, and context window @@ -6297,6 +7641,7 @@ export interface ModelCapabilitiesSupports { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelCapabilitiesLimits". */ +/** @experimental */ export interface ModelCapabilitiesLimits { /** * Maximum number of prompt/input tokens @@ -6318,6 +7663,7 @@ export interface ModelCapabilitiesLimits { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelCapabilitiesLimitsVision". */ +/** @experimental */ export interface ModelCapabilitiesLimitsVision { /** * MIME types the model accepts @@ -6338,6 +7684,7 @@ export interface ModelCapabilitiesLimitsVision { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelPolicy". */ +/** @experimental */ export interface ModelPolicy { state: ModelPolicyState; /** @@ -6351,12 +7698,18 @@ export interface ModelPolicy { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelBilling". */ +/** @experimental */ export interface ModelBilling { /** * Billing cost multiplier relative to the base rate */ multiplier?: number; tokenPrices?: ModelBillingTokenPrices; + /** + * Whole-number percentage discount (0-100) applied to usage billed through this model. Populated for the synthetic `auto` model, where requests routed by auto-mode are billed at a reduced rate; absent for concrete models. + */ + discountPercent?: number; + promo?: ModelBillingPromo; } /** * Token-level pricing information for this model @@ -6364,6 +7717,7 @@ export interface ModelBilling { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelBillingTokenPrices". */ +/** @experimental */ export interface ModelBillingTokenPrices { /** * AI Credits cost per billing batch of input tokens @@ -6407,6 +7761,7 @@ export interface ModelBillingTokenPrices { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelBillingTokenPricesLongContext". */ +/** @experimental */ export interface ModelBillingTokenPricesLongContext { /** * AI Credits cost per billing batch of input tokens @@ -6439,6 +7794,31 @@ export interface ModelBillingTokenPricesLongContext { */ maxPromptTokens?: number; } +/** + * Active server-driven promotion for a model, including its discount and expiry. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ModelBillingPromo". + */ +/** @experimental */ +export interface ModelBillingPromo { + /** + * Stable identifier for the promotion campaign. + */ + id?: string; + /** + * Percentage discount (0-100) applied while the promotion is active. May be fractional. + */ + discountPercent?: number; + /** + * UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. + */ + endsAt: string; + /** + * Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. + */ + message?: string; +} /** * Optional capability overrides (vision, tool_calls, reasoning, etc.). * @@ -6466,6 +7846,7 @@ export interface ModelCapabilitiesOverrideSupports { * Whether this model supports reasoning effort configuration */ reasoningEffort?: boolean; + adaptive_thinking?: AdaptiveThinkingSupport; } /** * Token limits for prompts, outputs, and context window @@ -6516,6 +7897,7 @@ export interface ModelCapabilitiesOverrideLimitsVision { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelList". */ +/** @experimental */ export interface ModelList { /** * List of available models with full metadata @@ -6562,6 +7944,7 @@ export interface ModelSetReasoningEffortResult { reasoningEffort: string; } +/** @experimental */ export interface ModelsListRequest { /** * GitHub token for per-user model listing. When provided, resolves this token to determine the user's Copilot plan and available models instead of using the global auth. @@ -6585,6 +7968,7 @@ export interface ModelSwitchToRequest { */ reasoningEffort?: string; reasoningSummary?: ReasoningSummary; + verbosity?: Verbosity; modelCapabilities?: ModelCapabilitiesOverride; contextTier?: ContextTier; } @@ -6716,7 +8100,7 @@ export interface NameSetRequest { name: string; } /** - * Schema for the `OptionsUpdateAdditionalContentExclusionPolicy` type. + * Content-exclusion policy supplied to `session.options.update`, with rules, last-updated data, and scope. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "OptionsUpdateAdditionalContentExclusionPolicy". @@ -6728,7 +8112,7 @@ export interface OptionsUpdateAdditionalContentExclusionPolicy { scope: OptionsUpdateAdditionalContentExclusionPolicyScope; } /** - * Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRule` type. + * Single content-exclusion rule supplied to `session.options.update`, with paths, match conditions, and source. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "OptionsUpdateAdditionalContentExclusionPolicyRule". @@ -6741,7 +8125,7 @@ export interface OptionsUpdateAdditionalContentExclusionPolicyRule { source: OptionsUpdateAdditionalContentExclusionPolicyRuleSource; } /** - * Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. + * Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "OptionsUpdateAdditionalContentExclusionPolicyRuleSource". @@ -6752,7 +8136,7 @@ export interface OptionsUpdateAdditionalContentExclusionPolicyRuleSource { type: string; } /** - * Schema for the `PendingPermissionRequest` type. + * Pending permission prompt reconstructed from event history, with request ID and user-facing prompt details. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PendingPermissionRequest". @@ -6779,7 +8163,7 @@ export interface PendingPermissionRequestList { items: PendingPermissionRequest[]; } /** - * Schema for the `PermissionDecisionApproveOnce` type. + * Permission-decision request variant to approve only the current permission request. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveOnce". @@ -6792,7 +8176,7 @@ export interface PermissionDecisionApproveOnce { kind: "approve-once"; } /** - * Schema for the `PermissionDecisionApproveForSession` type. + * Permission-decision request variant to approve for the rest of the session, with optional tool approval or URL domain. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSession". @@ -6810,7 +8194,7 @@ export interface PermissionDecisionApproveForSession { domain?: string; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalCommands` type. + * Session-scoped approval details for specific command identifiers. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalCommands". @@ -6827,7 +8211,7 @@ export interface PermissionDecisionApproveForSessionApprovalCommands { commandIdentifiers: string[]; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalRead` type. + * Session-scoped approval details for read-only filesystem operations. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalRead". @@ -6840,7 +8224,7 @@ export interface PermissionDecisionApproveForSessionApprovalRead { kind: "read"; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalWrite` type. + * Session-scoped approval details for filesystem write operations. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalWrite". @@ -6853,7 +8237,7 @@ export interface PermissionDecisionApproveForSessionApprovalWrite { kind: "write"; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalMcp` type. + * Session-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalMcp". @@ -6874,7 +8258,7 @@ export interface PermissionDecisionApproveForSessionApprovalMcp { toolName: string | null; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalMcpSampling` type. + * Session-scoped approval details for MCP sampling requests from a server. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalMcpSampling". @@ -6891,7 +8275,7 @@ export interface PermissionDecisionApproveForSessionApprovalMcpSampling { serverName: string; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalMemory` type. + * Session-scoped approval details for writes to long-term memory. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalMemory". @@ -6904,7 +8288,7 @@ export interface PermissionDecisionApproveForSessionApprovalMemory { kind: "memory"; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalCustomTool` type. + * Session-scoped approval details for a custom tool, keyed by tool name. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalCustomTool". @@ -6921,7 +8305,7 @@ export interface PermissionDecisionApproveForSessionApprovalCustomTool { toolName: string; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalExtensionManagement` type. + * Session-scoped approval details for extension-management operations, optionally narrowed by operation. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalExtensionManagement". @@ -6938,7 +8322,7 @@ export interface PermissionDecisionApproveForSessionApprovalExtensionManagement operation?: string; } /** - * Schema for the `PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess` type. + * Session-scoped approval details for an extension's permission-gated capability access, keyed by extension name. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess". @@ -6955,7 +8339,7 @@ export interface PermissionDecisionApproveForSessionApprovalExtensionPermissionA extensionName: string; } /** - * Schema for the `PermissionDecisionApproveForLocation` type. + * Permission-decision request variant to approve and persist a permission for a project location, with approval details and location key. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocation". @@ -6973,7 +8357,7 @@ export interface PermissionDecisionApproveForLocation { locationKey: string; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalCommands` type. + * Location-scoped approval details for specific command identifiers. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalCommands". @@ -6990,7 +8374,7 @@ export interface PermissionDecisionApproveForLocationApprovalCommands { commandIdentifiers: string[]; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalRead` type. + * Location-scoped approval details for read-only filesystem operations. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalRead". @@ -7003,7 +8387,7 @@ export interface PermissionDecisionApproveForLocationApprovalRead { kind: "read"; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalWrite` type. + * Location-scoped approval details for filesystem write operations. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalWrite". @@ -7016,7 +8400,7 @@ export interface PermissionDecisionApproveForLocationApprovalWrite { kind: "write"; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalMcp` type. + * Location-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalMcp". @@ -7037,7 +8421,7 @@ export interface PermissionDecisionApproveForLocationApprovalMcp { toolName: string | null; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalMcpSampling` type. + * Location-scoped approval details for MCP sampling requests from a server. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalMcpSampling". @@ -7054,7 +8438,7 @@ export interface PermissionDecisionApproveForLocationApprovalMcpSampling { serverName: string; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalMemory` type. + * Location-scoped approval details for writes to long-term memory. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalMemory". @@ -7067,7 +8451,7 @@ export interface PermissionDecisionApproveForLocationApprovalMemory { kind: "memory"; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalCustomTool` type. + * Location-scoped approval details for a custom tool, keyed by tool name. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalCustomTool". @@ -7084,7 +8468,7 @@ export interface PermissionDecisionApproveForLocationApprovalCustomTool { toolName: string; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalExtensionManagement` type. + * Location-scoped approval details for extension-management operations, optionally narrowed by operation. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalExtensionManagement". @@ -7101,7 +8485,7 @@ export interface PermissionDecisionApproveForLocationApprovalExtensionManagement operation?: string; } /** - * Schema for the `PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess` type. + * Location-scoped approval details for an extension's permission-gated capability access, keyed by extension name. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess". @@ -7118,7 +8502,7 @@ export interface PermissionDecisionApproveForLocationApprovalExtensionPermission extensionName: string; } /** - * Schema for the `PermissionDecisionApprovePermanently` type. + * Permission-decision request variant to permanently approve a URL domain across sessions. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApprovePermanently". @@ -7135,7 +8519,7 @@ export interface PermissionDecisionApprovePermanently { domain: string; } /** - * Schema for the `PermissionDecisionReject` type. + * Permission-decision request variant to reject a pending permission request, with optional feedback. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionReject". @@ -7152,7 +8536,7 @@ export interface PermissionDecisionReject { feedback?: string; } /** - * Schema for the `PermissionDecisionUserNotAvailable` type. + * Permission-decision variant indicating no user was available to confirm the request. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionUserNotAvailable". @@ -7165,7 +8549,7 @@ export interface PermissionDecisionUserNotAvailable { kind: "user-not-available"; } /** - * Schema for the `PermissionDecisionApproved` type. + * Permission-decision variant indicating the request was approved. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApproved". @@ -7178,7 +8562,7 @@ export interface PermissionDecisionApproved { kind: "approved"; } /** - * Schema for the `PermissionDecisionApprovedForSession` type. + * Permission-decision variant indicating approval was remembered for the session, with approval details. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApprovedForSession". @@ -7192,7 +8576,7 @@ export interface PermissionDecisionApprovedForSession { approval: UserToolSessionApproval; } /** - * Schema for the `PermissionDecisionApprovedForLocation` type. + * Permission-decision variant indicating approval was persisted for a project location, with approval details and location key. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionApprovedForLocation". @@ -7210,7 +8594,7 @@ export interface PermissionDecisionApprovedForLocation { locationKey: string; } /** - * Schema for the `PermissionDecisionCancelled` type. + * Permission-decision variant indicating the request was cancelled before use, with an optional reason. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionCancelled". @@ -7227,7 +8611,7 @@ export interface PermissionDecisionCancelled { reason?: string; } /** - * Schema for the `PermissionDecisionDeniedByRules` type. + * Permission-decision variant indicating explicit denial by permission rules, with the matching rules. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionDeniedByRules". @@ -7244,7 +8628,7 @@ export interface PermissionDecisionDeniedByRules { rules: PermissionRule[]; } /** - * Schema for the `PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. + * Permission-decision variant indicating no approval rule matched and user confirmation was unavailable. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser". @@ -7257,7 +8641,7 @@ export interface PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUse kind: "denied-no-approval-rule-and-could-not-request-from-user"; } /** - * Schema for the `PermissionDecisionDeniedInteractivelyByUser` type. + * Permission-decision variant indicating the user denied an interactive prompt, with optional feedback and force-reject flag. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionDeniedInteractivelyByUser". @@ -7278,7 +8662,7 @@ export interface PermissionDecisionDeniedInteractivelyByUser { forceReject?: boolean; } /** - * Schema for the `PermissionDecisionDeniedByContentExclusionPolicy` type. + * Permission-decision variant indicating denial by content-exclusion policy, with path and message. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionDeniedByContentExclusionPolicy". @@ -7299,7 +8683,7 @@ export interface PermissionDecisionDeniedByContentExclusionPolicy { message: string; } /** - * Schema for the `PermissionDecisionDeniedByPermissionRequestHook` type. + * Permission-decision variant indicating denial by a permission request hook, with optional message and interrupt flag. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionDecisionDeniedByPermissionRequestHook". @@ -7348,7 +8732,7 @@ export interface PermissionLocationAddToolApprovalParams { approval: PermissionsLocationsAddToolApprovalDetails; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsCommands` type. + * Location-persisted tool approval details for specific command identifiers. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsCommands". @@ -7365,7 +8749,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsCommands { commandIdentifiers: string[]; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsRead` type. + * Location-persisted tool approval details for read-only filesystem operations. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsRead". @@ -7378,7 +8762,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsRead { kind: "read"; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsWrite` type. + * Location-persisted tool approval details for filesystem write operations. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsWrite". @@ -7391,7 +8775,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsWrite { kind: "write"; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsMcp` type. + * Location-persisted tool approval details for an MCP server tool, or all tools when `toolName` is null. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsMcp". @@ -7412,7 +8796,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsMcp { toolName: string | null; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsMcpSampling` type. + * Location-persisted tool approval details for MCP sampling requests from a server. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsMcpSampling". @@ -7429,7 +8813,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsMcpSampling { serverName: string; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsMemory` type. + * Location-persisted tool approval details for writes to long-term memory. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsMemory". @@ -7442,7 +8826,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsMemory { kind: "memory"; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsCustomTool` type. + * Location-persisted tool approval details for a custom tool, keyed by tool name. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsCustomTool". @@ -7459,7 +8843,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsCustomTool { toolName: string; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionManagement` type. + * Location-persisted tool approval details for extension-management operations, optionally narrowed by operation. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsExtensionManagement". @@ -7476,7 +8860,7 @@ export interface PermissionsLocationsAddToolApprovalDetailsExtensionManagement { operation?: string; } /** - * Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess` type. + * Location-persisted tool approval details for an extension's permission-gated capability access, keyed by extension name. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess". @@ -7726,7 +9110,7 @@ export interface PermissionRulesSet { denied: PermissionRule[]; } /** - * Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. + * Content-exclusion policy supplied to `session.permissions.configure`, with rules, last-updated data, and scope. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsConfigureAdditionalContentExclusionPolicy". @@ -7738,7 +9122,7 @@ export interface PermissionsConfigureAdditionalContentExclusionPolicy { scope: PermissionsConfigureAdditionalContentExclusionPolicyScope; } /** - * Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRule` type. + * Single content-exclusion rule supplied to `session.permissions.configure`, with paths, match conditions, and source. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsConfigureAdditionalContentExclusionPolicyRule". @@ -7751,7 +9135,7 @@ export interface PermissionsConfigureAdditionalContentExclusionPolicyRule { source: PermissionsConfigureAdditionalContentExclusionPolicyRuleSource; } /** - * Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. + * Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsConfigureAdditionalContentExclusionPolicyRuleSource". @@ -7834,6 +9218,7 @@ export interface PermissionsFolderTrustAddTrustedResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsGetAllowAllRequest". */ +/** @experimental */ export interface PermissionsGetAllowAllRequest {} /** * Indicates whether the operation succeeded. @@ -7915,6 +9300,7 @@ export interface PermissionsPathsAddResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsPathsListRequest". */ +/** @experimental */ export interface PermissionsPathsListRequest {} /** * Indicates whether the operation succeeded. @@ -7935,6 +9321,7 @@ export interface PermissionsPathsUpdatePrimaryResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsPendingRequestsRequest". */ +/** @experimental */ export interface PermissionsPendingRequestsRequest {} /** * No parameters; clears all session-scoped tool permission approvals. @@ -7942,6 +9329,7 @@ export interface PermissionsPendingRequestsRequest {} * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsResetSessionApprovalsRequest". */ +/** @experimental */ export interface PermissionsResetSessionApprovalsRequest {} /** * Indicates whether the operation succeeded. @@ -7957,17 +9345,22 @@ export interface PermissionsResetSessionApprovalsResult { success: boolean; } /** - * Whether to enable full allow-all permissions for the session. + * Allow-all mode to apply for the session. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsSetAllowAllRequest". */ /** @experimental */ export interface PermissionsSetAllowAllRequest { + mode?: PermissionsAllowAllMode; /** - * Whether to enable full allow-all permissions + * Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. */ - enabled: boolean; + enabled?: boolean; + /** + * Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. + */ + model?: string; source?: PermissionsSetAllowAllSource; } /** @@ -8055,6 +9448,7 @@ export interface PermissionUrlsSetUnrestrictedModeParams { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PingRequest". */ +/** @experimental */ export interface PingRequest { /** * Optional message to echo back @@ -8067,6 +9461,7 @@ export interface PingRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PingResult". */ +/** @experimental */ export interface PingResult { /** * Echoed message (or default greeting) @@ -8188,7 +9583,7 @@ export interface PlanUpdateRequest { content: string; } /** - * Schema for the `Plugin` type. + * Session plugin metadata, with name, marketplace, optional version, and enabled state. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "Plugin". @@ -8304,7 +9699,7 @@ export interface PluginsInstallRequest { workingDirectory?: string; } /** - * Marketplace source to register. + * Marketplace source and optional working directory for relative-path resolution. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PluginsMarketplacesAddRequest". @@ -8315,6 +9710,10 @@ export interface PluginsMarketplacesAddRequest { * Marketplace source. Accepts the same forms as the CLI: "owner/repo" or "owner/repo#ref" (GitHub), an http/https/ssh URL (optionally with #ref), a git scp-style URL (user@host:path), or a local path. The marketplace's own name (from its manifest) is used as the registration key. */ source: string; + /** + * Working directory used to resolve relative local paths in `source`. Defaults to the server's current working directory. + */ + workingDirectory?: string; } /** * Name of the marketplace whose plugin catalog to fetch. @@ -8374,6 +9773,10 @@ export interface PluginsReloadRequest { * Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). */ reloadHooks?: boolean; + /** + * Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + */ + reloadExtensions?: boolean; /** * When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. */ @@ -8391,6 +9794,10 @@ export interface PluginsUninstallRequest { * Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the fully-qualified spec. */ name: string; + /** + * Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall when multiple installed plugins share the same name. + */ + directSourceId?: string | null; } /** * Name (or spec) of the plugin to update. @@ -8406,7 +9813,7 @@ export interface PluginsUpdateRequest { name: string; } /** - * Schema for the `PluginUpdateAllEntry` type. + * Per-plugin result from updating all plugins, with versions, skills installed, success flag, and optional error. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PluginUpdateAllEntry". @@ -8476,36 +9883,6 @@ export interface PluginUpdateResult { */ skillsInstalled: number; } -/** - * Batch of spawn events plus a cursor for follow-up polls. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PollSpawnedSessionsResult". - */ -/** @experimental */ -export interface PollSpawnedSessionsResult { - /** - * Spawn events emitted since the supplied cursor. - */ - events: SessionsPollSpawnedSessionsEvent[]; - /** - * Opaque cursor to pass back to receive only events after this batch. - */ - cursor: string; -} -/** - * Schema for the `SessionsPollSpawnedSessionsEvent` type. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SessionsPollSpawnedSessionsEvent". - */ -/** @experimental */ -export interface SessionsPollSpawnedSessionsEvent { - /** - * Session id of the newly-spawned session. - */ - sessionId: string; -} /** * BYOK providers and/or models to add to the session's registry at runtime. Both fields are optional; provide providers, models, or both. * @@ -8776,118 +10153,391 @@ export interface PushAttachmentFileLineRange { /** @experimental */ export interface PushAttachmentDirectory { /** - * Attachment type discriminator + * Attachment type discriminator + */ + type: "directory"; + /** + * Absolute directory path + */ + path: string; + /** + * User-facing display name for the attachment + */ + displayName: string; +} +/** + * Code selection attachment from an editor + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentSelection". + */ +/** @experimental */ +export interface PushAttachmentSelection { + /** + * Attachment type discriminator + */ + type: "selection"; + /** + * Absolute path to the file containing the selection + */ + filePath: string; + /** + * User-facing display name for the selection + */ + displayName: string; + /** + * The selected text content + */ + text: string; + selection: PushAttachmentSelectionDetails; +} +/** + * Position range of the selection within the file + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentSelectionDetails". + */ +/** @experimental */ +export interface PushAttachmentSelectionDetails { + start: PushAttachmentSelectionDetailsStart; + end: PushAttachmentSelectionDetailsEnd; +} +/** + * Start position of the selection + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentSelectionDetailsStart". + */ +/** @experimental */ +export interface PushAttachmentSelectionDetailsStart { + /** + * Start line number (0-based) + */ + line: number; + /** + * Start character offset within the line (0-based) + */ + character: number; +} +/** + * End position of the selection + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentSelectionDetailsEnd". + */ +/** @experimental */ +export interface PushAttachmentSelectionDetailsEnd { + /** + * End line number (0-based) + */ + line: number; + /** + * End character offset within the line (0-based) + */ + character: number; +} +/** + * GitHub issue, pull request, or discussion reference + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentGitHubReference". + */ +/** @experimental */ +export interface PushAttachmentGitHubReference { + /** + * Attachment type discriminator + */ + type: "github_reference"; + /** + * Issue, pull request, or discussion number + */ + number: number; + /** + * Title of the referenced item + */ + title: string; + referenceType: PushAttachmentGitHubReferenceType; + /** + * Current state of the referenced item (e.g., open, closed, merged) + */ + state: string; + /** + * URL to the referenced item on GitHub + */ + url: string; +} +/** + * Pointer to a GitHub commit. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentGitHubCommit". + */ +/** @experimental */ +export interface PushAttachmentGitHubCommit { + /** + * Attachment type discriminator + */ + type: "github_commit"; + repo: PushGitHubRepoRef; + /** + * Full commit SHA + */ + oid: string; + /** + * First line of the commit message + */ + message: string; + /** + * URL to the commit on GitHub + */ + url: string; +} +/** + * Pointer to a GitHub repository. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushGitHubRepoRef". + */ +/** @experimental */ +export interface PushGitHubRepoRef { + /** + * Numeric GitHub repository id + */ + id?: number; + /** + * Repository name (without owner) + */ + name: string; + /** + * Repository owner login (user or organization) + */ + owner: string; +} +/** + * Pointer to a GitHub release. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentGitHubRelease". + */ +/** @experimental */ +export interface PushAttachmentGitHubRelease { + /** + * Attachment type discriminator + */ + type: "github_release"; + repo: PushGitHubRepoRef; + /** + * Git tag the release is anchored to + */ + tagName: string; + /** + * Human-readable release name + */ + name: string; + /** + * URL to the release on GitHub + */ + url: string; +} +/** + * Pointer to a GitHub Actions job. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentGitHubActionsJob". + */ +/** @experimental */ +export interface PushAttachmentGitHubActionsJob { + /** + * Attachment type discriminator + */ + type: "github_actions_job"; + repo: PushGitHubRepoRef; + /** + * Job id within the workflow run + */ + jobId: number; + /** + * Display name of the job + */ + jobName: string; + /** + * Display name of the workflow the job ran in + */ + workflowName: string; + /** + * URL to the job on GitHub + */ + url: string; + /** + * Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. + */ + conclusion?: string; +} +/** + * Pointer to a GitHub repository. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentGitHubRepository". + */ +/** @experimental */ +export interface PushAttachmentGitHubRepository { + /** + * Attachment type discriminator + */ + type: "github_repository"; + repo: PushGitHubRepoRef; + /** + * URL to the repository on GitHub + */ + url: string; + /** + * Short description of the repository + */ + description?: string; + /** + * Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. + */ + ref?: string; +} +/** + * Pointer to a single-file diff. At least one of `head` and `base` must be present. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentGitHubFileDiff". + */ +/** @experimental */ +export interface PushAttachmentGitHubFileDiff { + /** + * Attachment type discriminator + */ + type: "github_file_diff"; + /** + * URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) + */ + url: string; + head?: PushAttachmentGitHubFileDiffSide; + base?: PushAttachmentGitHubFileDiffSide; +} +/** + * One side of a file diff (head or base) + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PushAttachmentGitHubFileDiffSide". + */ +/** @experimental */ +export interface PushAttachmentGitHubFileDiffSide { + repo: PushGitHubRepoRef; + /** + * Git ref (branch, tag, or commit SHA) the file is read at */ - type: "directory"; + ref: string; /** - * Absolute directory path + * Repository-relative path to the file */ path: string; - /** - * User-facing display name for the attachment - */ - displayName: string; } /** - * Code selection attachment from an editor + * Pointer to a comparison between two git revisions. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PushAttachmentSelection". + * via the `definition` "PushAttachmentGitHubTreeComparison". */ /** @experimental */ -export interface PushAttachmentSelection { +export interface PushAttachmentGitHubTreeComparison { /** * Attachment type discriminator */ - type: "selection"; - /** - * Absolute path to the file containing the selection - */ - filePath: string; - /** - * User-facing display name for the selection - */ - displayName: string; + type: "github_tree_comparison"; /** - * The selected text content + * URL to the comparison on GitHub */ - text: string; - selection: PushAttachmentSelectionDetails; + url: string; + base: PushAttachmentGitHubTreeComparisonSide; + head: PushAttachmentGitHubTreeComparisonSide; } /** - * Position range of the selection within the file + * One side of a tree comparison (head or base) * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PushAttachmentSelectionDetails". + * via the `definition` "PushAttachmentGitHubTreeComparisonSide". */ /** @experimental */ -export interface PushAttachmentSelectionDetails { - start: PushAttachmentSelectionDetailsStart; - end: PushAttachmentSelectionDetailsEnd; +export interface PushAttachmentGitHubTreeComparisonSide { + repo: PushGitHubRepoRef; + /** + * Git revision (branch, tag, or commit SHA) + */ + revision: string; } /** - * Start position of the selection + * Generic GitHub URL reference. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PushAttachmentSelectionDetailsStart". + * via the `definition` "PushAttachmentGitHubUrl". */ /** @experimental */ -export interface PushAttachmentSelectionDetailsStart { +export interface PushAttachmentGitHubUrl { /** - * Start line number (0-based) + * Attachment type discriminator */ - line: number; + type: "github_url"; /** - * Start character offset within the line (0-based) + * URL to the GitHub resource */ - character: number; + url: string; } /** - * End position of the selection + * Pointer to a file in a GitHub repository at a specific ref. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PushAttachmentSelectionDetailsEnd". + * via the `definition` "PushAttachmentGitHubFile". */ /** @experimental */ -export interface PushAttachmentSelectionDetailsEnd { +export interface PushAttachmentGitHubFile { /** - * End line number (0-based) + * Attachment type discriminator */ - line: number; + type: "github_file"; + repo: PushGitHubRepoRef; /** - * End character offset within the line (0-based) + * Git ref the file is read at (branch, tag, or commit SHA) */ - character: number; + ref: string; + /** + * Repository-relative path to the file + */ + path: string; + /** + * URL to the file on GitHub + */ + url: string; } /** - * GitHub issue, pull request, or discussion reference + * Pointer to a line range inside a file in a GitHub repository. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PushAttachmentGitHubReference". + * via the `definition` "PushAttachmentGitHubSnippet". */ /** @experimental */ -export interface PushAttachmentGitHubReference { +export interface PushAttachmentGitHubSnippet { /** * Attachment type discriminator */ - type: "github_reference"; - /** - * Issue, pull request, or discussion number - */ - number: number; + type: "github_snippet"; + repo: PushGitHubRepoRef; /** - * Title of the referenced item + * Git ref the file is read at (branch, tag, or commit SHA) */ - title: string; - referenceType: PushAttachmentGitHubReferenceType; + ref: string; /** - * Current state of the referenced item (e.g., open, closed, merged) + * Repository-relative path to the file */ - state: string; + path: string; /** - * URL to the referenced item on GitHub + * URL to the snippet on GitHub (with line anchor) */ url: string; + lineRange: PushAttachmentFileLineRange; } /** * Blob attachment with inline base64-encoded data @@ -8915,7 +10565,7 @@ export interface PushAttachmentBlob { displayName?: string; } /** - * Schema for the `QueuePendingItems` type. + * User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "QueuePendingItems". @@ -8967,7 +10617,7 @@ export interface QueueRemoveMostRecentResult { /** @experimental */ export interface RegisterEventInterestParams { /** - * The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates the full interactive OAuth flow to the consumer; when no interest is registered the runtime installs a browserless fallback that silently reuses cached tokens). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. + * The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. */ eventType: string; } @@ -9168,6 +10818,12 @@ export interface RemoteControlStatusActive { promptManager?: { [k: string]: unknown | undefined; }; + /** + * True while a read-only/session-sync export is deferred, awaiting the first `user.message` before its MC session exists. Marked internal: this field is excluded from the public SDK surface and is populated only on the CLI in-process path. + * + * @internal + */ + awaitingFirstMessage?: boolean; } /** * The last setup attempt failed. The singleton is otherwise off. @@ -9460,14 +11116,6 @@ export interface SandboxConfigUserPolicyNetwork { * Whether traffic to local/loopback addresses is allowed. */ allowLocalNetwork?: boolean; - /** - * Hosts allowed in addition to the base policy. - */ - allowedHosts?: string[]; - /** - * Hosts explicitly blocked. - */ - blockedHosts?: string[]; } /** * macOS seatbelt-specific options. @@ -9506,7 +11154,7 @@ export interface SandboxConfigUserPolicyExperimentalSeatbelt { keychainAccess?: boolean; } /** - * Schema for the `ScheduleEntry` type. + * Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ScheduleEntry". @@ -9596,6 +11244,7 @@ export interface ScheduleStopResult { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SecretsAddFilterValuesRequest". */ +/** @experimental */ export interface SecretsAddFilterValuesRequest { /** * Raw secret values to register for redaction @@ -9608,6 +11257,7 @@ export interface SecretsAddFilterValuesRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SecretsAddFilterValuesResult". */ +/** @experimental */ export interface SecretsAddFilterValuesResult { /** * Whether the values were successfully registered @@ -9631,6 +11281,93 @@ export interface SendAttachmentsToMessageParams { */ attachments: PushAttachment[]; } +/** + * A single user message to append to the session as part of a `session.sendMessages` turn + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SendMessageItem". + */ +/** @experimental */ +export interface SendMessageItem { + /** + * The user message text + */ + prompt: string; + /** + * If provided, this is shown in the timeline instead of `prompt` + */ + displayPrompt?: string; + /** + * Optional attachments (files, directories, selections, blobs, GitHub references) to include with this message + */ + attachments?: Attachment[]; + /** + * If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. + * + * @internal + */ + billable?: boolean; + /** + * If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange + */ + requiredTool?: string; + /** + * Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. + * + * @internal + */ + source?: string; +} +/** + * Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SendMessagesRequest". + */ +/** @experimental */ +export interface SendMessagesRequest { + /** + * The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. + */ + messages: SendMessageItem[]; + mode?: SendMode; + /** + * If true, adds the messages to the front of the queue instead of the end + */ + prepend?: boolean; + agentMode?: SendAgentMode; + /** + * Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. + */ + requestHeaders?: { + [k: string]: string | undefined; + }; + /** + * W3C Trace Context traceparent header for distributed tracing of this agent turn + */ + traceparent?: string; + /** + * W3C Trace Context tracestate header for distributed tracing + */ + tracestate?: string; + /** + * If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. + */ + wait?: boolean; +} +/** + * Result of sending zero or more user messages + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SendMessagesResult". + */ +/** @experimental */ +export interface SendMessagesResult { + /** + * Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. + */ + messageIds: string[]; +} /** * Parameters for sending a user message to the session * @@ -9730,11 +11467,12 @@ export interface ServerInstructionSourceList { sources: InstructionSource[]; } /** - * Schema for the `ServerSkill` type. + * Server-side skill metadata, including name, description, source, enabled/invocable state, path, project path, and argument hint. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ServerSkill". */ +/** @experimental */ export interface ServerSkill { /** * Unique identifier for the skill @@ -9772,6 +11510,7 @@ export interface ServerSkill { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ServerSkillList". */ +/** @experimental */ export interface ServerSkillList { /** * All discovered skills across all sources @@ -9979,7 +11718,7 @@ export interface SessionFsReaddirResult { error?: SessionFsError; } /** - * Schema for the `SessionFsReaddirWithTypesEntry` type. + * Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionFsReaddirWithTypesEntry". @@ -10106,6 +11845,7 @@ export interface SessionFsRmRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionFsSetProviderCapabilities". */ +/** @experimental */ export interface SessionFsSetProviderCapabilities { /** * Whether the provider supports SQLite query/exists operations @@ -10118,6 +11858,7 @@ export interface SessionFsSetProviderCapabilities { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionFsSetProviderRequest". */ +/** @experimental */ export interface SessionFsSetProviderRequest { /** * Initial working directory for sessions @@ -10136,6 +11877,7 @@ export interface SessionFsSetProviderRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionFsSetProviderResult". */ +/** @experimental */ export interface SessionFsSetProviderResult { /** * Whether the provider was set successfully @@ -10280,7 +12022,7 @@ export interface SessionFsWriteFileRequest { mode?: number; } /** - * Schema for the `SessionInstalledPlugin` type. + * Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionInstalledPlugin". @@ -10314,7 +12056,7 @@ export interface SessionInstalledPlugin { source?: SessionInstalledPluginSource; } /** - * Schema for the `SessionInstalledPluginSourceGitHub` type. + * Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionInstalledPluginSourceGitHub". @@ -10330,7 +12072,7 @@ export interface SessionInstalledPluginSourceGitHub { path?: string; } /** - * Schema for the `SessionInstalledPluginSourceUrl` type. + * Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionInstalledPluginSourceUrl". @@ -10346,7 +12088,7 @@ export interface SessionInstalledPluginSourceUrl { path?: string; } /** - * Schema for the `SessionInstalledPluginSourceLocal` type. + * Source descriptor for a direct local plugin install, with a local filesystem path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionInstalledPluginSourceLocal". @@ -10468,6 +12210,10 @@ export interface SessionMetadataSnapshot { * Currently selected model identifier, if any */ selectedModel?: string; + /** + * Current session limits, or null when no limits are active + */ + sessionLimits: SessionLimitsConfig | null; /** * Public-facing workspace metadata for this session, or null if the session has no associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, internal flags). */ @@ -10485,6 +12231,10 @@ export interface SessionModelList { * Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). */ list: unknown[]; + /** + * Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. + */ + modelPriceCategories?: SessionModelPriceCategory[]; /** * Per-quota snapshots returned alongside the model list, keyed by quota type. */ @@ -10492,6 +12242,17 @@ export interface SessionModelList { [k: string]: unknown | undefined; }; } +/** + * Cost-category metadata for a CAPI model. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionModelPriceCategory". + */ +/** @experimental */ +export interface SessionModelPriceCategory { + id: string; + priceCategory: ModelPickerPriceCategory; +} /** * Session construction options. * @@ -10517,6 +12278,7 @@ export interface SessionOpenOptions { */ reasoningEffort?: string; reasoningSummary?: SessionOpenOptionsReasoningSummary; + verbosity?: Verbosity; /** * Identifier of the client driving the session. */ @@ -10541,6 +12303,10 @@ export interface SessionOpenOptions { expAssignments?: { [k: string]: unknown | undefined; }; + /** + * Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. + */ + enableManagedSettings?: boolean; /** * Feature-flag values resolved by the host. */ @@ -10599,6 +12365,14 @@ export interface SessionOpenOptions { * Denylist of tool names. */ excludedTools?: string[]; + /** + * Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. + */ + includedBuiltinAgents?: string[]; + /** + * Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. + */ + excludedBuiltinAgents?: string[]; /** * Whether shell-script safety heuristics are enabled. */ @@ -10617,6 +12391,10 @@ export interface SessionOpenOptions { */ logInteractiveShells?: boolean; envValueMode?: SessionOpenOptionsEnvValueMode; + /** + * Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. + */ + allowAllMcpServerInstructions?: boolean; /** * Additional directories to search for skills. */ @@ -10684,6 +12462,7 @@ export interface SessionOpenOptions { */ maxInlineBinaryBytes?: number; modelCapabilitiesOverrides?: ModelCapabilitiesOverride; + sessionLimits?: SessionLimitsConfig; /** * Runtime context discriminator for agent filtering. */ @@ -10709,7 +12488,7 @@ export interface SessionOpenOptions { sessionCapabilities?: SessionCapability[]; } /** - * Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicy` type. + * Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated data, and scope. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionOpenOptionsAdditionalContentExclusionPolicy". @@ -10721,7 +12500,7 @@ export interface SessionOpenOptionsAdditionalContentExclusionPolicy { scope: SessionOpenOptionsAdditionalContentExclusionPolicyScope; } /** - * Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRule` type. + * Single content-exclusion rule supplied to `sessions.open` options, with paths, match conditions, and source. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionOpenOptionsAdditionalContentExclusionPolicyRule". @@ -10734,7 +12513,7 @@ export interface SessionOpenOptionsAdditionalContentExclusionPolicyRule { source: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource; } /** - * Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type. + * Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource". @@ -10893,6 +12672,14 @@ export interface SessionsOpenHandoff { onProgress?: { [k: string]: unknown | undefined; }; + /** + * In-process confirmation callback `(request) => boolean | Promise` invoked when the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch between the current working directory and the remote session). Returning `true` proceeds with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal because a function reference cannot cross the JSON-RPC boundary, for the same reasons as `onProgress`. + * + * @internal + */ + onConfirm?: { + [k: string]: unknown | undefined; + }; } /** * Result of opening a session. @@ -10932,7 +12719,7 @@ export interface SessionOpenResult { progress?: SessionsOpenProgress[]; } /** - * Schema for the `SessionsOpenProgress` type. + * `sessions.open` handoff progress update with step, status, and optional message. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionsOpenProgress". @@ -11070,6 +12857,138 @@ export interface SessionSetCredentialsResult { * Whether the operation succeeded */ success: boolean; + /** + * Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). + */ + copilotUserResolved?: boolean; +} +/** + * Availability of built-in job tools surfaced to boundary consumers. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsBuiltInToolAvailabilitySnapshot". + */ +/** @experimental */ +export interface SessionSettingsBuiltInToolAvailabilitySnapshot { + reportProgress?: boolean; + createPullRequest?: boolean; +} +/** + * Named Rust-owned settings predicate to evaluate for this session. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsEvaluatePredicateRequest". + */ +/** @experimental */ +export interface SessionSettingsEvaluatePredicateRequest { + name: SessionSettingsPredicateName; + /** + * Tool name for tool-scoped predicates such as trivial-change handling. + */ + toolName?: string; +} +/** + * Result of evaluating a Rust-owned settings predicate. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsEvaluatePredicateResult". + */ +/** @experimental */ +export interface SessionSettingsEvaluatePredicateResult { + enabled: boolean; +} +/** + * Redacted job settings for a session. The job nonce is excluded. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsJobSnapshot". + */ +/** @experimental */ +export interface SessionSettingsJobSnapshot { + eventType?: string; + isTriggerJob?: boolean; + builtInToolAvailability?: SessionSettingsBuiltInToolAvailabilitySnapshot; +} +/** + * Redacted model routing settings for a session. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsModelSnapshot". + */ +/** @experimental */ +export interface SessionSettingsModelSnapshot { + model?: string; + defaultReasoningEffort?: string; + instanceId?: string; + callbackUrl?: string; +} +/** + * Online-evaluation settings safe to expose across the SDK boundary. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsOnlineEvaluationSnapshot". + */ +/** @experimental */ +export interface SessionSettingsOnlineEvaluationSnapshot { + disableOnlineEvaluation?: boolean; + enableOnlineEvaluationOutputFile?: boolean; +} +/** + * Redacted repository and GitHub host settings for a session. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsRepoSnapshot". + */ +/** @experimental */ +export interface SessionSettingsRepoSnapshot { + name?: string; + id?: number; + branch?: string; + commit?: string; + readWrite?: boolean; + ownerName?: string; + ownerId?: number; + serverUrl?: string; + host?: string; + hostProtocol?: string; + secretScanningUrl?: string; + prCommitCount?: number; +} +/** + * Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsSnapshot". + */ +/** @experimental */ +export interface SessionSettingsSnapshot { + version?: string; + clientName?: string; + timeoutMs?: number; + startTimeMs?: number; + repo: SessionSettingsRepoSnapshot; + model: SessionSettingsModelSnapshot; + validation: SessionSettingsValidationSnapshot; + job: SessionSettingsJobSnapshot; + onlineEvaluation: SessionSettingsOnlineEvaluationSnapshot; +} +/** + * Redacted validation and memory-tool settings for a session. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionSettingsValidationSnapshot". + */ +/** @experimental */ +export interface SessionSettingsValidationSnapshot { + timeout?: number; + dependabotTimeout?: number; + codeqlEnabled?: boolean; + codeReviewEnabled?: boolean; + codeReviewModel?: string; + advisoryEnabled?: boolean; + secretScanningEnabled?: boolean; + memoryStoreEnabled?: boolean; + memoryVoteEnabled?: boolean; } /** * UUID prefix to resolve to a unique session ID. @@ -11313,18 +13232,6 @@ export interface SessionsLoadDeferredRepoHooksRequest { */ sessionId: string; } - -/** @experimental */ -export interface SessionsPollSpawnedSessionsRequest { - /** - * Opaque cursor returned by a previous poll. Omit on the first call to receive any spawn events buffered since the runtime started. - */ - cursor?: string; - /** - * Milliseconds to wait for new spawn events when the cursor is at the tail. 0 (default) returns immediately even if no events are buffered. Capped at 60000ms. - */ - waitMs?: number; -} /** * Age threshold and optional flags controlling which old sessions are pruned (or simulated when dryRun is true). * @@ -11525,6 +13432,7 @@ export interface SessionUpdateOptionsParams { */ reasoningEffort?: string; reasoningSummary?: OptionsUpdateReasoningSummary; + verbosity?: Verbosity; /** * Identifier of the client driving the session. */ @@ -11561,6 +13469,14 @@ export interface SessionUpdateOptionsParams { * Denylist of tool names for this session. */ excludedTools?: string[]; + /** + * Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. + */ + includedBuiltinAgents?: string[] | null; + /** + * Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. + */ + excludedBuiltinAgents?: string[]; toolFilterPrecedence?: OptionsUpdateToolFilterPrecedence; /** * Whether shell-script safety heuristics are enabled. @@ -11580,6 +13496,10 @@ export interface SessionUpdateOptionsParams { */ logInteractiveShells?: boolean; envValueMode?: OptionsUpdateEnvValueMode; + /** + * Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. + */ + allowAllMcpServerInstructions?: boolean; /** * Additional directories to search for skills. */ @@ -11695,6 +13615,10 @@ export interface SessionUpdateOptionsParams { */ enableSkills?: boolean; contextTier?: OptionsUpdateContextTier; + /** + * Optional session limits. Pass null to clear the session limits. + */ + sessionLimits?: SessionLimitsConfig | null; } /** * Indicates whether the session options patch was applied successfully. @@ -11708,6 +13632,10 @@ export interface SessionUpdateOptionsResult { * Whether the operation succeeded */ success: boolean; + /** + * Number of hooks loaded from installed plugins, returned when installedPlugins is updated + */ + pluginHookCount?: number; } /** * User-requested shell execution cancellation handle. @@ -11815,7 +13743,7 @@ export interface ShutdownRequest { reason?: string; } /** - * Schema for the `Skill` type. + * Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "Skill". @@ -11853,7 +13781,7 @@ export interface Skill { argumentHint?: string; } /** - * Schema for the `SkillDiscoveryPath` type. + * Canonical directory where skills can be discovered or created, with scope, preference, and optional project path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SkillDiscoveryPath". @@ -11906,6 +13834,7 @@ export interface SkillList { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SkillsConfigSetDisabledSkillsRequest". */ +/** @experimental */ export interface SkillsConfigSetDisabledSkillsRequest { /** * List of skill names to disable @@ -11931,6 +13860,7 @@ export interface SkillsDisableRequest { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SkillsDiscoverRequest". */ +/** @experimental */ export interface SkillsDiscoverRequest { /** * Optional list of project directory paths to scan for project-scoped skills @@ -11989,7 +13919,7 @@ export interface SkillsGetInvokedResult { skills: SkillsInvokedSkill[]; } /** - * Schema for the `SkillsInvokedSkill` type. + * Skill invocation record with name, path, content, allowed tools, and turn number. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SkillsInvokedSkill". @@ -12035,7 +13965,7 @@ export interface SkillsLoadDiagnostics { errors: string[]; } /** - * Schema for the `SlashCommandAgentPromptResult` type. + * Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SlashCommandAgentPromptResult". @@ -12055,13 +13985,17 @@ export interface SlashCommandAgentPromptResult { */ displayPrompt: string; mode?: SessionMode; + /** + * Optional user-facing notice to show before the prompt is submitted + */ + notice?: string; /** * True when the invocation mutated user runtime settings; consumers caching settings should refresh */ runtimeSettingsChanged?: boolean; } /** - * Schema for the `SlashCommandCompletedResult` type. + * Slash-command invocation result indicating completion, with optional message and settings-change flag. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SlashCommandCompletedResult". @@ -12082,7 +14016,7 @@ export interface SlashCommandCompletedResult { runtimeSettingsChanged?: boolean; } /** - * Schema for the `SlashCommandTextResult` type. + * Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SlashCommandTextResult". @@ -12111,7 +14045,7 @@ export interface SlashCommandTextResult { runtimeSettingsChanged?: boolean; } /** - * Schema for the `SlashCommandSelectSubcommandResult` type. + * Slash-command invocation result asking the client to present subcommand options for a parent command. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SlashCommandSelectSubcommandResult". @@ -12140,7 +14074,7 @@ export interface SlashCommandSelectSubcommandResult { runtimeSettingsChanged?: boolean; } /** - * Schema for the `SlashCommandSelectSubcommandOption` type. + * Selectable slash-command subcommand option with name, description, and optional group label. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SlashCommandSelectSubcommandOption". @@ -12179,7 +14113,7 @@ export interface SubagentSettingsEntry { contextTier?: SubagentSettingsEntryContextTier; } /** - * Schema for the `TaskAgentInfo` type. + * Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "TaskAgentInfo". @@ -12258,7 +14192,7 @@ export interface TaskAgentInfo { idleSince?: string; } /** - * Schema for the `TaskAgentProgress` type. + * Progress snapshot for an agent task, with recent activity lines and optional latest intent. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "TaskAgentProgress". @@ -12279,7 +14213,7 @@ export interface TaskAgentProgress { latestIntent?: string; } /** - * Schema for the `TaskProgressLine` type. + * Timestamped display line for task progress output or recent agent activity. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "TaskProgressLine". @@ -12296,7 +14230,7 @@ export interface TaskProgressLine { timestamp: string; } /** - * Schema for the `TaskShellInfo` type. + * Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "TaskShellInfo". @@ -12357,7 +14291,7 @@ export interface TaskList { tasks: TaskInfo[]; } /** - * Schema for the `TaskShellProgress` type. + * Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "TaskShellProgress". @@ -12613,11 +14547,12 @@ export interface TelemetrySetFeatureOverridesRequest { }; } /** - * Schema for the `Tool` type. + * Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "Tool". */ +/** @experimental */ export interface Tool { /** * Tool identifier (e.g., "bash", "grep", "str_replace_editor") @@ -12648,6 +14583,7 @@ export interface Tool { * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ToolList". */ +/** @experimental */ export interface ToolList { /** * List of available built-in tools with metadata @@ -12681,6 +14617,7 @@ export interface ToolsInitializeAndValidateResult {} * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ToolsListRequest". */ +/** @experimental */ export interface ToolsListRequest { /** * Optional model ID — when provided, the returned tool list reflects model-specific overrides @@ -12743,7 +14680,7 @@ export interface UIElicitationArrayAnyOfFieldItems { anyOf: UIElicitationArrayAnyOfFieldItemsAnyOf[]; } /** - * Schema for the `UIElicitationArrayAnyOfFieldItemsAnyOf` type. + * Selectable option for a UI elicitation multi-select array item, with submitted value and display label. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UIElicitationArrayAnyOfFieldItemsAnyOf". @@ -12910,7 +14847,7 @@ export interface UIElicitationStringOneOfField { default?: string; } /** - * Schema for the `UIElicitationStringOneOfFieldOneOf` type. + * Selectable option for a UI elicitation single-select string field, with submitted value and display label. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UIElicitationStringOneOfFieldOneOf". @@ -13092,7 +15029,7 @@ export interface UIEphemeralQueryResult { answer: string; } /** - * Schema for the `UIExitPlanModeResponse` type. + * User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UIExitPlanModeResponse". @@ -13192,6 +15129,38 @@ export interface UIHandlePendingSamplingRequest { export interface UIHandlePendingSamplingResponse { [k: string]: unknown | undefined; } +/** + * Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UIHandlePendingSessionLimitsExhaustedRequest". + */ +/** @experimental */ +export interface UIHandlePendingSessionLimitsExhaustedRequest { + /** + * The unique request ID from the session_limits_exhausted.requested event + */ + requestId: string; + response: UISessionLimitsExhaustedResponse; +} +/** + * The user's selected action for an exhausted session limit. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UISessionLimitsExhaustedResponse". + */ +/** @experimental */ +export interface UISessionLimitsExhaustedResponse { + action: UISessionLimitsExhaustedResponseAction; + /** + * AI Credits to add to the current max when action is 'add'. + */ + additionalAiCredits?: number; + /** + * New absolute max AI Credits when action is 'set'. + */ + maxAiCredits?: number; +} /** * Request ID of a pending `user_input.requested` event and the user's response. * @@ -13207,7 +15176,7 @@ export interface UIHandlePendingUserInputRequest { response: UIUserInputResponse; } /** - * Schema for the `UIUserInputResponse` type. + * User response for a pending user-input request, with answer text and whether it was typed freeform. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UIUserInputResponse". @@ -13330,7 +15299,7 @@ export interface UsageGetMetricsResult { lastCallOutputTokens: number; } /** - * Schema for the `UsageMetricsTokenDetail` type. + * Session-wide token-detail entry containing the accumulated token count for one token type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UsageMetricsTokenDetail". @@ -13368,7 +15337,7 @@ export interface UsageMetricsCodeChanges { filesModified: string[]; } /** - * Schema for the `UsageMetricsModelMetric` type. + * Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UsageMetricsModelMetric". @@ -13435,7 +15404,7 @@ export interface UsageMetricsModelMetricUsage { reasoningTokens?: number; } /** - * Schema for the `UsageMetricsModelMetricTokenDetail` type. + * Per-model token-detail entry containing the accumulated token count for one token type. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "UsageMetricsModelMetricTokenDetail". @@ -13476,6 +15445,120 @@ export interface UserRequestedShellCommandResult { */ error?: string; } +/** + * A single user setting's effective value alongside its default, so consumers can render settings left at their default. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UserSettingMetadata". + */ +/** @experimental */ +export interface UserSettingMetadata { + /** + * The effective value: the user's value if set, otherwise the default. + */ + value: { + [k: string]: unknown | undefined; + }; + /** + * The centrally-known default for this setting (null when no default is registered). + */ + default: { + [k: string]: unknown | undefined; + }; + /** + * True when the user has not set an explicit value for this setting (i.e. it is left at its default). Reflects whether the user has overridden the key, not whether the effective value happens to equal the default — a key explicitly set to a value identical to the default still reports false. + */ + isDefault: boolean; +} +/** + * Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UserSettingsGetResult". + */ +/** @experimental */ +export interface UserSettingsGetResult { + /** + * Every known user setting keyed by setting name, each with its effective value, default, and whether it is at the default. + */ + settings: { + [k: string]: UserSettingMetadata; + }; +} +/** + * Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UserSettingsSetRequest". + */ +/** @experimental */ +export interface UserSettingsSetRequest { + /** + * Partial user settings to write, as a free-form object keyed by setting name + */ + settings: { + [k: string]: unknown | undefined; + }; +} +/** + * Outcome of writing user settings. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "UserSettingsSetResult". + */ +/** @experimental */ +export interface UserSettingsSetResult { + /** + * Top-level keys whose write landed in settings.json but is shadowed by a value still present in the legacy config.json (config.json wins on read). The write does not take effect until the legacy value is removed. + */ + shadowedKeys: string[]; +} +/** + * Current sharing status and shareable GitHub URL for a session. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "VisibilityGetResult". + */ +/** @experimental */ +export interface VisibilityGetResult { + /** + * Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. + */ + synced: boolean; + status?: SessionVisibilityStatus; + /** + * Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + */ + shareUrl?: string; +} +/** + * Desired sharing status for the session. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "VisibilitySetRequest". + */ +/** @experimental */ +export interface VisibilitySetRequest { + status: SessionVisibilityStatus; +} +/** + * Effective sharing status and shareable GitHub URL after updating session visibility. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "VisibilitySetResult". + */ +/** @experimental */ +export interface VisibilitySetResult { + /** + * Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. + */ + synced: boolean; + status?: SessionVisibilityStatus; + /** + * Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + */ + shareUrl?: string; +} /** * A single changed file and its unified diff. * @@ -13526,7 +15609,7 @@ export interface WorkspaceDiffResult { isFallback: boolean; } /** - * Schema for the `WorkspacesCheckpoints` type. + * Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "WorkspacesCheckpoints". @@ -13762,9 +15845,12 @@ export function createServerRpc(connection: MessageConnection) { * @param params Optional message to echo back to the caller. * * @returns Server liveness response, including the echoed message, current server timestamp, and protocol version. + * + * @experimental */ ping: async (params: PingRequest): Promise => connection.sendRequest("ping", params), + /** @experimental */ models: { /** * Lists Copilot models available to the authenticated user. @@ -13776,6 +15862,7 @@ export function createServerRpc(connection: MessageConnection) { list: async (params: ModelsListRequest): Promise => connection.sendRequest("models.list", params), }, + /** @experimental */ tools: { /** * Lists built-in tools available for a model. @@ -13787,6 +15874,7 @@ export function createServerRpc(connection: MessageConnection) { list: async (params: ToolsListRequest): Promise => connection.sendRequest("tools.list", params), }, + /** @experimental */ account: { /** * Gets Copilot quota usage for the authenticated user or supplied GitHub token. @@ -13830,6 +15918,7 @@ export function createServerRpc(connection: MessageConnection) { logout: async (params: AccountLogoutRequest): Promise => connection.sendRequest("account.logout", params), }, + /** @experimental */ secrets: { /** * Registers secret values for redaction in session logs and exports. The SDK calls this to inject dynamically generated secret values (e.g., OIDC tokens). @@ -13841,7 +15930,9 @@ export function createServerRpc(connection: MessageConnection) { addFilterValues: async (params: SecretsAddFilterValuesRequest): Promise => connection.sendRequest("secrets.addFilterValues", params), }, + /** @experimental */ mcp: { + /** @experimental */ config: { /** * Lists MCP servers from user configuration. @@ -13968,7 +16059,7 @@ export function createServerRpc(connection: MessageConnection) { /** * Registers a new marketplace from a source (owner/repo, URL, or local path). * - * @param params Marketplace source to register. + * @param params Marketplace source and optional working directory for relative-path resolution. * * @returns Result of registering a new marketplace. */ @@ -14003,7 +16094,9 @@ export function createServerRpc(connection: MessageConnection) { connection.sendRequest("plugins.marketplaces.refresh", params), }, }, + /** @experimental */ skills: { + /** @experimental */ config: { /** * Replaces the global list of disabled skills. @@ -14028,8 +16121,6 @@ export function createServerRpc(connection: MessageConnection) { * @param params Optional project paths to enumerate. * * @returns Canonical locations where skills can be created so the runtime will recognize them. - * - * @experimental */ getDiscoveryPaths: async (params: SkillsGetDiscoveryPathsRequest): Promise => connection.sendRequest("skills.getDiscoveryPaths", params), @@ -14076,15 +16167,44 @@ export function createServerRpc(connection: MessageConnection) { getDiscoveryPaths: async (params: InstructionsGetDiscoveryPathsRequest): Promise => connection.sendRequest("instructions.getDiscoveryPaths", params), }, + /** @experimental */ + commands: { + /** + * Lists the well-known built-in slash commands that work as the first message in a new session (e.g. /plan, /env), without requiring an active session. Commands that depend on session state, authentication, or a synced session are omitted. + * + * @returns Slash commands available in the session, after applying any include/exclude filters. + */ + list: async (): Promise => + connection.sendRequest("commands.list", {}), + }, + /** @experimental */ user: { + /** @experimental */ settings: { /** * Drops this runtime process's in-memory user settings cache so the next settings read observes disk. */ reload: async (): Promise => connection.sendRequest("user.settings.reload", {}), + /** + * Lists every known user setting (settings.json overlaid with the legacy config.json, config.json wins), each with its effective value, its default, and whether it is at the default — so settings the user has never set still appear with their default value. Does not include repository- or enterprise-managed overrides that the runtime layers on top at session time. + * + * @returns Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. + */ + get: async (): Promise => + connection.sendRequest("user.settings.get", {}), + /** + * Writes one or more user settings to settings.json, replacing each provided top-level key. A key whose value is null is removed. Returns the keys whose new value is shadowed by a legacy config.json entry (config.json wins on read), which the runtime leaves in place — such writes do not take effect until the legacy value is removed. + * + * @param params Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. + * + * @returns Outcome of writing user settings. + */ + set: async (params: UserSettingsSetRequest): Promise => + connection.sendRequest("user.settings.set", params), }, }, + /** @experimental */ runtime: { /** * Gracefully shuts down an SDK-owned runtime. The response is sent only after cleanup completes; callers may then terminate the owned runtime process. @@ -14092,6 +16212,7 @@ export function createServerRpc(connection: MessageConnection) { shutdown: async (): Promise => connection.sendRequest("runtime.shutdown", {}), }, + /** @experimental */ sessionFs: { /** * Registers an SDK client as the session filesystem provider. @@ -14362,9 +16483,11 @@ export function createInternalServerRpc(connection: MessageConnection) { /** * Performs the SDK server connection handshake and validates the optional connection token. Marked internal because this is JSON-RPC transport plumbing invoked automatically by an SDK client's own `connect()` wrapper, not a user-facing method. Stays internal as long as the SDK client owns the handshake; would only become public if the SDK ever exposed the raw schema surface to consumers without a connection wrapper. * - * @param params Optional connection token presented by the SDK client during the handshake. + * @param params Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). * * @returns Handshake result reporting the server's protocol version and package version on success. + * + * @experimental */ connect: async (params: ConnectRequest): Promise => connection.sendRequest("connect", params), @@ -14397,15 +16520,6 @@ export function createInternalServerRpc(connection: MessageConnection) { */ getBoardEntryCount: async (params: SessionsGetBoardEntryCountRequest): Promise => connection.sendRequest("sessions.getBoardEntryCount", params), - /** - * Cursor-based long-poll for sessions spawned by the runtime (e.g. in response to a Mission Control `start_session` command). The cursor is an opaque token; pass it back to receive only spawn events that occurred AFTER the cursor was issued. Omit the cursor on the first call to receive any events buffered since the runtime started. Internal: this is a CLI background-daemon plumbing primitive. SDK consumers that need to react to runtime-spawned sessions should subscribe to a higher-level event stream rather than driving a long-poll loop. - * - * @param params Cursor and optional long-poll wait for polling runtime-spawned sessions. - * - * @returns Batch of spawn events plus a cursor for follow-up polls. - */ - pollSpawnedSessions: async (params: SessionsPollSpawnedSessionsRequest): Promise => - connection.sendRequest("sessions.pollSpawnedSessions", params), /** * Registers extension-provided tools on the given session, gated by an optional `enabled` callback. Returns an opaque unsubscribe function the caller must invoke to deregister the tools when the extension is torn down. Marked internal because `loader`, `enabled`, and the returned `unsubscribe` are in-process handles that cannot cross the JSON-RPC boundary. Disappears once extension discovery / launch / tool registration are owned by the runtime: SDK consumers will pass pure config (search paths, disabled ids) via `SessionOptions` and the runtime will resolve, launch, register, and tear down extensions itself. * @@ -14447,6 +16561,17 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ send: async (params: SendRequest): Promise => connection.sendRequest("session.send", { sessionId, ...params }), + /** + * Sends zero or more user messages to the session in a single turn and returns their message IDs. All provided messages are appended to the conversation in order, then exactly one agent turn runs over the resulting history. When the list is empty, one turn runs over the existing history with no new user message. Remote-backed (Mission Control) sessions do not support this method and will return an error. + * + * @param params Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. + * + * @returns Result of sending zero or more user messages + * + * @experimental + */ + sendMessages: async (params: SendMessagesRequest): Promise => + connection.sendRequest("session.sendMessages", { sessionId, ...params }), /** * Aborts the current agent turn. * @@ -14468,14 +16593,14 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin shutdown: async (params: ShutdownRequest): Promise => connection.sendRequest("session.shutdown", { sessionId, ...params }), /** @experimental */ - auth: { + gitHubAuth: { /** * Gets authentication status and account metadata for the session. * * @returns Authentication status and account metadata for the session. */ getStatus: async (): Promise => - connection.sendRequest("session.auth.getStatus", { sessionId }), + connection.sendRequest("session.gitHubAuth.getStatus", { sessionId }), /** * Updates the session's auth credentials used for outbound model and API requests. * @@ -14484,7 +16609,19 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin * @returns Indicates whether the credential update succeeded. */ setCredentials: async (params: SessionSetCredentialsParams): Promise => - connection.sendRequest("session.auth.setCredentials", { sessionId, ...params }), + connection.sendRequest("session.gitHubAuth.setCredentials", { sessionId, ...params }), + }, + /** @experimental */ + debug: { + /** + * Collects a redacted session debug log bundle into a local archive or staging directory. The runtime includes session-owned logs by default and accepts caller-provided diagnostic entries so host applications can add their own files without changing this API shape. + * + * @param params Options for collecting a redacted session debug bundle. + * + * @returns Result of collecting a redacted debug bundle. + */ + collectLogs: async (params: DebugCollectLogsRequest): Promise => + connection.sendRequest("session.debug.collectLogs", { sessionId, ...params }), }, /** @experimental */ canvas: { @@ -14715,6 +16852,25 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin connection.sendRequest("session.workspaces.diff", { sessionId, ...params }), }, /** @experimental */ + completions: { + /** + * Gets the characters that should trigger host-driven completions for the session. Empty disables host-driven completions (e.g. local sessions, or a relay host that does not advertise them). + * + * @returns Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). + */ + getTriggerCharacters: async (): Promise => + connection.sendRequest("session.completions.getTriggerCharacters", { sessionId }), + /** + * Requests host-driven completion items for the current composer input. Returns an empty list when the host has no items or does not support completions. + * + * @param params Request host-driven completions for the current composer input. + * + * @returns Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. + */ + request: async (params: CompletionsRequestRequest): Promise => + connection.sendRequest("session.completions.request", { sessionId, ...params }), + }, + /** @experimental */ instructions: { /** * Gets instruction sources loaded for the session. @@ -14919,7 +17075,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin list: async (): Promise => connection.sendRequest("session.mcp.list", { sessionId }), /** - * Lists the tools exposed by a connected MCP server on this session's host. + * Lists the tools exposed by a connected MCP server on this session's host. This performs a live `tools/list` request. Tool UI metadata is returned independently of whether MCP Apps rendering is enabled for the session. * * @param params Server name whose tool list should be returned. * @@ -14980,6 +17136,20 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ removeGitHub: async (): Promise => connection.sendRequest("session.mcp.removeGitHub", { sessionId }), + /** + * Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. + * + * @param params Server name and configuration for an individual MCP server start. + */ + startServer: async (params: McpStartServerRequest): Promise => + connection.sendRequest("session.mcp.startServer", { sessionId, ...params }), + /** + * Restarts an individual MCP server on the live session (stops then starts). Omit `config` for a config-free restart-by-name of an already-configured server; supply `config` to restart with a replacement configuration. Session-scoped and ephemeral: does NOT modify persistent user configuration (`mcp.config.*`). + * + * @param params Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. + */ + restartServer: async (params: McpRestartServerRequest): Promise => + connection.sendRequest("session.mcp.restartServer", { sessionId, ...params }), /** * Stops an individual MCP server on the session's host. * @@ -15018,6 +17188,18 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin connection.sendRequest("session.mcp.oauth.login", { sessionId, ...params }), }, /** @experimental */ + headers: { + /** + * Responds to a pending MCP dynamic headers refresh request. Hosts that subscribe to `mcp.headers_refresh_required` use this to provide short-lived per-server headers or to indicate that no dynamic headers are available for this refresh. + * + * @param params MCP headers refresh request id and the host response. + * + * @returns Indicates whether the pending MCP headers refresh response was accepted. + */ + handlePendingHeadersRefreshRequest: async (params: McpHeadersHandlePendingHeadersRefreshRequestRequest): Promise => + connection.sendRequest("session.mcp.headers.handlePendingHeadersRefreshRequest", { sessionId, ...params }), + }, + /** @experimental */ apps: { /** * Fetch an MCP resource (typically a `ui://` MCP App bundle, per SEP-1865) from a connected server. Requires the `mcp-apps` session capability. @@ -15070,6 +17252,36 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin diagnose: async (params: McpAppsDiagnoseRequest): Promise => connection.sendRequest("session.mcp.apps.diagnose", { sessionId, ...params }), }, + /** @experimental */ + resources: { + /** + * Fetch an MCP resource from a connected server by URI (proxies MCP `resources/read`). + * + * @param params MCP server and resource URI to fetch. + * + * @returns Resource contents returned by the MCP server. + */ + read: async (params: McpResourcesReadRequest): Promise => + connection.sendRequest("session.mcp.resources.read", { sessionId, ...params }), + /** + * Enumerate one page of resources a connected MCP server exposes (proxies MCP `resources/list`). Pass `cursor` to continue from a prior result's `nextCursor`. + * + * @param params MCP server whose resources to enumerate. + * + * @returns One page of resources advertised by the named MCP server. + */ + list: async (params: McpResourcesListRequest): Promise => + connection.sendRequest("session.mcp.resources.list", { sessionId, ...params }), + /** + * Enumerate one page of resource templates a connected MCP server exposes (proxies MCP `resources/templates/list`). Pass `cursor` to continue from a prior result's `nextCursor`. + * + * @param params MCP server whose resource templates to enumerate. + * + * @returns One page of resource templates advertised by the named MCP server. + */ + listTemplates: async (params: McpResourcesListTemplatesRequest): Promise => + connection.sendRequest("session.mcp.resources.listTemplates", { sessionId, ...params }), + }, }, /** @experimental */ plugins: { @@ -15218,7 +17430,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin * * @param params Slash command name and optional raw input string to invoke. * - * @returns Result of invoking the slash command (text output, prompt to send to the agent, or completion). + * @returns Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). */ invoke: async (params: CommandsInvokeRequest): Promise => connection.sendRequest("session.commands.invoke", { sessionId, ...params }), @@ -15332,6 +17544,15 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ handlePendingAutoModeSwitch: async (params: UIHandlePendingAutoModeSwitchRequest): Promise => connection.sendRequest("session.ui.handlePendingAutoModeSwitch", { sessionId, ...params }), + /** + * Resolves a pending `session_limits_exhausted.requested` event with the user's selected limit action. + * + * @param params Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. + * + * @returns Indicates whether the pending UI request was resolved by this call. + */ + handlePendingSessionLimitsExhausted: async (params: UIHandlePendingSessionLimitsExhaustedRequest): Promise => + connection.sendRequest("session.ui.handlePendingSessionLimitsExhausted", { sessionId, ...params }), /** * Resolves a pending `exit_plan_mode.requested` event with the user's response. * @@ -15395,18 +17616,18 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin setApproveAll: async (params: PermissionsSetApproveAllRequest): Promise => connection.sendRequest("session.permissions.setApproveAll", { sessionId, ...params }), /** - * Enables or disables full allow-all permissions (tools, paths, and URLs) for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. Unlike `setApproveAll`, this swaps in the unrestricted path and URL managers and emits `session.permissions_changed` on transition. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire. + * Sets the allow-all permission mode for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. The `on` mode swaps in unrestricted path and URL managers and emits `session.permissions_changed` on transition; the `auto` mode keeps normal prompt paths active while attaching LLM safety recommendations. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire. * - * @param params Whether to enable full allow-all permissions for the session. + * @param params Allow-all mode to apply for the session. * * @returns Indicates whether the operation succeeded and reports the post-mutation state. */ setAllowAll: async (params: PermissionsSetAllowAllRequest): Promise => connection.sendRequest("session.permissions.setAllowAll", { sessionId, ...params }), /** - * Returns whether full allow-all permissions are currently active for the session. + * Returns the current allow-all permission mode for the session. * - * @returns Current full allow-all permission state. + * @returns Current allow-all permission mode. */ getAllowAll: async (): Promise => connection.sendRequest("session.permissions.getAllowAll", { sessionId }), @@ -15597,6 +17818,22 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ contextInfo: async (params: MetadataContextInfoRequest): Promise => connection.sendRequest("session.metadata.contextInfo", { sessionId, ...params }), + /** + * Returns the experimental per-source attribution breakdown of the session's current context window as a flat list of entries (skills, subagents, MCP servers, built-in tools, plugin rollups, system/tool-definition costs, with nesting via parentId), plus the successful compaction count. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. Returns null until the session has initialized its system prompt and tool metadata. + * + * @returns Per-source attribution breakdown for the session's current context window, or null if uninitialized. + */ + getContextAttribution: async (): Promise => + connection.sendRequest("session.metadata.getContextAttribution", { sessionId }), + /** + * Returns the largest individual messages currently in the session's context window, most-expensive first. Companion to `metadata.getContextAttribution`. Returns an empty list until the session has initialized. + * + * @param params Parameters for the heaviest-messages query. + * + * @returns The heaviest individual messages in the session's context window, most-expensive first. + */ + getContextHeaviestMessages: async (params: MetadataContextHeaviestMessagesRequest): Promise => + connection.sendRequest("session.metadata.getContextHeaviestMessages", { sessionId, ...params }), /** * Records a working-directory/git context change and emits a `session.context_changed` event. * @@ -15607,11 +17844,11 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin recordContextChange: async (params: MetadataRecordContextChangeRequest): Promise => connection.sendRequest("session.metadata.recordContextChange", { sessionId, ...params }), /** - * Updates the session's recorded working directory. + * Updates the session's working directory. For local sessions the target is validated first (an absolute path that exists on disk) and the permission primary directory is re-based; a rejected validation fails the call before any session state changes. * - * @param params Absolute path to set as the session's new working directory. + * @param params Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. * - * @returns Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. + * @returns Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. */ setWorkingDirectory: async (params: MetadataSetWorkingDirectoryRequest): Promise => connection.sendRequest("session.metadata.setWorkingDirectory", { sessionId, ...params }), @@ -15802,6 +18039,25 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin connection.sendRequest("session.remote.notifySteerableChanged", { sessionId, ...params }), }, /** @experimental */ + visibility: { + /** + * Returns the session's current Mission Control sharing status and shareable GitHub URL. Reflects whether the synced session is visible to repository readers ("repo") or restricted to its creator and collaborators ("unshared"). + * + * @returns Current sharing status and shareable GitHub URL for a session. + */ + get: async (): Promise => + connection.sendRequest("session.visibility.get", { sessionId }), + /** + * Sets the session's Mission Control sharing status, controlling whether the synced session is visible to repository readers. Returns the effective status and shareable GitHub URL after the change. + * + * @param params Desired sharing status for the session. + * + * @returns Effective sharing status and shareable GitHub URL after updating session visibility. + */ + set: async (params: VisibilitySetRequest): Promise => + connection.sendRequest("session.visibility.set", { sessionId, ...params }), + }, + /** @experimental */ schedule: { /** * Lists the session's currently active scheduled prompts. @@ -15850,20 +18106,6 @@ export function createInternalSessionRpc(connection: MessageConnection, sessionI */ configureGitHub: async (params: McpConfigureGitHubRequest): Promise => connection.sendRequest("session.mcp.configureGitHub", { sessionId, ...params }), - /** - * Starts an individual MCP server on the session's host. - * - * @param params Server name and opaque configuration for an individual MCP server start. - */ - startServer: async (params: McpStartServerRequest): Promise => - connection.sendRequest("session.mcp.startServer", { sessionId, ...params }), - /** - * Restarts an individual MCP server on the session's host (stops then starts). - * - * @param params Server name and opaque configuration for an individual MCP server restart. - */ - restartServer: async (params: McpRestartServerRequest): Promise => - connection.sendRequest("session.mcp.restartServer", { sessionId, ...params }), /** * Registers a pre-connected external MCP client (e.g. IDE) on the session's host. The caller retains lifecycle ownership of the client and transport. Marked internal because the `client` and `transport` arguments are in-process MCP SDK instances that cannot be serialized across the JSON-RPC boundary; once the CLI moves on top of the SDK, external clients will be expressed as transport configs the runtime can construct itself. * @@ -15878,18 +18120,25 @@ export function createInternalSessionRpc(connection: MessageConnection, sessionI */ unregisterExternalClient: async (params: McpUnregisterExternalClientRequest): Promise => connection.sendRequest("session.mcp.unregisterExternalClient", { sessionId, ...params }), - /** @experimental */ - oauth: { - /** - * Responds to a pending MCP OAuth request with an in-process provider. This internal CLI-only API accepts a live OAuthClientProvider instance and cannot be used over the SDK JSON-RPC boundary. Use session.mcp.oauth.handlePendingRequest instead for the public SDK-safe response path. - * - * @param params MCP OAuth request id and optional provider response. - * - * @returns Empty result after recording the MCP OAuth response. - */ - respond: async (params: McpOauthRespondRequest): Promise => - connection.sendRequest("session.mcp.oauth.respond", { sessionId, ...params }), - }, + }, + /** @experimental */ + settings: { + /** + * Returns a redacted snapshot of session runtime settings, with secrets and raw feature flags excluded. Internal: the runtime settings shape is a runtime-internal surface and is deliberately kept out of the public SDK, because consumers should not depend on the runtime's internal settings layout. It remains callable in-process and is expected to be reworked as the runtime internals are consolidated. + * + * @returns Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. + */ + snapshot: async (): Promise => + connection.sendRequest("session.settings.snapshot", { sessionId }), + /** + * Evaluates a named Rust-owned settings predicate without exposing raw feature flags. Internal: the raw feature-flag names and composition are runtime-internal, so this predicate-evaluation helper is kept out of the public SDK surface and is callable in-process only. + * + * @param params Named Rust-owned settings predicate to evaluate for this session. + * + * @returns Result of evaluating a Rust-owned settings predicate. + */ + evaluatePredicate: async (params: SessionSettingsEvaluatePredicateRequest): Promise => + connection.sendRequest("session.settings.evaluatePredicate", { sessionId, ...params }), }, }; } @@ -16134,6 +18383,19 @@ export function registerClientSessionApiHandlers( }); } +/** Handler for `hooks` client global API methods. */ +/** @experimental */ +export interface HooksHandler { + /** + * Dispatches one SDK callback hook from the runtime to the connection that registered it. Internal transport plumbing: clients opt in through session initialization and the Rust hook processor owns ordering, policy, timeout, and callback routing. + * + * @param params Runtime-owned wire payload for a server-to-client hook callback invocation. + * + * @returns Optional output returned by an SDK callback hook. + */ + invoke(params: HookInvokeRequest): Promise; +} + /** Handler for `llmInference` client global API methods. */ /** @experimental */ export interface LlmInferenceHandler { @@ -16155,9 +18417,22 @@ export interface LlmInferenceHandler { httpRequestChunk(params: LlmInferenceHttpRequestChunkRequest): Promise; } +/** Handler for `gitHubTelemetry` client global API methods. */ +/** @experimental */ +export interface GitHubTelemetryHandler { + /** + * Forwards a single GitHub telemetry event to a host connection that opted into telemetry forwarding during the `server.connect` handshake. Opted-in connections receive every event the runtime emits after the handshake — across all sessions, plus sessionless events (for example, `server.sendTelemetry` calls with no session id). + * + * @param params Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. + */ + event(params: GitHubTelemetryNotification): Promise; +} + /** All client global API handler groups. */ export interface ClientGlobalApiHandlers { + hooks?: HooksHandler; llmInference?: LlmInferenceHandler; + gitHubTelemetry?: GitHubTelemetryHandler; } /** @@ -16171,6 +18446,11 @@ export function registerClientGlobalApiHandlers( connection: MessageConnection, handlers: ClientGlobalApiHandlers, ): void { + connection.onRequest("hooks.invoke", async (params: HookInvokeRequest) => { + const handler = handlers.hooks; + if (!handler) throw new Error("No hooks client-global handler registered"); + return handler.invoke(params); + }); connection.onRequest("llmInference.httpRequestStart", async (params: LlmInferenceHttpRequestStartRequest) => { const handler = handlers.llmInference; if (!handler) throw new Error("No llmInference client-global handler registered"); @@ -16181,4 +18461,9 @@ export function registerClientGlobalApiHandlers( if (!handler) throw new Error("No llmInference client-global handler registered"); return handler.httpRequestChunk(params); }); + connection.onNotification("gitHubTelemetry.event", async (params: GitHubTelemetryNotification) => { + const handler = handlers.gitHubTelemetry; + if (!handler) return; + await handler.event(params); + }); } diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index 96a3bddac7..7581545a8e 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -21,6 +21,7 @@ export type SessionEvent = | WarningEvent | ModelChangeEvent | ModeChangedEvent + | SessionLimitsChangedEvent | PermissionsChangedEvent | PlanChangedEvent | TodosChangedEvent @@ -29,6 +30,7 @@ export type SessionEvent = | TruncationEvent | SnapshotRewindEvent | ShutdownEvent + | UsageCheckpointEvent | ContextChangedEvent | UsageInfoEvent | CompactionStartEvent @@ -38,13 +40,16 @@ export type SessionEvent = | PendingMessagesModifiedEvent | AssistantTurnStartEvent | AssistantIntentEvent + | AssistantServerToolProgressEvent | AssistantReasoningEvent | AssistantReasoningDeltaEvent + | AssistantToolCallDeltaEvent | AssistantStreamingDeltaEvent | AssistantMessageEvent | AssistantMessageStartEvent | AssistantMessageDeltaEvent | AssistantTurnEndEvent + | AssistantIdleEvent | AssistantUsageEvent | ModelCallFailureEvent | AbortEvent @@ -75,6 +80,8 @@ export type SessionEvent = | SamplingCompletedEvent | McpOauthRequiredEvent | McpOauthCompletedEvent + | McpHeadersRefreshRequiredEvent + | McpHeadersRefreshCompletedEvent | CustomNotificationEvent | ExternalToolRequestedEvent | ExternalToolCompletedEvent @@ -83,6 +90,10 @@ export type SessionEvent = | CommandCompletedEvent | AutoModeSwitchRequestedEvent | AutoModeSwitchCompletedEvent + | SessionLimitsExhaustedRequestedEvent + | SessionLimitsExhaustedCompletedEvent + | AutoModeResolvedEvent + | ManagedSettingsResolvedEvent | CommandsChangedEvent | CapabilitiesChangedEvent | ExitPlanModeRequestedEvent @@ -93,6 +104,9 @@ export type SessionEvent = | CustomAgentsUpdatedEvent | McpServersLoadedEvent | McpServerStatusChangedEvent + | McpToolsListChangedEvent + | McpResourcesListChangedEvent + | McpPromptsListChangedEvent | ExtensionsLoadedEvent | CanvasOpenedEvent | CanvasRegistryChangedEvent @@ -128,6 +142,16 @@ export type ReasoningSummary = | "concise" /** Request a detailed summary of the model's reasoning. */ | "detailed"; +/** + * Output verbosity level used for supported model calls (e.g. "low", "medium", "high") + */ +export type Verbosity = + /** A terse response was requested. */ + | "low" + /** A medium amount of response detail was requested. */ + | "medium" + /** A more detailed response was requested. */ + | "high"; /** * The type of operation performed on the autopilot objective state file */ @@ -160,6 +184,17 @@ export type SessionMode = | "plan" /** The agent is working autonomously toward task completion. */ | "autopilot"; +/** + * Allow-all mode for the session. + */ +/** @experimental */ +export type PermissionAllowAllMode = + /** Permission requests follow the normal approval flow. */ + | "off" + /** Tool, path, and URL permission requests are automatically approved. */ + | "on" + /** Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. */ + | "auto"; /** * The type of operation performed on the plan file */ @@ -207,13 +242,22 @@ export type UserMessageAgentMode = /** The agent is in shell-focused UI mode. */ | "shell"; /** - * A user message attachment — a file, directory, code selection, blob, GitHub reference, or extension-supplied context payload + * A user message attachment — a file, directory, code selection, blob, GitHub reference, GitHub-anchored pointer, or extension-supplied context payload */ export type Attachment = | AttachmentFile | AttachmentDirectory | AttachmentSelection | AttachmentGitHubReference + | AttachmentGitHubCommit + | AttachmentGitHubRelease + | AttachmentGitHubActionsJob + | AttachmentGitHubRepository + | AttachmentGitHubFileDiff + | AttachmentGitHubTreeComparison + | AttachmentGitHubUrl + | AttachmentGitHubFile + | AttachmentGitHubSnippet | AttachmentBlob | AttachmentExtensionContext; /** @@ -234,6 +278,24 @@ export type AttachmentGitHubReferenceType = | "pr" /** GitHub discussion reference. */ | "discussion"; +/** + * How this user message was delivered to the agentic loop, relative to whether the loop was already running. This is the timing axis only; the message's origin (human vs. system/command/schedule/skill/etc.) is carried separately by `source`. A system-injected message has a delivery too — e.g. a background-task notification waking an idle agent is `idle`, the same mechanism as a human starting a fresh turn. + */ +export type UserMessageDelivery = + /** Delivered while the loop was idle; starts its own run immediately (a human's fresh turn, or a system notification waking an idle agent). */ + | "idle" + /** Injected into the current in-flight run while the agent was busy (immediate mode). */ + | "steering" + /** Enqueued while the agent was busy; processed as its own run afterward. */ + | "queued"; +/** + * Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent. + */ +export type AssistantMessageToolRequestType = + /** Standard function-style tool call. */ + | "function" + /** Custom grammar-based tool call. */ + | "custom"; /** * The system that produced a citation. */ @@ -250,14 +312,6 @@ export type CitationProvider = */ /** @experimental */ export type CitationLocation = CitationLocationChar | CitationLocationPage | CitationLocationBlock; -/** - * Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent. - */ -export type AssistantMessageToolRequestType = - /** Standard function-style tool call. */ - | "function" - /** Custom grammar-based tool call. */ - | "custom"; /** * API endpoint used for this model call, matching CAPI supported_endpoints vocabulary */ @@ -341,6 +395,7 @@ export type BinaryAssetReferenceType = export type ToolExecutionCompleteContent = | ToolExecutionCompleteContentText | ToolExecutionCompleteContentTerminal + | ToolExecutionCompleteContentShellExit | ToolExecutionCompleteContentImage | ToolExecutionCompleteContentAudio | ToolExecutionCompleteContentResourceLink @@ -454,6 +509,19 @@ export type PermissionPromptRequest = | PermissionPromptRequestHook | PermissionPromptRequestExtensionManagement | PermissionPromptRequestExtensionPermissionAccess; +/** + * Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). + */ +/** @experimental */ +export type AutoApprovalRecommendation = + /** The judge evaluated the request and recommends automatically approving it. */ + | "approve" + /** The judge evaluated the request and does not recommend auto-approving it; explicit approval is required. Whether that means prompting, denying, or something else is the consumer's decision. */ + | "requireApproval" + /** Auto mode is enabled, but this request category is never auto-approvable (for example, sandbox-bypass requests), so the judge was not consulted. */ + | "excluded" + /** The judge was consulted but did not return a usable recommendation, so the request requires explicit approval. */ + | "error"; /** * Underlying permission kind that needs path approval */ @@ -507,6 +575,18 @@ export type ElicitationCompletedAction = | "decline" /** The user dismissed the request. */ | "cancel"; +/** + * Reason the runtime is requesting host-provided MCP OAuth credentials + */ +export type McpOauthRequestReason = + /** Initial credentials are required before connecting to the MCP server. */ + | "initial" + /** The current host-provided credential was rejected and a replacement is requested. */ + | "refresh" + /** The server requires a new host authorization flow before continuing. */ + | "reauth" + /** The server requires a credential with additional scope or audience. */ + | "upscope"; /** * How the pending MCP OAuth request was completed */ @@ -515,6 +595,26 @@ export type McpOauthCompletionOutcome = | "token" /** The request completed without an OAuth provider. */ | "cancelled"; +/** + * Why dynamic headers are being requested. + */ +export type McpHeadersRefreshRequiredReason = + /** The transport is making its first dynamic header request for this server. */ + | "startup" + /** The previously cached dynamic headers expired. */ + | "ttl-expired" + /** The server returned 401 and stale dynamic headers were invalidated. */ + | "auth-failed"; +/** + * How the pending MCP headers refresh request resolved. + */ +export type McpHeadersRefreshCompletedOutcome = + /** The host supplied dynamic headers. */ + | "headers" + /** The host responded with no dynamic headers. */ + | "none" + /** No response arrived within the bounded window. */ + | "timeout"; /** * The user's auto-mode-switch choice */ @@ -525,6 +625,38 @@ export type AutoModeSwitchResponse = | "yes_always" /** Do not switch models. */ | "no"; +/** + * User action selected for an exhausted session limit. + */ +export type SessionLimitsExhaustedResponseAction = + /** Increase the current max by an exact AI Credits amount. */ + | "add" + /** Set a new absolute max AI Credits value. */ + | "set" + /** Remove the current session limit. */ + | "unset" + /** Leave the limit unchanged and cancel the blocked model request. */ + | "cancel"; +/** + * Coarse request-difficulty bucket for UX explainability + */ +export type AutoModeResolvedReasoningBucket = + /** The request looks low-reasoning; a lighter model is appropriate. */ + | "low" + /** The request needs a moderate amount of reasoning. */ + | "medium" + /** The request looks high-reasoning; a stronger model is appropriate. */ + | "high"; +/** + * Which channel supplied the effective enterprise managed settings (highest-authority present layer wins wholesale) + */ +export type ManagedSettingsResolvedSource = + /** Account/org policy self-fetched from the GitHub managed-settings endpoint (higher authority). */ + | "server" + /** Device-level MDM policy discovered from plist/registry/file (lower authority). */ + | "device" + /** No managed policy is in force (no layer contributed). */ + | "none"; /** * Exit plan mode action */ @@ -692,10 +824,12 @@ export interface StartData { * Unique identifier for the session */ sessionId: string; + sessionLimits?: SessionLimitsConfig; /** * ISO 8601 timestamp when the session was created */ startTime: string; + verbosity?: Verbosity; /** * Schema version number for the session event format */ @@ -735,6 +869,15 @@ export interface WorkingDirectoryContext { */ repositoryHost?: string; } +/** + * Optional session limits. + */ +export interface SessionLimitsConfig { + /** + * Maximum AI Credits allowed across the session's current accounting window. + */ + maxAiCredits?: number; +} /** * Session event "session.resume". Session resume metadata including current context and event count */ @@ -807,10 +950,15 @@ export interface ResumeData { * Model currently selected at resume time */ selectedModel?: string; + /** + * Session limits currently configured at resume time; null when no limits are active + */ + sessionLimits?: SessionLimitsConfig | null; /** * True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. */ sessionWasActive?: boolean; + verbosity?: Verbosity; } /** * Session event "session.remote_steerable_changed". Notifies that the session's remote steering capability has changed @@ -1347,11 +1495,13 @@ export interface ModelChangeData { */ previousReasoningEffort?: string; previousReasoningSummary?: ReasoningSummary; + previousVerbosity?: Verbosity; /** * Reasoning effort level after the model change, if applicable */ reasoningEffort?: string | null; reasoningSummary?: ReasoningSummary; + verbosity?: Verbosity; } /** * Session event "session.mode_changed". Agent mode change details including previous and new modes @@ -1391,7 +1541,46 @@ export interface ModeChangedData { previousMode: SessionMode; } /** - * Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all boolean transition. + * Session event "session.session_limits_changed". Session limits update details. Null clears the limits. + */ +export interface SessionLimitsChangedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: SessionLimitsChangedData; + /** + * When true, the event is transient and not persisted to the session event log on disk + */ + ephemeral?: boolean; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "session.session_limits_changed". + */ + type: "session.session_limits_changed"; +} +/** + * Session limits update details. Null clears the limits. + */ +export interface SessionLimitsChangedData { + /** + * Current session limits, or null when no limits are active + */ + sessionLimits: SessionLimitsConfig | null; +} +/** + * Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all transition. */ export interface PermissionsChangedEvent { /** @@ -1421,13 +1610,25 @@ export interface PermissionsChangedEvent { type: "session.permissions_changed"; } /** - * Permissions change details carrying the aggregate allow-all boolean transition. + * Permissions change details carrying the aggregate allow-all transition. */ export interface PermissionsChangedData { + /** + * Allow-all mode after the change + * + * @experimental + */ + allowAllPermissionMode?: PermissionAllowAllMode; /** * Aggregate allow-all flag after the change */ allowAllPermissions: boolean; + /** + * Allow-all mode before the change + * + * @experimental + */ + previousAllowAllPermissionMode?: PermissionAllowAllMode; /** * Aggregate allow-all flag before the change */ @@ -1842,7 +2043,7 @@ export interface ShutdownCodeChanges { linesRemoved: number; } /** - * Schema for the `ShutdownModelMetric` type. + * Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details. */ export interface ShutdownModelMetric { requests: ShutdownModelMetricRequests; @@ -1878,7 +2079,7 @@ export interface ShutdownModelMetricRequests { count?: number; } /** - * Schema for the `ShutdownModelMetricTokenDetail` type. + * A token-type entry in a shutdown model metric, storing the accumulated token count. */ export interface ShutdownModelMetricTokenDetail { /** @@ -1912,7 +2113,7 @@ export interface ShutdownModelMetricUsage { reasoningTokens?: number; } /** - * Schema for the `ShutdownTokenDetail` type. + * A session-wide shutdown token-type entry storing the accumulated token count. */ export interface ShutdownTokenDetail { /** @@ -1920,6 +2121,51 @@ export interface ShutdownTokenDetail { */ tokenCount: number; } +/** + * Session event "session.usage_checkpoint". Durable session usage checkpoint for reconstructing aggregate accounting on resume + */ +export interface UsageCheckpointEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: UsageCheckpointData; + /** + * When true, the event is transient and not persisted to the session event log on disk + */ + ephemeral?: boolean; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "session.usage_checkpoint". + */ + type: "session.usage_checkpoint"; +} +/** + * Durable session usage checkpoint for reconstructing aggregate accounting on resume + */ +export interface UsageCheckpointData { + /** + * Session-wide accumulated nano-AI units cost at checkpoint time + */ + totalNanoAiu: number; + /** + * Total number of premium API requests used at checkpoint time + * + * @internal + */ + totalPremiumRequests?: number; +} /** * Session event "session.context_changed". Updated working directory and git context after the change */ @@ -2051,6 +2297,10 @@ export interface CompactionStartData { * Token count from non-system messages (user, assistant, tool) at compaction start */ conversationTokens?: number; + /** + * Model identifier used for compaction, when known + */ + model?: string; /** * Token count from system message(s) at compaction start */ @@ -2280,7 +2530,7 @@ export interface TaskCompleteData { summary?: string; } /** - * Session event "user.message". + * Session event "user.message". Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. */ export interface UserMessageEvent { /** @@ -2310,7 +2560,7 @@ export interface UserMessageEvent { type: "user.message"; } /** - * Schema for the `UserMessageData` type. + * Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. */ export interface UserMessageData { agentMode?: UserMessageAgentMode; @@ -2322,6 +2572,7 @@ export interface UserMessageData { * The user's message text as displayed in the timeline */ content: string; + delivery?: UserMessageDelivery; /** * CAPI interaction ID for correlating this user message with its turn */ @@ -2502,185 +2753,461 @@ export interface AttachmentGitHubReference { url: string; } /** - * Blob attachment with inline base64-encoded data + * Pointer to a GitHub commit. */ -export interface AttachmentBlob { - /** - * Internal: content-addressed id of the session.binary_asset event holding this attachment's model-facing bytes (e.g. "sha256:..."). Absent externally. - */ - assetId?: string; - /** - * Internal: decoded byte length of the attachment's model-facing bytes. Absent externally. - */ - byteLength?: number; +export interface AttachmentGitHubCommit { /** - * Base64-encoded content. Present on input and for external consumers; replaced by an internal `assetId` reference in persisted events when interned to a content-addressed asset. + * First line of the commit message */ - data?: string; + message: string; /** - * User-facing display name for the attachment + * Full commit SHA */ - displayName?: string; + oid: string; + repo: GitHubRepoRef; /** - * MIME type of the inline data + * Attachment type discriminator */ - mimeType: string; - omittedReason?: OmittedBinaryOmittedReason; + type: "github_commit"; /** - * Attachment type discriminator + * URL to the commit on GitHub */ - type: "blob"; + url: string; } /** - * Structured context contributed by an extension. Composer pills displayed in the host are forwarded back through session.send.attachments, then rendered into the model prompt as an XML block. + * Pointer to a GitHub repository. */ -export interface AttachmentExtensionContext { +export interface GitHubRepoRef { /** - * Provider-local canvas identifier when the push was bound to a canvas instance + * Numeric GitHub repository id */ - canvasId?: string; + id?: number; /** - * ISO 8601 timestamp captured by the runtime when the push was accepted + * Repository name (without owner) */ - capturedAt: string; + name: string; /** - * Owning extension identifier. Runtime-derived from the caller's connection when produced via session.extensions.sendAttachmentsToMessage; preserved verbatim on subsequent transports. + * Repository owner login (user or organization) */ - extensionId: string; + owner: string; +} +/** + * Pointer to a GitHub release. + */ +export interface AttachmentGitHubRelease { /** - * Open canvas instance identifier when the push was bound to a canvas instance + * Human-readable release name */ - instanceId?: string; + name: string; + repo: GitHubRepoRef; /** - * Caller-supplied JSON payload + * Git tag the release is anchored to */ - payload?: { - [k: string]: unknown | undefined; - }; + tagName: string; /** - * Human-readable composer pill label + * Attachment type discriminator */ - title: string; + type: "github_release"; /** - * Attachment type discriminator + * URL to the release on GitHub */ - type: "extension_context"; + url: string; } /** - * Session event "pending_messages.modified". Empty payload; the event signals that the pending message queue has changed + * Pointer to a GitHub Actions job. */ -export interface PendingMessagesModifiedEvent { +export interface AttachmentGitHubActionsJob { /** - * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + * Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. */ - agentId?: string; - data: PendingMessagesModifiedData; + conclusion?: string; /** - * Always true for events that are transient and not persisted to the session event log on disk. + * Job id within the workflow run */ - ephemeral: true; + jobId: number; /** - * Unique event identifier (UUID v4), generated when the event is emitted + * Display name of the job */ - id: string; + jobName: string; + repo: GitHubRepoRef; /** - * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + * Attachment type discriminator */ - parentId: string | null; + type: "github_actions_job"; /** - * ISO 8601 timestamp when the event was created + * URL to the job on GitHub */ - timestamp: string; + url: string; /** - * Type discriminator. Always "pending_messages.modified". + * Display name of the workflow the job ran in */ - type: "pending_messages.modified"; + workflowName: string; } /** - * Empty payload; the event signals that the pending message queue has changed - */ -export interface PendingMessagesModifiedData {} -/** - * Session event "assistant.turn_start". Turn initialization metadata including identifier and interaction tracking + * Pointer to a GitHub repository. */ -export interface AssistantTurnStartEvent { +export interface AttachmentGitHubRepository { /** - * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + * Short description of the repository */ - agentId?: string; - data: AssistantTurnStartData; + description?: string; /** - * When true, the event is transient and not persisted to the session event log on disk + * Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. */ - ephemeral?: boolean; + ref?: string; + repo: GitHubRepoRef; /** - * Unique event identifier (UUID v4), generated when the event is emitted + * Attachment type discriminator */ - id: string; + type: "github_repository"; /** - * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + * URL to the repository on GitHub */ - parentId: string | null; + url: string; +} +/** + * Pointer to a single-file diff. At least one of `head` and `base` must be present. + */ +export interface AttachmentGitHubFileDiff { + base?: AttachmentGitHubFileDiffSide; + head?: AttachmentGitHubFileDiffSide; /** - * ISO 8601 timestamp when the event was created + * Attachment type discriminator */ - timestamp: string; + type: "github_file_diff"; /** - * Type discriminator. Always "assistant.turn_start". + * URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) */ - type: "assistant.turn_start"; + url: string; } /** - * Turn initialization metadata including identifier and interaction tracking + * One side of a file diff (head or base) */ -export interface AssistantTurnStartData { +export interface AttachmentGitHubFileDiffSide { /** - * CAPI interaction ID for correlating this turn with upstream telemetry + * Repository-relative path to the file */ - interactionId?: string; + path: string; /** - * Identifier for this turn within the agentic loop, typically a stringified turn number + * Git ref (branch, tag, or commit SHA) the file is read at */ - turnId: string; + ref: string; + repo: GitHubRepoRef; } /** - * Session event "assistant.intent". Agent intent description for current activity or plan + * Pointer to a comparison between two git revisions. */ -export interface AssistantIntentEvent { - /** - * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. - */ - agentId?: string; - data: AssistantIntentData; +export interface AttachmentGitHubTreeComparison { + base: AttachmentGitHubTreeComparisonSide; + head: AttachmentGitHubTreeComparisonSide; /** - * Always true for events that are transient and not persisted to the session event log on disk. + * Attachment type discriminator */ - ephemeral: true; + type: "github_tree_comparison"; /** - * Unique event identifier (UUID v4), generated when the event is emitted + * URL to the comparison on GitHub */ - id: string; + url: string; +} +/** + * One side of a tree comparison (head or base) + */ +export interface AttachmentGitHubTreeComparisonSide { + repo: GitHubRepoRef; /** - * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + * Git revision (branch, tag, or commit SHA) */ - parentId: string | null; + revision: string; +} +/** + * Generic GitHub URL reference. + */ +export interface AttachmentGitHubUrl { /** - * ISO 8601 timestamp when the event was created + * Attachment type discriminator */ - timestamp: string; + type: "github_url"; /** - * Type discriminator. Always "assistant.intent". + * URL to the GitHub resource */ - type: "assistant.intent"; + url: string; } /** - * Agent intent description for current activity or plan + * Pointer to a file in a GitHub repository at a specific ref. */ -export interface AssistantIntentData { +export interface AttachmentGitHubFile { /** - * Short description of what the agent is currently doing or planning to do + * Repository-relative path to the file */ - intent: string; + path: string; + /** + * Git ref the file is read at (branch, tag, or commit SHA) + */ + ref: string; + repo: GitHubRepoRef; + /** + * Attachment type discriminator + */ + type: "github_file"; + /** + * URL to the file on GitHub + */ + url: string; +} +/** + * Pointer to a line range inside a file in a GitHub repository. + */ +export interface AttachmentGitHubSnippet { + lineRange: AttachmentFileLineRange; + /** + * Repository-relative path to the file + */ + path: string; + /** + * Git ref the file is read at (branch, tag, or commit SHA) + */ + ref: string; + repo: GitHubRepoRef; + /** + * Attachment type discriminator + */ + type: "github_snippet"; + /** + * URL to the snippet on GitHub (with line anchor) + */ + url: string; +} +/** + * Blob attachment with inline base64-encoded data + */ +export interface AttachmentBlob { + /** + * Internal: content-addressed id of the session.binary_asset event holding this attachment's model-facing bytes (e.g. "sha256:..."). Absent externally. + */ + assetId?: string; + /** + * Internal: decoded byte length of the attachment's model-facing bytes. Absent externally. + */ + byteLength?: number; + /** + * Base64-encoded content. Present on input and for external consumers; replaced by an internal `assetId` reference in persisted events when interned to a content-addressed asset. + */ + data?: string; + /** + * User-facing display name for the attachment + */ + displayName?: string; + /** + * MIME type of the inline data + */ + mimeType: string; + omittedReason?: OmittedBinaryOmittedReason; + /** + * Attachment type discriminator + */ + type: "blob"; +} +/** + * Structured context contributed by an extension. Composer pills displayed in the host are forwarded back through session.send.attachments, then rendered into the model prompt as an XML block. + */ +export interface AttachmentExtensionContext { + /** + * Provider-local canvas identifier when the push was bound to a canvas instance + */ + canvasId?: string; + /** + * ISO 8601 timestamp captured by the runtime when the push was accepted + */ + capturedAt: string; + /** + * Owning extension identifier. Runtime-derived from the caller's connection when produced via session.extensions.sendAttachmentsToMessage; preserved verbatim on subsequent transports. + */ + extensionId: string; + /** + * Open canvas instance identifier when the push was bound to a canvas instance + */ + instanceId?: string; + /** + * Caller-supplied JSON payload + */ + payload?: { + [k: string]: unknown | undefined; + }; + /** + * Human-readable composer pill label + */ + title: string; + /** + * Attachment type discriminator + */ + type: "extension_context"; +} +/** + * Session event "pending_messages.modified". Empty payload; the event signals that the pending message queue has changed + */ +export interface PendingMessagesModifiedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: PendingMessagesModifiedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "pending_messages.modified". + */ + type: "pending_messages.modified"; +} +/** + * Empty payload; the event signals that the pending message queue has changed + */ +export interface PendingMessagesModifiedData {} +/** + * Session event "assistant.turn_start". Turn initialization metadata including identifier and interaction tracking + */ +export interface AssistantTurnStartEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: AssistantTurnStartData; + /** + * When true, the event is transient and not persisted to the session event log on disk + */ + ephemeral?: boolean; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "assistant.turn_start". + */ + type: "assistant.turn_start"; +} +/** + * Turn initialization metadata including identifier and interaction tracking + */ +export interface AssistantTurnStartData { + /** + * CAPI interaction ID for correlating this turn with upstream telemetry + */ + interactionId?: string; + /** + * Model identifier used for this turn, when known + */ + model?: string; + /** + * Identifier for this turn within the agentic loop, typically a stringified turn number + */ + turnId: string; +} +/** + * Session event "assistant.intent". Agent intent description for current activity or plan + */ +export interface AssistantIntentEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: AssistantIntentData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "assistant.intent". + */ + type: "assistant.intent"; +} +/** + * Agent intent description for current activity or plan + */ +export interface AssistantIntentData { + /** + * Short description of what the agent is currently doing or planning to do + */ + intent: string; +} +/** + * Session event "assistant.server_tool_progress". Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message + */ +export interface AssistantServerToolProgressEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: AssistantServerToolProgressData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "assistant.server_tool_progress". + */ + type: "assistant.server_tool_progress"; +} +/** + * Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message + */ +export interface AssistantServerToolProgressData { + /** + * Kind of hosted server tool that is running. Only `web_search` is emitted today. + */ + kind: string; + /** + * Position of the hosted tool call in the response output. Stable across the call's lifecycle events (unlike the provider's per-event item id, which CAPI rotates), so the host keys the live in-progress row on it. + */ + outputIndex: number; + /** + * Lifecycle status of the hosted call: `in_progress`, `searching`, or `completed`. + */ + status: string; } /** * Session event "assistant.reasoning". Assistant reasoning content for timeline display with complete thinking text @@ -2766,7 +3293,55 @@ export interface AssistantReasoningDeltaData { /** * Reasoning block ID this delta belongs to, matching the corresponding assistant.reasoning event */ - reasoningId: string; + reasoningId: string; +} +/** + * Session event "assistant.tool_call_delta". Streaming tool-call input delta for incremental tool-call updates + */ +export interface AssistantToolCallDeltaEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: AssistantToolCallDeltaData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "assistant.tool_call_delta". + */ + type: "assistant.tool_call_delta"; +} +/** + * Streaming tool-call input delta for incremental tool-call updates + */ +export interface AssistantToolCallDeltaData { + /** + * Raw provider tool input fragment to append for this tool call. Function/tool-use providers stream serialized JSON argument text (so newlines inside JSON string values may appear as escaped `\n` until the accumulated JSON is parsed); custom tool calls stream raw custom input. + */ + inputDelta: string; + /** + * Tool call ID this delta belongs to, matching the corresponding assistant.message tool request + */ + toolCallId: string; + /** + * Name of the tool being invoked, when known from the stream + */ + toolName?: string; + toolType?: AssistantMessageToolRequestType; } /** * Session event "assistant.streaming_delta". Streaming response progress with cumulative byte count @@ -2851,6 +3426,10 @@ export interface AssistantMessageData { * @experimental */ citations?: Citations; + /** + * Client-minted request id (x-request-id header) echoed by the server. Distinct from requestId (x-github-request-id) and serviceRequestId (x-copilot-service-request-id). + */ + clientRequestId?: string; /** * The assistant's text response content */ @@ -2892,6 +3471,10 @@ export interface AssistantMessageData { * Readable reasoning text from the model's extended thinking */ reasoningText?: string; + /** + * OpenAI-compatible wire field the provider used for reasoning (e.g. reasoning_content/reasoning). Populated only when non-canonical, so the dialect round-trips across turns. + */ + reasoningWireField?: string; /** * GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs */ @@ -3214,11 +3797,54 @@ export interface AssistantTurnEndEvent { * Turn completion metadata including the turn identifier */ export interface AssistantTurnEndData { + /** + * Model identifier used for this turn, when known + */ + model?: string; /** * Identifier of the turn that has ended, matching the corresponding assistant.turn_start event */ turnId: string; } +/** + * Session event "assistant.idle". Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred + */ +export interface AssistantIdleEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: AssistantIdleData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "assistant.idle". + */ + type: "assistant.idle"; +} +/** + * Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred + */ +export interface AssistantIdleData { + /** + * True when the preceding agentic loop was cancelled via abort signal + */ + aborted?: boolean; +} /** * Session event "assistant.usage". LLM API call usage metrics including tokens, costs, quotas, and billing information */ @@ -3376,7 +4002,7 @@ export interface AssistantUsageCopilotUsageTokenDetail { tokenType: string; } /** - * Schema for the `AssistantUsageQuotaSnapshot` type. + * Internal per-quota snapshot for assistant usage, including entitlement, consumed requests, overage, reset date, and remaining quota. */ /** @internal */ export interface AssistantUsageQuotaSnapshot { @@ -3712,6 +4338,7 @@ export interface ToolExecutionStartData { * Tool call ID of the parent tool invocation when this event originates from a sub-agent */ parentToolCallId?: string; + shellToolInfo?: ToolExecutionStartShellToolInfo; /** * Unique identifier for this tool call */ @@ -3726,6 +4353,19 @@ export interface ToolExecutionStartData { */ turnId?: string; } +/** + * Shell-aware path hints for a shell tool's command, captured at start time so consumers can snapshot a file's pre-image before the tool runs. + */ +export interface ToolExecutionStartShellToolInfo { + /** + * Whether the command includes a file write redirection (e.g., > or >>). + */ + hasWriteFileRedirection: boolean; + /** + * File paths the command may read or write, derived from the command at start time. Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. + */ + possiblePaths: string[]; +} /** * Tool definition metadata, present for MCP tools with MCP Apps support */ @@ -3747,7 +4387,7 @@ export interface ToolExecutionStartToolDescriptionMeta { ui?: ToolExecutionStartToolDescriptionMetaUI; } /** - * Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. + * MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. */ export interface ToolExecutionStartToolDescriptionMetaUI { /** @@ -3888,6 +4528,14 @@ export interface ToolExecutionCompleteData { * Whether this tool call was explicitly requested by the user rather than the assistant */ isUserRequested?: boolean; + /** + * FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels). Persisted as `{ ifc: ... }` so the label survives session resume, including model-visible failure results. Experimental. + * + * @experimental + */ + mcpMeta?: { + [k: string]: unknown | undefined; + }; /** * Model identifier that generated this tool call */ @@ -3963,6 +4611,14 @@ export interface ToolExecutionCompleteResult { * Full detailed tool result for UI/timeline display, preserving complete content such as diffs. Falls back to content when absent. */ detailedContent?: string; + /** + * FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels) — persisted as `{ ifc: ... }` (only the `ifc` key, not the whole `_meta`). Persisted so the FIDES IFC label survives session resume: the engine rehydrates accumulated taint by replaying these on load. Populated for ingress sources when FIDES IFC is on. Experimental. + * + * @experimental + */ + mcpMeta?: { + [k: string]: unknown | undefined; + }; /** * Structured content (arbitrary JSON) returned verbatim by the MCP tool */ @@ -4090,7 +4746,8 @@ export interface ToolExecutionCompleteContentText { type: "text"; } /** - * Terminal/shell output content block with optional exit code and working directory + * @deprecated + * Deprecated for shell command exit metadata. Use ToolExecutionCompleteContentShellExit instead. */ export interface ToolExecutionCompleteContentTerminal { /** @@ -4110,6 +4767,35 @@ export interface ToolExecutionCompleteContentTerminal { */ type: "terminal"; } +/** + * Shell command exit metadata with optional output preview + */ +export interface ToolExecutionCompleteContentShellExit { + /** + * Working directory where the shell command was executed + */ + cwd?: string; + /** + * Exit code from the completed shell command + */ + exitCode: number; + /** + * Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. + */ + outputPreview?: string; + /** + * Whether outputPreview is known to be incomplete or truncated + */ + outputTruncated?: boolean; + /** + * Shell id, as assigned by Copilot runtime + */ + shellId: string; + /** + * Content block type discriminator + */ + type: "shell_exit"; +} /** * Image content block with base64-encoded data */ @@ -4210,7 +4896,7 @@ export interface ToolExecutionCompleteContentResource { type: "resource"; } /** - * Schema for the `EmbeddedTextResourceContents` type. + * Embedded text resource contents identified by a URI, with an optional MIME type and a text payload. */ export interface EmbeddedTextResourceContents { /** @@ -4227,7 +4913,7 @@ export interface EmbeddedTextResourceContents { uri: string; } /** - * Schema for the `EmbeddedBlobResourceContents` type. + * Embedded binary resource contents identified by a URI, with an optional MIME type and a base64-encoded blob. */ export interface EmbeddedBlobResourceContents { /** @@ -4272,7 +4958,7 @@ export interface ToolExecutionCompleteUIResourceMeta { ui?: ToolExecutionCompleteUIResourceMetaUI; } /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. + * MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. */ export interface ToolExecutionCompleteUIResourceMetaUI { csp?: ToolExecutionCompleteUIResourceMetaUICsp; @@ -4281,7 +4967,7 @@ export interface ToolExecutionCompleteUIResourceMetaUI { prefersBorder?: boolean; } /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. + * CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. */ export interface ToolExecutionCompleteUIResourceMetaUICsp { baseUriDomains?: string[]; @@ -4290,7 +4976,7 @@ export interface ToolExecutionCompleteUIResourceMetaUICsp { resourceDomains?: string[]; } /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. + * Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. */ export interface ToolExecutionCompleteUIResourceMetaUIPermissions { camera?: ToolExecutionCompleteUIResourceMetaUIPermissionsCamera; @@ -4299,19 +4985,19 @@ export interface ToolExecutionCompleteUIResourceMetaUIPermissions { microphone?: ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone; } /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. + * Marker object for camera permission on an MCP Apps UI resource. */ export interface ToolExecutionCompleteUIResourceMetaUIPermissionsCamera {} /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. + * Marker object for clipboard-write permission on an MCP Apps UI resource. */ export interface ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite {} /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. + * Marker object for geolocation permission on an MCP Apps UI resource. */ export interface ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation {} /** - * Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. + * Marker object for microphone permission on an MCP Apps UI resource. */ export interface ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone {} /** @@ -4335,7 +5021,7 @@ export interface ToolExecutionCompleteToolDescriptionMeta { ui?: ToolExecutionCompleteToolDescriptionMetaUI; } /** - * Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. + * MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. */ export interface ToolExecutionCompleteToolDescriptionMetaUI { /** @@ -4393,6 +5079,10 @@ export interface SkillInvokedData { * Description of the skill from its SKILL.md frontmatter */ description?: string; + /** + * Model identifier active when the skill was invoked, when known + */ + model?: string; /** * Name of the invoked skill */ @@ -5008,7 +5698,7 @@ export interface SystemNotificationData { kind: SystemNotification; } /** - * Schema for the `SystemNotificationAgentCompleted` type. + * System notification metadata for a background agent that completed or failed, including agent ID, type, status, description, and prompt. */ export interface SystemNotificationAgentCompleted { /** @@ -5034,7 +5724,7 @@ export interface SystemNotificationAgentCompleted { type: "agent_completed"; } /** - * Schema for the `SystemNotificationAgentIdle` type. + * System notification metadata for a background agent that became idle, including agent ID, type, and description. */ export interface SystemNotificationAgentIdle { /** @@ -5055,7 +5745,7 @@ export interface SystemNotificationAgentIdle { type: "agent_idle"; } /** - * Schema for the `SystemNotificationNewInboxMessage` type. + * System notification metadata for a new inbox message, including entry ID, sender details, and summary. */ export interface SystemNotificationNewInboxMessage { /** @@ -5080,7 +5770,7 @@ export interface SystemNotificationNewInboxMessage { type: "new_inbox_message"; } /** - * Schema for the `SystemNotificationShellCompleted` type. + * System notification metadata for a shell session that completed, including shell ID, optional exit code, and description. */ export interface SystemNotificationShellCompleted { /** @@ -5101,7 +5791,7 @@ export interface SystemNotificationShellCompleted { type: "shell_completed"; } /** - * Schema for the `SystemNotificationShellDetachedCompleted` type. + * System notification metadata for a detached shell session that completed, including shell ID and description. */ export interface SystemNotificationShellDetachedCompleted { /** @@ -5118,7 +5808,7 @@ export interface SystemNotificationShellDetachedCompleted { type: "shell_detached_completed"; } /** - * Schema for the `SystemNotificationInstructionDiscovered` type. + * System notification metadata for an instruction file discovered during tool access, including source, trigger file, and tool. */ export interface SystemNotificationInstructionDiscovered { /** @@ -5241,7 +5931,7 @@ export interface PermissionRequestShell { warning?: string; } /** - * Schema for the `PermissionRequestShellCommand` type. + * A parsed command identifier in a shell permission request, including whether it is read-only. */ export interface PermissionRequestShellCommand { /** @@ -5254,7 +5944,7 @@ export interface PermissionRequestShellCommand { readOnly: boolean; } /** - * Schema for the `PermissionRequestShellPossibleUrl` type. + * A URL that may be accessed by a command in a shell permission request. */ export interface PermissionRequestShellPossibleUrl { /** @@ -5290,6 +5980,14 @@ export interface PermissionRequestWrite { * Complete new file contents for newly created files */ newFileContents?: string; + /** + * True when a built-in file tool (apply_patch / str_replace_editor) asked to write a path the sandbox filesystem policy would block, and the host opted in via sandbox.allowBypass. This is a request, not a grant: the write happens unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + */ + requestSandboxBypass?: boolean; + /** + * Justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + */ + requestSandboxBypassReason?: string; /** * Tool call ID that triggered this permission request */ @@ -5311,6 +6009,14 @@ export interface PermissionRequestRead { * Path of the file or directory being read */ path: string; + /** + * True when the model has requested to run this search outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the search runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + */ + requestSandboxBypass?: boolean; + /** + * Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + */ + requestSandboxBypassReason?: string; /** * Tool call ID that triggered this permission request */ @@ -5363,6 +6069,14 @@ export interface PermissionRequestUrl { * Permission kind discriminator */ kind: "url"; + /** + * True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + */ + requestSandboxBypass?: boolean; + /** + * Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + */ + requestSandboxBypassReason?: string; /** * Tool call ID that triggered this permission request */ @@ -5503,6 +6217,12 @@ export interface PermissionRequestExtensionPermissionAccess { * Shell command permission prompt */ export interface PermissionPromptRequestCommands { + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Whether the UI can offer session-wide approval for this command pattern */ @@ -5532,10 +6252,27 @@ export interface PermissionPromptRequestCommands { */ warning?: string; } +/** + * Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is "auto"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request. + */ +/** @experimental */ +export interface PermissionAutoApproval { + /** + * Human-readable reason for the judge's recommendation, when available. + */ + reason?: string; + recommendation: AutoApprovalRecommendation; +} /** * File write permission prompt */ export interface PermissionPromptRequestWrite { + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Whether the UI can offer session-wide approval for file write operations */ @@ -5569,6 +6306,12 @@ export interface PermissionPromptRequestWrite { * File read permission prompt */ export interface PermissionPromptRequestRead { + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Human-readable description of why the file is being read */ @@ -5596,6 +6339,12 @@ export interface PermissionPromptRequestMcp { args?: { [k: string]: unknown | undefined; }; + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Prompt kind discriminator */ @@ -5621,6 +6370,12 @@ export interface PermissionPromptRequestMcp { * URL access permission prompt */ export interface PermissionPromptRequestUrl { + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Human-readable description of why the URL is being accessed */ @@ -5629,6 +6384,14 @@ export interface PermissionPromptRequestUrl { * Prompt kind discriminator */ kind: "url"; + /** + * True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + */ + requestSandboxBypass?: boolean; + /** + * Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + */ + requestSandboxBypassReason?: string; /** * Tool call ID that triggered this permission request */ @@ -5643,6 +6406,12 @@ export interface PermissionPromptRequestUrl { */ export interface PermissionPromptRequestMemory { action?: PermissionRequestMemoryAction; + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Source references for the stored fact (store only) */ @@ -5679,6 +6448,12 @@ export interface PermissionPromptRequestCustomTool { args?: { [k: string]: unknown | undefined; }; + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Prompt kind discriminator */ @@ -5701,6 +6476,12 @@ export interface PermissionPromptRequestCustomTool { */ export interface PermissionPromptRequestPath { accessKind: PermissionPromptRequestPathAccessKind; + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Prompt kind discriminator */ @@ -5718,6 +6499,12 @@ export interface PermissionPromptRequestPath { * Hook confirmation permission prompt */ export interface PermissionPromptRequestHook { + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Optional message from the hook explaining why confirmation is needed */ @@ -5745,6 +6532,12 @@ export interface PermissionPromptRequestHook { * Extension management permission prompt */ export interface PermissionPromptRequestExtensionManagement { + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Name of the extension being managed */ @@ -5766,6 +6559,12 @@ export interface PermissionPromptRequestExtensionManagement { * Extension permission access prompt */ export interface PermissionPromptRequestExtensionPermissionAccess { + /** + * Auto-approval judge information for this request; present only when auto mode is enabled. + * + * @experimental + */ + autoApproval?: PermissionAutoApproval; /** * Capabilities the extension is requesting */ @@ -5828,7 +6627,7 @@ export interface PermissionCompletedData { toolCallId?: string; } /** - * Schema for the `PermissionApproved` type. + * Permission response variant indicating the request was approved without persisting an approval rule. */ export interface PermissionApproved { /** @@ -5837,7 +6636,7 @@ export interface PermissionApproved { kind: "approved"; } /** - * Schema for the `PermissionApprovedForSession` type. + * Permission response variant that approves a request and remembers the provided approval for the rest of the session. */ export interface PermissionApprovedForSession { approval: UserToolSessionApproval; @@ -5847,7 +6646,7 @@ export interface PermissionApprovedForSession { kind: "approved-for-session"; } /** - * Schema for the `UserToolSessionApprovalCommands` type. + * Session-scoped tool-approval rule for specific shell command identifiers. */ export interface UserToolSessionApprovalCommands { /** @@ -5860,7 +6659,7 @@ export interface UserToolSessionApprovalCommands { kind: "commands"; } /** - * Schema for the `UserToolSessionApprovalRead` type. + * Session-scoped tool-approval rule for read-only filesystem operations. */ export interface UserToolSessionApprovalRead { /** @@ -5869,7 +6668,7 @@ export interface UserToolSessionApprovalRead { kind: "read"; } /** - * Schema for the `UserToolSessionApprovalWrite` type. + * Session-scoped tool-approval rule for filesystem write operations. */ export interface UserToolSessionApprovalWrite { /** @@ -5878,7 +6677,7 @@ export interface UserToolSessionApprovalWrite { kind: "write"; } /** - * Schema for the `UserToolSessionApprovalMcp` type. + * Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null. */ export interface UserToolSessionApprovalMcp { /** @@ -5895,7 +6694,7 @@ export interface UserToolSessionApprovalMcp { toolName: string | null; } /** - * Schema for the `UserToolSessionApprovalMemory` type. + * Session-scoped tool-approval rule for writes to long-term memory. */ export interface UserToolSessionApprovalMemory { /** @@ -5904,7 +6703,7 @@ export interface UserToolSessionApprovalMemory { kind: "memory"; } /** - * Schema for the `UserToolSessionApprovalCustomTool` type. + * Session-scoped tool-approval rule for a custom tool, keyed by tool name. */ export interface UserToolSessionApprovalCustomTool { /** @@ -5917,7 +6716,7 @@ export interface UserToolSessionApprovalCustomTool { toolName: string; } /** - * Schema for the `UserToolSessionApprovalExtensionManagement` type. + * Session-scoped tool-approval rule for extension-management operations, optionally narrowed by operation. */ export interface UserToolSessionApprovalExtensionManagement { /** @@ -5930,7 +6729,7 @@ export interface UserToolSessionApprovalExtensionManagement { operation?: string; } /** - * Schema for the `UserToolSessionApprovalExtensionPermissionAccess` type. + * Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name. */ export interface UserToolSessionApprovalExtensionPermissionAccess { /** @@ -5943,7 +6742,7 @@ export interface UserToolSessionApprovalExtensionPermissionAccess { kind: "extension-permission-access"; } /** - * Schema for the `PermissionApprovedForLocation` type. + * Permission response variant that approves a request and persists the provided approval to a project location key. */ export interface PermissionApprovedForLocation { approval: UserToolSessionApproval; @@ -5957,7 +6756,7 @@ export interface PermissionApprovedForLocation { locationKey: string; } /** - * Schema for the `PermissionCancelled` type. + * Permission response variant indicating the request was cancelled before use, with an optional reason. */ export interface PermissionCancelled { /** @@ -5970,7 +6769,7 @@ export interface PermissionCancelled { reason?: string; } /** - * Schema for the `PermissionDeniedByRules` type. + * Permission response variant denied because matching approval rules explicitly blocked the request. */ export interface PermissionDeniedByRules { /** @@ -5983,7 +6782,7 @@ export interface PermissionDeniedByRules { rules: PermissionRule[]; } /** - * Schema for the `PermissionRule` type. + * A permission approval or denial rule matched against a tool request, identified by a rule kind with an optional argument value. */ export interface PermissionRule { /** @@ -5996,7 +6795,7 @@ export interface PermissionRule { kind: string; } /** - * Schema for the `PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. + * Permission response variant denied because no approval rule matched and user confirmation was unavailable. */ export interface PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser { /** @@ -6005,7 +6804,7 @@ export interface PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser { kind: "denied-no-approval-rule-and-could-not-request-from-user"; } /** - * Schema for the `PermissionDeniedInteractivelyByUser` type. + * Permission response variant denied in an interactive user prompt, with optional feedback and force-reject flag. */ export interface PermissionDeniedInteractivelyByUser { /** @@ -6022,7 +6821,7 @@ export interface PermissionDeniedInteractivelyByUser { kind: "denied-interactively-by-user"; } /** - * Schema for the `PermissionDeniedByContentExclusionPolicy` type. + * Permission response variant denying a path under content exclusion policy, with the path and message. */ export interface PermissionDeniedByContentExclusionPolicy { /** @@ -6039,7 +6838,7 @@ export interface PermissionDeniedByContentExclusionPolicy { path: string; } /** - * Schema for the `PermissionDeniedByPermissionRequestHook` type. + * Permission response variant denied by a permission-request hook, with optional message and interrupt flag. */ export interface PermissionDeniedByPermissionRequestHook { /** @@ -6280,7 +7079,7 @@ export interface ElicitationCompletedData { requestId: string; } /** - * Schema for the `ElicitationCompletedContent` type. + * Opaque JSON value submitted for one field in accepted `elicitation.completed` form content. */ export interface ElicitationCompletedContent { [k: string]: unknown | undefined; @@ -6407,6 +7206,8 @@ export interface McpOauthRequiredEvent { * OAuth authentication request for an MCP server */ export interface McpOauthRequiredData { + httpResponse?: McpOauthHttpResponse; + reason: McpOauthRequestReason; /** * Unique identifier for this OAuth request; used to respond via session.mcp.oauth.handlePendingRequest */ @@ -6426,6 +7227,36 @@ export interface McpOauthRequiredData { staticClientConfig?: McpOauthRequiredStaticClientConfig; wwwAuthenticateParams?: McpOauthWWWAuthenticateParams; } +/** + * Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. + */ +export interface McpOauthHttpResponse { + /** + * Complete UTF-8 response body for host-specific challenge handling, including an empty string for an empty body. Omitted when the complete body is not valid UTF-8; body read failures fail the HTTP operation rather than exposing a partial response. + */ + body?: string; + /** + * HTTP response headers as observed by the runtime. Order and casing are transport-dependent, and duplicate header names may appear multiple times. + */ + headers: HeaderEntry[]; + /** + * HTTP status code returned with the auth challenge. + */ + statusCode: number; +} +/** + * Single HTTP header entry as a name/value pair. + */ +export interface HeaderEntry { + /** + * HTTP response header name as observed by the runtime. + */ + name: string; + /** + * HTTP response header value as observed by the runtime. + */ + value: string; +} /** * Static OAuth client configuration, if the server specifies one */ @@ -6434,6 +7265,10 @@ export interface McpOauthRequiredStaticClientConfig { * OAuth client ID for the server */ clientId: string; + /** + * Optional OAuth client secret for confidential static clients, when the runtime can resolve one + */ + clientSecret?: string; /** * Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). */ @@ -6452,23 +7287,111 @@ export interface McpOauthWWWAuthenticateParams { */ error?: string; /** - * Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter + * Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter, if present + */ + resourceMetadataUrl?: string; + /** + * Requested OAuth scopes from the WWW-Authenticate scope parameter, if present + */ + scope?: string; +} +/** + * Session event "mcp.oauth_completed". MCP OAuth request completion notification + */ +export interface McpOauthCompletedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: McpOauthCompletedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "mcp.oauth_completed". + */ + type: "mcp.oauth_completed"; +} +/** + * MCP OAuth request completion notification + */ +export interface McpOauthCompletedData { + outcome: McpOauthCompletionOutcome; + /** + * Request ID of the resolved OAuth request + */ + requestId: string; +} +/** + * Session event "mcp.headers_refresh_required". Dynamic headers refresh request for a remote MCP server + */ +export interface McpHeadersRefreshRequiredEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: McpHeadersRefreshRequiredData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "mcp.headers_refresh_required". + */ + type: "mcp.headers_refresh_required"; +} +/** + * Dynamic headers refresh request for a remote MCP server + */ +export interface McpHeadersRefreshRequiredData { + reason: McpHeadersRefreshRequiredReason; + /** + * Unique identifier for this headers refresh request; used to respond via session.mcp.headers.handlePendingHeadersRefreshRequest() + */ + requestId: string; + /** + * Display name of the remote MCP server requesting headers */ - resourceMetadataUrl: string; + serverName: string; /** - * Requested OAuth scopes from the WWW-Authenticate scope parameter, if present + * URL of the remote MCP server requesting headers */ - scope?: string; + serverUrl: string; } /** - * Session event "mcp.oauth_completed". MCP OAuth request completion notification + * Session event "mcp.headers_refresh_completed". MCP headers refresh request completion notification */ -export interface McpOauthCompletedEvent { +export interface McpHeadersRefreshCompletedEvent { /** * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; - data: McpOauthCompletedData; + data: McpHeadersRefreshCompletedData; /** * Always true for events that are transient and not persisted to the session event log on disk. */ @@ -6486,17 +7409,17 @@ export interface McpOauthCompletedEvent { */ timestamp: string; /** - * Type discriminator. Always "mcp.oauth_completed". + * Type discriminator. Always "mcp.headers_refresh_completed". */ - type: "mcp.oauth_completed"; + type: "mcp.headers_refresh_completed"; } /** - * MCP OAuth request completion notification + * MCP headers refresh request completion notification */ -export interface McpOauthCompletedData { - outcome: McpOauthCompletionOutcome; +export interface McpHeadersRefreshCompletedData { + outcome: McpHeadersRefreshCompletedOutcome; /** - * Request ID of the resolved OAuth request + * Request ID of the resolved headers refresh request */ requestId: string; } @@ -6889,6 +7812,231 @@ export interface AutoModeSwitchCompletedData { requestId: string; response: AutoModeSwitchResponse; } +/** + * Session event "session_limits_exhausted.requested". Session limit exhaustion notification requiring user action. + */ +export interface SessionLimitsExhaustedRequestedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: SessionLimitsExhaustedRequestedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "session_limits_exhausted.requested". + */ + type: "session_limits_exhausted.requested"; +} +/** + * Session limit exhaustion notification requiring user action. + */ +export interface SessionLimitsExhaustedRequestedData { + /** + * Configured max AI Credits for the current accounting window. + */ + maxAiCredits: number; + /** + * Unique identifier for this request; used to respond via session.ui.handlePendingSessionLimitsExhausted(). + */ + requestId: string; + /** + * AI Credits already consumed in the current accounting window. + */ + usedAiCredits: number; +} +/** + * Session event "session_limits_exhausted.completed". Session limit exhaustion prompt completion notification. + */ +export interface SessionLimitsExhaustedCompletedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: SessionLimitsExhaustedCompletedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "session_limits_exhausted.completed". + */ + type: "session_limits_exhausted.completed"; +} +/** + * Session limit exhaustion prompt completion notification. + */ +export interface SessionLimitsExhaustedCompletedData { + /** + * Request ID of the resolved request; clients should dismiss any UI for this request. + */ + requestId: string; + response: SessionLimitsExhaustedResponse; +} +/** + * The user's selected action for an exhausted session limit. + */ +export interface SessionLimitsExhaustedResponse { + action: SessionLimitsExhaustedResponseAction; + /** + * AI Credits to add to the current max when action is 'add'. + */ + additionalAiCredits?: number; + /** + * New absolute max AI Credits when action is 'set'. + */ + maxAiCredits?: number; +} +/** + * Session event "session.auto_mode_resolved". Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. + */ +/** @experimental */ +export interface AutoModeResolvedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: AutoModeResolvedData; + /** + * When true, the event is transient and not persisted to the session event log on disk + */ + ephemeral?: boolean; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "session.auto_mode_resolved". + */ + type: "session.auto_mode_resolved"; +} +/** + * Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. + */ +/** @experimental */ +export interface AutoModeResolvedData { + /** + * Ordered candidate model list the router returned, when not a fallback + */ + candidateModels?: string[]; + /** + * Per-category classifier scores (0-1) behind the bucket: the granular HYDRA capability scores (reasoning, code_gen, debugging, tool_use), or the binary needs_reasoning/no_reasoning scores when HYDRA didn't run. Lets clients show a breakdown rather than just the bucket. + */ + categoryScores?: { + [k: string]: number | undefined; + }; + /** + * The concrete model the session will use after any intent refinement + */ + chosenModel: string; + /** + * Classifier confidence for the predicted label, when available + */ + confidence?: number; + /** + * The predicted classifier label (e.g. `needs_reasoning`), when available + */ + predictedLabel?: string; + reasoningBucket?: AutoModeResolvedReasoningBucket; +} +/** + * Session event "session.managed_settings_resolved". Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. + */ +/** @experimental */ +export interface ManagedSettingsResolvedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: ManagedSettingsResolvedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "session.managed_settings_resolved". + */ + type: "session.managed_settings_resolved"; +} +/** + * Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. + */ +/** @experimental */ +export interface ManagedSettingsResolvedData { + /** + * Whether enterprise policy disables bypass-permissions ("yolo") mode for this session. Deny-wins across layers, and forced on when `failClosed` is true. + */ + bypassPermissionsDisabled: boolean; + /** + * Whether the device (MDM/plist/registry/file) managed-settings layer was present + */ + deviceManaged: boolean; + /** + * Whether managed policy could not be determined (e.g. a failed server fetch) and the session fell back to the fail-closed restriction. When true, restrictions such as disabling bypass-permissions are enforced even though `settings` may be absent. + */ + failClosed: boolean; + /** + * The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. + */ + managedKeys: string[]; + /** + * Whether the server (account/org) managed-settings layer was present + */ + serverManaged: boolean; + /** + * The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. + */ + settings?: { + [k: string]: unknown | undefined; + }; + source: ManagedSettingsResolvedSource; +} /** * Session event "commands.changed". SDK command registration change notification */ @@ -6929,7 +8077,7 @@ export interface CommandsChangedData { commands: CommandsChangedCommand[]; } /** - * Schema for the `CommandsChangedCommand` type. + * A single slash command available in the session, as listed by the `commands.changed` event. */ export interface CommandsChangedCommand { /** @@ -7099,7 +8247,7 @@ export interface ExitPlanModeCompletedData { selectedAction?: ExitPlanModeAction; } /** - * Session event "session.tools_updated". + * Session event "session.tools_updated". Payload of `session.tools_updated` identifying the model whose resolved tools were updated. */ export interface ToolsUpdatedEvent { /** @@ -7129,7 +8277,7 @@ export interface ToolsUpdatedEvent { type: "session.tools_updated"; } /** - * Schema for the `ToolsUpdatedData` type. + * Payload of `session.tools_updated` identifying the model whose resolved tools were updated. */ export interface ToolsUpdatedData { /** @@ -7138,7 +8286,7 @@ export interface ToolsUpdatedData { model: string; } /** - * Session event "session.background_tasks_changed". + * Session event "session.background_tasks_changed". Empty payload for `session.background_tasks_changed`, indicating background task state changed. */ export interface BackgroundTasksChangedEvent { /** @@ -7168,11 +8316,11 @@ export interface BackgroundTasksChangedEvent { type: "session.background_tasks_changed"; } /** - * Schema for the `BackgroundTasksChangedData` type. + * Empty payload for `session.background_tasks_changed`, indicating background task state changed. */ export interface BackgroundTasksChangedData {} /** - * Session event "session.skills_loaded". + * Session event "session.skills_loaded". Payload of `session.skills_loaded` listing resolved skill metadata. */ export interface SkillsLoadedEvent { /** @@ -7202,7 +8350,7 @@ export interface SkillsLoadedEvent { type: "session.skills_loaded"; } /** - * Schema for the `SkillsLoadedData` type. + * Payload of `session.skills_loaded` listing resolved skill metadata. */ export interface SkillsLoadedData { /** @@ -7211,7 +8359,7 @@ export interface SkillsLoadedData { skills: SkillsLoadedSkill[]; } /** - * Schema for the `SkillsLoadedSkill` type. + * A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. */ export interface SkillsLoadedSkill { /** @@ -7241,7 +8389,7 @@ export interface SkillsLoadedSkill { userInvocable: boolean; } /** - * Session event "session.custom_agents_updated". + * Session event "session.custom_agents_updated". Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. */ export interface CustomAgentsUpdatedEvent { /** @@ -7271,7 +8419,7 @@ export interface CustomAgentsUpdatedEvent { type: "session.custom_agents_updated"; } /** - * Schema for the `CustomAgentsUpdatedData` type. + * Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. */ export interface CustomAgentsUpdatedData { /** @@ -7288,7 +8436,7 @@ export interface CustomAgentsUpdatedData { warnings: string[]; } /** - * Schema for the `CustomAgentsUpdatedAgent` type. + * A single loaded custom agent in `session.custom_agents_updated`, with identity, source, tools, invocability, and model override. */ export interface CustomAgentsUpdatedAgent { /** @@ -7325,7 +8473,7 @@ export interface CustomAgentsUpdatedAgent { userInvocable: boolean; } /** - * Session event "session.mcp_servers_loaded". + * Session event "session.mcp_servers_loaded". Payload of `session.mcp_servers_loaded` listing MCP server status summaries. */ export interface McpServersLoadedEvent { /** @@ -7355,7 +8503,7 @@ export interface McpServersLoadedEvent { type: "session.mcp_servers_loaded"; } /** - * Schema for the `McpServersLoadedData` type. + * Payload of `session.mcp_servers_loaded` listing MCP server status summaries. */ export interface McpServersLoadedData { /** @@ -7364,7 +8512,7 @@ export interface McpServersLoadedData { servers: McpServersLoadedServer[]; } /** - * Schema for the `McpServersLoadedServer` type. + * A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata. */ export interface McpServersLoadedServer { /** @@ -7388,7 +8536,7 @@ export interface McpServersLoadedServer { transport?: McpServerTransport; } /** - * Session event "session.mcp_server_status_changed". + * Session event "session.mcp_server_status_changed". Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. */ export interface McpServerStatusChangedEvent { /** @@ -7418,7 +8566,7 @@ export interface McpServerStatusChangedEvent { type: "session.mcp_server_status_changed"; } /** - * Schema for the `McpServerStatusChangedData` type. + * Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. */ export interface McpServerStatusChangedData { /** @@ -7432,7 +8580,106 @@ export interface McpServerStatusChangedData { status: McpServerStatus; } /** - * Session event "session.extensions_loaded". + * Session event "mcp.tools.list_changed". Payload identifying the MCP server associated with a list change. + */ +export interface McpToolsListChangedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: McpListChangedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "mcp.tools.list_changed". + */ + type: "mcp.tools.list_changed"; +} +/** + * Payload identifying the MCP server associated with a list change. + */ +export interface McpListChangedData { + /** + * Name of the MCP server whose list changed + */ + serverName: string; +} +/** + * Session event "mcp.resources.list_changed". Payload identifying the MCP server associated with a list change. + */ +export interface McpResourcesListChangedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: McpListChangedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "mcp.resources.list_changed". + */ + type: "mcp.resources.list_changed"; +} +/** + * Session event "mcp.prompts.list_changed". Payload identifying the MCP server associated with a list change. + */ +export interface McpPromptsListChangedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: McpListChangedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "mcp.prompts.list_changed". + */ + type: "mcp.prompts.list_changed"; +} +/** + * Session event "session.extensions_loaded". Payload of `session.extensions_loaded` listing discovered extensions and their statuses. */ export interface ExtensionsLoadedEvent { /** @@ -7462,7 +8709,7 @@ export interface ExtensionsLoadedEvent { type: "session.extensions_loaded"; } /** - * Schema for the `ExtensionsLoadedData` type. + * Payload of `session.extensions_loaded` listing discovered extensions and their statuses. */ export interface ExtensionsLoadedData { /** @@ -7471,7 +8718,7 @@ export interface ExtensionsLoadedData { extensions: ExtensionsLoadedExtension[]; } /** - * Schema for the `ExtensionsLoadedExtension` type. + * A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status. */ export interface ExtensionsLoadedExtension { /** @@ -7486,7 +8733,7 @@ export interface ExtensionsLoadedExtension { status: ExtensionsLoadedExtensionStatus; } /** - * Session event "session.canvas.opened". + * Session event "session.canvas.opened". Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. */ /** @experimental */ export interface CanvasOpenedEvent { @@ -7517,7 +8764,7 @@ export interface CanvasOpenedEvent { type: "session.canvas.opened"; } /** - * Schema for the `CanvasOpenedData` type. + * Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. */ /** @experimental */ export interface CanvasOpenedData { @@ -7533,6 +8780,10 @@ export interface CanvasOpenedData { * Owning extension display name, when available */ extensionName?: string; + /** + * Host-local PNG path for the canvas icon, when supplied + */ + icon?: string; /** * Input supplied when the instance was opened */ @@ -7557,7 +8808,7 @@ export interface CanvasOpenedData { url?: string; } /** - * Session event "session.canvas.registry_changed". + * Session event "session.canvas.registry_changed". Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. */ /** @experimental */ export interface CanvasRegistryChangedEvent { @@ -7588,7 +8839,7 @@ export interface CanvasRegistryChangedEvent { type: "session.canvas.registry_changed"; } /** - * Schema for the `CanvasRegistryChangedData` type. + * Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. */ /** @experimental */ export interface CanvasRegistryChangedData { @@ -7598,7 +8849,7 @@ export interface CanvasRegistryChangedData { canvases: CanvasRegistryChangedCanvas[]; } /** - * Schema for the `CanvasRegistryChangedCanvas` type. + * A single canvas declaration in `session.canvas.registry_changed`, including provider IDs, display metadata, input schema, and actions. */ /** @experimental */ export interface CanvasRegistryChangedCanvas { @@ -7626,6 +8877,10 @@ export interface CanvasRegistryChangedCanvas { * Owning extension display name, when available */ extensionName?: string; + /** + * Host-local PNG path for the canvas icon, when supplied + */ + icon?: string; /** * JSON Schema for canvas open input */ @@ -7634,7 +8889,7 @@ export interface CanvasRegistryChangedCanvas { }; } /** - * Schema for the `CanvasRegistryChangedCanvasAction` type. + * A single action within a canvas declaration, with its name, optional description, and optional input schema. */ /** @experimental */ export interface CanvasRegistryChangedCanvasAction { @@ -7654,7 +8909,7 @@ export interface CanvasRegistryChangedCanvasAction { name: string; } /** - * Session event "session.canvas.closed". + * Session event "session.canvas.closed". Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. */ /** @experimental */ export interface CanvasClosedEvent { @@ -7685,7 +8940,7 @@ export interface CanvasClosedEvent { type: "session.canvas.closed"; } /** - * Schema for the `CanvasClosedData` type. + * Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. */ /** @experimental */ export interface CanvasClosedData { @@ -7860,7 +9115,7 @@ export interface CanvasRemovedData { instanceId: string; } /** - * Session event "session.extensions.attachments_pushed". + * Session event "session.extensions.attachments_pushed". Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. */ export interface ExtensionsAttachmentsPushedEvent { /** @@ -7890,7 +9145,7 @@ export interface ExtensionsAttachmentsPushedEvent { type: "session.extensions.attachments_pushed"; } /** - * Schema for the `ExtensionsAttachmentsPushedData` type. + * Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. */ export interface ExtensionsAttachmentsPushedData { /** @@ -7979,7 +9234,7 @@ export interface McpAppToolCallCompleteToolMeta { ui?: McpAppToolCallCompleteToolMetaUI; } /** - * Schema for the `McpAppToolCallCompleteToolMetaUI` type. + * MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. */ export interface McpAppToolCallCompleteToolMetaUI { /** diff --git a/nodejs/src/index.ts b/nodejs/src/index.ts index eebf9add5e..9d3bdcd7f0 100644 --- a/nodejs/src/index.ts +++ b/nodejs/src/index.ts @@ -51,6 +51,7 @@ export type { CommandContext, CommandDefinition, CommandHandler, + CanvasProviderIdentity, CloudSessionOptions, CloudSessionRepository, AutoModeSwitchHandler, @@ -59,8 +60,10 @@ export type { CopilotClientMode, CopilotClientOptions, StdioRuntimeConnection, + InProcessRuntimeConnection, TcpRuntimeConnection, UriRuntimeConnection, + ChildProcessRuntimeConnection, CustomAgentConfig, ElicitationFieldValue, ElicitationHandler, @@ -76,6 +79,9 @@ export type { ForegroundSessionInfo, GetAuthStatusResponse, GetStatusResponse, + GitHubTelemetryNotification, + GitHubTelemetryEvent, + GitHubTelemetryClientInfo, InfiniteSessionConfig, LargeToolOutputConfig, MemoryConfiguration, @@ -144,8 +150,10 @@ export type { Tool, ToolHandler, ToolInvocation, + CurrentToolMetadata, ToolTelemetry, ToolResultObject, + ToolSearchConfig, TypedSessionEventHandler, TypedSessionLifecycleHandler, ZodSchema, diff --git a/nodejs/src/session.ts b/nodejs/src/session.ts index 8bf9589c39..1f71209de8 100644 --- a/nodejs/src/session.ts +++ b/nodejs/src/session.ts @@ -10,7 +10,12 @@ import type { MessageConnection } from "vscode-jsonrpc/node.js"; import { ConnectionError, ErrorCodes, ResponseError } from "vscode-jsonrpc/node.js"; import { createSessionRpc } from "./generated/rpc.js"; -import type { ClientSessionApiHandlers, CanvasActionInvokeResult } from "./generated/rpc.js"; +import type { + ClientSessionApiHandlers, + CanvasActionInvokeResult, + CurrentToolMetadata, + McpOauthPendingRequestResponse, +} from "./generated/rpc.js"; import { type Canvas, CanvasError } from "./canvas.js"; import type { OpenCanvasInstance } from "./generated/rpc.js"; import { getTraceContext } from "./telemetry.js"; @@ -29,6 +34,8 @@ import type { BearerTokenProvider, UiInputOptions, MessageOptions, + McpAuthHandler, + McpAuthRequest, PermissionHandler, PermissionRequest, ContextTier, @@ -90,6 +97,8 @@ function isOpenCanvasInstance(value: unknown): value is OpenCanvasInstance { /** Assistant message event - the final response from the assistant. */ export type AssistantMessageEvent = Extract; +const TOOL_SEARCH_TOOL_NAME = "tool_search_tool"; + /** * Represents a single conversation session with the Copilot CLI. * @@ -115,6 +124,12 @@ export type AssistantMessageEvent = Extract = new Set(); private typedEventHandlers: Map void>> = @@ -124,6 +139,7 @@ export class CopilotSession { private bearerTokenProviders: Map = new Map(); private commandHandlers: Map = new Map(); private permissionHandler?: PermissionHandler; + private mcpAuthHandler?: McpAuthHandler; private userInputHandler?: UserInputHandler; private elicitationHandler?: ElicitationHandler; private exitPlanModeHandler?: ExitPlanModeHandler; @@ -152,9 +168,11 @@ export class CopilotSession { public readonly sessionId: string, private connection: MessageConnection, private _workspacePath?: string, - traceContextProvider?: TraceContextProvider + traceContextProvider?: TraceContextProvider, + options?: { mcpAuthHandler?: McpAuthHandler } ) { this.traceContextProvider = traceContextProvider; + this.mcpAuthHandler = options?.mcpAuthHandler; } /** @@ -499,6 +517,19 @@ export class CopilotSession { if (this.permissionHandler) { void this._executePermissionAndRespond(requestId, permissionRequest); } + } else if (event.type === "mcp.oauth_required") { + const data = event.data as McpAuthRequest | undefined; + if (!data?.requestId) { + return; + } + if (!this.mcpAuthHandler) { + console.warn( + "Received MCP OAuth request without a registered MCP auth handler. " + + `SessionId=${this.sessionId}, RequestId=${data.requestId}` + ); + return; + } + void this._executeMcpAuthAndRespond(data); } else if (event.type === "command.execute") { const { requestId, commandName, command, args } = event.data as { requestId: string; @@ -584,11 +615,26 @@ export class CopilotSession { tracestate?: string ): Promise { try { + // The built-in tool-search tool receives a snapshot of the session's + // currently initialized tools so an override can filter the live + // catalog without issuing its own RPC. Fetch it only for that tool + // to avoid a round-trip on every tool call; a failed fetch simply + // leaves the snapshot undefined rather than failing the tool. + let availableTools: CurrentToolMetadata[] | undefined; + if (toolName === TOOL_SEARCH_TOOL_NAME) { + try { + const metadata = await this.rpc.tools.getCurrentMetadata(); + availableTools = metadata.tools ?? undefined; + } catch { + availableTools = undefined; + } + } const rawResult = await handler(args, { sessionId: this.sessionId, toolCallId, toolName, arguments: args, + availableTools, traceparent, tracestate, }); @@ -661,6 +707,35 @@ export class CopilotSession { } } + /** + * Executes an MCP auth handler and sends the result back via RPC. + * @internal + */ + private async _executeMcpAuthAndRespond(request: McpAuthRequest): Promise { + try { + const result = await this.mcpAuthHandler!(request, { sessionId: this.sessionId }); + const response: McpOauthPendingRequestResponse = + result && "accessToken" in result + ? { kind: "token", ...result } + : { kind: "cancelled" }; + await this.rpc.mcp.oauth.handlePendingRequest({ + requestId: request.requestId, + result: response, + }); + } catch (_error) { + try { + await this.rpc.mcp.oauth.handlePendingRequest({ + requestId: request.requestId, + result: { kind: "cancelled" }, + }); + } catch (rpcError) { + if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) { + throw rpcError; + } + } + } + } + /** * Executes a command handler and sends the result back via RPC. * @internal @@ -1297,7 +1372,7 @@ export class CopilotSession { * * @example * ```typescript - * await session.setModel("gpt-4.1"); + * await session.setModel("gpt-5.4"); * await session.setModel("claude-sonnet-4.6", { reasoningEffort: "high" }); * ``` */ diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index e354bd8218..fc0fa51d00 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -12,16 +12,25 @@ import type { SessionFsProvider } from "./sessionFsProvider.js"; import type { CopilotRequestHandler } from "./copilotRequestHandler.js"; import type { ReasoningSummary, + SessionLimitsConfig, SessionEvent as GeneratedSessionEvent, } from "./generated/session-events.js"; import type { CopilotSession } from "./session.js"; import type { + GitHubTelemetryNotification, ModelBillingTokenPrices, OpenCanvasInstance, RemoteSessionMode, + CurrentToolMetadata, } from "./generated/rpc.js"; import type { ToolSet } from "./toolSet.js"; export type { RemoteSessionMode } from "./generated/rpc.js"; +export type { CurrentToolMetadata } from "./generated/rpc.js"; +export type { + GitHubTelemetryNotification, + GitHubTelemetryEvent, + GitHubTelemetryClientInfo, +} from "./generated/rpc.js"; export type { ModelBillingTokenPrices, ModelBillingTokenPricesLongContext, @@ -89,25 +98,60 @@ export interface TelemetryConfig { */ export type RuntimeConnection = | StdioRuntimeConnection + | InProcessRuntimeConnection | TcpRuntimeConnection | UriRuntimeConnection; /** - * Spawns a runtime child process and communicates over its stdin/stdout. - * This is the default if no {@link CopilotClientOptions.connection} is set. + * Shared shape for the transports that spawn a runtime **child process** + * ({@link StdioRuntimeConnection} and {@link TcpRuntimeConnection}). */ -export interface StdioRuntimeConnection { - readonly kind: "stdio"; +export interface ChildProcessRuntimeConnection { /** Path to the runtime executable. When omitted, the bundled runtime is used. */ readonly path?: string; /** Extra command-line arguments to pass to the runtime process. */ readonly args?: readonly string[]; + /** + * Environment variables for the spawned runtime child process, replacing the + * inherited environment. Cannot be combined with + * {@link CopilotClientOptions.env}; setting both throws when the client is + * constructed. When omitted, the client-level env (or `process.env`) is used. + */ + readonly env?: Record; +} + +/** + * Spawns a runtime child process and communicates over its stdin/stdout. + * This is the default if no {@link CopilotClientOptions.connection} is set. + */ +export interface StdioRuntimeConnection extends ChildProcessRuntimeConnection { + readonly kind: "stdio"; +} + +/** + * Hosts the runtime in-process by loading the native runtime library and speaking + * JSON-RPC over its C ABI (FFI), instead of spawning a runtime child process. The + * native host spawns the CLI worker itself. Construct via + * {@link RuntimeConnection.forInProcess}. + * + * @experimental The in-process (FFI) transport is experimental and its behavior may + * change. Per-client options that are lowered to environment variables — including + * {@link CopilotClientOptions.env}, {@link CopilotClientOptions.telemetry}, + * {@link CopilotClientOptions.gitHubToken}, and + * {@link CopilotClientOptions.baseDirectory} — are **not** honored with this + * transport, because the native runtime loads into the shared host process and its + * worker inherits that process's ambient environment. To configure the in-process + * runtime, set the corresponding environment variables on the host process before + * constructing the client. See https://github.com/github/copilot-sdk/issues/1934. + */ +export interface InProcessRuntimeConnection { + readonly kind: "inprocess"; } /** * Spawns a runtime child process that listens on a TCP socket and connects to it. */ -export interface TcpRuntimeConnection { +export interface TcpRuntimeConnection extends ChildProcessRuntimeConnection { readonly kind: "tcp"; /** * TCP port to listen on. `0` (the default) auto-allocates a free port. @@ -120,10 +164,6 @@ export interface TcpRuntimeConnection { * loopback listener is safe by default. */ readonly connectionToken?: string; - /** Path to the runtime executable. When omitted, the bundled runtime is used. */ - readonly path?: string; - /** Extra command-line arguments to pass to the runtime process. */ - readonly args?: readonly string[]; } /** @@ -147,8 +187,10 @@ export const RuntimeConnection = { * Spawn a runtime child process and communicate over its stdin/stdout. * This is the default if no {@link CopilotClientOptions.connection} is set. */ - forStdio(opts: { path?: string; args?: readonly string[] } = {}): StdioRuntimeConnection { - return { kind: "stdio", path: opts.path, args: opts.args }; + forStdio( + opts: { path?: string; args?: readonly string[]; env?: Record } = {} + ): StdioRuntimeConnection { + return { kind: "stdio", path: opts.path, args: opts.args, env: opts.env }; }, /** * Spawn a runtime child process that listens on a TCP socket and connect to it. @@ -159,6 +201,7 @@ export const RuntimeConnection = { connectionToken?: string; path?: string; args?: readonly string[]; + env?: Record; } = {} ): TcpRuntimeConnection { return { @@ -167,6 +210,7 @@ export const RuntimeConnection = { connectionToken: opts.connectionToken, path: opts.path, args: opts.args, + env: opts.env, }; }, /** @@ -176,6 +220,18 @@ export const RuntimeConnection = { forUri(url: string, opts: { connectionToken?: string } = {}): UriRuntimeConnection { return { kind: "uri", url, connectionToken: opts.connectionToken }; }, + /** + * Host the runtime in-process over the native runtime library's C ABI (FFI). + * + * @experimental Per-client options lowered to environment variables (`env`, + * `telemetry`, `gitHubToken`, `baseDirectory`) are **not** honored in-process; + * the worker inherits the host process's ambient environment. Set the + * corresponding environment variables on the host process instead. See + * https://github.com/github/copilot-sdk/issues/1934. + */ + forInProcess(): InProcessRuntimeConnection { + return { kind: "inprocess" }; + }, } as const; /** @@ -338,6 +394,18 @@ export interface CopilotClientOptions { */ requestHandler?: CopilotRequestHandler; + /** + * Experimental. Receives GitHub telemetry events the runtime forwards to + * this connection. When set, the client opts each session it creates or + * resumes into telemetry forwarding and dispatches each + * `gitHubTelemetry.event` notification to this connection-global handler; + * each {@link GitHubTelemetryNotification} carries its originating + * `sessionId`. + * + * @experimental + */ + onGitHubTelemetry?: (notification: GitHubTelemetryNotification) => void | Promise; + /** * Server-wide idle timeout for sessions in seconds. * Sessions without activity for this duration are automatically cleaned up. @@ -384,6 +452,10 @@ export type ToolResultObject = { error?: string; sessionLog?: string; toolTelemetry?: ToolTelemetry; + /** + * Names of tools returned by a tool-search tool. + */ + toolReferences?: string[]; }; export type ToolResult = string | ToolResultObject; @@ -508,6 +580,14 @@ export interface ToolInvocation { toolCallId: string; toolName: string; arguments: unknown; + /** + * Snapshot of the session's currently initialized tools. Populated by the + * SDK only when this invocation targets the built-in tool-search tool + * (`tool_search_tool`), so a tool-search override can rank/filter the live + * catalog — including MCP tools configured in settings — without issuing its + * own RPC. `undefined` for every other tool invocation. + */ + availableTools?: CurrentToolMetadata[]; /** W3C Trace Context traceparent from the CLI's execute_tool span. */ traceparent?: string; /** W3C Trace Context tracestate from the CLI's execute_tool span. */ @@ -560,6 +640,14 @@ export interface Tool { * Optional; defaults to `"auto"`. */ defer?: "auto" | "never"; + /** + * Opaque, host-defined metadata associated with the tool definition. + * + * Keys are namespaced and are not part of the stable public API. Values are + * not interpreted and may be recognized to inform host-specific behavior. + * Unknown keys are preserved and round-tripped untouched. + */ + metadata?: Record; } /** @@ -575,11 +663,41 @@ export function defineTool( overridesBuiltInTool?: boolean; skipPermission?: boolean; defer?: "auto" | "never"; + metadata?: Record; } ): Tool { return { name, ...config }; } +/** + * SDK-supplied override for the runtime's built-in tool-search behavior. + * + * Tool search lets the model discover tools on demand instead of loading every + * tool definition up front. When the total tool count exceeds the deferral + * threshold, MCP and external tools are marked as deferred and surfaced through + * the built-in `tool_search_tool`. + * + * To override the tool-search tool's model-facing definition and/or its + * execution, register a {@link Tool} named `tool_search_tool` with + * `overridesBuiltInTool: true`. To customize the in-prompt tool-search + * guidance, use the `tool_instructions` section of {@link SystemMessageConfig} + * in `"customize"` mode. + */ +export interface ToolSearchConfig { + /** + * Toggle to enable/disable tool search. When disabled, all tools are pre-loaded + * and the model's active tool set is not deferred. + */ + enabled?: boolean; + + /** + * Overrides the total tool count at which MCP and external tools are + * automatically deferred behind tool search. Defaults to the built-in + * threshold (30) when omitted. + */ + deferThreshold?: number; +} + // ============================================================================ // Commands // ============================================================================ @@ -1523,6 +1641,12 @@ export interface CustomAgentConfig { * falling back to the parent session model if unavailable. */ model?: string; + /** + * Reasoning effort level for this agent's model. + * When omitted, no per-agent override is sent and the backend chooses its + * default. The parent session effort is not inherited. + */ + reasoningEffort?: ReasoningEffort; } /** @@ -1615,6 +1739,76 @@ export type ReasoningEffort = "low" | "medium" | "high" | "xhigh"; */ export type ContextTier = "default" | "long_context"; +/** Parsed parameters from an MCP server's WWW-Authenticate response. */ +export interface McpAuthWwwAuthenticateParams { + /** Parsed resource_metadata URL used for protected-resource metadata discovery, if present. */ + resourceMetadataUrl?: string; + /** Parsed OAuth scope, if present. */ + scope?: string; + /** Parsed OAuth error, if present. */ + error?: string; +} + +/** Static OAuth client configuration supplied by the MCP server, if available. */ +export interface McpAuthStaticClientConfig { + /** OAuth client ID for the server. */ + clientId: string; + /** Optional OAuth client secret for confidential static clients. */ + clientSecret?: string; + /** Optional non-default OAuth grant type. */ + grantType?: "client_credentials"; + /** Whether this is a public OAuth client. */ + publicClient?: boolean; +} + +/** MCP OAuth request that the SDK host can satisfy with a host-acquired token. */ +export interface McpAuthRequest { + /** Unique request identifier used by the SDK when responding. */ + requestId: string; + /** Display name of the MCP server that requires OAuth. */ + serverName: string; + /** URL of the MCP server that requires OAuth. */ + serverUrl: string; + /** Why the runtime is requesting host-provided OAuth credentials. */ + reason: "initial" | "refresh" | "reauth" | "upscope"; + /** Parsed WWW-Authenticate parameters from the MCP server. */ + wwwAuthenticateParams?: McpAuthWwwAuthenticateParams; + /** Raw RFC 9728 protected-resource metadata JSON fetched by the runtime, if available. */ + resourceMetadata?: string; + /** Static OAuth client configuration, if the server specifies one. */ + staticClientConfig?: McpAuthStaticClientConfig; +} + +/** Host-provided OAuth token data for a pending MCP OAuth request. */ +export interface McpAuthToken { + /** Access token acquired by the SDK host. */ + accessToken: string; + /** OAuth token type. Defaults to Bearer when omitted. */ + tokenType?: string; + /** Token lifetime in seconds, if known. */ + expiresIn?: number; +} + +/** + * Result returned by an MCP auth request handler. + * + * Return `null`/`undefined` or `{ kind: "cancelled" }` to cancel the pending + * OAuth request. Return `{ kind: "token", ... }` to provide host-acquired + * OAuth token data. + */ +export type McpAuthResult = ({ kind: "token" } & McpAuthToken) | { kind: "cancelled" }; + +/** Callback invoked when an MCP server requires OAuth and the SDK host opted in. */ +export type McpAuthHandler = ( + request: McpAuthRequest, + context: { sessionId: string } +) => + | McpAuthResult + | McpAuthToken + | null + | undefined + | Promise; + /** * Stable extension identity for session participants that provide canvases. */ @@ -1625,6 +1819,23 @@ export interface ExtensionInfo { name: string; } +/** + * Stable identity for a host/SDK connection that supplies built-in canvases. + * + * When set on session create or resume, the runtime uses {@link id} verbatim + * as the agent-facing canvas extension id, so canvases declared on a control + * connection survive stdio reconnect and CLI process restart instead of being + * re-keyed to a per-connection id. The id is opaque to the runtime; a + * per-window-stable value such as `app:builtin:` is recommended. An + * id beginning with `connection:` is reserved and ignored by the runtime. + */ +export interface CanvasProviderIdentity { + /** Opaque, stable provider id used verbatim as the canvas extension id. */ + id: string; + /** Optional display name surfaced as the canvas extension name. */ + name?: string; +} + /** * Provider-scoped options for the Copilot API (CAPI). * @@ -1769,6 +1980,14 @@ export interface SessionConfigBase { */ extensionInfo?: ExtensionInfo; + /** + * Stable identity for a host/SDK connection that supplies built-in + * canvases. When set, the runtime uses `id` verbatim as the agent-facing + * canvas extension id, so canvases declared on a control connection survive + * reconnect and CLI restart. Honored on session create and resume. + */ + canvasProvider?: CanvasProviderIdentity; + /** * Slash commands registered for this session. * When the CLI has a TUI, each command appears as `/name` for the user to invoke. @@ -1782,6 +2001,15 @@ export interface SessionConfigBase { */ systemMessage?: SystemMessageConfig; + /** + * Override for the runtime's built-in tool-search behavior. + * + * To also override the tool-search tool's implementation, register a + * {@link Tool} named `tool_search_tool` with `overridesBuiltInTool: true` in + * {@link SessionConfigBase.tools}. + */ + toolSearch?: ToolSearchConfig; + /** * List of tool names to allow. When specified, only these tools will be available. * @@ -1805,6 +2033,13 @@ export interface SessionConfigBase { */ excludedTools?: string[] | ToolSet; + /** + * Names of built-in agents to exclude from the session. Excluded built-in + * agents are hidden from discovery and cannot be selected or invoked unless + * a custom agent with the same name is configured. + */ + excludedBuiltinAgents?: string[]; + /** * Custom provider configuration (BYOK - Bring Your Own Key). * When specified, uses the provided API endpoint instead of the Copilot API. @@ -1854,6 +2089,20 @@ export interface SessionConfigBase { */ enableSessionTelemetry?: boolean; + /** + * Enables native model citations for supported providers. + * + * @experimental + */ + enableCitations?: boolean; + + /** + * Limits applied to this session's current accounting window. + * + * @experimental + */ + sessionLimits?: SessionLimitsConfig; + /** * When true, the runtime skips loading custom-instruction sources * (e.g. `.github/copilot-instructions.md`, `AGENTS.md`, `CLAUDE.md`). @@ -1898,6 +2147,13 @@ export interface SessionConfigBase { */ onPermissionRequest?: PermissionHandler; + /** + * Optional handler for MCP OAuth requests from MCP servers. + * When provided, the SDK can satisfy MCP server OAuth requests with + * host-provided token data or cancellation. + */ + onMcpAuthRequest?: McpAuthHandler; + /** * Handler for user input requests from the agent. * When provided, enables the ask_user tool allowing the agent to ask questions. @@ -2072,6 +2328,14 @@ export interface SessionConfigBase { */ gitHubToken?: string; + /** + * Opt-in: when true, the runtime self-fetches enterprise managed settings + * (bypass-permissions policy) at session bootstrap using the session's + * `gitHubToken`. Requires {@link SessionConfigBase.gitHubToken} to be set; + * if omitted, the runtime is expected to reject session creation (fail-closed). + */ + enableManagedSettings?: boolean; + /** * When true, skips embedding-based retrieval for this session. * Use in multitenant deployments to prevent cross-session information leakage diff --git a/nodejs/test/client.test.ts b/nodejs/test/client.test.ts index 96d7da30cf..e90143cb44 100644 --- a/nodejs/test/client.test.ts +++ b/nodejs/test/client.test.ts @@ -1,12 +1,13 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { EventEmitter } from "node:events"; -import { describe, expect, it, onTestFinished, vi } from "vitest"; import { PassThrough } from "stream"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; import { approveAll, CopilotClient, createCanvas, RuntimeConnection, + type GitHubTelemetryNotification, type ModelInfo, } from "../src/index.js"; import { CopilotSession } from "../src/session.js"; @@ -14,6 +15,10 @@ import { defaultJoinSessionPermissionHandler } from "../src/types.js"; // This file is for unit tests. Where relevant, prefer to add e2e tests in e2e/*.test.ts instead +async function stopClient(client: CopilotClient): Promise { + await client.stop(); +} + describe("CopilotClient", () => { it("disposes the stdio connection when child stdin emits an error", async () => { const client = new CopilotClient(); @@ -41,10 +46,243 @@ describe("CopilotClient", () => { expect(spy).not.toHaveBeenCalled(); }); + it("responds to MCP OAuth requests with host token data", async () => { + const sendRequest = vi.fn(async () => ({ success: true })); + let observedRequest: any; + const session = new CopilotSession( + "session-1", + { sendRequest } as any, + undefined, + undefined, + { + mcpAuthHandler: async (request) => { + observedRequest = request; + return { + accessToken: "host-token", + tokenType: "Bearer", + expiresIn: 3600, + }; + }, + } + ); + + await (session as any)._executeMcpAuthAndRespond({ + requestId: "oauth-request", + serverName: "oauth-server", + serverUrl: "https://example.com/mcp", + reason: "initial", + wwwAuthenticateParams: { + resourceMetadataUrl: "https://example.com/.well-known/oauth-protected-resource", + }, + resourceMetadata: '{"resource":"https://example.com/mcp"}', + staticClientConfig: { + clientId: "static-client", + clientSecret: "static-secret", + grantType: "client_credentials", + publicClient: false, + }, + }); + + expect(observedRequest.resourceMetadata).toBe('{"resource":"https://example.com/mcp"}'); + expect(observedRequest.staticClientConfig).toEqual({ + clientId: "static-client", + clientSecret: "static-secret", + grantType: "client_credentials", + publicClient: false, + }); + expect(sendRequest).toHaveBeenCalledWith("session.mcp.oauth.handlePendingRequest", { + sessionId: "session-1", + requestId: "oauth-request", + result: { + kind: "token", + accessToken: "host-token", + tokenType: "Bearer", + expiresIn: 3600, + }, + }); + }); + + it("passes MCP OAuth requests through when optional metadata is absent", async () => { + let observedRequest: any; + const session = new CopilotSession( + "session-1", + { sendRequest: vi.fn(async () => ({ success: true })) } as any, + undefined, + undefined, + { + mcpAuthHandler: async (request) => { + observedRequest = request; + return { kind: "cancelled" }; + }, + } + ); + + await (session as any)._executeMcpAuthAndRespond({ + requestId: "oauth-request", + serverName: "oauth-server", + serverUrl: "https://example.com/mcp", + reason: "initial", + }); + + expect(observedRequest.reason).toBe("initial"); + expect(observedRequest.resourceMetadata).toBeUndefined(); + expect(observedRequest.wwwAuthenticateParams).toBeUndefined(); + }); + + it("registers interest in MCP OAuth required events after create when an auth handler is configured", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.eventLog.registerInterest") { + return { id: "interest-1" }; + } + if (method === "session.create") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + await client.createSession({ + onPermissionRequest: approveAll, + onMcpAuthRequest: () => ({ kind: "cancelled" }), + }); + + expect(spy.mock.calls[0][0]).toBe("session.create"); + expect(spy.mock.calls[1]).toEqual([ + "session.eventLog.registerInterest", + expect.objectContaining({ eventType: "mcp.oauth_required" }), + ]); + expect(spy.mock.calls[1][1].sessionId).toBe(spy.mock.calls[0][1].sessionId); + }); + + it("does not register MCP OAuth interest without an auth handler", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.create") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + await client.createSession({ + onPermissionRequest: approveAll, + onEvent: () => {}, + }); + + expect(spy).not.toHaveBeenCalledWith( + "session.eventLog.registerInterest", + expect.objectContaining({ eventType: "mcp.oauth_required" }) + ); + expect(spy).toHaveBeenCalledWith( + "session.create", + expect.objectContaining({ requestPermission: true }) + ); + }); + + it("registers MCP OAuth interest after cloud create only when an auth handler is configured", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + + let cloudCreateCount = 0; + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, _params: any) => { + if (method === "session.eventLog.registerInterest") { + return { id: "interest-1" }; + } + if (method === "session.create") + return { sessionId: `server-assigned-session-${++cloudCreateCount}` }; + throw new Error(`Unexpected method: ${method}`); + }); + + await client.createSession({ + onPermissionRequest: approveAll, + cloud: { repository: { owner: "github", name: "copilot-sdk", branch: "main" } }, + }); + + expect(spy).not.toHaveBeenCalledWith( + "session.eventLog.registerInterest", + expect.objectContaining({ eventType: "mcp.oauth_required" }) + ); + + spy.mockClear(); + await client.createSession({ + onPermissionRequest: approveAll, + onMcpAuthRequest: () => ({ kind: "cancelled" }), + cloud: { repository: { owner: "github", name: "copilot-sdk", branch: "main" } }, + }); + + expect(spy.mock.calls[0][0]).toBe("session.create"); + expect(spy.mock.calls[1]).toEqual([ + "session.eventLog.registerInterest", + { sessionId: "server-assigned-session-2", eventType: "mcp.oauth_required" }, + ]); + }); + + it("registers MCP OAuth interest after resuming only when an auth handler is configured", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.eventLog.registerInterest") { + return { id: "interest-1" }; + } + if (method === "session.resume") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + await client.resumeSession("session-with-auth", { + onPermissionRequest: approveAll, + onMcpAuthRequest: () => ({ kind: "cancelled" }), + }); + + // `session.eventLog.registerInterest` is session-scoped: the runtime only + // registers the session id while handling `session.resume`, so resume must + // be sent BEFORE registering interest. + const resumeIndex = spy.mock.calls.findIndex(([method]) => method === "session.resume"); + const interestIndex = spy.mock.calls.findIndex( + ([method]) => method === "session.eventLog.registerInterest" + ); + expect(resumeIndex).toBeGreaterThanOrEqual(0); + expect(interestIndex).toBeGreaterThanOrEqual(0); + expect(resumeIndex).toBeLessThan(interestIndex); + expect(spy.mock.calls[resumeIndex][1]).toEqual( + expect.objectContaining({ sessionId: "session-with-auth", requestPermission: true }) + ); + expect(spy.mock.calls[interestIndex][1]).toEqual({ + sessionId: "session-with-auth", + eventType: "mcp.oauth_required", + }); + + spy.mockClear(); + await client.resumeSession("session-without-auth", { + onPermissionRequest: approveAll, + onEvent: () => {}, + }); + + expect(spy).not.toHaveBeenCalledWith( + "session.eventLog.registerInterest", + expect.objectContaining({ eventType: "mcp.oauth_required" }) + ); + expect(spy).toHaveBeenCalledWith( + "session.resume", + expect.objectContaining({ sessionId: "session-without-auth", requestPermission: true }) + ); + }); + it("forwards canvas declarations and request flags in session.create", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const canvas = createCanvas({ id: "counter", @@ -67,6 +305,7 @@ describe("CopilotClient", () => { requestCanvasRenderer: true, requestExtensions: true, extensionInfo: { source: "github-app", name: "counter-provider" }, + canvasProvider: { id: "app:builtin:window-1", name: "Built-in" }, }); const payload = spy.mock.calls.find(([method]) => method === "session.create")![1] as any; @@ -84,12 +323,16 @@ describe("CopilotClient", () => { source: "github-app", name: "counter-provider", }); + expect(payload.canvasProvider).toEqual({ + id: "app:builtin:window-1", + name: "Built-in", + }); }); it("forwards canvas declarations in session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const canvas = createCanvas({ @@ -111,6 +354,7 @@ describe("CopilotClient", () => { requestCanvasRenderer: true, requestExtensions: true, extensionInfo: { source: "github-app", name: "counter-provider" }, + canvasProvider: { id: "app:builtin:window-1" }, }); const payload = spy.mock.calls.find(([method]) => method === "session.resume")![1] as any; @@ -121,13 +365,14 @@ describe("CopilotClient", () => { source: "github-app", name: "counter-provider", }); + expect(payload.canvasProvider).toEqual({ id: "app:builtin:window-1" }); expect(payload.openCanvasInstances).toBeUndefined(); }); it("forwards reasoningSummary in session.create and session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -159,7 +404,7 @@ describe("CopilotClient", () => { it("forwards contextTier in session.create and session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -188,11 +433,281 @@ describe("CopilotClient", () => { expect(resumePayload.contextTier).toBe("default"); }); - it("forwards expAssignments in session.create and session.resume", async () => { + it("forwards tool metadata verbatim in session.create and session.resume", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => client.forceStop()); + + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.create") return { sessionId: params.sessionId }; + if (method === "session.resume") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + const metadata = { + "github.com/copilot:safeForTelemetry": { name: true, inputsNames: false }, + }; + const tool = { + name: "my_tool", + description: "a tool", + parameters: { type: "object", properties: {} }, + metadata, + }; + + const session = await client.createSession({ + onPermissionRequest: approveAll, + tools: [tool], + }); + await client.resumeSession(session.sessionId, { + onPermissionRequest: approveAll, + tools: [tool], + }); + + const createPayload = spy.mock.calls.find( + ([method]) => method === "session.create" + )![1] as any; + const resumePayload = spy.mock.calls.find( + ([method]) => method === "session.resume" + )![1] as any; + expect(createPayload.tools[0].metadata).toEqual(metadata); + expect(resumePayload.tools[0].metadata).toEqual(metadata); + }); + + it("omits tool metadata from session.create when unset", async () => { const client = new CopilotClient(); await client.start(); onTestFinished(() => client.forceStop()); + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.create") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + await client.createSession({ + onPermissionRequest: approveAll, + tools: [{ name: "my_tool", description: "a tool" }], + }); + + const createPayload = spy.mock.calls.find( + ([method]) => method === "session.create" + )![1] as any; + expect(createPayload.tools[0].metadata).toBeUndefined(); + }); + + it("forwards new session options in session.create and session.resume", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.create") return { sessionId: params.sessionId }; + if (method === "session.resume") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + const session = await client.createSession({ + onPermissionRequest: approveAll, + enableCitations: true, + excludedBuiltinAgents: ["explore"], + sessionLimits: { maxAiCredits: 30 }, + }); + await client.resumeSession(session.sessionId, { + onPermissionRequest: approveAll, + enableCitations: false, + excludedBuiltinAgents: ["task"], + sessionLimits: { maxAiCredits: 15 }, + }); + + const createPayload = spy.mock.calls.find( + ([method]) => method === "session.create" + )![1] as any; + const resumePayload = spy.mock.calls.find( + ([method]) => method === "session.resume" + )![1] as any; + expect(createPayload.enableCitations).toBe(true); + expect(createPayload.excludedBuiltinAgents).toEqual(["explore"]); + expect(createPayload.sessionLimits).toEqual({ maxAiCredits: 30 }); + expect(resumePayload.enableCitations).toBe(false); + expect(resumePayload.excludedBuiltinAgents).toEqual(["task"]); + expect(resumePayload.sessionLimits).toEqual({ maxAiCredits: 15 }); + }); + + it("opts into GitHub telemetry forwarding when onGitHubTelemetry is provided", async () => { + const client = new CopilotClient({ onGitHubTelemetry: () => {} }); + await client.start(); + onTestFinished(() => stopClient(client)); + + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.create") return { sessionId: params.sessionId }; + if (method === "session.resume") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + const session = await client.createSession({ onPermissionRequest: approveAll }); + await client.resumeSession(session.sessionId, { onPermissionRequest: approveAll }); + + const createPayload = spy.mock.calls.find( + ([method]) => method === "session.create" + )![1] as any; + const resumePayload = spy.mock.calls.find( + ([method]) => method === "session.resume" + )![1] as any; + expect(createPayload.enableGitHubTelemetryForwarding).toBe(true); + expect(resumePayload.enableGitHubTelemetryForwarding).toBe(true); + }); + + it("opts into GitHub telemetry forwarding on the connect handshake when a handler is provided", async () => { + const client = new CopilotClient({ onGitHubTelemetry: () => {} }); + onTestFinished(() => stopClient(client)); + + const sendRequest = vi.fn(async (method: string) => { + if (method === "connect") return { ok: true, protocolVersion: 3, version: "test" }; + throw new Error(`Unexpected method: ${method}`); + }); + (client as any).connection = { sendRequest }; + + await (client as any).verifyProtocolVersion(); + + const connectCall = sendRequest.mock.calls.find(([method]) => method === "connect"); + expect(connectCall).toBeDefined(); + expect((connectCall![1] as any).enableGitHubTelemetryForwarding).toBe(true); + }); + + it("does not opt into GitHub telemetry forwarding on the connect handshake without a handler", async () => { + const client = new CopilotClient(); + onTestFinished(() => stopClient(client)); + + const sendRequest = vi.fn(async (method: string) => { + if (method === "connect") return { ok: true, protocolVersion: 3, version: "test" }; + throw new Error(`Unexpected method: ${method}`); + }); + (client as any).connection = { sendRequest }; + + await (client as any).verifyProtocolVersion(); + + const connectCall = sendRequest.mock.calls.find(([method]) => method === "connect"); + expect(connectCall).toBeDefined(); + expect((connectCall![1] as any).enableGitHubTelemetryForwarding).toBeUndefined(); + }); + + it("does not opt into GitHub telemetry forwarding without a handler", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + + const spy = vi + .spyOn((client as any).connection!, "sendRequest") + .mockImplementation(async (method: string, params: any) => { + if (method === "session.create") return { sessionId: params.sessionId }; + throw new Error(`Unexpected method: ${method}`); + }); + + await client.createSession({ onPermissionRequest: approveAll }); + + const createPayload = spy.mock.calls.find( + ([method]) => method === "session.create" + )![1] as any; + expect(createPayload.enableGitHubTelemetryForwarding).toBeUndefined(); + }); + + it("dispatches a real gitHubTelemetry.event wire message to the handler", async () => { + const { createMessageConnection, StreamMessageReader, StreamMessageWriter } = + await import("vscode-jsonrpc/node.js"); + const { registerClientGlobalApiHandlers } = await import("../src/generated/rpc.js"); + + const clientToServer = new PassThrough(); + const serverToClient = new PassThrough(); + + const clientConn = createMessageConnection( + new StreamMessageReader(serverToClient), + new StreamMessageWriter(clientToServer) + ); + const serverConn = createMessageConnection( + new StreamMessageReader(clientToServer), + new StreamMessageWriter(serverToClient) + ); + onTestFinished(() => { + clientConn.dispose(); + serverConn.dispose(); + }); + + const received: GitHubTelemetryNotification[] = []; + let resolveReceived: () => void; + const got = new Promise((resolve) => { + resolveReceived = resolve; + }); + + registerClientGlobalApiHandlers(clientConn, { + gitHubTelemetry: { + event: async (notification) => { + received.push(notification); + resolveReceived(); + }, + }, + }); + + clientConn.listen(); + serverConn.listen(); + + const notification: GitHubTelemetryNotification = { + sessionId: "session-1", + restricted: false, + event: { + kind: "tool_call_executed", + properties: { tool: "shell" }, + metrics: { duration_ms: 42 }, + }, + }; + + // Deliver the event as a real JSON-RPC *notification* (no id) and confirm + // the generated dispatcher routes it to the registered handler. The runtime + // forwards telemetry via `sendNotification`, which only fires `onNotification` + // handlers — an `onRequest` registration would never be invoked, so sending a + // notification here guards against regressing back to request-style dispatch. + serverConn.sendNotification("gitHubTelemetry.event", notification); + await got; + + expect(received).toEqual([notification]); + }); + + it("registers no gitHubTelemetry handler when onGitHubTelemetry is omitted", () => { + const client = new CopilotClient(); + onTestFinished(() => stopClient(client)); + + const handlers = (client as any).clientGlobalHandlers; + expect(handlers.gitHubTelemetry).toBeUndefined(); + }); + + it("forwards gitHubTelemetry events to the onGitHubTelemetry handler", () => { + const received: GitHubTelemetryNotification[] = []; + const client = new CopilotClient({ onGitHubTelemetry: (n) => received.push(n) }); + onTestFinished(() => stopClient(client)); + + const handlers = (client as any).clientGlobalHandlers; + expect(handlers.gitHubTelemetry).toBeDefined(); + + const notification: GitHubTelemetryNotification = { + sessionId: "session-1", + restricted: false, + event: { kind: "tool_call_executed", properties: {}, metrics: {} }, + }; + handlers.gitHubTelemetry.event(notification); + expect(received).toEqual([notification]); + }); + + it("forwards expAssignments in session.create and session.resume", async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + const spy = vi .spyOn((client as any).connection!, "sendRequest") .mockImplementation(async (method: string, params: any) => { @@ -228,7 +743,7 @@ describe("CopilotClient", () => { it("omits expAssignments from session.create and session.resume when unset", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -254,7 +769,7 @@ describe("CopilotClient", () => { it("forwards capi options in session.create and session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -286,7 +801,7 @@ describe("CopilotClient", () => { it("forwards pluginDirectories and largeOutput in session.create and session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -527,7 +1042,7 @@ describe("CopilotClient", () => { it("forwards clientName in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ clientName: "my-app", onPermissionRequest: approveAll }); @@ -541,7 +1056,7 @@ describe("CopilotClient", () => { it("forwards cloud options in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -566,7 +1081,7 @@ describe("CopilotClient", () => { it("forwards clientName in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); // Mock sendRequest to capture the call without hitting the runtime @@ -591,7 +1106,7 @@ describe("CopilotClient", () => { it("forwards enableSessionTelemetry in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -608,7 +1123,7 @@ describe("CopilotClient", () => { it("forwards enableSessionTelemetry in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -632,7 +1147,7 @@ describe("CopilotClient", () => { it("forwards enableOnDemandInstructionDiscovery in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -649,7 +1164,7 @@ describe("CopilotClient", () => { it("forwards enableOnDemandInstructionDiscovery in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -676,7 +1191,7 @@ describe("CopilotClient", () => { it("defaults includeSubAgentStreamingEvents to true in session.create when not specified", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ onPermissionRequest: approveAll }); @@ -688,7 +1203,7 @@ describe("CopilotClient", () => { it("forwards explicit false for includeSubAgentStreamingEvents in session.create", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -703,7 +1218,7 @@ describe("CopilotClient", () => { it("defaults includeSubAgentStreamingEvents to true in session.resume when not specified", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -722,7 +1237,7 @@ describe("CopilotClient", () => { it("forwards explicit false for includeSubAgentStreamingEvents in session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -744,7 +1259,7 @@ describe("CopilotClient", () => { it("defaults mcpOAuthTokenStorage to 'in-memory' in session.create when mode is empty", async () => { const client = new CopilotClient({ mode: "empty", baseDirectory: "/tmp/copilot-test" }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -762,7 +1277,7 @@ describe("CopilotClient", () => { it("does not send mcpOAuthTokenStorage in session.create when mode is copilot-cli", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ onPermissionRequest: approveAll }); @@ -774,7 +1289,7 @@ describe("CopilotClient", () => { it("forwards explicit 'persistent' for mcpOAuthTokenStorage in session.create", async () => { const client = new CopilotClient({ mode: "empty", baseDirectory: "/tmp/copilot-test" }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -796,7 +1311,7 @@ describe("CopilotClient", () => { it("defaults mcpOAuthTokenStorage to 'in-memory' in session.resume when mode is empty", async () => { const client = new CopilotClient({ mode: "empty", baseDirectory: "/tmp/copilot-test" }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -816,7 +1331,7 @@ describe("CopilotClient", () => { it("forwards explicit 'persistent' for mcpOAuthTokenStorage in session.resume", async () => { const client = new CopilotClient({ mode: "empty", baseDirectory: "/tmp/copilot-test" }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -840,7 +1355,7 @@ describe("CopilotClient", () => { it("defaults memory to { enabled: false } in session.create when mode is empty", async () => { const client = new CopilotClient({ mode: "empty", baseDirectory: "/tmp/copilot-test" }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -858,7 +1373,7 @@ describe("CopilotClient", () => { it("does not send memory in session.create when mode is copilot-cli", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ onPermissionRequest: approveAll }); @@ -870,7 +1385,7 @@ describe("CopilotClient", () => { it("forwards explicit memory config in session.create even in empty mode", async () => { const client = new CopilotClient({ mode: "empty", baseDirectory: "/tmp/copilot-test" }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -892,7 +1407,7 @@ describe("CopilotClient", () => { it("defaults memory to { enabled: false } in session.resume when mode is empty", async () => { const client = new CopilotClient({ mode: "empty", baseDirectory: "/tmp/copilot-test" }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -912,7 +1427,7 @@ describe("CopilotClient", () => { it("does not send memory in session.resume when mode is copilot-cli", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -931,7 +1446,7 @@ describe("CopilotClient", () => { it("forwards continuePendingWork in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -953,7 +1468,7 @@ describe("CopilotClient", () => { it("omits continuePendingWork from session.resume payload when not specified", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -972,7 +1487,7 @@ describe("CopilotClient", () => { it("forwards memory configuration in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -995,7 +1510,7 @@ describe("CopilotClient", () => { it("forwards memory configuration in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1017,7 +1532,7 @@ describe("CopilotClient", () => { it("omits memory from session.create payload when not specified", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -1038,7 +1553,7 @@ describe("CopilotClient", () => { it("forwards provider headers in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi .spyOn((client as any).connection!, "sendRequest") @@ -1079,7 +1594,7 @@ describe("CopilotClient", () => { it("forwards provider headers in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1120,7 +1635,7 @@ describe("CopilotClient", () => { it("forwards defaultAgent in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -1139,7 +1654,7 @@ describe("CopilotClient", () => { it("forwards defaultAgent in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi.spyOn((client as any).connection!, "sendRequest"); @@ -1159,7 +1674,7 @@ describe("CopilotClient", () => { it("forwards instructionDirectories in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const instructionDirectories = ["C:\\extra-instructions", "C:\\more-instructions"]; const spy = vi.spyOn((client as any).connection!, "sendRequest"); @@ -1177,7 +1692,7 @@ describe("CopilotClient", () => { it("forwards instructionDirectories in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const instructionDirectories = ["C:\\resume-instructions"]; @@ -1205,7 +1720,7 @@ describe("CopilotClient", () => { it("does not request permissions on session.resume when using the default joinSession handler", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1232,7 +1747,7 @@ describe("CopilotClient", () => { it("requests permissions on session.resume when using an explicit handler", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1259,7 +1774,7 @@ describe("CopilotClient", () => { it("forwards mode callback request flags in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1289,7 +1804,7 @@ describe("CopilotClient", () => { it("sends session.model.switchTo RPC with correct params", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); @@ -1315,7 +1830,7 @@ describe("CopilotClient", () => { it("sends reasoning options with session.model.switchTo when provided", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); @@ -1557,13 +2072,84 @@ describe("CopilotClient", () => { /gitHubToken and useLoggedInUser cannot be used with RuntimeConnection.forUri/ ); }); + + it("should throw error when env is used with forInProcess", () => { + expect(() => { + new CopilotClient({ + connection: RuntimeConnection.forInProcess(), + env: { FOO: "bar" }, + logLevel: "error", + }); + }).toThrow(/env is not supported with RuntimeConnection.forInProcess/); + }); + + it("should throw error when telemetry is used with forInProcess", () => { + expect(() => { + new CopilotClient({ + connection: RuntimeConnection.forInProcess(), + telemetry: { otlpEndpoint: "http://localhost:4318" }, + logLevel: "error", + }); + }).toThrow(/telemetry is not supported with RuntimeConnection.forInProcess/); + }); + + it("should throw error when workingDirectory is used with forInProcess", () => { + expect(() => { + new CopilotClient({ + connection: RuntimeConnection.forInProcess(), + workingDirectory: "/tmp", + logLevel: "error", + }); + }).toThrow(/workingDirectory is not supported with RuntimeConnection.forInProcess/); + }); + + it("should throw error when env is set on both the client and a stdio connection", () => { + expect(() => { + new CopilotClient({ + connection: RuntimeConnection.forStdio({ env: { FOO: "conn" } }), + env: { FOO: "client" }, + logLevel: "error", + }); + }).toThrow( + /Set environment variables via either the client-level env option or the connection/ + ); + }); + + it("should throw error when env is set on both the client and a tcp connection", () => { + expect(() => { + new CopilotClient({ + connection: RuntimeConnection.forTcp({ env: { FOO: "conn" } }), + env: { FOO: "client" }, + logLevel: "error", + }); + }).toThrow( + /Set environment variables via either the client-level env option or the connection/ + ); + }); + + it("should use the connection-level env for child-process transports", () => { + const client = new CopilotClient({ + connection: RuntimeConnection.forStdio({ env: { FOO: "from-conn" } }), + logLevel: "error", + }); + expect((client as any).resolvedEnv).toEqual({ FOO: "from-conn" }); + }); + + it("should allow env on the client alone with a child-process transport", () => { + const client = new CopilotClient({ + connection: RuntimeConnection.forStdio(), + env: { FOO: "from-client" }, + logLevel: "error", + }); + expect((client as any).resolvedEnv).toEqual({ FOO: "from-client" }); + }); }); describe("overridesBuiltInTool in tool definitions", () => { it("sends overridesBuiltInTool in tool definition on session.create", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -1587,7 +2173,7 @@ describe("CopilotClient", () => { it("sends overridesBuiltInTool in tool definition on session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); // Mock sendRequest to capture the call without hitting the runtime @@ -1621,7 +2207,7 @@ describe("CopilotClient", () => { it("sends defer in tool definition on session.create", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -1645,7 +2231,7 @@ describe("CopilotClient", () => { it("sends defer in tool definition on session.resume", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1678,7 +2264,7 @@ describe("CopilotClient", () => { it("forwards agent in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -1695,12 +2281,13 @@ describe("CopilotClient", () => { const payload = spy.mock.calls.find((c) => c[0] === "session.create")![1] as any; expect(payload.agent).toBe("test-agent"); expect(payload.customAgents).toEqual([expect.objectContaining({ name: "test-agent" })]); + expect(payload.customAgents[0].reasoningEffort).toBeUndefined(); }); - it("forwards custom agent model in session.create request", async () => { + it("forwards custom agent model and reasoning effort in session.create request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -1710,20 +2297,25 @@ describe("CopilotClient", () => { name: "model-agent", prompt: "You are a model agent.", model: "claude-haiku-4.5", + reasoningEffort: "high", }, ], }); const payload = spy.mock.calls.find((c) => c[0] === "session.create")![1] as any; expect(payload.customAgents).toEqual([ - expect.objectContaining({ name: "model-agent", model: "claude-haiku-4.5" }), + expect.objectContaining({ + name: "model-agent", + model: "claude-haiku-4.5", + reasoningEffort: "high", + }), ]); }); it("forwards agent in session.resume request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1781,7 +2373,7 @@ describe("CopilotClient", () => { const handler = vi.fn().mockReturnValue(customModels); const client = new CopilotClient({ onListModels: handler }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const models = await client.listModels(); expect(handler).toHaveBeenCalledTimes(1); @@ -1804,7 +2396,7 @@ describe("CopilotClient", () => { const handler = vi.fn().mockReturnValue(customModels); const client = new CopilotClient({ onListModels: handler }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); await client.listModels(); await client.listModels(); @@ -1826,7 +2418,7 @@ describe("CopilotClient", () => { const handler = vi.fn().mockResolvedValue(customModels); const client = new CopilotClient({ onListModels: handler }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const models = await client.listModels(); expect(models).toEqual(customModels); @@ -1854,22 +2446,29 @@ describe("CopilotClient", () => { }); describe("unexpected disconnection", () => { - it("transitions to disconnected when child process is killed", async () => { - const client = new CopilotClient(); - await client.start(); - onTestFinished(() => client.forceStop()); - - expect((client as any).state).toBe("connected"); - - // Kill the child process to simulate unexpected termination - const proc = (client as any).cliProcess as import("node:child_process").ChildProcess; - proc.kill(); - - // Wait for the connection.onClose handler to fire - await vi.waitFor(() => { - expect((client as any).state).toBe("disconnected"); - }); - }); + // No child process exists over the in-process (FFI) transport, so this + // child-process-kill scenario does not apply there. Covered by the default + // (stdio) cell. + it.skipIf((process.env.COPILOT_SDK_DEFAULT_CONNECTION ?? "").toLowerCase() === "inprocess")( + "transitions to disconnected when child process is killed", + async () => { + const client = new CopilotClient(); + await client.start(); + onTestFinished(() => stopClient(client)); + + expect((client as any).state).toBe("connected"); + + // Kill the child process to simulate unexpected termination + const proc = (client as any) + .cliProcess as import("node:child_process").ChildProcess; + proc.kill(); + + // Wait for the connection.onClose handler to fire + await vi.waitFor(() => { + expect((client as any).state).toBe("disconnected"); + }); + } + ); }); describe("onGetTraceContext", () => { @@ -1881,7 +2480,7 @@ describe("CopilotClient", () => { const provider = vi.fn().mockReturnValue(traceContext); const client = new CopilotClient({ onGetTraceContext: provider }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ onPermissionRequest: approveAll }); @@ -1903,7 +2502,7 @@ describe("CopilotClient", () => { const provider = vi.fn().mockReturnValue(traceContext); const client = new CopilotClient({ onGetTraceContext: provider }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1929,7 +2528,7 @@ describe("CopilotClient", () => { const provider = vi.fn().mockReturnValue(traceContext); const client = new CopilotClient({ onGetTraceContext: provider }); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1951,7 +2550,7 @@ describe("CopilotClient", () => { it("forwards requestHeaders in session.send request", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -1978,7 +2577,7 @@ describe("CopilotClient", () => { it("does not include trace context when no callback is provided", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ onPermissionRequest: approveAll }); @@ -1993,7 +2592,7 @@ describe("CopilotClient", () => { it("forwards commands in session.create RPC", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const spy = vi.spyOn((client as any).connection!, "sendRequest"); await client.createSession({ @@ -2014,7 +2613,7 @@ describe("CopilotClient", () => { it("forwards commands in session.resume RPC", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); const spy = vi @@ -2036,7 +2635,7 @@ describe("CopilotClient", () => { it("routes command.execute event to the correct handler", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const handler = vi.fn(); const session = await client.createSession({ @@ -2090,7 +2689,7 @@ describe("CopilotClient", () => { it("sends error when command handler throws", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll, @@ -2138,7 +2737,7 @@ describe("CopilotClient", () => { it("sends error for unknown command", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll, @@ -2184,7 +2783,7 @@ describe("CopilotClient", () => { it("reads capabilities from session.create response", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); // Intercept session.create to inject capabilities const origSendRequest = (client as any).connection!.sendRequest.bind( @@ -2210,7 +2809,7 @@ describe("CopilotClient", () => { it("defaults capabilities when not injected", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); // CLI returns actual capabilities (elicitation false in headless mode) @@ -2220,7 +2819,7 @@ describe("CopilotClient", () => { it("elicitation throws when capability is missing", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll }); @@ -2239,7 +2838,7 @@ describe("CopilotClient", () => { it("sends requestElicitation flag when onElicitationRequest is provided", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const rpcSpy = vi.spyOn((client as any).connection!, "sendRequest"); @@ -2265,7 +2864,7 @@ describe("CopilotClient", () => { it("does not send requestElicitation when no handler provided", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const rpcSpy = vi.spyOn((client as any).connection!, "sendRequest"); @@ -2287,7 +2886,7 @@ describe("CopilotClient", () => { it("sends mode callback request flags based on handler presence", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const rpcSpy = vi.spyOn((client as any).connection!, "sendRequest"); @@ -2322,7 +2921,7 @@ describe("CopilotClient", () => { it("dispatches mode callback requests to registered handlers", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll, @@ -2370,7 +2969,7 @@ describe("CopilotClient", () => { it("sends cancel when elicitation handler throws", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const session = await client.createSession({ onPermissionRequest: approveAll, @@ -2430,7 +3029,7 @@ describe("CopilotClient", () => { it("dispatches postToolUseFailure to onPostToolUseFailure handler", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const received: { input: any; invocation: any }[] = []; const session = await client.createSession({ @@ -2471,7 +3070,7 @@ describe("CopilotClient", () => { it("does not fall back to onPostToolUse for postToolUseFailure events", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const postUseCalls: string[] = []; const session = await client.createSession({ @@ -2500,7 +3099,7 @@ describe("CopilotClient", () => { it("dispatches postToolUse and postToolUseFailure to their respective handlers", async () => { const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const postCalls: string[] = []; const failureCalls: string[] = []; @@ -2540,7 +3139,7 @@ describe("CopilotClient", () => { it("routes hooks.invoke JSON-RPC requests to the SessionHooks handler", async () => { // Validates the full JSON-RPC entry point used by the CLI: - // CopilotClient.handleHooksInvoke({sessionId, hookType, input}) + // clientGlobalHandlers.hooks.invoke({sessionId, hookType, input}) // → CopilotSession._handleHooksInvoke(hookType, input) // → SessionHooks.onPostToolUseFailure(normalizedInput, {sessionId}) // @@ -2550,7 +3149,7 @@ describe("CopilotClient", () => { // The SDK maps that to public `{..., timestamp: Date, workingDirectory}`. const client = new CopilotClient(); await client.start(); - onTestFinished(() => client.forceStop()); + onTestFinished(() => stopClient(client)); const received: { input: any; invocation: any }[] = []; const session = await client.createSession({ @@ -2571,7 +3170,7 @@ describe("CopilotClient", () => { cwd: "/tmp", }; - const response = await (client as any).handleHooksInvoke({ + const response = await (client as any).clientGlobalHandlers.hooks.invoke({ sessionId: session.sessionId, hookType: "postToolUseFailure", input: failureInput, diff --git a/nodejs/test/e2e/client.e2e.test.ts b/nodejs/test/e2e/client.e2e.test.ts index 33b7a0636b..89489f78e6 100644 --- a/nodejs/test/e2e/client.e2e.test.ts +++ b/nodejs/test/e2e/client.e2e.test.ts @@ -1,11 +1,12 @@ import { ChildProcess } from "child_process"; import { describe, expect, it, onTestFinished } from "vitest"; -import { CopilotClient, approveAll, RuntimeConnection } from "../../src/index.js"; +import { approveAll, CopilotClient, RuntimeConnection } from "../../src/index.js"; +import { isInProcessTransport } from "./harness/sdkTestContext.js"; -function onTestFinishedForceStop(client: CopilotClient) { +function onTestFinishedStop(client: CopilotClient) { onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors - process may already be stopped } @@ -18,7 +19,7 @@ describe("Client", () => { { transport: "tcp", connection: () => RuntimeConnection.forTcp() }, ])("allows createSession without onPermissionRequest ($transport)", async ({ connection }) => { const client = new CopilotClient({ connection: connection() }); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await using session = await client.createSession({}); expect(session.sessionId).toMatch(/^[a-f0-9-]+$/); @@ -30,7 +31,7 @@ describe("Client", () => { const client = new CopilotClient({ connection: RuntimeConnection.forTcp({ connectionToken }), }); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await using originalSession = await client.createSession({}); @@ -42,7 +43,7 @@ describe("Client", () => { const resumeClient = new CopilotClient({ connection: RuntimeConnection.forUri(`localhost:${port}`, { connectionToken }), }); - onTestFinishedForceStop(resumeClient); + onTestFinishedStop(resumeClient); await using resumedSession = await resumeClient.resumeSession( originalSession.sessionId, @@ -53,7 +54,7 @@ describe("Client", () => { it("should start and connect to server using stdio", async () => { const client = new CopilotClient(); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); @@ -66,7 +67,7 @@ describe("Client", () => { it("should start and connect to server using tcp", async () => { const client = new CopilotClient({ connection: RuntimeConnection.forTcp() }); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); @@ -106,9 +107,14 @@ describe("Client", () => { 60_000 ); - it("should forceStop without cleanup", async () => { + // Skipping on in-proc: + // - It breaks the macOS E2E run (failure: EPIPE) + // - It's not clear that anyone should use forceStop in the in-proc case - there's no child process + // to terminate, so we can't be sure to leave a clean state + // - If you want to get to a clean state within your process, that's what "stop" (not "forceStop") is for + it.skipIf(isInProcessTransport)("should forceStop without cleanup", async () => { const client = new CopilotClient({}); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.createSession({ onPermissionRequest: approveAll }); await client.forceStop(); @@ -116,7 +122,7 @@ describe("Client", () => { it("should get status with version and protocol info", async () => { const client = new CopilotClient(); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); @@ -132,7 +138,7 @@ describe("Client", () => { it("should get auth status", async () => { const client = new CopilotClient(); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); @@ -148,7 +154,7 @@ describe("Client", () => { it("should list models when authenticated", async () => { const client = new CopilotClient(); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); @@ -177,7 +183,7 @@ describe("Client", () => { const client = new CopilotClient({ connection: RuntimeConnection.forStdio({ args: ["--nonexistent-flag-for-testing"] }), }); - onTestFinishedForceStop(client); + onTestFinishedStop(client); let initialError: Error | undefined; try { diff --git a/nodejs/test/e2e/client_api.e2e.test.ts b/nodejs/test/e2e/client_api.e2e.test.ts index 4adaad6ec3..46c23cee69 100644 --- a/nodejs/test/e2e/client_api.e2e.test.ts +++ b/nodejs/test/e2e/client_api.e2e.test.ts @@ -44,6 +44,7 @@ describe("Client session management", async () => { await waitFor(async () => (await client.listSessions()).some((s) => s.sessionId === sessionId) ); + await session.abort(); await session.disconnect(); await client.deleteSession(sessionId); diff --git a/nodejs/test/e2e/client_options.e2e.test.ts b/nodejs/test/e2e/client_options.e2e.test.ts index 2cfc69456f..e207f275ab 100644 --- a/nodejs/test/e2e/client_options.e2e.test.ts +++ b/nodejs/test/e2e/client_options.e2e.test.ts @@ -6,8 +6,8 @@ import * as fs from "fs"; import * as net from "net"; import * as path from "path"; import { describe, expect, it, onTestFinished } from "vitest"; -import { approveAll, CopilotClient, RuntimeConnection } from "../../src/index.js"; -import { createSdkTestContext } from "./harness/sdkTestContext.js"; +import { approveAll, CopilotClient, createCanvas, RuntimeConnection } from "../../src/index.js"; +import { createSdkTestContext, DEFAULT_GITHUB_TOKEN } from "./harness/sdkTestContext.js"; const FAKE_STDIO_CLI_SCRIPT = `const fs = require("fs"); @@ -99,6 +99,17 @@ function handleMessage(message) { return; } + if (message.method === "session.resume") { + const sessionId = message.params?.sessionId ?? message.params?.[0]?.sessionId ?? "fake-session"; + writeResponse(message.id, { + sessionId, + workspacePath: null, + capabilities: null, + openCanvases: message.params?.openCanvases ?? [] + }); + return; + } + writeResponse(message.id, {}); } @@ -138,6 +149,27 @@ function assertArgumentValue( expect(args[index + 1]).toBe(expectedValue); } +function getCapturedRequest(capturePath: string, method: string): Record { + const raw = fs.readFileSync(capturePath, "utf8"); + const capture = JSON.parse(raw) as { + requests: { method: string; params: Record }[]; + }; + const request = capture.requests.find((r) => r.method === method); + expect(request, `Expected ${method} request in capture`).toBeDefined(); + return request!.params; +} + +function getObject(value: unknown): Record { + expect(value).toBeTypeOf("object"); + expect(value).not.toBeNull(); + return value as Record; +} + +function getArray(value: unknown): unknown[] { + expect(Array.isArray(value)).toBe(true); + return value as unknown[]; +} + describe("Client options", async () => { const { copilotClient: defaultClient, env, workDir } = await createSdkTestContext(); @@ -146,10 +178,11 @@ describe("Client options", async () => { workingDirectory: workDir, env, connection: RuntimeConnection.forStdio({ path: process.env.COPILOT_CLI_PATH }), + gitHubToken: DEFAULT_GITHUB_TOKEN, }); onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors } @@ -173,7 +206,7 @@ describe("Client options", async () => { }); onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors } @@ -200,11 +233,11 @@ describe("Client options", async () => { workingDirectory: clientCwd, env, connection: RuntimeConnection.forStdio({ path: process.env.COPILOT_CLI_PATH }), - gitHubToken: process.env.CI ? "fake-token-for-e2e-tests" : undefined, + gitHubToken: DEFAULT_GITHUB_TOKEN, }); onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors } @@ -258,7 +291,7 @@ describe("Client options", async () => { }); onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors } @@ -318,6 +351,315 @@ describe("Client options", async () => { await session.disconnect(); }); + it("should forward advanced session options in create wire request", async () => { + const cliPath = path.join( + workDir, + `fake-cli-advanced-create-${Date.now()}-${Math.random().toString(36).slice(2)}.js` + ); + const capturePath = path.join( + workDir, + `fake-cli-advanced-create-capture-${Date.now()}-${Math.random().toString(36).slice(2)}.json` + ); + const outputDirectory = path.join(workDir, "large-output-create"); + fs.writeFileSync(cliPath, FAKE_STDIO_CLI_SCRIPT); + + const client = new CopilotClient({ + workingDirectory: workDir, + env, + connection: RuntimeConnection.forStdio({ + path: cliPath, + args: ["--capture-file", capturePath], + }), + useLoggedInUser: false, + }); + onTestFinished(async () => { + try { + await client.stop(); + } catch { + // Ignore cleanup errors + } + }); + + await client.start(); + + const canvas = createCanvas({ + id: "advanced-create-canvas", + displayName: "Advanced Create Canvas", + description: "Covers create-time canvas options.", + open: () => ({ url: "https://example.test/advanced-create-canvas" }), + }); + const session = await client.createSession({ + clientName: "advanced-create-client", + model: "claude-sonnet-4.5", + reasoningEffort: "medium", + reasoningSummary: "detailed", + contextTier: "long_context", + enableCitations: true, + capi: { enableWebSocketResponses: false }, + mcpOAuthTokenStorage: "persistent", + customAgents: [ + { + name: "agent-one", + displayName: "Agent One", + description: "Handles agent-one tasks.", + prompt: "Be agent one.", + tools: ["view"], + infer: true, + skills: ["create-skill"], + model: "claude-haiku-4.5", + }, + ], + defaultAgent: { excludedTools: ["edit"] }, + agent: "agent-one", + skillDirectories: ["skills-create"], + disabledSkills: ["disabled-create-skill"], + pluginDirectories: ["plugins-create"], + infiniteSessions: { + enabled: false, + backgroundCompactionThreshold: 0.5, + bufferExhaustionThreshold: 0.9, + }, + largeOutput: { + enabled: true, + maxSizeBytes: 4096, + outputDirectory, + }, + memory: { enabled: true }, + gitHubToken: "session-create-token", + remoteSession: "export", + cloud: { + repository: { + owner: "github", + name: "copilot-sdk", + branch: "main", + }, + }, + enableMcpApps: true, + requestCanvasRenderer: true, + requestExtensions: true, + extensionSdkPath: "custom-extension-sdk", + extensionInfo: { source: "typescript-sdk-tests", name: "advanced-create-extension" }, + canvases: [canvas], + providers: [ + { + name: "create-provider", + type: "openai", + wireApi: "responses", + baseUrl: "https://create-provider.example.test/v1", + apiKey: "create-provider-key", + headers: { "X-Create-Provider": "yes" }, + }, + ], + models: [ + { + provider: "create-provider", + id: "create-model", + name: "Create Model", + modelId: "claude-sonnet-4.5", + wireModel: "create-wire-model", + maxContextWindowTokens: 12_000, + maxPromptTokens: 10_000, + maxOutputTokens: 2_000, + }, + ], + onPermissionRequest: approveAll, + }); + + const createRequest = getCapturedRequest(capturePath, "session.create"); + expect(createRequest.clientName).toBe("advanced-create-client"); + expect(createRequest.model).toBe("claude-sonnet-4.5"); + expect(createRequest.reasoningEffort).toBe("medium"); + expect(createRequest.reasoningSummary).toBe("detailed"); + expect(createRequest.contextTier).toBe("long_context"); + expect(createRequest.enableCitations).toBe(true); + expect(getObject(createRequest.capi).enableWebSocketResponses).toBe(false); + expect(createRequest.mcpOAuthTokenStorage).toBe("persistent"); + expect(createRequest.agent).toBe("agent-one"); + expect(getArray(getObject(createRequest.defaultAgent).excludedTools)[0]).toBe("edit"); + expect(getObject(getArray(createRequest.customAgents)[0]).name).toBe("agent-one"); + expect(getArray(createRequest.pluginDirectories)[0]).toBe("plugins-create"); + expect(getArray(createRequest.disabledSkills)[0]).toBe("disabled-create-skill"); + expect(getObject(createRequest.infiniteSessions).enabled).toBe(false); + expect(getObject(createRequest.largeOutput).enabled).toBe(true); + expect(getObject(createRequest.largeOutput).maxSizeBytes).toBe(4096); + expect(getObject(createRequest.largeOutput).outputDir).toBe(outputDirectory); + expect(getObject(createRequest.memory).enabled).toBe(true); + expect(createRequest.gitHubToken).toBe("session-create-token"); + expect(createRequest.remoteSession).toBe("export"); + expect(getObject(getObject(createRequest.cloud).repository).owner).toBe("github"); + expect(createRequest.requestMcpApps).toBe(true); + expect(createRequest.requestCanvasRenderer).toBe(true); + expect(createRequest.requestExtensions).toBe(true); + expect(createRequest.extensionSdkPath).toBe("custom-extension-sdk"); + expect(getObject(createRequest.extensionInfo).name).toBe("advanced-create-extension"); + expect(getObject(getArray(createRequest.canvases)[0]).id).toBe("advanced-create-canvas"); + expect(getObject(getArray(createRequest.providers)[0]).name).toBe("create-provider"); + expect(getObject(getArray(createRequest.providers)[0]).wireApi).toBe("responses"); + expect(getObject(getArray(createRequest.models)[0]).id).toBe("create-model"); + expect(getObject(getArray(createRequest.models)[0]).maxContextWindowTokens).toBe(12_000); + + await session.disconnect(); + }); + + it("should forward singular provider options in create wire request", async () => { + const cliPath = path.join( + workDir, + `fake-cli-provider-create-${Date.now()}-${Math.random().toString(36).slice(2)}.js` + ); + const capturePath = path.join( + workDir, + `fake-cli-provider-create-capture-${Date.now()}-${Math.random().toString(36).slice(2)}.json` + ); + fs.writeFileSync(cliPath, FAKE_STDIO_CLI_SCRIPT); + + const client = new CopilotClient({ + workingDirectory: workDir, + env, + connection: RuntimeConnection.forStdio({ + path: cliPath, + args: ["--capture-file", capturePath], + }), + useLoggedInUser: false, + }); + onTestFinished(async () => { + try { + await client.stop(); + } catch { + // Ignore cleanup errors + } + }); + + await client.start(); + + const session = await client.createSession({ + model: "claude-sonnet-4.5", + provider: { + type: "azure", + wireApi: "responses", + transport: "http", + baseUrl: "https://azure-provider.example.test/openai", + apiKey: "provider-api-key", + bearerToken: "provider-bearer-token", + azure: { apiVersion: "2024-02-15-preview" }, + headers: { "X-Provider-Wire": "yes" }, + modelId: "claude-sonnet-4.5", + wireModel: "azure-deployment", + maxPromptTokens: 8192, + maxOutputTokens: 1024, + }, + onPermissionRequest: approveAll, + }); + + const provider = getObject(getCapturedRequest(capturePath, "session.create").provider); + expect(provider.type).toBe("azure"); + expect(provider.wireApi).toBe("responses"); + expect(provider.transport).toBe("http"); + expect(provider.baseUrl).toBe("https://azure-provider.example.test/openai"); + expect(provider.apiKey).toBe("provider-api-key"); + expect(provider.bearerToken).toBe("provider-bearer-token"); + expect(getObject(provider.azure).apiVersion).toBe("2024-02-15-preview"); + expect(getObject(provider.headers)["X-Provider-Wire"]).toBe("yes"); + expect(provider.modelId).toBe("claude-sonnet-4.5"); + expect(provider.wireModel).toBe("azure-deployment"); + expect(provider.maxPromptTokens).toBe(8192); + expect(provider.maxOutputTokens).toBe(1024); + + await session.disconnect(); + }); + + it("should forward advanced session options in resume wire request", async () => { + const cliPath = path.join( + workDir, + `fake-cli-advanced-resume-${Date.now()}-${Math.random().toString(36).slice(2)}.js` + ); + const capturePath = path.join( + workDir, + `fake-cli-advanced-resume-capture-${Date.now()}-${Math.random().toString(36).slice(2)}.json` + ); + const outputDirectory = path.join(workDir, "large-output-resume"); + fs.writeFileSync(cliPath, FAKE_STDIO_CLI_SCRIPT); + + const client = new CopilotClient({ + workingDirectory: workDir, + env, + connection: RuntimeConnection.forStdio({ + path: cliPath, + args: ["--capture-file", capturePath], + }), + useLoggedInUser: false, + }); + onTestFinished(async () => { + try { + await client.stop(); + } catch { + // Ignore cleanup errors + } + }); + + await client.start(); + + const session = await client.resumeSession("advanced-resume-session", { + clientName: "advanced-resume-client", + model: "claude-haiku-4.5", + reasoningEffort: "low", + reasoningSummary: "none", + contextTier: "default", + suppressResumeEvent: true, + continuePendingWork: true, + mcpOAuthTokenStorage: "persistent", + pluginDirectories: ["plugins-resume"], + largeOutput: { + enabled: false, + maxSizeBytes: 2048, + outputDirectory, + }, + memory: { enabled: false }, + remoteSession: "on", + openCanvases: [ + { + canvasId: "resume-canvas", + extensionId: "typescript-sdk-tests/resume-extension", + extensionName: "Resume Extension", + instanceId: "resume-canvas-1", + input: { start: 41 }, + status: "ready", + title: "Resume Canvas", + url: "https://example.com/resume-canvas", + }, + ], + onPermissionRequest: approveAll, + }); + + const resumeRequest = getCapturedRequest(capturePath, "session.resume"); + expect(resumeRequest.sessionId).toBe("advanced-resume-session"); + expect(resumeRequest.clientName).toBe("advanced-resume-client"); + expect(resumeRequest.model).toBe("claude-haiku-4.5"); + expect(resumeRequest.reasoningEffort).toBe("low"); + expect(resumeRequest.reasoningSummary).toBe("none"); + expect(resumeRequest.contextTier).toBe("default"); + expect(resumeRequest.disableResume).toBe(true); + expect(resumeRequest.continuePendingWork).toBe(true); + expect(resumeRequest.mcpOAuthTokenStorage).toBe("persistent"); + expect(getArray(resumeRequest.pluginDirectories)[0]).toBe("plugins-resume"); + expect(getObject(resumeRequest.largeOutput).enabled).toBe(false); + expect(getObject(resumeRequest.largeOutput).maxSizeBytes).toBe(2048); + expect(getObject(resumeRequest.largeOutput).outputDir).toBe(outputDirectory); + expect(getObject(resumeRequest.memory).enabled).toBe(false); + expect(resumeRequest.remoteSession).toBe("on"); + + const openCanvas = getObject(getArray(resumeRequest.openCanvases)[0]); + expect(openCanvas.canvasId).toBe("resume-canvas"); + expect(openCanvas.extensionId).toBe("typescript-sdk-tests/resume-extension"); + expect(openCanvas.extensionName).toBe("Resume Extension"); + expect(openCanvas.instanceId).toBe("resume-canvas-1"); + expect(getObject(openCanvas.input).start).toBe(41); + expect(openCanvas.status).toBe("ready"); + expect(openCanvas.title).toBe("Resume Canvas"); + expect(openCanvas.url).toBe("https://example.com/resume-canvas"); + + await session.disconnect(); + }); + it("should throw when gitHubToken used with forUri", () => { expect(() => { new CopilotClient({ diff --git a/nodejs/test/e2e/copilot_request_cancel_error.e2e.test.ts b/nodejs/test/e2e/copilot_request_cancel_error.e2e.test.ts index 5a9cad5a59..69bacd4f6e 100644 --- a/nodejs/test/e2e/copilot_request_cancel_error.e2e.test.ts +++ b/nodejs/test/e2e/copilot_request_cancel_error.e2e.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest"; import { approveAll, CopilotRequestHandler, type CopilotRequestContext } from "../../src/index.js"; -import { createSdkTestContext } from "./harness/sdkTestContext.js"; +import { createSdkTestContext, isInProcessTransport } from "./harness/sdkTestContext.js"; /** * Cancellation and error coverage for {@link CopilotRequestHandler}. These two @@ -162,23 +162,33 @@ describe("CopilotRequestHandler observes runtime cancellation", async () => { copilotClientOptions: { requestHandler: handler }, }); - it("fires ctx.signal when the consumer aborts an in-flight inference request", async () => { - await client.start(); - const session = await client.createSession({ onPermissionRequest: approveAll }); - try { - await session.send("Say OK."); - await waitFor(() => handler.inferenceEntered, 60_000); - await session.abort(); - await waitFor(() => handler.sawAbort, 30_000); - } finally { - await session.disconnect(); - } + // The runtime enforces a single, process-wide LLM inference provider: a second + // client.start() with a requestHandler rejects llmInference.setProvider with + // "Another client is already the LLM inference provider." The sibling error test + // above already registers a provider and holds it for this file's lifetime, and + // inproc runs share one runtime host, so this scenario can only run on the default + // (stdio) cell, where each client owns its own runtime process. + it.skipIf(isInProcessTransport)( + "fires ctx.signal when the consumer aborts an in-flight inference request", + async () => { + await client.start(); + const session = await client.createSession({ onPermissionRequest: approveAll }); + try { + await session.send("Say OK."); + await waitFor(() => handler.inferenceEntered, 60_000); + await session.abort(); + await waitFor(() => handler.sawAbort, 30_000); + } finally { + await session.disconnect(); + } - expect(handler.inferenceEntered, "expected the inference callback to be entered").toBe( - true - ); - expect(handler.sawAbort, "expected the callback to observe runtime cancellation").toBe( - true - ); - }, 90_000); + expect(handler.inferenceEntered, "expected the inference callback to be entered").toBe( + true + ); + expect(handler.sawAbort, "expected the callback to observe runtime cancellation").toBe( + true + ); + }, + 90_000 + ); }); diff --git a/nodejs/test/e2e/copilot_request_session_id.e2e.test.ts b/nodejs/test/e2e/copilot_request_session_id.e2e.test.ts index 3f01475aae..bd070c20ca 100644 --- a/nodejs/test/e2e/copilot_request_session_id.e2e.test.ts +++ b/nodejs/test/e2e/copilot_request_session_id.e2e.test.ts @@ -11,6 +11,9 @@ const SYNTHETIC_TEXT = "OK from the synthetic stream."; interface InterceptedRequest { url: string; sessionId?: string; + agentId?: string; + parentAgentId?: string; + interactionType?: string; } function isInferenceUrl(url: string): boolean { @@ -43,7 +46,13 @@ class RecordingRequestHandler extends CopilotRequestHandler { ctx: CopilotRequestContext ): Promise { const url = request.url; - this.records.push({ url, sessionId: ctx.sessionId }); + this.records.push({ + url, + sessionId: ctx.sessionId, + agentId: ctx.agentId, + parentAgentId: ctx.parentAgentId, + interactionType: ctx.interactionType, + }); const bodyText = request.body ? await request.text() : ""; return isInferenceUrl(url) ? buildInferenceResponse(url, bodyText) @@ -105,6 +114,11 @@ function buildNonInferenceResponse(url: string): Response { return json("{}"); } +function expectAgentMetadata(r: InterceptedRequest): void { + expect(r.agentId).toBeTruthy(); + expect(r.interactionType).toBeTruthy(); +} + const RESPONSES_STREAM_EVENTS: string[] = [ `event: response.created\ndata: ${JSON.stringify({ type: "response.created", @@ -273,6 +287,7 @@ describe("CopilotRequestHandler threads the runtime session id (CAPI + BYOK)", a expect(r.sessionId, "CAPI inference request must carry the runtime session id").toBe( session.sessionId ); + expectAgentMetadata(r); } // Validate the final assistant response arrived (guards against truncated captures) @@ -313,6 +328,7 @@ describe("CopilotRequestHandler threads the runtime session id (CAPI + BYOK)", a expect(r.sessionId, "BYOK inference request must carry the runtime session id").toBe( byokSessionId ); + expectAgentMetadata(r); } // Session ids are per-session, so the two turns must differ — proves diff --git a/nodejs/test/e2e/github_telemetry.e2e.test.ts b/nodejs/test/e2e/github_telemetry.e2e.test.ts new file mode 100644 index 0000000000..e33178f9d0 --- /dev/null +++ b/nodejs/test/e2e/github_telemetry.e2e.test.ts @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it } from "vitest"; +import { approveAll, GitHubTelemetryNotification } from "../../src/index.js"; +import { createSdkTestContext } from "./harness/sdkTestContext.js"; +import { waitForCondition } from "./harness/sdkTestHelper.js"; + +// Experimental: exercises the end-to-end GitHub (hydro) telemetry forwarding +// path. The runtime forwards per-session telemetry to opted-in connections via +// the `gitHubTelemetry.event` JSON-RPC *notification*; the SDK opts in +// automatically whenever an `onGitHubTelemetry` handler is registered. Creating +// a session emits an early `session.start` hydro event, so no model round-trip +// (and therefore no recorded CAPI exchange) is needed to observe forwarding. +describe("GitHub telemetry forwarding", async () => { + const received: GitHubTelemetryNotification[] = []; + + const { copilotClient: client } = await createSdkTestContext({ + copilotClientOptions: { + onGitHubTelemetry: (notification) => { + received.push(notification); + }, + }, + }); + + it( + "forwards gitHubTelemetry.event notifications from a live session", + { timeout: 60_000 }, + async () => { + received.length = 0; + + const session = await client.createSession({ + onPermissionRequest: approveAll, + }); + + // The CLI forwards telemetry over the JSON-RPC connection + // asynchronously, so wait until at least one event arrives or we + // time out. + await waitForCondition(() => received.length > 0, { + timeoutMs: 30_000, + timeoutMessage: "Timed out waiting for a gitHubTelemetry.event notification.", + }); + + expect(received.length).toBeGreaterThan(0); + + const notification = received[0]; + expect(typeof notification.sessionId).toBe("string"); + expect(notification.sessionId.length).toBeGreaterThan(0); + expect(typeof notification.restricted).toBe("boolean"); + expect(notification.event).toBeDefined(); + expect(typeof notification.event.kind).toBe("string"); + + await session.disconnect(); + } + ); +}); diff --git a/nodejs/test/e2e/harness/sdkTestContext.ts b/nodejs/test/e2e/harness/sdkTestContext.ts index cd6494cad3..bf62db4826 100644 --- a/nodejs/test/e2e/harness/sdkTestContext.ts +++ b/nodejs/test/e2e/harness/sdkTestContext.ts @@ -16,10 +16,40 @@ import { formatError, retry } from "./sdkTestHelper"; export const isCI = process.env.GITHUB_ACTIONS === "true"; export const DEFAULT_GITHUB_TOKEN = "fake-token-for-e2e-tests"; +/** + * True when the E2E suite is running over the in-process (FFI) transport + * (COPILOT_SDK_DEFAULT_CONNECTION=inprocess). Use with `it.skipIf` / `describe.skipIf` + * to skip tests for features that are not supported over the in-process transport (the + * runtime loads into the shared host process), so the in-process CI cell stays green. + * Such features are covered by the default (stdio) cell. + */ +export const isInProcessTransport = + (process.env.COPILOT_SDK_DEFAULT_CONNECTION ?? "").toLowerCase() === "inprocess"; + +// The in-process (FFI) transport resolves auth host-side, in this test process, and +// ranks HMAC above the GitHub token — so an ambient COPILOT_HMAC_KEY (CI sets one as a +// job-level credential) would be picked over the SDK/Bearer token the replay snapshots +// expect, yielding 401s. Host-side auth can capture the key as early as client +// construction (before any per-test beforeEach runs), so neutralize it at module load — +// the analogue of .NET's InProcessEnvIsolation `[ModuleInitializer]`. Only applied for +// the in-process transport; stdio/tcp children resolve auth in their own process where +// the token already outranks HMAC. See https://github.com/github/copilot-sdk/issues/1934. +if ((process.env.COPILOT_SDK_DEFAULT_CONNECTION ?? "").toLowerCase() === "inprocess") { + delete process.env.COPILOT_HMAC_KEY; + delete process.env.CAPI_HMAC_KEY; +} + const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const SNAPSHOTS_DIR = resolve(__dirname, "../../../../test/snapshots"); +function getCliPathForTests(): string | undefined { + if (process.env.COPILOT_CLI_PATH) { + return process.env.COPILOT_CLI_PATH; + } + return undefined; +} + export async function createSdkTestContext({ logLevel, useStdio, @@ -39,6 +69,7 @@ export async function createSdkTestContext({ await openAiEndpoint.setCopilotUserByToken(DEFAULT_GITHUB_TOKEN, { login: "e2e-test-user", copilot_plan: "individual_pro", + is_mcp_enabled: true, endpoints: { api: proxyUrl, telemetry: "https://localhost:1/telemetry", @@ -61,8 +92,14 @@ export async function createSdkTestContext({ COPILOT_HOME: copilotHomeDir, COPILOT_SDK_AUTH_TOKEN: "", GH_CONFIG_DIR: homeDir, - GH_TOKEN: "", - GITHUB_TOKEN: "", + // Use the proxy-recognized token rather than blanking these. Tests that spin up + // their own client without passing `gitHubToken` (e.g. the stdio/tcp + // "works without onPermissionRequest" cases) rely on GH_TOKEN/GITHUB_TOKEN to + // authenticate against the replay proxy. Blanking them only worked on CI, where an + // ambient COPILOT_HMAC_KEY secret supplies the credential instead; locally there is + // no HMAC key, so the child CLI had nothing to authenticate with and got a 401. + GH_TOKEN: authTokenToUse, + GITHUB_TOKEN: authTokenToUse, // TODO: I'm not convinced the SDK should default to using whatever config you happen to have in your homedir. // The SDK config should be independent of the regular CLI app. Likewise it shouldn't mix sessions from the @@ -72,6 +109,7 @@ export async function createSdkTestContext({ }; const userConn = copilotClientOptions?.connection; + const cliPath = getCliPathForTests(); let connection: RuntimeConnection; if (userConn) { // Caller supplied a RuntimeConnection — merge in the harness-managed @@ -82,40 +120,121 @@ export async function createSdkTestContext({ const { kind: _k, ...tcp } = userConn; connection = RuntimeConnection.forTcp({ ...tcp, - path: tcp.path ?? process.env.COPILOT_CLI_PATH, + path: tcp.path ?? cliPath, }); } else if (userConn.kind === "stdio") { const { kind: _k, ...stdio } = userConn; connection = RuntimeConnection.forStdio({ ...stdio, - path: stdio.path ?? process.env.COPILOT_CLI_PATH, + path: stdio.path ?? cliPath, }); } else { connection = userConn; } + } else if (useStdio === false) { + connection = RuntimeConnection.forTcp({ path: cliPath }); + } else if ( + useStdio === undefined && + (process.env.COPILOT_SDK_DEFAULT_CONNECTION ?? "").toLowerCase() === "inprocess" + ) { + // The in-process FFI transport resolves the CLI entrypoint itself + // (COPILOT_CLI_PATH or the bundled platform package), so no path is passed. + connection = RuntimeConnection.forInProcess(); } else { - connection = - useStdio === false - ? RuntimeConnection.forTcp({ path: process.env.COPILOT_CLI_PATH }) - : RuntimeConnection.forStdio({ path: process.env.COPILOT_CLI_PATH }); + connection = RuntimeConnection.forStdio({ path: cliPath }); } - const { connection: _ignoredConnection, ...remainingClientOptions } = - copilotClientOptions ?? {}; - const copilotClient = new CopilotClient({ - workingDirectory: workDir, - env, - logLevel: logLevel || "error", - connection, - gitHubToken: authTokenToUse, - ...remainingClientOptions, - }); + const { + connection: _ignoredConnection, + env: userEnv, + ...remainingClientOptions + } = copilotClientOptions ?? {}; - const harness = { homeDir, workDir, openAiEndpoint, copilotClient, env }; + const mergedEnv = { ...env, ...userEnv }; + + // The in-process (FFI) transport loads the runtime into this test host process, + // and its worker inherits this process's ambient environment rather than a + // per-client env block (see https://github.com/github/copilot-sdk/issues/1934). + // So the per-test redirects, isolated home, and credentials must be mirrored onto + // the real process environment. Node's `process.env` writes reach native `getenv`, + // so host-side runtime reads (auth resolution, GitHub API redirect) observe them. + // Auth flows via GH_TOKEN/GITHUB_TOKEN here (the FFI argv omits the stdio + // `--auth-token-env COPILOT_SDK_AUTH_TOKEN` wiring), and HMAC is disabled so + // host-side auth resolution picks the SDK/Bearer token the replay snapshots expect. + const isInProcess = connection.kind === "inprocess"; + const inProcessEnv: Record = isInProcess + ? { + ...(mergedEnv as Record), + GH_TOKEN: authTokenToUse, + GITHUB_TOKEN: authTokenToUse, + COPILOT_HMAC_KEY: "", + CAPI_HMAC_KEY: "", + } + : {}; + + // Builds a CopilotClient wired for the active transport, so tests that need a + // secondary client (e.g. resuming a session from a fresh client) don't have to + // reimplement the in-process env/cwd handling. Callers may override the connection + // (e.g. pin stdio for telemetry, which the in-process transport cannot carry + // per-client); env is attached to child-process transports and mirrored onto the + // process for in-process (see beforeEach below), never passed per-client for the + // in-process transport where it would be rejected. + function createClient(overrides: Partial = {}): CopilotClient { + const { + connection: overrideConnection, + env: _ignoredEnv, + workingDirectory: overrideWorkingDirectory, + ...rest + } = overrides; + + let effectiveConnection = overrideConnection ?? connection; + // Fill in the bundled CLI path for child-process connections that omit it + // (e.g. a bare RuntimeConnection.forStdio() used to pin telemetry to stdio). + if (effectiveConnection.kind === "stdio" && effectiveConnection.path === undefined) { + effectiveConnection = RuntimeConnection.forStdio({ + ...effectiveConnection, + path: cliPath, + }); + } else if (effectiveConnection.kind === "tcp" && effectiveConnection.path === undefined) { + effectiveConnection = RuntimeConnection.forTcp({ + ...effectiveConnection, + path: cliPath, + }); + } + const effectiveInProcess = effectiveConnection.kind === "inprocess"; + + return new CopilotClient({ + // The in-process transport rejects a per-client workingDirectory (it would have to + // mutate the shared host process cwd). Instead the harness changes this process's + // cwd to workDir around the in-process worker's startup (see beforeEach below), so + // the worker still spawns with workDir as its cwd. Out-of-process clients get it + // as a normal per-client option. + workingDirectory: + overrideWorkingDirectory ?? (effectiveInProcess ? undefined : workDir), + // In-process hosting mirrors the environment onto the real process (per test, in + // beforeEach below), so the worker inherits it; passing a per-client env here + // would have no effect (and is rejected by the in-process transport). + env: effectiveInProcess ? undefined : mergedEnv, + logLevel: logLevel || "error", + connection: effectiveConnection, + gitHubToken: authTokenToUse, + ...rest, + }); + } + + const copilotClient = createClient(remainingClientOptions); + + const harness = { homeDir, workDir, openAiEndpoint, copilotClient, env, createClient }; // Track if any test fails to avoid writing corrupted snapshots let anyTestFailed = false; + // Holds the process.env entries the current test overwrote, so afterEach restores them. + let restoreProcessEnv: Array<[string, string | undefined]> = []; + + // Holds the process cwd before an in-process test changed it, so afterEach restores it. + let restoreCwd: string | undefined; + // Wire up to Vitest lifecycle beforeEach(async (testContext) => { // Must be inside beforeEach - vitest requires test context @@ -123,6 +242,25 @@ export async function createSdkTestContext({ anyTestFailed = true; }); + // Mirror this context's environment onto the real process for in-process + // hosting, right before the test runs (see the comment above the client). The + // client auto-starts on first use inside the test body, so the worker spawns + // under these values. + restoreProcessEnv = []; + for (const [key, value] of Object.entries(inProcessEnv)) { + restoreProcessEnv.push([key, process.env[key]]); + process.env[key] = value; + } + + // The in-process worker inherits this process's cwd at spawn (the client auto-starts + // on first use inside the test body). Point cwd at workDir here so the worker spawns + // with the same working directory the out-of-process transport passes explicitly; + // afterEach restores it. + if (isInProcess) { + restoreCwd = process.cwd(); + process.chdir(workDir); + } + await openAiEndpoint.updateConfig({ filePath: getTrafficCapturePath(testContext), workDir, @@ -134,6 +272,20 @@ export async function createSdkTestContext({ }); afterEach(async () => { + // Undo this test's process.env mirror so it can't leak into the next test/suite. + for (const [key, previous] of restoreProcessEnv.reverse()) { + if (previous === undefined) { + delete process.env[key]; + } else { + process.env[key] = previous; + } + } + restoreProcessEnv = []; + // Restore the cwd an in-process test changed for worker startup. + if (restoreCwd !== undefined) { + process.chdir(restoreCwd); + restoreCwd = undefined; + } // Empty directories but leave them in place for next test await rimraf([join(homeDir, "*"), join(workDir, "*")], { glob: true }); }); @@ -141,7 +293,15 @@ export async function createSdkTestContext({ afterAll(async () => { await copilotClient.stop(); await openAiEndpoint.stop(anyTestFailed); - await rmDir("remove e2e test copilotHomeDir", copilotHomeDir); + // On Windows, this Vitest worker can retain the in-process runtime's session.db + // lock until the worker exits. Retrying from its afterAll hook cannot succeed: + // the hook waits for the lock, while the lock cannot clear until the hook returns + // and lets the worker exit. + await rmDir( + "remove e2e test copilotHomeDir", + copilotHomeDir, + isInProcess && process.platform === "win32" ? 1 : 30 + ); await rmDir("remove e2e test homeDir", homeDir); await rmDir("remove e2e test workDir", workDir); }); @@ -168,14 +328,14 @@ function getTrafficCapturePath(testContext: TestContext): string { return join(SNAPSHOTS_DIR, testFileName, `${taskNameAsFilename}.yaml`); } -async function rmDir(message: string, path: string): Promise { +async function rmDir(message: string, path: string, maxTries = 30): Promise { // Use longer retries to tolerate Windows holding SQLite session-store.db // open briefly after the CLI subprocess exits. If the temp dir still can't // be removed (e.g. CLI background writer racing with cleanup), warn and // continue rather than failing the whole test run — the OS / CI runner // will reclaim the temp dir on shutdown. try { - await retry(message, () => rm(path, { recursive: true, force: true }), 30, 1000); + await retry(message, () => rm(path, { recursive: true, force: true }), maxTries, 1000); } catch (error) { console.warn( `WARN: ${message} failed; leaving temp dir for OS cleanup: ${formatError(error)}` diff --git a/nodejs/test/e2e/hooks.e2e.test.ts b/nodejs/test/e2e/hooks.e2e.test.ts index 895097adbc..4fce7d2acf 100644 --- a/nodejs/test/e2e/hooks.e2e.test.ts +++ b/nodejs/test/e2e/hooks.e2e.test.ts @@ -19,13 +19,14 @@ describe("Session hooks", async () => { it("should invoke preToolUse hook when model runs a tool", async () => { const preToolUseInputs: PreToolUseHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onPreToolUse: async (input, invocation) => { preToolUseInputs.push(input); - expect(invocation.sessionId).toBe(session.sessionId); + invocationSessionIds.push(invocation.sessionId); // Allow the tool to run return { permissionDecision: "allow" } as PreToolUseHookOutput; }, @@ -41,6 +42,9 @@ describe("Session hooks", async () => { // Should have received at least one preToolUse hook call expect(preToolUseInputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); // Should have received the tool name expect(preToolUseInputs.some((input) => input.toolName)).toBe(true); @@ -50,13 +54,14 @@ describe("Session hooks", async () => { it("should invoke postToolUse hook after model runs a tool", async () => { const postToolUseInputs: PostToolUseHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onPostToolUse: async (input, invocation) => { postToolUseInputs.push(input); - expect(invocation.sessionId).toBe(session.sessionId); + invocationSessionIds.push(invocation.sessionId); return null as PostToolUseHookOutput; }, }, @@ -71,6 +76,9 @@ describe("Session hooks", async () => { // Should have received at least one postToolUse hook call expect(postToolUseInputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); // Should have received the tool name and result expect(postToolUseInputs.some((input) => input.toolName)).toBe(true); diff --git a/nodejs/test/e2e/hooks_extended.e2e.test.ts b/nodejs/test/e2e/hooks_extended.e2e.test.ts index caa69399ed..82e1812f11 100644 --- a/nodejs/test/e2e/hooks_extended.e2e.test.ts +++ b/nodejs/test/e2e/hooks_extended.e2e.test.ts @@ -21,13 +21,14 @@ describe("Extended session hooks", async () => { it("should invoke onSessionStart hook on new session", async () => { const sessionStartInputs: SessionStartHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onSessionStart: async (input, invocation) => { sessionStartInputs.push(input); - expect(invocation.sessionId).toBe(session.sessionId); + invocationSessionIds.push(invocation.sessionId); }, }, }); @@ -37,6 +38,9 @@ describe("Extended session hooks", async () => { }); expect(sessionStartInputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); expect(sessionStartInputs[0].source).toBe("new"); expect(sessionStartInputs[0].timestamp).toBeInstanceOf(Date); expect(sessionStartInputs[0].workingDirectory).toBeDefined(); @@ -46,13 +50,14 @@ describe("Extended session hooks", async () => { it("should invoke onUserPromptSubmitted hook when sending a message", async () => { const userPromptInputs: UserPromptSubmittedHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onUserPromptSubmitted: async (input, invocation) => { userPromptInputs.push(input); - expect(invocation.sessionId).toBe(session.sessionId); + invocationSessionIds.push(invocation.sessionId); }, }, }); @@ -62,6 +67,9 @@ describe("Extended session hooks", async () => { }); expect(userPromptInputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); expect(userPromptInputs[0].prompt).toContain("Say hello"); expect(userPromptInputs[0].timestamp).toBeInstanceOf(Date); expect(userPromptInputs[0].workingDirectory).toBeDefined(); @@ -71,13 +79,14 @@ describe("Extended session hooks", async () => { it("should invoke onSessionEnd hook when session is disconnected", async () => { const sessionEndInputs: SessionEndHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onSessionEnd: async (input, invocation) => { sessionEndInputs.push(input); - expect(invocation.sessionId).toBe(session.sessionId); + invocationSessionIds.push(invocation.sessionId); }, }, }); @@ -92,17 +101,21 @@ describe("Extended session hooks", async () => { await new Promise((resolve) => setTimeout(resolve, 100)); expect(sessionEndInputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); }); it("should invoke onErrorOccurred hook when error occurs", async () => { const errorInputs: ErrorOccurredHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onErrorOccurred: async (input, invocation) => { errorInputs.push(input); - expect(invocation.sessionId).toBe(session.sessionId); + invocationSessionIds.push(invocation.sessionId); expect(input.timestamp).toBeInstanceOf(Date); expect(input.workingDirectory).toBeDefined(); expect(input.error).toBeDefined(); @@ -121,20 +134,23 @@ describe("Extended session hooks", async () => { // onErrorOccurred is dispatched by the runtime for actual errors (model failures, system errors). // In a normal session it may not fire. Verify the hook is properly wired by checking // that the session works correctly with the hook registered. - // If the hook did fire, the assertions inside it would have run. expect(session.sessionId).toBeDefined(); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); await session.disconnect(); }); it("should invoke userPromptSubmitted hook and modify prompt", async () => { const inputs: UserPromptSubmittedHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onUserPromptSubmitted: async (input, invocation) => { inputs.push(input); - expect(invocation.sessionId).toBeTruthy(); + invocationSessionIds.push(invocation.sessionId); return { modifiedPrompt: "Reply with exactly: HOOKED_PROMPT" }; }, }, @@ -143,6 +159,9 @@ describe("Extended session hooks", async () => { const response = await session.sendAndWait({ prompt: "Say something else" }); expect(inputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); expect(inputs[0].prompt).toContain("Say something else"); expect(response?.data.content ?? "").toContain("HOOKED_PROMPT"); @@ -151,12 +170,13 @@ describe("Extended session hooks", async () => { it("should invoke sessionStart hook", async () => { const inputs: SessionStartHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onSessionStart: async (input, invocation) => { inputs.push(input); - expect(invocation.sessionId).toBeTruthy(); + invocationSessionIds.push(invocation.sessionId); return { additionalContext: "Session start hook context." }; }, }, @@ -165,6 +185,9 @@ describe("Extended session hooks", async () => { await session.sendAndWait({ prompt: "Say hi" }); expect(inputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); expect(inputs[0].source).toBe("new"); expect(inputs[0].workingDirectory).toBeTruthy(); @@ -173,6 +196,7 @@ describe("Extended session hooks", async () => { it("should invoke sessionEnd hook", async () => { const inputs: SessionEndHookInput[] = []; + const invocationSessionIds: string[] = []; let resolveHook!: (value: SessionEndHookInput) => void; const hookInvoked = new Promise((resolve) => { resolveHook = resolve; @@ -183,7 +207,7 @@ describe("Extended session hooks", async () => { hooks: { onSessionEnd: async (input, invocation) => { inputs.push(input); - expect(invocation.sessionId).toBeTruthy(); + invocationSessionIds.push(invocation.sessionId); resolveHook(input); return { sessionSummary: "session ended" }; }, @@ -206,16 +230,20 @@ describe("Extended session hooks", async () => { } expect(inputs.length).toBeGreaterThan(0); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); }); it("should register erroroccurred hook", async () => { const inputs: ErrorOccurredHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { onErrorOccurred: async (input, invocation) => { inputs.push(input); - expect(invocation.sessionId).toBeTruthy(); + invocationSessionIds.push(invocation.sessionId); return { errorHandling: "skip" }; }, }, @@ -226,6 +254,7 @@ describe("Extended session hooks", async () => { // OnErrorOccurred is dispatched only by genuine runtime errors. A normal turn // cannot deterministically trigger one; this test is registration-only. expect(inputs.length).toBe(0); + expect(invocationSessionIds).toHaveLength(0); expect(session.sessionId).toBeTruthy(); await session.disconnect(); @@ -307,6 +336,7 @@ describe("Extended session hooks", async () => { // wasn't specified. Follow up with runtime team. const failureInputs: PostToolUseFailureHookInput[] = []; const postToolUseInputs: PostToolUseHookInput[] = []; + const invocationSessionIds: string[] = []; const session = await client.createSession({ onPermissionRequest: approveAll, hooks: { @@ -315,7 +345,7 @@ describe("Extended session hooks", async () => { }, onPostToolUseFailure: async (input, invocation) => { failureInputs.push(input); - expect(invocation.sessionId).toBe(session.sessionId); + invocationSessionIds.push(invocation.sessionId); return { additionalContext: "HOOK_FAILURE_GUIDANCE_APPLIED" }; }, }, @@ -327,6 +357,9 @@ describe("Extended session hooks", async () => { expect(postToolUseInputs).toHaveLength(0); expect(failureInputs).toHaveLength(1); + expect(invocationSessionIds.every((sessionId) => sessionId === session.sessionId)).toBe( + true + ); expect(failureInputs[0].toolName).toBe("view"); expect(failureInputs[0].error).toContain("does not exist"); expect((failureInputs[0].toolArgs as { path?: string }).path).toContain("missing.txt"); diff --git a/nodejs/test/e2e/inprocess_ffi.e2e.test.ts b/nodejs/test/e2e/inprocess_ffi.e2e.test.ts new file mode 100644 index 0000000000..af879ea77b --- /dev/null +++ b/nodejs/test/e2e/inprocess_ffi.e2e.test.ts @@ -0,0 +1,26 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it } from "vitest"; +import { CopilotClient, RuntimeConnection } from "../../src/index.js"; + +describe("In-process FFI transport", () => { + // Smoke test that the in-process FFI transport starts and completes a round-trip. + // Resolution of the in-process transport from COPILOT_SDK_DEFAULT_CONNECTION is + // exercised by the full E2E suite running under the `inprocess` CI matrix cell, + // not a dedicated test. + it("should start and connect over in-process FFI", async () => { + // In-process FFI hosting resolves the CLI entrypoint (COPILOT_CLI_PATH or the + // bundled platform package) and its sibling native runtime library itself. If + // neither is available, start() throws and the test fails hard. + const client = new CopilotClient({ connection: RuntimeConnection.forInProcess() }); + await client.start(); + + const pong = await client.ping("ffi message"); + expect(pong.message).toBe("pong: ffi message"); + expect(Date.parse(pong.timestamp)).not.toBeNaN(); + + expect(await client.stop()).toHaveLength(0); // No errors on stop + }); +}); diff --git a/nodejs/test/e2e/mcp_oauth.e2e.test.ts b/nodejs/test/e2e/mcp_oauth.e2e.test.ts new file mode 100644 index 0000000000..0556e857fc --- /dev/null +++ b/nodejs/test/e2e/mcp_oauth.e2e.test.ts @@ -0,0 +1,378 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; +import { dirname, resolve } from "node:path"; +import { createInterface } from "node:readline"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it, onTestFinished } from "vitest"; +import type { CopilotSession, MCPServerConfig, McpAuthRequest } from "../../src/index.js"; +import { approveAll } from "../../src/index.js"; +import { createSdkTestContext } from "./harness/sdkTestContext.js"; +import { waitForCondition } from "./harness/sdkTestHelper.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const TEST_MCP_OAUTH_SERVER = resolve(__dirname, "../../../test/harness/test-mcp-oauth-server.mjs"); +const EXPECTED_TOKEN = "sdk-host-token"; +const REFRESH_TOKEN = `${EXPECTED_TOKEN}-refresh`; +const UPSCOPE_TOKEN = `${EXPECTED_TOKEN}-upscope`; +const REAUTH_TOKEN = `${EXPECTED_TOKEN}-reauth`; + +describe("MCP OAuth host auth", async () => { + const { copilotClient: client } = await createSdkTestContext({ + copilotClientOptions: { + env: { + COPILOT_MCP_APPS: "true", + MCP_APPS: "true", + }, + }, + }); + + it("should satisfy MCP OAuth using host-provided token", { timeout: 120_000 }, async () => { + const oauthServer = await startOAuthMcpServer(); + const serverName = "oauth-protected-mcp"; + let authRequest: McpAuthRequest | undefined; + + const session = await client.createSession({ + onPermissionRequest: approveAll, + enableMcpApps: true, + onMcpAuthRequest: async (request) => { + authRequest = request; + return { + kind: "token", + accessToken: EXPECTED_TOKEN, + tokenType: "Bearer", + expiresIn: 3600, + }; + }, + mcpServers: { + [serverName]: { + type: "http", + url: `${oauthServer.url}/mcp`, + tools: ["*"], + oauthClientId: "sdk-e2e-client", + oauthPublicClient: true, + } as unknown as MCPServerConfig, + }, + }); + onTestFinished(() => disconnectSession(session)); + + await waitForMcpServerStatus(session, serverName); + + const tools = await session.rpc.mcp.listTools({ serverName }); + expect(tools.tools.map((tool) => tool.name)).toContain("whoami"); + + expect(authRequest).toMatchObject({ + requestId: expect.any(String), + serverName, + serverUrl: `${oauthServer.url}/mcp`, + reason: "initial", + wwwAuthenticateParams: { + resourceMetadataUrl: `${oauthServer.url}/.well-known/oauth-protected-resource`, + scope: "mcp.read", + error: "invalid_token", + }, + resourceMetadata: JSON.stringify({ + resource: `${oauthServer.url}/mcp`, + authorization_servers: [oauthServer.url], + scopes_supported: ["mcp.read"], + bearer_methods_supported: ["header"], + }), + }); + + const requests = await oauthServer.requests(); + expect(requests.some((request) => request.authorization === null)).toBe(true); + expect( + requests.some((request) => request.authorization === `Bearer ${EXPECTED_TOKEN}`) + ).toBe(true); + }); + + it( + "should resolve pending MCP OAuth request with direct RPC", + { timeout: 120_000 }, + async () => { + const oauthServer = await startOAuthMcpServer(); + const serverName = "oauth-direct-rpc-mcp"; + let resolveAuthRequest!: (request: McpAuthRequest) => void; + const authRequest = new Promise((resolve) => { + resolveAuthRequest = resolve; + }); + let releaseHandler!: (value: unknown) => void; + const handlerResult = new Promise((resolve) => { + releaseHandler = resolve; + }); + + const session = await client.createSession({ + onPermissionRequest: approveAll, + enableMcpApps: true, + onMcpAuthRequest: async (request) => { + resolveAuthRequest(request); + await handlerResult; + return { kind: "token", accessToken: EXPECTED_TOKEN }; + }, + mcpServers: { + [serverName]: { + type: "http", + url: `${oauthServer.url}/mcp`, + tools: ["*"], + oauthClientId: "sdk-e2e-client", + oauthPublicClient: true, + } as unknown as MCPServerConfig, + }, + }); + onTestFinished(() => disconnectSession(session)); + + const connected = waitForMcpServerStatus(session, serverName); + const request = await authRequest; + expect(request).toMatchObject({ + requestId: expect.any(String), + serverName, + serverUrl: `${oauthServer.url}/mcp`, + reason: "initial", + wwwAuthenticateParams: { + resourceMetadataUrl: `${oauthServer.url}/.well-known/oauth-protected-resource`, + scope: "mcp.read", + error: "invalid_token", + }, + }); + + const handled = await session.rpc.mcp.oauth.handlePendingRequest({ + requestId: request.requestId, + result: { + kind: "token", + accessToken: EXPECTED_TOKEN, + tokenType: "Bearer", + expiresIn: 3600, + }, + }); + expect(handled.success).toBe(true); + + await connected; + const tools = await session.rpc.mcp.listTools({ serverName }); + expect(tools.tools.map((tool) => tool.name)).toContain("whoami"); + releaseHandler(undefined); + } + ); + + it( + "should request host-owned replacement tokens across the MCP OAuth lifecycle", + { timeout: 120_000 }, + async () => { + const oauthServer = await startOAuthMcpServer(); + const serverName = "oauth-lifecycle-mcp"; + const authRequests: McpAuthRequest[] = []; + let refreshCount = 0; + + const session = await client.createSession({ + onPermissionRequest: approveAll, + enableMcpApps: true, + onMcpAuthRequest: async (request) => { + authRequests.push(request); + switch (request.reason) { + case "initial": + return { kind: "token", accessToken: EXPECTED_TOKEN }; + case "refresh": + refreshCount++; + if (refreshCount === 1) { + return { kind: "token", accessToken: REFRESH_TOKEN }; + } + return { kind: "cancelled" }; + case "upscope": + return { kind: "token", accessToken: UPSCOPE_TOKEN }; + case "reauth": + return { kind: "token", accessToken: REAUTH_TOKEN }; + } + }, + mcpServers: { + [serverName]: { + type: "http", + url: `${oauthServer.url}/mcp`, + tools: ["*"], + oauthClientId: "sdk-e2e-client", + oauthPublicClient: true, + } as unknown as MCPServerConfig, + }, + }); + onTestFinished(() => disconnectSession(session)); + + await waitForMcpServerStatus(session, serverName); + await callWhoami(session, serverName, "refresh"); + await callWhoami(session, serverName, "upscope"); + await callWhoami(session, serverName, "reauth"); + + expect(authRequests.map((request) => request.reason)).toEqual([ + "initial", + "refresh", + "upscope", + "refresh", + "reauth", + ]); + + const upscopeRequest = authRequests.find((request) => request.reason === "upscope"); + expect(upscopeRequest?.wwwAuthenticateParams).toEqual({ + resourceMetadataUrl: `${oauthServer.url}/.well-known/oauth-protected-resource`, + scope: "mcp.write", + error: "insufficient_scope", + }); + expect(upscopeRequest?.resourceMetadata).toBe( + JSON.stringify({ + resource: `${oauthServer.url}/mcp`, + authorization_servers: [oauthServer.url], + scopes_supported: ["mcp.read"], + bearer_methods_supported: ["header"], + }) + ); + + const requests = await oauthServer.requests(); + for (const token of [EXPECTED_TOKEN, REFRESH_TOKEN, UPSCOPE_TOKEN, REAUTH_TOKEN]) { + expect( + requests.some((request) => request.authorization === `Bearer ${token}`) + ).toBe(true); + } + } + ); + + it( + "should cancel pending MCP OAuth requests when the host declines", + { timeout: 120_000 }, + async () => { + const oauthServer = await startOAuthMcpServer(); + const serverName = "oauth-cancelled-mcp"; + let authRequest: McpAuthRequest | undefined; + + const session = await client.createSession({ + onPermissionRequest: approveAll, + onMcpAuthRequest: async (request) => { + authRequest = request; + return { kind: "cancelled" }; + }, + mcpServers: { + [serverName]: { + type: "http", + url: `${oauthServer.url}/mcp`, + tools: ["*"], + oauthClientId: "sdk-e2e-client", + oauthPublicClient: true, + } as unknown as MCPServerConfig, + }, + }); + onTestFinished(() => disconnectSession(session)); + + await waitForMcpServerStatus(session, serverName, "needs-auth"); + + expect(authRequest).toMatchObject({ + serverName, + reason: "initial", + }); + } + ); +}); + +async function waitForMcpServerStatus( + session: CopilotSession, + serverName: string, + expectedStatus = "connected" +): Promise { + let lastStatus = ""; + await waitForCondition( + async () => { + const result = await session.rpc.mcp.list(); + const server = result.servers.find((entry) => entry.name === serverName); + lastStatus = server?.status ?? ""; + return server?.status === expectedStatus; + }, + { + timeoutMs: 60_000, + intervalMs: 200, + timeoutMessage: `${serverName} did not reach ${expectedStatus}; last status was ${lastStatus}`, + } + ); +} + +async function callWhoami( + session: CopilotSession, + serverName: string, + scenario: "refresh" | "upscope" | "reauth" +): Promise { + const result = await session.rpc.mcp.apps.callTool({ + serverName, + originServerName: serverName, + toolName: "whoami", + arguments: { scenario }, + }); + expect(result.content).toEqual([{ type: "text", text: "oauth-test-user" }]); +} + +async function startOAuthMcpServer(): Promise<{ + url: string; + requests: () => Promise>; +}> { + const child = spawn(process.execPath, [TEST_MCP_OAUTH_SERVER], { + env: { ...process.env, EXPECTED_TOKEN }, + stdio: ["ignore", "pipe", "pipe"], + }); + onTestFinished(() => stopChild(child)); + + const stderr: string[] = []; + child.stderr.on("data", (chunk) => stderr.push(String(chunk))); + + const url = await new Promise((resolvePromise, reject) => { + const rl = createInterface({ input: child.stdout }); + const timeout = setTimeout(() => { + rl.close(); + reject(new Error(`Timed out waiting for OAuth MCP server. ${stderr.join("")}`)); + }, 10_000); + + child.once("exit", (code, signal) => { + clearTimeout(timeout); + rl.close(); + reject( + new Error( + `OAuth MCP server exited before listening. code=${code} signal=${signal} ${stderr.join("")}` + ) + ); + }); + + rl.on("line", (line) => { + const match = /^Listening: (.+)$/.exec(line); + if (!match) { + return; + } + clearTimeout(timeout); + rl.close(); + resolvePromise(match[1]); + }); + }); + + return { + url, + requests: async () => { + const response = await fetch(`${url}/__requests`); + if (!response.ok) { + throw new Error(`Failed to fetch OAuth MCP requests: ${response.status}`); + } + return response.json(); + }, + }; +} + +async function disconnectSession(session: CopilotSession): Promise { + try { + await session.disconnect(); + } catch { + // Best-effort cleanup. + } +} + +function stopChild(child: ChildProcessWithoutNullStreams): Promise { + if (child.exitCode !== null || child.killed) { + return Promise.resolve(); + } + const exitPromise = new Promise((resolvePromise) => { + child.once("exit", () => resolvePromise()); + }); + child.kill("SIGTERM"); + return exitPromise; +} diff --git a/nodejs/test/e2e/mode_handlers.e2e.test.ts b/nodejs/test/e2e/mode_handlers.e2e.test.ts index 8e2b8aed67..71c4b08963 100644 --- a/nodejs/test/e2e/mode_handlers.e2e.test.ts +++ b/nodejs/test/e2e/mode_handlers.e2e.test.ts @@ -110,7 +110,7 @@ describe("Mode handlers", async () => { expect(exitPlanModeRequests).toHaveLength(1); expect(exitPlanModeRequests[0]).toMatchObject({ summary: PLAN_SUMMARY, - actions: ["interactive", "autopilot", "exit_only"], + actions: ["autopilot", "interactive", "exit_only"], recommendedAction: "interactive", }); expect(exitPlanModeRequests[0].planContent).toBeDefined(); diff --git a/nodejs/test/e2e/multi-client.e2e.test.ts b/nodejs/test/e2e/multi-client.e2e.test.ts index a63b1b0ebf..a44ceec3c3 100644 --- a/nodejs/test/e2e/multi-client.e2e.test.ts +++ b/nodejs/test/e2e/multi-client.e2e.test.ts @@ -6,7 +6,7 @@ import { describe, expect, it, afterAll } from "vitest"; import { z } from "zod"; import { CopilotClient, defineTool, approveAll, RuntimeConnection } from "../../src/index.js"; import type { SessionEvent } from "../../src/index.js"; -import { createSdkTestContext } from "./harness/sdkTestContext"; +import { createSdkTestContext, isInProcessTransport } from "./harness/sdkTestContext"; describe("Multi-client broadcast", async () => { // Use TCP mode so a second client can connect to the same CLI process @@ -304,71 +304,75 @@ describe("Multi-client broadcast", async () => { } ); - it("disconnecting client removes its tools", { timeout: 90_000 }, async () => { - const toolA = defineTool("stable_tool", { - description: "A tool that persists across disconnects", - parameters: z.object({ input: z.string() }), - handler: ({ input }) => `STABLE_${input}`, - }); + it.skipIf(isInProcessTransport)( + "disconnecting client removes its tools", + { timeout: 90_000 }, + async () => { + const toolA = defineTool("stable_tool", { + description: "A tool that persists across disconnects", + parameters: z.object({ input: z.string() }), + handler: ({ input }) => `STABLE_${input}`, + }); - const toolB = defineTool("ephemeral_tool", { - description: "A tool that will disappear when its client disconnects", - parameters: z.object({ input: z.string() }), - handler: ({ input }) => `EPHEMERAL_${input}`, - }); + const toolB = defineTool("ephemeral_tool", { + description: "A tool that will disappear when its client disconnects", + parameters: z.object({ input: z.string() }), + handler: ({ input }) => `EPHEMERAL_${input}`, + }); - // Client 1 creates a session with stable_tool - const session1 = await client1.createSession({ - onPermissionRequest: approveAll, - tools: [toolA], - }); + // Client 1 creates a session with stable_tool + const session1 = await client1.createSession({ + onPermissionRequest: approveAll, + tools: [toolA], + }); - // Client 2 resumes with ephemeral_tool - await client2.resumeSession(session1.sessionId, { - onPermissionRequest: approveAll, - tools: [toolB], - }); + // Client 2 resumes with ephemeral_tool + await client2.resumeSession(session1.sessionId, { + onPermissionRequest: approveAll, + tools: [toolB], + }); - // Verify both tools work before disconnect (sequential to avoid nondeterministic tool_call ordering) - const stableResponse = await session1.sendAndWait({ - prompt: "Use the stable_tool with input 'test1' and tell me the result.", - }); - expect(stableResponse?.data.content).toContain("STABLE_test1"); + // Verify both tools work before disconnect (sequential to avoid nondeterministic tool_call ordering) + const stableResponse = await session1.sendAndWait({ + prompt: "Use the stable_tool with input 'test1' and tell me the result.", + }); + expect(stableResponse?.data.content).toContain("STABLE_test1"); - const ephemeralResponse = await session1.sendAndWait({ - prompt: "Use the ephemeral_tool with input 'test2' and tell me the result.", - }); - expect(ephemeralResponse?.data.content).toContain("EPHEMERAL_test2"); - - // Disconnect client 2 without destroying the shared session. - // Suppress "Connection is disposed" rejections that occur when the server - // broadcasts events (e.g. tool_changed_notice) to the now-dead connection. - const suppressDisposed = (reason: unknown) => { - if (reason instanceof Error && reason.message.includes("Connection is disposed")) { - return; - } - throw reason; - }; - process.on("unhandledRejection", suppressDisposed); - await client2.forceStop(); - - // Give the server time to process the connection close and remove tools - await new Promise((resolve) => setTimeout(resolve, 500)); - process.removeListener("unhandledRejection", suppressDisposed); - - // Recreate client2 for cleanup in afterAll (but don't rejoin the session) - client2 = new CopilotClient({ - connection: RuntimeConnection.forUri(`localhost:${runtimePort}`, { - connectionToken: tcpConnectionToken, - }), - }); + const ephemeralResponse = await session1.sendAndWait({ + prompt: "Use the ephemeral_tool with input 'test2' and tell me the result.", + }); + expect(ephemeralResponse?.data.content).toContain("EPHEMERAL_test2"); + + // Disconnect client 2 without destroying the shared session. + // Suppress "Connection is disposed" rejections that occur when the server + // broadcasts events (e.g. tool_changed_notice) to the now-dead connection. + const suppressDisposed = (reason: unknown) => { + if (reason instanceof Error && reason.message.includes("Connection is disposed")) { + return; + } + throw reason; + }; + process.on("unhandledRejection", suppressDisposed); + await client2.forceStop(); + + // Give the server time to process the connection close and remove tools + await new Promise((resolve) => setTimeout(resolve, 500)); + process.removeListener("unhandledRejection", suppressDisposed); + + // Recreate client2 for cleanup in afterAll (but don't rejoin the session) + client2 = new CopilotClient({ + connection: RuntimeConnection.forUri(`localhost:${runtimePort}`, { + connectionToken: tcpConnectionToken, + }), + }); - // Now only stable_tool should be available - const afterResponse = await session1.sendAndWait({ - prompt: "Use the stable_tool with input 'still_here'. Also try using ephemeral_tool if it is available.", - }); - expect(afterResponse?.data.content).toContain("STABLE_still_here"); - // ephemeral_tool should NOT have produced a result - expect(afterResponse?.data.content).not.toContain("EPHEMERAL_"); - }); + // Now only stable_tool should be available + const afterResponse = await session1.sendAndWait({ + prompt: "Use the stable_tool with input 'still_here'. Also try using ephemeral_tool if it is available.", + }); + expect(afterResponse?.data.content).toContain("STABLE_still_here"); + // ephemeral_tool should NOT have produced a result + expect(afterResponse?.data.content).not.toContain("EPHEMERAL_"); + } + ); }); diff --git a/nodejs/test/e2e/pending_work_resume.e2e.test.ts b/nodejs/test/e2e/pending_work_resume.e2e.test.ts index 60bb2399e8..85abc3a900 100644 --- a/nodejs/test/e2e/pending_work_resume.e2e.test.ts +++ b/nodejs/test/e2e/pending_work_resume.e2e.test.ts @@ -57,6 +57,20 @@ async function waitWithTimeout( } } +async function waitForPendingPermissionRequestId(session: CopilotSession): Promise { + const deadline = Date.now() + PENDING_WORK_TIMEOUT_MS; + do { + const pending = await session.rpc.permissions.pendingRequests(); + const request = pending.items[0]; + if (request) { + return request.requestId; + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } while (Date.now() < deadline); + + throw new Error("Timeout waiting for pending permission request"); +} + function waitForExternalToolRequests( session: CopilotSession, toolNames: string[] @@ -205,7 +219,7 @@ describe("Pending work resume", async () => { PENDING_WORK_TIMEOUT_MS, "originalPermissionRequest" ); - const permissionEvent = await permissionRequestedP; + await permissionRequestedP; expect(initialRequest.kind).toBe("custom-tool"); await suspendedClient.forceStop(); @@ -222,10 +236,11 @@ describe("Pending work resume", async () => { }), ], }); + const requestId = await waitForPendingPermissionRequestId(session2); const permissionResult = await session2.rpc.permissions.handlePendingPermissionRequest({ - requestId: permissionEvent.data.requestId, + requestId, result: { kind: "approve-once" }, }); expect(permissionResult.success).toBe(true); diff --git a/nodejs/test/e2e/per_session_auth.e2e.test.ts b/nodejs/test/e2e/per_session_auth.e2e.test.ts index 0bb1dbd4e9..5f55d397d8 100644 --- a/nodejs/test/e2e/per_session_auth.e2e.test.ts +++ b/nodejs/test/e2e/per_session_auth.e2e.test.ts @@ -42,7 +42,7 @@ describe("Per-session GitHub auth", async () => { gitHubToken: "token-alice", }); - const authStatus = await session.rpc.auth.getStatus(); + const authStatus = await session.rpc.gitHubAuth.getStatus(); expect(authStatus.isAuthenticated).toBe(true); expect(authStatus.login).toBe("alice"); expect(authStatus.copilotPlan).toBe("individual_pro"); @@ -60,8 +60,8 @@ describe("Per-session GitHub auth", async () => { gitHubToken: "token-bob", }); - const statusA = await sessionA.rpc.auth.getStatus(); - const statusB = await sessionB.rpc.auth.getStatus(); + const statusA = await sessionA.rpc.gitHubAuth.getStatus(); + const statusB = await sessionB.rpc.gitHubAuth.getStatus(); expect(statusA.isAuthenticated).toBe(true); expect(statusA.login).toBe("alice"); @@ -92,7 +92,7 @@ describe("Per-session GitHub auth", async () => { onPermissionRequest: approveAll, }); - const authStatus = await session.rpc.auth.getStatus(); + const authStatus = await session.rpc.gitHubAuth.getStatus(); // Without a per-session GitHub token, there is no per-session identity. // In CI the process-level fake token may still authenticate globally, // so we check login rather than isAuthenticated. diff --git a/nodejs/test/e2e/provider_endpoint.e2e.test.ts b/nodejs/test/e2e/provider_endpoint.e2e.test.ts index 1bac76253b..8acf6a2469 100644 --- a/nodejs/test/e2e/provider_endpoint.e2e.test.ts +++ b/nodejs/test/e2e/provider_endpoint.e2e.test.ts @@ -7,12 +7,12 @@ import { approveAll } from "../../src/index.js"; import { createSdkTestContext } from "./harness/sdkTestContext.js"; describe("session.provider.getEndpoint RPC", async () => { - const { copilotClient: client, env } = await createSdkTestContext(); - - // The provider endpoint API is gated behind an opt-in env var; the harness - // env object is the same one passed to the CLI subprocess, so mutating it - // here enables the API for this test file's client. - env.COPILOT_ALLOW_GET_PROVIDER_ENDPOINT = "true"; + const { copilotClient: client } = await createSdkTestContext({ + copilotClientOptions: { + // The provider endpoint API is gated behind an opt-in env var. + env: { COPILOT_ALLOW_GET_PROVIDER_ENDPOINT: "true" }, + }, + }); it("returns the BYOK provider endpoint when a custom provider is configured", async () => { const session = await client.createSession({ diff --git a/nodejs/test/e2e/rpc.e2e.test.ts b/nodejs/test/e2e/rpc.e2e.test.ts index 0442ab9267..f90547da9b 100644 --- a/nodejs/test/e2e/rpc.e2e.test.ts +++ b/nodejs/test/e2e/rpc.e2e.test.ts @@ -2,10 +2,10 @@ import { describe, expect, it, onTestFinished } from "vitest"; import { CopilotClient, approveAll } from "../../src/index.js"; import { createSdkTestContext } from "./harness/sdkTestContext.js"; -function onTestFinishedForceStop(client: CopilotClient) { +function onTestFinishedStop(client: CopilotClient) { onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors - process may already be stopped } @@ -15,7 +15,7 @@ function onTestFinishedForceStop(client: CopilotClient) { describe("RPC", () => { it("should call rpc.ping with typed params and result", async () => { const client = new CopilotClient(); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); @@ -28,7 +28,7 @@ describe("RPC", () => { it("should call rpc.models.list with typed result", async () => { const client = new CopilotClient(); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); @@ -48,7 +48,7 @@ describe("RPC", () => { // account.getQuota is defined in schema but not yet implemented in CLI it.skip("should call rpc.account.getQuota when authenticated", async () => { const client = new CopilotClient(); - onTestFinishedForceStop(client); + onTestFinishedStop(client); await client.start(); diff --git a/nodejs/test/e2e/rpc_mcp_and_skills.e2e.test.ts b/nodejs/test/e2e/rpc_mcp_and_skills.e2e.test.ts index cdd64017c1..4025dc444c 100644 --- a/nodejs/test/e2e/rpc_mcp_and_skills.e2e.test.ts +++ b/nodejs/test/e2e/rpc_mcp_and_skills.e2e.test.ts @@ -74,7 +74,7 @@ describe("Session MCP and skills RPC", async () => { }); onTestFinished(async () => { try { - await mcpAppsClient.forceStop(); + await mcpAppsClient.stop(); } catch { // Ignore cleanup errors } diff --git a/nodejs/test/e2e/rpc_mcp_config.e2e.test.ts b/nodejs/test/e2e/rpc_mcp_config.e2e.test.ts index 581567cb3e..95694a8c63 100644 --- a/nodejs/test/e2e/rpc_mcp_config.e2e.test.ts +++ b/nodejs/test/e2e/rpc_mcp_config.e2e.test.ts @@ -9,7 +9,7 @@ function startEphemeralClient(): CopilotClient { const client = new CopilotClient(); onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors } diff --git a/nodejs/test/e2e/rpc_server.e2e.test.ts b/nodejs/test/e2e/rpc_server.e2e.test.ts index 3d4b00c961..5075ae68d9 100644 --- a/nodejs/test/e2e/rpc_server.e2e.test.ts +++ b/nodejs/test/e2e/rpc_server.e2e.test.ts @@ -39,7 +39,7 @@ describe("Server-scoped RPC", async () => { }); onTestFinished(async () => { try { - await extraClient.forceStop(); + await extraClient.stop(); } catch { // Ignore cleanup errors } @@ -103,6 +103,39 @@ describe("Server-scoped RPC", async () => { expect(Date.parse(result.timestamp)).not.toBeNaN(); }); + it("should reject llm inference response frames for missing request", async () => { + await client.start(); + + const start = await client.rpc.llmInference.httpResponseStart({ + requestId: "missing-llm-inference-request", + status: 200, + headers: { + "content-type": ["text/event-stream"], + }, + statusText: "OK", + }); + expect(start.accepted).toBe(false); + + const chunk = await client.rpc.llmInference.httpResponseChunk({ + requestId: "missing-llm-inference-request", + data: "data: {}\n\n", + binary: false, + end: false, + }); + expect(chunk.accepted).toBe(false); + + const error = await client.rpc.llmInference.httpResponseChunk({ + requestId: "missing-llm-inference-request", + data: "", + end: true, + error: { + code: "missing_request", + message: "No pending LLM inference request.", + }, + }); + expect(error.accepted).toBe(false); + }); + it("should call rpc models list with typed result", async () => { const token = "rpc-models-token"; await configureAuthenticatedUser(token); @@ -401,6 +434,59 @@ describe("Server-scoped RPC", async () => { expect(discovered[0].enabled).toBe(true); expect(discovered[0].path.endsWith(path.join(skillName, "SKILL.md"))).toBe(true); + const skillPaths = await client.rpc.skills.getDiscoveryPaths({ + projectPaths: [workDir], + excludeHostSkills: true, + }); + const projectSkillPath = skillPaths.paths.find( + (p) => p.projectPath && pathsEqual(p.projectPath, workDir) && p.preferredForCreation + ); + if (!projectSkillPath) { + throw new Error(`Expected skill discovery paths to include ${workDir}`); + } + expect(projectSkillPath.path.trim()).not.toBe(""); + + const agents = await client.rpc.agents.discover({ + projectPaths: [workDir], + excludeHostAgents: true, + }); + expect(agents.agents.every((agent) => agent.name.trim() !== "")).toBe(true); + + const agentPaths = await client.rpc.agents.getDiscoveryPaths({ + projectPaths: [workDir], + excludeHostAgents: true, + }); + const projectAgentPath = agentPaths.paths.find( + (p) => p.projectPath && pathsEqual(p.projectPath, workDir) && p.preferredForCreation + ); + if (!projectAgentPath) { + throw new Error(`Expected agent discovery paths to include ${workDir}`); + } + expect(projectAgentPath.path.trim()).not.toBe(""); + + const instructions = await client.rpc.instructions.discover({ + projectPaths: [workDir], + excludeHostInstructions: true, + }); + expect( + instructions.sources.every( + (source) => + source.id.trim() !== "" && + source.label.trim() !== "" && + source.sourcePath.trim() !== "" + ) + ).toBe(true); + + const instructionPaths = await client.rpc.instructions.getDiscoveryPaths({ + projectPaths: [workDir], + excludeHostInstructions: true, + }); + expect(instructionPaths.paths.length).toBeGreaterThan(0); + expect( + instructionPaths.paths.some((p) => p.projectPath && pathsEqual(p.projectPath, workDir)) + ).toBe(true); + expect(instructionPaths.paths.every((p) => p.path.trim() !== "")).toBe(true); + try { await client.rpc.skills.config.setDisabledSkills({ disabledSkills: [skillName] }); const disabled = await client.rpc.skills.discover({ diff --git a/nodejs/test/e2e/rpc_server_misc.e2e.test.ts b/nodejs/test/e2e/rpc_server_misc.e2e.test.ts index d358c7d9d1..4f12e507a5 100644 --- a/nodejs/test/e2e/rpc_server_misc.e2e.test.ts +++ b/nodejs/test/e2e/rpc_server_misc.e2e.test.ts @@ -11,7 +11,7 @@ import { createSdkTestContext, DEFAULT_GITHUB_TOKEN } from "./harness/sdkTestCon import { formatError, waitForCondition } from "./harness/sdkTestHelper.js"; describe("Miscellaneous server-scoped RPC", async () => { - const { copilotClient: client, env, workDir } = await createSdkTestContext(); + const { copilotClient: client, env, openAiEndpoint, workDir } = await createSdkTestContext(); function createUniqueDirectory(prefix: string): string { const directory = join(workDir, `${prefix}-${randomUUID()}`); @@ -19,7 +19,10 @@ describe("Miscellaneous server-scoped RPC", async () => { return directory; } - function createClient(extraEnv: Record = {}): CopilotClient { + function createClient( + extraEnv: Record, + gitHubToken: string | undefined + ): CopilotClient { return new CopilotClient({ workingDirectory: workDir, env: { @@ -28,21 +31,29 @@ describe("Miscellaneous server-scoped RPC", async () => { }, logLevel: "error", connection: RuntimeConnection.forStdio({ path: process.env.COPILOT_CLI_PATH }), - gitHubToken: DEFAULT_GITHUB_TOKEN, + gitHubToken, + useLoggedInUser: gitHubToken === undefined ? false : undefined, }); } - async function createIsolatedStartedClient(): Promise<{ + async function createIsolatedStartedClient( + gitHubToken: string | null = DEFAULT_GITHUB_TOKEN + ): Promise<{ client: CopilotClient; home: string; }> { const home = createUniqueDirectory("copilot-e2e-misc-home"); - const isolatedClient = createClient({ - COPILOT_HOME: home, - GH_CONFIG_DIR: home, - XDG_CONFIG_HOME: home, - XDG_STATE_HOME: home, - }); + const effectiveGitHubToken = gitHubToken === null ? undefined : gitHubToken; + const isolatedClient = createClient( + { + COPILOT_HOME: home, + GH_CONFIG_DIR: home, + XDG_CONFIG_HOME: home, + XDG_STATE_HOME: home, + COPILOT_DEBUG_GITHUB_API_URL: env.COPILOT_API_URL, + }, + effectiveGitHubToken + ); try { await isolatedClient.start(); return { client: isolatedClient, home }; @@ -54,7 +65,7 @@ describe("Miscellaneous server-scoped RPC", async () => { async function disposeIsolated(isolatedClient: CopilotClient, home: string): Promise { try { - await isolatedClient.forceStop(); + await isolatedClient.stop(); } catch { // Best-effort cleanup. } @@ -63,7 +74,7 @@ describe("Miscellaneous server-scoped RPC", async () => { async function forceStop(target: CopilotClient): Promise { try { - await target.forceStop(); + await target.stop(); } catch { // Runtime may already be gone. } @@ -83,6 +94,101 @@ describe("Miscellaneous server-scoped RPC", async () => { await client.rpc.user.settings.reload(); }); + it("should get set and clear user settings", { timeout: 120_000 }, async () => { + const { client: isolatedClient, home } = await createIsolatedStartedClient(); + try { + const before = await isolatedClient.rpc.user.settings.get(); + expect(Object.keys(before.settings).length).toBeGreaterThan(0); + for (const [key, setting] of Object.entries(before.settings)) { + expect(key.trim()).toBeTruthy(); + expect(setting.value !== undefined || setting.default !== undefined).toBe(true); + } + + const entry = Object.entries(before.settings).find( + ([, setting]) => typeof setting.value === "boolean" + ); + expect(entry).toBeDefined(); + const [settingKey, setting] = entry!; + const toggledValue = setting.value !== true; + + const set = await isolatedClient.rpc.user.settings.set({ + settings: { [settingKey]: toggledValue }, + }); + expect(set.shadowedKeys).not.toContain(settingKey); + + await isolatedClient.rpc.user.settings.reload(); + const afterSet = await isolatedClient.rpc.user.settings.get(); + expect(afterSet.settings[settingKey].isDefault).toBe(false); + expect(afterSet.settings[settingKey].value).toBe(toggledValue); + + await isolatedClient.rpc.user.settings.set({ + settings: { [settingKey]: null }, + }); + await isolatedClient.rpc.user.settings.reload(); + const afterClear = await isolatedClient.rpc.user.settings.get(); + expect(afterClear.settings[settingKey].isDefault).toBe(true); + } finally { + await disposeIsolated(isolatedClient, home); + } + }); + + it("should login list getCurrentAuth and logout account", { timeout: 120_000 }, async () => { + const login = `rpc-account-${randomUUID().replaceAll("-", "")}`; + const token = `rpc-account-token-${randomUUID().replaceAll("-", "")}`; + await openAiEndpoint.setCopilotUserByToken(token, { + login, + copilot_plan: "individual_pro", + endpoints: { + api: env.COPILOT_API_URL, + telemetry: "https://localhost:1/telemetry", + }, + analytics_tracking_id: "rpc-account-tracking-id", + }); + + const { client: isolatedClient, home } = await createIsolatedStartedClient(null); + try { + const initial = await isolatedClient.rpc.account.getCurrentAuth(); + expect(initial.authInfo).toBeUndefined(); + + const loginResult = await isolatedClient.rpc.account.login({ + host: "https://github.com", + login, + token, + }); + expect(typeof loginResult.storedInVault).toBe("boolean"); + + const current = await isolatedClient.rpc.account.getCurrentAuth(); + expect(current.authErrors).toBeUndefined(); + expect(current.authInfo).toMatchObject({ + type: "user", + host: "https://github.com", + login, + }); + + const users = await isolatedClient.rpc.account.getAllUsers(); + expect(Array.isArray(users)).toBe(true); + for (const user of users) { + expect(user.authInfo.type.trim()).toBeTruthy(); + } + const account = users.find( + (user) => user.authInfo.type === "user" && user.authInfo.login === login + ); + if (account) { + expect(account?.token).toBe(token); + } + + const logout = await isolatedClient.rpc.account.logout({ + authInfo: current.authInfo!, + }); + expect(logout.hasMoreUsers).toBe(false); + + const afterLogout = await isolatedClient.rpc.account.getCurrentAuth(); + expect(afterLogout.authInfo).toBeUndefined(); + } finally { + await disposeIsolated(isolatedClient, home); + } + }); + it("should report agent registry spawn gate closed", { timeout: 120_000 }, async () => { const { client: isolatedClient, home } = await createIsolatedStartedClient(); try { @@ -104,7 +210,7 @@ describe("Miscellaneous server-scoped RPC", async () => { }); it("should shut down owned runtime", { timeout: 120_000 }, async () => { - const dedicatedClient = createClient(); + const dedicatedClient = createClient({}, DEFAULT_GITHUB_TOKEN); try { await dedicatedClient.start(); await dedicatedClient.rpc.user.settings.reload(); diff --git a/nodejs/test/e2e/rpc_server_plugins.e2e.test.ts b/nodejs/test/e2e/rpc_server_plugins.e2e.test.ts index c678c05436..20575a9114 100644 --- a/nodejs/test/e2e/rpc_server_plugins.e2e.test.ts +++ b/nodejs/test/e2e/rpc_server_plugins.e2e.test.ts @@ -59,7 +59,7 @@ describe("Server-scoped plugin RPC", async () => { fixtureDir?: string ): Promise { try { - await client.forceStop(); + await client.stop(); } catch { // Best-effort cleanup. } @@ -127,46 +127,31 @@ This skill exists so the plugin reports at least one installed skill. writeFileSync(join(pluginDir, "SKILL.md"), skill); } - it( - "should install list and uninstall plugin from local marketplace", - { timeout: 120_000 }, - async () => { - const marketplaceDir = createLocalMarketplaceFixture(); - const { client, home } = await createIsolatedStartedClient(); - try { - await client.rpc.plugins.marketplaces.add({ source: marketplaceDir }); - - const spec = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`; - const install = await client.rpc.plugins.install({ source: spec }); - - expect(install.plugin.name).toBe(PLUGIN_NAME); - expect(install.plugin.marketplace).toBe(MARKETPLACE_NAME); - expect(install.plugin.enabled).toBe(true); - expect(install.skillsInstalled).toBeGreaterThanOrEqual(1); - expect(install.deprecationWarning ?? null).toBeNull(); + it("should install and list plugin from local marketplace", { timeout: 120_000 }, async () => { + const marketplaceDir = createLocalMarketplaceFixture(); + const { client, home } = await createIsolatedStartedClient(); + try { + await client.rpc.plugins.marketplaces.add({ source: marketplaceDir }); - const afterInstall = await client.rpc.plugins.list(); - const listed = afterInstall.plugins.filter( - (plugin) => - plugin.name === PLUGIN_NAME && plugin.marketplace === MARKETPLACE_NAME - ); - expect(listed).toHaveLength(1); - expect(listed[0].enabled).toBe(true); + const spec = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`; + const install = await client.rpc.plugins.install({ source: spec }); - await client.rpc.plugins.uninstall({ name: spec }); + expect(install.plugin.name).toBe(PLUGIN_NAME); + expect(install.plugin.marketplace).toBe(MARKETPLACE_NAME); + expect(install.plugin.enabled).toBe(true); + expect(install.skillsInstalled).toBeGreaterThanOrEqual(1); + expect(install.deprecationWarning ?? null).toBeNull(); - const afterUninstall = await client.rpc.plugins.list(); - expect( - afterUninstall.plugins.some( - (plugin) => - plugin.name === PLUGIN_NAME && plugin.marketplace === MARKETPLACE_NAME - ) - ).toBe(false); - } finally { - await disposeIsolated(client, home, marketplaceDir); - } + const afterInstall = await client.rpc.plugins.list(); + const listed = afterInstall.plugins.filter( + (plugin) => plugin.name === PLUGIN_NAME && plugin.marketplace === MARKETPLACE_NAME + ); + expect(listed).toHaveLength(1); + expect(listed[0].enabled).toBe(true); + } finally { + await disposeIsolated(client, home, marketplaceDir); } - ); + }); it("should enable and disable marketplace plugin", { timeout: 120_000 }, async () => { const marketplaceDir = createLocalMarketplaceFixture(); @@ -244,8 +229,12 @@ This skill exists so the plugin reports at least one installed skill. expect( afterInstall.plugins.filter((plugin) => plugin.name === DIRECT_PLUGIN_NAME) ).toHaveLength(1); + expect(install.plugin.directSourceId).toBeTruthy(); - await client.rpc.plugins.uninstall({ name: DIRECT_PLUGIN_NAME }); + await client.rpc.plugins.uninstall({ + name: DIRECT_PLUGIN_NAME, + directSourceId: install.plugin.directSourceId, + }); const afterUninstall = await client.rpc.plugins.list(); expect( diff --git a/nodejs/test/e2e/rpc_server_remote_control.e2e.test.ts b/nodejs/test/e2e/rpc_server_remote_control.e2e.test.ts index 2e6c6cf05b..3094d32577 100644 --- a/nodejs/test/e2e/rpc_server_remote_control.e2e.test.ts +++ b/nodejs/test/e2e/rpc_server_remote_control.e2e.test.ts @@ -23,7 +23,7 @@ describe("Server-scoped remote-control RPC", async () => { async function forceStop(client: CopilotClient): Promise { try { - await client.forceStop(); + await client.stop(); } catch { // Runtime may already be gone. } diff --git a/nodejs/test/e2e/rpc_session_state.e2e.test.ts b/nodejs/test/e2e/rpc_session_state.e2e.test.ts index d1a628a0df..7c33d55d68 100644 --- a/nodejs/test/e2e/rpc_session_state.e2e.test.ts +++ b/nodejs/test/e2e/rpc_session_state.e2e.test.ts @@ -492,7 +492,7 @@ describe("Session-scoped RPC", async () => { const session = await client.createSession({ onPermissionRequest: approveAll }); try { const login = `sdk-rpc-${randomUUID()}`; - const setCredentials = await session.rpc.auth.setCredentials({ + const setCredentials = await session.rpc.gitHubAuth.setCredentials({ credentials: { type: "user", host: "https://github.com", @@ -511,7 +511,7 @@ describe("Session-scoped RPC", async () => { }); expect(setCredentials.success).toBe(true); - const status = await session.rpc.auth.getStatus(); + const status = await session.rpc.gitHubAuth.getStatus(); expect(status.isAuthenticated).toBe(true); expect(status.authType).toBe("user"); expect(status.host).toBe("https://github.com"); diff --git a/nodejs/test/e2e/rpc_session_state_extras.e2e.test.ts b/nodejs/test/e2e/rpc_session_state_extras.e2e.test.ts index 4b0ff9ba17..54f40fe12c 100644 --- a/nodejs/test/e2e/rpc_session_state_extras.e2e.test.ts +++ b/nodejs/test/e2e/rpc_session_state_extras.e2e.test.ts @@ -84,7 +84,7 @@ describe("Session-scoped state extras RPC", async () => { } finally { await disconnect(session); try { - await authClient.forceStop(); + await authClient.stop(); } catch { // Best-effort cleanup. } @@ -103,6 +103,103 @@ describe("Session-scoped state extras RPC", async () => { } }); + it("should add byok provider and model at runtime", { timeout: 120_000 }, async () => { + const session = await createSession(); + try { + const providerName = `sdk-runtime-provider-${Date.now()}-${Math.random().toString(36).slice(2)}`; + const modelId = "sdk-runtime-model"; + const selectionId = `${providerName}/${modelId}`; + + const added = await session.rpc.provider.add({ + providers: [ + { + name: providerName, + type: "openai", + wireApi: "completions", + baseUrl: "https://api.example.test/v1", + apiKey: "runtime-provider-secret", + headers: { "X-SDK-Provider": "runtime" }, + }, + ], + models: [ + { + provider: providerName, + id: modelId, + name: "SDK Runtime Model", + modelId: "claude-sonnet-4.5", + wireModel: "wire-sdk-runtime-model", + maxContextWindowTokens: 4096, + maxPromptTokens: 3072, + maxOutputTokens: 1024, + capabilities: { + limits: { + maxContextWindowTokens: 4096, + maxPromptTokens: 3072, + maxOutputTokens: 1024, + }, + supports: { + reasoningEffort: false, + vision: false, + }, + }, + }, + ], + }); + + expect(added.models).toHaveLength(1); + expect(JSON.stringify(added.models[0])).toContain(selectionId); + expect(JSON.stringify(added.models[0])).toContain("SDK Runtime Model"); + + const listed = await session.rpc.model.list(); + expect(listed.list.some((model) => JSON.stringify(model).includes(selectionId))).toBe( + true + ); + + const switched = await session.rpc.model.switchTo({ modelId: selectionId }); + expect(switched.modelId).toBe(selectionId); + expect((await session.rpc.model.getCurrent()).modelId).toBe(selectionId); + } finally { + await session.disconnect(); + } + }); + + it( + "should return empty completions when host does not provide them", + { timeout: 120_000 }, + async () => { + const session = await createSession(); + try { + const triggers = await session.rpc.completions.getTriggerCharacters(); + expect(triggers.triggerCharacters).toEqual([]); + + const completions = await session.rpc.completions.request({ + text: "Use @", + offset: 5, + }); + expect(completions.items).toEqual([]); + } finally { + await session.disconnect(); + } + } + ); + + it("should report visibility as unsynced for local session", { timeout: 120_000 }, async () => { + const session = await createSession(); + try { + const initial = await session.rpc.visibility.get(); + expect(initial.synced).toBe(false); + expect(initial.status).toBeUndefined(); + expect(initial.shareUrl).toBeUndefined(); + + const set = await session.rpc.visibility.set({ status: "repo" }); + expect(set.synced).toBe(false); + expect(set.status).toBeUndefined(); + expect(set.shareUrl).toBeUndefined(); + } finally { + await session.disconnect(); + } + }); + it("should get and set allowall permissions", { timeout: 120_000 }, async () => { const session = await createSession(); try { @@ -128,6 +225,72 @@ describe("Session-scoped state extras RPC", async () => { } }); + it( + "should get context attribution and heaviest messages after turn", + { timeout: 120_000 }, + async () => { + const session = await createSession(); + try { + const answer = await session.sendAndWait({ + prompt: "Say CONTEXT_METADATA_OK exactly.", + }); + expect(answer?.data.content ?? "").toContain("CONTEXT_METADATA_OK"); + + const attribution = await session.rpc.metadata.getContextAttribution(); + expect(attribution.contextAttribution).not.toBeNull(); + const contextAttribution = attribution.contextAttribution!; + expect(contextAttribution.totalTokens).toBeGreaterThan(0); + expect(contextAttribution.entries.length).toBeGreaterThan(0); + for (const entry of contextAttribution.entries) { + expect(entry.id.trim()).toBeTruthy(); + expect(entry.kind.trim()).toBeTruthy(); + expect(entry.label.trim()).toBeTruthy(); + expect(entry.tokens).toBeGreaterThanOrEqual(0); + for (const attribute of entry.attributes ?? []) { + expect(attribute.key.trim()).toBeTruthy(); + } + } + + const heaviest = await session.rpc.metadata.getContextHeaviestMessages({ + limit: 2, + }); + expect(heaviest.totalTokens).toBeGreaterThan(0); + expect(heaviest.messages.length).toBeLessThanOrEqual(2); + for (const message of heaviest.messages) { + expect(message.id.trim()).toBeTruthy(); + expect(message.tokens).toBeGreaterThanOrEqual(0); + } + } finally { + await session.disconnect(); + } + } + ); + + it("should update and clear live subagent settings", { timeout: 120_000 }, async () => { + const session = await createSession(); + try { + await expect( + session.rpc.tools.updateSubagentSettings({ + subagents: { + "general-purpose": { + model: "claude-haiku-4.5", + effortLevel: "low", + contextTier: "default", + }, + }, + }) + ).resolves.toBeDefined(); + + await expect( + session.rpc.tools.updateSubagentSettings({ + subagents: null, + }) + ).resolves.toBeDefined(); + } finally { + await session.disconnect(); + } + }); + it("should read empty sql todos for fresh session", { timeout: 120_000 }, async () => { const session = await createSession(); try { diff --git a/nodejs/test/e2e/rpc_tasks_and_handlers.e2e.test.ts b/nodejs/test/e2e/rpc_tasks_and_handlers.e2e.test.ts index e7f7664c3c..cb41c69e68 100644 --- a/nodejs/test/e2e/rpc_tasks_and_handlers.e2e.test.ts +++ b/nodejs/test/e2e/rpc_tasks_and_handlers.e2e.test.ts @@ -173,6 +173,27 @@ describe("Session tasks RPC and pending handlers", async () => { }); expect(locationApproval.success).toBe(false); + const sessionLimits = await session.rpc.ui.handlePendingSessionLimitsExhausted({ + requestId: "missing-session-limits-request", + response: { action: "cancel" }, + }); + expect(sessionLimits.success).toBe(false); + + const headers = await session.rpc.mcp.headers.handlePendingHeadersRefreshRequest({ + requestId: "missing-headers-refresh-request", + result: { + kind: "headers", + headers: { "X-SDK-Test": "missing" }, + }, + }); + expect(headers.success).toBe(false); + + const noHeaders = await session.rpc.mcp.headers.handlePendingHeadersRefreshRequest({ + requestId: "missing-headers-refresh-none-request", + result: { kind: "none" }, + }); + expect(noHeaders.success).toBe(false); + await session.disconnect(); }); diff --git a/nodejs/test/e2e/rpc_workspace_checkpoints.e2e.test.ts b/nodejs/test/e2e/rpc_workspace_checkpoints.e2e.test.ts index d7f478e1f1..78a820f67a 100644 --- a/nodejs/test/e2e/rpc_workspace_checkpoints.e2e.test.ts +++ b/nodejs/test/e2e/rpc_workspace_checkpoints.e2e.test.ts @@ -23,9 +23,9 @@ describe("Session workspace checkpoint RPC", async () => { it("should return null or empty content for unknown checkpoint", async () => { const session = await client.createSession({ onPermissionRequest: approveAll }); try { - const result = await session.rpc.workspaces.readCheckpoint({ - number: Number.MAX_SAFE_INTEGER, - }); + // A high but 32-bit-safe checkpoint number that will never exist in a fresh + // session, so the read reports the checkpoint as missing. + const result = await session.rpc.workspaces.readCheckpoint({ number: 4294967294 }); expect(result.content ?? "").toBe(""); } finally { await session.disconnect(); diff --git a/nodejs/test/e2e/session.e2e.test.ts b/nodejs/test/e2e/session.e2e.test.ts index 55a064ab4e..2cb88917e3 100644 --- a/nodejs/test/e2e/session.e2e.test.ts +++ b/nodejs/test/e2e/session.e2e.test.ts @@ -2,18 +2,19 @@ import { rm } from "fs/promises"; import { describe, expect, it, onTestFinished, vi } from "vitest"; import { ParsedHttpExchange } from "../../../test/harness/replayingCapiProxy.js"; import { CopilotClient, approveAll, defineTool, RuntimeConnection } from "../../src/index.js"; -import { createSdkTestContext, isCI } from "./harness/sdkTestContext.js"; +import { createSdkTestContext, DEFAULT_GITHUB_TOKEN, isCI } from "./harness/sdkTestContext.js"; import { getFinalAssistantMessage, getNextEventOfType, retry } from "./harness/sdkTestHelper.js"; -describe("Sessions", async () => { - const { - copilotClient: client, - openAiEndpoint, - homeDir, - workDir, - env, - } = await createSdkTestContext(); +const { + copilotClient: client, + openAiEndpoint, + homeDir, + workDir, + env, + createClient, +} = await createSdkTestContext(); +describe("Sessions", () => { async function waitForExchanges(minimumCount = 1) { await retry( `capture ${minimumCount} chat completion request(s)`, @@ -39,15 +40,14 @@ describe("Sessions", async () => { }); onTestFinished(async () => { try { - await standaloneClient.forceStop(); + await standaloneClient.stop(); } catch { // ignore } }); - const session = await standaloneClient.createSession({}); + await using session = await standaloneClient.createSession({}); expect(session.sessionId).toMatch(/^[a-f0-9-]+$/); - await session.disconnect(); } ); @@ -64,7 +64,7 @@ describe("Sessions", async () => { }); onTestFinished(async () => { try { - await tcpClient.forceStop(); + await tcpClient.stop(); } catch { // ignore } @@ -84,7 +84,7 @@ describe("Sessions", async () => { }); onTestFinished(async () => { try { - await resumeClient.forceStop(); + await resumeClient.stop(); } catch { // ignore } @@ -96,7 +96,7 @@ describe("Sessions", async () => { await originalSession.disconnect(); }); it("should create and disconnect sessions", async () => { - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, model: "claude-sonnet-4.5", }); @@ -118,7 +118,7 @@ describe("Sessions", async () => { // TODO: Re-enable once test harness CAPI proxy supports this test's session lifecycle it.skip("should list sessions with context field", { timeout: 60000 }, async () => { // Create a session — just creating it is enough for it to appear in listSessions - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); expect(session.sessionId).toMatch(/^[a-f0-9-]+$/); // Verify it has a start event (confirms session is active) @@ -137,7 +137,7 @@ describe("Sessions", async () => { }); it("should get session metadata by ID", { timeout: 60000 }, async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); expect(session.sessionId).toMatch(/^[a-f0-9-]+$/); // Send a message to persist the session to disk @@ -164,7 +164,7 @@ describe("Sessions", async () => { }); it("should have stateful conversation", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); const assistantMessage = await session.sendAndWait({ prompt: "What is 1+1?" }); expect(assistantMessage?.data.content).toContain("2"); @@ -176,7 +176,7 @@ describe("Sessions", async () => { it("should create a session with appended systemMessage config", async () => { const systemMessageSuffix = "End each response with the phrase 'Have a nice day!'"; - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, systemMessage: { mode: "append", @@ -197,7 +197,7 @@ describe("Sessions", async () => { it("should create a session with replaced systemMessage config", async () => { const testSystemMessage = "You are an assistant called Testy McTestface. Reply succinctly."; - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, systemMessage: { mode: "replace", content: testSystemMessage }, }); @@ -218,7 +218,7 @@ describe("Sessions", async () => { async () => { const customTone = "Respond in a warm, professional tone. Be thorough in explanations."; const appendedContent = "Always mention quarterly earnings."; - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, systemMessage: { mode: "customize", @@ -230,66 +230,54 @@ describe("Sessions", async () => { }, }); - try { - await session.send({ prompt: "Who are you?" }); - - // Validate the system message sent to the model - const traffic = await waitForExchanges(); - const systemMessage = getSystemMessage(traffic[0]); - expect(systemMessage).toContain(customTone); - expect(systemMessage).toContain(appendedContent); - // The code_change_rules section should have been removed - expect(systemMessage).not.toContain(""); - } finally { - await session.disconnect(); - } + await session.send({ prompt: "Who are you?" }); + + // Validate the system message sent to the model + const traffic = await waitForExchanges(); + const systemMessage = getSystemMessage(traffic[0]); + expect(systemMessage).toContain(customTone); + expect(systemMessage).toContain(appendedContent); + // The code_change_rules section should have been removed + expect(systemMessage).not.toContain(""); } ); it("should create a session with availableTools", async () => { - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, availableTools: ["view", "edit"], }); - try { - await session.send({ prompt: "What is 1+1?" }); + await session.send({ prompt: "What is 1+1?" }); - // It only tells the model about the specified tools and no others - const traffic = await waitForExchanges(); - expect(traffic[0].request.tools).toMatchObject([ - { function: { name: "view" } }, - { function: { name: "edit" } }, - ]); - } finally { - await session.disconnect(); - } + // It only tells the model about the specified tools and no others + const traffic = await waitForExchanges(); + expect(traffic[0].request.tools).toMatchObject([ + { function: { name: "view" } }, + { function: { name: "edit" } }, + ]); }); it("should create a session with excludedTools", async () => { - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, excludedTools: ["view"], }); - try { - await session.send({ prompt: "What is 1+1?" }); + await session.send({ prompt: "What is 1+1?" }); - // It has other tools, but not the one we excluded - const traffic = await waitForExchanges(); - const functionNames = traffic[0].request.tools?.map( - (t) => (t as { function: { name: string } }).function.name - ); - expect(functionNames).toContain("edit"); - expect(functionNames).toContain("grep"); - expect(functionNames).not.toContain("view"); - } finally { - await session.disconnect(); - } + // It has other tools, but not the one we excluded + const traffic = await waitForExchanges(); + const functionNames = traffic[0].request.tools?.map( + (t) => (t as { function: { name: string } }).function.name + ); + expect(functionNames).toContain("edit"); + expect(functionNames).toContain("grep"); + expect(functionNames).not.toContain("view"); }); it("should create a session with defaultAgent excludedTools", async () => { - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, tools: [ defineTool("secret_tool", { @@ -307,19 +295,15 @@ describe("Sessions", async () => { }, }); - try { - await session.send({ prompt: "What is 1+1?" }); + await session.send({ prompt: "What is 1+1?" }); - // The secret_tool should be registered with the runtime but not advertised - // to the default agent's underlying model call. - const traffic = await waitForExchanges(); - const functionNames = traffic[0].request.tools?.map( - (t) => (t as { function: { name: string } }).function.name - ); - expect(functionNames).not.toContain("secret_tool"); - } finally { - await session.disconnect(); - } + // The secret_tool should be registered with the runtime but not advertised + // to the default agent's underlying model call. + const traffic = await waitForExchanges(); + const functionNames = traffic[0].request.tools?.map( + (t) => (t as { function: { name: string } }).function.name + ); + expect(functionNames).not.toContain("secret_tool"); }); // TODO: This test shows there's a race condition inside client.ts. If createSession is called @@ -362,7 +346,9 @@ describe("Sessions", async () => { expect(answer?.data.content).toContain("2"); // Resume using the same client - const session2 = await client.resumeSession(sessionId, { onPermissionRequest: approveAll }); + await using session2 = await client.resumeSession(sessionId, { + onPermissionRequest: approveAll, + }); expect(session2.sessionId).toBe(sessionId); const messages = await session2.getEvents(); const assistantMessages = messages.filter((m) => m.type === "assistant.message"); @@ -377,19 +363,18 @@ describe("Sessions", async () => { it("should resume a session using a new client", async () => { // Create initial session - const session1 = await client.createSession({ onPermissionRequest: approveAll }); + await using session1 = await client.createSession({ onPermissionRequest: approveAll }); const sessionId = session1.sessionId; const answer = await session1.sendAndWait({ prompt: "What is 1+1?" }); expect(answer?.data.content).toContain("2"); // Resume using a new client - const newClient = new CopilotClient({ - env, + const newClient = createClient({ gitHubToken: isCI ? "fake-token-for-e2e-tests" : undefined, }); - onTestFinished(() => newClient.forceStop()); - const session2 = await newClient.resumeSession(sessionId, { + onTestFinished(() => newClient.stop()); + await using session2 = await newClient.resumeSession(sessionId, { onPermissionRequest: approveAll, }); expect(session2.sessionId).toBe(sessionId); @@ -417,7 +402,7 @@ describe("Sessions", async () => { }); it("should create session with custom tool", async () => { - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, tools: [ { @@ -452,7 +437,7 @@ describe("Sessions", async () => { const sessionId = session.sessionId; // Resume the session with a provider - const session2 = await client.resumeSession(sessionId, { + await using session2 = await client.resumeSession(sessionId, { onPermissionRequest: approveAll, provider: { type: "openai", @@ -464,8 +449,40 @@ describe("Sessions", async () => { expect(session2.sessionId).toBe(sessionId); }); + it("resumes a persisted session from a new client when an MCP OAuth handler is configured", async () => { + // Take a turn so the session is persisted to the store and can be + // loaded by a different CLI process. + await using session1 = await client.createSession({ + onPermissionRequest: approveAll, + onMcpAuthRequest: () => ({ kind: "cancelled" }), + }); + const sessionId = session1.sessionId; + const answer = await session1.sendAndWait({ prompt: "What is 1+1?" }); + expect(answer?.data.content).toContain("2"); + + // Resume from a fresh client (new CLI process). Its routing table does + // not know the session until it handles `session.resume`. Because an MCP + // OAuth handler is configured, the SDK issues a session-scoped + // `session.eventLog.registerInterest` for `mcp.oauth_required`; that must + // be sent AFTER `session.resume`, otherwise the runtime rejects it with + // "Session not found: ". + const newClient = createClient({ + gitHubToken: isCI + ? DEFAULT_GITHUB_TOKEN + : (process.env.GITHUB_TOKEN ?? DEFAULT_GITHUB_TOKEN), + }); + onTestFinished(() => newClient.stop()); + + await using session2 = await newClient.resumeSession(sessionId, { + onPermissionRequest: approveAll, + onMcpAuthRequest: () => ({ kind: "cancelled" }), + }); + + expect(session2.sessionId).toBe(sessionId); + }); + it("should abort a session", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); // Set up event listeners BEFORE sending to avoid race conditions const nextToolCallStart = getNextEventOfType(session, "tool.execution_start"); @@ -496,7 +513,7 @@ describe("Sessions", async () => { // if the session weren't registered in the sessions map before the RPC, // the event would be dropped. const earlyEvents: Array<{ type: string }> = []; - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, onEvent: (event) => { earlyEvents.push(event); @@ -528,7 +545,7 @@ describe("Sessions", async () => { }); it("handler exception does not halt event delivery", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); let eventCount = 0; let gotIdle = false; @@ -553,12 +570,10 @@ describe("Sessions", async () => { // Handler saw more than just the first (throwing) event. expect(eventCount).toBeGreaterThan(1); - - await session.disconnect(); }); it("disposeAsync from handler does not deadlock", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); let disposed = false; const disposedPromise = new Promise((resolve) => { @@ -585,25 +600,21 @@ describe("Sessions", async () => { onTestFinished(async () => { await rm(customConfigDir, { recursive: true, force: true }).catch(() => {}); }); - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, configDirectory: customConfigDir, }); expect(session.sessionId).toMatch(/^[a-f0-9-]+$/); - try { - // Session should work normally with custom config dir - await session.send({ prompt: "What is 1+1?" }); - const assistantMessage = await getFinalAssistantMessage(session); - expect(assistantMessage.data.content).toContain("2"); - } finally { - await session.disconnect(); - } + // Session should work normally with custom config dir + await session.send({ prompt: "What is 1+1?" }); + const assistantMessage = await getFinalAssistantMessage(session); + expect(assistantMessage.data.content).toContain("2"); }); it("should log messages at all levels and emit matching session events", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); const events: Array<{ type: string; id?: string; data?: Record }> = []; session.on((event) => { @@ -658,7 +669,7 @@ describe("Sessions", async () => { const { writeFile } = await import("fs/promises"); await writeFile(filePath, "FILE_ATTACHMENT_SENTINEL"); - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); await session.sendAndWait({ prompt: "Read the attached file and reply with its contents.", @@ -692,8 +703,6 @@ describe("Sessions", async () => { expect(attachment.displayName).toBe("attached-file.txt"); expect(attachment.path).toBe(filePath); expect(attachment.lineRange).toEqual({ start: 1, end: 1 }); - - await session.disconnect(); }); it("should send with directory attachment", async () => { @@ -702,7 +711,7 @@ describe("Sessions", async () => { await mkdir(directoryPath, { recursive: true }); await writeFile(`${directoryPath}/readme.txt`, "DIRECTORY_ATTACHMENT_SENTINEL"); - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); await session.sendAndWait({ prompt: "List the attached directory.", @@ -725,8 +734,6 @@ describe("Sessions", async () => { expect(attachment.type).toBe("directory"); expect(attachment.displayName).toBe("attached-directory"); expect(attachment.path).toBe(directoryPath); - - await session.disconnect(); }); it("should send with selection attachment", async () => { @@ -734,7 +741,7 @@ describe("Sessions", async () => { const { writeFile } = await import("fs/promises"); await writeFile(filePath, 'class C { string Value = "SELECTION_SENTINEL"; }'); - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); await session.sendAndWait({ prompt: "Summarize the selected code.", @@ -774,8 +781,6 @@ describe("Sessions", async () => { expect(attachment.text).toBe('string Value = "SELECTION_SENTINEL";'); expect(attachment.selection.start).toEqual({ line: 1, character: 10 }); expect(attachment.selection.end).toEqual({ line: 1, character: 45 }); - - await session.disconnect(); }); it("should accept blob attachments", async () => { @@ -784,7 +789,7 @@ describe("Sessions", async () => { const { writeFile } = await import("fs/promises"); await writeFile(`${workDir}/test-pixel.png`, Buffer.from(pngBase64, "base64")); - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); await session.sendAndWait({ prompt: "Describe this image", @@ -797,12 +802,10 @@ describe("Sessions", async () => { }, ], }); - - await session.disconnect(); }); it("should send with github reference attachment", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); await session.sendAndWait({ prompt: "Using only the GitHub reference metadata in this message, summarize the reference. Do not call any tools.", @@ -842,12 +845,10 @@ describe("Sessions", async () => { expect(attachment.state).toBe("open"); expect(attachment.title).toBe("Add E2E attachment coverage"); expect(attachment.url).toBe("https://github.com/github/copilot-sdk/issues/1234"); - - await session.disconnect(); }); it("should send with mode property", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); await session.sendAndWait({ prompt: "Say mode ok.", @@ -861,12 +862,10 @@ describe("Sessions", async () => { expect(userMessage).toBeDefined(); expect(userMessage!.data.content).toBe("Say mode ok."); expect(userMessage!.data.agentMode).toBe("plan"); - - await session.disconnect(); }); it("should send with custom requestHeaders", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); await session.sendAndWait({ prompt: "What is 1+1?", @@ -885,8 +884,6 @@ describe("Sessions", async () => { const headerValue = headers[matchingKey!]; const headerStr = Array.isArray(headerValue) ? headerValue.join(",") : (headerValue ?? ""); expect(headerStr).toContain("ts-request-headers"); - - await session.disconnect(); }); }); @@ -899,10 +896,8 @@ function getSystemMessage(exchange: ParsedHttpExchange): string | undefined { describe("Send Blocking Behavior", async () => { // Tests for Issue #17: send() should return immediately, not block until turn completes - const { copilotClient: client } = await createSdkTestContext(); - it("send returns immediately while events stream in background", async () => { - const session = await client.createSession({ + await using session = await client.createSession({ onPermissionRequest: approveAll, }); @@ -926,7 +921,7 @@ describe("Send Blocking Behavior", async () => { }); it("sendAndWait blocks until session.idle and returns final assistant message", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); const events: string[] = []; session.on((event) => { @@ -945,16 +940,17 @@ describe("Send Blocking Behavior", async () => { // This test validates client-side timeout behavior. // The snapshot has no assistant response since we expect timeout before completion. it("sendAndWait throws on timeout", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); // Use a slow command to ensure timeout triggers before completion await expect( session.sendAndWait({ prompt: "Run 'sleep 2 && echo done'" }, 100) ).rejects.toThrow(/Timeout after 100ms/); + await session.abort(); }); it("should set model on existing session", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); // Subscribe for the model change event before calling setModel. const modelChangePromise = getNextEventOfType(session, "session.model_change"); @@ -964,12 +960,10 @@ describe("Send Blocking Behavior", async () => { // Verify a model_change event was emitted with the new model. const event = await modelChangePromise; expect(event.data.newModel).toBe("gpt-4.1"); - - await session.disconnect(); }); it("should set model with reasoningEffort", async () => { - const session = await client.createSession({ onPermissionRequest: approveAll }); + await using session = await client.createSession({ onPermissionRequest: approveAll }); const modelChangePromise = getNextEventOfType(session, "session.model_change"); diff --git a/nodejs/test/e2e/session_config.e2e.test.ts b/nodejs/test/e2e/session_config.e2e.test.ts index acb31f0588..98b1a0bfaa 100644 --- a/nodejs/test/e2e/session_config.e2e.test.ts +++ b/nodejs/test/e2e/session_config.e2e.test.ts @@ -1,12 +1,18 @@ import { describe, expect, it } from "vitest"; import { writeFile, mkdir } from "fs/promises"; import { join } from "path"; -import { approveAll } from "../../src/index.js"; -import { createSdkTestContext } from "./harness/sdkTestContext.js"; +import { + approveAll, + CopilotClient, + CopilotRequestHandler, + RuntimeConnection, + type CopilotRequestContext, +} from "../../src/index.js"; +import { createSdkTestContext, DEFAULT_GITHUB_TOKEN } from "./harness/sdkTestContext.js"; import { retry } from "./harness/sdkTestHelper.js"; describe("Session Configuration", async () => { - const { copilotClient: client, workDir, openAiEndpoint } = await createSdkTestContext(); + const { copilotClient: client, workDir, openAiEndpoint, env } = await createSdkTestContext(); async function waitForExchanges(minimumCount = 1) { await retry( @@ -216,6 +222,397 @@ describe("Session Configuration", async () => { return (exchange.request.tools ?? []).map((t) => t.function.name); } + async function sendAndGetNextExchange( + session: { sendAndWait(options: { prompt: string }): Promise }, + prompt: string + ) { + const existingCount = (await openAiEndpoint.getExchanges()).length; + await session.sendAndWait({ prompt }); + const exchanges = await waitForExchanges(existingCount + 1); + return exchanges[existingCount]; + } + + function assertSessionLimitsStatus( + exchange: { request: { messages?: Array<{ role: string; content: unknown }> } }, + expectedRemaining: string + ) { + const message = (exchange.request.messages ?? []).find( + (m) => + m.role === "user" && + typeof m.content === "string" && + m.content.includes("") + ); + expect(message?.content).toContain(`Remaining session limits: ${expectedRemaining}.`); + expect(message?.content).toContain( + "Be frugal; avoid optional exploration and unnecessary tool calls." + ); + } + + function getTaskAgentTypes(exchange: { + request: { + tools?: Array<{ + function: { name: string; parameters?: unknown }; + }>; + }; + }): string[] { + const taskTool = (exchange.request.tools ?? []).find( + (tool) => tool.function.name === "task" + ); + expect(taskTool).toBeDefined(); + const parameters = taskTool?.function.parameters as + | { properties?: { agent_type?: { enum?: string[] } } } + | undefined; + const values = parameters?.properties?.agent_type?.enum; + expect(values).toBeDefined(); + return values ?? []; + } + + interface InterceptedRequest { + url: string; + body: string; + } + + class RecordingRequestHandler extends CopilotRequestHandler { + readonly records: InterceptedRequest[] = []; + + protected override async sendRequest( + request: Request, + _ctx: CopilotRequestContext + ): Promise { + const body = request.body ? await request.text() : ""; + this.records.push({ url: request.url, body }); + return isInferenceUrl(request.url) + ? buildInferenceResponse(request.url, body) + : buildNonInferenceResponse(request.url); + } + + inferenceRequests(): InterceptedRequest[] { + return this.records.filter((record) => isInferenceUrl(record.url)); + } + } + + function isInferenceUrl(url: string): boolean { + const u = url.toLowerCase(); + return ( + u.endsWith("/chat/completions") || + u.endsWith("/responses") || + u.endsWith("/v1/messages") || + u.endsWith("/messages") + ); + } + + function json(body: unknown): Response { + return new Response(typeof body === "string" ? body : JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json" }, + }); + } + + function sse(body: string): Response { + return new Response(body, { + status: 200, + headers: { "content-type": "text/event-stream" }, + }); + } + + function anthropicMessageStreamBody(text: string): string { + const events: Array<[string, unknown]> = [ + [ + "message_start", + { + type: "message_start", + message: { + id: "msg_stub_1", + type: "message", + role: "assistant", + model: "claude-sonnet-4.5", + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 5, output_tokens: 1 }, + }, + }, + ], + [ + "content_block_start", + { + type: "content_block_start", + index: 0, + content_block: { type: "text", text: "" }, + }, + ], + [ + "content_block_delta", + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } }, + ], + ["content_block_stop", { type: "content_block_stop", index: 0 }], + [ + "message_delta", + { + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: 7 }, + }, + ], + ["message_stop", { type: "message_stop" }], + ]; + return events + .map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`) + .join(""); + } + + function buildNonInferenceResponse(url: string): Response { + const u = url.toLowerCase(); + if (u.endsWith("/models")) { + return json({ + data: [ + { + id: "claude-sonnet-4.5", + name: "Claude Sonnet 4.5", + object: "model", + vendor: "Anthropic", + version: "1", + preview: false, + model_picker_enabled: true, + capabilities: { + type: "chat", + family: "claude-sonnet-4.5", + tokenizer: "o200k_base", + limits: { max_context_window_tokens: 200000, max_output_tokens: 8192 }, + supports: { + streaming: true, + tool_calls: true, + parallel_tool_calls: true, + vision: true, + }, + }, + }, + ], + }); + } + if (u.includes("/models/session")) return json({}); + if (u.includes("/policy")) return json({ state: "enabled" }); + return json({}); + } + + function buildInferenceResponse(url: string, body: string): Response { + const u = url.toLowerCase(); + const wantsStream = /"stream"\s*:\s*true/.test(body); + if (u.endsWith("/messages")) { + if (wantsStream) { + return sse(anthropicMessageStreamBody("OK from the synthetic stream.")); + } + return json({ + id: "msg_stub_1", + type: "message", + role: "assistant", + model: "claude-sonnet-4.5", + content: [{ type: "text", text: "OK from the synthetic stream." }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: 5, output_tokens: 7 }, + }); + } + return json({ + id: "chatcmpl-stub-1", + object: "chat.completion", + created: 1, + model: "claude-sonnet-4.5", + choices: [ + { + index: 0, + message: { role: "assistant", content: "OK from the synthetic stream." }, + finish_reason: "stop", + }, + ], + usage: { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 }, + }); + } + + function createPdfAttachment() { + const pdfText = + "%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n"; + return { + type: "blob" as const, + data: Buffer.from(pdfText, "ascii").toString("base64"), + displayName: "citation-source.pdf", + mimeType: "application/pdf", + }; + } + + function createAnthropicProvider() { + return { + type: "anthropic" as const, + baseUrl: "https://anthropic-citations.invalid/v1", + apiKey: "test-provider-key", + modelId: "claude-sonnet-4.5", + wireModel: "claude-sonnet-4.5", + }; + } + + function assertAnthropicDocumentCitationsEnabled(requestBody: string) { + const body = JSON.parse(requestBody) as { + messages: Array<{ content: Array> }>; + }; + const documentBlocks = body.messages.flatMap((message) => + message.content.filter((block) => block.type === "document") + ); + expect(documentBlocks).toHaveLength(1); + expect(documentBlocks[0].title).toBe("citation-source.pdf"); + expect(documentBlocks[0].citations).toEqual({ enabled: true }); + } + + it("should apply session limits on create", async () => { + const session = await client.createSession({ + onPermissionRequest: approveAll, + sessionLimits: { maxAiCredits: 30 }, + }); + + const exchange = await sendAndGetNextExchange( + session, + "Acknowledge the current session limits." + ); + assertSessionLimitsStatus(exchange, "30 AI credits"); + + await session.disconnect(); + }); + + it("should apply session limits on resume", async () => { + const session1 = await client.createSession({ onPermissionRequest: approveAll }); + const session2 = await client.resumeSession(session1.sessionId, { + onPermissionRequest: approveAll, + sessionLimits: { maxAiCredits: 30 }, + }); + + const exchange = await sendAndGetNextExchange( + session2, + "Acknowledge the current session limits." + ); + assertSessionLimitsStatus(exchange, "30 AI credits"); + + await session2.disconnect(); + await session1.disconnect(); + }); + + it("should apply excluded built-in agents on create", async () => { + const excludedAgent = "explore"; + const prompt = "What is 1+1?"; + + const baselineSession = await client.createSession({ onPermissionRequest: approveAll }); + const baselineExchange = await sendAndGetNextExchange(baselineSession, prompt); + expect(getTaskAgentTypes(baselineExchange)).toContain(excludedAgent); + await baselineSession.disconnect(); + + const excludedSession = await client.createSession({ + onPermissionRequest: approveAll, + excludedBuiltinAgents: [excludedAgent], + }); + const excludedExchange = await sendAndGetNextExchange(excludedSession, prompt); + const agentTypes = getTaskAgentTypes(excludedExchange); + expect(agentTypes.length).toBeGreaterThan(0); + expect(agentTypes).not.toContain(excludedAgent); + + await excludedSession.disconnect(); + }); + + it("should apply excluded built-in agents on resume", async () => { + const excludedAgent = "explore"; + const session1 = await client.createSession({ onPermissionRequest: approveAll }); + const session2 = await client.resumeSession(session1.sessionId, { + onPermissionRequest: approveAll, + excludedBuiltinAgents: [excludedAgent], + }); + + const exchange = await sendAndGetNextExchange(session2, "What is 1+1?"); + const agentTypes = getTaskAgentTypes(exchange); + expect(agentTypes.length).toBeGreaterThan(0); + expect(agentTypes).not.toContain(excludedAgent); + + await session2.disconnect(); + await session1.disconnect(); + }); + + it("should enable citations for Anthropic file attachments on create", async () => { + const handler = new RecordingRequestHandler(); + const citationClient = new CopilotClient({ + connection: RuntimeConnection.forStdio({ path: process.env.COPILOT_CLI_PATH }), + workingDirectory: workDir, + env, + gitHubToken: DEFAULT_GITHUB_TOKEN, + requestHandler: handler, + }); + + await citationClient.start(); + try { + const session = await citationClient.createSession({ + onPermissionRequest: approveAll, + model: "claude-sonnet-4.5", + enableCitations: true, + provider: createAnthropicProvider(), + }); + try { + await session.sendAndWait({ + prompt: "Summarize the attached PDF with citations enabled.", + attachments: [createPdfAttachment()], + }); + expect(handler.inferenceRequests()).toHaveLength(1); + assertAnthropicDocumentCitationsEnabled(handler.inferenceRequests()[0].body); + } finally { + await session.disconnect(); + } + } finally { + await citationClient.stop(); + } + }); + + it("should enable citations for Anthropic file attachments on resume", async () => { + const handler = new RecordingRequestHandler(); + const connectionToken = "ts-citation-resume-token"; + const serverClient = new CopilotClient({ + connection: RuntimeConnection.forTcp({ + path: process.env.COPILOT_CLI_PATH, + connectionToken, + }), + workingDirectory: workDir, + env, + gitHubToken: DEFAULT_GITHUB_TOKEN, + requestHandler: handler, + }); + + await serverClient.start(); + try { + const session1 = await serverClient.createSession({ onPermissionRequest: approveAll }); + const port = (serverClient as unknown as { runtimePort: number | null }).runtimePort; + expect(port).not.toBeNull(); + const resumeClient = new CopilotClient({ + connection: RuntimeConnection.forUri(`localhost:${port}`, { connectionToken }), + }); + try { + const session2 = await resumeClient.resumeSession(session1.sessionId, { + onPermissionRequest: approveAll, + model: "claude-sonnet-4.5", + enableCitations: true, + provider: createAnthropicProvider(), + }); + try { + await session2.sendAndWait({ + prompt: "Summarize the attached PDF with citations enabled.", + attachments: [createPdfAttachment()], + }); + expect(handler.inferenceRequests()).toHaveLength(1); + assertAnthropicDocumentCitationsEnabled(handler.inferenceRequests()[0].body); + } finally { + await session2.disconnect(); + } + } finally { + await resumeClient.stop(); + await session1.disconnect(); + } + } finally { + await serverClient.stop(); + } + }); + it("should apply instructionDirectories on session create", async () => { const projectDir = join(workDir, "instruction-create-project"); const instructionDir = join(workDir, "extra-create-instructions"); diff --git a/nodejs/test/e2e/session_fs.e2e.test.ts b/nodejs/test/e2e/session_fs.e2e.test.ts index cba98996ef..11de9582e1 100644 --- a/nodejs/test/e2e/session_fs.e2e.test.ts +++ b/nodejs/test/e2e/session_fs.e2e.test.ts @@ -108,7 +108,7 @@ describe("Session Fs", async () => { connection: RuntimeConnection.forTcp({ connectionToken: tcpConnectionToken }), env, }); - onTestFinished(() => client.forceStop()); + onTestFinished(() => client.stop()); await client.createSession({ onPermissionRequest: approveAll, createSessionFsProvider }); const { runtimePort: port } = client as unknown as { runtimePort: number }; @@ -123,7 +123,7 @@ describe("Session Fs", async () => { }), sessionFs: sessionFsConfig, }); - onTestFinished(() => client2.forceStop()); + onTestFinished(() => client2.stop()); await expect(client2.start()).rejects.toThrow(); }); diff --git a/nodejs/test/e2e/streaming_fidelity.e2e.test.ts b/nodejs/test/e2e/streaming_fidelity.e2e.test.ts index 52f893469a..17b5222616 100644 --- a/nodejs/test/e2e/streaming_fidelity.e2e.test.ts +++ b/nodejs/test/e2e/streaming_fidelity.e2e.test.ts @@ -3,11 +3,11 @@ *--------------------------------------------------------------------------------------------*/ import { describe, expect, it, onTestFinished } from "vitest"; -import { CopilotClient, SessionEvent, approveAll } from "../../src/index.js"; +import { SessionEvent, approveAll } from "../../src/index.js"; import { createSdkTestContext, isCI } from "./harness/sdkTestContext"; describe("Streaming Fidelity", async () => { - const { copilotClient: client, env } = await createSdkTestContext(); + const { copilotClient: client, createClient } = await createSdkTestContext(); it("should produce delta events when streaming is enabled", async () => { const session = await client.createSession({ @@ -81,11 +81,10 @@ describe("Streaming Fidelity", async () => { await session.disconnect(); // Resume using a new client - const newClient = new CopilotClient({ - env, + const newClient = createClient({ gitHubToken: isCI ? "fake-token-for-e2e-tests" : process.env.GITHUB_TOKEN, }); - onTestFinished(() => newClient.forceStop()); + onTestFinished(() => newClient.stop()); const session2 = await newClient.resumeSession(session.sessionId, { onPermissionRequest: approveAll, streaming: true, @@ -120,11 +119,10 @@ describe("Streaming Fidelity", async () => { await session.disconnect(); // Resume using a new client with streaming DISABLED - const newClient = new CopilotClient({ - env, + const newClient = createClient({ gitHubToken: isCI ? "fake-token-for-e2e-tests" : process.env.GITHUB_TOKEN, }); - onTestFinished(() => newClient.forceStop()); + onTestFinished(() => newClient.stop()); const session2 = await newClient.resumeSession(session.sessionId, { onPermissionRequest: approveAll, streaming: false, diff --git a/nodejs/test/e2e/subagent_hooks.e2e.test.ts b/nodejs/test/e2e/subagent_hooks.e2e.test.ts index 0e6c2e95e0..dbc3ca673b 100644 --- a/nodejs/test/e2e/subagent_hooks.e2e.test.ts +++ b/nodejs/test/e2e/subagent_hooks.e2e.test.ts @@ -6,28 +6,82 @@ import { writeFile } from "fs/promises"; import { join } from "path"; import { describe, expect, it } from "vitest"; import type { + CopilotRequestContext, PreToolUseHookInput, PreToolUseHookOutput, PostToolUseHookInput, PostToolUseHookOutput, } from "../../src/index.js"; -import { approveAll } from "../../src/index.js"; +import { approveAll, CopilotRequestHandler } from "../../src/index.js"; import { createSdkTestContext, isCI } from "./harness/sdkTestContext.js"; +interface RequestRecord { + url: string; + agentId?: string; + parentAgentId?: string; + interactionType?: string; +} + +class RecordingRequestHandler extends CopilotRequestHandler { + readonly records: RequestRecord[] = []; + + protected override async sendRequest( + request: Request, + ctx: CopilotRequestContext + ): Promise { + this.records.push({ + url: request.url, + agentId: ctx.agentId, + parentAgentId: ctx.parentAgentId, + interactionType: ctx.interactionType, + }); + return super.sendRequest(request, ctx); + } +} + +function isInferenceUrl(url: string): boolean { + const u = url.toLowerCase(); + return ( + u.endsWith("/chat/completions") || + u.endsWith("/responses") || + u.endsWith("/v1/messages") || + u.endsWith("/messages") + ); +} + +function expectSubagentRequestMetadata(records: RequestRecord[]): void { + const inference = records.filter((r) => isInferenceUrl(r.url)); + expect(inference.length, "request handler should observe inference requests").toBeGreaterThan( + 0 + ); + + const subagentRequest = inference.find((r) => r.parentAgentId); + expect( + subagentRequest, + "sub-agent inference request should carry a parentAgentId" + ).toBeDefined(); + expect( + subagentRequest!.agentId, + "sub-agent inference request should carry an agentId" + ).toBeTruthy(); + expect( + subagentRequest!.interactionType, + "sub-agent inference request should carry an interactionType" + ).toBeTruthy(); + expect(subagentRequest!.parentAgentId).not.toBe(subagentRequest!.agentId); +} + describe("Subagent hooks", async () => { // For snapshot recording (non-CI), use RECORD_GH_TOKEN if available const recordToken = !isCI ? process.env.RECORD_GH_TOKEN : undefined; - const { - copilotClient: client, - workDir, - env, - } = await createSdkTestContext({ - ...(recordToken ? { copilotClientOptions: { gitHubToken: recordToken } } : {}), + const requestHandler = new RecordingRequestHandler(); + const { copilotClient: client, workDir } = await createSdkTestContext({ + copilotClientOptions: { + ...(recordToken ? { gitHubToken: recordToken } : {}), + requestHandler, + env: { COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS: "true" }, + }, }); - // Sub-agent hook propagation requires the session-based subagents feature flag. - // Without this flag, the legacy callback-bridge path is used, which does not - // support SDK preToolUse/postToolUse hooks for sub-agent tool calls. - env.COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS = "true"; it("should invoke preToolUse and postToolUse hooks for sub-agent tool calls", async () => { const hookLog: { kind: "pre" | "post"; toolName: string; sessionId: string }[] = []; @@ -80,6 +134,7 @@ describe("Subagent hooks", async () => { // input.sessionId distinguishes parent from sub-agent: parent tools and // sub-agent tools carry different sessionIds expect(viewPre[0].sessionId).not.toBe(taskPre!.sessionId); + expectSubagentRequestMetadata(requestHandler.records); await session.disconnect(); }, 120_000); diff --git a/nodejs/test/e2e/suspend.e2e.test.ts b/nodejs/test/e2e/suspend.e2e.test.ts index 79e8987260..2c8639ad38 100644 --- a/nodejs/test/e2e/suspend.e2e.test.ts +++ b/nodejs/test/e2e/suspend.e2e.test.ts @@ -4,8 +4,8 @@ import { describe, expect, it, onTestFinished } from "vitest"; import { z } from "zod"; -import { approveAll, CopilotClient, defineTool, RuntimeConnection } from "../../src/index.js"; import type { PermissionRequest, PermissionRequestResult, SessionEvent } from "../../src/index.js"; +import { approveAll, CopilotClient, defineTool, RuntimeConnection } from "../../src/index.js"; import { createSdkTestContext, DEFAULT_GITHUB_TOKEN } from "./harness/sdkTestContext.js"; const SUSPEND_TIMEOUT_MS = 60_000; @@ -47,10 +47,10 @@ async function waitWithTimeout( } } -function onTestFinishedForceStop(client: CopilotClient): void { +function onTestFinishedStop(client: CopilotClient): void { onTestFinished(async () => { try { - await client.forceStop(); + await client.stop(); } catch { // Ignore cleanup errors } @@ -71,7 +71,7 @@ describe("Suspend RPC", async () => { connectionToken: SHARED_TOKEN, }), }); - onTestFinishedForceStop(server); + onTestFinishedStop(server); return server; } @@ -79,7 +79,7 @@ describe("Suspend RPC", async () => { const connectedClient = new CopilotClient({ connection: RuntimeConnection.forUri(cliUrl, { connectionToken: SHARED_TOKEN }), }); - onTestFinishedForceStop(connectedClient); + onTestFinishedStop(connectedClient); return connectedClient; } diff --git a/nodejs/test/e2e/telemetry.e2e.test.ts b/nodejs/test/e2e/telemetry.e2e.test.ts index 9df6b7f88e..c0f71ebfc6 100644 --- a/nodejs/test/e2e/telemetry.e2e.test.ts +++ b/nodejs/test/e2e/telemetry.e2e.test.ts @@ -6,7 +6,7 @@ import { readFile } from "fs/promises"; import { join } from "path"; import { describe, expect, it } from "vitest"; import { z } from "zod"; -import { approveAll, defineTool } from "../../src/index.js"; +import { approveAll, defineTool, RuntimeConnection } from "../../src/index.js"; import { createSdkTestContext } from "./harness/sdkTestContext.js"; import { getFinalAssistantMessage } from "./harness/sdkTestHelper.js"; @@ -58,6 +58,12 @@ describe("Telemetry export", async () => { const { copilotClient: client, workDir } = await createSdkTestContext({ copilotClientOptions: { + // Telemetry is lowered to environment variables the native runtime reads, which + // the in-process transport cannot carry per-client (the runtime runs in the shared + // host process); see https://github.com/github/copilot-sdk/issues/1934. Pin the + // child-process (stdio) transport so this scenario is exercised even in the + // in-process CI cell, matching the .NET suite. + connection: RuntimeConnection.forStdio(), telemetry: { filePath: telemetryFileName, exporterType: "file", diff --git a/nodejs/test/e2e/ui_elicitation.e2e.test.ts b/nodejs/test/e2e/ui_elicitation.e2e.test.ts index 3bc9335a21..2e85dd5af2 100644 --- a/nodejs/test/e2e/ui_elicitation.e2e.test.ts +++ b/nodejs/test/e2e/ui_elicitation.e2e.test.ts @@ -5,7 +5,7 @@ import { afterAll, describe, expect, it } from "vitest"; import { CopilotClient, approveAll, RuntimeConnection } from "../../src/index.js"; import type { SessionEvent } from "../../src/index.js"; -import { createSdkTestContext } from "./harness/sdkTestContext.js"; +import { createSdkTestContext, isInProcessTransport } from "./harness/sdkTestContext.js"; describe("UI Elicitation", async () => { const { copilotClient: client } = await createSdkTestContext(); @@ -116,7 +116,7 @@ describe("UI Elicitation Multi-Client Capabilities", async () => { } ); - it( + it.skipIf(isInProcessTransport)( "capabilities.changed fires when elicitation provider disconnects", { timeout: 60_000 }, async () => { diff --git a/nodejs/test/session-event-codegen.test.ts b/nodejs/test/session-event-codegen.test.ts index 86c76f71bc..14340292be 100644 --- a/nodejs/test/session-event-codegen.test.ts +++ b/nodejs/test/session-event-codegen.test.ts @@ -209,6 +209,38 @@ describe("session event codegen", () => { ); }); + it("drops leading underscores from C# member names while preserving JSON names", () => { + const schema: JSONSchema7 = { + definitions: { + SessionEvent: { + anyOf: [ + { + type: "object", + required: ["type", "data"], + properties: { + type: { const: "session.synthetic" }, + data: { + type: "object", + required: ["_meta"], + properties: { + _meta: { type: "string" }, + }, + }, + }, + }, + ], + }, + }, + }; + + const csharpCode = generateCSharpSessionEventsCode(schema); + + expect(csharpCode).toContain( + '[JsonPropertyName("_meta")]\n public required string Meta { get; set; }' + ); + expect(csharpCode).not.toContain("public required string _meta"); + }); + it("collapses redundant callable wrapper lambdas", () => { const schema: JSONSchema7 = { definitions: { diff --git a/python/README.md b/python/README.md index 86f568bd7a..3089c36699 100644 --- a/python/README.md +++ b/python/README.md @@ -32,6 +32,17 @@ python -m copilot download-runtime This caches the runtime binary locally. If you skip this step, the SDK will attempt to download it automatically on first use as a fallback. +To pre-provision the native library required by the in-process (FFI) transport +(see [In-process (FFI) transport](#in-process-ffi-transport)), pass `--in-process`: + +```bash +python -m copilot download-runtime --in-process +``` + +This additionally fetches the native runtime library into the versioned runtime +cache. Stdio/TCP users never download it. When omitted, it is downloaded +lazily on first use of the in-process transport. + | Platform | Cache path | |----------|-----------| | Linux | `~/.cache/github-copilot-sdk/cli//copilot` | @@ -136,7 +147,7 @@ asyncio.run(main()) ## Features - ✅ Full JSON-RPC protocol support -- ✅ stdio and TCP transports +- ✅ stdio, TCP, and in-process (FFI) transports - ✅ Real-time streaming events - ✅ Session history with `get_events()` - ✅ Type hints throughout @@ -184,8 +195,9 @@ CopilotClient(connection=..., log_level="debug", github_token=..., ...) All options are kw-only parameters: - `connection` (RuntimeConnection | None): How to reach the runtime. Use - `RuntimeConnection.for_stdio(...)`, `RuntimeConnection.for_tcp(...)`, or - `RuntimeConnection.for_uri(...)`. Defaults to a stdio connection with the bundled binary. + `RuntimeConnection.for_stdio(...)`, `RuntimeConnection.for_tcp(...)`, + `RuntimeConnection.for_uri(...)`, or `RuntimeConnection.for_inprocess(...)`. + Defaults to a stdio connection with the bundled binary. - `working_directory` (str | None): Working directory for the CLI process (default: current dir). - `log_level` (str): Log level (default: "info"). - `env` (dict | None): Environment variables for the CLI process. @@ -204,6 +216,51 @@ All options are kw-only parameters: - `RuntimeConnection.for_stdio(path=None, args=None)` — spawn a local CLI process and talk over stdio. - `RuntimeConnection.for_tcp(port=0, connection_token=None, path=None, args=None)` — spawn a local CLI in TCP mode. - `RuntimeConnection.for_uri(url, connection_token=None)` — connect to an existing CLI server (e.g. `"localhost:8080"`). +- `RuntimeConnection.for_inprocess()` — host the runtime in-process via its native C ABI (FFI). See [In-process (FFI) transport](#in-process-ffi-transport). + +Child-process connections (`for_stdio`/`for_tcp`) also expose a per-connection +`env` field for the spawned process. Set it on the returned connection instead of +the client-level `env` — setting both raises: + +```python +conn = RuntimeConnection.for_stdio() +conn.env = {"MY_VAR": "value"} +client = CopilotClient(connection=conn) # do NOT also pass env=... here +``` + +### In-process (FFI) transport + +> ⚠️ **Experimental.** The in-process transport loads the runtime's native shared +> library into your process and drives JSON-RPC over its C ABI (via stdlib +> `ctypes`), instead of spawning a child process. + +```python +from copilot import CopilotClient, RuntimeConnection + +client = CopilotClient(connection=RuntimeConnection.for_inprocess()) +await client.start() +try: + pong = await client.ping("hello") + print(pong.message) +finally: + await client.stop() +``` + +**Requirements & behavior:** + +- Pre-provision the native runtime with + `python -m copilot download-runtime --in-process`, or let the SDK download it + lazily on first use of this transport. +- Set `COPILOT_CLI_PATH` only when using an externally provisioned compatible + runtime package. In-process connections do not accept per-connection paths + or raw process arguments. +- Because the runtime shares this single host process, per-client options that + lower to environment variables or a working directory **cannot** be honored and + are rejected: `env`, `telemetry`, and `working_directory` all raise `ValueError` + with `for_inprocess()`. Set the corresponding values on the host process + environment / working directory before creating the client instead. +- Set `COPILOT_SDK_DEFAULT_CONNECTION=inprocess` to select the in-process + transport by default when no explicit `connection` is supplied. **`CopilotClient.create_session()`:** diff --git a/python/copilot/__init__.py b/python/copilot/__init__.py index ff13d47de3..76f79b79f4 100644 --- a/python/copilot/__init__.py +++ b/python/copilot/__init__.py @@ -24,6 +24,7 @@ CanvasHostContext, CanvasHostContextCapabilities, CanvasJsonSchema, + CanvasProviderIdentity, ExtensionInfo, OpenCanvasInstance, ) @@ -35,6 +36,7 @@ CopilotClient, GetAuthStatusResponse, GetStatusResponse, + InProcessRuntimeConnection, LogLevel, ModelBilling, ModelCapabilities, @@ -74,6 +76,10 @@ LlmInferenceHeaders, ) from .generated.rpc import ( + CurrentToolMetadata, + GitHubTelemetryClientInfo, + GitHubTelemetryEvent, + GitHubTelemetryNotification, ModelBillingTokenPrices, ModelBillingTokenPricesLongContext, ) @@ -104,6 +110,13 @@ InfiniteSessionConfig, InputOptions, LargeToolOutputConfig, + McpAuthContext, + McpAuthHandler, + McpAuthRequest, + McpAuthResult, + McpAuthStaticClientConfig, + McpAuthToken, + McpAuthWwwAuthenticateParams, MCPHTTPServerConfig, MCPServerConfig, MCPStdioServerConfig, @@ -139,12 +152,14 @@ SessionFsCapabilities, SessionFsConfig, SessionHooks, + SessionLimitsConfig, SessionStartHandler, SessionStartHookInput, SessionStartHookOutput, SessionUiApi, SessionUiCapabilities, SystemMessageConfig, + ToolSearchConfig, UserInputHandler, UserInputRequest, UserInputResponse, @@ -189,6 +204,7 @@ "CanvasHostContext", "CanvasHostContextCapabilities", "CanvasJsonSchema", + "CanvasProviderIdentity", "CapiSessionOptions", "ChildProcessRuntimeConnection", "CloudSessionOptions", @@ -203,6 +219,7 @@ "CopilotWebSocketCloseStatus", "CopilotWebSocketHandler", "CreateSessionFsHandler", + "CurrentToolMetadata", "ElicitationContext", "ElicitationHandler", "ElicitationParams", @@ -218,7 +235,11 @@ "GetAuthStatusResponse", "BearerTokenProvider", "GetStatusResponse", + "GitHubTelemetryClientInfo", + "GitHubTelemetryEvent", + "GitHubTelemetryNotification", "InfiniteSessionConfig", + "InProcessRuntimeConnection", "InputOptions", "LargeToolOutputConfig", "LlmInferenceHeaders", @@ -226,6 +247,13 @@ "MCPHTTPServerConfig", "MCPServerConfig", "MCPStdioServerConfig", + "McpAuthContext", + "McpAuthHandler", + "McpAuthRequest", + "McpAuthResult", + "McpAuthStaticClientConfig", + "McpAuthToken", + "McpAuthWwwAuthenticateParams", "ModelBilling", "ModelBillingTokenPrices", "ModelBillingTokenPricesLongContext", @@ -285,6 +313,7 @@ "SessionFsSqliteProvider", "SessionFsSqliteQueryResult", "SessionHooks", + "SessionLimitsConfig", "SessionLifecycleEvent", "SessionLifecycleEventBase", "SessionLifecycleEventMetadata", @@ -308,6 +337,7 @@ "ToolInvocation", "ToolResult", "ToolResultType", + "ToolSearchConfig", "ToolSet", "UriRuntimeConnection", "UserInputHandler", diff --git a/python/copilot/_cli_download.py b/python/copilot/_cli_download.py index 1a5ebc9024..b831e072ad 100644 --- a/python/copilot/_cli_download.py +++ b/python/copilot/_cli_download.py @@ -16,6 +16,7 @@ from __future__ import annotations +import base64 import hashlib import io import os @@ -35,6 +36,9 @@ get_asset_info, get_checksums_url, get_download_url, + get_npm_platform, + get_runtime_lib_packument_url, + get_runtime_lib_url, ) _CACHE_DIR_NAME = "github-copilot-sdk" @@ -304,6 +308,153 @@ def download_cli(version: str | None = None, *, force: bool = False) -> str: return str(binary_path) +def _fetch_url_bytes(url: str, *, timeout: int) -> bytes: + """Download bytes from ``url`` with retries.""" + last_exc: Exception | None = None + for attempt in range(_MAX_RETRIES): + try: + with urlopen(url, timeout=timeout) as response: + return response.read() + except (HTTPError, URLError) as exc: + last_exc = exc + if attempt < _MAX_RETRIES - 1: + time.sleep(2**attempt) + raise RuntimeError(f"Failed to download from {url}: {last_exc}") from last_exc + + +def _fetch_runtime_integrity(npm_platform: str, version: str) -> str | None: + """Return the npm ``dist.integrity`` (Subresource Integrity) for the tarball. + + Best-effort: returns None if the packument can't be fetched or parsed. + """ + import json + + url = get_runtime_lib_packument_url(npm_platform) + try: + raw = _fetch_url_bytes(url, timeout=30) + packument = json.loads(raw) + dist = packument.get("versions", {}).get(version, {}).get("dist", {}) + integrity = dist.get("integrity") + return integrity if isinstance(integrity, str) else None + except (RuntimeError, ValueError, KeyError): + return None + + +def _verify_integrity(data: bytes, integrity: str) -> None: + """Verify data against an npm Subresource Integrity string (e.g. ``sha512-``).""" + algo, _, b64 = integrity.partition("-") + algo = algo.lower() + if algo not in ("sha512", "sha384", "sha256"): + # Fail closed: an unrecognized algorithm means we cannot verify this native + # library, so refuse rather than loading unverified native code. + raise RuntimeError( + f"Unsupported integrity algorithm '{algo}' for the in-process runtime " + "library; refusing to load unverified native code." + ) + expected = base64.b64decode(b64) + actual = hashlib.new(algo, data).digest() + if actual != expected: + raise RuntimeError( + f"Integrity mismatch for runtime library ({algo}): " + "downloaded tarball does not match the npm registry checksum." + ) + + +def _extract_runtime_node(data: bytes, npm_platform: str) -> bytes: + """Extract ``package/prebuilds//runtime.node`` from an npm tarball.""" + target = f"package/prebuilds/{npm_platform}/runtime.node" + with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tf: + for name in tf.getnames(): + if name == target or name.endswith(f"/prebuilds/{npm_platform}/runtime.node"): + member = tf.getmember(name) + extracted = tf.extractfile(member) + if extracted is not None: + return extracted.read() + raise RuntimeError(f"'{target}' not found in runtime package for {npm_platform}.") + + +def ensure_runtime_library(cli_path: str, version: str | None = None) -> str | None: + """Ensure the native in-process (FFI) runtime library sits next to ``cli_path``. + + The library is NOT part of the GitHub Releases CLI archive; it ships in the npm + platform package ``@github/copilot-`` under + ``package/prebuilds//runtime.node``. This helper downloads that tarball + and writes the library next to the CLI binary under its natural platform name + (``libcopilot_runtime.so`` / ``.dylib`` / ``copilot_runtime.dll``). + + This is opt-in — only invoked when the in-process transport is actually selected + (lazy) or via ``python -m copilot download-runtime --in-process`` (explicit). The + default stdio download path never fetches these extra bytes. + + Returns the absolute path to the library, or None if it could not be provisioned + (e.g. download disabled or unsupported platform). Raises RuntimeError on + download/verification failure. + """ + # Import lazily to avoid a hard dependency for stdio-only users. + from ._ffi_runtime_host import _natural_library_name, resolve_library_path + + # Already present (bundled prebuilds layout in dev, or a prior download)? + existing = resolve_library_path(cli_path) + if existing is not None: + return existing + + if _should_skip_download(): + return None + + ver = version or CLI_VERSION + if not ver: + return None + + try: + npm_platform = get_npm_platform() + except RuntimeError: + return None + + cli_dir = Path(cli_path).resolve().parent + lib_path = cli_dir / _natural_library_name() + if lib_path.exists(): + return str(lib_path) + + url = get_runtime_lib_url(ver, npm_platform) + data = _fetch_url_bytes(url, timeout=600) + + integrity = _fetch_runtime_integrity(npm_platform, ver) + if not integrity: + # Fail closed: this native library is loaded into the host process, so it must + # be verified before use. The npm packument (which carries dist.integrity) was + # unavailable, so refuse rather than loading unverified native code — mirroring + # the CLI download, which requires a checksum. Retry when the registry is + # reachable, or install a runtime package that ships the library. + raise RuntimeError( + "No Subresource Integrity value available for the in-process runtime " + f"library ({npm_platform}@{ver}); refusing to load unverified native code." + ) + _verify_integrity(data, integrity) + + lib_bytes = _extract_runtime_node(data, npm_platform) + + # Write atomically next to the CLI so concurrent starts don't observe a partial + # library. A rename within the same directory is atomic on POSIX and Windows. + cli_dir.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp(dir=cli_dir, prefix=".runtime-lib-") + try: + with os.fdopen(fd, "wb") as out: + out.write(lib_bytes) + os.replace(tmp_name, lib_path) + except OSError: + try: + os.unlink(tmp_name) + except OSError: + # Best-effort cleanup of the temp file; ignore if it's already gone or + # can't be removed (the OS reclaims it, and it doesn't affect correctness). + pass + if lib_path.exists(): + return str(lib_path) + raise + + return str(lib_path) + + def get_or_download_cli(version: str | None = None) -> str | None: """Get the cached CLI binary, downloading it if necessary. @@ -361,6 +512,15 @@ def main() -> None: "--version", help="Runtime version to download (default: pinned version)", ) + dl_parser.add_argument( + "--in-process", + action="store_true", + help=( + "Also download the native in-process (FFI) runtime library " + "(prebuilds//runtime.node) and place it next to the CLI. " + "Only needed for the experimental in-process transport." + ), + ) args = parser.parse_args() @@ -378,6 +538,17 @@ def main() -> None: try: path = download_cli(ver, force=args.force) print(f"Runtime cached at: {path}") + if args.in_process: + print("Downloading in-process (FFI) runtime library...") + lib_path = ensure_runtime_library(path, ver) + if lib_path: + print(f"Runtime library cached at: {lib_path}") + else: + print( + "Warning: could not provision the in-process runtime library " + "(download disabled or unsupported platform).", + file=sys.stderr, + ) except RuntimeError as exc: print(f"Error: {exc}", file=sys.stderr) sys.exit(1) diff --git a/python/copilot/_cli_version.py b/python/copilot/_cli_version.py index 4ff9cfb7af..cb5939820a 100644 --- a/python/copilot/_cli_version.py +++ b/python/copilot/_cli_version.py @@ -36,6 +36,31 @@ _DOWNLOAD_BASE_URL = "https://github.com/github/copilot-cli/releases/download" +# The native in-process (FFI) runtime library (`runtime.node`) is NOT part of the +# GitHub Releases `copilot-` archive (that ships only the CLI binary). It +# lives in the npm platform package `@github/copilot-`, under +# `package/prebuilds//runtime.node`. Mirrors the .NET SDK targets, +# which download the same npm tarball. +_NPM_REGISTRY_BASE_URL = "https://registry.npmjs.org" + +# Maps (sys.platform, platform.machine()) → npm platform name (glibc Linux/macOS/Windows). +NPM_PLATFORMS: dict[tuple[str, str], str] = { + ("linux", "x86_64"): "linux-x64", + ("linux", "aarch64"): "linux-arm64", + ("linux", "arm64"): "linux-arm64", + ("darwin", "x86_64"): "darwin-x64", + ("darwin", "arm64"): "darwin-arm64", + ("win32", "AMD64"): "win32-x64", + ("win32", "ARM64"): "win32-arm64", +} + +# Musl (Alpine) npm platform variants — detected at runtime via _is_musl(). +_MUSL_NPM_PLATFORMS: dict[str, str] = { + "x86_64": "linuxmusl-x64", + "aarch64": "linuxmusl-arm64", + "arm64": "linuxmusl-arm64", +} + def _is_musl() -> bool: """Detect whether the current Linux system uses musl libc (e.g. Alpine).""" @@ -93,3 +118,45 @@ def get_checksums_url(version: str) -> str: base = os.environ.get("COPILOT_CLI_DOWNLOAD_BASE_URL", _DOWNLOAD_BASE_URL) return f"{base}/v{version}/SHA256SUMS.txt" + + +def get_npm_platform() -> str: + """Return the npm platform name (e.g. ``linux-x64``) for the current host. + + Used to locate the native in-process runtime library. Raises RuntimeError if + the platform is not supported. + """ + key = get_platform_key() + + if key[0] == "linux" and _is_musl(): + musl = _MUSL_NPM_PLATFORMS.get(key[1]) + if musl: + return musl + + npm_platform = NPM_PLATFORMS.get(key) + if npm_platform is None: + raise RuntimeError( + f"Unsupported platform for in-process runtime: {key[0]}/{key[1]}. " + f"Supported platforms: {', '.join(f'{p}/{m}' for p, m in NPM_PLATFORMS)}" + ) + return npm_platform + + +def get_runtime_lib_packument_url(npm_platform: str) -> str: + """Return the npm packument URL for the platform runtime package.""" + import os + + base = os.environ.get("COPILOT_NPM_REGISTRY_URL", _NPM_REGISTRY_BASE_URL).rstrip("/") + return f"{base}/@github/copilot-{npm_platform}" + + +def get_runtime_lib_url(version: str, npm_platform: str) -> str: + """Return the download URL for the platform runtime tarball. + + Mirrors the .NET targets' URL layout + ``/@github/copilot-/-/copilot--.tgz``. + """ + import os + + base = os.environ.get("COPILOT_NPM_REGISTRY_URL", _NPM_REGISTRY_BASE_URL).rstrip("/") + return f"{base}/@github/copilot-{npm_platform}/-/copilot-{npm_platform}-{version}.tgz" diff --git a/python/copilot/_ffi_runtime_host.py b/python/copilot/_ffi_runtime_host.py new file mode 100644 index 0000000000..e04d1655e6 --- /dev/null +++ b/python/copilot/_ffi_runtime_host.py @@ -0,0 +1,514 @@ +"""In-process (FFI) hosting of the Copilot runtime. + +Instead of spawning the Copilot CLI as a child process and talking JSON-RPC over +stdio/TCP, the in-process transport loads the runtime's native shared library +(``runtime.node`` — a Rust ``cdylib``) into this process and drives JSON-RPC over +its C ABI (FFI). The native ``host_start`` export spawns the residual worker +itself, so the SDK never launches the worker directly; it only pumps opaque LSP +``Content-Length:``-framed JSON-RPC bytes across the boundary: + +- client → server frames go to ``copilot_runtime_connection_write`` +- server → client frames arrive on a native callback that feeds a thread-safe + receive buffer + +The existing :class:`~copilot._jsonrpc.JsonRpcClient` handles framing unchanged — +this is a transport swap, not a new protocol. The host exposes a *process-like* +adapter (``stdin``/``stdout``/``stderr``/``poll``) so ``JsonRpcClient`` can drive +it exactly like a :class:`subprocess.Popen`. + +The C ABI (shared with the .NET, Node.js, and Rust SDKs):: + + uint32 copilot_runtime_host_start(uint8 *argv, size_t argv_len, + uint8 *env, size_t env_len); + bool copilot_runtime_host_shutdown(uint32 server_id); + uint32 copilot_runtime_connection_open(uint32 server_id, outbound cb, + void *user_data, + uint8 *a, size_t a_len, + uint8 *b, size_t b_len, + uint8 *c, size_t c_len); + bool copilot_runtime_connection_write(uint32 conn_id, + uint8 *bytes, size_t len); + bool copilot_runtime_connection_close(uint32 conn_id); + // outbound callback: + void outbound(void *user_data, uint8 *bytes, size_t len); +""" + +from __future__ import annotations + +import ctypes +import json +import logging +import os +import sys +import threading +import time +from collections.abc import Sequence +from pathlib import Path + +logger = logging.getLogger("copilot.ffi") + +_SYMBOL_PREFIX = "copilot_runtime_" + +# The C ABI outbound callback: void(void *user_data, uint8 *bytes, size_t len). +_OutboundCallback = ctypes.CFUNCTYPE( + None, ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint8), ctypes.c_size_t +) + + +def get_prebuilds_folder() -> str | None: + """Return the ``prebuilds/`` folder name for the current host. + + Matches the napi-rs ``-`` layout the runtime package + ships (e.g. ``linux-x64``, ``darwin-arm64``, ``win32-x64``), including the + musl (Alpine) variants. Returns ``None`` for unsupported platforms. + """ + if sys.platform.startswith("linux"): + platform_name = "linuxmusl" if _is_musl() else "linux" + elif sys.platform == "darwin": + platform_name = "darwin" + elif sys.platform == "win32": + platform_name = "win32" + else: + return None + + machine = _normalize_machine() + if machine is None: + return None + return f"{platform_name}-{machine}" + + +def _normalize_machine() -> str | None: + import platform + + machine = platform.machine().lower() + if machine in ("x86_64", "amd64", "x64"): + return "x64" + if machine in ("arm64", "aarch64"): + return "arm64" + return None + + +def _is_musl() -> bool: + """Detect whether the current Linux system uses musl libc (e.g. Alpine).""" + if sys.platform != "linux": + return False + try: + import subprocess + + result = subprocess.run(["ldd", "--version"], capture_output=True, text=True, timeout=5) + return "musl" in (result.stdout + result.stderr).lower() + except (FileNotFoundError, OSError, Exception): # noqa: BLE001 + return False + + +def _natural_library_name() -> str: + """The natural platform shared-library file name for the runtime cdylib. + + The ``.node`` file renamed to what a Rust ``cdylib`` would be called on this + OS. The library is loaded by absolute path, so the on-disk name is ours. + """ + if sys.platform == "win32": + return "copilot_runtime.dll" + if sys.platform == "darwin": + return "libcopilot_runtime.dylib" + return "libcopilot_runtime.so" + + +def resolve_library_path(cli_entrypoint: str) -> str | None: + """Resolve the native runtime library next to the given CLI entrypoint. + + Checks, in order: + + 1. The natural platform library name next to the CLI (bundled/flat layout, + what the Python download-at-first-use path writes). + 2. ``prebuilds//runtime.node`` next to the CLI (dev/package layout). + + Returns the absolute path, or ``None`` when neither exists. + """ + directory = Path(cli_entrypoint).resolve().parent + + flat = directory / _natural_library_name() + if flat.is_file(): + return str(flat) + + folder = get_prebuilds_folder() + if folder is not None: + prebuilt = directory / "prebuilds" / folder / "runtime.node" + if prebuilt.is_file(): + return str(prebuilt) + + return None + + +# The cdylib may only be loaded once per process; a second load of a *different* +# path is unsupported (matches the Node/Rust hosts). Guard it here. +_loaded_library: ctypes.CDLL | None = None +_loaded_library_path: str | None = None +_load_lock = threading.Lock() + + +class _FfiLibrary: + """Binds the ``copilot_runtime_*`` C ABI exports of a loaded cdylib.""" + + def __init__(self, lib: ctypes.CDLL) -> None: + self._lib = lib + + self.host_start = getattr(lib, f"{_SYMBOL_PREFIX}host_start") + self.host_start.argtypes = [ + ctypes.c_char_p, + ctypes.c_size_t, + ctypes.c_char_p, + ctypes.c_size_t, + ] + self.host_start.restype = ctypes.c_uint32 + + self.host_shutdown = getattr(lib, f"{_SYMBOL_PREFIX}host_shutdown") + self.host_shutdown.argtypes = [ctypes.c_uint32] + self.host_shutdown.restype = ctypes.c_bool + + self.connection_open = getattr(lib, f"{_SYMBOL_PREFIX}connection_open") + self.connection_open.argtypes = [ + ctypes.c_uint32, + _OutboundCallback, + ctypes.c_void_p, + ctypes.c_char_p, + ctypes.c_size_t, + ctypes.c_char_p, + ctypes.c_size_t, + ctypes.c_char_p, + ctypes.c_size_t, + ] + self.connection_open.restype = ctypes.c_uint32 + + self.connection_write = getattr(lib, f"{_SYMBOL_PREFIX}connection_write") + self.connection_write.argtypes = [ + ctypes.c_uint32, + ctypes.c_char_p, + ctypes.c_size_t, + ] + self.connection_write.restype = ctypes.c_bool + + self.connection_close = getattr(lib, f"{_SYMBOL_PREFIX}connection_close") + self.connection_close.argtypes = [ctypes.c_uint32] + self.connection_close.restype = ctypes.c_bool + + +def _load_library(library_path: str) -> _FfiLibrary: + global _loaded_library, _loaded_library_path + with _load_lock: + if _loaded_library is not None: + if _loaded_library_path != library_path: + raise RuntimeError( + f"An in-process FFI runtime library is already loaded from " + f"'{_loaded_library_path}'; loading a different library from " + f"'{library_path}' in the same process is not supported." + ) + return _FfiLibrary(_loaded_library) + + # Load with immediate binding (RTLD_NOW) on POSIX, matching the .NET/Rust + # hosts. The runtime cdylib from the npm platform package is self-contained; + # eager binding surfaces any load problem here rather than at first call. + if sys.platform == "win32": + lib = ctypes.WinDLL(library_path) + else: + lib = ctypes.CDLL(library_path, mode=os.RTLD_NOW | os.RTLD_LOCAL) + _loaded_library = lib + _loaded_library_path = library_path + return _FfiLibrary(lib) + + +class _ReceiveBuffer: + """Thread-safe byte buffer feeding blocking ``read(n)`` from a producer thread. + + The native outbound callback (invoked on a foreign runtime thread) appends + frames via :meth:`feed` without ever blocking; the JSON-RPC reader thread + drains them via :meth:`read`, which blocks until data or EOF. + """ + + def __init__(self) -> None: + self._buffer = bytearray() + self._closed = False + self._cond = threading.Condition() + + def feed(self, data: bytes) -> None: + with self._cond: + if self._closed: + return + self._buffer.extend(data) + self._cond.notify_all() + + def close(self) -> None: + with self._cond: + self._closed = True + self._cond.notify_all() + + def read(self, size: int) -> bytes: + if size <= 0: + return b"" + with self._cond: + while not self._buffer and not self._closed: + self._cond.wait() + if not self._buffer: + return b"" # EOF + chunk = bytes(self._buffer[:size]) + del self._buffer[:size] + return chunk + + def readline(self) -> bytes: + """Read through the next ``\\n`` (inclusive), blocking until available. + + Returns whatever remains (possibly without a trailing newline) at EOF, or + ``b""`` if the buffer is empty and closed. Mirrors the blocking + ``BufferedReader.readline`` semantics :class:`JsonRpcClient` expects when + parsing LSP ``Content-Length:`` headers. + """ + with self._cond: + while b"\n" not in self._buffer and not self._closed: + self._cond.wait() + newline_index = self._buffer.find(b"\n") + if newline_index == -1: + # EOF with no newline: return the remaining bytes (may be empty). + line = bytes(self._buffer) + self._buffer.clear() + return line + end = newline_index + 1 + line = bytes(self._buffer[:end]) + del self._buffer[:end] + return line + + +class _FfiStdin: + """Writable side of the process-like adapter; forwards frames to the runtime.""" + + def __init__(self, host: FfiRuntimeHost) -> None: + self._host = host + + def write(self, data: bytes) -> int: + self._host._write_frame(data) + return len(data) + + def flush(self) -> None: + # connection_write enqueues synchronously, so there is nothing to flush. + pass + + +class _FfiProcessAdapter: + """A ``subprocess.Popen``-shaped view over an :class:`FfiRuntimeHost`. + + :class:`~copilot._jsonrpc.JsonRpcClient` only needs ``stdin`` (writable), + ``stdout`` (blocking ``read``), an optional ``stderr``, and ``poll()``. The + in-process transport has no OS pipes, so this adapter bridges those to the + FFI host's frame plumbing. + """ + + def __init__(self, host: FfiRuntimeHost) -> None: + self._host = host + self.stdin = _FfiStdin(host) + self.stdout = host._receive_buffer + # No separate error stream in-process; JsonRpcClient skips the stderr + # thread when this is falsy. + self.stderr = None + + def poll(self) -> int | None: + """Return ``None`` while the connection is live, ``0`` once closed.""" + return None if not self._host._disposed else 0 + + def terminate(self) -> None: + self._host.dispose() + + def kill(self) -> None: + self._host.dispose() + + def wait(self, timeout: float | None = None) -> int: # noqa: ARG002 + self._host.dispose() + return 0 + + +class FfiRuntimeHost: + """Hosts the Copilot runtime in-process via its native C ABI. + + Construct with :meth:`create`, then :meth:`start` to spawn the worker and open + the FFI connection. Expose :attr:`process` to :class:`JsonRpcClient`, and call + :meth:`dispose` to tear everything down. + """ + + def __init__( + self, + library_path: str, + cli_entrypoint: str, + environment: dict[str, str] | None = None, + args: Sequence[str] = (), + ) -> None: + self._library_path = library_path + self._cli_entrypoint = cli_entrypoint + self._environment = environment + self._extra_args = list(args) + self._lib = _load_library(library_path) + + self._server_id = 0 + self._connection_id = 0 + self._disposed = False + self._dispose_lock = threading.Lock() + + self._receive_buffer = _ReceiveBuffer() + # Keep a strong reference to the ctypes callback for its whole lifetime; + # dropping it while native code can still invoke it is a use-after-free. + self._outbound_callback: ctypes._FuncPointer | None = None + # Serializes teardown against in-flight native callbacks. + self._active_callbacks = 0 + self._callback_lock = threading.Lock() + + self._process = _FfiProcessAdapter(self) + + @property + def process(self) -> _FfiProcessAdapter: + """The ``subprocess.Popen``-shaped adapter for :class:`JsonRpcClient`.""" + return self._process + + @staticmethod + def create( + cli_entrypoint: str, + environment: dict[str, str] | None = None, + args: Sequence[str] = (), + ) -> FfiRuntimeHost: + """Resolve the cdylib next to the CLI entrypoint and prepare the host. + + Raises: + RuntimeError: If the native runtime library cannot be found. + """ + full_entrypoint = str(Path(cli_entrypoint).resolve()) + library_path = resolve_library_path(full_entrypoint) + if library_path is None: + raise RuntimeError( + "In-process FFI runtime library not found next to " + f"'{full_entrypoint}'. Download it with " + "`python -m copilot download-runtime --in-process`, or set " + "COPILOT_CLI_PATH to a runtime package that ships it." + ) + return FfiRuntimeHost(library_path, full_entrypoint, environment, args) + + def _build_argv(self) -> bytes: + # A `.js` entrypoint (dev) is launched via node; the packaged single-file + # CLI embeds its own Node and is invoked directly. `--no-auto-update` + # pins the worker to the runtime package matching the loaded cdylib. + if self._cli_entrypoint.lower().endswith(".js"): + argv = ["node", self._cli_entrypoint, "--embedded-host", "--no-auto-update"] + else: + argv = [self._cli_entrypoint, "--embedded-host", "--no-auto-update"] + argv.extend(self._extra_args) + return json.dumps(argv).encode("utf-8") + + def _build_env(self) -> bytes | None: + if not self._environment: + return None + obj = {k: v for k, v in self._environment.items() if v is not None} + if not obj: + return None + return json.dumps(obj).encode("utf-8") + + def start_blocking(self) -> None: + """Spawn the worker and open the FFI connection (blocks up to ~30s). + + Must be run off the event loop (e.g. via :func:`asyncio.to_thread`); + ``host_start`` blocks until the worker connects back and signals + readiness. + """ + argv = self._build_argv() + env = self._build_env() + + self._server_id = self._lib.host_start(argv, len(argv), env, len(env) if env else 0) + if not self._server_id: + raise RuntimeError( + f"copilot_runtime_host_start failed (library '{self._library_path}', " + f"entrypoint '{self._cli_entrypoint}')." + ) + + self._outbound_callback = _OutboundCallback(self._on_outbound) + self._connection_id = self._lib.connection_open( + self._server_id, + self._outbound_callback, + None, + None, + 0, + None, + 0, + None, + 0, + ) + if not self._connection_id: + self._outbound_callback = None + self._lib.host_shutdown(self._server_id) + self._server_id = 0 + raise RuntimeError("copilot_runtime_connection_open failed.") + + def _on_outbound( + self, + _user_data: int | None, + bytes_ptr: ctypes._Pointer, + bytes_len: int, + ) -> None: + """Native server → client callback (invoked on a foreign runtime thread). + + The native pointer is only valid for this call, so the bytes are copied + out before returning. Exceptions must not cross the FFI boundary, so + everything is caught and logged. + """ + with self._callback_lock: + if self._disposed: + return + self._active_callbacks += 1 + try: + if bytes_ptr and bytes_len > 0: + data = ctypes.string_at(bytes_ptr, bytes_len) + self._receive_buffer.feed(data) + except Exception: # noqa: BLE001 + logger.error("In-process FFI inbound callback failed", exc_info=True) + finally: + with self._callback_lock: + self._active_callbacks -= 1 + + def _write_frame(self, frame: bytes) -> None: + if self._disposed or not self._connection_id: + raise RuntimeError("The in-process runtime connection is closed.") + ok = self._lib.connection_write(self._connection_id, frame, len(frame)) + if not ok: + raise RuntimeError("Failed to write a frame to the in-process runtime connection.") + + def dispose(self) -> None: + """Close the FFI connection, shut down the native host, release resources. + + Idempotent. Waits for any in-flight outbound callback to finish before + dropping the callback reference to avoid a use-after-free. + """ + with self._dispose_lock: + if self._disposed: + return + self._disposed = True + + # Stop accepting new callbacks and wait for in-flight ones to drain. + with self._callback_lock: + pass # _disposed is set; new callbacks bail out immediately. + while True: + with self._callback_lock: + if self._active_callbacks == 0: + break + time.sleep(0.001) + + try: + if self._connection_id: + self._lib.connection_close(self._connection_id) + self._connection_id = 0 + except Exception: # noqa: BLE001 + logger.debug("Error closing in-process FFI connection", exc_info=True) + + try: + if self._server_id: + self._lib.host_shutdown(self._server_id) + self._server_id = 0 + except Exception: # noqa: BLE001 + logger.debug("Error shutting down in-process FFI host", exc_info=True) + + self._receive_buffer.close() + # Safe to drop now: no native code can invoke the callback after + # connection_close, and all in-flight callbacks have drained. + self._outbound_callback = None diff --git a/python/copilot/_jsonrpc.py b/python/copilot/_jsonrpc.py index a58908d08d..ed70e4e8d0 100644 --- a/python/copilot/_jsonrpc.py +++ b/python/copilot/_jsonrpc.py @@ -80,6 +80,7 @@ def __init__(self, process): self.pending_requests: dict[str, asyncio.Future] = {} self._pending_inline_callbacks: dict[str, Callable[[Any], None]] = {} self.notification_handler: Callable[[str, dict], None] | None = None + self.notification_method_handlers: dict[str, Callable[[dict], Any]] = {} self.request_handlers: dict[str, RequestHandler] = {} self._running = False self._read_thread: threading.Thread | None = None @@ -232,6 +233,19 @@ def set_notification_handler(self, handler: Callable[[str, dict], None]): """Set the handler for incoming notifications from the server.""" self.notification_handler = handler + def set_notification_method_handler(self, method: str, handler: Callable[[dict], Any] | None): + """Register a handler for a specific server-to-client notification method. + + Notifications carry no ``id`` and expect no response, so they are + dispatched separately from request handlers. A registered method + handler takes precedence over the generic notification handler. The + handler may be a coroutine function; its result is awaited. + """ + if handler is None: + self.notification_method_handlers.pop(method, None) + else: + self.notification_method_handlers[method] = handler + def set_request_handler(self, method: str, handler: RequestHandler): if handler is None: self.request_handlers.pop(method, None) @@ -397,9 +411,14 @@ def _handle_message(self, message: dict): # Check if it's a notification from the server if "method" in message and "id" not in message: + method = message["method"] + params = message.get("params", {}) + handler = self.notification_method_handlers.get(method) + if handler is not None and self._loop: + # Method-specific notification handler takes precedence. + self._loop.call_soon_threadsafe(self._dispatch_notification, handler, params) + return if self.notification_handler and self._loop: - method = message["method"] - params = message.get("params", {}) # Schedule notification handler on the event loop for thread safety self._loop.call_soon_threadsafe(self.notification_handler, method, params) return @@ -427,6 +446,25 @@ def _handle_request(self, message: dict): self._loop, ) + def _dispatch_notification(self, handler: Callable[[dict], Any], params: dict): + """Invoke a method-specific notification handler. Runs on the event loop; + coroutine results are scheduled and any error is logged (notifications + carry no response, so failures never propagate to the server).""" + try: + outcome = handler(params) + except Exception: # pylint: disable=broad-except + logger.warning("Notification handler raised", exc_info=True) + return + if inspect.isawaitable(outcome): + + async def _await_outcome(): + try: + await outcome + except Exception: # pylint: disable=broad-except + logger.warning("Notification handler raised", exc_info=True) + + asyncio.create_task(_await_outcome()) + async def _dispatch_request(self, message: dict, handler: RequestHandler): try: params = message.get("params", {}) diff --git a/python/copilot/canvas.py b/python/copilot/canvas.py index ddbc8539a2..9b8dec5258 100644 --- a/python/copilot/canvas.py +++ b/python/copilot/canvas.py @@ -39,6 +39,7 @@ "CanvasHostContext", "CanvasHostContextCapabilities", "CanvasJsonSchema", + "CanvasProviderIdentity", "ExtensionInfo", "OpenCanvasInstance", ] @@ -66,6 +67,33 @@ def to_dict(self) -> dict[str, Any]: return {"source": self.source, "name": self.name} +@dataclass +class CanvasProviderIdentity: + """Stable identity for a host/SDK connection that supplies built-in canvases. + + Lets a host advertise a stable canvas-provider extension id so host-provided + canvases restore across a cold session resume. Serializes to + ``{"id": ...}`` (with an optional ``"name"``) on the wire. + + .. note:: + + **Experimental.** This type is part of an experimental wire-protocol + surface and may change or be removed in future SDK or CLI releases. + """ + + id: str + """Stable provider identifier, e.g. ``"app:builtin:window-1"``.""" + + name: str | None = None + """Optional human-readable provider name.""" + + def to_dict(self) -> dict[str, Any]: + result: dict[str, Any] = {"id": self.id} + if self.name is not None: + result["name"] = self.name + return result + + @dataclass class CanvasDeclaration: """Declarative metadata for a single canvas, sent on create/resume. diff --git a/python/copilot/client.py b/python/copilot/client.py index c7d11d12b1..e6ac9b03e5 100644 --- a/python/copilot/client.py +++ b/python/copilot/client.py @@ -32,6 +32,7 @@ from typing import Any, ClassVar, Literal, TypedDict, cast, overload from ._diagnostics import log_timing +from ._ffi_runtime_host import FfiRuntimeHost from ._jsonrpc import JsonRpcClient, JsonRpcError, ProcessExitedError from ._mode import ( CopilotClientMode, @@ -58,19 +59,22 @@ from .canvas import ( CanvasDeclaration, CanvasHandler, + CanvasProviderIdentity, ExtensionInfo, ) from .copilot_request_handler import CopilotRequestHandler, create_copilot_request_adapter from .generated.rpc import ( ClientGlobalApiHandlers, ClientSessionApiHandlers, + GitHubTelemetryNotification, ModelBillingTokenPrices, ModelBillingTokenPricesLongContext, # noqa: F401 OpenCanvasInstance, RemoteSessionMode, ServerRpc, - _ConnectRequest, - _InternalServerRpc, + _ConnectResult, + _HookInvokeRequest, + _HookInvokeResponse, from_datetime, register_client_global_api_handlers, register_client_session_api_handlers, @@ -92,6 +96,7 @@ ExitPlanModeHandler, InfiniteSessionConfig, LargeToolOutputConfig, + McpAuthHandler, MCPServerConfig, MemoryConfiguration, ModelCapabilitiesOverride, @@ -103,7 +108,9 @@ SectionTransformFn, SessionFsConfig, SessionHooks, + SessionLimitsConfig, SystemMessageConfig, + ToolSearchConfig, UserInputHandler, _capabilities_to_dict, _PermissionHandlerFn, @@ -244,6 +251,24 @@ def _memory_to_wire(config: Mapping[str, Any]) -> dict[str, Any]: return {"enabled": config["enabled"]} +def _session_limits_to_wire(config: Mapping[str, Any]) -> dict[str, Any]: + """Convert a ``SessionLimitsConfig`` mapping to wire format.""" + wire: dict[str, Any] = {} + if "max_ai_credits" in config: + wire["maxAiCredits"] = config["max_ai_credits"] + return wire + + +def _tool_search_to_wire(config: Mapping[str, Any]) -> dict[str, Any]: + """Convert a ``ToolSearchConfig`` mapping to wire format.""" + wire: dict[str, Any] = {} + if "enabled" in config: + wire["enabled"] = config["enabled"] + if "defer_threshold" in config: + wire["deferThreshold"] = config["defer_threshold"] + return wire + + class TelemetryConfig(TypedDict, total=False): """Configuration for OpenTelemetry integration with the Copilot CLI.""" @@ -338,6 +363,33 @@ def for_uri(url: str, *, connection_token: str | None = None) -> UriRuntimeConne """ return UriRuntimeConnection(url=url, connection_token=connection_token) + @staticmethod + def for_inprocess() -> InProcessRuntimeConnection: + """Host the runtime **in-process** via its native C ABI (FFI). + + **Experimental.** The in-process (FFI) transport is experimental and its + behavior may change or be removed in a future release. + + Instead of spawning the runtime as a child process, the SDK loads the + runtime's native shared library into this process and drives JSON-RPC + over its C ABI. + + Because the runtime loads into this single shared process, per-client + options that lower to environment variables or a working directory + cannot be honored: :attr:`CopilotClientOptions.env`, + :attr:`CopilotClientOptions.telemetry`, and + :attr:`CopilotClientOptions.working_directory` are rejected with this + transport. Set those on the host process before creating the client. + Set ``COPILOT_CLI_PATH`` only when using an externally provisioned + compatible runtime package. + + Note: + Pre-provision the native runtime with + ``python -m copilot download-runtime --in-process`` when automatic + downloads are disabled. + """ + return InProcessRuntimeConnection() + @dataclass class ChildProcessRuntimeConnection(RuntimeConnection): @@ -352,6 +404,13 @@ class ChildProcessRuntimeConnection(RuntimeConnection): args: Sequence[str] = () """Extra command-line arguments passed to the runtime process.""" + env: dict[str, str] | None = None + """Per-connection environment variables for the spawned child process. + + When set, do not also set :attr:`CopilotClientOptions.env` — the client + rejects setting environment in both places. ``None`` inherits the + client-level env (or the current process env).""" + @dataclass class StdioRuntimeConnection(ChildProcessRuntimeConnection): @@ -389,6 +448,58 @@ class UriRuntimeConnection(RuntimeConnection): """Shared secret to authenticate the connection.""" +@dataclass +class InProcessRuntimeConnection(RuntimeConnection): + """Hosts the runtime in-process via its native C ABI (FFI). + + **Experimental.** The in-process (FFI) transport is experimental and its + behavior may change or be removed in a future release. + + Construct via :meth:`RuntimeConnection.for_inprocess`. The runtime's native + shared library is loaded into this process and JSON-RPC is driven over its + C ABI. + """ + + +class _GitHubTelemetryAdapter: + """Adapts a user-provided ``on_github_telemetry`` callback to the generated + ``GitHubTelemetryHandler`` protocol. + """ + + def __init__( + self, + callback: Callable[[GitHubTelemetryNotification], None | Awaitable[None]], + ) -> None: + self._callback = callback + + async def event(self, params: GitHubTelemetryNotification) -> None: + try: + result = self._callback(params) + if inspect.isawaitable(result): + await result + except Exception: + logger.warning("Error handling gitHubTelemetry.event notification", exc_info=True) + + +class _HooksAdapter: + """Adapts session-scoped hook dispatch to the generated ``HooksHandler`` protocol. + + ``hooks.invoke`` is a client-global RPC method whose payload carries a + ``sessionId``. This adapter routes each invocation to the matching session's + registered hook handlers. + """ + + def __init__(self, get_session: Callable[[str], CopilotSession | None]) -> None: + self._get_session = get_session + + async def invoke(self, params: _HookInvokeRequest) -> _HookInvokeResponse: + session = self._get_session(params.session_id) + if session is None: + raise ValueError(f"unknown session {params.session_id}") + output = await session._handle_hooks_invoke(params.hook_type.value, params.input) + return _HookInvokeResponse(output=output) + + @dataclass class _CopilotClientOptions: """Internal configuration carrier used by :class:`CopilotClient`. @@ -410,6 +521,9 @@ class _CopilotClientOptions: session_idle_timeout_seconds: int | None = None enable_remote_sessions: bool = False on_list_models: Callable[[], list[ModelInfo] | Awaitable[list[ModelInfo]]] | None = None + on_github_telemetry: Callable[[GitHubTelemetryNotification], None | Awaitable[None]] | None = ( + None + ) mode: CopilotClientMode = "copilot-cli" @@ -1003,15 +1117,23 @@ def _session_lifecycle_event_from_dict(data: dict) -> SessionLifecycleEvent: _CLI_PROCESS_EXIT_TIMEOUT_SECONDS = 5 -def _get_or_download_cli() -> str | None: +def _get_or_download_cli(*, include_runtime_lib: bool = False) -> str | None: """Get the cached CLI binary, downloading if necessary. Returns the path to the CLI binary, or None if unavailable (dev install with no pinned version, or auto-download disabled). + + When ``include_runtime_lib`` is set, also ensures the native in-process FFI + runtime is available (downloading it on first use). """ from ._cli_download import get_or_download_cli - return get_or_download_cli() + cli_path = get_or_download_cli() + if cli_path and include_runtime_lib: + from ._cli_download import ensure_runtime_library + + ensure_runtime_library(cli_path) + return cli_path def _extract_transform_callbacks( @@ -1049,6 +1171,78 @@ def _extract_transform_callbacks( return wire_payload, callbacks +_DEFAULT_CONNECTION_ENV_VAR = "COPILOT_SDK_DEFAULT_CONNECTION" + + +def _resolve_default_connection(env: Mapping[str, str]) -> RuntimeConnection: + """Resolve the transport when the caller supplies no explicit connection. + + Honors the ``COPILOT_SDK_DEFAULT_CONNECTION`` override (``"inprocess"`` or + ``"stdio"``); defaults to stdio. Matches the Node/.NET/Rust default-transport + override so the CI matrix can run the whole suite under either transport. + """ + value = env.get(_DEFAULT_CONNECTION_ENV_VAR) + if value is None or value == "": + return RuntimeConnection.for_stdio() + normalized = value.strip().lower() + if normalized == "inprocess": + return RuntimeConnection.for_inprocess() + if normalized == "stdio": + return RuntimeConnection.for_stdio() + raise ValueError( + f"Invalid {_DEFAULT_CONNECTION_ENV_VAR}={value!r}. Expected 'inprocess', 'stdio', or unset." + ) + + +def _validate_environment_options( + options: _CopilotClientOptions, connection: RuntimeConnection +) -> None: + """Validate env/telemetry/working-directory options against the transport. + + Per-client environment is only representable for child-process transports + (each client owns its own OS process). The in-process (FFI) transport loads + the native runtime into the shared host process, whose single environment + block and process-global working directory cannot carry per-client values, + so options that lower to them are rejected there (fail loud, not silent). + """ + if isinstance(connection, InProcessRuntimeConnection): + if options.env is not None: + raise ValueError( + "env is not supported with RuntimeConnection.for_inprocess(): the " + "in-process transport loads the native runtime into the shared host " + "process, whose single environment block cannot carry per-client " + "values. Set the variables on the host process environment instead." + ) + if options.telemetry is not None: + raise ValueError( + "telemetry is not supported with RuntimeConnection.for_inprocess(): " + "telemetry configuration is lowered to environment variables read by " + "native runtime code running in the shared host process, so per-client " + "telemetry cannot be honored in-process. Configure telemetry via the " + "host process environment, or use a child-process transport." + ) + if options.working_directory is not None: + raise ValueError( + "working_directory is not supported with RuntimeConnection.for_inprocess(): " + "the native runtime shares the host process working directory, so a " + "per-client working directory cannot be honored in-process. Use a " + "child-process " + "transport, or set the process working directory before creating the client." + ) + return + + if ( + isinstance(connection, ChildProcessRuntimeConnection) + and connection.env is not None + and options.env is not None + ): + raise ValueError( + "Set environment variables via either the client-level env argument or " + "ChildProcessRuntimeConnection.env, not both. Prefer the connection-level " + "env for child-process transports." + ) + + class CopilotClient: """ Main client for interacting with the Copilot CLI. @@ -1099,15 +1293,19 @@ def __init__( session_idle_timeout_seconds: int | None = None, enable_remote_sessions: bool = False, on_list_models: Callable[[], list[ModelInfo] | Awaitable[list[ModelInfo]]] | None = None, + on_github_telemetry: Callable[[GitHubTelemetryNotification], None | Awaitable[None]] + | None = None, mode: CopilotClientMode = "copilot-cli", ): """ Initialize a new CopilotClient. - All process-management options (``working_directory``, ``log_level``, - ``env``, ``github_token``, …) apply only when the SDK spawns the runtime - (stdio / tcp connections). They are ignored when connecting to an - existing runtime via :meth:`RuntimeConnection.for_uri`. + Runtime options apply to locally hosted connections. The in-process + transport supports typed runtime options such as ``log_level``, + ``github_token``, and ``base_directory``, but rejects per-client + ``working_directory``, ``env``, and ``telemetry``. Options are ignored + when connecting to an existing runtime via + :meth:`RuntimeConnection.for_uri`. Args: connection: How to reach the runtime. Defaults to @@ -1143,6 +1341,10 @@ def __init__( on_list_models: Custom handler for :meth:`list_models`. When provided, the handler is called instead of querying the runtime server. + on_github_telemetry: Internal. Callback invoked when the runtime + forwards a GitHub telemetry event for a session. The callback + may be sync or async. Registering a handler opts every session + opened by this client into telemetry forwarding. Example: >>> # Default — spawns runtime using stdio with the bundled binary @@ -1173,11 +1375,15 @@ def __init__( session_idle_timeout_seconds=session_idle_timeout_seconds, enable_remote_sessions=enable_remote_sessions, on_list_models=on_list_models, + on_github_telemetry=on_github_telemetry, mode=mode, ) connection = ( - options.connection if options.connection is not None else RuntimeConnection.for_stdio() + options.connection + if options.connection is not None + else _resolve_default_connection(os.environ) ) + _validate_environment_options(options, connection) _require_storage_for_empty_mode( mode=options.mode, base_directory=options.base_directory, @@ -1188,10 +1394,14 @@ def __init__( self._options: _CopilotClientOptions = options self._connection: RuntimeConnection = connection self._on_list_models = options.on_list_models + self._on_github_telemetry = options.on_github_telemetry # Resolve connection-mode-specific state. self._actual_host: str = "localhost" self._is_external_server: bool = isinstance(connection, UriRuntimeConnection) + self._cli_path_source: str | None = None + self._ffi_host: FfiRuntimeHost | None = None + self._inprocess_runtime_path: str | None = None if isinstance(connection, UriRuntimeConnection): if connection.connection_token is not None and len(connection.connection_token) == 0: @@ -1199,6 +1409,15 @@ def __init__( self._actual_host, actual_port = self._parse_cli_url(connection.url) self._runtime_port: int | None = actual_port self._effective_connection_token: str | None = connection.connection_token + elif isinstance(connection, InProcessRuntimeConnection): + # In-process (FFI): no child process and no per-connection token. + self._runtime_port = None + self._effective_connection_token = None + self._inprocess_runtime_path = self._resolve_runtime_entrypoint( + None, include_runtime_lib=True + ) + if options.use_logged_in_user is None: + options.use_logged_in_user = not bool(options.github_token) else: assert isinstance(connection, ChildProcessRuntimeConnection) self._runtime_port = None @@ -1218,26 +1437,17 @@ def __init__( self._effective_connection_token = None # Resolve CLI path: explicit > COPILOT_CLI_PATH env var > downloaded binary. - effective_env = options.env if options.env is not None else os.environ - self._cli_path_source: str | None = "explicit" - if connection.path is None: - env_cli_path = effective_env.get("COPILOT_CLI_PATH") - if env_cli_path: - connection.path = env_cli_path - self._cli_path_source = "environment" - else: - downloaded_path = _get_or_download_cli() - if downloaded_path: - connection.path = downloaded_path - self._cli_path_source = "downloaded" - else: - raise RuntimeError( - "Copilot CLI not found. Install a published wheel (which " - "auto-downloads the CLI on first use), set COPILOT_CLI_PATH, " - "or pass an explicit path via " - "RuntimeConnection.for_stdio(path=...) / " - "RuntimeConnection.for_tcp(path=...)." - ) + # Select the environment by identity, not truthiness, so an intentionally + # empty per-connection or client env stays authoritative (the spawned child + # receives that empty mapping) instead of falling back to os.environ and + # unexpectedly honoring a host COPILOT_CLI_PATH. + if connection.env is not None: + effective_env: Mapping[str, str] = connection.env + elif options.env is not None: + effective_env = options.env + else: + effective_env = os.environ + connection.path = self._resolve_runtime_entrypoint(connection.path, env=effective_env) # Resolve use_logged_in_user default if options.use_logged_in_user is None: @@ -1263,6 +1473,58 @@ def __init__( self._session_fs_config = options.session_fs self._request_handler = options.request_handler + def _resolve_runtime_entrypoint( + self, + path: str | None, + *, + env: Mapping[str, str] | None = None, + include_runtime_lib: bool = False, + ) -> str: + """Resolve the runtime executable path (explicit > env > downloaded). + + Sets ``self._cli_path_source`` for diagnostics. When + ``include_runtime_lib`` is set (in-process transport), also ensures the + native runtime library is downloaded alongside the CLI. + + Raises: + RuntimeError: If no runtime path can be resolved. + """ + if path is not None: + self._cli_path_source = "explicit" + return self._ensure_runtime_lib(path) if include_runtime_lib else path + + lookup = env if env is not None else os.environ + env_cli_path = lookup.get("COPILOT_CLI_PATH") + if env_cli_path: + self._cli_path_source = "environment" + return self._ensure_runtime_lib(env_cli_path) if include_runtime_lib else env_cli_path + + downloaded_path = _get_or_download_cli(include_runtime_lib=include_runtime_lib) + if downloaded_path: + self._cli_path_source = "downloaded" + return downloaded_path + + raise RuntimeError( + "Copilot CLI not found. Install a published wheel (which " + "auto-downloads the CLI on first use), set COPILOT_CLI_PATH, " + "or pass an explicit path via " + "RuntimeConnection.for_stdio(path=...) / " + "RuntimeConnection.for_tcp(path=...)." + ) + + @staticmethod + def _ensure_runtime_lib(cli_path: str) -> str: + """Ensure the in-process runtime library sits next to a user-supplied CLI. + + For explicit/``COPILOT_CLI_PATH`` entrypoints, the native library may + already be bundled (dev ``prebuilds`` layout); otherwise it is fetched on + first use. Returns ``cli_path`` unchanged. + """ + from ._cli_download import ensure_runtime_library + + ensure_runtime_library(cli_path) + return cli_path + @property def rpc(self) -> ServerRpc: """Typed server-scoped RPC methods.""" @@ -1501,7 +1763,11 @@ async def stop(self) -> None: StopError(message=f"Failed to disconnect session {session.session_id}: {e}") ) - if self._rpc is not None and self._cli_process is not None and not self._is_external_server: + if ( + self._rpc is not None + and (self._cli_process is not None or self._ffi_host is not None) + and not self._is_external_server + ): runtime_shutdown_start = time.perf_counter() try: await self._rpc.runtime.shutdown(timeout=_RUNTIME_SHUTDOWN_TIMEOUT_SECONDS) @@ -1531,6 +1797,15 @@ async def stop(self) -> None: async with self._models_cache_lock: self._models_cache = None + # Dispose the in-process FFI host and release the loaded native library. + if self._ffi_host is not None: + try: + self._ffi_host.dispose() + except Exception: + logger.debug("Error while disposing in-process FFI host", exc_info=True) + self._ffi_host = None + self._process = None + # Close TCP socket wrappers without treating them as owned processes. if self._process is not None and self._process is not self._cli_process: try: @@ -1624,6 +1899,15 @@ async def force_stop(self) -> None: except Exception: logger.debug("Error while force-stopping Copilot CLI process", exc_info=True) + # Force-dispose the in-process FFI host before tearing down JSON-RPC. + if self._ffi_host is not None: + try: + self._ffi_host.dispose() + except Exception: + logger.debug("Error while force-disposing in-process FFI host", exc_info=True) + self._ffi_host = None + self._process = None + # Then clean up the JSON-RPC client if self._client: try: @@ -1655,6 +1939,7 @@ async def create_session( context_tier: ContextTier | None = None, tools: list[Tool] | None = None, system_message: SystemMessageConfig | None = None, + tool_search: ToolSearchConfig | None = None, available_tools: list[str] | ToolSet | None = None, excluded_tools: list[str] | ToolSet | None = None, on_user_input_request: UserInputHandler | None = None, @@ -1665,6 +1950,9 @@ async def create_session( providers: list[NamedProviderConfig] | None = None, models: list[ProviderModelConfig] | None = None, enable_session_telemetry: bool | None = None, + enable_citations: bool | None = None, + excluded_builtin_agents: list[str] | None = None, + session_limits: SessionLimitsConfig | None = None, skip_custom_instructions: bool | None = None, custom_agents_local_only: bool | None = None, coauthor_enabled: bool | None = None, @@ -1697,6 +1985,7 @@ async def create_session( on_event: Callable[[SessionEvent], None] | None = None, commands: list[CommandDefinition] | None = None, on_elicitation_request: ElicitationHandler | None = None, + on_mcp_auth_request: McpAuthHandler | None = None, enable_mcp_apps: bool = False, on_exit_plan_mode_request: ExitPlanModeHandler | None = None, on_auto_mode_switch_request: AutoModeSwitchHandler | None = None, @@ -1709,8 +1998,10 @@ async def create_session( request_extensions: bool | None = None, extension_sdk_path: str | None = None, extension_info: ExtensionInfo | None = None, + canvas_provider: CanvasProviderIdentity | None = None, canvas_handler: CanvasHandler | None = None, exp_assignments: dict[str, Any] | None = None, + enable_managed_settings: bool | None = None, ) -> CopilotSession: """ Create a new conversation session with the Copilot CLI. @@ -1768,6 +2059,14 @@ async def create_session( a custom provider (BYOK) is configured, session telemetry is always disabled regardless of this setting. This is independent of the client OpenTelemetry configuration. + enable_citations: **Experimental.** Enables native model citations for + supported providers. + excluded_builtin_agents: Built-in agent names to exclude from the + session. Excluded built-in agents are hidden from discovery and + cannot be selected or invoked unless a custom agent with the same + name is configured. + session_limits: **Experimental.** Limits applied to this session's + current accounting window. model_capabilities: Override individual model capabilities resolved by the runtime. streaming: Whether to enable streaming responses. include_sub_agent_streaming_events: Whether to include sub-agent streaming @@ -1834,6 +2133,13 @@ async def create_session( malformed payloads are dropped by the runtime (fail-open). This is an internal/trusted-integrator option. Sent on the wire as ``expAssignments``. + enable_managed_settings: Opt-in flag. When ``True``, the runtime + self-fetches enterprise managed settings (bypass-permissions + policy) at session bootstrap using the session's ``github_token``. + Requires ``github_token`` to be set; if omitted, the runtime is + expected to reject session creation (fail-closed). When unset, + behaves exactly as before. Sent on the wire as + ``enableManagedSettings``. Returns: A :class:`CopilotSession` instance for the new session. @@ -1873,6 +2179,8 @@ async def create_session( definition["skipPermission"] = True if tool.defer is not None: definition["defer"] = tool.defer + if tool.metadata is not None: + definition["metadata"] = tool.metadata tool_defs.append(definition) # Empty-mode validation and normalization @@ -1917,6 +2225,9 @@ async def create_session( if wire_system_message: payload["systemMessage"] = wire_system_message + if tool_search is not None: + payload["toolSearch"] = _tool_search_to_wire(tool_search) + if available_tools is not None: payload["availableTools"] = available_tools if excluded_tools is not None: @@ -1965,6 +2276,10 @@ async def create_session( if exp_assignments is not None: payload["expAssignments"] = exp_assignments + # Opt the runtime into self-fetching enterprise managed settings + if enable_managed_settings is not None: + payload["enableManagedSettings"] = enable_managed_settings + # Add working directory if provided if working_directory: payload["workingDirectory"] = working_directory @@ -1980,6 +2295,11 @@ async def create_session( else True ) + # Opt this connection into gitHubTelemetry.event notifications when a + # telemetry handler was registered on the client. + if self._on_github_telemetry is not None: + payload["enableGitHubTelemetryForwarding"] = True + # Add provider configuration if provided if provider: payload["provider"] = self._convert_provider_to_wire_format(provider) @@ -1996,6 +2316,12 @@ async def create_session( if enable_session_telemetry is not None: payload["enableSessionTelemetry"] = enable_session_telemetry + if enable_citations is not None: + payload["enableCitations"] = enable_citations + if excluded_builtin_agents is not None: + payload["excludedBuiltinAgents"] = excluded_builtin_agents + if session_limits is not None: + payload["sessionLimits"] = _session_limits_to_wire(session_limits) # Add model capabilities override if provided if model_capabilities: @@ -2096,6 +2422,8 @@ async def create_session( payload["extensionSdkPath"] = extension_sdk_path if extension_info is not None: payload["extensionInfo"] = extension_info.to_dict() + if canvas_provider is not None: + payload["canvasProvider"] = canvas_provider.to_dict() if not self._client: raise RuntimeError("Client not connected") @@ -2149,6 +2477,7 @@ def _initialize_session(sid: str) -> CopilotSession: s._register_tools(tools) s._register_commands(commands) s._register_permission_handler(on_permission_request) + s._register_mcp_auth_handler(on_mcp_auth_request) if on_user_input_request: s._register_user_input_handler(on_user_input_request) if on_elicitation_request: @@ -2229,6 +2558,11 @@ def _register_inline(raw_response: Any) -> None: f"session.create returned sessionId {response.get('sessionId')} " f"but the caller requested {local_session_id}" ) + if on_mcp_auth_request is not None: + await self._client.request( + "session.eventLog.registerInterest", + {"sessionId": session.session_id, "eventType": "mcp.oauth_required"}, + ) session._workspace_path = response.get("workspacePath") capabilities = response.get("capabilities") session._set_capabilities(capabilities) @@ -2277,6 +2611,7 @@ async def resume_session( context_tier: ContextTier | None = None, tools: list[Tool] | None = None, system_message: SystemMessageConfig | None = None, + tool_search: ToolSearchConfig | None = None, available_tools: list[str] | ToolSet | None = None, excluded_tools: list[str] | ToolSet | None = None, on_user_input_request: UserInputHandler | None = None, @@ -2287,6 +2622,9 @@ async def resume_session( providers: list[NamedProviderConfig] | None = None, models: list[ProviderModelConfig] | None = None, enable_session_telemetry: bool | None = None, + enable_citations: bool | None = None, + excluded_builtin_agents: list[str] | None = None, + session_limits: SessionLimitsConfig | None = None, skip_custom_instructions: bool | None = None, custom_agents_local_only: bool | None = None, coauthor_enabled: bool | None = None, @@ -2319,6 +2657,7 @@ async def resume_session( on_event: Callable[[SessionEvent], None] | None = None, commands: list[CommandDefinition] | None = None, on_elicitation_request: ElicitationHandler | None = None, + on_mcp_auth_request: McpAuthHandler | None = None, enable_mcp_apps: bool = False, on_exit_plan_mode_request: ExitPlanModeHandler | None = None, on_auto_mode_switch_request: AutoModeSwitchHandler | None = None, @@ -2331,9 +2670,11 @@ async def resume_session( request_extensions: bool | None = None, extension_sdk_path: str | None = None, extension_info: ExtensionInfo | None = None, + canvas_provider: CanvasProviderIdentity | None = None, canvas_handler: CanvasHandler | None = None, open_canvases: list[OpenCanvasInstance] | None = None, exp_assignments: dict[str, Any] | None = None, + enable_managed_settings: bool | None = None, ) -> CopilotSession: """ Resume an existing conversation session by its ID. @@ -2391,6 +2732,14 @@ async def resume_session( a custom provider (BYOK) is configured, session telemetry is always disabled regardless of this setting. This is independent of the client OpenTelemetry configuration. + enable_citations: **Experimental.** Enables native model citations for + supported providers. + excluded_builtin_agents: Built-in agent names to exclude from the + resumed session. Excluded built-in agents are hidden from discovery + and cannot be selected or invoked unless a custom agent with the + same name is configured. + session_limits: **Experimental.** Limits applied to this session's + current accounting window. model_capabilities: Override individual model capabilities resolved by the runtime. streaming: Whether to enable streaming responses. include_sub_agent_streaming_events: Whether to include sub-agent streaming @@ -2458,6 +2807,13 @@ async def resume_session( malformed payloads are dropped by the runtime (fail-open). This is an internal/trusted-integrator option. Sent on the wire as ``expAssignments``. + enable_managed_settings: Opt-in flag. When ``True``, the runtime + self-fetches enterprise managed settings (bypass-permissions + policy) at session bootstrap using the session's ``github_token``. + Requires ``github_token`` to be set; if omitted, the runtime is + expected to reject session creation (fail-closed). When unset, + behaves exactly as before. Sent on the wire as + ``enableManagedSettings``. Returns: A :class:`CopilotSession` instance for the resumed session. @@ -2499,6 +2855,8 @@ async def resume_session( definition["skipPermission"] = True if tool.defer is not None: definition["defer"] = tool.defer + if tool.metadata is not None: + definition["metadata"] = tool.metadata tool_defs.append(definition) # Empty-mode validation and normalization @@ -2539,6 +2897,8 @@ async def resume_session( wire_system_message, transform_callbacks = _extract_transform_callbacks(system_message) if wire_system_message: payload["systemMessage"] = wire_system_message + if tool_search is not None: + payload["toolSearch"] = _tool_search_to_wire(tool_search) if available_tools is not None: payload["availableTools"] = available_tools if excluded_tools is not None: @@ -2556,6 +2916,12 @@ async def resume_session( payload["models"] = [self._convert_model_to_wire_format(m) for m in models] if enable_session_telemetry is not None: payload["enableSessionTelemetry"] = enable_session_telemetry + if enable_citations is not None: + payload["enableCitations"] = enable_citations + if excluded_builtin_agents is not None: + payload["excludedBuiltinAgents"] = excluded_builtin_agents + if session_limits is not None: + payload["sessionLimits"] = _session_limits_to_wire(session_limits) if model_capabilities: payload["modelCapabilities"] = _capabilities_to_dict(model_capabilities) if streaming is not None: @@ -2568,6 +2934,11 @@ async def resume_session( else True ) + # Opt this connection into gitHubTelemetry.event notifications when a + # telemetry handler was registered on the client. + if self._on_github_telemetry is not None: + payload["enableGitHubTelemetryForwarding"] = True + # Enable permission request callback if handler provided payload["requestPermission"] = bool(on_permission_request) @@ -2602,6 +2973,10 @@ async def resume_session( if exp_assignments is not None: payload["expAssignments"] = exp_assignments + # Opt the runtime into self-fetching enterprise managed settings + if enable_managed_settings is not None: + payload["enableManagedSettings"] = enable_managed_settings + if working_directory: payload["workingDirectory"] = working_directory if config_directory: @@ -2690,6 +3065,8 @@ async def resume_session( payload["extensionSdkPath"] = extension_sdk_path if extension_info is not None: payload["extensionInfo"] = extension_info.to_dict() + if canvas_provider is not None: + payload["canvasProvider"] = canvas_provider.to_dict() if not self._client: raise RuntimeError("Client not connected") @@ -2723,6 +3100,7 @@ async def resume_session( session._register_tools(tools) session._register_commands(commands) session._register_permission_handler(on_permission_request) + session._register_mcp_auth_handler(on_mcp_auth_request) if on_user_input_request: session._register_user_input_handler(on_user_input_request) if on_elicitation_request: @@ -2773,6 +3151,11 @@ async def resume_session( session._set_open_canvases( [OpenCanvasInstance.from_dict(inst) for inst in open_canvases_raw] ) + if on_mcp_auth_request is not None: + await self._client.request( + "session.eventLog.registerInterest", + {"sessionId": session.session_id, "eventType": "mcp.oauth_required"}, + ) except BaseException as exc: with self._sessions_lock: self._sessions.pop(session_id, None) @@ -3203,8 +3586,17 @@ async def _verify_protocol_version(self) -> None: server_version: int | None try: - connect_result = await _InternalServerRpc(self._client)._connect( - _ConnectRequest(token=self._effective_connection_token) + connect_params: dict[str, Any] = {} + if self._effective_connection_token is not None: + connect_params["token"] = self._effective_connection_token + # Opt in to GitHub telemetry forwarding at the connection level when a + # handler is registered (mirrors the runtime, which reads this flag on the + # `connect` handshake so the first session's un-replayable `session.start` + # event is forwarded). Also sent on session.create/resume for older CLIs. + if self._on_github_telemetry is not None: + connect_params["enableGitHubTelemetryForwarding"] = True + connect_result = _ConnectResult.from_dict( + await self._client.request("connect", connect_params) ) server_version = connect_result.protocol_version except JsonRpcError as err: @@ -3369,6 +3761,8 @@ def _convert_custom_agent_to_wire_format( wire_agent["skills"] = agent["skills"] if "model" in agent: wire_agent["model"] = agent["model"] + if "reasoning_effort" in agent: + wire_agent["reasoningEffort"] = agent["reasoning_effort"] return wire_agent def _convert_default_agent_to_wire_format( @@ -3392,11 +3786,15 @@ async def _start_cli_server(self) -> None: """Start the runtime process. This spawns the runtime as a subprocess using the configured transport - mode (stdio or TCP). + mode (stdio or TCP), or hosts it in-process for the FFI transport. Raises: RuntimeError: If the server fails to start or times out. """ + if isinstance(self._connection, InProcessRuntimeConnection): + await self._start_inprocess_ffi() + return + assert isinstance(self._connection, ChildProcessRuntimeConnection) conn = self._connection opts = self._options @@ -3449,8 +3847,13 @@ async def _start_cli_server(self) -> None: }, ) - # Get environment variables - if opts.env is None: + # Get environment variables. Per-connection env (ChildProcessRuntimeConnection.env) + # takes precedence over the client-level env; the constructor already rejects + # setting both. When neither is set, inherit the current process environment. + conn_env = conn.env if isinstance(conn, ChildProcessRuntimeConnection) else None + if conn_env is not None: + env = dict(conn_env) + elif opts.env is None: env = dict(os.environ) else: env = dict(opts.env) @@ -3565,6 +3968,69 @@ async def read_port(): except TimeoutError: raise RuntimeError("Timeout waiting for CLI server to start") + async def _start_inprocess_ffi(self) -> None: + """Host the runtime in-process via the native FFI library. + + Loads the native runtime library and opens the FFI JSON-RPC connection. + + Raises: + RuntimeError: If the native library is missing or startup fails. + """ + assert isinstance(self._connection, InProcessRuntimeConnection) + runtime_path = self._inprocess_runtime_path + assert runtime_path is not None # resolved in __init__ + + logger.info( + "CopilotClient._start_inprocess_ffi hosting Copilot runtime in-process", + extra={"runtime_path": runtime_path, "runtime_path_source": self._cli_path_source}, + ) + + opts = self._options + args: list[str] = [] + if opts.log_level: + args.extend(["--log-level", opts.log_level]) + if opts.github_token: + args.extend(["--auth-token-env", "COPILOT_SDK_AUTH_TOKEN"]) + if not opts.use_logged_in_user: + args.append("--no-auto-login") + if opts.session_idle_timeout_seconds is not None and opts.session_idle_timeout_seconds > 0: + args.extend(["--session-idle-timeout", str(opts.session_idle_timeout_seconds)]) + if opts.enable_remote_sessions: + args.append("--remote") + + environment: dict[str, str] = {} + if opts.github_token: + environment["COPILOT_SDK_AUTH_TOKEN"] = opts.github_token + if opts.base_directory: + environment["COPILOT_HOME"] = opts.base_directory + if opts.mode == "empty": + environment["COPILOT_DISABLE_KEYTAR"] = "1" + + host = FfiRuntimeHost.create( + runtime_path, + environment=environment or None, + args=tuple(args), + ) + + # Track the host and expose its process-like adapter *before* the blocking + # handshake. asyncio.to_thread keeps running host_start after a cancellation + # (a thread can't be interrupted), and CancelledError bypasses start()'s + # `except Exception`, so assigning here — as .NET does before StartAsync — + # keeps a completed native host owned so stop()/force_stop() can dispose it + # instead of leaking it. + self._ffi_host = host + self._process = host.process + + ffi_start = time.perf_counter() + # Native startup may block, so run the handshake off the event loop. + await asyncio.to_thread(host.start_blocking) + log_timing( + logger, + logging.DEBUG, + "CopilotClient._start_inprocess_ffi FFI host started", + ffi_start, + ) + async def _connect_to_server(self) -> None: """Connect to the runtime via the configured transport. @@ -3574,7 +4040,9 @@ async def _connect_to_server(self) -> None: RuntimeError: If the connection fails. """ setup_start = time.perf_counter() - if isinstance(self._connection, StdioRuntimeConnection): + if isinstance(self._connection, (StdioRuntimeConnection, InProcessRuntimeConnection)): + # The in-process FFI host exposes a process-like adapter (stdin/stdout), + # so the same stdio JSON-RPC wiring drives it unchanged. await self._connect_via_stdio() else: await self._connect_via_tcp() @@ -3627,12 +4095,11 @@ def handle_notification(method: str, params: dict): self._client.set_request_handler( "autoModeSwitch.request", self._handle_auto_mode_switch_request ) - self._client.set_request_handler("hooks.invoke", self._handle_hooks_invoke) self._client.set_request_handler( "systemMessage.transform", self._handle_system_message_transform ) register_client_session_api_handlers(self._client, self._get_client_session_handlers) - self._register_llm_inference_handlers() + self._register_client_global_handlers() # Start listening for messages loop = asyncio.get_running_loop() @@ -3747,12 +4214,11 @@ def handle_notification(method: str, params: dict): self._client.set_request_handler( "autoModeSwitch.request", self._handle_auto_mode_switch_request ) - self._client.set_request_handler("hooks.invoke", self._handle_hooks_invoke) self._client.set_request_handler( "systemMessage.transform", self._handle_system_message_transform ) register_client_session_api_handlers(self._client, self._get_client_session_handlers) - self._register_llm_inference_handlers() + self._register_client_global_handlers() # Start listening for messages loop = asyncio.get_running_loop() @@ -3825,17 +4291,31 @@ async def _set_session_fs_provider(self) -> None: await self._client.request("sessionFs.setProvider", params) - def _register_llm_inference_handlers(self) -> None: - if self._request_handler is None or not self._client: + def _register_client_global_handlers(self) -> None: + if not self._client: return - adapter = create_copilot_request_adapter( - self._request_handler, - lambda: self._rpc.llm_inference if self._rpc is not None else None, - ) + llm_inference_adapter = None + if self._request_handler is not None: + llm_inference_adapter = create_copilot_request_adapter( + self._request_handler, + lambda: self._rpc.llm_inference if self._rpc is not None else None, + ) + github_telemetry_adapter = None + if self._on_github_telemetry is not None: + github_telemetry_adapter = _GitHubTelemetryAdapter(self._on_github_telemetry) register_client_global_api_handlers( - self._client, ClientGlobalApiHandlers(llm_inference=adapter) + self._client, + ClientGlobalApiHandlers( + hooks=_HooksAdapter(self._get_session), + llm_inference=llm_inference_adapter, + git_hub_telemetry=github_telemetry_adapter, + ), ) + def _get_session(self, session_id: str) -> CopilotSession | None: + with self._sessions_lock: + return self._sessions.get(session_id) + async def _set_llm_inference_provider(self) -> None: if self._request_handler is None or self._rpc is None: return @@ -3908,34 +4388,6 @@ async def _handle_auto_mode_switch_request(self, params: dict) -> dict: response = await session._handle_auto_mode_switch_request(params) return {"response": response} - async def _handle_hooks_invoke(self, params: dict) -> dict: - """ - Handle a hooks invocation from the CLI server. - - Args: - params: The hooks invocation parameters from the server. - - Returns: - A dict containing the hook output. - - Raises: - ValueError: If the request payload is invalid. - """ - session_id = params.get("sessionId") - hook_type = params.get("hookType") - input_data = params.get("input") - - if not session_id or not hook_type: - raise ValueError("invalid hooks invoke payload") - - with self._sessions_lock: - session = self._sessions.get(session_id) - if not session: - raise ValueError(f"unknown session {session_id}") - - output = await session._handle_hooks_invoke(hook_type, input_data) - return {"output": output} - async def _handle_system_message_transform(self, params: dict) -> dict: """Handle a systemMessage.transform request from the CLI server.""" session_id = params.get("sessionId") diff --git a/python/copilot/copilot_request_handler.py b/python/copilot/copilot_request_handler.py index 54e71027c9..e6465b7bbc 100644 --- a/python/copilot/copilot_request_handler.py +++ b/python/copilot/copilot_request_handler.py @@ -96,6 +96,15 @@ class CopilotRequestContext: """Id of the runtime session that triggered this request, when in scope. Absent for out-of-session requests (e.g. the startup model catalog).""" + agent_id: str | None = None + """Stable per-agent-instance id for the agent trajectory that issued this request.""" + + parent_agent_id: str | None = None + """Id of the parent agent when this request was issued by a subagent.""" + + interaction_type: str | None = None + """Runtime classification for the interaction that produced this request.""" + _bridge: _CopilotWebSocketResponseBridge | None = field(default=None, repr=False) @@ -253,6 +262,9 @@ async def _dispatch(self, exchange: _CopilotRequestExchange) -> None: ctx = CopilotRequestContext( request_id=exchange.request_id, session_id=exchange.session_id, + agent_id=exchange.agent_id, + parent_agent_id=exchange.parent_agent_id, + interaction_type=exchange.interaction_type, transport=exchange.transport, url=exchange.url, headers=exchange.headers, @@ -382,6 +394,9 @@ def __init__( ) -> None: self.request_id = request_id self.session_id: str | None = None + self.agent_id: str | None = None + self.parent_agent_id: str | None = None + self.interaction_type: str | None = None self.method: str = "GET" self.url: str = "" self.headers: dict[str, list[str]] = {} @@ -397,6 +412,9 @@ def __init__( def set_context(self, params: LlmInferenceHTTPRequestStartRequest) -> None: """Fill in the request context once the matching start frame arrives.""" self.session_id = params.session_id + self.agent_id = params.agent_id + self.parent_agent_id = params.parent_agent_id + self.interaction_type = params.interaction_type self.method = params.method self.url = params.url self.headers = params.headers diff --git a/python/copilot/generated/rpc.py b/python/copilot/generated/rpc.py index b38c12ff39..828eaa3ce4 100644 --- a/python/copilot/generated/rpc.py +++ b/python/copilot/generated/rpc.py @@ -6,7 +6,7 @@ from typing import ClassVar, TYPE_CHECKING -from .session_events import AbortReason, Attachment, ContextTier, EmbeddedBlobResourceContents, EmbeddedTextResourceContents, McpServerSource, McpServerStatus, PermissionPromptRequest, PermissionRule, ReasoningSummary, SessionEvent, SessionMode, ShutdownType, SkillSource, UserToolSessionApproval +from .session_events import AbortReason, Attachment, ContextTier, EmbeddedBlobResourceContents, EmbeddedTextResourceContents, McpServerSource, McpServerStatus, PermissionPromptRequest, PermissionRule, ReasoningSummary, SessionEvent, SessionLimitsConfig, SessionMode, ShutdownType, SkillSource, UserToolSessionApproval, Verbosity if TYPE_CHECKING: from .._jsonrpc import JsonRpcClient @@ -120,9 +120,10 @@ def to_dict(self) -> dict: result["error"] = from_union([from_str, from_none], self.error) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CopilotUserResponseEndpoints: - """Schema for the `CopilotUserResponseEndpoints` type.""" + """Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough.""" api: str | None = None origin_tracker: str | None = None @@ -150,6 +151,102 @@ def to_dict(self) -> dict: result["telemetry"] = from_union([from_str, from_none], self.telemetry) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CopilotUserResponseQuotaSnapshots: + """Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, + overage, remaining quota, reset, and billing fields. + + Completions quota snapshot from the raw Copilot user-response passthrough, with + entitlement, overage, remaining quota, reset, and billing fields. + + Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with + entitlement, overage, remaining quota, reset, and billing fields. + """ + entitlement: float | None = None + """Number of requests/units included in the entitlement for this period; `-1` denotes an + unlimited entitlement. + """ + has_quota: bool | None = None + """Whether the user currently has quota available; when `false` and not unlimited, further + requests are blocked until the quota resets. + """ + overage_count: float | None = None + """Count of additional pay-per-request usage consumed this period beyond the entitlement.""" + + overage_permitted: bool | None = None + """Whether usage may continue at pay-per-request rates once the entitlement is exhausted.""" + + percent_remaining: float | None = None + """Percentage of the entitlement remaining at the snapshot timestamp.""" + + quota_id: str | None = None + """Identifier of the quota bucket this snapshot describes.""" + + quota_remaining: float | None = None + """Amount of quota remaining at the snapshot timestamp.""" + + quota_reset_at: float | None = None + """Unix epoch time, in seconds, when this quota next resets.""" + + remaining: float | None = None + """Remaining entitlement/quota amount at the snapshot timestamp.""" + + timestamp_utc: str | None = None + """UTC timestamp when this snapshot was captured.""" + + token_based_billing: bool | None = None + """Whether this category uses usage-based (token/AI-credit) billing rather than a fixed + premium-request count. + """ + unlimited: bool | None = None + """Whether the entitlement for this category is unlimited.""" + + @staticmethod + def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshots': + assert isinstance(obj, dict) + entitlement = from_union([from_float, from_none], obj.get("entitlement")) + has_quota = from_union([from_bool, from_none], obj.get("has_quota")) + overage_count = from_union([from_float, from_none], obj.get("overage_count")) + overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) + percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) + quota_id = from_union([from_str, from_none], obj.get("quota_id")) + quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) + quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) + remaining = from_union([from_float, from_none], obj.get("remaining")) + timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + unlimited = from_union([from_bool, from_none], obj.get("unlimited")) + return CopilotUserResponseQuotaSnapshots(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) + + def to_dict(self) -> dict: + result: dict = {} + if self.entitlement is not None: + result["entitlement"] = from_union([to_float, from_none], self.entitlement) + if self.has_quota is not None: + result["has_quota"] = from_union([from_bool, from_none], self.has_quota) + if self.overage_count is not None: + result["overage_count"] = from_union([to_float, from_none], self.overage_count) + if self.overage_permitted is not None: + result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) + if self.percent_remaining is not None: + result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) + if self.quota_id is not None: + result["quota_id"] = from_union([from_str, from_none], self.quota_id) + if self.quota_remaining is not None: + result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) + if self.quota_reset_at is not None: + result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) + if self.remaining is not None: + result["remaining"] = from_union([to_float, from_none], self.remaining) + if self.timestamp_utc is not None: + result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + if self.unlimited is not None: + result["unlimited"] = from_union([from_bool, from_none], self.unlimited) + return result + # Experimental: this type is part of an experimental API and may change or be removed. class AuthInfoType(Enum): """Authentication type""" @@ -162,9 +259,11 @@ class AuthInfoType(Enum): TOKEN = "token" USER = "user" +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountAllUsers: - """Schema for the `AccountAllUsers` type. + """Authenticated account entry returned by `account.getAllUsers`, with auth info and an + optional associated token. List of all authenticated users """ @@ -188,6 +287,7 @@ def to_dict(self) -> dict: result["token"] = from_union([from_str, from_none], self.token) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountGetCurrentAuthResult: """Current authentication state""" @@ -213,6 +313,7 @@ def to_dict(self) -> dict: result["authInfo"] = from_union([lambda x: (x).to_dict(), from_none], self.auth_info) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountGetQuotaRequest: git_hub_token: str | None = None @@ -232,10 +333,12 @@ def to_dict(self) -> dict: result["gitHubToken"] = from_union([from_str, from_none], self.git_hub_token) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountQuotaSnapshot: - """Schema for the `AccountQuotaSnapshot` type.""" - + """Quota usage snapshot for a Copilot quota type, including entitlement, used requests, + overage, reset date, and remaining percentage. + """ entitlement_requests: int """Number of requests included in the entitlement, or -1 for unlimited entitlements""" @@ -286,6 +389,7 @@ def to_dict(self) -> dict: result["resetDate"] = from_union([from_str, from_none], self.reset_date) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountLoginRequest: """Credentials to store after successful authentication""" @@ -314,6 +418,7 @@ def to_dict(self) -> dict: result["token"] = from_str(self.token) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountLoginResult: """Result of a successful login; throws on failure""" @@ -335,6 +440,7 @@ def to_dict(self) -> dict: result["storedInVault"] = from_bool(self.stored_in_vault) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountLogoutRequest: """User to log out""" @@ -353,6 +459,7 @@ def to_dict(self) -> dict: result["authInfo"] = (self.auth_info).to_dict() return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountLogoutResult: """Logout result indicating if more users remain""" @@ -371,6 +478,17 @@ def to_dict(self) -> dict: result["hasMoreUsers"] = from_bool(self.has_more_users) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class AdaptiveThinkingSupport(Enum): + """Resolved Anthropic adaptive-thinking capability for a model. + + Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. + 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + """ + OPTIONAL = "optional" + REQUIRED = "required" + UNSUPPORTED = "unsupported" + # Experimental: this type is part of an experimental API and may change or be removed. class AgentDiscoveryPathScope(Enum): """Which tier this directory belongs to""" @@ -558,47 +676,19 @@ def to_dict(self) -> dict: return result # Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class AllowAllPermissionSetResult: - """Indicates whether the operation succeeded and reports the post-mutation state.""" - - enabled: bool - """Authoritative allow-all state after the mutation""" - - success: bool - """Whether the operation succeeded""" - - @staticmethod - def from_dict(obj: Any) -> 'AllowAllPermissionSetResult': - assert isinstance(obj, dict) - enabled = from_bool(obj.get("enabled")) - success = from_bool(obj.get("success")) - return AllowAllPermissionSetResult(enabled, success) - - def to_dict(self) -> dict: - result: dict = {} - result["enabled"] = from_bool(self.enabled) - result["success"] = from_bool(self.success) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class AllowAllPermissionState: - """Current full allow-all permission state.""" +class PermissionsAllowAllMode(Enum): + """Authoritative allow-all mode after the mutation - enabled: bool - """Whether full allow-all permissions are currently active""" + Current or requested allow-all mode. - @staticmethod - def from_dict(obj: Any) -> 'AllowAllPermissionState': - assert isinstance(obj, dict) - enabled = from_bool(obj.get("enabled")) - return AllowAllPermissionState(enabled) + Current allow-all mode - def to_dict(self) -> dict: - result: dict = {} - result["enabled"] = from_bool(self.enabled) - return result + Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM + auto-approval; `off` disables both. + """ + AUTO = "auto" + OFF = "off" + ON = "on" class APIKeyAuthInfoType(Enum): API_KEY = "api-key" @@ -703,65 +793,6 @@ def to_dict(self) -> dict: result["instanceId"] = from_str(self.instance_id) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class OpenCanvasInstance: - """Open canvas instance snapshot.""" - - canvas_id: str - """Provider-local canvas identifier""" - - extension_id: str - """Owning provider identifier""" - - instance_id: str - """Stable caller-supplied canvas instance identifier""" - - extension_name: str | None = None - """Owning extension display name, when available""" - - input: Any = None - """Input supplied when the instance was opened""" - - status: str | None = None - """Provider-supplied status text""" - - title: str | None = None - """Rendered title""" - - url: str | None = None - """URL for web-rendered canvases""" - - @staticmethod - def from_dict(obj: Any) -> 'OpenCanvasInstance': - assert isinstance(obj, dict) - canvas_id = from_str(obj.get("canvasId")) - extension_id = from_str(obj.get("extensionId")) - instance_id = from_str(obj.get("instanceId")) - extension_name = from_union([from_str, from_none], obj.get("extensionName")) - input = obj.get("input") - status = from_union([from_str, from_none], obj.get("status")) - title = from_union([from_str, from_none], obj.get("title")) - url = from_union([from_str, from_none], obj.get("url")) - return OpenCanvasInstance(canvas_id, extension_id, instance_id, extension_name, input, status, title, url) - - def to_dict(self) -> dict: - result: dict = {} - result["canvasId"] = from_str(self.canvas_id) - result["extensionId"] = from_str(self.extension_id) - result["instanceId"] = from_str(self.instance_id) - if self.extension_name is not None: - result["extensionName"] = from_union([from_str, from_none], self.extension_name) - if self.input is not None: - result["input"] = self.input - if self.status is not None: - result["status"] = from_union([from_str, from_none], self.status) - if self.title is not None: - result["title"] = from_union([from_str, from_none], self.title) - if self.url is not None: - result["url"] = from_union([from_str, from_none], self.url) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CanvasOpenRequest: @@ -876,6 +907,30 @@ def to_dict(self) -> dict: result["enableWebSocketResponses"] = from_union([from_bool, from_none], self.enable_web_socket_responses) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SlashCommandInputChoice: + """A literal choice the command input accepts, with a human-facing description""" + + description: str + """Human-readable description shown alongside the choice""" + + name: str + """The literal choice value (e.g. 'on', 'off', 'show')""" + + @staticmethod + def from_dict(obj: Any) -> 'SlashCommandInputChoice': + assert isinstance(obj, dict) + description = from_str(obj.get("description")) + name = from_str(obj.get("name")) + return SlashCommandInputChoice(description, name) + + def to_dict(self) -> dict: + result: dict = {} + result["description"] = from_str(self.description) + result["name"] = from_str(self.name) + return result + # Experimental: this type is part of an experimental API and may change or be removed. class SlashCommandInputCompletion(Enum): """Optional completion hint for the input (e.g. 'directory' for filesystem path completion)""" @@ -1038,6 +1093,99 @@ def to_dict(self) -> dict: result["success"] = from_bool(self.success) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CompletionsGetTriggerCharactersResult: + """Characters that, when typed in the composer, should trigger a `completions.request`. + Empty when the session has no host-driven completions (e.g. local sessions, or a relay + host that does not advertise `completionTriggerCharacters`). + """ + trigger_characters: list[str] + """Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven + completions for the session. + """ + + @staticmethod + def from_dict(obj: Any) -> 'CompletionsGetTriggerCharactersResult': + assert isinstance(obj, dict) + trigger_characters = from_list(from_str, obj.get("triggerCharacters")) + return CompletionsGetTriggerCharactersResult(trigger_characters) + + def to_dict(self) -> dict: + result: dict = {} + result["triggerCharacters"] = from_list(from_str, self.trigger_characters) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CompletionsRequestRequest: + """Request host-driven completions for the current composer input.""" + + offset: int + """Cursor offset within `text`, in UTF-16 code units.""" + + text: str + """The full composed composer input.""" + + @staticmethod + def from_dict(obj: Any) -> 'CompletionsRequestRequest': + assert isinstance(obj, dict) + offset = from_int(obj.get("offset")) + text = from_str(obj.get("text")) + return CompletionsRequestRequest(offset, text) + + def to_dict(self) -> dict: + result: dict = {} + result["offset"] = from_int(self.offset) + result["text"] = from_str(self.text) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionCompletionItem: + """A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` + (UTF-16 code units) in the composer with `insertText`; when the range is absent, the + active token around the cursor is replaced. + """ + insert_text: str + """Text spliced into the composer when the item is accepted.""" + + kind: str | None = None + """Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the + host's display kind. + """ + label: str | None = None + """Primary display label for the picker row. Falls back to `insertText` when absent.""" + + range_end: int | None = None + """End (exclusive) of the replacement range in `text`, in UTF-16 code units.""" + + range_start: int | None = None + """Start of the replacement range in `text`, in UTF-16 code units.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionCompletionItem': + assert isinstance(obj, dict) + insert_text = from_str(obj.get("insertText")) + kind = from_union([from_str, from_none], obj.get("kind")) + label = from_union([from_str, from_none], obj.get("label")) + range_end = from_union([from_int, from_none], obj.get("rangeEnd")) + range_start = from_union([from_int, from_none], obj.get("rangeStart")) + return SessionCompletionItem(insert_text, kind, label, range_end, range_start) + + def to_dict(self) -> dict: + result: dict = {} + result["insertText"] = from_str(self.insert_text) + if self.kind is not None: + result["kind"] = from_union([from_str, from_none], self.kind) + if self.label is not None: + result["label"] = from_union([from_str, from_none], self.label) + if self.range_end is not None: + result["rangeEnd"] = from_union([from_int, from_none], self.range_end) + if self.range_start is not None: + result["rangeStart"] = from_union([from_int, from_none], self.range_start) + return result + # Experimental: this type is part of an experimental API and may change or be removed. # Internal: this type is an internal SDK API and is not part of the public surface. @dataclass @@ -1086,26 +1234,41 @@ def to_dict(self) -> dict: result["sessionId"] = from_str(self.session_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. # Internal: this type is an internal SDK API and is not part of the public surface. @dataclass class _ConnectRequest: - """Optional connection token presented by the SDK client during the handshake.""" - + """Parameters for the `server.connect` handshake: an optional connection token and optional + connection-level opt-ins (e.g. GitHub telemetry forwarding). + """ + enable_git_hub_telemetry_forwarding: bool | None = None + """Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the + runtime forwards every internal telemetry event it emits — across all sessions, plus + sessionless events — to this connection over the `gitHubTelemetry.event` notification, in + addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for + first-party hosts that re-emit the events into their own telemetry stores. Both + unrestricted and restricted events are forwarded, each tagged with a `restricted` + discriminator; a backstop drops restricted events when restricted telemetry is disabled. + """ token: str | None = None """Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN""" @staticmethod def from_dict(obj: Any) -> '_ConnectRequest': assert isinstance(obj, dict) + enable_git_hub_telemetry_forwarding = from_union([from_bool, from_none], obj.get("enableGitHubTelemetryForwarding")) token = from_union([from_str, from_none], obj.get("token")) - return _ConnectRequest(token) + return _ConnectRequest(enable_git_hub_telemetry_forwarding, token) def to_dict(self) -> dict: result: dict = {} + if self.enable_git_hub_telemetry_forwarding is not None: + result["enableGitHubTelemetryForwarding"] = from_union([from_bool, from_none], self.enable_git_hub_telemetry_forwarding) if self.token is not None: result["token"] = from_union([from_str, from_none], self.token) return result +# Experimental: this type is part of an experimental API and may change or be removed. # Internal: this type is an internal SDK API and is not part of the public surface. @dataclass class _ConnectResult: @@ -1171,6 +1334,7 @@ def to_dict(self) -> dict: result["owner"] = from_str(self.owner) return result +# Experimental: this type is part of an experimental API and may change or be removed. class ContentFilterMode(Enum): """Controls how MCP tool result content is filtered: none leaves content unchanged, markdown sanitizes HTML while preserving Markdown-friendly output, and hidden_characters removes @@ -1180,28 +1344,90 @@ class ContentFilterMode(Enum): MARKDOWN = "markdown" NONE = "none" -class Host(Enum): - HTTPS_GITHUB_COM = "https://github.com" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ContextHeaviestMessage: + """A single large message currently in context.""" + + id: str + """Stable identifier for this message within the snapshot.""" + + label: str + """Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only.""" + + role: str + """Role of the chat message (`user`, `assistant`, or `tool`).""" + + tokens: int + """Token count currently in context for this individual message.""" + + @staticmethod + def from_dict(obj: Any) -> 'ContextHeaviestMessage': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + label = from_str(obj.get("label")) + role = from_str(obj.get("role")) + tokens = from_int(obj.get("tokens")) + return ContextHeaviestMessage(id, label, role, tokens) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + result["label"] = from_str(self.label) + result["role"] = from_str(self.role) + result["tokens"] = from_int(self.tokens) + return result + +class Host(Enum): + HTTPS_GITHUB_COM = "https://github.com" class CopilotAPITokenAuthInfoType(Enum): COPILOT_API_TOKEN = "copilot-api-token" +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CopilotUserResponseQuotaSnapshotsChat: - """Schema for the `CopilotUserResponseQuotaSnapshotsChat` type.""" - + """Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, + overage, remaining quota, reset, and billing fields. + """ entitlement: float | None = None + """Number of requests/units included in the entitlement for this period; `-1` denotes an + unlimited entitlement. + """ has_quota: bool | None = None + """Whether the user currently has quota available; when `false` and not unlimited, further + requests are blocked until the quota resets. + """ overage_count: float | None = None + """Count of additional pay-per-request usage consumed this period beyond the entitlement.""" + overage_permitted: bool | None = None + """Whether usage may continue at pay-per-request rates once the entitlement is exhausted.""" + percent_remaining: float | None = None + """Percentage of the entitlement remaining at the snapshot timestamp.""" + quota_id: str | None = None + """Identifier of the quota bucket this snapshot describes.""" + quota_remaining: float | None = None + """Amount of quota remaining at the snapshot timestamp.""" + quota_reset_at: float | None = None + """Unix epoch time, in seconds, when this quota next resets.""" + remaining: float | None = None + """Remaining entitlement/quota amount at the snapshot timestamp.""" + timestamp_utc: str | None = None + """UTC timestamp when this snapshot was captured.""" + token_based_billing: bool | None = None + """Whether this category uses usage-based (token/AI-credit) billing rather than a fixed + premium-request count. + """ unlimited: bool | None = None + """Whether the entitlement for this category is unlimited.""" @staticmethod def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsChat': @@ -1248,22 +1474,50 @@ def to_dict(self) -> dict: result["unlimited"] = from_union([from_bool, from_none], self.unlimited) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CopilotUserResponseQuotaSnapshotsCompletions: - """Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type.""" - + """Completions quota snapshot from the raw Copilot user-response passthrough, with + entitlement, overage, remaining quota, reset, and billing fields. + """ entitlement: float | None = None + """Number of requests/units included in the entitlement for this period; `-1` denotes an + unlimited entitlement. + """ has_quota: bool | None = None + """Whether the user currently has quota available; when `false` and not unlimited, further + requests are blocked until the quota resets. + """ overage_count: float | None = None + """Count of additional pay-per-request usage consumed this period beyond the entitlement.""" + overage_permitted: bool | None = None + """Whether usage may continue at pay-per-request rates once the entitlement is exhausted.""" + percent_remaining: float | None = None + """Percentage of the entitlement remaining at the snapshot timestamp.""" + quota_id: str | None = None + """Identifier of the quota bucket this snapshot describes.""" + quota_remaining: float | None = None + """Amount of quota remaining at the snapshot timestamp.""" + quota_reset_at: float | None = None + """Unix epoch time, in seconds, when this quota next resets.""" + remaining: float | None = None + """Remaining entitlement/quota amount at the snapshot timestamp.""" + timestamp_utc: str | None = None + """UTC timestamp when this snapshot was captured.""" + token_based_billing: bool | None = None + """Whether this category uses usage-based (token/AI-credit) billing rather than a fixed + premium-request count. + """ unlimited: bool | None = None + """Whether the entitlement for this category is unlimited.""" @staticmethod def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsCompletions': @@ -1310,22 +1564,50 @@ def to_dict(self) -> dict: result["unlimited"] = from_union([from_bool, from_none], self.unlimited) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CopilotUserResponseQuotaSnapshotsPremiumInteractions: - """Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type.""" - + """Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with + entitlement, overage, remaining quota, reset, and billing fields. + """ entitlement: float | None = None + """Number of requests/units included in the entitlement for this period; `-1` denotes an + unlimited entitlement. + """ has_quota: bool | None = None + """Whether the user currently has quota available; when `false` and not unlimited, further + requests are blocked until the quota resets. + """ overage_count: float | None = None + """Count of additional pay-per-request usage consumed this period beyond the entitlement.""" + overage_permitted: bool | None = None + """Whether usage may continue at pay-per-request rates once the entitlement is exhausted.""" + percent_remaining: float | None = None + """Percentage of the entitlement remaining at the snapshot timestamp.""" + quota_id: str | None = None + """Identifier of the quota bucket this snapshot describes.""" + quota_remaining: float | None = None + """Amount of quota remaining at the snapshot timestamp.""" + quota_reset_at: float | None = None + """Unix epoch time, in seconds, when this quota next resets.""" + remaining: float | None = None + """Remaining entitlement/quota amount at the snapshot timestamp.""" + timestamp_utc: str | None = None + """UTC timestamp when this snapshot was captured.""" + token_based_billing: bool | None = None + """Whether this category uses usage-based (token/AI-credit) billing rather than a fixed + premium-request count. + """ unlimited: bool | None = None + """Whether the entitlement for this category is unlimited.""" @staticmethod def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshotsPremiumInteractions': @@ -1409,6 +1691,127 @@ def to_dict(self) -> dict: result["reasoningEffort"] = from_union([from_str, from_none], self.reasoning_effort) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class DebugCollectLogsSource(Enum): + """Source category for this entry. + + Source category for a collected debug bundle entry. + """ + ADDITIONAL = "additional" + EVENTS = "events" + PROCESS_LOG = "process-log" + SHELL_LOG = "shell-log" + +# Experimental: this type is part of an experimental API and may change or be removed. +class DebugCollectLogsResultKind(Enum): + """Destination kind that was written.""" + + ARCHIVE = "archive" + DIRECTORY = "directory" + +# Experimental: this type is part of an experimental API and may change or be removed. +class DebugCollectLogsRedaction(Enum): + """How text content from this entry should be redacted. Defaults to plain-text. + + How a collected debug entry should be redacted before being staged. + """ + EVENTS_JSONL = "events-jsonl" + PLAIN_TEXT = "plain-text" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class DebugCollectLogsInclude: + """Built-in session diagnostics to include in the bundle. Omitted fields default to true. + + Which built-in session diagnostics to include. Omitted fields default to true. + """ + current_process_log_path: str | None = None + """Server-local path to the current process log. When set, it is included as `process.log` + and its directory is searched for prior logs from the same session. + """ + events: bool | None = None + """Include the session event log (`events.jsonl`). Defaults to true.""" + + events_path: str | None = None + """Server-local path to the session's events.jsonl file. Internal callers normally omit this + and let the runtime derive it from the session. + """ + previous_process_log_limit: int | None = None + """Maximum number of previous process logs to include. Defaults to 5.""" + + process_log_directory: str | None = None + """Server-local process log directory to search when `currentProcessLogPath` is unavailable, + useful for collecting logs for inactive sessions. + """ + process_logs: bool | None = None + """Include process logs for the session. Defaults to true.""" + + shell_logs: bool | None = None + """Include interactive shell logs written under the session's `shell-logs` directory. + Defaults to true. + """ + + @staticmethod + def from_dict(obj: Any) -> 'DebugCollectLogsInclude': + assert isinstance(obj, dict) + current_process_log_path = from_union([from_str, from_none], obj.get("currentProcessLogPath")) + events = from_union([from_bool, from_none], obj.get("events")) + events_path = from_union([from_str, from_none], obj.get("eventsPath")) + previous_process_log_limit = from_union([from_int, from_none], obj.get("previousProcessLogLimit")) + process_log_directory = from_union([from_str, from_none], obj.get("processLogDirectory")) + process_logs = from_union([from_bool, from_none], obj.get("processLogs")) + shell_logs = from_union([from_bool, from_none], obj.get("shellLogs")) + return DebugCollectLogsInclude(current_process_log_path, events, events_path, previous_process_log_limit, process_log_directory, process_logs, shell_logs) + + def to_dict(self) -> dict: + result: dict = {} + if self.current_process_log_path is not None: + result["currentProcessLogPath"] = from_union([from_str, from_none], self.current_process_log_path) + if self.events is not None: + result["events"] = from_union([from_bool, from_none], self.events) + if self.events_path is not None: + result["eventsPath"] = from_union([from_str, from_none], self.events_path) + if self.previous_process_log_limit is not None: + result["previousProcessLogLimit"] = from_union([from_int, from_none], self.previous_process_log_limit) + if self.process_log_directory is not None: + result["processLogDirectory"] = from_union([from_str, from_none], self.process_log_directory) + if self.process_logs is not None: + result["processLogs"] = from_union([from_bool, from_none], self.process_logs) + if self.shell_logs is not None: + result["shellLogs"] = from_union([from_bool, from_none], self.shell_logs) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class DebugCollectLogsSkippedEntry: + """An optional debug bundle entry that could not be included.""" + + bundle_path: str + """Relative path requested for this bundle entry.""" + + reason: str + """Reason the entry was skipped.""" + + path: str | None = None + """Server-local source path that could not be read.""" + + @staticmethod + def from_dict(obj: Any) -> 'DebugCollectLogsSkippedEntry': + assert isinstance(obj, dict) + bundle_path = from_str(obj.get("bundlePath")) + reason = from_str(obj.get("reason")) + path = from_union([from_str, from_none], obj.get("path")) + return DebugCollectLogsSkippedEntry(bundle_path, reason, path) + + def to_dict(self) -> dict: + result: dict = {} + result["bundlePath"] = from_str(self.bundle_path) + result["reason"] = from_str(self.reason) + if self.path is not None: + result["path"] = from_union([from_str, from_none], self.path) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. class DiscoveredMCPServerType(Enum): """Server transport type: stdio, http, sse (deprecated), or memory""" @@ -1658,6 +2061,7 @@ class ExternalToolTextResultForLlmContentType(Enum): IMAGE = "image" RESOURCE = "resource" RESOURCE_LINK = "resource_link" + SHELL_EXIT = "shell_exit" TERMINAL = "terminal" TEXT = "text" @@ -1673,6 +2077,9 @@ class ExternalToolTextResultForLlmContentResourceType(Enum): class ExternalToolTextResultForLlmContentResourceLinkType(Enum): RESOURCE_LINK = "resource_link" +class ExternalToolTextResultForLlmContentShellExitType(Enum): + SHELL_EXIT = "shell_exit" + class ExternalToolTextResultForLlmContentTerminalType(Enum): TERMINAL = "terminal" @@ -1778,6 +2185,77 @@ def to_dict(self) -> dict: class GhCLIAuthInfoType(Enum): GH_CLI = "gh-cli" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class GitHubTelemetryClientInfo: + """Client environment metadata describing the process that produced a telemetry event. + + Client environment metadata. + """ + cli_version: str + """Copilot CLI version string.""" + + node_version: str + """Node.js runtime version string.""" + + os_arch: str + """Operating system architecture (e.g. arm64, x64).""" + + os_platform: str + """Operating system platform (e.g. darwin, linux, win32).""" + + os_version: str + """Operating system version string.""" + + client_name: str | None = None + """Name of the client application.""" + + client_type: str | None = None + """Type of client.""" + + copilot_plan: str | None = None + """Copilot subscription plan, when known.""" + + dev_device_id: str | None = None + """Stable machine identifier for the device.""" + + is_staff: bool | None = None + """Whether the user is a GitHub/Microsoft staff member.""" + + @staticmethod + def from_dict(obj: Any) -> 'GitHubTelemetryClientInfo': + assert isinstance(obj, dict) + cli_version = from_str(obj.get("cli_version")) + node_version = from_str(obj.get("node_version")) + os_arch = from_str(obj.get("os_arch")) + os_platform = from_str(obj.get("os_platform")) + os_version = from_str(obj.get("os_version")) + client_name = from_union([from_str, from_none], obj.get("client_name")) + client_type = from_union([from_str, from_none], obj.get("client_type")) + copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) + dev_device_id = from_union([from_str, from_none], obj.get("dev_device_id")) + is_staff = from_union([from_bool, from_none], obj.get("is_staff")) + return GitHubTelemetryClientInfo(cli_version, node_version, os_arch, os_platform, os_version, client_name, client_type, copilot_plan, dev_device_id, is_staff) + + def to_dict(self) -> dict: + result: dict = {} + result["cli_version"] = from_str(self.cli_version) + result["node_version"] = from_str(self.node_version) + result["os_arch"] = from_str(self.os_arch) + result["os_platform"] = from_str(self.os_platform) + result["os_version"] = from_str(self.os_version) + if self.client_name is not None: + result["client_name"] = from_union([from_str, from_none], self.client_name) + if self.client_type is not None: + result["client_type"] = from_union([from_str, from_none], self.client_type) + if self.copilot_plan is not None: + result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) + if self.dev_device_id is not None: + result["dev_device_id"] = from_union([from_str, from_none], self.dev_device_id) + if self.is_staff is not None: + result["is_staff"] = from_union([from_bool, from_none], self.is_staff) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class HandlePendingToolCallResult: @@ -1968,6 +2446,46 @@ def to_dict(self) -> dict: class HMACAuthInfoType(Enum): HMAC = "hmac" +# Internal: this type is an internal SDK API and is not part of the public surface. +class _HookType(Enum): + """Hook event name dispatched through the SDK callback transport.""" + + AGENT_STOP = "agentStop" + ERROR_OCCURRED = "errorOccurred" + NOTIFICATION = "notification" + PERMISSION_REQUEST = "permissionRequest" + POST_RESULT = "postResult" + POST_TOOL_USE = "postToolUse" + POST_TOOL_USE_FAILURE = "postToolUseFailure" + PRE_COMPACT = "preCompact" + PRE_MCP_TOOL_CALL = "preMcpToolCall" + PRE_PR_DESCRIPTION = "prePRDescription" + PRE_TOOL_USE = "preToolUse" + SESSION_END = "sessionEnd" + SESSION_START = "sessionStart" + SUBAGENT_START = "subagentStart" + SUBAGENT_STOP = "subagentStop" + USER_PROMPT_SUBMITTED = "userPromptSubmitted" + +# Internal: this type is an internal SDK API and is not part of the public surface. +@dataclass +class _HookInvokeResponse: + """Optional output returned by an SDK callback hook.""" + + output: Any = None + + @staticmethod + def from_dict(obj: Any) -> '_HookInvokeResponse': + assert isinstance(obj, dict) + output = obj.get("output") + return _HookInvokeResponse(output) + + def to_dict(self) -> dict: + result: dict = {} + if self.output is not None: + result["output"] = self.output + return result + class PurpleSource(Enum): GITHUB = "github" LOCAL = "local" @@ -1982,15 +2500,6 @@ class TentacledSource(Enum): class StickySource(Enum): URL = "url" -# Experimental: this type is part of an experimental API and may change or be removed. -class InstructionDiscoveryPathKind(Enum): - """Whether the target is a single file or a directory of instruction files - - Entry type - """ - DIRECTORY = "directory" - FILE = "file" - # Experimental: this type is part of an experimental API and may change or be removed. class InstructionLocation(Enum): """Which tier this target belongs to @@ -2411,8 +2920,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MarketplaceRefreshEntry: - """Schema for the `MarketplaceRefreshEntry` type.""" - + """Per-marketplace refresh result, including marketplace name, success flag, and optional + failure error. + """ name: str """Marketplace name that was refreshed""" @@ -2467,7 +2977,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPAllowedServer: - """Schema for the `McpAllowedServer` type.""" + """MCP server allowed by policy, with server name and optional PII-free explanatory note.""" name: str """Allowed server name""" @@ -2663,8 +3173,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPAppsResourceContent: - """Schema for the `McpAppsResourceContent` type.""" - + """MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource + metadata. + """ uri: str """The resource URI (typically ui://...)""" @@ -2745,6 +3256,7 @@ def to_dict(self) -> dict: result["cancelled"] = from_bool(self.cancelled) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServerAuthConfigRedirectPort: """Authentication settings with optional redirect port configuration.""" @@ -2764,6 +3276,7 @@ def to_dict(self) -> dict: result["redirectPort"] = from_union([from_int, from_none], self.redirect_port) return result +# Experimental: this type is part of an experimental API and may change or be removed. class MCPServerConfigDeferTools(Enum): """Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) @@ -2783,12 +3296,14 @@ class MCPGrantType(Enum): AUTHORIZATION_CODE = "authorization_code" CLIENT_CREDENTIALS = "client_credentials" +# Experimental: this type is part of an experimental API and may change or be removed. class MCPServerConfigHTTPType(Enum): """Remote transport type. Defaults to "http" when omitted.""" HTTP = "http" SSE = "sse" +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigDisableRequest: """MCP server names to disable for new sessions.""" @@ -2810,6 +3325,7 @@ def to_dict(self) -> dict: result["names"] = from_list(from_str, self.names) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigEnableRequest: """MCP server names to enable for new sessions.""" @@ -2830,6 +3346,7 @@ def to_dict(self) -> dict: result["names"] = from_list(from_str, self.names) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigRemoveRequest: """MCP server name to remove from user configuration.""" @@ -2908,6 +3425,7 @@ def to_dict(self) -> dict: result["serverName"] = from_str(self.server_name) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPDiscoverRequest: """Optional working directory used as context for MCP server discovery.""" @@ -2949,8 +3467,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPFilteredServer: - """Schema for the `McpFilteredServer` type.""" - + """MCP server filtered by policy, with name, reason, optional redacted reason, and + enterprise login. + """ name: str """Filtered server name""" @@ -2982,6 +3501,31 @@ def to_dict(self) -> dict: result["redactedReason"] = from_union([from_str, from_none], self.redacted_reason) return result +class MCPHeadersHandlePendingHeadersRefreshRequestKind(Enum): + HEADERS = "headers" + NONE = "none" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPHeadersHandlePendingHeadersRefreshRequestResult: + """Indicates whether the pending MCP headers refresh response was accepted.""" + + success: bool + """Whether the response was accepted. False if the request was unknown, timed out, or + already resolved. + """ + + @staticmethod + def from_dict(obj: Any) -> 'MCPHeadersHandlePendingHeadersRefreshRequestResult': + assert isinstance(obj, dict) + success = from_bool(obj.get("success")) + return MCPHeadersHandlePendingHeadersRefreshRequestResult(success) + + def to_dict(self) -> dict: + result: dict = {} + result["success"] = from_bool(self.success) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServerFailureInfo: @@ -3082,6 +3626,13 @@ def to_dict(self) -> dict: result["serverName"] = from_str(self.server_name) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class MCPToolUIVisibility(Enum): + """Consumer allowed to call an MCP tool.""" + + APP = "app" + MODEL = "model" + class MCPOauthPendingRequestResponseKind(Enum): CANCELLED = "cancelled" TOKEN = "token" @@ -3133,19 +3684,6 @@ def to_dict(self) -> dict: result["authorizationUrl"] = from_union([from_str, from_none], self.authorization_url) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class MCPOauthRespondResult: - """Empty result after recording the MCP OAuth response.""" - @staticmethod - def from_dict(obj: Any) -> 'MCPOauthRespondResult': - assert isinstance(obj, dict) - return MCPOauthRespondResult() - - def to_dict(self) -> dict: - result: dict = {} - return result - # Experimental: this type is part of an experimental API and may change or be removed. # Internal: this type is an internal SDK API and is not part of the public surface. @dataclass @@ -3192,45 +3730,163 @@ def to_dict(self) -> dict: return result # Experimental: this type is part of an experimental API and may change or be removed. -class MCPSamplingExecutionAction(Enum): - """Outcome of the sampling inference. 'success' produced a response; 'failure' encountered - an error (including agent-side rejection by content filter or criteria); 'cancelled' the - caller cancelled this execution via cancelSamplingExecution. +@dataclass +class MCPResourceContent: + """MCP resource content with URI, optional MIME type, text or base64 blob, and resource + metadata. """ - CANCELLED = "cancelled" - FAILURE = "failure" - SUCCESS = "success" - -# Experimental: this type is part of an experimental API and may change or be removed. -class MCPSetEnvValueModeDetails(Enum): - """How environment-variable values supplied to MCP servers are resolved. "direct" passes - literal string values; "indirect" treats values as references (e.g. names of environment - variables on the host) that the runtime resolves before launch. Defaults to the runtime's - startup mode; clients that intentionally launch MCP servers with literal values (e.g. CLI - prompt mode and ACP) set this to "direct". - - Mode recorded on the session after the update + uri: str + """The resource URI""" - How env values are passed to MCP servers (`direct` inlines literal values; `indirect` - resolves at launch). + meta: dict[str, Any] | None = None + """Resource-level metadata (CSP, permissions, etc.)""" - How MCP server environment values are interpreted. - """ - DIRECT = "direct" - INDIRECT = "indirect" + blob: str | None = None + """Base64-encoded binary content""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class MCPStopServerRequest: - """Server name for an individual MCP server stop.""" + mime_type: str | None = None + """MIME type of the content""" - server_name: str - """Name of the MCP server to stop""" + text: str | None = None + """Text content (e.g. HTML)""" @staticmethod - def from_dict(obj: Any) -> 'MCPStopServerRequest': + def from_dict(obj: Any) -> 'MCPResourceContent': assert isinstance(obj, dict) - server_name = from_str(obj.get("serverName")) + uri = from_str(obj.get("uri")) + meta = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("_meta")) + blob = from_union([from_str, from_none], obj.get("blob")) + mime_type = from_union([from_str, from_none], obj.get("mimeType")) + text = from_union([from_str, from_none], obj.get("text")) + return MCPResourceContent(uri, meta, blob, mime_type, text) + + def to_dict(self) -> dict: + result: dict = {} + result["uri"] = from_str(self.uri) + if self.meta is not None: + result["_meta"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.meta) + if self.blob is not None: + result["blob"] = from_union([from_str, from_none], self.blob) + if self.mime_type is not None: + result["mimeType"] = from_union([from_str, from_none], self.mime_type) + if self.text is not None: + result["text"] = from_union([from_str, from_none], self.text) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourcesListRequest: + """MCP server whose resources to enumerate.""" + + server_name: str + """Name of the MCP server whose resources to enumerate""" + + cursor: str | None = None + """Opaque MCP pagination cursor from a prior `nextCursor` value""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResourcesListRequest': + assert isinstance(obj, dict) + server_name = from_str(obj.get("serverName")) + cursor = from_union([from_str, from_none], obj.get("cursor")) + return MCPResourcesListRequest(server_name, cursor) + + def to_dict(self) -> dict: + result: dict = {} + result["serverName"] = from_str(self.server_name) + if self.cursor is not None: + result["cursor"] = from_union([from_str, from_none], self.cursor) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourcesListTemplatesRequest: + """MCP server whose resource templates to enumerate.""" + + server_name: str + """Name of the MCP server whose resource templates to enumerate""" + + cursor: str | None = None + """Opaque MCP pagination cursor from a prior `nextCursor` value""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResourcesListTemplatesRequest': + assert isinstance(obj, dict) + server_name = from_str(obj.get("serverName")) + cursor = from_union([from_str, from_none], obj.get("cursor")) + return MCPResourcesListTemplatesRequest(server_name, cursor) + + def to_dict(self) -> dict: + result: dict = {} + result["serverName"] = from_str(self.server_name) + if self.cursor is not None: + result["cursor"] = from_union([from_str, from_none], self.cursor) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourcesReadRequest: + """MCP server and resource URI to fetch.""" + + server_name: str + """Name of the MCP server hosting the resource""" + + uri: str + """Resource URI""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResourcesReadRequest': + assert isinstance(obj, dict) + server_name = from_str(obj.get("serverName")) + uri = from_str(obj.get("uri")) + return MCPResourcesReadRequest(server_name, uri) + + def to_dict(self) -> dict: + result: dict = {} + result["serverName"] = from_str(self.server_name) + result["uri"] = from_str(self.uri) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class MCPSamplingExecutionAction(Enum): + """Outcome of the sampling inference. 'success' produced a response; 'failure' encountered + an error (including agent-side rejection by content filter or criteria); 'cancelled' the + caller cancelled this execution via cancelSamplingExecution. + """ + CANCELLED = "cancelled" + FAILURE = "failure" + SUCCESS = "success" + +# Experimental: this type is part of an experimental API and may change or be removed. +class MCPSetEnvValueModeDetails(Enum): + """How environment-variable values supplied to MCP servers are resolved. "direct" passes + literal string values; "indirect" treats values as references (e.g. names of environment + variables on the host) that the runtime resolves before launch. Defaults to the runtime's + startup mode; clients that intentionally launch MCP servers with literal values (e.g. CLI + prompt mode and ACP) set this to "direct". + + Mode recorded on the session after the update + + How env values are passed to MCP servers (`direct` inlines literal values; `indirect` + resolves at launch). + + How MCP server environment values are interpreted. + """ + DIRECT = "direct" + INDIRECT = "indirect" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPStopServerRequest: + """Server name for an individual MCP server stop.""" + + server_name: str + """Name of the MCP server to stop""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPStopServerRequest': + assert isinstance(obj, dict) + server_name = from_str(obj.get("serverName")) return MCPStopServerRequest(server_name) def to_dict(self) -> dict: @@ -3277,6 +3933,97 @@ def to_dict(self) -> dict: result["enabled"] = from_bool(self.enabled) return result +@dataclass +class Compactions: + """Successful compaction history for the session.""" + + count: int + """Number of successful compactions in this session.""" + + @staticmethod + def from_dict(obj: Any) -> 'Compactions': + assert isinstance(obj, dict) + count = from_int(obj.get("count")) + return Compactions(count) + + def to_dict(self) -> dict: + result: dict = {} + result["count"] = from_int(self.count) + return result + +@dataclass +class Entry: + id: str + """Identifier for this entry, formed by joining its `kind` and source name (e.g. + `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to + match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP + registries), and as the `parentId` target for nesting. Distinct from the human-facing + `label`. + """ + kind: str + """Source category for this entry. Not a closed set — tolerate unknown values. Known values + today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + """ + label: str + """Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be + localized/reformatted without notice — do not key off it. + """ + tokens: int + """Token count currently in context attributable to this entry.""" + + attributes: dict[str, str] | None = None + """Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, + `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + """ + parent_id: str | None = None + """Optional `id` of the parent entry: e.g. a `plugin` entry parenting its + `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. + Omitted for top-level entries. + """ + + @staticmethod + def from_dict(obj: Any) -> 'Entry': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + kind = from_str(obj.get("kind")) + label = from_str(obj.get("label")) + tokens = from_int(obj.get("tokens")) + attributes = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("attributes")) + parent_id = from_union([from_str, from_none], obj.get("parentId")) + return Entry(id, kind, label, tokens, attributes, parent_id) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + result["kind"] = from_str(self.kind) + result["label"] = from_str(self.label) + result["tokens"] = from_int(self.tokens) + if self.attributes is not None: + result["attributes"] = from_union([lambda x: from_dict(from_str, x), from_none], self.attributes) + if self.parent_id is not None: + result["parentId"] = from_union([from_str, from_none], self.parent_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MetadataContextHeaviestMessagesRequest: + """Parameters for the heaviest-messages query.""" + + limit: int | None = None + """Maximum number of messages to return, most-expensive first. Omit for the server default.""" + + @staticmethod + def from_dict(obj: Any) -> 'MetadataContextHeaviestMessagesRequest': + assert isinstance(obj, dict) + limit = from_union([from_int, from_none], obj.get("limit")) + return MetadataContextHeaviestMessagesRequest(limit) + + def to_dict(self) -> dict: + result: dict = {} + if self.limit is not None: + result["limit"] = from_union([from_int, from_none], self.limit) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionContextInfo: @@ -3420,8 +4167,11 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MetadataSetWorkingDirectoryRequest: - """Absolute path to set as the session's new working directory.""" - + """Absolute path to set as the session's new working directory. For local sessions the path + must be absolute and exist on disk: it is validated before any session state changes, and + a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote + sessions record the path as-is. + """ working_directory: str """Absolute path to set as the session's working directory. The runtime updates the session's recorded cwd so subsequent operations (shell tools, file lookups, telemetry) @@ -3443,9 +4193,13 @@ def to_dict(self) -> dict: @dataclass class MetadataSetWorkingDirectoryResult: """Update the session's working directory. Used by the host when the user explicitly changes - cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any - related side-effects (file index, etc.); this method only updates the session's own - recorded path. + cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects + (file index, etc.); it does NOT change the process working directory (a session's cwd is + per-session, not process-global). For local sessions the runtime validates the target + first (an absolute path that exists on disk) and re-bases the permission primary + directory; a rejected validation fails the call before anything is mutated, persisted, or + emitted. Location-scoped permission rules are then re-keyed to the new directory + (best-effort). Remote sessions only record the path. """ working_directory: str """Working directory after the update""" @@ -3530,6 +4284,51 @@ def to_dict(self) -> dict: result["mode"] = to_enum(SessionMode, self.mode) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ModelBillingPromo: + """Active server-driven promotion for this model, if any. Present when the model is being + promoted with a time-boxed discount. + + Active server-driven promotion for a model, including its discount and expiry. + """ + ends_at: str + """UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only + surfaces a promo whose expiry parses and is in the future. Consumers should treat a past + value as expired. + """ + discount_percent: float | None = None + """Percentage discount (0-100) applied while the promotion is active. May be fractional.""" + + id: str | None = None + """Stable identifier for the promotion campaign.""" + + message: str | None = None + """Human-readable promotion message. Does not include the expiry timestamp; consumers may + format endsAt and append it. + """ + + @staticmethod + def from_dict(obj: Any) -> 'ModelBillingPromo': + assert isinstance(obj, dict) + ends_at = from_str(obj.get("endsAt")) + discount_percent = from_union([from_float, from_none], obj.get("discountPercent")) + id = from_union([from_str, from_none], obj.get("id")) + message = from_union([from_str, from_none], obj.get("message")) + return ModelBillingPromo(ends_at, discount_percent, id, message) + + def to_dict(self) -> dict: + result: dict = {} + result["endsAt"] = from_str(self.ends_at) + if self.discount_percent is not None: + result["discountPercent"] = from_union([to_float, from_none], self.discount_percent) + if self.id is not None: + result["id"] = from_union([from_str, from_none], self.id) + if self.message is not None: + result["message"] = from_union([from_str, from_none], self.message) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelBillingTokenPricesLongContext: """Long context tier pricing (available for models with extended context windows)""" @@ -3587,6 +4386,7 @@ def to_dict(self) -> dict: result["outputPrice"] = from_union([to_float, from_none], self.output_price) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelCapabilitiesLimitsVision: """Vision-specific limits""" @@ -3615,31 +4415,7 @@ def to_dict(self) -> dict: result["supported_media_types"] = from_list(from_str, self.supported_media_types) return result -@dataclass -class ModelCapabilitiesSupports: - """Feature flags indicating what the model supports""" - - reasoning_effort: bool | None = None - """Whether this model supports reasoning effort configuration""" - - vision: bool | None = None - """Whether this model supports vision/image input""" - - @staticmethod - def from_dict(obj: Any) -> 'ModelCapabilitiesSupports': - assert isinstance(obj, dict) - reasoning_effort = from_union([from_bool, from_none], obj.get("reasoningEffort")) - vision = from_union([from_bool, from_none], obj.get("vision")) - return ModelCapabilitiesSupports(reasoning_effort, vision) - - def to_dict(self) -> dict: - result: dict = {} - if self.reasoning_effort is not None: - result["reasoningEffort"] = from_union([from_bool, from_none], self.reasoning_effort) - if self.vision is not None: - result["vision"] = from_union([from_bool, from_none], self.vision) - return result - +# Experimental: this type is part of an experimental API and may change or be removed. class ModelPickerPriceCategory(Enum): """Relative cost tier for token-based billing users""" @@ -3648,6 +4424,7 @@ class ModelPickerPriceCategory(Enum): MEDIUM = "medium" VERY_HIGH = "very_high" +# Experimental: this type is part of an experimental API and may change or be removed. class ModelPolicyState(Enum): """Current policy state for this model""" @@ -3687,32 +4464,6 @@ def to_dict(self) -> dict: result["supported_media_types"] = from_union([lambda x: from_list(from_str, x), from_none], self.supported_media_types) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ModelCapabilitiesOverrideSupports: - """Feature flags indicating what the model supports""" - - reasoning_effort: bool | None = None - """Whether this model supports reasoning effort configuration""" - - vision: bool | None = None - """Whether this model supports vision/image input""" - - @staticmethod - def from_dict(obj: Any) -> 'ModelCapabilitiesOverrideSupports': - assert isinstance(obj, dict) - reasoning_effort = from_union([from_bool, from_none], obj.get("reasoningEffort")) - vision = from_union([from_bool, from_none], obj.get("vision")) - return ModelCapabilitiesOverrideSupports(reasoning_effort, vision) - - def to_dict(self) -> dict: - result: dict = {} - if self.reasoning_effort is not None: - result["reasoningEffort"] = from_union([from_bool, from_none], self.reasoning_effort) - if self.vision is not None: - result["vision"] = from_union([from_bool, from_none], self.vision) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelListRequest: @@ -3795,6 +4546,7 @@ def to_dict(self) -> dict: result["modelId"] = from_union([from_str, from_none], self.model_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelsListRequest: git_hub_token: str | None = None @@ -3948,8 +4700,9 @@ class ProviderWireAPI(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class OptionsUpdateAdditionalContentExclusionPolicyRuleSource: - """Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type.""" - + """Source descriptor for a `session.options.update` content-exclusion rule, with source name + and type. + """ name: str type: str @@ -3999,8 +4752,9 @@ class OptionsUpdateToolFilterPrecedence(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PendingPermissionRequest: - """Schema for the `PendingPermissionRequest` type.""" - + """Pending permission prompt reconstructed from event history, with request ID and + user-facing prompt details. + """ request: PermissionPromptRequest """The user-facing permission prompt details (commands, write, read, mcp, url, memory, custom-tool, path, hook) @@ -4452,8 +5206,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsConfigureAdditionalContentExclusionPolicyRuleSource: - """Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type.""" - + """Source descriptor for a `session.permissions.configure` content-exclusion rule, with + source name and type. + """ name: str type: str @@ -4761,6 +5516,7 @@ def to_dict(self) -> dict: result["success"] = from_bool(self.success) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PingRequest: """Optional message to echo back to the caller.""" @@ -4780,6 +5536,7 @@ def to_dict(self) -> dict: result["message"] = from_union([from_str, from_none], self.message) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PingResult: """Server liveness response, including the echoed message, current server timestamp, and @@ -4924,7 +5681,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class Plugin: - """Schema for the `Plugin` type.""" + """Session plugin metadata, with name, marketplace, optional version, and enabled state.""" enabled: bool """Whether the plugin is currently enabled""" @@ -4990,7 +5747,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PluginsMarketplacesAddRequest: - """Marketplace source to register.""" + """Marketplace source and optional working directory for relative-path resolution.""" source: str """Marketplace source. Accepts the same forms as the CLI: "owner/repo" or "owner/repo#ref" @@ -4998,17 +5755,24 @@ class PluginsMarketplacesAddRequest: (user@host:path), or a local path. The marketplace's own name (from its manifest) is used as the registration key. """ + working_directory: str | None = None + """Working directory used to resolve relative local paths in `source`. Defaults to the + server's current working directory. + """ @staticmethod def from_dict(obj: Any) -> 'PluginsMarketplacesAddRequest': assert isinstance(obj, dict) source = from_str(obj.get("source")) - return PluginsMarketplacesAddRequest(source) + working_directory = from_union([from_str, from_none], obj.get("workingDirectory")) + return PluginsMarketplacesAddRequest(source, working_directory) def to_dict(self) -> dict: result: dict = {} result["source"] = from_str(self.source) - return result + if self.working_directory is not None: + result["workingDirectory"] = from_union([from_str, from_none], self.working_directory) + return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass @@ -5087,6 +5851,11 @@ class PluginsReloadRequest: reload_custom_agents: bool | None = None """Re-run custom-agent discovery after refreshing plugins. Defaults to true.""" + reload_extensions: bool | None = None + """Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) + after refreshing plugins. Defaults to true. Has no effect when the session has no active + extension controller (e.g. extensions were not requested for the session). + """ reload_hooks: bool | None = None """Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). @@ -5099,9 +5868,10 @@ def from_dict(obj: Any) -> 'PluginsReloadRequest': assert isinstance(obj, dict) defer_repo_hooks = from_union([from_bool, from_none], obj.get("deferRepoHooks")) reload_custom_agents = from_union([from_bool, from_none], obj.get("reloadCustomAgents")) + reload_extensions = from_union([from_bool, from_none], obj.get("reloadExtensions")) reload_hooks = from_union([from_bool, from_none], obj.get("reloadHooks")) reload_mcp = from_union([from_bool, from_none], obj.get("reloadMcp")) - return PluginsReloadRequest(defer_repo_hooks, reload_custom_agents, reload_hooks, reload_mcp) + return PluginsReloadRequest(defer_repo_hooks, reload_custom_agents, reload_extensions, reload_hooks, reload_mcp) def to_dict(self) -> dict: result: dict = {} @@ -5109,31 +5879,14 @@ def to_dict(self) -> dict: result["deferRepoHooks"] = from_union([from_bool, from_none], self.defer_repo_hooks) if self.reload_custom_agents is not None: result["reloadCustomAgents"] = from_union([from_bool, from_none], self.reload_custom_agents) + if self.reload_extensions is not None: + result["reloadExtensions"] = from_union([from_bool, from_none], self.reload_extensions) if self.reload_hooks is not None: result["reloadHooks"] = from_union([from_bool, from_none], self.reload_hooks) if self.reload_mcp is not None: result["reloadMcp"] = from_union([from_bool, from_none], self.reload_mcp) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionsPollSpawnedSessionsEvent: - """Schema for the `SessionsPollSpawnedSessionsEvent` type.""" - - session_id: str - """Session id of the newly-spawned session.""" - - @staticmethod - def from_dict(obj: Any) -> 'SessionsPollSpawnedSessionsEvent': - assert isinstance(obj, dict) - session_id = from_str(obj.get("sessionId")) - return SessionsPollSpawnedSessionsEvent(session_id) - - def to_dict(self) -> dict: - result: dict = {} - result["sessionId"] = from_str(self.session_id) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ProviderAddResult: @@ -5216,11 +5969,55 @@ def to_dict(self) -> dict: result["token"] = from_str(self.token) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushGitHubRepoRef: + """Repository the commit belongs to + + Pointer to a GitHub repository. + + Repository the release belongs to + + Repository the workflow run belongs to + + Repository pointer + + Repository the file lives in + + Repository the revision belongs to + """ + name: str + """Repository name (without owner)""" + + owner: str + """Repository owner login (user or organization)""" + + id: int | None = None + """Numeric GitHub repository id""" + + @staticmethod + def from_dict(obj: Any) -> 'PushGitHubRepoRef': + assert isinstance(obj, dict) + name = from_str(obj.get("name")) + owner = from_str(obj.get("owner")) + id = from_union([from_int, from_none], obj.get("id")) + return PushGitHubRepoRef(name, owner, id) + + def to_dict(self) -> dict: + result: dict = {} + result["name"] = from_str(self.name) + result["owner"] = from_str(self.owner) + if self.id is not None: + result["id"] = from_union([from_int, from_none], self.id) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PushAttachmentFileLineRange: - """Optional line range to scope the attachment to a specific section of the file""" + """Optional line range to scope the attachment to a specific section of the file + Line range the snippet covers + """ end: int """End line number (1-based, inclusive)""" @@ -5300,7 +6097,16 @@ class PushAttachmentType(Enum): DIRECTORY = "directory" EXTENSION_CONTEXT = "extension_context" FILE = "file" + GITHUB_ACTIONS_JOB = "github_actions_job" + GITHUB_COMMIT = "github_commit" + GITHUB_FILE = "github_file" + GITHUB_FILE_DIFF = "github_file_diff" GITHUB_REFERENCE = "github_reference" + GITHUB_RELEASE = "github_release" + GITHUB_REPOSITORY = "github_repository" + GITHUB_SNIPPET = "github_snippet" + GITHUB_TREE_COMPARISON = "github_tree_comparison" + GITHUB_URL = "github_url" SELECTION = "selection" class PushAttachmentBlobType(Enum): @@ -5309,10 +6115,37 @@ class PushAttachmentBlobType(Enum): class PushAttachmentFileType(Enum): FILE = "file" +class PushAttachmentGitHubActionsJobType(Enum): + GITHUB_ACTIONS_JOB = "github_actions_job" + +class PushAttachmentGitHubCommitType(Enum): + GITHUB_COMMIT = "github_commit" + +class PushAttachmentGitHubFileType(Enum): + GITHUB_FILE = "github_file" + +class PushAttachmentGitHubFileDiffType(Enum): + GITHUB_FILE_DIFF = "github_file_diff" + # Experimental: this type is part of an experimental API and may change or be removed. class PushAttachmentGitHubReferenceType(Enum): GITHUB_REFERENCE = "github_reference" +class PushAttachmentGitHubReleaseType(Enum): + GITHUB_RELEASE = "github_release" + +class PushAttachmentGitHubRepositoryType(Enum): + GITHUB_REPOSITORY = "github_repository" + +class PushAttachmentGitHubSnippetType(Enum): + GITHUB_SNIPPET = "github_snippet" + +class PushAttachmentGitHubTreeComparisonType(Enum): + GITHUB_TREE_COMPARISON = "github_tree_comparison" + +class PushAttachmentGitHubURLType(Enum): + GITHUB_URL = "github_url" + class PushAttachmentSelectionType(Enum): SELECTION = "selection" @@ -5347,8 +6180,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class QueuedCommandHandled: - """Schema for the `QueuedCommandHandled` type.""" - + """Queued-command response indicating the host executed the command, with an optional flag + to stop queue processing. + """ handled: ClassVar[str] = "true" """The host actually executed the queued command.""" @@ -5373,8 +6207,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class QueuedCommandNotHandled: - """Schema for the `QueuedCommandNotHandled` type.""" - + """Queued-command response indicating the host did not execute the command and the queue may + continue. + """ handled: ClassVar[str] = "false" """The host did not execute the queued command. Unblocks the queue without claiming the command was processed (e.g. when the handler threw before completing). @@ -5399,16 +6234,18 @@ class RegisterEventInterestParams: """The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly - (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates the full - interactive OAuth flow to the consumer; when no interest is registered the runtime - installs a browserless fallback that silently reuses cached tokens). SDK clients that - long-poll events do NOT automatically appear as listeners to these gating checks — they - must explicitly call `registerInterest` for each event type they want the runtime to - count as having a consumer. Multiple registrations for the same event type from the same - or different consumers are tracked independently and must each be released. See: - `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, - `user_input.requested`, `elicitation.requested`, `command.queued`, - `exit_plan_mode.requested`. + (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive + OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest + is registered the runtime still attempts non-interactive reconnect from cached or + refreshable tokens, and only marks the server `needs-auth` if usable credentials are + unavailable — it does not open a browser or start interactive OAuth without a consumer). + SDK clients that long-poll events do NOT automatically appear as listeners to these + gating checks — they must explicitly call `registerInterest` for each event type they + want the runtime to count as having a consumer. Multiple registrations for the same event + type from the same or different consumers are tracked independently and must each be + released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, + `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, + `command.queued`, `exit_plan_mode.requested`. """ @staticmethod @@ -5795,37 +6632,25 @@ def to_dict(self) -> dict: class SandboxConfigUserPolicyNetwork: """Network rules to merge into the base policy.""" - allowed_hosts: list[str] | None = None - """Hosts allowed in addition to the base policy.""" - allow_local_network: bool | None = None """Whether traffic to local/loopback addresses is allowed.""" allow_outbound: bool | None = None """Whether outbound network traffic is allowed at all.""" - blocked_hosts: list[str] | None = None - """Hosts explicitly blocked.""" - @staticmethod def from_dict(obj: Any) -> 'SandboxConfigUserPolicyNetwork': assert isinstance(obj, dict) - allowed_hosts = from_union([lambda x: from_list(from_str, x), from_none], obj.get("allowedHosts")) allow_local_network = from_union([from_bool, from_none], obj.get("allowLocalNetwork")) allow_outbound = from_union([from_bool, from_none], obj.get("allowOutbound")) - blocked_hosts = from_union([lambda x: from_list(from_str, x), from_none], obj.get("blockedHosts")) - return SandboxConfigUserPolicyNetwork(allowed_hosts, allow_local_network, allow_outbound, blocked_hosts) + return SandboxConfigUserPolicyNetwork(allow_local_network, allow_outbound) def to_dict(self) -> dict: result: dict = {} - if self.allowed_hosts is not None: - result["allowedHosts"] = from_union([lambda x: from_list(from_str, x), from_none], self.allowed_hosts) if self.allow_local_network is not None: result["allowLocalNetwork"] = from_union([from_bool, from_none], self.allow_local_network) if self.allow_outbound is not None: result["allowOutbound"] = from_union([from_bool, from_none], self.allow_outbound) - if self.blocked_hosts is not None: - result["blockedHosts"] = from_union([lambda x: from_list(from_str, x), from_none], self.blocked_hosts) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -5853,7 +6678,8 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ScheduleEntry: - """Schema for the `ScheduleEntry` type. + """Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, + recurrence, and next run time. The removed entry, or omitted if no entry matched. """ @@ -5944,6 +6770,7 @@ def to_dict(self) -> dict: result["id"] = from_int(self.id) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SecretsAddFilterValuesRequest: """Secret values to add to the redaction filter.""" @@ -5962,6 +6789,7 @@ def to_dict(self) -> dict: result["values"] = from_list(from_str, self.values) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SecretsAddFilterValuesResult: """Confirmation that the secret values were registered.""" @@ -5984,6 +6812,9 @@ def to_dict(self) -> dict: class SendAgentMode(Enum): """The UI mode the agent was in when this message was sent. Defaults to the session's current mode. + + The UI mode the agent was in when these messages were sent. Defaults to the session's + current mode. """ AUTOPILOT = "autopilot" INTERACTIVE = "interactive" @@ -6020,14 +6851,96 @@ def to_dict(self) -> dict: result["instanceId"] = from_union([from_str, from_none], self.instance_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SendMessageItem: + """A single user message to append to the session as part of a `session.sendMessages` turn""" + + prompt: str + """The user message text""" + + attachments: list[Attachment] | None = None + """Optional attachments (files, directories, selections, blobs, GitHub references) to + include with this message + """ + # Internal: this field is an internal SDK API and is not part of the public surface. + billable: bool | None = None + """If false, this message will not trigger a Premium Request Unit charge. User messages + default to billable. + """ + display_prompt: str | None = None + """If provided, this is shown in the timeline instead of `prompt`""" + + required_tool: str | None = None + """If set, the request will fail if the named tool is not available when this message is + among the user messages at the start of the current exchange + """ + # Internal: this field is an internal SDK API and is not part of the public surface. + source: str | None = None + """Optional provenance tag copied to the resulting user.message event. Must match one of + three forms: the literal `system`, `command-` for messages originating from a + command (e.g. slash command, Mission Control command), or `schedule-` for + messages originating from a scheduled job. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SendMessageItem': + assert isinstance(obj, dict) + prompt = from_str(obj.get("prompt")) + attachments = from_union([lambda x: from_list(Attachment.from_dict, x), from_none], obj.get("attachments")) + billable = from_union([from_bool, from_none], obj.get("billable")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + required_tool = from_union([from_str, from_none], obj.get("requiredTool")) + source = from_union([from_str, from_none], obj.get("source")) + return SendMessageItem(prompt, attachments, billable, display_prompt, required_tool, source) + + def to_dict(self) -> dict: + result: dict = {} + result["prompt"] = from_str(self.prompt) + if self.attachments is not None: + result["attachments"] = from_union([lambda x: from_list(lambda x: to_class(Attachment, x), x), from_none], self.attachments) + if self.billable is not None: + result["billable"] = from_union([from_bool, from_none], self.billable) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + if self.required_tool is not None: + result["requiredTool"] = from_union([from_str, from_none], self.required_tool) + if self.source is not None: + result["source"] = from_union([from_str, from_none], self.source) + return result + # Experimental: this type is part of an experimental API and may change or be removed. class SendMode(Enum): - """How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` + """How to deliver the messages. `enqueue` (default) appends to the message queue. + `immediate` interjects during an in-progress turn. + + How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. """ ENQUEUE = "enqueue" IMMEDIATE = "immediate" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SendMessagesResult: + """Result of sending zero or more user messages""" + + message_ids: list[str] + """Unique identifiers assigned to the messages, one per provided message in order. Empty + when no messages were provided. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SendMessagesResult': + assert isinstance(obj, dict) + message_ids = from_list(from_str, obj.get("messageIds")) + return SendMessagesResult(message_ids) + + def to_dict(self) -> dict: + result: dict = {} + result["messageIds"] = from_list(from_str, self.message_ids) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SendResult: @@ -6047,10 +6960,12 @@ def to_dict(self) -> dict: result["messageId"] = from_str(self.message_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ServerSkill: - """Schema for the `ServerSkill` type.""" - + """Server-side skill metadata, including name, description, source, enabled/invocable state, + path, project path, and argument hint. + """ description: str """Description of what the skill does""" @@ -6431,6 +7346,7 @@ def to_dict(self) -> dict: result["recursive"] = from_union([from_bool, from_none], self.recursive) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionFSSetProviderCapabilities: """Optional capabilities declared by the provider""" @@ -6450,12 +7366,14 @@ def to_dict(self) -> dict: result["sqlite"] = from_union([from_bool, from_none], self.sqlite) return result +# Experimental: this type is part of an experimental API and may change or be removed. class SessionFSSetProviderConventions(Enum): """Path conventions used by this filesystem""" POSIX = "posix" WINDOWS = "windows" +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionFSSetProviderResult: """Indicates whether the calling client was registered as the session filesystem provider.""" @@ -6664,37 +7582,10 @@ def to_dict(self) -> dict: result["startupPrompts"] = from_list(from_str, self.startup_prompts) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionModelList: - """The list of models available to this session.""" - - list: list[Any] - """Available models, ordered with the most preferred default first. Includes both Copilot - (CAPI) models and any registry BYOK models; a BYOK model appears under its - provider-qualified selection id (`provider/id`). - """ - quota_snapshots: dict[str, Any] | None = None - """Per-quota snapshots returned alongside the model list, keyed by quota type.""" - - @staticmethod - def from_dict(obj: Any) -> 'SessionModelList': - assert isinstance(obj, dict) - list = from_list(lambda x: x, obj.get("list")) - quota_snapshots = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("quotaSnapshots")) - return SessionModelList(list, quota_snapshots) - - def to_dict(self) -> dict: - result: dict = {} - result["list"] = from_list(lambda x: x, self.list) - if self.quota_snapshots is not None: - result["quotaSnapshots"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.quota_snapshots) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource: - """Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type.""" + """Source descriptor for a `sessions.open` content-exclusion rule, with source name and type.""" name: str type: str @@ -6796,10 +7687,14 @@ class SessionSetCredentialsParams: credentials: AuthInfo | None = None """The new auth credentials to install on the session. When omitted or `undefined`, the call - is a no-op and the session's existing credentials are preserved. The runtime stores the - value verbatim and uses it for outbound model/API requests; it does NOT re-validate or - re-fetch the associated Copilot user response. Several variants carry secret material; - treat this method's params as containing secrets at rest and in transit. + is a no-op and the session's existing credentials are preserved. The runtime installs the + supplied value immediately for outbound model/API requests. When the credential carries a + raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally + re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous + install) so plan/quota/billing metadata regains fidelity; on resolution failure the + verbatim credential remains installed. It does NOT otherwise validate the credential. + Several variants carry secret material; treat this method's params as containing secrets + at rest and in transit. """ @staticmethod @@ -6822,15 +7717,265 @@ class SessionSetCredentialsResult: success: bool """Whether the operation succeeded""" + copilot_user_resolved: bool | None = None + """Whether the session ended up with a populated `copilotUser` for the installed + credentials. `true` when the supplied credential already carried `copilotUser` or it was + successfully re-resolved server-side. `false` when the credential is installed without + `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from + the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In + both `false` cases the token swap still applied, but plan/quota/billing metadata is + degraded. Present whenever a credential was supplied; omitted only when no credential was + supplied (no-op call). + """ + @staticmethod def from_dict(obj: Any) -> 'SessionSetCredentialsResult': assert isinstance(obj, dict) success = from_bool(obj.get("success")) - return SessionSetCredentialsResult(success) + copilot_user_resolved = from_union([from_bool, from_none], obj.get("copilotUserResolved")) + return SessionSetCredentialsResult(success, copilot_user_resolved) def to_dict(self) -> dict: result: dict = {} result["success"] = from_bool(self.success) + if self.copilot_user_resolved is not None: + result["copilotUserResolved"] = from_union([from_bool, from_none], self.copilot_user_resolved) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsBuiltInToolAvailabilitySnapshot: + """Availability of built-in job tools surfaced to boundary consumers.""" + + create_pull_request: bool | None = None + report_progress: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsBuiltInToolAvailabilitySnapshot': + assert isinstance(obj, dict) + create_pull_request = from_union([from_bool, from_none], obj.get("createPullRequest")) + report_progress = from_union([from_bool, from_none], obj.get("reportProgress")) + return SessionSettingsBuiltInToolAvailabilitySnapshot(create_pull_request, report_progress) + + def to_dict(self) -> dict: + result: dict = {} + if self.create_pull_request is not None: + result["createPullRequest"] = from_union([from_bool, from_none], self.create_pull_request) + if self.report_progress is not None: + result["reportProgress"] = from_union([from_bool, from_none], self.report_progress) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class SessionSettingsPredicateName(Enum): + """Predicate name. The runtime owns the raw feature-flag names and composition logic. + + Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names + are intentionally not part of the contract. + """ + CAP_CLAUDE_OPUS_TOKEN_LIMITS_ENABLED = "capClaudeOpusTokenLimitsEnabled" + CCA_USE_TS_AUTOFIND_ENABLED = "ccaUseTsAutofindEnabled" + CHRONICLE_ENABLED = "chronicleEnabled" + CODEQL_CHECKER_ENABLED = "codeqlCheckerEnabled" + CODE_REVIEW_FEATURE_ENABLED = "codeReviewFeatureEnabled" + CONTENT_EXCLUSION_SELF_FETCH_ENABLED = "contentExclusionSelfFetchEnabled" + CO_AUTHOR_HOOK_ENABLED = "coAuthorHookEnabled" + DEPENDABOT_CHECKER_ENABLED = "dependabotCheckerEnabled" + DEPENDENCY_CHECKER_ENABLED = "dependencyCheckerEnabled" + PARALLEL_VALIDATION_ENABLED = "parallelValidationEnabled" + RUNTIME_TIMING_TELEMETRY_ENABLED = "runtimeTimingTelemetryEnabled" + SECURITY_TOOLS_ENABLED = "securityToolsEnabled" + THIRD_PARTY_SECURITY_PROMPT_ENABLED = "thirdPartySecurityPromptEnabled" + TRIVIAL_CHANGE_ENABLED = "trivialChangeEnabled" + TRIVIAL_CHANGE_ENABLED_FOR_CODE_REVIEW = "trivialChangeEnabledForCodeReview" + TRIVIAL_CHANGE_ENABLED_FOR_TOOL = "trivialChangeEnabledForTool" + TRIVIAL_CHANGE_SKIP_ENABLED = "trivialChangeSkipEnabled" + TRIVIAL_CHANGE_SKIP_ENABLED_FOR_CODE_REVIEW = "trivialChangeSkipEnabledForCodeReview" + TRIVIAL_CHANGE_SKIP_ENABLED_FOR_TOOL = "trivialChangeSkipEnabledForTool" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsEvaluatePredicateResult: + """Result of evaluating a Rust-owned settings predicate.""" + + enabled: bool + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsEvaluatePredicateResult': + assert isinstance(obj, dict) + enabled = from_bool(obj.get("enabled")) + return SessionSettingsEvaluatePredicateResult(enabled) + + def to_dict(self) -> dict: + result: dict = {} + result["enabled"] = from_bool(self.enabled) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsModelSnapshot: + """Redacted model routing settings for a session.""" + + callback_url: str | None = None + default_reasoning_effort: str | None = None + instance_id: str | None = None + model: str | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsModelSnapshot': + assert isinstance(obj, dict) + callback_url = from_union([from_str, from_none], obj.get("callbackUrl")) + default_reasoning_effort = from_union([from_str, from_none], obj.get("defaultReasoningEffort")) + instance_id = from_union([from_str, from_none], obj.get("instanceId")) + model = from_union([from_str, from_none], obj.get("model")) + return SessionSettingsModelSnapshot(callback_url, default_reasoning_effort, instance_id, model) + + def to_dict(self) -> dict: + result: dict = {} + if self.callback_url is not None: + result["callbackUrl"] = from_union([from_str, from_none], self.callback_url) + if self.default_reasoning_effort is not None: + result["defaultReasoningEffort"] = from_union([from_str, from_none], self.default_reasoning_effort) + if self.instance_id is not None: + result["instanceId"] = from_union([from_str, from_none], self.instance_id) + if self.model is not None: + result["model"] = from_union([from_str, from_none], self.model) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsOnlineEvaluationSnapshot: + """Online-evaluation settings safe to expose across the SDK boundary.""" + + disable_online_evaluation: bool | None = None + enable_online_evaluation_output_file: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsOnlineEvaluationSnapshot': + assert isinstance(obj, dict) + disable_online_evaluation = from_union([from_bool, from_none], obj.get("disableOnlineEvaluation")) + enable_online_evaluation_output_file = from_union([from_bool, from_none], obj.get("enableOnlineEvaluationOutputFile")) + return SessionSettingsOnlineEvaluationSnapshot(disable_online_evaluation, enable_online_evaluation_output_file) + + def to_dict(self) -> dict: + result: dict = {} + if self.disable_online_evaluation is not None: + result["disableOnlineEvaluation"] = from_union([from_bool, from_none], self.disable_online_evaluation) + if self.enable_online_evaluation_output_file is not None: + result["enableOnlineEvaluationOutputFile"] = from_union([from_bool, from_none], self.enable_online_evaluation_output_file) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsRepoSnapshot: + """Redacted repository and GitHub host settings for a session.""" + + branch: str | None = None + commit: str | None = None + host: str | None = None + host_protocol: str | None = None + id: float | None = None + name: str | None = None + owner_id: float | None = None + owner_name: str | None = None + pr_commit_count: float | None = None + read_write: bool | None = None + secret_scanning_url: str | None = None + server_url: str | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsRepoSnapshot': + assert isinstance(obj, dict) + branch = from_union([from_str, from_none], obj.get("branch")) + commit = from_union([from_str, from_none], obj.get("commit")) + host = from_union([from_str, from_none], obj.get("host")) + host_protocol = from_union([from_str, from_none], obj.get("hostProtocol")) + id = from_union([from_float, from_none], obj.get("id")) + name = from_union([from_str, from_none], obj.get("name")) + owner_id = from_union([from_float, from_none], obj.get("ownerId")) + owner_name = from_union([from_str, from_none], obj.get("ownerName")) + pr_commit_count = from_union([from_float, from_none], obj.get("prCommitCount")) + read_write = from_union([from_bool, from_none], obj.get("readWrite")) + secret_scanning_url = from_union([from_str, from_none], obj.get("secretScanningUrl")) + server_url = from_union([from_str, from_none], obj.get("serverUrl")) + return SessionSettingsRepoSnapshot(branch, commit, host, host_protocol, id, name, owner_id, owner_name, pr_commit_count, read_write, secret_scanning_url, server_url) + + def to_dict(self) -> dict: + result: dict = {} + if self.branch is not None: + result["branch"] = from_union([from_str, from_none], self.branch) + if self.commit is not None: + result["commit"] = from_union([from_str, from_none], self.commit) + if self.host is not None: + result["host"] = from_union([from_str, from_none], self.host) + if self.host_protocol is not None: + result["hostProtocol"] = from_union([from_str, from_none], self.host_protocol) + if self.id is not None: + result["id"] = from_union([to_float, from_none], self.id) + if self.name is not None: + result["name"] = from_union([from_str, from_none], self.name) + if self.owner_id is not None: + result["ownerId"] = from_union([to_float, from_none], self.owner_id) + if self.owner_name is not None: + result["ownerName"] = from_union([from_str, from_none], self.owner_name) + if self.pr_commit_count is not None: + result["prCommitCount"] = from_union([to_float, from_none], self.pr_commit_count) + if self.read_write is not None: + result["readWrite"] = from_union([from_bool, from_none], self.read_write) + if self.secret_scanning_url is not None: + result["secretScanningUrl"] = from_union([from_str, from_none], self.secret_scanning_url) + if self.server_url is not None: + result["serverUrl"] = from_union([from_str, from_none], self.server_url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsValidationSnapshot: + """Redacted validation and memory-tool settings for a session.""" + + advisory_enabled: bool | None = None + codeql_enabled: bool | None = None + code_review_enabled: bool | None = None + code_review_model: str | None = None + dependabot_timeout: float | None = None + memory_store_enabled: bool | None = None + memory_vote_enabled: bool | None = None + secret_scanning_enabled: bool | None = None + timeout: float | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsValidationSnapshot': + assert isinstance(obj, dict) + advisory_enabled = from_union([from_bool, from_none], obj.get("advisoryEnabled")) + codeql_enabled = from_union([from_bool, from_none], obj.get("codeqlEnabled")) + code_review_enabled = from_union([from_bool, from_none], obj.get("codeReviewEnabled")) + code_review_model = from_union([from_str, from_none], obj.get("codeReviewModel")) + dependabot_timeout = from_union([from_float, from_none], obj.get("dependabotTimeout")) + memory_store_enabled = from_union([from_bool, from_none], obj.get("memoryStoreEnabled")) + memory_vote_enabled = from_union([from_bool, from_none], obj.get("memoryVoteEnabled")) + secret_scanning_enabled = from_union([from_bool, from_none], obj.get("secretScanningEnabled")) + timeout = from_union([from_float, from_none], obj.get("timeout")) + return SessionSettingsValidationSnapshot(advisory_enabled, codeql_enabled, code_review_enabled, code_review_model, dependabot_timeout, memory_store_enabled, memory_vote_enabled, secret_scanning_enabled, timeout) + + def to_dict(self) -> dict: + result: dict = {} + if self.advisory_enabled is not None: + result["advisoryEnabled"] = from_union([from_bool, from_none], self.advisory_enabled) + if self.codeql_enabled is not None: + result["codeqlEnabled"] = from_union([from_bool, from_none], self.codeql_enabled) + if self.code_review_enabled is not None: + result["codeReviewEnabled"] = from_union([from_bool, from_none], self.code_review_enabled) + if self.code_review_model is not None: + result["codeReviewModel"] = from_union([from_str, from_none], self.code_review_model) + if self.dependabot_timeout is not None: + result["dependabotTimeout"] = from_union([to_float, from_none], self.dependabot_timeout) + if self.memory_store_enabled is not None: + result["memoryStoreEnabled"] = from_union([from_bool, from_none], self.memory_store_enabled) + if self.memory_vote_enabled is not None: + result["memoryVoteEnabled"] = from_union([from_bool, from_none], self.memory_vote_enabled) + if self.secret_scanning_enabled is not None: + result["secretScanningEnabled"] = from_union([from_bool, from_none], self.secret_scanning_enabled) + if self.timeout is not None: + result["timeout"] = from_union([to_float, from_none], self.timeout) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -6888,19 +8033,43 @@ class SessionUpdateOptionsResult: success: bool """Whether the operation succeeded""" + plugin_hook_count: int | None = None + """Number of hooks loaded from installed plugins, returned when installedPlugins is updated""" + @staticmethod def from_dict(obj: Any) -> 'SessionUpdateOptionsResult': assert isinstance(obj, dict) success = from_bool(obj.get("success")) - return SessionUpdateOptionsResult(success) + plugin_hook_count = from_union([from_int, from_none], obj.get("pluginHookCount")) + return SessionUpdateOptionsResult(success, plugin_hook_count) def to_dict(self) -> dict: result: dict = {} result["success"] = from_bool(self.success) + if self.plugin_hook_count is not None: + result["pluginHookCount"] = from_union([from_int, from_none], self.plugin_hook_count) return result # Experimental: this type is part of an experimental API and may change or be removed. -@dataclass +class SessionVisibilityStatus(Enum): + """Sharing status for a synced session. "repo" makes the session visible to anyone with read + access to the repository; "unshared" restricts it to the creator and collaborators. + + Current sharing status. Absent when the session is not synced or the status could not be + retrieved (e.g. the user is not authenticated). + + Sharing status to apply. "repo" makes the session visible to repository readers; + "unshared" restricts it to the creator and collaborators. + + Effective sharing status after the update. May differ from the requested status for task + types that are already visible to repository readers by default. Absent when the update + could not be applied (e.g. the session is not synced or the user is not authenticated). + """ + REPO = "repo" + UNSHARED = "unshared" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass class SessionsBulkDeleteRequest: """Session IDs to close, deactivate, and delete from disk.""" @@ -7311,33 +8480,6 @@ class SessionsOpenResumeKind(Enum): class SessionsOpenResumeLastKind(Enum): RESUME_LAST = "resumeLast" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionsPollSpawnedSessionsRequest: - cursor: str | None = None - """Opaque cursor returned by a previous poll. Omit on the first call to receive any spawn - events buffered since the runtime started. - """ - wait_ms: int | None = None - """Milliseconds to wait for new spawn events when the cursor is at the tail. 0 (default) - returns immediately even if no events are buffered. Capped at 60000ms. - """ - - @staticmethod - def from_dict(obj: Any) -> 'SessionsPollSpawnedSessionsRequest': - assert isinstance(obj, dict) - cursor = from_union([from_str, from_none], obj.get("cursor")) - wait_ms = from_union([from_int, from_none], obj.get("waitMs")) - return SessionsPollSpawnedSessionsRequest(cursor, wait_ms) - - def to_dict(self) -> dict: - result: dict = {} - if self.cursor is not None: - result["cursor"] = from_union([from_str, from_none], self.cursor) - if self.wait_ms is not None: - result["waitMs"] = from_union([from_int, from_none], self.wait_ms) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsPruneOldRequest: @@ -7730,8 +8872,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class Skill: - """Schema for the `Skill` type.""" - + """Skill metadata available to a session, with name, description, source, enabled/invocable + state, path, plugin, and argument hint. + """ description: str """Description of what the skill does""" @@ -7813,6 +8956,7 @@ def to_dict(self) -> dict: result["name"] = from_str(self.name) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SkillsDiscoverRequest: """Optional project paths and additional skill directories to include in discovery.""" @@ -7893,46 +9037,6 @@ def to_dict(self) -> dict: result["projectPaths"] = from_union([lambda x: from_list(from_str, x), from_none], self.project_paths) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SkillsInvokedSkill: - """Schema for the `SkillsInvokedSkill` type.""" - - content: str - """Full content of the skill file""" - - invoked_at_turn: int - """Turn number when the skill was invoked""" - - name: str - """Unique identifier for the skill""" - - path: str - """Path to the SKILL.md file""" - - allowed_tools: list[str] | None = None - """Tools that should be auto-approved when this skill is active, captured at invocation time""" - - @staticmethod - def from_dict(obj: Any) -> 'SkillsInvokedSkill': - assert isinstance(obj, dict) - content = from_str(obj.get("content")) - invoked_at_turn = from_int(obj.get("invokedAtTurn")) - name = from_str(obj.get("name")) - path = from_str(obj.get("path")) - allowed_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("allowedTools")) - return SkillsInvokedSkill(content, invoked_at_turn, name, path, allowed_tools) - - def to_dict(self) -> dict: - result: dict = {} - result["content"] = from_str(self.content) - result["invokedAtTurn"] = from_int(self.invoked_at_turn) - result["name"] = from_str(self.name) - result["path"] = from_str(self.path) - if self.allowed_tools is not None: - result["allowedTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.allowed_tools) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SkillsLoadDiagnostics: @@ -7972,8 +9076,9 @@ class SlashCommandInvocationResultKind(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SlashCommandSelectSubcommandOption: - """Schema for the `SlashCommandSelectSubcommandOption` type.""" - + """Selectable slash-command subcommand option with name, description, and optional group + label. + """ description: str """Human-readable description of the subcommand""" @@ -8033,7 +9138,7 @@ class TaskAgentInfoType(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class TaskProgressLine: - """Schema for the `TaskProgressLine` type.""" + """Timestamped display line for task progress output or recent agent activity.""" message: str """Display message, e.g., "▸ bash", "✓ edit src/foo.ts\"""" @@ -8443,10 +9548,12 @@ def to_dict(self) -> dict: class TokenAuthInfoType(Enum): TOKEN = "token" +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class Tool: - """Schema for the `Tool` type.""" - + """Built-in tool metadata with identifier, optional namespaced name, description, + input-parameter schema, and usage instructions. + """ description: str """Description of what the tool does""" @@ -8501,6 +9608,7 @@ def to_dict(self) -> dict: result: dict = {} return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ToolsListRequest: """Optional model identifier whose tool overrides should be applied to the listing.""" @@ -8547,8 +9655,9 @@ class UIAutoModeSwitchResponse(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UIElicitationArrayAnyOfFieldItemsAnyOf: - """Schema for the `UIElicitationArrayAnyOfFieldItemsAnyOf` type.""" - + """Selectable option for a UI elicitation multi-select array item, with submitted value and + display label. + """ const: str """Value submitted when this option is selected.""" @@ -8586,8 +9695,9 @@ class UIElicitationSchemaPropertyStringFormat(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UIElicitationStringOneOfFieldOneOf: - """Schema for the `UIElicitationStringOneOfFieldOneOf` type.""" - + """Selectable option for a UI elicitation single-select string field, with submitted value + and display label. + """ const: str """Value submitted when this option is selected.""" @@ -8738,11 +9848,23 @@ def to_dict(self) -> dict: result["response"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.response) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class UISessionLimitsExhaustedResponseAction(Enum): + """Action selected by the user. + + User action selected for an exhausted session limit. + """ + ADD = "add" + CANCEL = "cancel" + SET = "set" + UNSET = "unset" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UIUserInputResponse: - """Schema for the `UIUserInputResponse` type.""" - + """User response for a pending user-input request, with answer text and whether it was typed + freeform. + """ answer: str """The user's answer text""" @@ -8891,7 +10013,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UsageMetricsModelMetricTokenDetail: - """Schema for the `UsageMetricsModelMetricTokenDetail` type.""" + """Per-model token-detail entry containing the accumulated token count for one token type.""" token_count: int """Accumulated token count for this token type""" @@ -8950,7 +10072,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UsageMetricsTokenDetail: - """Schema for the `UsageMetricsTokenDetail` type.""" + """Session-wide token-detail entry containing the accumulated token count for one token type.""" token_count: int """Accumulated token count for this token type""" @@ -8969,6 +10091,81 @@ def to_dict(self) -> dict: class UserAuthInfoType(Enum): USER = "user" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UserSettingMetadata: + """A single user setting's effective value alongside its default, so consumers can render + settings left at their default. + """ + default: Any + """The centrally-known default for this setting (null when no default is registered).""" + + is_default: bool + """True when the user has not set an explicit value for this setting (i.e. it is left at its + default). Reflects whether the user has overridden the key, not whether the effective + value happens to equal the default — a key explicitly set to a value identical to the + default still reports false. + """ + value: Any + """The effective value: the user's value if set, otherwise the default.""" + + @staticmethod + def from_dict(obj: Any) -> 'UserSettingMetadata': + assert isinstance(obj, dict) + default = obj.get("default") + is_default = from_bool(obj.get("isDefault")) + value = obj.get("value") + return UserSettingMetadata(default, is_default, value) + + def to_dict(self) -> dict: + result: dict = {} + result["default"] = self.default + result["isDefault"] = from_bool(self.is_default) + result["value"] = self.value + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UserSettingsSetRequest: + """Partial user settings to write to settings.json. Each top-level key is written + individually, replacing the existing value; a key whose value is null is removed. + """ + settings: Any + """Partial user settings to write, as a free-form object keyed by setting name""" + + @staticmethod + def from_dict(obj: Any) -> 'UserSettingsSetRequest': + assert isinstance(obj, dict) + settings = obj.get("settings") + return UserSettingsSetRequest(settings) + + def to_dict(self) -> dict: + result: dict = {} + result["settings"] = self.settings + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UserSettingsSetResult: + """Outcome of writing user settings.""" + + shadowed_keys: list[str] + """Top-level keys whose write landed in settings.json but is shadowed by a value still + present in the legacy config.json (config.json wins on read). The write does not take + effect until the legacy value is removed. + """ + + @staticmethod + def from_dict(obj: Any) -> 'UserSettingsSetResult': + assert isinstance(obj, dict) + shadowed_keys = from_list(from_str, obj.get("shadowedKeys")) + return UserSettingsSetResult(shadowed_keys) + + def to_dict(self) -> dict: + result: dict = {} + result["shadowedKeys"] = from_list(from_str, self.shadowed_keys) + return result + # Experimental: this type is part of an experimental API and may change or be removed. class WorkspaceDiffFileChangeType(Enum): """Type of change represented by this file diff.""" @@ -8988,35 +10185,6 @@ class WorkspaceDiffMode(Enum): SESSION = "session" UNSTAGED = "unstaged" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class WorkspacesCheckpoints: - """Schema for the `WorkspacesCheckpoints` type.""" - - filename: str - """Filename of the checkpoint within the workspace checkpoints directory""" - - number: int - """Checkpoint number assigned by the workspace manager""" - - title: str - """Human-readable checkpoint title""" - - @staticmethod - def from_dict(obj: Any) -> 'WorkspacesCheckpoints': - assert isinstance(obj, dict) - filename = from_str(obj.get("filename")) - number = from_int(obj.get("number")) - title = from_str(obj.get("title")) - return WorkspacesCheckpoints(filename, number, title) - - def to_dict(self) -> dict: - result: dict = {} - result["filename"] = from_str(self.filename) - result["number"] = from_int(self.number) - result["title"] = from_str(self.title) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkspacesCreateFileRequest: @@ -9230,6 +10398,7 @@ def to_dict(self) -> dict: result["statusMessage"] = from_union([from_str, from_none], self.status_message) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountGetQuotaResult: """Quota usage snapshots for the resolved user, keyed by quota type.""" @@ -9250,9 +10419,76 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class AgentDiscoveryPath: - """Schema for the `AgentDiscoveryPath` type.""" +class ModelCapabilitiesSupports: + """Feature flags indicating what the model supports""" + + adaptive_thinking: AdaptiveThinkingSupport | None = None + """Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. + 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + """ + reasoning_effort: bool | None = None + """Whether this model supports reasoning effort configuration""" + + vision: bool | None = None + """Whether this model supports vision/image input""" + + @staticmethod + def from_dict(obj: Any) -> 'ModelCapabilitiesSupports': + assert isinstance(obj, dict) + adaptive_thinking = from_union([AdaptiveThinkingSupport, from_none], obj.get("adaptive_thinking")) + reasoning_effort = from_union([from_bool, from_none], obj.get("reasoningEffort")) + vision = from_union([from_bool, from_none], obj.get("vision")) + return ModelCapabilitiesSupports(adaptive_thinking, reasoning_effort, vision) + + def to_dict(self) -> dict: + result: dict = {} + if self.adaptive_thinking is not None: + result["adaptive_thinking"] = from_union([lambda x: to_enum(AdaptiveThinkingSupport, x), from_none], self.adaptive_thinking) + if self.reasoning_effort is not None: + result["reasoningEffort"] = from_union([from_bool, from_none], self.reasoning_effort) + if self.vision is not None: + result["vision"] = from_union([from_bool, from_none], self.vision) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ModelCapabilitiesOverrideSupports: + """Feature flags indicating what the model supports""" + + adaptive_thinking: AdaptiveThinkingSupport | None = None + """Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. + 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + """ + reasoning_effort: bool | None = None + """Whether this model supports reasoning effort configuration""" + + vision: bool | None = None + """Whether this model supports vision/image input""" + + @staticmethod + def from_dict(obj: Any) -> 'ModelCapabilitiesOverrideSupports': + assert isinstance(obj, dict) + adaptive_thinking = from_union([AdaptiveThinkingSupport, from_none], obj.get("adaptive_thinking")) + reasoning_effort = from_union([from_bool, from_none], obj.get("reasoningEffort")) + vision = from_union([from_bool, from_none], obj.get("vision")) + return ModelCapabilitiesOverrideSupports(adaptive_thinking, reasoning_effort, vision) + + def to_dict(self) -> dict: + result: dict = {} + if self.adaptive_thinking is not None: + result["adaptive_thinking"] = from_union([lambda x: to_enum(AdaptiveThinkingSupport, x), from_none], self.adaptive_thinking) + if self.reasoning_effort is not None: + result["reasoningEffort"] = from_union([from_bool, from_none], self.reasoning_effort) + if self.vision is not None: + result["vision"] = from_union([from_bool, from_none], self.vision) + return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AgentDiscoveryPath: + """Canonical directory where custom agents can be discovered or created, with scope, + preference, and optional project path. + """ path: str """Absolute path of the search/create directory (may not exist on disk yet)""" @@ -9389,73 +10625,57 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class DiscoveredCanvas: - """Canvas available in the current session.""" - - canvas_id: str - """Provider-local canvas identifier""" - - description: str - """Short, single-sentence description shown to the agent in canvas catalogs.""" - - display_name: str - """Human-readable canvas name""" - - extension_id: str - """Owning provider identifier""" +class AllowAllPermissionSetResult: + """Indicates whether the operation succeeded and reports the post-mutation state.""" - actions: list[CanvasAction] | None = None - """Actions the agent or host may invoke on an open instance""" + enabled: bool + """Authoritative full allow-all state after the mutation""" - extension_name: str | None = None - """Owning extension display name, when available""" + success: bool + """Whether the operation succeeded""" - input_schema: Any = None - """JSON Schema for canvas open input""" + mode: PermissionsAllowAllMode | None = None + """Authoritative allow-all mode after the mutation""" @staticmethod - def from_dict(obj: Any) -> 'DiscoveredCanvas': + def from_dict(obj: Any) -> 'AllowAllPermissionSetResult': assert isinstance(obj, dict) - canvas_id = from_str(obj.get("canvasId")) - description = from_str(obj.get("description")) - display_name = from_str(obj.get("displayName")) - extension_id = from_str(obj.get("extensionId")) - actions = from_union([lambda x: from_list(CanvasAction.from_dict, x), from_none], obj.get("actions")) - extension_name = from_union([from_str, from_none], obj.get("extensionName")) - input_schema = obj.get("inputSchema") - return DiscoveredCanvas(canvas_id, description, display_name, extension_id, actions, extension_name, input_schema) + enabled = from_bool(obj.get("enabled")) + success = from_bool(obj.get("success")) + mode = from_union([PermissionsAllowAllMode, from_none], obj.get("mode")) + return AllowAllPermissionSetResult(enabled, success, mode) def to_dict(self) -> dict: result: dict = {} - result["canvasId"] = from_str(self.canvas_id) - result["description"] = from_str(self.description) - result["displayName"] = from_str(self.display_name) - result["extensionId"] = from_str(self.extension_id) - if self.actions is not None: - result["actions"] = from_union([lambda x: from_list(lambda x: to_class(CanvasAction, x), x), from_none], self.actions) - if self.extension_name is not None: - result["extensionName"] = from_union([from_str, from_none], self.extension_name) - if self.input_schema is not None: - result["inputSchema"] = self.input_schema + result["enabled"] = from_bool(self.enabled) + result["success"] = from_bool(self.success) + if self.mode is not None: + result["mode"] = from_union([lambda x: to_enum(PermissionsAllowAllMode, x), from_none], self.mode) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CanvasListOpenResult: - """Live open-canvas snapshot.""" +class AllowAllPermissionState: + """Current allow-all permission mode.""" - open_canvases: list[OpenCanvasInstance] - """Currently open canvas instances""" + enabled: bool + """Whether full allow-all permissions are currently active""" + + mode: PermissionsAllowAllMode | None = None + """Current allow-all mode""" @staticmethod - def from_dict(obj: Any) -> 'CanvasListOpenResult': + def from_dict(obj: Any) -> 'AllowAllPermissionState': assert isinstance(obj, dict) - open_canvases = from_list(OpenCanvasInstance.from_dict, obj.get("openCanvases")) - return CanvasListOpenResult(open_canvases) + enabled = from_bool(obj.get("enabled")) + mode = from_union([PermissionsAllowAllMode, from_none], obj.get("mode")) + return AllowAllPermissionState(enabled, mode) def to_dict(self) -> dict: result: dict = {} - result["openCanvases"] = from_list(lambda x: to_class(OpenCanvasInstance, x), self.open_canvases) + result["enabled"] = from_bool(self.enabled) + if self.mode is not None: + result["mode"] = from_union([lambda x: to_enum(PermissionsAllowAllMode, x), from_none], self.mode) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -9466,6 +10686,10 @@ class SlashCommandInput: hint: str """Hint to display when command input has not been provided""" + choices: list[SlashCommandInputChoice] | None = None + """Optional literal choices the input accepts, each with a human-facing description; clients + may render these as selectable options + """ completion: SlashCommandInputCompletion | None = None """Optional completion hint for the input (e.g. 'directory' for filesystem path completion)""" @@ -9482,14 +10706,17 @@ class SlashCommandInput: def from_dict(obj: Any) -> 'SlashCommandInput': assert isinstance(obj, dict) hint = from_str(obj.get("hint")) + choices = from_union([lambda x: from_list(SlashCommandInputChoice.from_dict, x), from_none], obj.get("choices")) completion = from_union([SlashCommandInputCompletion, from_none], obj.get("completion")) preserve_multiline_input = from_union([from_bool, from_none], obj.get("preserveMultilineInput")) required = from_union([from_bool, from_none], obj.get("required")) - return SlashCommandInput(hint, completion, preserve_multiline_input, required) + return SlashCommandInput(hint, choices, completion, preserve_multiline_input, required) def to_dict(self) -> dict: result: dict = {} result["hint"] = from_str(self.hint) + if self.choices is not None: + result["choices"] = from_union([lambda x: from_list(lambda x: to_class(SlashCommandInputChoice, x), x), from_none], self.choices) if self.completion is not None: result["completion"] = from_union([lambda x: to_enum(SlashCommandInputCompletion, x), from_none], self.completion) if self.preserve_multiline_input is not None: @@ -9601,6 +10828,32 @@ def to_dict(self) -> dict: result["summary"] = from_union([from_str, from_none], self.summary) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MetadataContextHeaviestMessagesResult: + """The heaviest individual messages in the session's context window, most-expensive first.""" + + messages: list[ContextHeaviestMessage] + """Heaviest messages, most-expensive first.""" + + total_tokens: int + """Total token count of the current context window, so callers can compute each message's + share without a second call. + """ + + @staticmethod + def from_dict(obj: Any) -> 'MetadataContextHeaviestMessagesResult': + assert isinstance(obj, dict) + messages = from_list(ContextHeaviestMessage.from_dict, obj.get("messages")) + total_tokens = from_int(obj.get("totalTokens")) + return MetadataContextHeaviestMessagesResult(messages, total_tokens) + + def to_dict(self) -> dict: + result: dict = {} + result["messages"] = from_list(lambda x: to_class(ContextHeaviestMessage, x), self.messages) + result["totalTokens"] = from_int(self.total_tokens) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CanvasHostContextCapabilities: @@ -9621,70 +10874,215 @@ def to_dict(self) -> dict: result["canvases"] = from_union([from_bool, from_none], self.canvases) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CopilotUserResponseQuotaSnapshots: - """Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. +class DiscoveredCanvas: + """Canvas available in the current session.""" + + canvas_id: str + """Provider-local canvas identifier""" + + description: str + """Short, single-sentence description shown to the agent in canvas catalogs.""" + + display_name: str + """Human-readable canvas name""" + + extension_id: str + """Owning provider identifier""" + + actions: list[CanvasAction] | None = None + """Actions the agent or host may invoke on an open instance""" + + extension_name: str | None = None + """Owning extension display name, when available""" + + icon: str | None = None + """Host-local PNG path for the canvas icon, when supplied""" + + input_schema: Any = None + """JSON Schema for canvas open input""" + + @staticmethod + def from_dict(obj: Any) -> 'DiscoveredCanvas': + assert isinstance(obj, dict) + canvas_id = from_str(obj.get("canvasId")) + description = from_str(obj.get("description")) + display_name = from_str(obj.get("displayName")) + extension_id = from_str(obj.get("extensionId")) + actions = from_union([lambda x: from_list(CanvasAction.from_dict, x), from_none], obj.get("actions")) + extension_name = from_union([from_str, from_none], obj.get("extensionName")) + icon = from_union([from_str, from_none], obj.get("icon")) + input_schema = obj.get("inputSchema") + return DiscoveredCanvas(canvas_id, description, display_name, extension_id, actions, extension_name, icon, input_schema) + + def to_dict(self) -> dict: + result: dict = {} + result["canvasId"] = from_str(self.canvas_id) + result["description"] = from_str(self.description) + result["displayName"] = from_str(self.display_name) + result["extensionId"] = from_str(self.extension_id) + if self.actions is not None: + result["actions"] = from_union([lambda x: from_list(lambda x: to_class(CanvasAction, x), x), from_none], self.actions) + if self.extension_name is not None: + result["extensionName"] = from_union([from_str, from_none], self.extension_name) + if self.icon is not None: + result["icon"] = from_union([from_str, from_none], self.icon) + if self.input_schema is not None: + result["inputSchema"] = self.input_schema + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class OpenCanvasInstance: + """Open canvas instance snapshot.""" + + canvas_id: str + """Provider-local canvas identifier""" + + extension_id: str + """Owning provider identifier""" + + instance_id: str + """Stable caller-supplied canvas instance identifier""" + + extension_name: str | None = None + """Owning extension display name, when available""" + + icon: str | None = None + """Host-local PNG path for the canvas icon, when supplied""" + + input: Any = None + """Input supplied when the instance was opened""" + + status: str | None = None + """Provider-supplied status text""" + + title: str | None = None + """Rendered title""" + + url: str | None = None + """URL for web-rendered canvases""" + + @staticmethod + def from_dict(obj: Any) -> 'OpenCanvasInstance': + assert isinstance(obj, dict) + canvas_id = from_str(obj.get("canvasId")) + extension_id = from_str(obj.get("extensionId")) + instance_id = from_str(obj.get("instanceId")) + extension_name = from_union([from_str, from_none], obj.get("extensionName")) + icon = from_union([from_str, from_none], obj.get("icon")) + input = obj.get("input") + status = from_union([from_str, from_none], obj.get("status")) + title = from_union([from_str, from_none], obj.get("title")) + url = from_union([from_str, from_none], obj.get("url")) + return OpenCanvasInstance(canvas_id, extension_id, instance_id, extension_name, icon, input, status, title, url) + + def to_dict(self) -> dict: + result: dict = {} + result["canvasId"] = from_str(self.canvas_id) + result["extensionId"] = from_str(self.extension_id) + result["instanceId"] = from_str(self.instance_id) + if self.extension_name is not None: + result["extensionName"] = from_union([from_str, from_none], self.extension_name) + if self.icon is not None: + result["icon"] = from_union([from_str, from_none], self.icon) + if self.input is not None: + result["input"] = self.input + if self.status is not None: + result["status"] = from_union([from_str, from_none], self.status) + if self.title is not None: + result["title"] = from_union([from_str, from_none], self.title) + if self.url is not None: + result["url"] = from_union([from_str, from_none], self.url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CompletionsRequestResult: + """Host-driven completion items for the current composer input. Empty when the host returns + no items or does not support completions. + """ + items: list[SessionCompletionItem] + """Completion items in host-ranked order.""" + + @staticmethod + def from_dict(obj: Any) -> 'CompletionsRequestResult': + assert isinstance(obj, dict) + items = from_list(SessionCompletionItem.from_dict, obj.get("items")) + return CompletionsRequestResult(items) + + def to_dict(self) -> dict: + result: dict = {} + result["items"] = from_list(lambda x: to_class(SessionCompletionItem, x), self.items) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class DebugCollectLogsCollectedEntry: + """A file included in the redacted debug bundle.""" + + bundle_path: str + """Relative path of the file in the staged bundle/archive.""" + + size_bytes: int + """Redacted output size in bytes.""" + + source: DebugCollectLogsSource + """Source category for this entry.""" - Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + @staticmethod + def from_dict(obj: Any) -> 'DebugCollectLogsCollectedEntry': + assert isinstance(obj, dict) + bundle_path = from_str(obj.get("bundlePath")) + size_bytes = from_int(obj.get("sizeBytes")) + source = DebugCollectLogsSource(obj.get("source")) + return DebugCollectLogsCollectedEntry(bundle_path, size_bytes, source) + + def to_dict(self) -> dict: + result: dict = {} + result["bundlePath"] = from_str(self.bundle_path) + result["sizeBytes"] = from_int(self.size_bytes) + result["source"] = to_enum(DebugCollectLogsSource, self.source) + return result - Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class DebugCollectLogsDestination: + """Destination for the redacted debug bundle. + + Where the redacted bundle should be written. Use `archive` to produce a .tgz, or + `directory` to stage redacted files for caller-managed upload/post-processing. """ - entitlement: float | None = None - has_quota: bool | None = None - overage_count: float | None = None - overage_permitted: bool | None = None - percent_remaining: float | None = None - quota_id: str | None = None - quota_remaining: float | None = None - quota_reset_at: float | None = None - remaining: float | None = None - timestamp_utc: str | None = None - token_based_billing: bool | None = None - unlimited: bool | None = None + kind: DebugCollectLogsResultKind + no_overwrite: bool | None = None + """When true, create the archive atomically without overwriting an existing file by + appending ` (N)` before the extension as needed. Defaults to false. + """ + output_path: str | None = None + """Absolute or server-relative path for the .tgz archive to create.""" + + output_directory: str | None = None + """Directory where redacted files should be staged. The directory is created if needed.""" @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponseQuotaSnapshots': + def from_dict(obj: Any) -> 'DebugCollectLogsDestination': assert isinstance(obj, dict) - entitlement = from_union([from_float, from_none], obj.get("entitlement")) - has_quota = from_union([from_bool, from_none], obj.get("has_quota")) - overage_count = from_union([from_float, from_none], obj.get("overage_count")) - overage_permitted = from_union([from_bool, from_none], obj.get("overage_permitted")) - percent_remaining = from_union([from_float, from_none], obj.get("percent_remaining")) - quota_id = from_union([from_str, from_none], obj.get("quota_id")) - quota_remaining = from_union([from_float, from_none], obj.get("quota_remaining")) - quota_reset_at = from_union([from_float, from_none], obj.get("quota_reset_at")) - remaining = from_union([from_float, from_none], obj.get("remaining")) - timestamp_utc = from_union([from_str, from_none], obj.get("timestamp_utc")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - unlimited = from_union([from_bool, from_none], obj.get("unlimited")) - return CopilotUserResponseQuotaSnapshots(entitlement, has_quota, overage_count, overage_permitted, percent_remaining, quota_id, quota_remaining, quota_reset_at, remaining, timestamp_utc, token_based_billing, unlimited) + kind = DebugCollectLogsResultKind(obj.get("kind")) + no_overwrite = from_union([from_bool, from_none], obj.get("noOverwrite")) + output_path = from_union([from_str, from_none], obj.get("outputPath")) + output_directory = from_union([from_str, from_none], obj.get("outputDirectory")) + return DebugCollectLogsDestination(kind, no_overwrite, output_path, output_directory) def to_dict(self) -> dict: result: dict = {} - if self.entitlement is not None: - result["entitlement"] = from_union([to_float, from_none], self.entitlement) - if self.has_quota is not None: - result["has_quota"] = from_union([from_bool, from_none], self.has_quota) - if self.overage_count is not None: - result["overage_count"] = from_union([to_float, from_none], self.overage_count) - if self.overage_permitted is not None: - result["overage_permitted"] = from_union([from_bool, from_none], self.overage_permitted) - if self.percent_remaining is not None: - result["percent_remaining"] = from_union([to_float, from_none], self.percent_remaining) - if self.quota_id is not None: - result["quota_id"] = from_union([from_str, from_none], self.quota_id) - if self.quota_remaining is not None: - result["quota_remaining"] = from_union([to_float, from_none], self.quota_remaining) - if self.quota_reset_at is not None: - result["quota_reset_at"] = from_union([to_float, from_none], self.quota_reset_at) - if self.remaining is not None: - result["remaining"] = from_union([to_float, from_none], self.remaining) - if self.timestamp_utc is not None: - result["timestamp_utc"] = from_union([from_str, from_none], self.timestamp_utc) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) - if self.unlimited is not None: - result["unlimited"] = from_union([from_bool, from_none], self.unlimited) + result["kind"] = to_enum(DebugCollectLogsResultKind, self.kind) + if self.no_overwrite is not None: + result["noOverwrite"] = from_union([from_bool, from_none], self.no_overwrite) + if self.output_path is not None: + result["outputPath"] = from_union([from_str, from_none], self.output_path) + if self.output_directory is not None: + result["outputDirectory"] = from_union([from_str, from_none], self.output_directory) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -9786,8 +11184,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class Extension: - """Schema for the `Extension` type.""" - + """Discovered extension metadata, including source-qualified ID, name, discovery source, + status, and optional process ID. + """ id: str """Source-qualified ID (e.g., 'project:my-ext', 'user:auth-helper', 'plugin:my-plugin:my-ext') @@ -9934,6 +11333,49 @@ def to_dict(self) -> dict: ExternalToolTextResultForLlmContentResourceDetails = EmbeddedTextResourceContents | EmbeddedBlobResourceContents +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourceIcon: + """A resource icon descriptor plus preserved non-standard icon fields.""" + + src: str + """Icon URI""" + + additional_properties: dict[str, Any] | None = None + """Server-provided non-standard icon fields preserved from the MCP response""" + + mime_type: str | None = None + """Icon MIME type, when known""" + + sizes: str | None = None + """Icon sizes hint""" + + theme: str | None = None + """Theme hint for this icon""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResourceIcon': + assert isinstance(obj, dict) + src = from_str(obj.get("src")) + additional_properties = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("additionalProperties")) + mime_type = from_union([from_str, from_none], obj.get("mimeType")) + sizes = from_union([from_str, from_none], obj.get("sizes")) + theme = from_union([from_str, from_none], obj.get("theme")) + return MCPResourceIcon(src, additional_properties, mime_type, sizes, theme) + + def to_dict(self) -> dict: + result: dict = {} + result["src"] = from_str(self.src) + if self.additional_properties is not None: + result["additionalProperties"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.additional_properties) + if self.mime_type is not None: + result["mimeType"] = from_union([from_str, from_none], self.mime_type) + if self.sizes is not None: + result["sizes"] = from_union([from_str, from_none], self.sizes) + if self.theme is not None: + result["theme"] = from_union([from_str, from_none], self.theme) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ExternalToolTextResultForLlmContentAudio: @@ -10015,17 +11457,64 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class ExternalToolTextResultForLlmContentTerminal: - """Terminal/shell output content block with optional exit code and working directory""" +class ExternalToolTextResultForLlmContentShellExit: + """Shell command exit metadata with optional output preview""" - text: str - """Terminal/shell output text""" + exit_code: int + """Exit code from the completed shell command""" - type: ClassVar[str] = "terminal" + shell_id: str + """Shell id, as assigned by Copilot runtime""" + + type: ClassVar[str] = "shell_exit" """Content block type discriminator""" cwd: str | None = None - """Working directory where the command was executed""" + """Working directory where the shell command was executed""" + + output_preview: str | None = None + """Output associated with this shell command, if available. May be partial, truncated, or a + preview; not guaranteed to be full output. + """ + output_truncated: bool | None = None + """Whether outputPreview is known to be incomplete or truncated""" + + @staticmethod + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentShellExit': + assert isinstance(obj, dict) + exit_code = from_int(obj.get("exitCode")) + shell_id = from_str(obj.get("shellId")) + cwd = from_union([from_str, from_none], obj.get("cwd")) + output_preview = from_union([from_str, from_none], obj.get("outputPreview")) + output_truncated = from_union([from_bool, from_none], obj.get("outputTruncated")) + return ExternalToolTextResultForLlmContentShellExit(exit_code, shell_id, cwd, output_preview, output_truncated) + + def to_dict(self) -> dict: + result: dict = {} + result["exitCode"] = from_int(self.exit_code) + result["shellId"] = from_str(self.shell_id) + result["type"] = self.type + if self.cwd is not None: + result["cwd"] = from_union([from_str, from_none], self.cwd) + if self.output_preview is not None: + result["outputPreview"] = from_union([from_str, from_none], self.output_preview) + if self.output_truncated is not None: + result["outputTruncated"] = from_union([from_bool, from_none], self.output_truncated) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ExternalToolTextResultForLlmContentTerminal: + """Terminal/shell output content block with optional exit code and working directory""" + + text: str + """Terminal/shell output text""" + + type: ClassVar[str] = "terminal" + """Content block type discriminator""" + + cwd: str | None = None + """Working directory where the command was executed""" exit_code: int | None = None """Process exit code, if the command has completed""" @@ -10074,7 +11563,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SlashCommandTextResult: - """Schema for the `SlashCommandTextResult` type.""" + """Slash-command invocation result containing text output plus Markdown/ANSI rendering flags.""" kind: ClassVar[str] = "text" """Text result discriminator""" @@ -10158,11 +11647,128 @@ def to_dict(self) -> dict: result["summaryContent"] = from_union([from_str, from_none], self.summary_content) return result +# Internal: this type is an internal SDK API and is not part of the public surface. +@dataclass +class _HookInvokeRequest: + """Runtime-owned wire payload for a server-to-client hook callback invocation.""" + + hook_type: _HookType + input: Any + session_id: str + + @staticmethod + def from_dict(obj: Any) -> '_HookInvokeRequest': + assert isinstance(obj, dict) + hook_type = _HookType(obj.get("hookType")) + input = obj.get("input") + session_id = from_str(obj.get("sessionId")) + return _HookInvokeRequest(hook_type, input, session_id) + + def to_dict(self) -> dict: + result: dict = {} + result["hookType"] = to_enum(_HookType, self.hook_type) + result["input"] = self.input + result["sessionId"] = from_str(self.session_id) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class InstalledPluginSourceGitHub: - """Schema for the `InstalledPluginSourceGitHub` type.""" +class InstalledPluginSource: + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, + and optional subpath. + + Source descriptor for a direct URL plugin install, with URL, optional ref, and optional + subpath. + + Source descriptor for a direct local plugin install, with a local filesystem path. + """ + source: PurpleSource + """Constant value. Always "github". + + Constant value. Always "url". + + Constant value. Always "local". + """ + path: str | None = None + ref: str | None = None + repo: str | None = None + url: str | None = None + + @staticmethod + def from_dict(obj: Any) -> 'InstalledPluginSource': + assert isinstance(obj, dict) + source = PurpleSource(obj.get("source")) + path = from_union([from_str, from_none], obj.get("path")) + ref = from_union([from_str, from_none], obj.get("ref")) + repo = from_union([from_str, from_none], obj.get("repo")) + url = from_union([from_str, from_none], obj.get("url")) + return InstalledPluginSource(source, path, ref, repo, url) + + def to_dict(self) -> dict: + result: dict = {} + result["source"] = to_enum(PurpleSource, self.source) + if self.path is not None: + result["path"] = from_union([from_str, from_none], self.path) + if self.ref is not None: + result["ref"] = from_union([from_str, from_none], self.ref) + if self.repo is not None: + result["repo"] = from_union([from_str, from_none], self.repo) + if self.url is not None: + result["url"] = from_union([from_str, from_none], self.url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionInstalledPluginSource: + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, + and optional subpath. + + Source descriptor for a direct URL plugin install, with URL, optional ref, and optional + subpath. + + Source descriptor for a direct local plugin install, with a local filesystem path. + """ + source: PurpleSource + """Constant value. Always "github". + + Constant value. Always "url". + + Constant value. Always "local". + """ + path: str | None = None + ref: str | None = None + repo: str | None = None + url: str | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionInstalledPluginSource': + assert isinstance(obj, dict) + source = PurpleSource(obj.get("source")) + path = from_union([from_str, from_none], obj.get("path")) + ref = from_union([from_str, from_none], obj.get("ref")) + repo = from_union([from_str, from_none], obj.get("repo")) + url = from_union([from_str, from_none], obj.get("url")) + return SessionInstalledPluginSource(source, path, ref, repo, url) + + def to_dict(self) -> dict: + result: dict = {} + result["source"] = to_enum(PurpleSource, self.source) + if self.path is not None: + result["path"] = from_union([from_str, from_none], self.path) + if self.ref is not None: + result["ref"] = from_union([from_str, from_none], self.ref) + if self.repo is not None: + result["repo"] = from_union([from_str, from_none], self.repo) + if self.url is not None: + result["url"] = from_union([from_str, from_none], self.url) + return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class InstalledPluginSourceGitHub: + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, + and optional subpath. + """ repo: str source: FluffySource """Constant value. Always "github".""" @@ -10192,8 +11798,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionInstalledPluginSourceGitHub: - """Schema for the `SessionInstalledPluginSourceGitHub` type.""" - + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, + and optional subpath. + """ repo: str source: FluffySource """Constant value. Always "github".""" @@ -10223,7 +11830,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class InstalledPluginSourceLocal: - """Schema for the `InstalledPluginSourceLocal` type.""" + """Source descriptor for a direct local plugin install, with a local filesystem path.""" path: str source: TentacledSource @@ -10245,7 +11852,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionInstalledPluginSourceLocal: - """Schema for the `SessionInstalledPluginSourceLocal` type.""" + """Source descriptor for a direct local plugin install, with a local filesystem path.""" path: str source: TentacledSource @@ -10267,8 +11874,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class InstalledPluginSourceURL: - """Schema for the `InstalledPluginSourceUrl` type.""" - + """Source descriptor for a direct URL plugin install, with URL, optional ref, and optional + subpath. + """ source: StickySource """Constant value. Always "url".""" @@ -10298,8 +11906,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionInstalledPluginSourceURL: - """Schema for the `SessionInstalledPluginSourceUrl` type.""" - + """Source descriptor for a direct URL plugin install, with URL, optional ref, and optional + subpath. + """ source: StickySource """Constant value. Always "url".""" @@ -10326,76 +11935,12 @@ def to_dict(self) -> dict: result["ref"] = from_union([from_str, from_none], self.ref) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionFSReaddirWithTypesEntry: - """Schema for the `SessionFsReaddirWithTypesEntry` type.""" - - name: str - """Entry name""" - - type: InstructionDiscoveryPathKind - """Entry type""" - - @staticmethod - def from_dict(obj: Any) -> 'SessionFSReaddirWithTypesEntry': - assert isinstance(obj, dict) - name = from_str(obj.get("name")) - type = InstructionDiscoveryPathKind(obj.get("type")) - return SessionFSReaddirWithTypesEntry(name, type) - - def to_dict(self) -> dict: - result: dict = {} - result["name"] = from_str(self.name) - result["type"] = to_enum(InstructionDiscoveryPathKind, self.type) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class InstructionDiscoveryPath: - """Schema for the `InstructionDiscoveryPath` type.""" - - kind: InstructionDiscoveryPathKind - """Whether the target is a single file or a directory of instruction files""" - - location: InstructionLocation - """Which tier this target belongs to""" - - path: str - """Absolute path of the file or directory (may not exist on disk yet)""" - - preferred_for_creation: bool - """Whether this is the canonical target to create new instructions in its tier. At most one - entry per tier is preferred. - """ - project_path: str | None = None - """The input project path this target was derived from (only for repository targets)""" - - @staticmethod - def from_dict(obj: Any) -> 'InstructionDiscoveryPath': - assert isinstance(obj, dict) - kind = InstructionDiscoveryPathKind(obj.get("kind")) - location = InstructionLocation(obj.get("location")) - path = from_str(obj.get("path")) - preferred_for_creation = from_bool(obj.get("preferredForCreation")) - project_path = from_union([from_str, from_none], obj.get("projectPath")) - return InstructionDiscoveryPath(kind, location, path, preferred_for_creation, project_path) - - def to_dict(self) -> dict: - result: dict = {} - result["kind"] = to_enum(InstructionDiscoveryPathKind, self.kind) - result["location"] = to_enum(InstructionLocation, self.location) - result["path"] = from_str(self.path) - result["preferredForCreation"] = from_bool(self.preferred_for_creation) - if self.project_path is not None: - result["projectPath"] = from_union([from_str, from_none], self.project_path) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class InstructionSource: - """Schema for the `InstructionSource` type.""" - + """Loaded instruction source for a session, including path, content, category, location, + applicability, and optional description. + """ content: str """Raw content of the instruction file""" @@ -10480,6 +12025,35 @@ class LlmInferenceHTTPRequestStartRequest: url: str """Absolute request URL.""" + agent_id: str | None = None + """Stable per-agent-instance id attributing this request to a specific agent trajectory. + Present when the request originates from an agent turn; absent for requests issued + outside any agent context (e.g. some SDK callers). A request with an `agentId` but no + `parentAgentId` is a root-agent request; one carrying both is a subagent request. Sourced + from the runtime's per-request agent context and surfaced on the envelope independently + of transport, so it is available for both first-party (CAPI) and BYOK/custom-provider + requests; on the CAPI transport the runtime derives the upstream `X-Agent-Task-Id` header + from this same context. Consumers routing each provider call to a training trajectory + should key on this rather than on lifecycle events, since it is available on the request + path before sampling. + """ + interaction_type: str | None = None + """Coarse classification of the interaction that produced this request. Open string for + forward-compatibility; known values include `conversation-agent`, + `conversation-subagent`, `conversation-sampling`, `conversation-background`, + `conversation-compaction`, and `conversation-user`. Absent when the runtime did not + classify the request. Comes from the runtime's per-request agent context independently of + transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` + header from this same context. + """ + parent_agent_id: str | None = None + """Id of the parent agent that spawned the agent issuing this request. Present only for + subagent requests; absent for root-agent requests and non-agent requests. Combined with + `agentId`, this lets consumers attribute a call to a child trajectory versus the root. + Like `agentId`, it comes from the runtime's per-request agent context independently of + transport; on the CAPI transport the runtime derives the upstream `X-Parent-Agent-Id` + header from this same context. + """ session_id: str | None = None """Id of the runtime session that triggered this request, when one is in scope. Absent for requests issued outside any session (e.g. startup model-catalog or capability @@ -10502,9 +12076,12 @@ def from_dict(obj: Any) -> 'LlmInferenceHTTPRequestStartRequest': method = from_str(obj.get("method")) request_id = from_str(obj.get("requestId")) url = from_str(obj.get("url")) + agent_id = from_union([from_str, from_none], obj.get("agentId")) + interaction_type = from_union([from_str, from_none], obj.get("interactionType")) + parent_agent_id = from_union([from_str, from_none], obj.get("parentAgentId")) session_id = from_union([from_str, from_none], obj.get("sessionId")) transport = from_union([LlmInferenceHTTPRequestStartTransport, from_none], obj.get("transport")) - return LlmInferenceHTTPRequestStartRequest(headers, method, request_id, url, session_id, transport) + return LlmInferenceHTTPRequestStartRequest(headers, method, request_id, url, agent_id, interaction_type, parent_agent_id, session_id, transport) def to_dict(self) -> dict: result: dict = {} @@ -10512,6 +12089,12 @@ def to_dict(self) -> dict: result["method"] = from_str(self.method) result["requestId"] = from_str(self.request_id) result["url"] = from_str(self.url) + if self.agent_id is not None: + result["agentId"] = from_union([from_str, from_none], self.agent_id) + if self.interaction_type is not None: + result["interactionType"] = from_union([from_str, from_none], self.interaction_type) + if self.parent_agent_id is not None: + result["parentAgentId"] = from_union([from_str, from_none], self.parent_agent_id) if self.session_id is not None: result["sessionId"] = from_union([from_str, from_none], self.session_id) if self.transport is not None: @@ -11004,6 +12587,7 @@ def to_dict(self) -> dict: result["contents"] = from_list(lambda x: to_class(MCPAppsResourceContent, x), self.contents) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServerConfigStdio: """Stdio MCP server configuration launched as a child process.""" @@ -11162,10 +12746,14 @@ def to_dict(self) -> dict: result["publicClient"] = from_union([from_bool, from_none], self.public_client) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServerConfig: """MCP server configuration (stdio process or remote HTTP/SSE) + Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart + the server with its already-registered configuration (config-free restart-by-name). + Stdio MCP server configuration launched as a child process. Remote MCP server configuration accessed over HTTP or SSE. @@ -11284,6 +12872,7 @@ def to_dict(self) -> dict: result["url"] = from_union([from_str, from_none], self.url) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServerConfigHTTP: """Remote MCP server configuration accessed over HTTP or SSE.""" @@ -11402,6 +12991,31 @@ def to_dict(self) -> dict: result["allowedServers"] = from_union([lambda x: from_list(lambda x: to_class(MCPAllowedServer, x), x), from_none], self.allowed_servers) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPHeadersHandlePendingHeadersRefreshRequest: + """Host response: supply dynamic headers or decline this refresh.""" + + kind: MCPHeadersHandlePendingHeadersRefreshRequestKind + headers: dict[str, str] | None = None + """Headers to overlay onto the MCP request. Dynamic headers override static config headers + but do not replace SDK-managed request headers. + """ + + @staticmethod + def from_dict(obj: Any) -> 'MCPHeadersHandlePendingHeadersRefreshRequest': + assert isinstance(obj, dict) + kind = MCPHeadersHandlePendingHeadersRefreshRequestKind(obj.get("kind")) + headers = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("headers")) + return MCPHeadersHandlePendingHeadersRefreshRequest(kind, headers) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(MCPHeadersHandlePendingHeadersRefreshRequestKind, self.kind) + if self.headers is not None: + result["headers"] = from_union([lambda x: from_dict(from_str, x), from_none], self.headers) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPHostState: @@ -11463,9 +13077,6 @@ class MCPOauthPendingRequestResponse: expires_in: int | None = None """Token lifetime in seconds, if known.""" - refresh_token: str | None = None - """Refresh token supplied by the host, if available.""" - token_type: str | None = None """OAuth token type. Defaults to Bearer when omitted.""" @@ -11475,9 +13086,8 @@ def from_dict(obj: Any) -> 'MCPOauthPendingRequestResponse': kind = MCPOauthPendingRequestResponseKind(obj.get("kind")) access_token = from_union([from_str, from_none], obj.get("accessToken")) expires_in = from_union([from_int, from_none], obj.get("expiresIn")) - refresh_token = from_union([from_str, from_none], obj.get("refreshToken")) token_type = from_union([from_str, from_none], obj.get("tokenType")) - return MCPOauthPendingRequestResponse(kind, access_token, expires_in, refresh_token, token_type) + return MCPOauthPendingRequestResponse(kind, access_token, expires_in, token_type) def to_dict(self) -> dict: result: dict = {} @@ -11486,12 +13096,29 @@ def to_dict(self) -> dict: result["accessToken"] = from_union([from_str, from_none], self.access_token) if self.expires_in is not None: result["expiresIn"] = from_union([from_int, from_none], self.expires_in) - if self.refresh_token is not None: - result["refreshToken"] = from_union([from_str, from_none], self.refresh_token) if self.token_type is not None: result["tokenType"] = from_union([from_str, from_none], self.token_type) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourcesReadResult: + """Resource contents returned by the MCP server.""" + + contents: list[MCPResourceContent] + """Resource contents returned by the server""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResourcesReadResult': + assert isinstance(obj, dict) + contents = from_list(MCPResourceContent.from_dict, obj.get("contents")) + return MCPResourcesReadResult(contents) + + def to_dict(self) -> dict: + result: dict = {} + result["contents"] = from_list(lambda x: to_class(MCPResourceContent, x), self.contents) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPSamplingExecutionResult: @@ -11571,6 +13198,53 @@ def to_dict(self) -> dict: result["mode"] = to_enum(MCPSetEnvValueModeDetails, self.mode) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class DebugCollectLogsEntryKind(Enum): + """Kind of source path to include. + + Kind of caller-provided debug log entry. + + Whether the target is a single file or a directory of instruction files + + Entry type + """ + DIRECTORY = "directory" + FILE = "file" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionContextAttribution: + """Per-source token attribution snapshot for the current context window. The heaviest + individual messages are available separately via `metadata.getContextHeaviestMessages`. + """ + compactions: Compactions + """Successful compaction history for the session.""" + + entries: list[Entry] + """Flat list of per-source attribution entries. Group by `kind` and render unrecognized + kinds generically. Nesting and rollups are expressed via `parentId`. + """ + total_tokens: int + """Total token count of the current context window the entries are measured against (system + message + conversation messages + tool definitions — the same total reported by + /context). Divide an entry's `tokens` by this to derive its share. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SessionContextAttribution': + assert isinstance(obj, dict) + compactions = Compactions.from_dict(obj.get("compactions")) + entries = from_list(Entry.from_dict, obj.get("entries")) + total_tokens = from_int(obj.get("totalTokens")) + return SessionContextAttribution(compactions, entries, total_tokens) + + def to_dict(self) -> dict: + result: dict = {} + result["compactions"] = to_class(Compactions, self.compactions) + result["entries"] = from_list(lambda x: to_class(Entry, x), self.entries) + result["totalTokens"] = from_int(self.total_tokens) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MetadataContextInfoResult: @@ -11634,6 +13308,7 @@ def to_dict(self) -> dict: result["taskType"] = from_union([lambda x: to_enum(TaskType, x), from_none], self.task_type) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelBillingTokenPrices: """Token-level pricing information for this model""" @@ -11703,6 +13378,7 @@ def to_dict(self) -> dict: result["outputPrice"] = from_union([to_float, from_none], self.output_price) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelCapabilitiesLimits: """Token limits for prompts, outputs, and context window""" @@ -11740,8 +13416,30 @@ def to_dict(self) -> dict: result["vision"] = from_union([lambda x: to_class(ModelCapabilitiesLimitsVision, x), from_none], self.vision) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class ModelPolicy: +class SessionModelPriceCategory: + """Cost-category metadata for a CAPI model.""" + + id: str + price_category: ModelPickerPriceCategory + + @staticmethod + def from_dict(obj: Any) -> 'SessionModelPriceCategory': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + price_category = ModelPickerPriceCategory(obj.get("priceCategory")) + return SessionModelPriceCategory(id, price_category) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + result["priceCategory"] = to_enum(ModelPickerPriceCategory, self.price_category) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ModelPolicy: """Policy state (if applicable)""" state: ModelPolicyState @@ -11997,12 +13695,14 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class OptionsUpdateAdditionalContentExclusionPolicyRule: - """Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRule` type.""" - + """Single content-exclusion rule supplied to `session.options.update`, with paths, match + conditions, and source. + """ paths: list[str] source: OptionsUpdateAdditionalContentExclusionPolicyRuleSource - """Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type.""" - + """Source descriptor for a `session.options.update` content-exclusion rule, with source name + and type. + """ if_any_match: list[str] | None = None if_none_match: list[str] | None = None @@ -12051,8 +13751,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocation: - """Schema for the `PermissionDecisionApproveForLocation` type.""" - + """Permission-decision request variant to approve and persist a permission for a project + location, with approval details and location key. + """ approval: PermissionDecisionApproveForLocationApproval """Approval to persist for this location""" @@ -12079,7 +13780,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalCommands: - """Schema for the `PermissionDecisionApproveForLocationApprovalCommands` type.""" + """Location-scoped approval details for specific command identifiers.""" command_identifiers: list[str] """Command identifiers covered by this approval.""" @@ -12102,7 +13803,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalCommands: - """Schema for the `PermissionDecisionApproveForSessionApprovalCommands` type.""" + """Session-scoped approval details for specific command identifiers.""" command_identifiers: list[str] """Command identifiers covered by this approval.""" @@ -12125,7 +13826,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsCommands: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsCommands` type.""" + """Location-persisted tool approval details for specific command identifiers.""" command_identifiers: list[str] """Command identifiers covered by this approval.""" @@ -12148,7 +13849,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalCustomTool: - """Schema for the `PermissionDecisionApproveForLocationApprovalCustomTool` type.""" + """Location-scoped approval details for a custom tool, keyed by tool name.""" kind: ClassVar[str] = "custom-tool" """Approval covering a custom tool.""" @@ -12171,7 +13872,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalCustomTool: - """Schema for the `PermissionDecisionApproveForSessionApprovalCustomTool` type.""" + """Session-scoped approval details for a custom tool, keyed by tool name.""" kind: ClassVar[str] = "custom-tool" """Approval covering a custom tool.""" @@ -12194,7 +13895,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsCustomTool: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsCustomTool` type.""" + """Location-persisted tool approval details for a custom tool, keyed by tool name.""" kind: ClassVar[str] = "custom-tool" """Approval covering a custom tool.""" @@ -12217,8 +13918,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalExtensionManagement: - """Schema for the `PermissionDecisionApproveForLocationApprovalExtensionManagement` type.""" - + """Location-scoped approval details for extension-management operations, optionally narrowed + by operation. + """ kind: ClassVar[str] = "extension-management" """Approval covering extension lifecycle operations such as enable, disable, or reload.""" @@ -12243,8 +13945,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalExtensionManagement: - """Schema for the `PermissionDecisionApproveForSessionApprovalExtensionManagement` type.""" - + """Session-scoped approval details for extension-management operations, optionally narrowed + by operation. + """ kind: ClassVar[str] = "extension-management" """Approval covering extension lifecycle operations such as enable, disable, or reload.""" @@ -12269,8 +13972,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsExtensionManagement: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionManagement` type.""" - + """Location-persisted tool approval details for extension-management operations, optionally + narrowed by operation. + """ kind: ClassVar[str] = "extension-management" """Approval covering extension lifecycle operations such as enable, disable, or reload.""" @@ -12295,8 +13999,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalMCP: - """Schema for the `PermissionDecisionApproveForLocationApprovalMcp` type.""" - + """Location-scoped approval details for an MCP server tool, or all tools on the server when + `toolName` is null. + """ kind: ClassVar[str] = "mcp" """Approval covering an MCP tool.""" @@ -12323,8 +14028,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalMCP: - """Schema for the `PermissionDecisionApproveForSessionApprovalMcp` type.""" - + """Session-scoped approval details for an MCP server tool, or all tools on the server when + `toolName` is null. + """ kind: ClassVar[str] = "mcp" """Approval covering an MCP tool.""" @@ -12351,8 +14057,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsMCP: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsMcp` type.""" - + """Location-persisted tool approval details for an MCP server tool, or all tools when + `toolName` is null. + """ kind: ClassVar[str] = "mcp" """Approval covering an MCP tool.""" @@ -12379,7 +14086,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalMCPSampling: - """Schema for the `PermissionDecisionApproveForLocationApprovalMcpSampling` type.""" + """Location-scoped approval details for MCP sampling requests from a server.""" kind: ClassVar[str] = "mcp-sampling" """Approval covering MCP sampling requests for a server.""" @@ -12402,7 +14109,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalMCPSampling: - """Schema for the `PermissionDecisionApproveForSessionApprovalMcpSampling` type.""" + """Session-scoped approval details for MCP sampling requests from a server.""" kind: ClassVar[str] = "mcp-sampling" """Approval covering MCP sampling requests for a server.""" @@ -12425,7 +14132,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsMCPSampling: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsMcpSampling` type.""" + """Location-persisted tool approval details for MCP sampling requests from a server.""" kind: ClassVar[str] = "mcp-sampling" """Approval covering MCP sampling requests for a server.""" @@ -12448,7 +14155,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalMemory: - """Schema for the `PermissionDecisionApproveForLocationApprovalMemory` type.""" + """Location-scoped approval details for writes to long-term memory.""" kind: ClassVar[str] = "memory" """Approval covering writes to long-term memory.""" @@ -12466,7 +14173,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalMemory: - """Schema for the `PermissionDecisionApproveForSessionApprovalMemory` type.""" + """Session-scoped approval details for writes to long-term memory.""" kind: ClassVar[str] = "memory" """Approval covering writes to long-term memory.""" @@ -12484,7 +14191,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsMemory: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsMemory` type.""" + """Location-persisted tool approval details for writes to long-term memory.""" kind: ClassVar[str] = "memory" """Approval covering writes to long-term memory.""" @@ -12502,7 +14209,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalRead: - """Schema for the `PermissionDecisionApproveForLocationApprovalRead` type.""" + """Location-scoped approval details for read-only filesystem operations.""" kind: ClassVar[str] = "read" """Approval covering read-only filesystem operations.""" @@ -12520,7 +14227,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalRead: - """Schema for the `PermissionDecisionApproveForSessionApprovalRead` type.""" + """Session-scoped approval details for read-only filesystem operations.""" kind: ClassVar[str] = "read" """Approval covering read-only filesystem operations.""" @@ -12538,7 +14245,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsRead: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsRead` type.""" + """Location-persisted tool approval details for read-only filesystem operations.""" kind: ClassVar[str] = "read" """Approval covering read-only filesystem operations.""" @@ -12556,7 +14263,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalWrite: - """Schema for the `PermissionDecisionApproveForLocationApprovalWrite` type.""" + """Location-scoped approval details for filesystem write operations.""" kind: ClassVar[str] = "write" """Approval covering filesystem write operations.""" @@ -12574,7 +14281,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalWrite: - """Schema for the `PermissionDecisionApproveForSessionApprovalWrite` type.""" + """Session-scoped approval details for filesystem write operations.""" kind: ClassVar[str] = "write" """Approval covering filesystem write operations.""" @@ -12592,7 +14299,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsWrite: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsWrite` type.""" + """Location-persisted tool approval details for filesystem write operations.""" kind: ClassVar[str] = "write" """Approval covering filesystem write operations.""" @@ -12610,8 +14317,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSession: - """Schema for the `PermissionDecisionApproveForSession` type.""" - + """Permission-decision request variant to approve for the rest of the session, with optional + tool approval or URL domain. + """ kind: ClassVar[str] = "approve-for-session" """Approve and remember for the rest of the session""" @@ -12640,7 +14348,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveOnce: - """Schema for the `PermissionDecisionApproveOnce` type.""" + """Permission-decision request variant to approve only the current permission request.""" kind: ClassVar[str] = "approve-once" """Approve this single request only""" @@ -12658,7 +14366,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApprovePermanently: - """Schema for the `PermissionDecisionApprovePermanently` type.""" + """Permission-decision request variant to permanently approve a URL domain across sessions.""" domain: str """URL domain to approve permanently""" @@ -12681,7 +14389,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproved: - """Schema for the `PermissionDecisionApproved` type.""" + """Permission-decision variant indicating the request was approved.""" kind: ClassVar[str] = "approved" """The permission request was approved""" @@ -12699,8 +14407,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApprovedForLocation: - """Schema for the `PermissionDecisionApprovedForLocation` type.""" - + """Permission-decision variant indicating approval was persisted for a project location, + with approval details and location key. + """ approval: UserToolSessionApproval """The approval to persist for this location""" @@ -12727,8 +14436,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApprovedForSession: - """Schema for the `PermissionDecisionApprovedForSession` type.""" - + """Permission-decision variant indicating approval was remembered for the session, with + approval details. + """ approval: UserToolSessionApproval """The approval to add as a session-scoped rule""" @@ -12750,8 +14460,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionCancelled: - """Schema for the `PermissionDecisionCancelled` type.""" - + """Permission-decision variant indicating the request was cancelled before use, with an + optional reason. + """ kind: ClassVar[str] = "cancelled" """The permission request was cancelled before a response was used""" @@ -12774,8 +14485,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionDeniedByContentExclusionPolicy: - """Schema for the `PermissionDecisionDeniedByContentExclusionPolicy` type.""" - + """Permission-decision variant indicating denial by content-exclusion policy, with path and + message. + """ kind: ClassVar[str] = "denied-by-content-exclusion-policy" """Denied by the organization's content exclusion policy""" @@ -12802,8 +14514,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionDeniedByPermissionRequestHook: - """Schema for the `PermissionDecisionDeniedByPermissionRequestHook` type.""" - + """Permission-decision variant indicating denial by a permission request hook, with optional + message and interrupt flag. + """ kind: ClassVar[str] = "denied-by-permission-request-hook" """Denied by a permission request hook registered by an extension or plugin""" @@ -12832,8 +14545,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionDeniedByRules: - """Schema for the `PermissionDecisionDeniedByRules` type.""" - + """Permission-decision variant indicating explicit denial by permission rules, with the + matching rules. + """ kind: ClassVar[str] = "denied-by-rules" """Denied because approval rules explicitly blocked it""" @@ -12855,8 +14569,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionDeniedInteractivelyByUser: - """Schema for the `PermissionDecisionDeniedInteractivelyByUser` type.""" - + """Permission-decision variant indicating the user denied an interactive prompt, with + optional feedback and force-reject flag. + """ kind: ClassVar[str] = "denied-interactively-by-user" """Denied by the user during an interactive prompt""" @@ -12885,8 +14600,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser: - """Schema for the `PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type.""" - + """Permission-decision variant indicating no approval rule matched and user confirmation was + unavailable. + """ kind: ClassVar[str] = "denied-no-approval-rule-and-could-not-request-from-user" """Denied because no approval rule matched and user confirmation was unavailable""" @@ -12903,8 +14619,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionReject: - """Schema for the `PermissionDecisionReject` type.""" - + """Permission-decision request variant to reject a pending permission request, with optional + feedback. + """ kind: ClassVar[str] = "reject" """Reject the request""" @@ -12927,7 +14644,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionUserNotAvailable: - """Schema for the `PermissionDecisionUserNotAvailable` type.""" + """Permission-decision variant indicating no user was available to confirm the request.""" kind: ClassVar[str] = "user-not-available" """No user is available to confirm the request""" @@ -13013,12 +14730,14 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsConfigureAdditionalContentExclusionPolicyRule: - """Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRule` type.""" - + """Single content-exclusion rule supplied to `session.permissions.configure`, with paths, + match conditions, and source. + """ paths: list[str] source: PermissionsConfigureAdditionalContentExclusionPolicyRuleSource - """Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type.""" - + """Source descriptor for a `session.permissions.configure` content-exclusion rule, with + source name and type. + """ if_any_match: list[str] | None = None if_none_match: list[str] | None = None @@ -13129,10 +14848,12 @@ def to_dict(self) -> dict: result["rows"] = from_list(lambda x: to_class(PlanSQLTodosRow, x), self.rows) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class DiscoveredMCPServer: - """Schema for the `DiscoveredMcpServer` type.""" - + """MCP server discovered by `mcp.discover`, with config source, optional plugin source, + transport type, and enabled state. + """ enabled: bool """Whether the server is enabled (not in the disabled list)""" @@ -13192,6 +14913,11 @@ class InstalledPluginInfo: name: str """Plugin name""" + direct_source_id: str | None = None + """Opaque, stable hash identifying a direct (non-marketplace) install source. Present only + for direct repo / URL / local installs; absent for marketplace plugins. Same source + yields the same id; distinct sources never collide. + """ version: str | None = None """Installed version (when reported by the plugin manifest)""" @@ -13201,14 +14927,17 @@ def from_dict(obj: Any) -> 'InstalledPluginInfo': enabled = from_bool(obj.get("enabled")) marketplace = from_str(obj.get("marketplace")) name = from_str(obj.get("name")) + direct_source_id = from_union([from_str, from_none], obj.get("directSourceId")) version = from_union([from_str, from_none], obj.get("version")) - return InstalledPluginInfo(enabled, marketplace, name, version) + return InstalledPluginInfo(enabled, marketplace, name, direct_source_id, version) def to_dict(self) -> dict: result: dict = {} result["enabled"] = from_bool(self.enabled) result["marketplace"] = from_str(self.marketplace) result["name"] = from_str(self.name) + if self.direct_source_id is not None: + result["directSourceId"] = from_union([from_str, from_none], self.direct_source_id) if self.version is not None: result["version"] = from_union([from_str, from_none], self.version) return result @@ -13241,7 +14970,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPServer: - """Schema for the `McpServer` type.""" + """MCP server status entry, including config source/plugin source and any connection error.""" name: str """Server name (config key)""" @@ -13308,8 +15037,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PluginUpdateAllEntry: - """Schema for the `PluginUpdateAllEntry` type.""" - + """Per-plugin result from updating all plugins, with versions, skills installed, success + flag, and optional error. + """ marketplace: str """Marketplace the plugin came from. Empty string ("") for direct installs.""" @@ -13441,16 +15171,23 @@ class PluginsUninstallRequest: """Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the fully-qualified spec. """ + direct_source_id: str | None = None + """Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall + when multiple installed plugins share the same name. + """ @staticmethod def from_dict(obj: Any) -> 'PluginsUninstallRequest': assert isinstance(obj, dict) name = from_str(obj.get("name")) - return PluginsUninstallRequest(name) + direct_source_id = from_union([from_none, from_str], obj.get("directSourceId")) + return PluginsUninstallRequest(name, direct_source_id) def to_dict(self) -> dict: result: dict = {} result["name"] = from_str(self.name) + if self.direct_source_id is not None: + result["directSourceId"] = from_union([from_none, from_str], self.direct_source_id) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -13472,30 +15209,6 @@ def to_dict(self) -> dict: result["name"] = from_str(self.name) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class PollSpawnedSessionsResult: - """Batch of spawn events plus a cursor for follow-up polls.""" - - cursor: str - """Opaque cursor to pass back to receive only events after this batch.""" - - events: list[SessionsPollSpawnedSessionsEvent] - """Spawn events emitted since the supplied cursor.""" - - @staticmethod - def from_dict(obj: Any) -> 'PollSpawnedSessionsResult': - assert isinstance(obj, dict) - cursor = from_str(obj.get("cursor")) - events = from_list(SessionsPollSpawnedSessionsEvent.from_dict, obj.get("events")) - return PollSpawnedSessionsResult(cursor, events) - - def to_dict(self) -> dict: - result: dict = {} - result["cursor"] = from_str(self.cursor) - result["events"] = from_list(lambda x: to_class(SessionsPollSpawnedSessionsEvent, x), self.events) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ProviderEndpoint: @@ -13551,6 +15264,115 @@ def to_dict(self) -> dict: result["wireApi"] = from_union([lambda x: to_enum(ProviderWireAPI, x), from_none], self.wire_api) return result +@dataclass +class PushAttachmentGitHubSide: + """File location on the base side of the diff. Absent for additions. + + One side of a file diff (head or base) + + File location on the head side of the diff. Absent for deletions. + + Base side of the comparison + + One side of a tree comparison (head or base) + + Head side of the comparison + """ + repo: PushGitHubRepoRef + """Repository the file lives in + + Repository the revision belongs to + """ + path: str | None = None + """Repository-relative path to the file""" + + ref: str | None = None + """Git ref (branch, tag, or commit SHA) the file is read at""" + + revision: str | None = None + """Git revision (branch, tag, or commit SHA)""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubSide': + assert isinstance(obj, dict) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + path = from_union([from_str, from_none], obj.get("path")) + ref = from_union([from_str, from_none], obj.get("ref")) + revision = from_union([from_str, from_none], obj.get("revision")) + return PushAttachmentGitHubSide(repo, path, ref, revision) + + def to_dict(self) -> dict: + result: dict = {} + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + if self.path is not None: + result["path"] = from_union([from_str, from_none], self.path) + if self.ref is not None: + result["ref"] = from_union([from_str, from_none], self.ref) + if self.revision is not None: + result["revision"] = from_union([from_str, from_none], self.revision) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubFileDiffSide: + """File location on the base side of the diff. Absent for additions. + + One side of a file diff (head or base) + + File location on the head side of the diff. Absent for deletions. + """ + path: str + """Repository-relative path to the file""" + + ref: str + """Git ref (branch, tag, or commit SHA) the file is read at""" + + repo: PushGitHubRepoRef + """Repository the file lives in""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubFileDiffSide': + assert isinstance(obj, dict) + path = from_str(obj.get("path")) + ref = from_str(obj.get("ref")) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + return PushAttachmentGitHubFileDiffSide(path, ref, repo) + + def to_dict(self) -> dict: + result: dict = {} + result["path"] = from_str(self.path) + result["ref"] = from_str(self.ref) + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubTreeComparisonSide: + """Base side of the comparison + + One side of a tree comparison (head or base) + + Head side of the comparison + """ + repo: PushGitHubRepoRef + """Repository the revision belongs to""" + + revision: str + """Git revision (branch, tag, or commit SHA)""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubTreeComparisonSide': + assert isinstance(obj, dict) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + revision = from_str(obj.get("revision")) + return PushAttachmentGitHubTreeComparisonSide(repo, revision) + + def to_dict(self) -> dict: + result: dict = {} + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["revision"] = from_str(self.revision) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PushAttachmentSelectionDetails: @@ -13643,6 +15465,133 @@ def to_dict(self) -> dict: result["lineRange"] = from_union([lambda x: to_class(PushAttachmentFileLineRange, x), from_none], self.line_range) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubActionsJob: + """Pointer to a GitHub Actions job.""" + + job_id: int + """Job id within the workflow run""" + + job_name: str + """Display name of the job""" + + repo: PushGitHubRepoRef + """Repository the workflow run belongs to""" + + type: ClassVar[str] = "github_actions_job" + """Attachment type discriminator""" + + url: str + """URL to the job on GitHub""" + + workflow_name: str + """Display name of the workflow the job ran in""" + + conclusion: str | None = None + """Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent + for in-progress jobs. + """ + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubActionsJob': + assert isinstance(obj, dict) + job_id = from_int(obj.get("jobId")) + job_name = from_str(obj.get("jobName")) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + workflow_name = from_str(obj.get("workflowName")) + conclusion = from_union([from_str, from_none], obj.get("conclusion")) + return PushAttachmentGitHubActionsJob(job_id, job_name, repo, url, workflow_name, conclusion) + + def to_dict(self) -> dict: + result: dict = {} + result["jobId"] = from_int(self.job_id) + result["jobName"] = from_str(self.job_name) + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + result["workflowName"] = from_str(self.workflow_name) + if self.conclusion is not None: + result["conclusion"] = from_union([from_str, from_none], self.conclusion) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubCommit: + """Pointer to a GitHub commit.""" + + message: str + """First line of the commit message""" + + oid: str + """Full commit SHA""" + + repo: PushGitHubRepoRef + """Repository the commit belongs to""" + + type: ClassVar[str] = "github_commit" + """Attachment type discriminator""" + + url: str + """URL to the commit on GitHub""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubCommit': + assert isinstance(obj, dict) + message = from_str(obj.get("message")) + oid = from_str(obj.get("oid")) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + return PushAttachmentGitHubCommit(message, oid, repo, url) + + def to_dict(self) -> dict: + result: dict = {} + result["message"] = from_str(self.message) + result["oid"] = from_str(self.oid) + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubFile: + """Pointer to a file in a GitHub repository at a specific ref.""" + + path: str + """Repository-relative path to the file""" + + ref: str + """Git ref the file is read at (branch, tag, or commit SHA)""" + + repo: PushGitHubRepoRef + """Repository the file lives in""" + + type: ClassVar[str] = "github_file" + """Attachment type discriminator""" + + url: str + """URL to the file on GitHub""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubFile': + assert isinstance(obj, dict) + path = from_str(obj.get("path")) + ref = from_str(obj.get("ref")) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + return PushAttachmentGitHubFile(path, ref, repo, url) + + def to_dict(self) -> dict: + result: dict = {} + result["path"] = from_str(self.path) + result["ref"] = from_str(self.ref) + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PushAttachmentGitHubReference: @@ -13688,53 +15637,200 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class QueuePendingItems: - """Schema for the `QueuePendingItems` type.""" +class PushAttachmentGitHubRelease: + """Pointer to a GitHub release.""" - display_text: str - """Human-readable text to display for this queue entry in the UI""" + name: str + """Human-readable release name""" - kind: QueuePendingItemsKind - """Whether this item is a queued user message or a queued slash command / model change""" + repo: PushGitHubRepoRef + """Repository the release belongs to""" + + tag_name: str + """Git tag the release is anchored to""" + + type: ClassVar[str] = "github_release" + """Attachment type discriminator""" + + url: str + """URL to the release on GitHub""" @staticmethod - def from_dict(obj: Any) -> 'QueuePendingItems': + def from_dict(obj: Any) -> 'PushAttachmentGitHubRelease': assert isinstance(obj, dict) - display_text = from_str(obj.get("displayText")) - kind = QueuePendingItemsKind(obj.get("kind")) - return QueuePendingItems(display_text, kind) + name = from_str(obj.get("name")) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + tag_name = from_str(obj.get("tagName")) + url = from_str(obj.get("url")) + return PushAttachmentGitHubRelease(name, repo, tag_name, url) def to_dict(self) -> dict: result: dict = {} - result["displayText"] = from_str(self.display_text) - result["kind"] = to_enum(QueuePendingItemsKind, self.kind) + result["name"] = from_str(self.name) + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["tagName"] = from_str(self.tag_name) + result["type"] = self.type + result["url"] = from_str(self.url) return result # Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. @dataclass -class _RegisterExtensionToolsParams: - """Params to attach an extension loader's tools to a session.""" +class PushAttachmentGitHubRepository: + """Pointer to a GitHub repository.""" - loader: Any - """In-process ExtensionLoader handle (CLI-only optimization). Marked internal: this field is - excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, - extension discovery/launch moves entirely into the runtime — the CLI passes pure config - (search paths, disabled ids) via SessionOptions instead. - """ - session_id: str - """Session to register extension tools on.""" + repo: PushGitHubRepoRef + """Repository pointer""" - options: SessionsRegisterExtensionToolsOnSessionOptions | None = None - """Optional registration options.""" + type: ClassVar[str] = "github_repository" + """Attachment type discriminator""" + + url: str + """URL to the repository on GitHub""" + + description: str | None = None + """Short description of the repository""" + + ref: str | None = None + """Git ref this attachment is anchored at (branch, tag, or commit). When absent the default + branch is implied. + """ @staticmethod - def from_dict(obj: Any) -> '_RegisterExtensionToolsParams': + def from_dict(obj: Any) -> 'PushAttachmentGitHubRepository': assert isinstance(obj, dict) - loader = obj.get("loader") - session_id = from_str(obj.get("sessionId")) - options = from_union([SessionsRegisterExtensionToolsOnSessionOptions.from_dict, from_none], obj.get("options")) - return _RegisterExtensionToolsParams(loader, session_id, options) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + description = from_union([from_str, from_none], obj.get("description")) + ref = from_union([from_str, from_none], obj.get("ref")) + return PushAttachmentGitHubRepository(repo, url, description, ref) + + def to_dict(self) -> dict: + result: dict = {} + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + if self.description is not None: + result["description"] = from_union([from_str, from_none], self.description) + if self.ref is not None: + result["ref"] = from_union([from_str, from_none], self.ref) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubSnippet: + """Pointer to a line range inside a file in a GitHub repository.""" + + line_range: PushAttachmentFileLineRange + """Line range the snippet covers""" + + path: str + """Repository-relative path to the file""" + + ref: str + """Git ref the file is read at (branch, tag, or commit SHA)""" + + repo: PushGitHubRepoRef + """Repository the file lives in""" + + type: ClassVar[str] = "github_snippet" + """Attachment type discriminator""" + + url: str + """URL to the snippet on GitHub (with line anchor)""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubSnippet': + assert isinstance(obj, dict) + line_range = PushAttachmentFileLineRange.from_dict(obj.get("lineRange")) + path = from_str(obj.get("path")) + ref = from_str(obj.get("ref")) + repo = PushGitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + return PushAttachmentGitHubSnippet(line_range, path, ref, repo, url) + + def to_dict(self) -> dict: + result: dict = {} + result["lineRange"] = to_class(PushAttachmentFileLineRange, self.line_range) + result["path"] = from_str(self.path) + result["ref"] = from_str(self.ref) + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubURL: + """Generic GitHub URL reference.""" + + type: ClassVar[str] = "github_url" + """Attachment type discriminator""" + + url: str + """URL to the GitHub resource""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubURL': + assert isinstance(obj, dict) + url = from_str(obj.get("url")) + return PushAttachmentGitHubURL(url) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = self.type + result["url"] = from_str(self.url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueuePendingItems: + """User-facing pending queue entry, with kind and display text for a queued message, slash + command, or model change. + """ + display_text: str + """Human-readable text to display for this queue entry in the UI""" + + kind: QueuePendingItemsKind + """Whether this item is a queued user message or a queued slash command / model change""" + + @staticmethod + def from_dict(obj: Any) -> 'QueuePendingItems': + assert isinstance(obj, dict) + display_text = from_str(obj.get("displayText")) + kind = QueuePendingItemsKind(obj.get("kind")) + return QueuePendingItems(display_text, kind) + + def to_dict(self) -> dict: + result: dict = {} + result["displayText"] = from_str(self.display_text) + result["kind"] = to_enum(QueuePendingItemsKind, self.kind) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +# Internal: this type is an internal SDK API and is not part of the public surface. +@dataclass +class _RegisterExtensionToolsParams: + """Params to attach an extension loader's tools to a session.""" + + loader: Any + """In-process ExtensionLoader handle (CLI-only optimization). Marked internal: this field is + excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, + extension discovery/launch moves entirely into the runtime — the CLI passes pure config + (search paths, disabled ids) via SessionOptions instead. + """ + session_id: str + """Session to register extension tools on.""" + + options: SessionsRegisterExtensionToolsOnSessionOptions | None = None + """Optional registration options.""" + + @staticmethod + def from_dict(obj: Any) -> '_RegisterExtensionToolsParams': + assert isinstance(obj, dict) + loader = obj.get("loader") + session_id = from_str(obj.get("sessionId")) + options = from_union([SessionsRegisterExtensionToolsOnSessionOptions.from_dict, from_none], obj.get("options")) + return _RegisterExtensionToolsParams(loader, session_id, options) def to_dict(self) -> dict: result: dict = {} @@ -13805,6 +15901,12 @@ class RemoteControlStatusActive: state: ClassVar[str] = "active" """Remote control state tag: active.""" + # Internal: this field is an internal SDK API and is not part of the public surface. + awaiting_first_message: bool | None = None + """True while a read-only/session-sync export is deferred, awaiting the first `user.message` + before its MC session exists. Marked internal: this field is excluded from the public SDK + surface and is populated only on the CLI in-process path. + """ frontend_url: str | None = None """MC frontend URL for this session, when known.""" @@ -13821,15 +15923,18 @@ def from_dict(obj: Any) -> 'RemoteControlStatusActive': assert isinstance(obj, dict) attached_session_id = from_str(obj.get("attachedSessionId")) is_steerable = from_bool(obj.get("isSteerable")) + awaiting_first_message = from_union([from_bool, from_none], obj.get("awaitingFirstMessage")) frontend_url = from_union([from_str, from_none], obj.get("frontendUrl")) prompt_manager = obj.get("promptManager") - return RemoteControlStatusActive(attached_session_id, is_steerable, frontend_url, prompt_manager) + return RemoteControlStatusActive(attached_session_id, is_steerable, awaiting_first_message, frontend_url, prompt_manager) def to_dict(self) -> dict: result: dict = {} result["attachedSessionId"] = from_str(self.attached_session_id) result["isSteerable"] = from_bool(self.is_steerable) result["state"] = self.state + if self.awaiting_first_message is not None: + result["awaitingFirstMessage"] = from_union([from_bool, from_none], self.awaiting_first_message) if self.frontend_url is not None: result["frontendUrl"] = from_union([from_str, from_none], self.frontend_url) if self.prompt_manager is not None: @@ -13991,6 +16096,77 @@ def to_dict(self) -> dict: result["entry"] = from_union([lambda x: to_class(ScheduleEntry, x), from_none], self.entry) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SendMessagesRequest: + """Parameters for sending zero or more user messages to the session in a single turn. + Remote-backed (Mission Control) sessions do not support this method and will return an + error. + """ + messages: list[SendMessageItem] + """The user messages to append to the conversation, in order. May be empty, in which case a + single turn runs over the existing history with no new user message. + """ + agent_mode: SendAgentMode | None = None + """The UI mode the agent was in when these messages were sent. Defaults to the session's + current mode. + """ + mode: SendMode | None = None + """How to deliver the messages. `enqueue` (default) appends to the message queue. + `immediate` interjects during an in-progress turn. + """ + prepend: bool | None = None + """If true, adds the messages to the front of the queue instead of the end""" + + request_headers: dict[str, str] | None = None + """Custom HTTP headers to include in outbound model requests for this turn. Merged with + session-level provider headers; per-turn headers augment and overwrite session-level + headers with the same key. + """ + traceparent: str | None = None + """W3C Trace Context traceparent header for distributed tracing of this agent turn""" + + tracestate: str | None = None + """W3C Trace Context tracestate header for distributed tracing""" + + wait: bool | None = None + """If true, await completion of the agentic loop for this turn before returning. Defaults to + false (fire-and-forget). When true, the result still contains the same `messageIds`; the + caller can rely on the agent having processed the messages before the call resolves. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SendMessagesRequest': + assert isinstance(obj, dict) + messages = from_list(SendMessageItem.from_dict, obj.get("messages")) + agent_mode = from_union([SendAgentMode, from_none], obj.get("agentMode")) + mode = from_union([SendMode, from_none], obj.get("mode")) + prepend = from_union([from_bool, from_none], obj.get("prepend")) + request_headers = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("requestHeaders")) + traceparent = from_union([from_str, from_none], obj.get("traceparent")) + tracestate = from_union([from_str, from_none], obj.get("tracestate")) + wait = from_union([from_bool, from_none], obj.get("wait")) + return SendMessagesRequest(messages, agent_mode, mode, prepend, request_headers, traceparent, tracestate, wait) + + def to_dict(self) -> dict: + result: dict = {} + result["messages"] = from_list(lambda x: to_class(SendMessageItem, x), self.messages) + if self.agent_mode is not None: + result["agentMode"] = from_union([lambda x: to_enum(SendAgentMode, x), from_none], self.agent_mode) + if self.mode is not None: + result["mode"] = from_union([lambda x: to_enum(SendMode, x), from_none], self.mode) + if self.prepend is not None: + result["prepend"] = from_union([from_bool, from_none], self.prepend) + if self.request_headers is not None: + result["requestHeaders"] = from_union([lambda x: from_dict(from_str, x), from_none], self.request_headers) + if self.traceparent is not None: + result["traceparent"] = from_union([from_str, from_none], self.traceparent) + if self.tracestate is not None: + result["tracestate"] = from_union([from_str, from_none], self.tracestate) + if self.wait is not None: + result["wait"] = from_union([from_bool, from_none], self.wait) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SendRequest: @@ -14096,6 +16272,7 @@ def to_dict(self) -> dict: result["wait"] = from_union([from_bool, from_none], self.wait) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ServerSkillList: """Skills discovered across global and project sources.""" @@ -14139,6 +16316,7 @@ def to_dict(self) -> dict: result["message"] = from_union([from_str, from_none], self.message) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionFSSetProviderRequest: """Initial working directory, session-state path layout, and path conventions used to @@ -14214,11 +16392,12 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionOpenOptionsAdditionalContentExclusionPolicyRule: - """Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRule` type.""" - + """Single content-exclusion rule supplied to `sessions.open` options, with paths, match + conditions, and source. + """ paths: list[str] source: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource - """Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type.""" + """Source descriptor for a `sessions.open` content-exclusion rule, with source name and type.""" if_any_match: list[str] | None = None if_none_match: list[str] | None = None @@ -14245,7 +16424,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsOpenProgress: - """Schema for the `SessionsOpenProgress` type.""" + """`sessions.open` handoff progress update with step, status, and optional message.""" status: SessionsOpenProgressStatus """Step status.""" @@ -14272,6 +16451,33 @@ def to_dict(self) -> dict: result["message"] = from_union([from_str, from_none], self.message) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsJobSnapshot: + """Redacted job settings for a session. The job nonce is excluded.""" + + built_in_tool_availability: SessionSettingsBuiltInToolAvailabilitySnapshot | None = None + event_type: str | None = None + is_trigger_job: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsJobSnapshot': + assert isinstance(obj, dict) + built_in_tool_availability = from_union([SessionSettingsBuiltInToolAvailabilitySnapshot.from_dict, from_none], obj.get("builtInToolAvailability")) + event_type = from_union([from_str, from_none], obj.get("eventType")) + is_trigger_job = from_union([from_bool, from_none], obj.get("isTriggerJob")) + return SessionSettingsJobSnapshot(built_in_tool_availability, event_type, is_trigger_job) + + def to_dict(self) -> dict: + result: dict = {} + if self.built_in_tool_availability is not None: + result["builtInToolAvailability"] = from_union([lambda x: to_class(SessionSettingsBuiltInToolAvailabilitySnapshot, x), from_none], self.built_in_tool_availability) + if self.event_type is not None: + result["eventType"] = from_union([from_str, from_none], self.event_type) + if self.is_trigger_job is not None: + result["isTriggerJob"] = from_union([from_bool, from_none], self.is_trigger_job) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsListRequest: @@ -14323,6 +16529,98 @@ def to_dict(self) -> dict: result["throwOnError"] = from_union([from_bool, from_none], self.throw_on_error) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class VisibilityGetResult: + """Current sharing status and shareable GitHub URL for a session.""" + + synced: bool + """Whether the session has been synced to Mission Control (i.e. has a GitHub task). When + false, the session cannot be shared and `status`/`shareUrl` are absent. + """ + share_url: str | None = None + """Shareable GitHub URL for the session. Present when the session is synced and the URL can + be resolved. + """ + status: SessionVisibilityStatus | None = None + """Current sharing status. Absent when the session is not synced or the status could not be + retrieved (e.g. the user is not authenticated). + """ + + @staticmethod + def from_dict(obj: Any) -> 'VisibilityGetResult': + assert isinstance(obj, dict) + synced = from_bool(obj.get("synced")) + share_url = from_union([from_str, from_none], obj.get("shareUrl")) + status = from_union([SessionVisibilityStatus, from_none], obj.get("status")) + return VisibilityGetResult(synced, share_url, status) + + def to_dict(self) -> dict: + result: dict = {} + result["synced"] = from_bool(self.synced) + if self.share_url is not None: + result["shareUrl"] = from_union([from_str, from_none], self.share_url) + if self.status is not None: + result["status"] = from_union([lambda x: to_enum(SessionVisibilityStatus, x), from_none], self.status) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class VisibilitySetRequest: + """Desired sharing status for the session.""" + + status: SessionVisibilityStatus + """Sharing status to apply. "repo" makes the session visible to repository readers; + "unshared" restricts it to the creator and collaborators. + """ + + @staticmethod + def from_dict(obj: Any) -> 'VisibilitySetRequest': + assert isinstance(obj, dict) + status = SessionVisibilityStatus(obj.get("status")) + return VisibilitySetRequest(status) + + def to_dict(self) -> dict: + result: dict = {} + result["status"] = to_enum(SessionVisibilityStatus, self.status) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class VisibilitySetResult: + """Effective sharing status and shareable GitHub URL after updating session visibility.""" + + synced: bool + """Whether the session has been synced to Mission Control (i.e. has a GitHub task). When + false, the visibility change could not be applied and `status`/`shareUrl` are absent. + """ + share_url: str | None = None + """Shareable GitHub URL for the session. Present when the session is synced and the URL can + be resolved. + """ + status: SessionVisibilityStatus | None = None + """Effective sharing status after the update. May differ from the requested status for task + types that are already visible to repository readers by default. Absent when the update + could not be applied (e.g. the session is not synced or the user is not authenticated). + """ + + @staticmethod + def from_dict(obj: Any) -> 'VisibilitySetResult': + assert isinstance(obj, dict) + synced = from_bool(obj.get("synced")) + share_url = from_union([from_str, from_none], obj.get("shareUrl")) + status = from_union([SessionVisibilityStatus, from_none], obj.get("status")) + return VisibilitySetResult(synced, share_url, status) + + def to_dict(self) -> dict: + result: dict = {} + result["synced"] = from_bool(self.synced) + if self.share_url is not None: + result["shareUrl"] = from_union([from_str, from_none], self.share_url) + if self.status is not None: + result["status"] = from_union([lambda x: to_enum(SessionVisibilityStatus, x), from_none], self.status) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsOpenAttach: @@ -14378,7 +16676,8 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AgentInfo: - """Schema for the `AgentInfo` type. + """Custom agent metadata, including identifiers, display details, source, tools, model, MCP + servers, skills, and file path. The newly selected custom agent """ @@ -14478,6 +16777,7 @@ def to_dict(self) -> dict: result["skills"] = from_list(lambda x: to_class(Skill, x), self.skills) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SkillsConfigSetDisabledSkillsRequest: """Skill names to mark as disabled in global configuration, replacing any previous list.""" @@ -14498,65 +16798,88 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SkillDiscoveryPath: - """Schema for the `SkillDiscoveryPath` type.""" +class SkillsInvokedSkill: + """Skill invocation record with name, path, content, allowed tools, and turn number.""" - path: str - """Absolute path of the create/discovery target (may not exist on disk yet)""" + content: str + """Full content of the skill file""" - preferred_for_creation: bool - """Whether this is the canonical directory to create a new skill in its tier. At most one - entry per tier is preferred; the `personal-agents` and `custom` scopes are never - preferred. - """ - scope: SkillDiscoveryScope - """Which tier this directory belongs to""" + invoked_at_turn: int + """Turn number when the skill was invoked""" - project_path: str | None = None - """The input project path this directory was derived from (only for project scope)""" + name: str + """Unique identifier for the skill""" + + path: str + """Path to the SKILL.md file""" + + allowed_tools: list[str] | None = None + """Tools that should be auto-approved when this skill is active, captured at invocation time""" @staticmethod - def from_dict(obj: Any) -> 'SkillDiscoveryPath': + def from_dict(obj: Any) -> 'SkillsInvokedSkill': assert isinstance(obj, dict) + content = from_str(obj.get("content")) + invoked_at_turn = from_int(obj.get("invokedAtTurn")) + name = from_str(obj.get("name")) path = from_str(obj.get("path")) - preferred_for_creation = from_bool(obj.get("preferredForCreation")) - scope = SkillDiscoveryScope(obj.get("scope")) - project_path = from_union([from_str, from_none], obj.get("projectPath")) - return SkillDiscoveryPath(path, preferred_for_creation, scope, project_path) + allowed_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("allowedTools")) + return SkillsInvokedSkill(content, invoked_at_turn, name, path, allowed_tools) def to_dict(self) -> dict: result: dict = {} + result["content"] = from_str(self.content) + result["invokedAtTurn"] = from_int(self.invoked_at_turn) + result["name"] = from_str(self.name) result["path"] = from_str(self.path) - result["preferredForCreation"] = from_bool(self.preferred_for_creation) - result["scope"] = to_enum(SkillDiscoveryScope, self.scope) - if self.project_path is not None: - result["projectPath"] = from_union([from_str, from_none], self.project_path) + if self.allowed_tools is not None: + result["allowedTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.allowed_tools) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SkillsGetInvokedResult: - """Skills invoked during this session, ordered by invocation time (most recent last).""" +class SkillDiscoveryPath: + """Canonical directory where skills can be discovered or created, with scope, preference, + and optional project path. + """ + path: str + """Absolute path of the create/discovery target (may not exist on disk yet)""" - skills: list[SkillsInvokedSkill] - """Skills invoked during this session, ordered by invocation time (most recent last)""" + preferred_for_creation: bool + """Whether this is the canonical directory to create a new skill in its tier. At most one + entry per tier is preferred; the `personal-agents` and `custom` scopes are never + preferred. + """ + scope: SkillDiscoveryScope + """Which tier this directory belongs to""" + + project_path: str | None = None + """The input project path this directory was derived from (only for project scope)""" @staticmethod - def from_dict(obj: Any) -> 'SkillsGetInvokedResult': + def from_dict(obj: Any) -> 'SkillDiscoveryPath': assert isinstance(obj, dict) - skills = from_list(SkillsInvokedSkill.from_dict, obj.get("skills")) - return SkillsGetInvokedResult(skills) + path = from_str(obj.get("path")) + preferred_for_creation = from_bool(obj.get("preferredForCreation")) + scope = SkillDiscoveryScope(obj.get("scope")) + project_path = from_union([from_str, from_none], obj.get("projectPath")) + return SkillDiscoveryPath(path, preferred_for_creation, scope, project_path) def to_dict(self) -> dict: result: dict = {} - result["skills"] = from_list(lambda x: to_class(SkillsInvokedSkill, x), self.skills) + result["path"] = from_str(self.path) + result["preferredForCreation"] = from_bool(self.preferred_for_creation) + result["scope"] = to_enum(SkillDiscoveryScope, self.scope) + if self.project_path is not None: + result["projectPath"] = from_union([from_str, from_none], self.project_path) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SlashCommandAgentPromptResult: - """Schema for the `SlashCommandAgentPromptResult` type.""" - + """Slash-command invocation result that submits an agent prompt, with display prompt, + optional mode, optional user-facing notice, and settings-change flag. + """ display_prompt: str """Prompt text to display to the user""" @@ -14569,6 +16892,9 @@ class SlashCommandAgentPromptResult: mode: SessionMode | None = None """Optional target session mode for the agent prompt""" + notice: str | None = None + """Optional user-facing notice to show before the prompt is submitted""" + runtime_settings_changed: bool | None = None """True when the invocation mutated user runtime settings; consumers caching settings should refresh @@ -14580,8 +16906,9 @@ def from_dict(obj: Any) -> 'SlashCommandAgentPromptResult': display_prompt = from_str(obj.get("displayPrompt")) prompt = from_str(obj.get("prompt")) mode = from_union([SessionMode, from_none], obj.get("mode")) + notice = from_union([from_str, from_none], obj.get("notice")) runtime_settings_changed = from_union([from_bool, from_none], obj.get("runtimeSettingsChanged")) - return SlashCommandAgentPromptResult(display_prompt, prompt, mode, runtime_settings_changed) + return SlashCommandAgentPromptResult(display_prompt, prompt, mode, notice, runtime_settings_changed) def to_dict(self) -> dict: result: dict = {} @@ -14590,6 +16917,8 @@ def to_dict(self) -> dict: result["prompt"] = from_str(self.prompt) if self.mode is not None: result["mode"] = from_union([lambda x: to_enum(SessionMode, x), from_none], self.mode) + if self.notice is not None: + result["notice"] = from_union([from_str, from_none], self.notice) if self.runtime_settings_changed is not None: result["runtimeSettingsChanged"] = from_union([from_bool, from_none], self.runtime_settings_changed) return result @@ -14597,8 +16926,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SlashCommandCompletedResult: - """Schema for the `SlashCommandCompletedResult` type.""" - + """Slash-command invocation result indicating completion, with optional message and + settings-change flag. + """ kind: ClassVar[str] = "completed" """Completed result discriminator""" @@ -14629,8 +16959,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SlashCommandSelectSubcommandResult: - """Schema for the `SlashCommandSelectSubcommandResult` type.""" - + """Slash-command invocation result asking the client to present subcommand options for a + parent command. + """ command: str """Parent command name that requires subcommand selection""" @@ -14670,8 +17001,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class TaskAgentProgress: - """Schema for the `TaskAgentProgress` type.""" - + """Progress snapshot for an agent task, with recent activity lines and optional latest + intent. + """ recent_activity: list[TaskProgressLine] """Recent tool execution events converted to display lines""" @@ -14699,9 +17031,57 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class TaskShellInfo: - """Schema for the `TaskShellInfo` type.""" +class TaskProgress: + """Progress snapshot for an agent task, with recent activity lines and optional latest + intent. + + Progress snapshot for a shell task, with recent stdout/stderr output and optional process + ID. + """ + type: TaskInfoType + """Progress kind""" + + latest_intent: str | None = None + """The most recent intent reported by the agent""" + + recent_activity: list[TaskProgressLine] | None = None + """Recent tool execution events converted to display lines""" + + pid: int | None = None + """Process ID when available""" + + recent_output: str | None = None + """Recent stdout/stderr lines from the running shell command""" + + @staticmethod + def from_dict(obj: Any) -> 'TaskProgress': + assert isinstance(obj, dict) + type = TaskInfoType(obj.get("type")) + latest_intent = from_union([from_str, from_none], obj.get("latestIntent")) + recent_activity = from_union([lambda x: from_list(TaskProgressLine.from_dict, x), from_none], obj.get("recentActivity")) + pid = from_union([from_int, from_none], obj.get("pid")) + recent_output = from_union([from_str, from_none], obj.get("recentOutput")) + return TaskProgress(type, latest_intent, recent_activity, pid, recent_output) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = to_enum(TaskInfoType, self.type) + if self.latest_intent is not None: + result["latestIntent"] = from_union([from_str, from_none], self.latest_intent) + if self.recent_activity is not None: + result["recentActivity"] = from_union([lambda x: from_list(lambda x: to_class(TaskProgressLine, x), x), from_none], self.recent_activity) + if self.pid is not None: + result["pid"] = from_union([from_int, from_none], self.pid) + if self.recent_output is not None: + result["recentOutput"] = from_union([from_str, from_none], self.recent_output) + return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class TaskShellInfo: + """Tracked shell task metadata, including ID, command, status, timing, attachment/execution + mode, log path, and PID. + """ attachment_mode: TaskShellInfoAttachmentMode """Whether the shell runs inside a managed PTY session or as an independent background process @@ -14779,8 +17159,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class TaskShellProgress: - """Schema for the `TaskShellProgress` type.""" - + """Progress snapshot for a shell task, with recent stdout/stderr output and optional process + ID. + """ recent_output: str """Recent stdout/stderr lines from the running shell command""" @@ -14845,27 +17226,32 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class MCPTools: - """Schema for the `McpTools` type.""" - - name: str - """Tool name.""" +class MCPToolUI: + """Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` + block was present without recognized fields. - description: str | None = None - """Tool description, when provided.""" + Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. + """ + resource_uri: str | None = None + """URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use + `session.mcp.resources.read` to fetch its HTML and resource metadata. + """ + visibility: list[MCPToolUIVisibility] | None = None + """Tool visibility advertised by the server. When absent, MCP Apps defaults apply.""" @staticmethod - def from_dict(obj: Any) -> 'MCPTools': + def from_dict(obj: Any) -> 'MCPToolUI': assert isinstance(obj, dict) - name = from_str(obj.get("name")) - description = from_union([from_str, from_none], obj.get("description")) - return MCPTools(name, description) + resource_uri = from_union([from_str, from_none], obj.get("resourceUri")) + visibility = from_union([lambda x: from_list(MCPToolUIVisibility, x), from_none], obj.get("visibility")) + return MCPToolUI(resource_uri, visibility) def to_dict(self) -> dict: result: dict = {} - result["name"] = from_str(self.name) - if self.description is not None: - result["description"] = from_union([from_str, from_none], self.description) + if self.resource_uri is not None: + result["resourceUri"] = from_union([from_str, from_none], self.resource_uri) + if self.visibility is not None: + result["visibility"] = from_union([lambda x: from_list(lambda x: to_enum(MCPToolUIVisibility, x), x), from_none], self.visibility) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -14894,9 +17280,35 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class TaskAgentInfo: - """Schema for the `TaskAgentInfo` type.""" +class SessionSettingsEvaluatePredicateRequest: + """Named Rust-owned settings predicate to evaluate for this session.""" + + name: SessionSettingsPredicateName + """Predicate name. The runtime owns the raw feature-flag names and composition logic.""" + + tool_name: str | None = None + """Tool name for tool-scoped predicates such as trivial-change handling.""" + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsEvaluatePredicateRequest': + assert isinstance(obj, dict) + name = SessionSettingsPredicateName(obj.get("name")) + tool_name = from_union([from_str, from_none], obj.get("toolName")) + return SessionSettingsEvaluatePredicateRequest(name, tool_name) + + def to_dict(self) -> dict: + result: dict = {} + result["name"] = to_enum(SessionSettingsPredicateName, self.name) + if self.tool_name is not None: + result["toolName"] = from_union([from_str, from_none], self.tool_name) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class TaskAgentInfo: + """Tracked background agent task metadata, including IDs, status, timing, agent type, + prompt, model, result, and latest response. + """ agent_type: str """Type of agent running this task""" @@ -15014,6 +17426,7 @@ def to_dict(self) -> dict: result["result"] = from_union([from_str, from_none], self.result) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ToolList: """Built-in tools available for the requested model, with their parameters and instructions.""" @@ -15432,8 +17845,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UIExitPlanModeResponse: - """Schema for the `UIExitPlanModeResponse` type.""" - + """User response for a pending exit-plan-mode request, with approval state, selected action, + auto-approve flag, and feedback. + """ approved: bool """Whether the plan was approved.""" @@ -15468,6 +17882,39 @@ def to_dict(self) -> dict: result["selectedAction"] = from_union([lambda x: to_enum(UIExitPlanModeAction, x), from_none], self.selected_action) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UISessionLimitsExhaustedResponse: + """The selected session-limit action. + + The user's selected action for an exhausted session limit. + """ + action: UISessionLimitsExhaustedResponseAction + """Action selected by the user.""" + + additional_ai_credits: float | None = None + """AI Credits to add to the current max when action is 'add'.""" + + max_ai_credits: float | None = None + """New absolute max AI Credits when action is 'set'.""" + + @staticmethod + def from_dict(obj: Any) -> 'UISessionLimitsExhaustedResponse': + assert isinstance(obj, dict) + action = UISessionLimitsExhaustedResponseAction(obj.get("action")) + additional_ai_credits = from_union([from_float, from_none], obj.get("additionalAiCredits")) + max_ai_credits = from_union([from_float, from_none], obj.get("maxAiCredits")) + return UISessionLimitsExhaustedResponse(action, additional_ai_credits, max_ai_credits) + + def to_dict(self) -> dict: + result: dict = {} + result["action"] = to_enum(UISessionLimitsExhaustedResponseAction, self.action) + if self.additional_ai_credits is not None: + result["additionalAiCredits"] = from_union([to_float, from_none], self.additional_ai_credits) + if self.max_ai_credits is not None: + result["maxAiCredits"] = from_union([to_float, from_none], self.max_ai_credits) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UIHandlePendingUserInputRequest: @@ -15477,7 +17924,9 @@ class UIHandlePendingUserInputRequest: """The unique request ID from the user_input.requested event""" response: UIUserInputResponse - """Schema for the `UIUserInputResponse` type.""" + """User response for a pending user-input request, with answer text and whether it was typed + freeform. + """ @staticmethod def from_dict(obj: Any) -> 'UIHandlePendingUserInputRequest': @@ -15495,8 +17944,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UsageMetricsModelMetric: - """Schema for the `UsageMetricsModelMetric` type.""" - + """Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and + per-token-type details. + """ requests: UsageMetricsModelMetricRequests """Request count and cost metrics for this model""" @@ -15528,6 +17978,29 @@ def to_dict(self) -> dict: result["totalNanoAiu"] = from_union([to_float, from_none], self.total_nano_aiu) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UserSettingsGetResult: + """Per-key metadata for every known user setting (settings.json overlaid with the legacy + config.json, config.json wins), including settings left at their default. Excludes + repository- and enterprise-managed overrides. + """ + settings: dict[str, UserSettingMetadata] + """Every known user setting keyed by setting name, each with its effective value, default, + and whether it is at the default. + """ + + @staticmethod + def from_dict(obj: Any) -> 'UserSettingsGetResult': + assert isinstance(obj, dict) + settings = from_dict(UserSettingMetadata.from_dict, obj.get("settings")) + return UserSettingsGetResult(settings) + + def to_dict(self) -> dict: + result: dict = {} + result["settings"] = from_dict(lambda x: to_class(UserSettingMetadata, x), self.settings) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkspaceDiffFileChange: @@ -15664,30 +18137,12 @@ def to_dict(self) -> dict: result["logCapture"] = from_union([lambda x: to_class(AgentRegistryLogCapture, x), from_none], self.log_capture) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CanvasList: - """Declared canvases available in this session.""" - - canvases: list[DiscoveredCanvas] - """Declared canvases available in this session""" - - @staticmethod - def from_dict(obj: Any) -> 'CanvasList': - assert isinstance(obj, dict) - canvases = from_list(DiscoveredCanvas.from_dict, obj.get("canvases")) - return CanvasList(canvases) - - def to_dict(self) -> dict: - result: dict = {} - result["canvases"] = from_list(lambda x: to_class(DiscoveredCanvas, x), self.canvases) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SlashCommandInfo: - """Schema for the `SlashCommandInfo` type.""" - + """Slash-command metadata with name, aliases, description, kind, input hint, execution + allowance, and schedulability. + """ allow_during_agent_execution: bool """Whether the command may run while an agent turn is active""" @@ -15789,124 +18244,78 @@ def to_dict(self) -> dict: result["capabilities"] = from_union([lambda x: to_class(CanvasHostContextCapabilities, x), from_none], self.capabilities) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CopilotUserResponse: - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ - access_type_sku: str | None = None - analytics_tracking_id: str | None = None - assigned_date: Any = None - can_signup_for_limited: bool | None = None - can_upgrade_plan: bool | None = None - chat_enabled: bool | None = None - cli_remote_control_enabled: bool | None = None - cloud_session_storage_enabled: bool | None = None - codex_agent_enabled: bool | None = None - copilot_plan: str | None = None - copilotignore_enabled: bool | None = None - endpoints: CopilotUserResponseEndpoints | None = None - """Schema for the `CopilotUserResponseEndpoints` type.""" - - is_mcp_enabled: Any = None - is_staff: bool | None = None - limited_user_quotas: dict[str, float] | None = None - limited_user_reset_date: str | None = None - login: str | None = None - monthly_quotas: dict[str, float] | None = None - organization_list: Any = None - organization_login_list: list[str] | None = None - quota_reset_date: str | None = None - quota_reset_date_utc: str | None = None - quota_snapshots: dict[str, CopilotUserResponseQuotaSnapshots | None] | None = None - """Schema for the `CopilotUserResponseQuotaSnapshots` type.""" +class CanvasList: + """Declared canvases available in this session.""" - restricted_telemetry: bool | None = None - token_based_billing: bool | None = None + canvases: list[DiscoveredCanvas] + """Declared canvases available in this session""" @staticmethod - def from_dict(obj: Any) -> 'CopilotUserResponse': + def from_dict(obj: Any) -> 'CanvasList': assert isinstance(obj, dict) - access_type_sku = from_union([from_str, from_none], obj.get("access_type_sku")) - analytics_tracking_id = from_union([from_str, from_none], obj.get("analytics_tracking_id")) - assigned_date = obj.get("assigned_date") - can_signup_for_limited = from_union([from_bool, from_none], obj.get("can_signup_for_limited")) - can_upgrade_plan = from_union([from_bool, from_none], obj.get("can_upgrade_plan")) - chat_enabled = from_union([from_bool, from_none], obj.get("chat_enabled")) - cli_remote_control_enabled = from_union([from_bool, from_none], obj.get("cli_remote_control_enabled")) - cloud_session_storage_enabled = from_union([from_bool, from_none], obj.get("cloud_session_storage_enabled")) - codex_agent_enabled = from_union([from_bool, from_none], obj.get("codex_agent_enabled")) - copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) - copilotignore_enabled = from_union([from_bool, from_none], obj.get("copilotignore_enabled")) - endpoints = from_union([CopilotUserResponseEndpoints.from_dict, from_none], obj.get("endpoints")) - is_mcp_enabled = obj.get("is_mcp_enabled") - is_staff = from_union([from_bool, from_none], obj.get("is_staff")) - limited_user_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("limited_user_quotas")) - limited_user_reset_date = from_union([from_str, from_none], obj.get("limited_user_reset_date")) - login = from_union([from_str, from_none], obj.get("login")) - monthly_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("monthly_quotas")) - organization_list = obj.get("organization_list") - organization_login_list = from_union([lambda x: from_list(from_str, x), from_none], obj.get("organization_login_list")) - quota_reset_date = from_union([from_str, from_none], obj.get("quota_reset_date")) - quota_reset_date_utc = from_union([from_str, from_none], obj.get("quota_reset_date_utc")) - quota_snapshots = from_union([lambda x: from_dict(lambda x: from_union([CopilotUserResponseQuotaSnapshots.from_dict, from_none], x), x), from_none], obj.get("quota_snapshots")) - restricted_telemetry = from_union([from_bool, from_none], obj.get("restricted_telemetry")) - token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) - return CopilotUserResponse(access_type_sku, analytics_tracking_id, assigned_date, can_signup_for_limited, can_upgrade_plan, chat_enabled, cli_remote_control_enabled, cloud_session_storage_enabled, codex_agent_enabled, copilot_plan, copilotignore_enabled, endpoints, is_mcp_enabled, is_staff, limited_user_quotas, limited_user_reset_date, login, monthly_quotas, organization_list, organization_login_list, quota_reset_date, quota_reset_date_utc, quota_snapshots, restricted_telemetry, token_based_billing) + canvases = from_list(DiscoveredCanvas.from_dict, obj.get("canvases")) + return CanvasList(canvases) def to_dict(self) -> dict: result: dict = {} - if self.access_type_sku is not None: - result["access_type_sku"] = from_union([from_str, from_none], self.access_type_sku) - if self.analytics_tracking_id is not None: - result["analytics_tracking_id"] = from_union([from_str, from_none], self.analytics_tracking_id) - if self.assigned_date is not None: - result["assigned_date"] = self.assigned_date - if self.can_signup_for_limited is not None: - result["can_signup_for_limited"] = from_union([from_bool, from_none], self.can_signup_for_limited) - if self.can_upgrade_plan is not None: - result["can_upgrade_plan"] = from_union([from_bool, from_none], self.can_upgrade_plan) - if self.chat_enabled is not None: - result["chat_enabled"] = from_union([from_bool, from_none], self.chat_enabled) - if self.cli_remote_control_enabled is not None: - result["cli_remote_control_enabled"] = from_union([from_bool, from_none], self.cli_remote_control_enabled) - if self.cloud_session_storage_enabled is not None: - result["cloud_session_storage_enabled"] = from_union([from_bool, from_none], self.cloud_session_storage_enabled) - if self.codex_agent_enabled is not None: - result["codex_agent_enabled"] = from_union([from_bool, from_none], self.codex_agent_enabled) - if self.copilot_plan is not None: - result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) - if self.copilotignore_enabled is not None: - result["copilotignore_enabled"] = from_union([from_bool, from_none], self.copilotignore_enabled) - if self.endpoints is not None: - result["endpoints"] = from_union([lambda x: to_class(CopilotUserResponseEndpoints, x), from_none], self.endpoints) - if self.is_mcp_enabled is not None: - result["is_mcp_enabled"] = self.is_mcp_enabled - if self.is_staff is not None: - result["is_staff"] = from_union([from_bool, from_none], self.is_staff) - if self.limited_user_quotas is not None: - result["limited_user_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.limited_user_quotas) - if self.limited_user_reset_date is not None: - result["limited_user_reset_date"] = from_union([from_str, from_none], self.limited_user_reset_date) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) - if self.monthly_quotas is not None: - result["monthly_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.monthly_quotas) - if self.organization_list is not None: - result["organization_list"] = self.organization_list - if self.organization_login_list is not None: - result["organization_login_list"] = from_union([lambda x: from_list(from_str, x), from_none], self.organization_login_list) - if self.quota_reset_date is not None: - result["quota_reset_date"] = from_union([from_str, from_none], self.quota_reset_date) - if self.quota_reset_date_utc is not None: - result["quota_reset_date_utc"] = from_union([from_str, from_none], self.quota_reset_date_utc) - if self.quota_snapshots is not None: - result["quota_snapshots"] = from_union([lambda x: from_dict(lambda x: from_union([lambda x: to_class(CopilotUserResponseQuotaSnapshots, x), from_none], x), x), from_none], self.quota_snapshots) - if self.restricted_telemetry is not None: - result["restricted_telemetry"] = from_union([from_bool, from_none], self.restricted_telemetry) - if self.token_based_billing is not None: - result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + result["canvases"] = from_list(lambda x: to_class(DiscoveredCanvas, x), self.canvases) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CanvasListOpenResult: + """Live open-canvas snapshot.""" + + open_canvases: list[OpenCanvasInstance] + """Currently open canvas instances""" + + @staticmethod + def from_dict(obj: Any) -> 'CanvasListOpenResult': + assert isinstance(obj, dict) + open_canvases = from_list(OpenCanvasInstance.from_dict, obj.get("openCanvases")) + return CanvasListOpenResult(open_canvases) + + def to_dict(self) -> dict: + result: dict = {} + result["openCanvases"] = from_list(lambda x: to_class(OpenCanvasInstance, x), self.open_canvases) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class DebugCollectLogsResult: + """Result of collecting a redacted debug bundle.""" + + entries: list[DebugCollectLogsCollectedEntry] + """Files included in the redacted bundle.""" + + kind: DebugCollectLogsResultKind + """Destination kind that was written.""" + + path: str + """Actual archive path or staging directory path written. This may differ from the requested + path when no-overwrite suffixing or fallback-to-temp-directory was needed. + """ + skipped_entries: list[DebugCollectLogsSkippedEntry] | None = None + """Optional files or directories that could not be included.""" + + @staticmethod + def from_dict(obj: Any) -> 'DebugCollectLogsResult': + assert isinstance(obj, dict) + entries = from_list(DebugCollectLogsCollectedEntry.from_dict, obj.get("entries")) + kind = DebugCollectLogsResultKind(obj.get("kind")) + path = from_str(obj.get("path")) + skipped_entries = from_union([lambda x: from_list(DebugCollectLogsSkippedEntry.from_dict, x), from_none], obj.get("skippedEntries")) + return DebugCollectLogsResult(entries, kind, path, skipped_entries) + + def to_dict(self) -> dict: + result: dict = {} + result["entries"] = from_list(lambda x: to_class(DebugCollectLogsCollectedEntry, x), self.entries) + result["kind"] = to_enum(DebugCollectLogsResultKind, self.kind) + result["path"] = from_str(self.path) + if self.skipped_entries is not None: + result["skippedEntries"] = from_union([lambda x: from_list(lambda x: to_class(DebugCollectLogsSkippedEntry, x), x), from_none], self.skipped_entries) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -15928,11 +18337,132 @@ def to_dict(self) -> dict: result["extensions"] = from_list(lambda x: to_class(Extension, x), self.extensions) return result +@dataclass +class PermissionDecisionApproveForIonApproval: + """Session-scoped approval to remember (tool prompts only; omitted for path/url prompts) + + Session-scoped approval details for specific command identifiers. + + Session-scoped approval details for read-only filesystem operations. + + Session-scoped approval details for filesystem write operations. + + Session-scoped approval details for an MCP server tool, or all tools on the server when + `toolName` is null. + + Session-scoped approval details for MCP sampling requests from a server. + + Session-scoped approval details for writes to long-term memory. + + Session-scoped approval details for a custom tool, keyed by tool name. + + Session-scoped approval details for extension-management operations, optionally narrowed + by operation. + + Session-scoped approval details for an extension's permission-gated capability access, + keyed by extension name. + + Approval to persist for this location + + Location-scoped approval details for specific command identifiers. + + Location-scoped approval details for read-only filesystem operations. + + Location-scoped approval details for filesystem write operations. + + Location-scoped approval details for an MCP server tool, or all tools on the server when + `toolName` is null. + + Location-scoped approval details for MCP sampling requests from a server. + + Location-scoped approval details for writes to long-term memory. + + Location-scoped approval details for a custom tool, keyed by tool name. + + Location-scoped approval details for extension-management operations, optionally narrowed + by operation. + + Location-scoped approval details for an extension's permission-gated capability access, + keyed by extension name. + + The approval to add as a session-scoped rule + + The approval to persist for this location + """ + command_identifiers: list[str] | None = None + """Command identifiers covered by this approval.""" + + kind: ApprovalKind | None = None + """Approval scoped to specific command identifiers. + + Approval covering read-only filesystem operations. + + Approval covering filesystem write operations. + + Approval covering an MCP tool. + + Approval covering MCP sampling requests for a server. + + Approval covering writes to long-term memory. + + Approval covering a custom tool. + + Approval covering extension lifecycle operations such as enable, disable, or reload. + + Approval covering an extension's request to access a permission-gated capability. + """ + server_name: str | None = None + """MCP server name.""" + + tool_name: str | None = None + """MCP tool name, or null to cover every tool on the server. + + Custom tool name. + """ + operation: str | None = None + """Optional operation identifier; when omitted, the approval covers all extension management + operations. + """ + extension_name: str | None = None + """Extension name.""" + + external_ref_marker_external_ref_user_tool_session_approval: str | None = None + + @staticmethod + def from_dict(obj: Any) -> 'PermissionDecisionApproveForIonApproval': + assert isinstance(obj, dict) + command_identifiers = from_union([lambda x: from_list(from_str, x), from_none], obj.get("commandIdentifiers")) + kind = from_union([ApprovalKind, from_none], obj.get("kind")) + server_name = from_union([from_str, from_none], obj.get("serverName")) + tool_name = from_union([from_none, from_str], obj.get("toolName")) + operation = from_union([from_str, from_none], obj.get("operation")) + extension_name = from_union([from_str, from_none], obj.get("extensionName")) + external_ref_marker_external_ref_user_tool_session_approval = from_union([from_str, from_none], obj.get("__externalRefMarker___ExternalRef_UserToolSessionApproval")) + return PermissionDecisionApproveForIonApproval(command_identifiers, kind, server_name, tool_name, operation, extension_name, external_ref_marker_external_ref_user_tool_session_approval) + + def to_dict(self) -> dict: + result: dict = {} + if self.command_identifiers is not None: + result["commandIdentifiers"] = from_union([lambda x: from_list(from_str, x), from_none], self.command_identifiers) + if self.kind is not None: + result["kind"] = from_union([lambda x: to_enum(ApprovalKind, x), from_none], self.kind) + if self.server_name is not None: + result["serverName"] = from_union([from_str, from_none], self.server_name) + if self.tool_name is not None: + result["toolName"] = from_union([from_none, from_str], self.tool_name) + if self.operation is not None: + result["operation"] = from_union([from_str, from_none], self.operation) + if self.extension_name is not None: + result["extensionName"] = from_union([from_str, from_none], self.extension_name) + if self.external_ref_marker_external_ref_user_tool_session_approval is not None: + result["__externalRefMarker___ExternalRef_UserToolSessionApproval"] = from_union([from_str, from_none], self.external_ref_marker_external_ref_user_tool_session_approval) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess: - """Schema for the `PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess` - type. + """Location-scoped approval details for an extension's permission-gated capability access, + keyed by extension name. """ extension_name: str """Extension name.""" @@ -15955,8 +18485,8 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess: - """Schema for the `PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess` - type. + """Session-scoped approval details for an extension's permission-gated capability access, + keyed by extension name. """ extension_name: str """Extension name.""" @@ -15979,8 +18509,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess: - """Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess` type.""" - + """Location-persisted tool approval details for an extension's permission-gated capability + access, keyed by extension name. + """ extension_name: str """Extension name.""" @@ -16023,6 +18554,11 @@ class ExternalToolTextResultForLlm: session_log: str | None = None """Detailed log content for timeline display""" + tool_references: list[str] | None = None + """Tool references returned by a tool-search override: names of deferred tools to surface to + the model. When set, the tool result is materialized as `tool_reference` content blocks + (rather than plain text) so the model knows which deferred tools are now available. + """ tool_telemetry: dict[str, Any] | None = None """Optional tool-specific telemetry""" @@ -16035,8 +18571,9 @@ def from_dict(obj: Any) -> 'ExternalToolTextResultForLlm': error = from_union([from_str, from_none], obj.get("error")) result_type = from_union([from_str, from_none], obj.get("resultType")) session_log = from_union([from_str, from_none], obj.get("sessionLog")) + tool_references = from_union([lambda x: from_list(from_str, x), from_none], obj.get("toolReferences")) tool_telemetry = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("toolTelemetry")) - return ExternalToolTextResultForLlm(text_result_for_llm, binary_results_for_llm, contents, error, result_type, session_log, tool_telemetry) + return ExternalToolTextResultForLlm(text_result_for_llm, binary_results_for_llm, contents, error, result_type, session_log, tool_references, tool_telemetry) def to_dict(self) -> dict: result: dict = {} @@ -16051,6 +18588,8 @@ def to_dict(self) -> dict: result["resultType"] = from_union([from_str, from_none], self.result_type) if self.session_log is not None: result["sessionLog"] = from_union([from_str, from_none], self.session_log) + if self.tool_references is not None: + result["toolReferences"] = from_union([lambda x: from_list(from_str, x), from_none], self.tool_references) if self.tool_telemetry is not None: result["toolTelemetry"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.tool_telemetry) return result @@ -16115,110 +18654,108 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class InstalledPluginSource: - """Schema for the `InstalledPluginSourceGitHub` type. +class InstalledPlugin: + """Installed plugin record from global state, with marketplace, version, install time, + enabled state, cache path, and source. + """ + enabled: bool + """Whether the plugin is currently enabled""" - Schema for the `InstalledPluginSourceUrl` type. + installed_at: str + """Installation timestamp""" - Schema for the `InstalledPluginSourceLocal` type. - """ - source: PurpleSource - """Constant value. Always "github". + marketplace: str + """Marketplace the plugin came from (empty string for direct repo installs)""" - Constant value. Always "url". + name: str + """Plugin name""" - Constant value. Always "local". - """ - path: str | None = None - ref: str | None = None - repo: str | None = None - url: str | None = None + cache_path: str | None = None + """Path where the plugin is cached locally""" + + source: InstalledPluginSource | str | None = None + """Source for direct repo installs (when marketplace is empty)""" + + version: str | None = None + """Version installed (if available)""" @staticmethod - def from_dict(obj: Any) -> 'InstalledPluginSource': + def from_dict(obj: Any) -> 'InstalledPlugin': assert isinstance(obj, dict) - source = PurpleSource(obj.get("source")) - path = from_union([from_str, from_none], obj.get("path")) - ref = from_union([from_str, from_none], obj.get("ref")) - repo = from_union([from_str, from_none], obj.get("repo")) - url = from_union([from_str, from_none], obj.get("url")) - return InstalledPluginSource(source, path, ref, repo, url) + enabled = from_bool(obj.get("enabled")) + installed_at = from_str(obj.get("installed_at")) + marketplace = from_str(obj.get("marketplace")) + name = from_str(obj.get("name")) + cache_path = from_union([from_str, from_none], obj.get("cache_path")) + source = from_union([InstalledPluginSource.from_dict, from_str, from_none], obj.get("source")) + version = from_union([from_str, from_none], obj.get("version")) + return InstalledPlugin(enabled, installed_at, marketplace, name, cache_path, source, version) def to_dict(self) -> dict: result: dict = {} - result["source"] = to_enum(PurpleSource, self.source) - if self.path is not None: - result["path"] = from_union([from_str, from_none], self.path) - if self.ref is not None: - result["ref"] = from_union([from_str, from_none], self.ref) - if self.repo is not None: - result["repo"] = from_union([from_str, from_none], self.repo) - if self.url is not None: - result["url"] = from_union([from_str, from_none], self.url) + result["enabled"] = from_bool(self.enabled) + result["installed_at"] = from_str(self.installed_at) + result["marketplace"] = from_str(self.marketplace) + result["name"] = from_str(self.name) + if self.cache_path is not None: + result["cache_path"] = from_union([from_str, from_none], self.cache_path) + if self.source is not None: + result["source"] = from_union([lambda x: to_class(InstalledPluginSource, x), from_str, from_none], self.source) + if self.version is not None: + result["version"] = from_union([from_str, from_none], self.version) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionInstalledPluginSource: - """Schema for the `SessionInstalledPluginSourceGitHub` type. +class SessionInstalledPlugin: + """Installed plugin record for a session, with marketplace, version, install time, enabled + state, cache path, and source. + """ + enabled: bool + """Whether the plugin is currently enabled""" - Schema for the `SessionInstalledPluginSourceUrl` type. + installed_at: str + """Installation timestamp (ISO-8601)""" - Schema for the `SessionInstalledPluginSourceLocal` type. - """ - source: PurpleSource - """Constant value. Always "github". + marketplace: str + """Marketplace the plugin came from (empty string for direct repo installs)""" - Constant value. Always "url". + name: str + """Plugin name""" - Constant value. Always "local". - """ - path: str | None = None - ref: str | None = None - repo: str | None = None - url: str | None = None - - @staticmethod - def from_dict(obj: Any) -> 'SessionInstalledPluginSource': - assert isinstance(obj, dict) - source = PurpleSource(obj.get("source")) - path = from_union([from_str, from_none], obj.get("path")) - ref = from_union([from_str, from_none], obj.get("ref")) - repo = from_union([from_str, from_none], obj.get("repo")) - url = from_union([from_str, from_none], obj.get("url")) - return SessionInstalledPluginSource(source, path, ref, repo, url) + cache_path: str | None = None + """Path where the plugin is cached locally""" - def to_dict(self) -> dict: - result: dict = {} - result["source"] = to_enum(PurpleSource, self.source) - if self.path is not None: - result["path"] = from_union([from_str, from_none], self.path) - if self.ref is not None: - result["ref"] = from_union([from_str, from_none], self.ref) - if self.repo is not None: - result["repo"] = from_union([from_str, from_none], self.repo) - if self.url is not None: - result["url"] = from_union([from_str, from_none], self.url) - return result + source: SessionInstalledPluginSource | str | None = None + """Source descriptor for direct repo installs (when marketplace is empty)""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class InstructionDiscoveryPathList: - """Canonical files and directories where custom instructions can be created so the runtime - will recognize them. - """ - paths: list[InstructionDiscoveryPath] - """Canonical instruction create/discovery files and directories, in priority order""" + version: str | None = None + """Installed version, if known""" @staticmethod - def from_dict(obj: Any) -> 'InstructionDiscoveryPathList': + def from_dict(obj: Any) -> 'SessionInstalledPlugin': assert isinstance(obj, dict) - paths = from_list(InstructionDiscoveryPath.from_dict, obj.get("paths")) - return InstructionDiscoveryPathList(paths) + enabled = from_bool(obj.get("enabled")) + installed_at = from_str(obj.get("installed_at")) + marketplace = from_str(obj.get("marketplace")) + name = from_str(obj.get("name")) + cache_path = from_union([from_str, from_none], obj.get("cache_path")) + source = from_union([SessionInstalledPluginSource.from_dict, from_str, from_none], obj.get("source")) + version = from_union([from_str, from_none], obj.get("version")) + return SessionInstalledPlugin(enabled, installed_at, marketplace, name, cache_path, source, version) def to_dict(self) -> dict: result: dict = {} - result["paths"] = from_list(lambda x: to_class(InstructionDiscoveryPath, x), self.paths) + result["enabled"] = from_bool(self.enabled) + result["installed_at"] = from_str(self.installed_at) + result["marketplace"] = from_str(self.marketplace) + result["name"] = from_str(self.name) + if self.cache_path is not None: + result["cache_path"] = from_union([from_str, from_none], self.cache_path) + if self.source is not None: + result["source"] = from_union([lambda x: to_class(SessionInstalledPluginSource, x), from_str, from_none], self.source) + if self.version is not None: + result["version"] = from_union([from_str, from_none], self.version) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -16262,8 +18799,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class LocalSessionMetadataValue: - """Schema for the `LocalSessionMetadataValue` type.""" - + """Persisted local session metadata, including identifiers, timestamps, summary/name, + client, context, detached state, and task ID. + """ is_remote: bool """Always false for local sessions.""" @@ -16591,6 +19129,36 @@ def to_dict(self) -> dict: result["user_named"] = from_union([from_bool, from_none], self.user_named) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesCheckpoints: + """Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint + filename. + """ + filename: str + """Filename of the checkpoint within the workspace checkpoints directory""" + + number: int + """Checkpoint number assigned by the workspace manager""" + + title: str + """Human-readable checkpoint title""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesCheckpoints': + assert isinstance(obj, dict) + filename = from_str(obj.get("filename")) + number = from_int(obj.get("number")) + title = from_str(obj.get("title")) + return WorkspacesCheckpoints(filename, number, title) + + def to_dict(self) -> dict: + result: dict = {} + result["filename"] = from_str(self.filename) + result["number"] = from_int(self.number) + result["title"] = from_str(self.title) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkspacesGetWorkspaceResult: @@ -16618,25 +19186,6 @@ def to_dict(self) -> dict: result["workspace"] = from_union([lambda x: to_class(Workspace, x), from_none], self.workspace) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class WorkspacesListCheckpointsResult: - """Workspace checkpoints in chronological order; empty when the workspace is not enabled.""" - - checkpoints: list[WorkspacesCheckpoints] - """Workspace checkpoints in chronological order. Empty when workspace is not enabled.""" - - @staticmethod - def from_dict(obj: Any) -> 'WorkspacesListCheckpointsResult': - assert isinstance(obj, dict) - checkpoints = from_list(WorkspacesCheckpoints.from_dict, obj.get("checkpoints")) - return WorkspacesListCheckpointsResult(checkpoints) - - def to_dict(self) -> dict: - result: dict = {} - result["checkpoints"] = from_list(lambda x: to_class(WorkspacesCheckpoints, x), self.checkpoints) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPAppsHostContext: @@ -16675,6 +19224,7 @@ def to_dict(self) -> dict: result["context"] = to_class(MCPAppsSetHostContextDetails, self.context) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigAddRequest: """MCP server name and configuration to add to user configuration.""" @@ -16698,6 +19248,7 @@ def to_dict(self) -> dict: result["name"] = from_str(self.name) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigList: """User-configured MCP servers, keyed by server name.""" @@ -16716,6 +19267,7 @@ def to_dict(self) -> dict: result["servers"] = from_dict(lambda x: to_class(MCPServerConfig, x), self.servers) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPConfigUpdateRequest: """MCP server name and replacement configuration to write to user configuration.""" @@ -16740,57 +19292,81 @@ def to_dict(self) -> dict: return result # Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. @dataclass class MCPRestartServerRequest: - """Server name and opaque configuration for an individual MCP server restart.""" - + """Server name and optional replacement configuration for an individual MCP server restart. + Omit `config` for a config-free restart-by-name of an already-configured server. + """ server_name: str """Name of the MCP server to restart""" - config: Any = None - """Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime - shape supplied only by in-process CLI callers. + config: MCPServerConfig | None = None + """Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart + the server with its already-registered configuration (config-free restart-by-name). """ + @staticmethod def from_dict(obj: Any) -> 'MCPRestartServerRequest': assert isinstance(obj, dict) - config = obj.get("config") server_name = from_str(obj.get("serverName")) - return MCPRestartServerRequest(config, server_name) + config = from_union([MCPServerConfig.from_dict, from_none], obj.get("config")) + return MCPRestartServerRequest(server_name, config) def to_dict(self) -> dict: result: dict = {} - result["config"] = self.config result["serverName"] = from_str(self.server_name) + if self.config is not None: + result["config"] = from_union([lambda x: to_class(MCPServerConfig, x), from_none], self.config) return result # Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. @dataclass class MCPStartServerRequest: - """Server name and opaque configuration for an individual MCP server start.""" + """Server name and configuration for an individual MCP server start.""" + + config: MCPServerConfig + """MCP server configuration (stdio process or remote HTTP/SSE)""" server_name: str """Name of the MCP server to start""" - config: Any = None - """Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime - shape supplied only by in-process CLI callers. - """ @staticmethod def from_dict(obj: Any) -> 'MCPStartServerRequest': assert isinstance(obj, dict) - config = obj.get("config") + config = MCPServerConfig.from_dict(obj.get("config")) server_name = from_str(obj.get("serverName")) return MCPStartServerRequest(config, server_name) def to_dict(self) -> dict: result: dict = {} - result["config"] = self.config + result["config"] = to_class(MCPServerConfig, self.config) result["serverName"] = from_str(self.server_name) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPHeadersHandlePendingHeadersRefreshRequestRequest: + """MCP headers refresh request id and the host response.""" + + request_id: str + """Headers refresh request identifier from mcp.headers_refresh_required""" + + result: MCPHeadersHandlePendingHeadersRefreshRequest + """Host response: supply dynamic headers or decline this refresh.""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPHeadersHandlePendingHeadersRefreshRequestRequest': + assert isinstance(obj, dict) + request_id = from_str(obj.get("requestId")) + result = MCPHeadersHandlePendingHeadersRefreshRequest.from_dict(obj.get("result")) + return MCPHeadersHandlePendingHeadersRefreshRequestRequest(request_id, result) + + def to_dict(self) -> dict: + result: dict = {} + result["requestId"] = from_str(self.request_id) + result["result"] = to_class(MCPHeadersHandlePendingHeadersRefreshRequest, self.result) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPOauthHandlePendingRequest: @@ -16815,120 +19391,305 @@ def to_dict(self) -> dict: result["result"] = to_class(MCPOauthPendingRequestResponse, self.result) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class ModelBilling: - """Billing information""" +class DebugCollectLogsEntry: + """A caller-provided server-local file or directory to include in the debug bundle.""" - multiplier: float | None = None - """Billing cost multiplier relative to the base rate""" + bundle_path: str + """Relative path to use inside the staged bundle/archive.""" - token_prices: ModelBillingTokenPrices | None = None - """Token-level pricing information for this model""" + kind: DebugCollectLogsEntryKind + """Kind of source path to include.""" + + path: str + """Server-local source path to read.""" + + redaction: DebugCollectLogsRedaction | None = None + """How text content from this entry should be redacted. Defaults to plain-text.""" + + required: bool | None = None + """When true, collection fails if this entry cannot be read. Defaults to false, which + records the entry in `skippedEntries`. + """ @staticmethod - def from_dict(obj: Any) -> 'ModelBilling': + def from_dict(obj: Any) -> 'DebugCollectLogsEntry': assert isinstance(obj, dict) - multiplier = from_union([from_float, from_none], obj.get("multiplier")) - token_prices = from_union([ModelBillingTokenPrices.from_dict, from_none], obj.get("tokenPrices")) - return ModelBilling(multiplier, token_prices) + bundle_path = from_str(obj.get("bundlePath")) + kind = DebugCollectLogsEntryKind(obj.get("kind")) + path = from_str(obj.get("path")) + redaction = from_union([DebugCollectLogsRedaction, from_none], obj.get("redaction")) + required = from_union([from_bool, from_none], obj.get("required")) + return DebugCollectLogsEntry(bundle_path, kind, path, redaction, required) def to_dict(self) -> dict: result: dict = {} - if self.multiplier is not None: - result["multiplier"] = from_union([to_float, from_none], self.multiplier) - if self.token_prices is not None: - result["tokenPrices"] = from_union([lambda x: to_class(ModelBillingTokenPrices, x), from_none], self.token_prices) + result["bundlePath"] = from_str(self.bundle_path) + result["kind"] = to_enum(DebugCollectLogsEntryKind, self.kind) + result["path"] = from_str(self.path) + if self.redaction is not None: + result["redaction"] = from_union([lambda x: to_enum(DebugCollectLogsRedaction, x), from_none], self.redaction) + if self.required is not None: + result["required"] = from_union([from_bool, from_none], self.required) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class ModelCapabilitiesOverride: - """Optional capability overrides (vision, tool_calls, reasoning, etc.). +class InstructionDiscoveryPath: + """Canonical file or directory where custom instructions can be discovered or created, with + location, kind, preference, and project path. + """ + kind: DebugCollectLogsEntryKind + """Whether the target is a single file or a directory of instruction files""" - Override individual model capabilities resolved by the runtime + location: InstructionLocation + """Which tier this target belongs to""" - Initial model capability overrides. + path: str + """Absolute path of the file or directory (may not exist on disk yet)""" - Per-property model capability overrides for the selected model. + preferred_for_creation: bool + """Whether this is the canonical target to create new instructions in its tier. At most one + entry per tier is preferred. """ - limits: ModelCapabilitiesOverrideLimits | None = None - """Token limits for prompts, outputs, and context window""" - - supports: ModelCapabilitiesOverrideSupports | None = None - """Feature flags indicating what the model supports""" + project_path: str | None = None + """The input project path this target was derived from (only for repository targets)""" @staticmethod - def from_dict(obj: Any) -> 'ModelCapabilitiesOverride': + def from_dict(obj: Any) -> 'InstructionDiscoveryPath': assert isinstance(obj, dict) - limits = from_union([ModelCapabilitiesOverrideLimits.from_dict, from_none], obj.get("limits")) - supports = from_union([ModelCapabilitiesOverrideSupports.from_dict, from_none], obj.get("supports")) - return ModelCapabilitiesOverride(limits, supports) + kind = DebugCollectLogsEntryKind(obj.get("kind")) + location = InstructionLocation(obj.get("location")) + path = from_str(obj.get("path")) + preferred_for_creation = from_bool(obj.get("preferredForCreation")) + project_path = from_union([from_str, from_none], obj.get("projectPath")) + return InstructionDiscoveryPath(kind, location, path, preferred_for_creation, project_path) def to_dict(self) -> dict: result: dict = {} - if self.limits is not None: - result["limits"] = from_union([lambda x: to_class(ModelCapabilitiesOverrideLimits, x), from_none], self.limits) - if self.supports is not None: - result["supports"] = from_union([lambda x: to_class(ModelCapabilitiesOverrideSupports, x), from_none], self.supports) + result["kind"] = to_enum(DebugCollectLogsEntryKind, self.kind) + result["location"] = to_enum(InstructionLocation, self.location) + result["path"] = from_str(self.path) + result["preferredForCreation"] = from_bool(self.preferred_for_creation) + if self.project_path is not None: + result["projectPath"] = from_union([from_str, from_none], self.project_path) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class ProviderTokenAcquireRequest: - """Asks the SDK client to acquire a bearer token for a BYOK provider whose config set - `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; - the runtime does no caching, so this is sent once per request. - """ - provider_name: str - """Name of the BYOK provider needing a token. For the legacy whole-session `provider` this - is the implicit provider name; for named providers it is `NamedProviderConfig.name`. +class SessionFSReaddirWithTypesEntry: + """Directory entry returned by session filesystem `readdirWithTypes`, with name and entry + type. """ - session_id: str - """Target session identifier""" + name: str + """Entry name""" + + type: DebugCollectLogsEntryKind + """Entry type""" @staticmethod - def from_dict(obj: Any) -> 'ProviderTokenAcquireRequest': + def from_dict(obj: Any) -> 'SessionFSReaddirWithTypesEntry': assert isinstance(obj, dict) - provider_name = from_str(obj.get("providerName")) - session_id = from_str(obj.get("sessionId")) - return ProviderTokenAcquireRequest(provider_name, session_id) + name = from_str(obj.get("name")) + type = DebugCollectLogsEntryKind(obj.get("type")) + return SessionFSReaddirWithTypesEntry(name, type) def to_dict(self) -> dict: result: dict = {} - result["providerName"] = from_str(self.provider_name) - result["sessionId"] = from_str(self.session_id) + result["name"] = from_str(self.name) + result["type"] = to_enum(DebugCollectLogsEntryKind, self.type) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class OptionsUpdateAdditionalContentExclusionPolicy: - """Schema for the `OptionsUpdateAdditionalContentExclusionPolicy` type.""" - - last_updated_at: Any - rules: list[OptionsUpdateAdditionalContentExclusionPolicyRule] - scope: AdditionalContentExclusionPolicyScope - """Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration.""" +class MetadataContextAttributionResult: + """Per-source attribution breakdown for the session's current context window, or null if + uninitialized. + """ + context_attribution: SessionContextAttribution | None = None + """Per-source context-window attribution, or null if the session has not yet been + initialized (no system prompt or tool metadata cached). + """ @staticmethod - def from_dict(obj: Any) -> 'OptionsUpdateAdditionalContentExclusionPolicy': + def from_dict(obj: Any) -> 'MetadataContextAttributionResult': assert isinstance(obj, dict) - last_updated_at = obj.get("last_updated_at") - rules = from_list(OptionsUpdateAdditionalContentExclusionPolicyRule.from_dict, obj.get("rules")) - scope = AdditionalContentExclusionPolicyScope(obj.get("scope")) - return OptionsUpdateAdditionalContentExclusionPolicy(last_updated_at, rules, scope) + context_attribution = from_union([SessionContextAttribution.from_dict, from_none], obj.get("contextAttribution")) + return MetadataContextAttributionResult(context_attribution) def to_dict(self) -> dict: result: dict = {} - result["last_updated_at"] = self.last_updated_at - result["rules"] = from_list(lambda x: to_class(OptionsUpdateAdditionalContentExclusionPolicyRule, x), self.rules) - result["scope"] = to_enum(AdditionalContentExclusionPolicyScope, self.scope) + if self.context_attribution is not None: + result["contextAttribution"] = from_union([lambda x: to_class(SessionContextAttribution, x), from_none], self.context_attribution) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class PermissionsConfigureAdditionalContentExclusionPolicy: - """Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type.""" +class ModelBilling: + """Billing information""" + + discount_percent: int | None = None + """Whole-number percentage discount (0-100) applied to usage billed through this model. + Populated for the synthetic `auto` model, where requests routed by auto-mode are billed + at a reduced rate; absent for concrete models. + """ + multiplier: float | None = None + """Billing cost multiplier relative to the base rate""" + + promo: ModelBillingPromo | None = None + """Active server-driven promotion for this model, if any. Present when the model is being + promoted with a time-boxed discount. + """ + token_prices: ModelBillingTokenPrices | None = None + """Token-level pricing information for this model""" + + @staticmethod + def from_dict(obj: Any) -> 'ModelBilling': + assert isinstance(obj, dict) + discount_percent = from_union([from_int, from_none], obj.get("discountPercent")) + multiplier = from_union([from_float, from_none], obj.get("multiplier")) + promo = from_union([ModelBillingPromo.from_dict, from_none], obj.get("promo")) + token_prices = from_union([ModelBillingTokenPrices.from_dict, from_none], obj.get("tokenPrices")) + return ModelBilling(discount_percent, multiplier, promo, token_prices) + + def to_dict(self) -> dict: + result: dict = {} + if self.discount_percent is not None: + result["discountPercent"] = from_union([from_int, from_none], self.discount_percent) + if self.multiplier is not None: + result["multiplier"] = from_union([to_float, from_none], self.multiplier) + if self.promo is not None: + result["promo"] = from_union([lambda x: to_class(ModelBillingPromo, x), from_none], self.promo) + if self.token_prices is not None: + result["tokenPrices"] = from_union([lambda x: to_class(ModelBillingTokenPrices, x), from_none], self.token_prices) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionModelList: + """The list of models available to this session.""" + + list: list[Any] + """Available models, ordered with the most preferred default first. Includes both Copilot + (CAPI) models and any registry BYOK models; a BYOK model appears under its + provider-qualified selection id (`provider/id`). + """ + model_price_categories: list[SessionModelPriceCategory] | None = None + """Cost categories for the full CAPI catalog, including picker-disabled models that Auto may + select. Metadata only; entries absent from `list` are not manually selectable. + """ + quota_snapshots: dict[str, Any] | None = None + """Per-quota snapshots returned alongside the model list, keyed by quota type.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionModelList': + assert isinstance(obj, dict) + list = from_list(lambda x: x, obj.get("list")) + model_price_categories = from_union([lambda x: from_list(SessionModelPriceCategory.from_dict, x), from_none], obj.get("modelPriceCategories")) + quota_snapshots = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("quotaSnapshots")) + return SessionModelList(list, model_price_categories, quota_snapshots) + + def to_dict(self) -> dict: + result: dict = {} + result["list"] = from_list(lambda x: x, self.list) + if self.model_price_categories is not None: + result["modelPriceCategories"] = from_union([lambda x: from_list(lambda x: to_class(SessionModelPriceCategory, x), x), from_none], self.model_price_categories) + if self.quota_snapshots is not None: + result["quotaSnapshots"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.quota_snapshots) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ModelCapabilitiesOverride: + """Optional capability overrides (vision, tool_calls, reasoning, etc.). + + Override individual model capabilities resolved by the runtime + + Initial model capability overrides. + + Per-property model capability overrides for the selected model. + """ + limits: ModelCapabilitiesOverrideLimits | None = None + """Token limits for prompts, outputs, and context window""" + + supports: ModelCapabilitiesOverrideSupports | None = None + """Feature flags indicating what the model supports""" + + @staticmethod + def from_dict(obj: Any) -> 'ModelCapabilitiesOverride': + assert isinstance(obj, dict) + limits = from_union([ModelCapabilitiesOverrideLimits.from_dict, from_none], obj.get("limits")) + supports = from_union([ModelCapabilitiesOverrideSupports.from_dict, from_none], obj.get("supports")) + return ModelCapabilitiesOverride(limits, supports) + + def to_dict(self) -> dict: + result: dict = {} + if self.limits is not None: + result["limits"] = from_union([lambda x: to_class(ModelCapabilitiesOverrideLimits, x), from_none], self.limits) + if self.supports is not None: + result["supports"] = from_union([lambda x: to_class(ModelCapabilitiesOverrideSupports, x), from_none], self.supports) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ProviderTokenAcquireRequest: + """Asks the SDK client to acquire a bearer token for a BYOK provider whose config set + `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; + the runtime does no caching, so this is sent once per request. + """ + provider_name: str + """Name of the BYOK provider needing a token. For the legacy whole-session `provider` this + is the implicit provider name; for named providers it is `NamedProviderConfig.name`. + """ + session_id: str + """Target session identifier""" + + @staticmethod + def from_dict(obj: Any) -> 'ProviderTokenAcquireRequest': + assert isinstance(obj, dict) + provider_name = from_str(obj.get("providerName")) + session_id = from_str(obj.get("sessionId")) + return ProviderTokenAcquireRequest(provider_name, session_id) + + def to_dict(self) -> dict: + result: dict = {} + result["providerName"] = from_str(self.provider_name) + result["sessionId"] = from_str(self.session_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class OptionsUpdateAdditionalContentExclusionPolicy: + """Content-exclusion policy supplied to `session.options.update`, with rules, last-updated + data, and scope. + """ + last_updated_at: Any + rules: list[OptionsUpdateAdditionalContentExclusionPolicyRule] + scope: AdditionalContentExclusionPolicyScope + """Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration.""" + + @staticmethod + def from_dict(obj: Any) -> 'OptionsUpdateAdditionalContentExclusionPolicy': + assert isinstance(obj, dict) + last_updated_at = obj.get("last_updated_at") + rules = from_list(OptionsUpdateAdditionalContentExclusionPolicyRule.from_dict, obj.get("rules")) + scope = AdditionalContentExclusionPolicyScope(obj.get("scope")) + return OptionsUpdateAdditionalContentExclusionPolicy(last_updated_at, rules, scope) + def to_dict(self) -> dict: + result: dict = {} + result["last_updated_at"] = self.last_updated_at + result["rules"] = from_list(lambda x: to_class(OptionsUpdateAdditionalContentExclusionPolicyRule, x), self.rules) + result["scope"] = to_enum(AdditionalContentExclusionPolicyScope, self.scope) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PermissionsConfigureAdditionalContentExclusionPolicy: + """Content-exclusion policy supplied to `session.permissions.configure`, with rules, + last-updated data, and scope. + """ last_updated_at: Any rules: list[PermissionsConfigureAdditionalContentExclusionPolicyRule] scope: AdditionalContentExclusionPolicyScope @@ -16951,6 +19712,7 @@ def to_dict(self) -> dict: result["scope"] = to_enum(AdditionalContentExclusionPolicyScope, self.scope) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPDiscoverResult: """MCP servers discovered from user, workspace, plugin, and built-in sources.""" @@ -17088,6 +19850,74 @@ def to_dict(self) -> dict: result["results"] = from_list(lambda x: to_class(PluginUpdateAllEntry, x), self.results) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubFileDiff: + """Pointer to a single-file diff. At least one of `head` and `base` must be present.""" + + type: ClassVar[str] = "github_file_diff" + """Attachment type discriminator""" + + url: str + """URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL)""" + + base: PushAttachmentGitHubFileDiffSide | None = None + """File location on the base side of the diff. Absent for additions.""" + + head: PushAttachmentGitHubFileDiffSide | None = None + """File location on the head side of the diff. Absent for deletions.""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubFileDiff': + assert isinstance(obj, dict) + url = from_str(obj.get("url")) + base = from_union([PushAttachmentGitHubFileDiffSide.from_dict, from_none], obj.get("base")) + head = from_union([PushAttachmentGitHubFileDiffSide.from_dict, from_none], obj.get("head")) + return PushAttachmentGitHubFileDiff(url, base, head) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = self.type + result["url"] = from_str(self.url) + if self.base is not None: + result["base"] = from_union([lambda x: to_class(PushAttachmentGitHubFileDiffSide, x), from_none], self.base) + if self.head is not None: + result["head"] = from_union([lambda x: to_class(PushAttachmentGitHubFileDiffSide, x), from_none], self.head) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubTreeComparison: + """Pointer to a comparison between two git revisions.""" + + base: PushAttachmentGitHubTreeComparisonSide + """Base side of the comparison""" + + head: PushAttachmentGitHubTreeComparisonSide + """Head side of the comparison""" + + type: ClassVar[str] = "github_tree_comparison" + """Attachment type discriminator""" + + url: str + """URL to the comparison on GitHub""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubTreeComparison': + assert isinstance(obj, dict) + base = PushAttachmentGitHubTreeComparisonSide.from_dict(obj.get("base")) + head = PushAttachmentGitHubTreeComparisonSide.from_dict(obj.get("head")) + url = from_str(obj.get("url")) + return PushAttachmentGitHubTreeComparison(base, head, url) + + def to_dict(self) -> dict: + result: dict = {} + result["base"] = to_class(PushAttachmentGitHubTreeComparisonSide, self.base) + result["head"] = to_class(PushAttachmentGitHubTreeComparisonSide, self.head) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PushAttachmentSelection: @@ -17266,32 +20096,6 @@ def to_dict(self) -> dict: result["error"] = from_union([lambda x: to_class(SessionFSError, x), from_none], self.error) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionFSReaddirWithTypesResult: - """Entries in the requested directory paired with file/directory type information, or a - filesystem error if the read failed. - """ - entries: list[SessionFSReaddirWithTypesEntry] - """Directory entries with type information""" - - error: SessionFSError | None = None - """Describes a filesystem error.""" - - @staticmethod - def from_dict(obj: Any) -> 'SessionFSReaddirWithTypesResult': - assert isinstance(obj, dict) - entries = from_list(SessionFSReaddirWithTypesEntry.from_dict, obj.get("entries")) - error = from_union([SessionFSError.from_dict, from_none], obj.get("error")) - return SessionFSReaddirWithTypesResult(entries, error) - - def to_dict(self) -> dict: - result: dict = {} - result["entries"] = from_list(lambda x: to_class(SessionFSReaddirWithTypesEntry, x), self.entries) - if self.error is not None: - result["error"] = from_union([lambda x: to_class(SessionFSError, x), from_none], self.error) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionFSSqliteQueryResult: @@ -17382,8 +20186,9 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionOpenOptionsAdditionalContentExclusionPolicy: - """Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicy` type.""" - + """Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated + data, and scope. + """ last_updated_at: Any rules: list[SessionOpenOptionsAdditionalContentExclusionPolicyRule] scope: AdditionalContentExclusionPolicyScope @@ -17406,6 +20211,53 @@ def to_dict(self) -> dict: result["scope"] = to_enum(AdditionalContentExclusionPolicyScope, self.scope) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionSettingsSnapshot: + """Redacted, serializable view of session runtime settings for SDK boundary consumers. + Secrets and raw feature flags are intentionally excluded. + """ + job: SessionSettingsJobSnapshot + model: SessionSettingsModelSnapshot + online_evaluation: SessionSettingsOnlineEvaluationSnapshot + repo: SessionSettingsRepoSnapshot + validation: SessionSettingsValidationSnapshot + client_name: str | None = None + start_time_ms: float | None = None + timeout_ms: float | None = None + version: str | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionSettingsSnapshot': + assert isinstance(obj, dict) + job = SessionSettingsJobSnapshot.from_dict(obj.get("job")) + model = SessionSettingsModelSnapshot.from_dict(obj.get("model")) + online_evaluation = SessionSettingsOnlineEvaluationSnapshot.from_dict(obj.get("onlineEvaluation")) + repo = SessionSettingsRepoSnapshot.from_dict(obj.get("repo")) + validation = SessionSettingsValidationSnapshot.from_dict(obj.get("validation")) + client_name = from_union([from_str, from_none], obj.get("clientName")) + start_time_ms = from_union([from_float, from_none], obj.get("startTimeMs")) + timeout_ms = from_union([from_float, from_none], obj.get("timeoutMs")) + version = from_union([from_str, from_none], obj.get("version")) + return SessionSettingsSnapshot(job, model, online_evaluation, repo, validation, client_name, start_time_ms, timeout_ms, version) + + def to_dict(self) -> dict: + result: dict = {} + result["job"] = to_class(SessionSettingsJobSnapshot, self.job) + result["model"] = to_class(SessionSettingsModelSnapshot, self.model) + result["onlineEvaluation"] = to_class(SessionSettingsOnlineEvaluationSnapshot, self.online_evaluation) + result["repo"] = to_class(SessionSettingsRepoSnapshot, self.repo) + result["validation"] = to_class(SessionSettingsValidationSnapshot, self.validation) + if self.client_name is not None: + result["clientName"] = from_union([from_str, from_none], self.client_name) + if self.start_time_ms is not None: + result["startTimeMs"] = from_union([to_float, from_none], self.start_time_ms) + if self.timeout_ms is not None: + result["timeoutMs"] = from_union([to_float, from_none], self.timeout_ms) + if self.version is not None: + result["version"] = from_union([from_str, from_none], self.version) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AgentGetCurrentResult: @@ -17502,6 +20354,25 @@ def to_dict(self) -> dict: result["agents"] = from_list(lambda x: to_class(AgentInfo, x), self.agents) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SkillsGetInvokedResult: + """Skills invoked during this session, ordered by invocation time (most recent last).""" + + skills: list[SkillsInvokedSkill] + """Skills invoked during this session, ordered by invocation time (most recent last)""" + + @staticmethod + def from_dict(obj: Any) -> 'SkillsGetInvokedResult': + assert isinstance(obj, dict) + skills = from_list(SkillsInvokedSkill.from_dict, obj.get("skills")) + return SkillsGetInvokedResult(skills) + + def to_dict(self) -> dict: + result: dict = {} + result["skills"] = from_list(lambda x: to_class(SkillsInvokedSkill, x), self.skills) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SkillDiscoveryPathList: @@ -17523,66 +20394,58 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class TaskProgress: - """Schema for the `TaskAgentProgress` type. +class TasksGetProgressResult: + """Progress information for the task, or null when no task with that ID is tracked.""" - Schema for the `TaskShellProgress` type. + progress: TaskProgress | None = None + """Progress information for the task, discriminated by type. Returns null when no task with + this ID is currently tracked. """ - type: TaskInfoType - """Progress kind""" - - latest_intent: str | None = None - """The most recent intent reported by the agent""" - - recent_activity: list[TaskProgressLine] | None = None - """Recent tool execution events converted to display lines""" - - pid: int | None = None - """Process ID when available""" - - recent_output: str | None = None - """Recent stdout/stderr lines from the running shell command""" @staticmethod - def from_dict(obj: Any) -> 'TaskProgress': + def from_dict(obj: Any) -> 'TasksGetProgressResult': assert isinstance(obj, dict) - type = TaskInfoType(obj.get("type")) - latest_intent = from_union([from_str, from_none], obj.get("latestIntent")) - recent_activity = from_union([lambda x: from_list(TaskProgressLine.from_dict, x), from_none], obj.get("recentActivity")) - pid = from_union([from_int, from_none], obj.get("pid")) - recent_output = from_union([from_str, from_none], obj.get("recentOutput")) - return TaskProgress(type, latest_intent, recent_activity, pid, recent_output) + progress = from_union([TaskProgress.from_dict, from_none], obj.get("progress")) + return TasksGetProgressResult(progress) def to_dict(self) -> dict: result: dict = {} - result["type"] = to_enum(TaskInfoType, self.type) - if self.latest_intent is not None: - result["latestIntent"] = from_union([from_str, from_none], self.latest_intent) - if self.recent_activity is not None: - result["recentActivity"] = from_union([lambda x: from_list(lambda x: to_class(TaskProgressLine, x), x), from_none], self.recent_activity) - if self.pid is not None: - result["pid"] = from_union([from_int, from_none], self.pid) - if self.recent_output is not None: - result["recentOutput"] = from_union([from_str, from_none], self.recent_output) + if self.progress is not None: + result["progress"] = from_union([lambda x: to_class(TaskProgress, x), from_none], self.progress) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class MCPListToolsResult: - """Tools exposed by the connected MCP server. Throws when the server is not connected.""" +class MCPTools: + """MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery + metadata. + """ + name: str + """Tool name.""" - tools: list[MCPTools] - """Tools exposed by the server.""" + description: str | None = None + """Tool description, when provided.""" + + ui: MCPToolUI | None = None + """Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` + block was present without recognized fields. + """ @staticmethod - def from_dict(obj: Any) -> 'MCPListToolsResult': + def from_dict(obj: Any) -> 'MCPTools': assert isinstance(obj, dict) - tools = from_list(MCPTools.from_dict, obj.get("tools")) - return MCPListToolsResult(tools) + name = from_str(obj.get("name")) + description = from_union([from_str, from_none], obj.get("description")) + ui = from_union([MCPToolUI.from_dict, from_none], obj.get("ui")) + return MCPTools(name, description, ui) def to_dict(self) -> dict: result: dict = {} - result["tools"] = from_list(lambda x: to_class(MCPTools, x), self.tools) + result["name"] = from_str(self.name) + if self.description is not None: + result["description"] = from_union([from_str, from_none], self.description) + if self.ui is not None: + result["ui"] = from_union([lambda x: to_class(MCPToolUI, x), from_none], self.ui) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -17854,7 +20717,9 @@ class UIHandlePendingExitPlanModeRequest: """The unique request ID from the exit_plan_mode.requested event""" response: UIExitPlanModeResponse - """Schema for the `UIExitPlanModeResponse` type.""" + """User response for a pending exit-plan-mode request, with approval state, selected action, + auto-approve flag, and feedback. + """ @staticmethod def from_dict(obj: Any) -> 'UIHandlePendingExitPlanModeRequest': @@ -17869,6 +20734,31 @@ def to_dict(self) -> dict: result["response"] = to_class(UIExitPlanModeResponse, self.response) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UIHandlePendingSessionLimitsExhaustedRequest: + """Request ID of a pending `session_limits_exhausted.requested` event and the user's + selected limit action. + """ + request_id: str + """The unique request ID from the session_limits_exhausted.requested event""" + + response: UISessionLimitsExhaustedResponse + """The selected session-limit action.""" + + @staticmethod + def from_dict(obj: Any) -> 'UIHandlePendingSessionLimitsExhaustedRequest': + assert isinstance(obj, dict) + request_id = from_str(obj.get("requestId")) + response = UISessionLimitsExhaustedResponse.from_dict(obj.get("response")) + return UIHandlePendingSessionLimitsExhaustedRequest(request_id, response) + + def to_dict(self) -> dict: + result: dict = {} + result["requestId"] = from_str(self.request_id) + result["response"] = to_class(UISessionLimitsExhaustedResponse, self.response) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class UsageGetMetricsResult: @@ -18157,1100 +21047,1121 @@ def to_dict(self) -> dict: result["session"] = from_union([lambda x: to_class(CanvasSessionContext, x), from_none], self.session) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class APIKeyAuthInfo: - """Schema for the `ApiKeyAuthInfo` type.""" - - api_key: str - """The API key. Treat as a secret.""" - - host: str - """Authentication host.""" +class HandlePendingToolCallRequest: + """Pending external tool call request ID, with the tool result or an error describing why it + failed. + """ + request_id: str + """Request ID of the pending tool call""" - type: ClassVar[str] = "api-key" - """API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style).""" + error: str | None = None + """Error message if the tool call failed""" - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ + result: ExternalToolTextResultForLlm | str | None = None + """Tool call result (string or expanded result object)""" @staticmethod - def from_dict(obj: Any) -> 'APIKeyAuthInfo': + def from_dict(obj: Any) -> 'HandlePendingToolCallRequest': assert isinstance(obj, dict) - api_key = from_str(obj.get("apiKey")) - host = from_str(obj.get("host")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return APIKeyAuthInfo(api_key, host, copilot_user) + request_id = from_str(obj.get("requestId")) + error = from_union([from_str, from_none], obj.get("error")) + result = from_union([ExternalToolTextResultForLlm.from_dict, from_str, from_none], obj.get("result")) + return HandlePendingToolCallRequest(request_id, error, result) def to_dict(self) -> dict: result: dict = {} - result["apiKey"] = from_str(self.api_key) - result["host"] = from_str(self.host) - result["type"] = self.type - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["requestId"] = from_str(self.request_id) + if self.error is not None: + result["error"] = from_union([from_str, from_none], self.error) + if self.result is not None: + result["result"] = from_union([lambda x: to_class(ExternalToolTextResultForLlm, x), from_str, from_none], self.result) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CopilotAPITokenAuthInfo: - """Schema for the `CopilotApiTokenAuthInfo` type.""" - - host: Host - """Authentication host (always the public GitHub host).""" +class SessionsSetAdditionalPluginsRequest: + """Manager-wide additional plugins to register; replaces any previously-configured set.""" - type: ClassVar[str] = "copilot-api-token" - """Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` - environment-variable pair. The token itself is read from the environment by the runtime, - not carried in this struct. - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. + plugins: list[InstalledPlugin] + """Manager-wide additional plugins to register. Replaces any previously-configured set. Pass + an empty array to clear. """ @staticmethod - def from_dict(obj: Any) -> 'CopilotAPITokenAuthInfo': + def from_dict(obj: Any) -> 'SessionsSetAdditionalPluginsRequest': assert isinstance(obj, dict) - host = Host(obj.get("host")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return CopilotAPITokenAuthInfo(host, copilot_user) + plugins = from_list(InstalledPlugin.from_dict, obj.get("plugins")) + return SessionsSetAdditionalPluginsRequest(plugins) def to_dict(self) -> dict: result: dict = {} - result["host"] = to_enum(Host, self.host) - result["type"] = self.type - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["plugins"] = from_list(lambda x: to_class(InstalledPlugin, x), self.plugins) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class EnvAuthInfo: - """Schema for the `EnvAuthInfo` type.""" - - env_var: str - """Name of the environment variable the token was sourced from.""" - - host: str - """Authentication host (e.g. https://github.com or a GHES host).""" - - token: str - """The token value itself. Treat as a secret.""" - - type: ClassVar[str] = "env" - """Personal access token (PAT) or server-to-server token sourced from an environment - variable. - """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. +class SessionEnrichMetadataResult: + """The enriched metadata records, with summary and context fields backfilled where + available. Sessions confirmed empty and unnamed are omitted. """ - login: str | None = None - """User login associated with the token. Undefined for server-to-server tokens (those - starting with `ghs_`). + sessions: list[LocalSessionMetadataValue] + """Enriched records, with summary and context backfilled. Sessions confirmed empty and + unnamed may be omitted. """ @staticmethod - def from_dict(obj: Any) -> 'EnvAuthInfo': + def from_dict(obj: Any) -> 'SessionEnrichMetadataResult': assert isinstance(obj, dict) - env_var = from_str(obj.get("envVar")) - host = from_str(obj.get("host")) - token = from_str(obj.get("token")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - login = from_union([from_str, from_none], obj.get("login")) - return EnvAuthInfo(env_var, host, token, copilot_user, login) + sessions = from_list(LocalSessionMetadataValue.from_dict, obj.get("sessions")) + return SessionEnrichMetadataResult(sessions) def to_dict(self) -> dict: result: dict = {} - result["envVar"] = from_str(self.env_var) - result["host"] = from_str(self.host) - result["token"] = from_str(self.token) - result["type"] = self.type - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) - if self.login is not None: - result["login"] = from_union([from_str, from_none], self.login) + result["sessions"] = from_list(lambda x: to_class(LocalSessionMetadataValue, x), self.sessions) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class GhCLIAuthInfo: - """Schema for the `GhCliAuthInfo` type.""" - - host: str - """Authentication host.""" - - login: str - """User login as reported by `gh auth status`.""" - - token: str - """The token returned by `gh auth token`. Treat as a secret.""" - - type: ClassVar[str] = "gh-cli" - """Authentication via the `gh` CLI's saved credentials.""" +class SessionsEnrichMetadataRequest: + """Session metadata records to enrich with summary and context information.""" - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. + sessions: list[LocalSessionMetadataValue] + """Session metadata records to enrich. Records that already have summary and context are + returned unchanged. """ @staticmethod - def from_dict(obj: Any) -> 'GhCLIAuthInfo': + def from_dict(obj: Any) -> 'SessionsEnrichMetadataRequest': assert isinstance(obj, dict) - host = from_str(obj.get("host")) - login = from_str(obj.get("login")) - token = from_str(obj.get("token")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return GhCLIAuthInfo(host, login, token, copilot_user) + sessions = from_list(LocalSessionMetadataValue.from_dict, obj.get("sessions")) + return SessionsEnrichMetadataRequest(sessions) def to_dict(self) -> dict: result: dict = {} - result["host"] = from_str(self.host) - result["login"] = from_str(self.login) - result["token"] = from_str(self.token) - result["type"] = self.type - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["sessions"] = from_list(lambda x: to_class(LocalSessionMetadataValue, x), self.sessions) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class HMACAuthInfo: - """Schema for the `HMACAuthInfo` type.""" +class SessionOpenResult: + """Result of opening a session.""" - hmac: str - """HMAC secret used to sign requests.""" + status: SessionsOpenStatus + """Outcome of the open request.""" - host: Host - """Authentication host. HMAC auth always targets the public GitHub host.""" + metadata: RemoteSessionMetadataValue | None = None + """Remote session metadata, present when status is `connected`.""" - type: ClassVar[str] = "hmac" - """HMAC-based authentication used by GitHub-internal services.""" + progress: list[SessionsOpenProgress] | None = None + """Handoff progress steps, present when status is `handed_off`.""" - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. - """ + remote_session_id: str | None = None + """Remote session ID, present when status is `connected`.""" - @staticmethod - def from_dict(obj: Any) -> 'HMACAuthInfo': + # Internal: this field is an internal SDK API and is not part of the public surface. + session_api: Any = None + """In-process SessionClientApi handle for the opened session, returned to CLI callers as a + transitional shortcut. Marked internal so the public SDK surface does not expose it; SDK + consumers should construct per-session clients from `sessionId` instead. + """ + session_id: str | None = None + """Opened session ID. Omitted when status is `not_found`.""" + + startup_prompts: list[str] | None = None + """Startup prompts queued by user-level hook configs at session creation. Only populated + when status is `created`; resumed sessions return an empty array. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SessionOpenResult': assert isinstance(obj, dict) - hmac = from_str(obj.get("hmac")) - host = Host(obj.get("host")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return HMACAuthInfo(hmac, host, copilot_user) + status = SessionsOpenStatus(obj.get("status")) + metadata = from_union([RemoteSessionMetadataValue.from_dict, from_none], obj.get("metadata")) + progress = from_union([lambda x: from_list(SessionsOpenProgress.from_dict, x), from_none], obj.get("progress")) + remote_session_id = from_union([from_str, from_none], obj.get("remoteSessionId")) + session_api = obj.get("sessionApi") + session_id = from_union([from_str, from_none], obj.get("sessionId")) + startup_prompts = from_union([lambda x: from_list(from_str, x), from_none], obj.get("startupPrompts")) + return SessionOpenResult(status, metadata, progress, remote_session_id, session_api, session_id, startup_prompts) def to_dict(self) -> dict: result: dict = {} - result["hmac"] = from_str(self.hmac) - result["host"] = to_enum(Host, self.host) - result["type"] = self.type - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["status"] = to_enum(SessionsOpenStatus, self.status) + if self.metadata is not None: + result["metadata"] = from_union([lambda x: to_class(RemoteSessionMetadataValue, x), from_none], self.metadata) + if self.progress is not None: + result["progress"] = from_union([lambda x: from_list(lambda x: to_class(SessionsOpenProgress, x), x), from_none], self.progress) + if self.remote_session_id is not None: + result["remoteSessionId"] = from_union([from_str, from_none], self.remote_session_id) + if self.session_api is not None: + result["sessionApi"] = self.session_api + if self.session_id is not None: + result["sessionId"] = from_union([from_str, from_none], self.session_id) + if self.startup_prompts is not None: + result["startupPrompts"] = from_union([lambda x: from_list(from_str, x), from_none], self.startup_prompts) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class TokenAuthInfo: - """Schema for the `TokenAuthInfo` type.""" +class SessionMetadataSnapshot: + """Point-in-time snapshot of slow-changing session identifier and state fields""" - host: str - """Authentication host.""" + already_in_use: bool + """True when the session was detected to be in use by another process at construction time. + Local consumers may surface a confirmation prompt before fully attaching. Always false + for new sessions. + """ + current_mode: MetadataSnapshotCurrentMode + """The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot')""" - token: str - """The token value itself. Treat as a secret.""" + is_remote: bool + """Whether this is a remote session (i.e., one whose runtime executes elsewhere and is + steered through this process) + """ + modified_time: datetime + """ISO 8601 timestamp of when the session's persisted state was last modified on disk. For + new sessions, equals startTime. For resumed sessions, reflects the previous modification + time at construction. + """ + session_id: str + """The unique identifier of the session""" - type: ClassVar[str] = "token" - """SDK-side token authentication; the host configured the token directly via the SDK.""" + start_time: datetime + """ISO 8601 timestamp of when the session started""" - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. + working_directory: str + """Absolute path to the session's current working directory""" + + client_name: str | None = None + """Runtime client name associated with the session (telemetry identifier).""" + + initial_name: str | None = None + """User-provided name supplied at session construction (via `--name`), if any. Immutable + after construction. + """ + remote_metadata: MetadataSnapshotRemoteMetadata | None = None + """Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are + immutable for the lifetime of the session. + """ + selected_model: str | None = None + """Currently selected model identifier, if any""" + + session_limits: SessionLimitsConfig | None = None + """Current session limits, or null when no limits are active""" + + summary: str | None = None + """Short human-readable summary of the session, if known. Omitted when no summary has been + generated. + """ + workspace: WorkspaceSummary | None = None + """Public-facing workspace metadata for this session, or null if the session has no + associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, + internal flags). + """ + workspace_path: str | None = None + """Absolute path to the session's workspace directory on disk, or null if the session has no + associated workspace """ @staticmethod - def from_dict(obj: Any) -> 'TokenAuthInfo': + def from_dict(obj: Any) -> 'SessionMetadataSnapshot': assert isinstance(obj, dict) - host = from_str(obj.get("host")) - token = from_str(obj.get("token")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return TokenAuthInfo(host, token, copilot_user) + already_in_use = from_bool(obj.get("alreadyInUse")) + current_mode = MetadataSnapshotCurrentMode(obj.get("currentMode")) + is_remote = from_bool(obj.get("isRemote")) + modified_time = from_datetime(obj.get("modifiedTime")) + session_id = from_str(obj.get("sessionId")) + start_time = from_datetime(obj.get("startTime")) + working_directory = from_str(obj.get("workingDirectory")) + client_name = from_union([from_str, from_none], obj.get("clientName")) + initial_name = from_union([from_str, from_none], obj.get("initialName")) + remote_metadata = from_union([MetadataSnapshotRemoteMetadata.from_dict, from_none], obj.get("remoteMetadata")) + selected_model = from_union([from_str, from_none], obj.get("selectedModel")) + session_limits = from_union([SessionLimitsConfig.from_dict, from_none], obj.get("sessionLimits")) + summary = from_union([from_str, from_none], obj.get("summary")) + workspace = from_union([WorkspaceSummary.from_dict, from_none], obj.get("workspace")) + workspace_path = from_union([from_none, from_str], obj.get("workspacePath")) + return SessionMetadataSnapshot(already_in_use, current_mode, is_remote, modified_time, session_id, start_time, working_directory, client_name, initial_name, remote_metadata, selected_model, session_limits, summary, workspace, workspace_path) def to_dict(self) -> dict: result: dict = {} - result["host"] = from_str(self.host) - result["token"] = from_str(self.token) - result["type"] = self.type - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["alreadyInUse"] = from_bool(self.already_in_use) + result["currentMode"] = to_enum(MetadataSnapshotCurrentMode, self.current_mode) + result["isRemote"] = from_bool(self.is_remote) + result["modifiedTime"] = self.modified_time.isoformat() + result["sessionId"] = from_str(self.session_id) + result["startTime"] = self.start_time.isoformat() + result["workingDirectory"] = from_str(self.working_directory) + if self.client_name is not None: + result["clientName"] = from_union([from_str, from_none], self.client_name) + if self.initial_name is not None: + result["initialName"] = from_union([from_str, from_none], self.initial_name) + if self.remote_metadata is not None: + result["remoteMetadata"] = from_union([lambda x: to_class(MetadataSnapshotRemoteMetadata, x), from_none], self.remote_metadata) + if self.selected_model is not None: + result["selectedModel"] = from_union([from_str, from_none], self.selected_model) + result["sessionLimits"] = from_union([lambda x: to_class(SessionLimitsConfig, x), from_none], self.session_limits) + if self.summary is not None: + result["summary"] = from_union([from_str, from_none], self.summary) + if self.workspace is not None: + result["workspace"] = from_union([lambda x: to_class(WorkspaceSummary, x), from_none], self.workspace) + result["workspacePath"] = from_union([from_none, from_str], self.workspace_path) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class UserAuthInfo: - """Schema for the `UserAuthInfo` type.""" +class WorkspacesListCheckpointsResult: + """Workspace checkpoints in chronological order; empty when the workspace is not enabled.""" - host: str - """Authentication host.""" + checkpoints: list[WorkspacesCheckpoints] + """Workspace checkpoints in chronological order. Empty when workspace is not enabled.""" - login: str - """OAuth user login.""" + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesListCheckpointsResult': + assert isinstance(obj, dict) + checkpoints = from_list(WorkspacesCheckpoints.from_dict, obj.get("checkpoints")) + return WorkspacesListCheckpointsResult(checkpoints) - type: ClassVar[str] = "user" - """OAuth user authentication. The token itself is held in the runtime's secret token store - (keyed by host+login) and is NOT carried in this struct. + def to_dict(self) -> dict: + result: dict = {} + result["checkpoints"] = from_list(lambda x: to_class(WorkspacesCheckpoints, x), self.checkpoints) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class DebugCollectLogsRequest: + """Options for collecting a redacted session debug bundle.""" + + destination: DebugCollectLogsDestination + """Where the redacted bundle should be written. Use `archive` to produce a .tgz, or + `directory` to stage redacted files for caller-managed upload/post-processing. """ - copilot_user: CopilotUserResponse | None = None - """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the - GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this - verbatim and does not re-fetch when set. + additional_entries: list[DebugCollectLogsEntry] | None = None + """Caller-provided server-local files or directories to include in addition to the runtime's + built-in session diagnostics. This lets host applications add their own diagnostics + without changing the API shape. """ + include: DebugCollectLogsInclude | None = None + """Which built-in session diagnostics to include. Omitted fields default to true.""" @staticmethod - def from_dict(obj: Any) -> 'UserAuthInfo': + def from_dict(obj: Any) -> 'DebugCollectLogsRequest': assert isinstance(obj, dict) - host = from_str(obj.get("host")) - login = from_str(obj.get("login")) - copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) - return UserAuthInfo(host, login, copilot_user) + destination = DebugCollectLogsDestination.from_dict(obj.get("destination")) + additional_entries = from_union([lambda x: from_list(DebugCollectLogsEntry.from_dict, x), from_none], obj.get("additionalEntries")) + include = from_union([DebugCollectLogsInclude.from_dict, from_none], obj.get("include")) + return DebugCollectLogsRequest(destination, additional_entries, include) def to_dict(self) -> dict: result: dict = {} - result["host"] = from_str(self.host) - result["login"] = from_str(self.login) - result["type"] = self.type - if self.copilot_user is not None: - result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + result["destination"] = to_class(DebugCollectLogsDestination, self.destination) + if self.additional_entries is not None: + result["additionalEntries"] = from_union([lambda x: from_list(lambda x: to_class(DebugCollectLogsEntry, x), x), from_none], self.additional_entries) + if self.include is not None: + result["include"] = from_union([lambda x: to_class(DebugCollectLogsInclude, x), from_none], self.include) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class PermissionDecisionApproveForIonApproval: - """Session-scoped approval to remember (tool prompts only; omitted for path/url prompts) - - Schema for the `PermissionDecisionApproveForSessionApprovalCommands` type. +class InstructionDiscoveryPathList: + """Canonical files and directories where custom instructions can be created so the runtime + will recognize them. + """ + paths: list[InstructionDiscoveryPath] + """Canonical instruction create/discovery files and directories, in priority order""" - Schema for the `PermissionDecisionApproveForSessionApprovalRead` type. + @staticmethod + def from_dict(obj: Any) -> 'InstructionDiscoveryPathList': + assert isinstance(obj, dict) + paths = from_list(InstructionDiscoveryPath.from_dict, obj.get("paths")) + return InstructionDiscoveryPathList(paths) - Schema for the `PermissionDecisionApproveForSessionApprovalWrite` type. + def to_dict(self) -> dict: + result: dict = {} + result["paths"] = from_list(lambda x: to_class(InstructionDiscoveryPath, x), self.paths) + return result - Schema for the `PermissionDecisionApproveForSessionApprovalMcp` type. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionFSReaddirWithTypesResult: + """Entries in the requested directory paired with file/directory type information, or a + filesystem error if the read failed. + """ + entries: list[SessionFSReaddirWithTypesEntry] + """Directory entries with type information""" - Schema for the `PermissionDecisionApproveForSessionApprovalMcpSampling` type. + error: SessionFSError | None = None + """Describes a filesystem error.""" - Schema for the `PermissionDecisionApproveForSessionApprovalMemory` type. + @staticmethod + def from_dict(obj: Any) -> 'SessionFSReaddirWithTypesResult': + assert isinstance(obj, dict) + entries = from_list(SessionFSReaddirWithTypesEntry.from_dict, obj.get("entries")) + error = from_union([SessionFSError.from_dict, from_none], obj.get("error")) + return SessionFSReaddirWithTypesResult(entries, error) - Schema for the `PermissionDecisionApproveForSessionApprovalCustomTool` type. + def to_dict(self) -> dict: + result: dict = {} + result["entries"] = from_list(lambda x: to_class(SessionFSReaddirWithTypesEntry, x), self.entries) + if self.error is not None: + result["error"] = from_union([lambda x: to_class(SessionFSError, x), from_none], self.error) + return result - Schema for the `PermissionDecisionApproveForSessionApprovalExtensionManagement` type. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ProviderModelConfig: + """A BYOK model definition referencing a named provider.""" - Schema for the `PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess` - type. + id: str + """Provider-local model id, unique within its provider. The session-wide selection id (shown + in the model list and passed to switchTo) is the provider-qualified `provider/id`. + """ + provider: str + """Name of the NamedProviderConfig that serves this model.""" - Approval to persist for this location + capabilities: ModelCapabilitiesOverride | None = None + """Optional capability overrides (vision, tool_calls, reasoning, etc.).""" - Schema for the `PermissionDecisionApproveForLocationApprovalCommands` type. + max_context_window_tokens: float | None = None + """Maximum context window tokens for the model.""" - Schema for the `PermissionDecisionApproveForLocationApprovalRead` type. + max_output_tokens: float | None = None + """Maximum output tokens for the model.""" - Schema for the `PermissionDecisionApproveForLocationApprovalWrite` type. + max_prompt_tokens: float | None = None + """Maximum prompt/input tokens for the model.""" - Schema for the `PermissionDecisionApproveForLocationApprovalMcp` type. - - Schema for the `PermissionDecisionApproveForLocationApprovalMcpSampling` type. - - Schema for the `PermissionDecisionApproveForLocationApprovalMemory` type. - - Schema for the `PermissionDecisionApproveForLocationApprovalCustomTool` type. - - Schema for the `PermissionDecisionApproveForLocationApprovalExtensionManagement` type. - - Schema for the `PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess` - type. - - The approval to add as a session-scoped rule + model_id: str | None = None + """Well-known base model id used for behavior/capability/config lookup. Defaults to `id`.""" - The approval to persist for this location + name: str | None = None + """Display name for model pickers. Defaults to the provider-qualified selection id + (`provider/id`). """ - command_identifiers: list[str] | None = None - """Command identifiers covered by this approval.""" - - kind: ApprovalKind | None = None - """Approval scoped to specific command identifiers. - - Approval covering read-only filesystem operations. - - Approval covering filesystem write operations. - - Approval covering an MCP tool. - - Approval covering MCP sampling requests for a server. + wire_model: str | None = None + """The model name sent to the provider API for inference. Defaults to `id`.""" - Approval covering writes to long-term memory. + @staticmethod + def from_dict(obj: Any) -> 'ProviderModelConfig': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + provider = from_str(obj.get("provider")) + capabilities = from_union([ModelCapabilitiesOverride.from_dict, from_none], obj.get("capabilities")) + max_context_window_tokens = from_union([from_float, from_none], obj.get("maxContextWindowTokens")) + max_output_tokens = from_union([from_float, from_none], obj.get("maxOutputTokens")) + max_prompt_tokens = from_union([from_float, from_none], obj.get("maxPromptTokens")) + model_id = from_union([from_str, from_none], obj.get("modelId")) + name = from_union([from_str, from_none], obj.get("name")) + wire_model = from_union([from_str, from_none], obj.get("wireModel")) + return ProviderModelConfig(id, provider, capabilities, max_context_window_tokens, max_output_tokens, max_prompt_tokens, model_id, name, wire_model) - Approval covering a custom tool. + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + result["provider"] = from_str(self.provider) + if self.capabilities is not None: + result["capabilities"] = from_union([lambda x: to_class(ModelCapabilitiesOverride, x), from_none], self.capabilities) + if self.max_context_window_tokens is not None: + result["maxContextWindowTokens"] = from_union([to_float, from_none], self.max_context_window_tokens) + if self.max_output_tokens is not None: + result["maxOutputTokens"] = from_union([to_float, from_none], self.max_output_tokens) + if self.max_prompt_tokens is not None: + result["maxPromptTokens"] = from_union([to_float, from_none], self.max_prompt_tokens) + if self.model_id is not None: + result["modelId"] = from_union([from_str, from_none], self.model_id) + if self.name is not None: + result["name"] = from_union([from_str, from_none], self.name) + if self.wire_model is not None: + result["wireModel"] = from_union([from_str, from_none], self.wire_model) + return result - Approval covering extension lifecycle operations such as enable, disable, or reload. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PermissionsConfigureParams: + """Patch of permission policy fields to apply (omit a field to leave it unchanged).""" - Approval covering an extension's request to access a permission-gated capability. + additional_content_exclusion_policies: list[PermissionsConfigureAdditionalContentExclusionPolicy] | None = None + """If specified, replaces the host-supplied GitHub Content Exclusion policies on the session + (combined with natively-discovered policies when evaluating tool/file access). Omit to + leave the current policies unchanged. """ - server_name: str | None = None - """MCP server name.""" - - tool_name: str | None = None - """MCP tool name, or null to cover every tool on the server. - - Custom tool name. + approve_all_read_permission_requests: bool | None = None + """If specified, sets whether path/URL read permission requests are auto-approved. Omit to + leave the current value unchanged. """ - operation: str | None = None - """Optional operation identifier; when omitted, the approval covers all extension management - operations. + approve_all_tool_permission_requests: bool | None = None + """If specified, sets whether tool permission requests are auto-approved without prompting. + Omit to leave the current value unchanged. + """ + paths: PermissionPathsConfig | None = None + """If specified, replaces the session's path-permission policy. The runtime constructs the + appropriate PathManager based on these inputs (rooted at the session's working + directory). Omit to leave the current path policy unchanged. + """ + rules: PermissionRulesSet | None = None + """If specified, replaces the session's approved/denied permission rules. Omit to leave the + current rules unchanged. + """ + urls: PermissionUrlsConfig | None = None + """If specified, replaces the session's URL-permission policy. The runtime constructs a + fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy + unchanged. """ - extension_name: str | None = None - """Extension name.""" - - external_ref_marker_external_ref_user_tool_session_approval: str | None = None @staticmethod - def from_dict(obj: Any) -> 'PermissionDecisionApproveForIonApproval': + def from_dict(obj: Any) -> 'PermissionsConfigureParams': assert isinstance(obj, dict) - command_identifiers = from_union([lambda x: from_list(from_str, x), from_none], obj.get("commandIdentifiers")) - kind = from_union([ApprovalKind, from_none], obj.get("kind")) - server_name = from_union([from_str, from_none], obj.get("serverName")) - tool_name = from_union([from_none, from_str], obj.get("toolName")) - operation = from_union([from_str, from_none], obj.get("operation")) - extension_name = from_union([from_str, from_none], obj.get("extensionName")) - external_ref_marker_external_ref_user_tool_session_approval = from_union([from_str, from_none], obj.get("__externalRefMarker___ExternalRef_UserToolSessionApproval")) - return PermissionDecisionApproveForIonApproval(command_identifiers, kind, server_name, tool_name, operation, extension_name, external_ref_marker_external_ref_user_tool_session_approval) + additional_content_exclusion_policies = from_union([lambda x: from_list(PermissionsConfigureAdditionalContentExclusionPolicy.from_dict, x), from_none], obj.get("additionalContentExclusionPolicies")) + approve_all_read_permission_requests = from_union([from_bool, from_none], obj.get("approveAllReadPermissionRequests")) + approve_all_tool_permission_requests = from_union([from_bool, from_none], obj.get("approveAllToolPermissionRequests")) + paths = from_union([PermissionPathsConfig.from_dict, from_none], obj.get("paths")) + rules = from_union([PermissionRulesSet.from_dict, from_none], obj.get("rules")) + urls = from_union([PermissionUrlsConfig.from_dict, from_none], obj.get("urls")) + return PermissionsConfigureParams(additional_content_exclusion_policies, approve_all_read_permission_requests, approve_all_tool_permission_requests, paths, rules, urls) def to_dict(self) -> dict: result: dict = {} - if self.command_identifiers is not None: - result["commandIdentifiers"] = from_union([lambda x: from_list(from_str, x), from_none], self.command_identifiers) - if self.kind is not None: - result["kind"] = from_union([lambda x: to_enum(ApprovalKind, x), from_none], self.kind) - if self.server_name is not None: - result["serverName"] = from_union([from_str, from_none], self.server_name) - if self.tool_name is not None: - result["toolName"] = from_union([from_none, from_str], self.tool_name) - if self.operation is not None: - result["operation"] = from_union([from_str, from_none], self.operation) - if self.extension_name is not None: - result["extensionName"] = from_union([from_str, from_none], self.extension_name) - if self.external_ref_marker_external_ref_user_tool_session_approval is not None: - result["__externalRefMarker___ExternalRef_UserToolSessionApproval"] = from_union([from_str, from_none], self.external_ref_marker_external_ref_user_tool_session_approval) + if self.additional_content_exclusion_policies is not None: + result["additionalContentExclusionPolicies"] = from_union([lambda x: from_list(lambda x: to_class(PermissionsConfigureAdditionalContentExclusionPolicy, x), x), from_none], self.additional_content_exclusion_policies) + if self.approve_all_read_permission_requests is not None: + result["approveAllReadPermissionRequests"] = from_union([from_bool, from_none], self.approve_all_read_permission_requests) + if self.approve_all_tool_permission_requests is not None: + result["approveAllToolPermissionRequests"] = from_union([from_bool, from_none], self.approve_all_tool_permission_requests) + if self.paths is not None: + result["paths"] = from_union([lambda x: to_class(PermissionPathsConfig, x), from_none], self.paths) + if self.rules is not None: + result["rules"] = from_union([lambda x: to_class(PermissionRulesSet, x), from_none], self.rules) + if self.urls is not None: + result["urls"] = from_union([lambda x: to_class(PermissionUrlsConfig, x), from_none], self.urls) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class HandlePendingToolCallRequest: - """Pending external tool call request ID, with the tool result or an error describing why it - failed. - """ - request_id: str - """Request ID of the pending tool call""" +class SandboxConfig: + """Resolved sandbox configuration.""" - error: str | None = None - """Error message if the tool call failed""" + enabled: bool + """Whether sandboxing is enabled for the session.""" - result: ExternalToolTextResultForLlm | str | None = None - """Tool call result (string or expanded result object)""" + add_current_working_directory: bool | None = None + """Whether to auto-add the current working directory to readwritePaths. Default: true.""" + + user_policy: SandboxConfigUserPolicy | None = None + """User-managed sandbox policy fragment merged into the auto-discovered base policy.""" @staticmethod - def from_dict(obj: Any) -> 'HandlePendingToolCallRequest': + def from_dict(obj: Any) -> 'SandboxConfig': assert isinstance(obj, dict) - request_id = from_str(obj.get("requestId")) - error = from_union([from_str, from_none], obj.get("error")) - result = from_union([ExternalToolTextResultForLlm.from_dict, from_str, from_none], obj.get("result")) - return HandlePendingToolCallRequest(request_id, error, result) + enabled = from_bool(obj.get("enabled")) + add_current_working_directory = from_union([from_bool, from_none], obj.get("addCurrentWorkingDirectory")) + user_policy = from_union([SandboxConfigUserPolicy.from_dict, from_none], obj.get("userPolicy")) + return SandboxConfig(enabled, add_current_working_directory, user_policy) def to_dict(self) -> dict: result: dict = {} - result["requestId"] = from_str(self.request_id) - if self.error is not None: - result["error"] = from_union([from_str, from_none], self.error) - if self.result is not None: - result["result"] = from_union([lambda x: to_class(ExternalToolTextResultForLlm, x), from_str, from_none], self.result) + result["enabled"] = from_bool(self.enabled) + if self.add_current_working_directory is not None: + result["addCurrentWorkingDirectory"] = from_union([from_bool, from_none], self.add_current_working_directory) + if self.user_policy is not None: + result["userPolicy"] = from_union([lambda x: to_class(SandboxConfigUserPolicy, x), from_none], self.user_policy) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class InstalledPlugin: - """Schema for the `InstalledPlugin` type.""" +class MCPListToolsResult: + """Tools exposed by the connected MCP server. Throws when the server is not connected.""" - enabled: bool - """Whether the plugin is currently enabled""" + tools: list[MCPTools] + """Tools exposed by the server.""" - installed_at: str - """Installation timestamp""" + @staticmethod + def from_dict(obj: Any) -> 'MCPListToolsResult': + assert isinstance(obj, dict) + tools = from_list(MCPTools.from_dict, obj.get("tools")) + return MCPListToolsResult(tools) - marketplace: str - """Marketplace the plugin came from (empty string for direct repo installs)""" + def to_dict(self) -> dict: + result: dict = {} + result["tools"] = from_list(lambda x: to_class(MCPTools, x), self.tools) + return result - name: str - """Plugin name""" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UIElicitationSchema: + """JSON Schema describing the form fields to present to the user""" - cache_path: str | None = None - """Path where the plugin is cached locally""" + properties: dict[str, UIElicitationSchemaProperty] + """Form field definitions, keyed by field name""" - source: InstalledPluginSource | str | None = None - """Source for direct repo installs (when marketplace is empty)""" + type: UIElicitationSchemaType + """Schema type indicator (always 'object')""" - version: str | None = None - """Version installed (if available)""" + required: list[str] | None = None + """List of required field names""" @staticmethod - def from_dict(obj: Any) -> 'InstalledPlugin': + def from_dict(obj: Any) -> 'UIElicitationSchema': assert isinstance(obj, dict) - enabled = from_bool(obj.get("enabled")) - installed_at = from_str(obj.get("installed_at")) - marketplace = from_str(obj.get("marketplace")) - name = from_str(obj.get("name")) - cache_path = from_union([from_str, from_none], obj.get("cache_path")) - source = from_union([InstalledPluginSource.from_dict, from_str, from_none], obj.get("source")) - version = from_union([from_str, from_none], obj.get("version")) - return InstalledPlugin(enabled, installed_at, marketplace, name, cache_path, source, version) + properties = from_dict(UIElicitationSchemaProperty.from_dict, obj.get("properties")) + type = UIElicitationSchemaType(obj.get("type")) + required = from_union([lambda x: from_list(from_str, x), from_none], obj.get("required")) + return UIElicitationSchema(properties, type, required) def to_dict(self) -> dict: result: dict = {} - result["enabled"] = from_bool(self.enabled) - result["installed_at"] = from_str(self.installed_at) - result["marketplace"] = from_str(self.marketplace) - result["name"] = from_str(self.name) - if self.cache_path is not None: - result["cache_path"] = from_union([from_str, from_none], self.cache_path) - if self.source is not None: - result["source"] = from_union([lambda x: to_class(InstalledPluginSource, x), from_str, from_none], self.source) - if self.version is not None: - result["version"] = from_union([from_str, from_none], self.version) + result["properties"] = from_dict(lambda x: to_class(UIElicitationSchemaProperty, x), self.properties) + result["type"] = to_enum(UIElicitationSchemaType, self.type) + if self.required is not None: + result["required"] = from_union([lambda x: from_list(from_str, x), from_none], self.required) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionInstalledPlugin: - """Schema for the `SessionInstalledPlugin` type.""" - - enabled: bool - """Whether the plugin is currently enabled""" - - installed_at: str - """Installation timestamp (ISO-8601)""" - - marketplace: str - """Marketplace the plugin came from (empty string for direct repo installs)""" - - name: str - """Plugin name""" - - cache_path: str | None = None - """Path where the plugin is cached locally""" - - source: SessionInstalledPluginSource | str | None = None - """Source descriptor for direct repo installs (when marketplace is empty)""" - - version: str | None = None - """Installed version, if known""" +class ProviderAddRequest: + """BYOK providers and/or models to add to the session's registry at runtime. Both fields are + optional; provide providers, models, or both. + """ + models: list[ProviderModelConfig] | None = None + """BYOK model definitions to register. Each must reference a provider that is already + registered or included in this same call. Selection ids (`provider/id`) must be unique + across the registry. + """ + providers: list[NamedProviderConfig] | None = None + """Named BYOK provider connections to register, additive to any providers already in the + registry. Each name must be unique across the registry and must not contain '/'. + """ @staticmethod - def from_dict(obj: Any) -> 'SessionInstalledPlugin': + def from_dict(obj: Any) -> 'ProviderAddRequest': assert isinstance(obj, dict) - enabled = from_bool(obj.get("enabled")) - installed_at = from_str(obj.get("installed_at")) - marketplace = from_str(obj.get("marketplace")) - name = from_str(obj.get("name")) - cache_path = from_union([from_str, from_none], obj.get("cache_path")) - source = from_union([SessionInstalledPluginSource.from_dict, from_str, from_none], obj.get("source")) - version = from_union([from_str, from_none], obj.get("version")) - return SessionInstalledPlugin(enabled, installed_at, marketplace, name, cache_path, source, version) + models = from_union([lambda x: from_list(ProviderModelConfig.from_dict, x), from_none], obj.get("models")) + providers = from_union([lambda x: from_list(NamedProviderConfig.from_dict, x), from_none], obj.get("providers")) + return ProviderAddRequest(models, providers) def to_dict(self) -> dict: result: dict = {} - result["enabled"] = from_bool(self.enabled) - result["installed_at"] = from_str(self.installed_at) - result["marketplace"] = from_str(self.marketplace) - result["name"] = from_str(self.name) - if self.cache_path is not None: - result["cache_path"] = from_union([from_str, from_none], self.cache_path) - if self.source is not None: - result["source"] = from_union([lambda x: to_class(SessionInstalledPluginSource, x), from_str, from_none], self.source) - if self.version is not None: - result["version"] = from_union([from_str, from_none], self.version) + if self.models is not None: + result["models"] = from_union([lambda x: from_list(lambda x: to_class(ProviderModelConfig, x), x), from_none], self.models) + if self.providers is not None: + result["providers"] = from_union([lambda x: from_list(lambda x: to_class(NamedProviderConfig, x), x), from_none], self.providers) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionEnrichMetadataResult: - """The enriched metadata records, with summary and context fields backfilled where - available. Sessions confirmed empty and unnamed are omitted. - """ - sessions: list[LocalSessionMetadataValue] - """Enriched records, with summary and context backfilled. Sessions confirmed empty and - unnamed may be omitted. - """ +class SessionOpenOptions: + """Session construction options. - @staticmethod - def from_dict(obj: Any) -> 'SessionEnrichMetadataResult': - assert isinstance(obj, dict) - sessions = from_list(LocalSessionMetadataValue.from_dict, obj.get("sessions")) - return SessionEnrichMetadataResult(sessions) + Session resume options. - def to_dict(self) -> dict: - result: dict = {} - result["sessions"] = from_list(lambda x: to_class(LocalSessionMetadataValue, x), self.sessions) - return result + Session options for the connection. -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionsEnrichMetadataRequest: - """Session metadata records to enrich with summary and context information.""" + Session options for cloud session creation. - sessions: list[LocalSessionMetadataValue] - """Session metadata records to enrich. Records that already have summary and context are - returned unchanged. + Session construction options for the new local session. """ + additional_content_exclusion_policies: list[SessionOpenOptionsAdditionalContentExclusionPolicy] | None = None + """Additional content-exclusion policies to merge into the session policy set.""" - @staticmethod - def from_dict(obj: Any) -> 'SessionsEnrichMetadataRequest': - assert isinstance(obj, dict) - sessions = from_list(LocalSessionMetadataValue.from_dict, obj.get("sessions")) - return SessionsEnrichMetadataRequest(sessions) + agent_context: str | None = None + """Runtime context discriminator for agent filtering.""" - def to_dict(self) -> dict: - result: dict = {} - result["sessions"] = from_list(lambda x: to_class(LocalSessionMetadataValue, x), self.sessions) - return result + allow_all_mcp_server_instructions: bool | None = None + """Whether to include instructions from every MCP server in the system prompt instead of + only allowlisted servers. + """ + ask_user_disabled: bool | None = None + """Whether ask_user is explicitly disabled.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionOpenResult: - """Result of opening a session.""" + auth_info: AuthInfo | None = None + """Initial authentication info for the session.""" - status: SessionsOpenStatus - """Outcome of the open request.""" + available_tools: list[str] | None = None + """Allowlist of available tool names.""" - metadata: RemoteSessionMetadataValue | None = None - """Remote session metadata, present when status is `connected`.""" + capi: CapiSessionOptions | None = None + """Options scoped to the built-in CAPI (Copilot API) provider.""" - progress: list[SessionsOpenProgress] | None = None - """Handoff progress steps, present when status is `handed_off`.""" + client_kind: str | None = None + """Structured client kind used for runtime behavior gates.""" - remote_session_id: str | None = None - """Remote session ID, present when status is `connected`.""" + client_name: str | None = None + """Identifier of the client driving the session.""" - # Internal: this field is an internal SDK API and is not part of the public surface. - session_api: Any = None - """In-process SessionClientApi handle for the opened session, returned to CLI callers as a - transitional shortcut. Marked internal so the public SDK surface does not expose it; SDK - consumers should construct per-session clients from `sessionId` instead. - """ - session_id: str | None = None - """Opened session ID. Omitted when status is `not_found`.""" + coauthor_enabled: bool | None = None + """Whether commit-message coauthor trailers are enabled.""" - startup_prompts: list[str] | None = None - """Startup prompts queued by user-level hook configs at session creation. Only populated - when status is `created`; resumed sessions return an empty array. - """ + config_dir: str | None = None + """Override Copilot configuration directory.""" - @staticmethod - def from_dict(obj: Any) -> 'SessionOpenResult': - assert isinstance(obj, dict) - status = SessionsOpenStatus(obj.get("status")) - metadata = from_union([RemoteSessionMetadataValue.from_dict, from_none], obj.get("metadata")) - progress = from_union([lambda x: from_list(SessionsOpenProgress.from_dict, x), from_none], obj.get("progress")) - remote_session_id = from_union([from_str, from_none], obj.get("remoteSessionId")) - session_api = obj.get("sessionApi") - session_id = from_union([from_str, from_none], obj.get("sessionId")) - startup_prompts = from_union([lambda x: from_list(from_str, x), from_none], obj.get("startupPrompts")) - return SessionOpenResult(status, metadata, progress, remote_session_id, session_api, session_id, startup_prompts) + continue_on_auto_mode: bool | None = None + """Whether auto-mode continuation is enabled.""" - def to_dict(self) -> dict: - result: dict = {} - result["status"] = to_enum(SessionsOpenStatus, self.status) - if self.metadata is not None: - result["metadata"] = from_union([lambda x: to_class(RemoteSessionMetadataValue, x), from_none], self.metadata) - if self.progress is not None: - result["progress"] = from_union([lambda x: from_list(lambda x: to_class(SessionsOpenProgress, x), x), from_none], self.progress) - if self.remote_session_id is not None: - result["remoteSessionId"] = from_union([from_str, from_none], self.remote_session_id) - if self.session_api is not None: - result["sessionApi"] = self.session_api - if self.session_id is not None: - result["sessionId"] = from_union([from_str, from_none], self.session_id) - if self.startup_prompts is not None: - result["startupPrompts"] = from_union([lambda x: from_list(from_str, x), from_none], self.startup_prompts) - return result + copilot_url: str | None = None + """Override URL for the Copilot API endpoint.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionMetadataSnapshot: - """Point-in-time snapshot of slow-changing session identifier and state fields""" + custom_agents_local_only: bool | None = None + """Whether custom agents default to local-only execution.""" - already_in_use: bool - """True when the session was detected to be in use by another process at construction time. - Local consumers may surface a confirmation prompt before fully attaching. Always false - for new sessions. - """ - current_mode: MetadataSnapshotCurrentMode - """The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot')""" + detached_from_spawning_parent_engagement_id: str | None = None + """Parent engagement ID for detached child telemetry rollup.""" - is_remote: bool - """Whether this is a remote session (i.e., one whose runtime executes elsewhere and is - steered through this process) - """ - modified_time: datetime - """ISO 8601 timestamp of when the session's persisted state was last modified on disk. For - new sessions, equals startTime. For resumed sessions, reflects the previous modification - time at construction. + detached_from_spawning_parent_session_id: str | None = None + """Parent session ID for detached child telemetry rollup.""" + + disabled_instruction_sources: list[str] | None = None + """Instruction source IDs disabled for this session.""" + + disabled_skills: list[str] | None = None + """Skill IDs disabled for this session.""" + + enable_citations: bool | None = None + """Experimental: enable native model citations (Anthropic models today), normalized onto the + `assistant.message` event. Off by default; may change or be removed while the citations + surface is experimental. """ - session_id: str - """The unique identifier of the session""" + enable_managed_settings: bool | None = None + """Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap.""" - start_time: datetime - """ISO 8601 timestamp of when the session started""" + enable_on_demand_instruction_discovery: bool | None = None + """Whether on-demand custom instruction discovery is enabled.""" - working_directory: str - """Absolute path to the session's current working directory""" + enable_script_safety: bool | None = None + """Whether shell-script safety heuristics are enabled.""" - client_name: str | None = None - """Runtime client name associated with the session (telemetry identifier).""" + enable_streaming: bool | None = None + """Whether model responses stream as delta events.""" - initial_name: str | None = None - """User-provided name supplied at session construction (via `--name`), if any. Immutable - after construction. + env_value_mode: MCPSetEnvValueModeDetails | None = None + """How MCP server environment values are interpreted.""" + + events_log_directory: str | None = None + """Override directory for session event logs.""" + + excluded_builtin_agents: list[str] | None = None + """Built-in subagent names to exclude from this session. Excluded built-ins are hidden from + agent discovery and cannot be dispatched unless a custom agent with the same name is + available. """ - remote_metadata: MetadataSnapshotRemoteMetadata | None = None - """Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are - immutable for the lifetime of the session. + excluded_tools: list[str] | None = None + """Denylist of tool names.""" + + # Internal: this field is an internal SDK API and is not part of the public surface. + exp_assignments: Any = None + """ExP assignment ('flight') data injected by an SDK integrator, in the same JSON shape the + Copilot CLI fetches from the experimentation service (CopilotExpAssignmentResponse). When + supplied this is fed into the FeatureFlagService exactly like CLI-fetched assignments and + ExP-backed flags wait for it. When absent the session does not block on ExP. """ - selected_model: str | None = None - """Currently selected model identifier, if any""" + feature_flags: dict[str, bool] | None = None + """Feature-flag values resolved by the host.""" - summary: str | None = None - """Short human-readable summary of the session, if known. Omitted when no summary has been - generated. - """ - workspace: WorkspaceSummary | None = None - """Public-facing workspace metadata for this session, or null if the session has no - associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, - internal flags). - """ - workspace_path: str | None = None - """Absolute path to the session's workspace directory on disk, or null if the session has no - associated workspace + included_builtin_agents: list[str] | None = None + """Built-in subagent names to include in this session. When specified, only these built-ins + are available, subject to runtime availability and exclusions. Custom agents with the + same name remain available. """ + installed_plugins: list[InstalledPlugin] | None = None + """Installed plugins visible to the session.""" - @staticmethod - def from_dict(obj: Any) -> 'SessionMetadataSnapshot': - assert isinstance(obj, dict) - already_in_use = from_bool(obj.get("alreadyInUse")) - current_mode = MetadataSnapshotCurrentMode(obj.get("currentMode")) - is_remote = from_bool(obj.get("isRemote")) - modified_time = from_datetime(obj.get("modifiedTime")) - session_id = from_str(obj.get("sessionId")) - start_time = from_datetime(obj.get("startTime")) - working_directory = from_str(obj.get("workingDirectory")) - client_name = from_union([from_str, from_none], obj.get("clientName")) - initial_name = from_union([from_str, from_none], obj.get("initialName")) - remote_metadata = from_union([MetadataSnapshotRemoteMetadata.from_dict, from_none], obj.get("remoteMetadata")) - selected_model = from_union([from_str, from_none], obj.get("selectedModel")) - summary = from_union([from_str, from_none], obj.get("summary")) - workspace = from_union([WorkspaceSummary.from_dict, from_none], obj.get("workspace")) - workspace_path = from_union([from_none, from_str], obj.get("workspacePath")) - return SessionMetadataSnapshot(already_in_use, current_mode, is_remote, modified_time, session_id, start_time, working_directory, client_name, initial_name, remote_metadata, selected_model, summary, workspace, workspace_path) + integration_id: str | None = None + """Stable integration identifier for analytics.""" - def to_dict(self) -> dict: - result: dict = {} - result["alreadyInUse"] = from_bool(self.already_in_use) - result["currentMode"] = to_enum(MetadataSnapshotCurrentMode, self.current_mode) - result["isRemote"] = from_bool(self.is_remote) - result["modifiedTime"] = self.modified_time.isoformat() - result["sessionId"] = from_str(self.session_id) - result["startTime"] = self.start_time.isoformat() - result["workingDirectory"] = from_str(self.working_directory) - if self.client_name is not None: - result["clientName"] = from_union([from_str, from_none], self.client_name) - if self.initial_name is not None: - result["initialName"] = from_union([from_str, from_none], self.initial_name) - if self.remote_metadata is not None: - result["remoteMetadata"] = from_union([lambda x: to_class(MetadataSnapshotRemoteMetadata, x), from_none], self.remote_metadata) - if self.selected_model is not None: - result["selectedModel"] = from_union([from_str, from_none], self.selected_model) - if self.summary is not None: - result["summary"] = from_union([from_str, from_none], self.summary) - if self.workspace is not None: - result["workspace"] = from_union([lambda x: to_class(WorkspaceSummary, x), from_none], self.workspace) - result["workspacePath"] = from_union([from_none, from_str], self.workspace_path) - return result + is_experimental_mode: bool | None = None + """Whether experimental behavior is enabled.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ProviderModelConfig: - """A BYOK model definition referencing a named provider.""" + log_interactive_shells: bool | None = None + """Whether interactive shell sessions are logged.""" - id: str - """Provider-local model id, unique within its provider. The session-wide selection id (shown - in the model list and passed to switchTo) is the provider-qualified `provider/id`. - """ - provider: str - """Name of the NamedProviderConfig that serves this model.""" + lsp_client_name: str | None = None + """Identifier sent to LSP-style integrations.""" - capabilities: ModelCapabilitiesOverride | None = None - """Optional capability overrides (vision, tool_calls, reasoning, etc.).""" + max_inline_binary_bytes: int | None = None + """Maximum decoded byte size of a single inline model-facing binary tool result persisted in + session events (default 10 MB). + """ + memory: MemoryConfiguration | None = None + """Memory configuration for this session.""" - max_context_window_tokens: float | None = None - """Maximum context window tokens for the model.""" + model: str | None = None + """Initial model identifier.""" - max_output_tokens: float | None = None - """Maximum output tokens for the model.""" + model_capabilities_overrides: ModelCapabilitiesOverride | None = None + """Initial model capability overrides.""" - max_prompt_tokens: float | None = None - """Maximum prompt/input tokens for the model.""" + models: list[ProviderModelConfig] | None = None + """BYOK model definitions added to the selectable model list, each referencing a provider + name. + """ + name: str | None = None + """Optional human-friendly session name.""" - model_id: str | None = None - """Well-known base model id used for behavior/capability/config lookup. Defaults to `id`.""" + provider: ProviderConfig | None = None + """Custom model-provider configuration (BYOK).""" - name: str | None = None - """Display name for model pickers. Defaults to the provider-qualified selection id - (`provider/id`). + providers: list[NamedProviderConfig] | None = None + """Named BYOK provider connections, additive to CAPI auth. Combining with `provider` is + rejected. """ - wire_model: str | None = None - """The model name sent to the provider API for inference. Defaults to `id`.""" - - @staticmethod - def from_dict(obj: Any) -> 'ProviderModelConfig': - assert isinstance(obj, dict) - id = from_str(obj.get("id")) - provider = from_str(obj.get("provider")) - capabilities = from_union([ModelCapabilitiesOverride.from_dict, from_none], obj.get("capabilities")) - max_context_window_tokens = from_union([from_float, from_none], obj.get("maxContextWindowTokens")) - max_output_tokens = from_union([from_float, from_none], obj.get("maxOutputTokens")) - max_prompt_tokens = from_union([from_float, from_none], obj.get("maxPromptTokens")) - model_id = from_union([from_str, from_none], obj.get("modelId")) - name = from_union([from_str, from_none], obj.get("name")) - wire_model = from_union([from_str, from_none], obj.get("wireModel")) - return ProviderModelConfig(id, provider, capabilities, max_context_window_tokens, max_output_tokens, max_prompt_tokens, model_id, name, wire_model) + reasoning_effort: str | None = None + """Initial reasoning effort level.""" - def to_dict(self) -> dict: - result: dict = {} - result["id"] = from_str(self.id) - result["provider"] = from_str(self.provider) - if self.capabilities is not None: - result["capabilities"] = from_union([lambda x: to_class(ModelCapabilitiesOverride, x), from_none], self.capabilities) - if self.max_context_window_tokens is not None: - result["maxContextWindowTokens"] = from_union([to_float, from_none], self.max_context_window_tokens) - if self.max_output_tokens is not None: - result["maxOutputTokens"] = from_union([to_float, from_none], self.max_output_tokens) - if self.max_prompt_tokens is not None: - result["maxPromptTokens"] = from_union([to_float, from_none], self.max_prompt_tokens) - if self.model_id is not None: - result["modelId"] = from_union([from_str, from_none], self.model_id) - if self.name is not None: - result["name"] = from_union([from_str, from_none], self.name) - if self.wire_model is not None: - result["wireModel"] = from_union([from_str, from_none], self.wire_model) - return result + reasoning_summary: ReasoningSummary | None = None + """Initial reasoning summary mode for supported model clients.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class PermissionsConfigureParams: - """Patch of permission policy fields to apply (omit a field to leave it unchanged).""" + remote_defaulted_on: bool | None = None + """Telemetry-only remote-defaulted flag.""" - additional_content_exclusion_policies: list[PermissionsConfigureAdditionalContentExclusionPolicy] | None = None - """If specified, replaces the host-supplied GitHub Content Exclusion policies on the session - (combined with natively-discovered policies when evaluating tool/file access). Omit to - leave the current policies unchanged. - """ - approve_all_read_permission_requests: bool | None = None - """If specified, sets whether path/URL read permission requests are auto-approved. Omit to - leave the current value unchanged. - """ - approve_all_tool_permission_requests: bool | None = None - """If specified, sets whether tool permission requests are auto-approved without prompting. - Omit to leave the current value unchanged. - """ - paths: PermissionPathsConfig | None = None - """If specified, replaces the session's path-permission policy. The runtime constructs the - appropriate PathManager based on these inputs (rooted at the session's working - directory). Omit to leave the current path policy unchanged. - """ - rules: PermissionRulesSet | None = None - """If specified, replaces the session's approved/denied permission rules. Omit to leave the - current rules unchanged. - """ - urls: PermissionUrlsConfig | None = None - """If specified, replaces the session's URL-permission policy. The runtime constructs a - fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy - unchanged. - """ + remote_exporting: bool | None = None + """Telemetry-only remote exporting flag.""" - @staticmethod - def from_dict(obj: Any) -> 'PermissionsConfigureParams': - assert isinstance(obj, dict) - additional_content_exclusion_policies = from_union([lambda x: from_list(PermissionsConfigureAdditionalContentExclusionPolicy.from_dict, x), from_none], obj.get("additionalContentExclusionPolicies")) - approve_all_read_permission_requests = from_union([from_bool, from_none], obj.get("approveAllReadPermissionRequests")) - approve_all_tool_permission_requests = from_union([from_bool, from_none], obj.get("approveAllToolPermissionRequests")) - paths = from_union([PermissionPathsConfig.from_dict, from_none], obj.get("paths")) - rules = from_union([PermissionRulesSet.from_dict, from_none], obj.get("rules")) - urls = from_union([PermissionUrlsConfig.from_dict, from_none], obj.get("urls")) - return PermissionsConfigureParams(additional_content_exclusion_policies, approve_all_read_permission_requests, approve_all_tool_permission_requests, paths, rules, urls) + remote_steerable: bool | None = None + """Whether this session supports remote steering.""" - def to_dict(self) -> dict: - result: dict = {} - if self.additional_content_exclusion_policies is not None: - result["additionalContentExclusionPolicies"] = from_union([lambda x: from_list(lambda x: to_class(PermissionsConfigureAdditionalContentExclusionPolicy, x), x), from_none], self.additional_content_exclusion_policies) - if self.approve_all_read_permission_requests is not None: - result["approveAllReadPermissionRequests"] = from_union([from_bool, from_none], self.approve_all_read_permission_requests) - if self.approve_all_tool_permission_requests is not None: - result["approveAllToolPermissionRequests"] = from_union([from_bool, from_none], self.approve_all_tool_permission_requests) - if self.paths is not None: - result["paths"] = from_union([lambda x: to_class(PermissionPathsConfig, x), from_none], self.paths) - if self.rules is not None: - result["rules"] = from_union([lambda x: to_class(PermissionRulesSet, x), from_none], self.rules) - if self.urls is not None: - result["urls"] = from_union([lambda x: to_class(PermissionUrlsConfig, x), from_none], self.urls) - return result + running_in_interactive_mode: bool | None = None + """Whether the host is an interactive UI.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SandboxConfig: + sandbox_config: SandboxConfig | None = None """Resolved sandbox configuration.""" - enabled: bool - """Whether sandboxing is enabled for the session.""" - - add_current_working_directory: bool | None = None - """Whether to auto-add the current working directory to readwritePaths. Default: true.""" + session_capabilities: list[SessionCapability] | None = None + """Capabilities enabled for this session.""" - user_policy: SandboxConfigUserPolicy | None = None - """User-managed sandbox policy fragment merged into the auto-discovered base policy.""" + session_id: str | None = None + """Optional stable session identifier to use for a new session.""" - @staticmethod - def from_dict(obj: Any) -> 'SandboxConfig': - assert isinstance(obj, dict) - enabled = from_bool(obj.get("enabled")) - add_current_working_directory = from_union([from_bool, from_none], obj.get("addCurrentWorkingDirectory")) - user_policy = from_union([SandboxConfigUserPolicy.from_dict, from_none], obj.get("userPolicy")) - return SandboxConfig(enabled, add_current_working_directory, user_policy) + session_limits: SessionLimitsConfig | None = None + """Initial session limits.""" - def to_dict(self) -> dict: - result: dict = {} - result["enabled"] = from_bool(self.enabled) - if self.add_current_working_directory is not None: - result["addCurrentWorkingDirectory"] = from_union([from_bool, from_none], self.add_current_working_directory) - if self.user_policy is not None: - result["userPolicy"] = from_union([lambda x: to_class(SandboxConfigUserPolicy, x), from_none], self.user_policy) - return result + shell_init_profile: str | None = None + """Shell init profile.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class TasksGetProgressResult: - """Progress information for the task, or null when no task with that ID is tracked.""" + shell_process_flags: list[str] | None = None + """Per-shell process flags.""" - progress: TaskProgress | None = None - """Progress information for the task, discriminated by type. Returns null when no task with - this ID is currently tracked. - """ + skill_directories: list[str] | None = None + """Additional directories to search for skills.""" - @staticmethod - def from_dict(obj: Any) -> 'TasksGetProgressResult': - assert isinstance(obj, dict) - progress = from_union([TaskProgress.from_dict, from_none], obj.get("progress")) - return TasksGetProgressResult(progress) + skip_custom_instructions: bool | None = None + """Whether to skip custom instruction sources.""" - def to_dict(self) -> dict: - result: dict = {} - if self.progress is not None: - result["progress"] = from_union([lambda x: to_class(TaskProgress, x), from_none], self.progress) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class UIElicitationSchema: - """JSON Schema describing the form fields to present to the user""" - - properties: dict[str, UIElicitationSchemaProperty] - """Form field definitions, keyed by field name""" - - type: UIElicitationSchemaType - """Schema type indicator (always 'object')""" - - required: list[str] | None = None - """List of required field names""" - - @staticmethod - def from_dict(obj: Any) -> 'UIElicitationSchema': - assert isinstance(obj, dict) - properties = from_dict(UIElicitationSchemaProperty.from_dict, obj.get("properties")) - type = UIElicitationSchemaType(obj.get("type")) - required = from_union([lambda x: from_list(from_str, x), from_none], obj.get("required")) - return UIElicitationSchema(properties, type, required) - - def to_dict(self) -> dict: - result: dict = {} - result["properties"] = from_dict(lambda x: to_class(UIElicitationSchemaProperty, x), self.properties) - result["type"] = to_enum(UIElicitationSchemaType, self.type) - if self.required is not None: - result["required"] = from_union([lambda x: from_list(from_str, x), from_none], self.required) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionsSetAdditionalPluginsRequest: - """Manager-wide additional plugins to register; replaces any previously-configured set.""" - - plugins: list[InstalledPlugin] - """Manager-wide additional plugins to register. Replaces any previously-configured set. Pass - an empty array to clear. - """ + trajectory_file: str | None = None + """Optional trajectory output file path.""" - @staticmethod - def from_dict(obj: Any) -> 'SessionsSetAdditionalPluginsRequest': - assert isinstance(obj, dict) - plugins = from_list(InstalledPlugin.from_dict, obj.get("plugins")) - return SessionsSetAdditionalPluginsRequest(plugins) + verbosity: Verbosity | None = None + """Initial output verbosity level for supported models.""" - def to_dict(self) -> dict: - result: dict = {} - result["plugins"] = from_list(lambda x: to_class(InstalledPlugin, x), self.plugins) - return result + working_directory: str | None = None + """Working directory to anchor the session.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ProviderAddRequest: - """BYOK providers and/or models to add to the session's registry at runtime. Both fields are - optional; provide providers, models, or both. - """ - models: list[ProviderModelConfig] | None = None - """BYOK model definitions to register. Each must reference a provider that is already - registered or included in this same call. Selection ids (`provider/id`) must be unique - across the registry. - """ - providers: list[NamedProviderConfig] | None = None - """Named BYOK provider connections to register, additive to any providers already in the - registry. Each name must be unique across the registry and must not contain '/'. - """ + working_directory_context: SessionContext | None = None + """Pre-resolved working-directory context for session startup.""" @staticmethod - def from_dict(obj: Any) -> 'ProviderAddRequest': + def from_dict(obj: Any) -> 'SessionOpenOptions': assert isinstance(obj, dict) + additional_content_exclusion_policies = from_union([lambda x: from_list(SessionOpenOptionsAdditionalContentExclusionPolicy.from_dict, x), from_none], obj.get("additionalContentExclusionPolicies")) + agent_context = from_union([from_str, from_none], obj.get("agentContext")) + allow_all_mcp_server_instructions = from_union([from_bool, from_none], obj.get("allowAllMcpServerInstructions")) + ask_user_disabled = from_union([from_bool, from_none], obj.get("askUserDisabled")) + auth_info = from_union([_load_AuthInfo, from_none], obj.get("authInfo")) + available_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("availableTools")) + capi = from_union([CapiSessionOptions.from_dict, from_none], obj.get("capi")) + client_kind = from_union([from_str, from_none], obj.get("clientKind")) + client_name = from_union([from_str, from_none], obj.get("clientName")) + coauthor_enabled = from_union([from_bool, from_none], obj.get("coauthorEnabled")) + config_dir = from_union([from_str, from_none], obj.get("configDir")) + continue_on_auto_mode = from_union([from_bool, from_none], obj.get("continueOnAutoMode")) + copilot_url = from_union([from_str, from_none], obj.get("copilotUrl")) + custom_agents_local_only = from_union([from_bool, from_none], obj.get("customAgentsLocalOnly")) + detached_from_spawning_parent_engagement_id = from_union([from_str, from_none], obj.get("detachedFromSpawningParentEngagementId")) + detached_from_spawning_parent_session_id = from_union([from_str, from_none], obj.get("detachedFromSpawningParentSessionId")) + disabled_instruction_sources = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledInstructionSources")) + disabled_skills = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledSkills")) + enable_citations = from_union([from_bool, from_none], obj.get("enableCitations")) + enable_managed_settings = from_union([from_bool, from_none], obj.get("enableManagedSettings")) + enable_on_demand_instruction_discovery = from_union([from_bool, from_none], obj.get("enableOnDemandInstructionDiscovery")) + enable_script_safety = from_union([from_bool, from_none], obj.get("enableScriptSafety")) + enable_streaming = from_union([from_bool, from_none], obj.get("enableStreaming")) + env_value_mode = from_union([MCPSetEnvValueModeDetails, from_none], obj.get("envValueMode")) + events_log_directory = from_union([from_str, from_none], obj.get("eventsLogDirectory")) + excluded_builtin_agents = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedBuiltinAgents")) + excluded_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedTools")) + exp_assignments = obj.get("expAssignments") + feature_flags = from_union([lambda x: from_dict(from_bool, x), from_none], obj.get("featureFlags")) + included_builtin_agents = from_union([lambda x: from_list(from_str, x), from_none], obj.get("includedBuiltinAgents")) + installed_plugins = from_union([lambda x: from_list(InstalledPlugin.from_dict, x), from_none], obj.get("installedPlugins")) + integration_id = from_union([from_str, from_none], obj.get("integrationId")) + is_experimental_mode = from_union([from_bool, from_none], obj.get("isExperimentalMode")) + log_interactive_shells = from_union([from_bool, from_none], obj.get("logInteractiveShells")) + lsp_client_name = from_union([from_str, from_none], obj.get("lspClientName")) + max_inline_binary_bytes = from_union([from_int, from_none], obj.get("maxInlineBinaryBytes")) + memory = from_union([MemoryConfiguration.from_dict, from_none], obj.get("memory")) + model = from_union([from_str, from_none], obj.get("model")) + model_capabilities_overrides = from_union([ModelCapabilitiesOverride.from_dict, from_none], obj.get("modelCapabilitiesOverrides")) models = from_union([lambda x: from_list(ProviderModelConfig.from_dict, x), from_none], obj.get("models")) + name = from_union([from_str, from_none], obj.get("name")) + provider = from_union([ProviderConfig.from_dict, from_none], obj.get("provider")) providers = from_union([lambda x: from_list(NamedProviderConfig.from_dict, x), from_none], obj.get("providers")) - return ProviderAddRequest(models, providers) + reasoning_effort = from_union([from_str, from_none], obj.get("reasoningEffort")) + reasoning_summary = from_union([ReasoningSummary, from_none], obj.get("reasoningSummary")) + remote_defaulted_on = from_union([from_bool, from_none], obj.get("remoteDefaultedOn")) + remote_exporting = from_union([from_bool, from_none], obj.get("remoteExporting")) + remote_steerable = from_union([from_bool, from_none], obj.get("remoteSteerable")) + running_in_interactive_mode = from_union([from_bool, from_none], obj.get("runningInInteractiveMode")) + sandbox_config = from_union([SandboxConfig.from_dict, from_none], obj.get("sandboxConfig")) + session_capabilities = from_union([lambda x: from_list(SessionCapability, x), from_none], obj.get("sessionCapabilities")) + session_id = from_union([from_str, from_none], obj.get("sessionId")) + session_limits = from_union([SessionLimitsConfig.from_dict, from_none], obj.get("sessionLimits")) + shell_init_profile = from_union([from_str, from_none], obj.get("shellInitProfile")) + shell_process_flags = from_union([lambda x: from_list(from_str, x), from_none], obj.get("shellProcessFlags")) + skill_directories = from_union([lambda x: from_list(from_str, x), from_none], obj.get("skillDirectories")) + skip_custom_instructions = from_union([from_bool, from_none], obj.get("skipCustomInstructions")) + trajectory_file = from_union([from_str, from_none], obj.get("trajectoryFile")) + verbosity = from_union([Verbosity, from_none], obj.get("verbosity")) + working_directory = from_union([from_str, from_none], obj.get("workingDirectory")) + working_directory_context = from_union([SessionContext.from_dict, from_none], obj.get("workingDirectoryContext")) + return SessionOpenOptions(additional_content_exclusion_policies, agent_context, allow_all_mcp_server_instructions, ask_user_disabled, auth_info, available_tools, capi, client_kind, client_name, coauthor_enabled, config_dir, continue_on_auto_mode, copilot_url, custom_agents_local_only, detached_from_spawning_parent_engagement_id, detached_from_spawning_parent_session_id, disabled_instruction_sources, disabled_skills, enable_citations, enable_managed_settings, enable_on_demand_instruction_discovery, enable_script_safety, enable_streaming, env_value_mode, events_log_directory, excluded_builtin_agents, excluded_tools, exp_assignments, feature_flags, included_builtin_agents, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, max_inline_binary_bytes, memory, model, model_capabilities_overrides, models, name, provider, providers, reasoning_effort, reasoning_summary, remote_defaulted_on, remote_exporting, remote_steerable, running_in_interactive_mode, sandbox_config, session_capabilities, session_id, session_limits, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, trajectory_file, verbosity, working_directory, working_directory_context) def to_dict(self) -> dict: result: dict = {} + if self.additional_content_exclusion_policies is not None: + result["additionalContentExclusionPolicies"] = from_union([lambda x: from_list(lambda x: to_class(SessionOpenOptionsAdditionalContentExclusionPolicy, x), x), from_none], self.additional_content_exclusion_policies) + if self.agent_context is not None: + result["agentContext"] = from_union([from_str, from_none], self.agent_context) + if self.allow_all_mcp_server_instructions is not None: + result["allowAllMcpServerInstructions"] = from_union([from_bool, from_none], self.allow_all_mcp_server_instructions) + if self.ask_user_disabled is not None: + result["askUserDisabled"] = from_union([from_bool, from_none], self.ask_user_disabled) + if self.auth_info is not None: + result["authInfo"] = from_union([lambda x: (x).to_dict(), from_none], self.auth_info) + if self.available_tools is not None: + result["availableTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.available_tools) + if self.capi is not None: + result["capi"] = from_union([lambda x: to_class(CapiSessionOptions, x), from_none], self.capi) + if self.client_kind is not None: + result["clientKind"] = from_union([from_str, from_none], self.client_kind) + if self.client_name is not None: + result["clientName"] = from_union([from_str, from_none], self.client_name) + if self.coauthor_enabled is not None: + result["coauthorEnabled"] = from_union([from_bool, from_none], self.coauthor_enabled) + if self.config_dir is not None: + result["configDir"] = from_union([from_str, from_none], self.config_dir) + if self.continue_on_auto_mode is not None: + result["continueOnAutoMode"] = from_union([from_bool, from_none], self.continue_on_auto_mode) + if self.copilot_url is not None: + result["copilotUrl"] = from_union([from_str, from_none], self.copilot_url) + if self.custom_agents_local_only is not None: + result["customAgentsLocalOnly"] = from_union([from_bool, from_none], self.custom_agents_local_only) + if self.detached_from_spawning_parent_engagement_id is not None: + result["detachedFromSpawningParentEngagementId"] = from_union([from_str, from_none], self.detached_from_spawning_parent_engagement_id) + if self.detached_from_spawning_parent_session_id is not None: + result["detachedFromSpawningParentSessionId"] = from_union([from_str, from_none], self.detached_from_spawning_parent_session_id) + if self.disabled_instruction_sources is not None: + result["disabledInstructionSources"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_instruction_sources) + if self.disabled_skills is not None: + result["disabledSkills"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_skills) + if self.enable_citations is not None: + result["enableCitations"] = from_union([from_bool, from_none], self.enable_citations) + if self.enable_managed_settings is not None: + result["enableManagedSettings"] = from_union([from_bool, from_none], self.enable_managed_settings) + if self.enable_on_demand_instruction_discovery is not None: + result["enableOnDemandInstructionDiscovery"] = from_union([from_bool, from_none], self.enable_on_demand_instruction_discovery) + if self.enable_script_safety is not None: + result["enableScriptSafety"] = from_union([from_bool, from_none], self.enable_script_safety) + if self.enable_streaming is not None: + result["enableStreaming"] = from_union([from_bool, from_none], self.enable_streaming) + if self.env_value_mode is not None: + result["envValueMode"] = from_union([lambda x: to_enum(MCPSetEnvValueModeDetails, x), from_none], self.env_value_mode) + if self.events_log_directory is not None: + result["eventsLogDirectory"] = from_union([from_str, from_none], self.events_log_directory) + if self.excluded_builtin_agents is not None: + result["excludedBuiltinAgents"] = from_union([lambda x: from_list(from_str, x), from_none], self.excluded_builtin_agents) + if self.excluded_tools is not None: + result["excludedTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.excluded_tools) + if self.exp_assignments is not None: + result["expAssignments"] = self.exp_assignments + if self.feature_flags is not None: + result["featureFlags"] = from_union([lambda x: from_dict(from_bool, x), from_none], self.feature_flags) + if self.included_builtin_agents is not None: + result["includedBuiltinAgents"] = from_union([lambda x: from_list(from_str, x), from_none], self.included_builtin_agents) + if self.installed_plugins is not None: + result["installedPlugins"] = from_union([lambda x: from_list(lambda x: to_class(InstalledPlugin, x), x), from_none], self.installed_plugins) + if self.integration_id is not None: + result["integrationId"] = from_union([from_str, from_none], self.integration_id) + if self.is_experimental_mode is not None: + result["isExperimentalMode"] = from_union([from_bool, from_none], self.is_experimental_mode) + if self.log_interactive_shells is not None: + result["logInteractiveShells"] = from_union([from_bool, from_none], self.log_interactive_shells) + if self.lsp_client_name is not None: + result["lspClientName"] = from_union([from_str, from_none], self.lsp_client_name) + if self.max_inline_binary_bytes is not None: + result["maxInlineBinaryBytes"] = from_union([from_int, from_none], self.max_inline_binary_bytes) + if self.memory is not None: + result["memory"] = from_union([lambda x: to_class(MemoryConfiguration, x), from_none], self.memory) + if self.model is not None: + result["model"] = from_union([from_str, from_none], self.model) + if self.model_capabilities_overrides is not None: + result["modelCapabilitiesOverrides"] = from_union([lambda x: to_class(ModelCapabilitiesOverride, x), from_none], self.model_capabilities_overrides) if self.models is not None: result["models"] = from_union([lambda x: from_list(lambda x: to_class(ProviderModelConfig, x), x), from_none], self.models) + if self.name is not None: + result["name"] = from_union([from_str, from_none], self.name) + if self.provider is not None: + result["provider"] = from_union([lambda x: to_class(ProviderConfig, x), from_none], self.provider) if self.providers is not None: result["providers"] = from_union([lambda x: from_list(lambda x: to_class(NamedProviderConfig, x), x), from_none], self.providers) + if self.reasoning_effort is not None: + result["reasoningEffort"] = from_union([from_str, from_none], self.reasoning_effort) + if self.reasoning_summary is not None: + result["reasoningSummary"] = from_union([lambda x: to_enum(ReasoningSummary, x), from_none], self.reasoning_summary) + if self.remote_defaulted_on is not None: + result["remoteDefaultedOn"] = from_union([from_bool, from_none], self.remote_defaulted_on) + if self.remote_exporting is not None: + result["remoteExporting"] = from_union([from_bool, from_none], self.remote_exporting) + if self.remote_steerable is not None: + result["remoteSteerable"] = from_union([from_bool, from_none], self.remote_steerable) + if self.running_in_interactive_mode is not None: + result["runningInInteractiveMode"] = from_union([from_bool, from_none], self.running_in_interactive_mode) + if self.sandbox_config is not None: + result["sandboxConfig"] = from_union([lambda x: to_class(SandboxConfig, x), from_none], self.sandbox_config) + if self.session_capabilities is not None: + result["sessionCapabilities"] = from_union([lambda x: from_list(lambda x: to_enum(SessionCapability, x), x), from_none], self.session_capabilities) + if self.session_id is not None: + result["sessionId"] = from_union([from_str, from_none], self.session_id) + if self.session_limits is not None: + result["sessionLimits"] = from_union([lambda x: to_class(SessionLimitsConfig, x), from_none], self.session_limits) + if self.shell_init_profile is not None: + result["shellInitProfile"] = from_union([from_str, from_none], self.shell_init_profile) + if self.shell_process_flags is not None: + result["shellProcessFlags"] = from_union([lambda x: from_list(from_str, x), from_none], self.shell_process_flags) + if self.skill_directories is not None: + result["skillDirectories"] = from_union([lambda x: from_list(from_str, x), from_none], self.skill_directories) + if self.skip_custom_instructions is not None: + result["skipCustomInstructions"] = from_union([from_bool, from_none], self.skip_custom_instructions) + if self.trajectory_file is not None: + result["trajectoryFile"] = from_union([from_str, from_none], self.trajectory_file) + if self.verbosity is not None: + result["verbosity"] = from_union([lambda x: to_enum(Verbosity, x), from_none], self.verbosity) + if self.working_directory is not None: + result["workingDirectory"] = from_union([from_str, from_none], self.working_directory) + if self.working_directory_context is not None: + result["workingDirectoryContext"] = from_union([lambda x: to_class(SessionContext, x), from_none], self.working_directory_context) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionOpenOptions: - """Session construction options. - - Session resume options. - - Session options for the connection. - - Session options for cloud session creation. +class SessionUpdateOptionsParams: + """Patch of mutable session options to apply to the running session.""" - Session construction options for the new local session. - """ - additional_content_exclusion_policies: list[SessionOpenOptionsAdditionalContentExclusionPolicy] | None = None - """Additional content-exclusion policies to merge into the session policy set.""" + additional_content_exclusion_policies: list[OptionsUpdateAdditionalContentExclusionPolicy] | None = None + """Additional content-exclusion policies to merge into the session's policy set.""" agent_context: str | None = None - """Runtime context discriminator for agent filtering.""" + """Runtime context discriminator (e.g., `cli`, `actions`).""" + allow_all_mcp_server_instructions: bool | None = None + """Whether to include instructions from every MCP server in the system prompt instead of + only allowlisted servers. + """ ask_user_disabled: bool | None = None - """Whether ask_user is explicitly disabled.""" - - auth_info: AuthInfo | None = None - """Initial authentication info for the session.""" + """Whether to disable the `ask_user` tool (encourages autonomous behavior).""" available_tools: list[str] | None = None - """Allowlist of available tool names.""" + """Allowlist of tool names available to this session.""" capi: CapiSessionOptions | None = None """Options scoped to the built-in CAPI (Copilot API) provider.""" - client_kind: str | None = None - """Structured client kind used for runtime behavior gates.""" - client_name: str | None = None """Identifier of the client driving the session.""" coauthor_enabled: bool | None = None - """Whether commit-message coauthor trailers are enabled.""" - - config_dir: str | None = None - """Override Copilot configuration directory.""" + """Whether to include the `Co-authored-by` trailer in commit messages.""" + context_tier: OptionsUpdateContextTier | None = None + """Context tier for models with tiered pricing. The session uses this to derive effective + `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits + honor the selected tier. + """ continue_on_auto_mode: bool | None = None - """Whether auto-mode continuation is enabled.""" + """Whether to allow auto-mode continuation across turns.""" copilot_url: str | None = None """Override URL for the Copilot API endpoint.""" custom_agents_local_only: bool | None = None - """Whether custom agents default to local-only execution.""" - - detached_from_spawning_parent_engagement_id: str | None = None - """Parent engagement ID for detached child telemetry rollup.""" - - detached_from_spawning_parent_session_id: str | None = None - """Parent session ID for detached child telemetry rollup.""" + """Whether to default custom agents to local-only execution.""" disabled_instruction_sources: list[str] | None = None - """Instruction source IDs disabled for this session.""" + """Instruction source IDs to exclude from the system prompt.""" disabled_skills: list[str] | None = None - """Skill IDs disabled for this session.""" + """Skill IDs that should be excluded from this session.""" - enable_citations: bool | None = None - """Experimental: enable native model citations (Anthropic models today), normalized onto the - `assistant.message` event. Off by default; may change or be removed while the citations - surface is experimental. + enable_file_hooks: bool | None = None + """Whether to enable loading of `.github/hooks/` filesystem hooks. Separate from the SDK + callback hook mechanism. + """ + enable_host_git_operations: bool | None = None + """Whether to enable host git operations (context resolution, child repo scanning, git info + in system prompt). """ enable_on_demand_instruction_discovery: bool | None = None - """Whether on-demand custom instruction discovery is enabled.""" + """Whether to discover custom instructions on demand after successful file views (AGENTS.md + / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with + `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. + """ + enable_reasoning_summaries: bool | None = None + """Whether to surface reasoning-summary events from the model.""" enable_script_safety: bool | None = None """Whether shell-script safety heuristics are enabled.""" + enable_session_store: bool | None = None + """Whether to enable cross-session store writes and reads.""" + + enable_skills: bool | None = None + """Whether to enable skill directory scanning and loading. Falls back to + enableConfigDiscovery when unset. + """ enable_streaming: bool | None = None - """Whether model responses stream as delta events.""" + """Whether to stream model responses.""" env_value_mode: MCPSetEnvValueModeDetails | None = None - """How MCP server environment values are interpreted.""" - + """How env values are passed to MCP servers (`direct` inlines literal values; `indirect` + resolves at launch). + """ events_log_directory: str | None = None - """Override directory for session event logs.""" - + """Override directory for the session-events log. When unset, the runtime's default events + log directory is used. + """ + excluded_builtin_agents: list[str] | None = None + """Built-in subagent names to exclude from this session. Excluded built-ins are hidden from + agent discovery and cannot be dispatched unless a custom agent with the same name is + available. + """ excluded_tools: list[str] | None = None - """Denylist of tool names.""" + """Denylist of tool names for this session.""" - # Internal: this field is an internal SDK API and is not part of the public surface. - exp_assignments: Any = None - """ExP assignment ('flight') data injected by an SDK integrator, in the same JSON shape the - Copilot CLI fetches from the experimentation service (CopilotExpAssignmentResponse). When - supplied this is fed into the FeatureFlagService exactly like CLI-fetched assignments and - ExP-backed flags wait for it. When absent the session does not block on ExP. - """ feature_flags: dict[str, bool] | None = None - """Feature-flag values resolved by the host.""" - - installed_plugins: list[InstalledPlugin] | None = None - """Installed plugins visible to the session.""" + """Map of feature-flag IDs to their boolean enabled state.""" + included_builtin_agents: list[str] | None = None + """Built-in subagent names to include in this session. When specified, only these built-ins + are available, subject to runtime availability and exclusions. Custom agents with the + same name remain available. Set to null to remove the allowlist restriction. + """ + installed_plugins: list[SessionInstalledPlugin] | None = None + """Full set of installed plugins for the session. Replaces the existing list; the runtime + invalidates the skills cache only when the list materially changes. + """ integration_id: str | None = None - """Stable integration identifier for analytics.""" + """Stable integration identifier used for analytics and rate-limit attribution.""" is_experimental_mode: bool | None = None - """Whether experimental behavior is enabled.""" + """Whether experimental capabilities are enabled.""" log_interactive_shells: bool | None = None """Whether interactive shell sessions are logged.""" @@ -19258,197 +22169,202 @@ class SessionOpenOptions: lsp_client_name: str | None = None """Identifier sent to LSP-style integrations.""" + manage_schedule_enabled: bool | None = None + """Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the + per-session schedule registry; this flag only controls tool exposure (typically gated to + staff users). + """ max_inline_binary_bytes: int | None = None - """Maximum decoded byte size of a single inline model-facing binary tool result persisted in - session events (default 10 MB). + """Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) + persisted inline in session events and re-presented to the model on later turns / resume. + Larger results are persisted as a metadata-only marker and shown to the model as a short + text note. Defaults to 10 MB. """ - memory: MemoryConfiguration | None = None - """Memory configuration for this session.""" - model: str | None = None - """Initial model identifier.""" + """The model ID to use for assistant turns.""" model_capabilities_overrides: ModelCapabilitiesOverride | None = None - """Initial model capability overrides.""" + """Per-property model capability overrides for the selected model.""" - models: list[ProviderModelConfig] | None = None - """BYOK model definitions added to the selectable model list, each referencing a provider - name. - """ - name: str | None = None - """Optional human-friendly session name.""" + organization_custom_instructions: str | None = None + """Organization-level custom instructions to inject into the system prompt.""" provider: ProviderConfig | None = None """Custom model-provider configuration (BYOK).""" - providers: list[NamedProviderConfig] | None = None - """Named BYOK provider connections, additive to CAPI auth. Combining with `provider` is - rejected. - """ reasoning_effort: str | None = None - """Initial reasoning effort level.""" + """Reasoning effort for the selected model (model-defined enum).""" reasoning_summary: ReasoningSummary | None = None - """Initial reasoning summary mode for supported model clients.""" - - remote_defaulted_on: bool | None = None - """Telemetry-only remote-defaulted flag.""" - - remote_exporting: bool | None = None - """Telemetry-only remote exporting flag.""" - - remote_steerable: bool | None = None - """Whether this session supports remote steering.""" + """Reasoning summary mode for supported model clients.""" running_in_interactive_mode: bool | None = None - """Whether the host is an interactive UI.""" + """Whether the session is running in an interactive UI.""" sandbox_config: SandboxConfig | None = None """Resolved sandbox configuration.""" session_capabilities: list[SessionCapability] | None = None - """Capabilities enabled for this session.""" - - session_id: str | None = None - """Optional stable session identifier to use for a new session.""" + """Replaces the session's capability set with the given list. Use to enable or disable + capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the + field to leave the existing capability set unchanged. + """ + session_limits: SessionLimitsConfig | None = None + """Optional session limits. Pass null to clear the session limits.""" shell_init_profile: str | None = None - """Shell init profile.""" + """Shell init profile (`None` or `NonInteractive`).""" shell_process_flags: list[str] | None = None - """Per-shell process flags.""" + """Per-shell process flags (e.g., `pwsh` arguments).""" skill_directories: list[str] | None = None """Additional directories to search for skills.""" skip_custom_instructions: bool | None = None - """Whether to skip custom instruction sources.""" + """Whether to skip loading custom instruction sources.""" + + skip_embedding_retrieval: bool | None = None + """Whether to skip embedding retrieval pipeline initialization and execution.""" + suppress_custom_agent_prompt: bool | None = None + """When true, the selected custom agent's prompt is not injected into the user message + (skill context is still injected). Used by automation triggers where the agent prompt is + already in the problem statement. + """ + tool_filter_precedence: OptionsUpdateToolFilterPrecedence | None = None + """Controls how availableTools (allowlist) and excludedTools (denylist) combine when both + are set. + """ trajectory_file: str | None = None - """Optional trajectory output file path.""" + """Optional path for trajectory output.""" - working_directory: str | None = None - """Working directory to anchor the session.""" + verbosity: Verbosity | None = None + """Output verbosity level for supported models.""" - working_directory_context: SessionContext | None = None - """Pre-resolved working-directory context for session startup.""" + working_directory: str | None = None + """Absolute working-directory path for shell tools.""" @staticmethod - def from_dict(obj: Any) -> 'SessionOpenOptions': + def from_dict(obj: Any) -> 'SessionUpdateOptionsParams': assert isinstance(obj, dict) - additional_content_exclusion_policies = from_union([lambda x: from_list(SessionOpenOptionsAdditionalContentExclusionPolicy.from_dict, x), from_none], obj.get("additionalContentExclusionPolicies")) + additional_content_exclusion_policies = from_union([lambda x: from_list(OptionsUpdateAdditionalContentExclusionPolicy.from_dict, x), from_none], obj.get("additionalContentExclusionPolicies")) agent_context = from_union([from_str, from_none], obj.get("agentContext")) + allow_all_mcp_server_instructions = from_union([from_bool, from_none], obj.get("allowAllMcpServerInstructions")) ask_user_disabled = from_union([from_bool, from_none], obj.get("askUserDisabled")) - auth_info = from_union([_load_AuthInfo, from_none], obj.get("authInfo")) available_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("availableTools")) capi = from_union([CapiSessionOptions.from_dict, from_none], obj.get("capi")) - client_kind = from_union([from_str, from_none], obj.get("clientKind")) client_name = from_union([from_str, from_none], obj.get("clientName")) coauthor_enabled = from_union([from_bool, from_none], obj.get("coauthorEnabled")) - config_dir = from_union([from_str, from_none], obj.get("configDir")) + context_tier = from_union([OptionsUpdateContextTier, from_none], obj.get("contextTier")) continue_on_auto_mode = from_union([from_bool, from_none], obj.get("continueOnAutoMode")) copilot_url = from_union([from_str, from_none], obj.get("copilotUrl")) custom_agents_local_only = from_union([from_bool, from_none], obj.get("customAgentsLocalOnly")) - detached_from_spawning_parent_engagement_id = from_union([from_str, from_none], obj.get("detachedFromSpawningParentEngagementId")) - detached_from_spawning_parent_session_id = from_union([from_str, from_none], obj.get("detachedFromSpawningParentSessionId")) disabled_instruction_sources = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledInstructionSources")) disabled_skills = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledSkills")) - enable_citations = from_union([from_bool, from_none], obj.get("enableCitations")) + enable_file_hooks = from_union([from_bool, from_none], obj.get("enableFileHooks")) + enable_host_git_operations = from_union([from_bool, from_none], obj.get("enableHostGitOperations")) enable_on_demand_instruction_discovery = from_union([from_bool, from_none], obj.get("enableOnDemandInstructionDiscovery")) + enable_reasoning_summaries = from_union([from_bool, from_none], obj.get("enableReasoningSummaries")) enable_script_safety = from_union([from_bool, from_none], obj.get("enableScriptSafety")) + enable_session_store = from_union([from_bool, from_none], obj.get("enableSessionStore")) + enable_skills = from_union([from_bool, from_none], obj.get("enableSkills")) enable_streaming = from_union([from_bool, from_none], obj.get("enableStreaming")) env_value_mode = from_union([MCPSetEnvValueModeDetails, from_none], obj.get("envValueMode")) events_log_directory = from_union([from_str, from_none], obj.get("eventsLogDirectory")) + excluded_builtin_agents = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedBuiltinAgents")) excluded_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedTools")) - exp_assignments = obj.get("expAssignments") feature_flags = from_union([lambda x: from_dict(from_bool, x), from_none], obj.get("featureFlags")) - installed_plugins = from_union([lambda x: from_list(InstalledPlugin.from_dict, x), from_none], obj.get("installedPlugins")) + included_builtin_agents = from_union([lambda x: from_list(from_str, x), from_none], obj.get("includedBuiltinAgents")) + installed_plugins = from_union([lambda x: from_list(SessionInstalledPlugin.from_dict, x), from_none], obj.get("installedPlugins")) integration_id = from_union([from_str, from_none], obj.get("integrationId")) is_experimental_mode = from_union([from_bool, from_none], obj.get("isExperimentalMode")) log_interactive_shells = from_union([from_bool, from_none], obj.get("logInteractiveShells")) lsp_client_name = from_union([from_str, from_none], obj.get("lspClientName")) + manage_schedule_enabled = from_union([from_bool, from_none], obj.get("manageScheduleEnabled")) max_inline_binary_bytes = from_union([from_int, from_none], obj.get("maxInlineBinaryBytes")) - memory = from_union([MemoryConfiguration.from_dict, from_none], obj.get("memory")) model = from_union([from_str, from_none], obj.get("model")) model_capabilities_overrides = from_union([ModelCapabilitiesOverride.from_dict, from_none], obj.get("modelCapabilitiesOverrides")) - models = from_union([lambda x: from_list(ProviderModelConfig.from_dict, x), from_none], obj.get("models")) - name = from_union([from_str, from_none], obj.get("name")) + organization_custom_instructions = from_union([from_str, from_none], obj.get("organizationCustomInstructions")) provider = from_union([ProviderConfig.from_dict, from_none], obj.get("provider")) - providers = from_union([lambda x: from_list(NamedProviderConfig.from_dict, x), from_none], obj.get("providers")) reasoning_effort = from_union([from_str, from_none], obj.get("reasoningEffort")) reasoning_summary = from_union([ReasoningSummary, from_none], obj.get("reasoningSummary")) - remote_defaulted_on = from_union([from_bool, from_none], obj.get("remoteDefaultedOn")) - remote_exporting = from_union([from_bool, from_none], obj.get("remoteExporting")) - remote_steerable = from_union([from_bool, from_none], obj.get("remoteSteerable")) running_in_interactive_mode = from_union([from_bool, from_none], obj.get("runningInInteractiveMode")) sandbox_config = from_union([SandboxConfig.from_dict, from_none], obj.get("sandboxConfig")) session_capabilities = from_union([lambda x: from_list(SessionCapability, x), from_none], obj.get("sessionCapabilities")) - session_id = from_union([from_str, from_none], obj.get("sessionId")) + session_limits = from_union([SessionLimitsConfig.from_dict, from_none], obj.get("sessionLimits")) shell_init_profile = from_union([from_str, from_none], obj.get("shellInitProfile")) shell_process_flags = from_union([lambda x: from_list(from_str, x), from_none], obj.get("shellProcessFlags")) skill_directories = from_union([lambda x: from_list(from_str, x), from_none], obj.get("skillDirectories")) skip_custom_instructions = from_union([from_bool, from_none], obj.get("skipCustomInstructions")) + skip_embedding_retrieval = from_union([from_bool, from_none], obj.get("skipEmbeddingRetrieval")) + suppress_custom_agent_prompt = from_union([from_bool, from_none], obj.get("suppressCustomAgentPrompt")) + tool_filter_precedence = from_union([OptionsUpdateToolFilterPrecedence, from_none], obj.get("toolFilterPrecedence")) trajectory_file = from_union([from_str, from_none], obj.get("trajectoryFile")) + verbosity = from_union([Verbosity, from_none], obj.get("verbosity")) working_directory = from_union([from_str, from_none], obj.get("workingDirectory")) - working_directory_context = from_union([SessionContext.from_dict, from_none], obj.get("workingDirectoryContext")) - return SessionOpenOptions(additional_content_exclusion_policies, agent_context, ask_user_disabled, auth_info, available_tools, capi, client_kind, client_name, coauthor_enabled, config_dir, continue_on_auto_mode, copilot_url, custom_agents_local_only, detached_from_spawning_parent_engagement_id, detached_from_spawning_parent_session_id, disabled_instruction_sources, disabled_skills, enable_citations, enable_on_demand_instruction_discovery, enable_script_safety, enable_streaming, env_value_mode, events_log_directory, excluded_tools, exp_assignments, feature_flags, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, max_inline_binary_bytes, memory, model, model_capabilities_overrides, models, name, provider, providers, reasoning_effort, reasoning_summary, remote_defaulted_on, remote_exporting, remote_steerable, running_in_interactive_mode, sandbox_config, session_capabilities, session_id, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, trajectory_file, working_directory, working_directory_context) + return SessionUpdateOptionsParams(additional_content_exclusion_policies, agent_context, allow_all_mcp_server_instructions, ask_user_disabled, available_tools, capi, client_name, coauthor_enabled, context_tier, continue_on_auto_mode, copilot_url, custom_agents_local_only, disabled_instruction_sources, disabled_skills, enable_file_hooks, enable_host_git_operations, enable_on_demand_instruction_discovery, enable_reasoning_summaries, enable_script_safety, enable_session_store, enable_skills, enable_streaming, env_value_mode, events_log_directory, excluded_builtin_agents, excluded_tools, feature_flags, included_builtin_agents, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, manage_schedule_enabled, max_inline_binary_bytes, model, model_capabilities_overrides, organization_custom_instructions, provider, reasoning_effort, reasoning_summary, running_in_interactive_mode, sandbox_config, session_capabilities, session_limits, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, skip_embedding_retrieval, suppress_custom_agent_prompt, tool_filter_precedence, trajectory_file, verbosity, working_directory) def to_dict(self) -> dict: result: dict = {} if self.additional_content_exclusion_policies is not None: - result["additionalContentExclusionPolicies"] = from_union([lambda x: from_list(lambda x: to_class(SessionOpenOptionsAdditionalContentExclusionPolicy, x), x), from_none], self.additional_content_exclusion_policies) + result["additionalContentExclusionPolicies"] = from_union([lambda x: from_list(lambda x: to_class(OptionsUpdateAdditionalContentExclusionPolicy, x), x), from_none], self.additional_content_exclusion_policies) if self.agent_context is not None: result["agentContext"] = from_union([from_str, from_none], self.agent_context) + if self.allow_all_mcp_server_instructions is not None: + result["allowAllMcpServerInstructions"] = from_union([from_bool, from_none], self.allow_all_mcp_server_instructions) if self.ask_user_disabled is not None: result["askUserDisabled"] = from_union([from_bool, from_none], self.ask_user_disabled) - if self.auth_info is not None: - result["authInfo"] = from_union([lambda x: (x).to_dict(), from_none], self.auth_info) if self.available_tools is not None: result["availableTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.available_tools) if self.capi is not None: result["capi"] = from_union([lambda x: to_class(CapiSessionOptions, x), from_none], self.capi) - if self.client_kind is not None: - result["clientKind"] = from_union([from_str, from_none], self.client_kind) if self.client_name is not None: result["clientName"] = from_union([from_str, from_none], self.client_name) if self.coauthor_enabled is not None: result["coauthorEnabled"] = from_union([from_bool, from_none], self.coauthor_enabled) - if self.config_dir is not None: - result["configDir"] = from_union([from_str, from_none], self.config_dir) + if self.context_tier is not None: + result["contextTier"] = from_union([lambda x: to_enum(OptionsUpdateContextTier, x), from_none], self.context_tier) if self.continue_on_auto_mode is not None: result["continueOnAutoMode"] = from_union([from_bool, from_none], self.continue_on_auto_mode) if self.copilot_url is not None: result["copilotUrl"] = from_union([from_str, from_none], self.copilot_url) if self.custom_agents_local_only is not None: result["customAgentsLocalOnly"] = from_union([from_bool, from_none], self.custom_agents_local_only) - if self.detached_from_spawning_parent_engagement_id is not None: - result["detachedFromSpawningParentEngagementId"] = from_union([from_str, from_none], self.detached_from_spawning_parent_engagement_id) - if self.detached_from_spawning_parent_session_id is not None: - result["detachedFromSpawningParentSessionId"] = from_union([from_str, from_none], self.detached_from_spawning_parent_session_id) if self.disabled_instruction_sources is not None: result["disabledInstructionSources"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_instruction_sources) if self.disabled_skills is not None: result["disabledSkills"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_skills) - if self.enable_citations is not None: - result["enableCitations"] = from_union([from_bool, from_none], self.enable_citations) + if self.enable_file_hooks is not None: + result["enableFileHooks"] = from_union([from_bool, from_none], self.enable_file_hooks) + if self.enable_host_git_operations is not None: + result["enableHostGitOperations"] = from_union([from_bool, from_none], self.enable_host_git_operations) if self.enable_on_demand_instruction_discovery is not None: result["enableOnDemandInstructionDiscovery"] = from_union([from_bool, from_none], self.enable_on_demand_instruction_discovery) + if self.enable_reasoning_summaries is not None: + result["enableReasoningSummaries"] = from_union([from_bool, from_none], self.enable_reasoning_summaries) if self.enable_script_safety is not None: result["enableScriptSafety"] = from_union([from_bool, from_none], self.enable_script_safety) + if self.enable_session_store is not None: + result["enableSessionStore"] = from_union([from_bool, from_none], self.enable_session_store) + if self.enable_skills is not None: + result["enableSkills"] = from_union([from_bool, from_none], self.enable_skills) if self.enable_streaming is not None: result["enableStreaming"] = from_union([from_bool, from_none], self.enable_streaming) if self.env_value_mode is not None: result["envValueMode"] = from_union([lambda x: to_enum(MCPSetEnvValueModeDetails, x), from_none], self.env_value_mode) if self.events_log_directory is not None: result["eventsLogDirectory"] = from_union([from_str, from_none], self.events_log_directory) + if self.excluded_builtin_agents is not None: + result["excludedBuiltinAgents"] = from_union([lambda x: from_list(from_str, x), from_none], self.excluded_builtin_agents) if self.excluded_tools is not None: result["excludedTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.excluded_tools) - if self.exp_assignments is not None: - result["expAssignments"] = self.exp_assignments if self.feature_flags is not None: result["featureFlags"] = from_union([lambda x: from_dict(from_bool, x), from_none], self.feature_flags) + if self.included_builtin_agents is not None: + result["includedBuiltinAgents"] = from_union([lambda x: from_list(from_str, x), from_none], self.included_builtin_agents) if self.installed_plugins is not None: - result["installedPlugins"] = from_union([lambda x: from_list(lambda x: to_class(InstalledPlugin, x), x), from_none], self.installed_plugins) + result["installedPlugins"] = from_union([lambda x: from_list(lambda x: to_class(SessionInstalledPlugin, x), x), from_none], self.installed_plugins) if self.integration_id is not None: result["integrationId"] = from_union([from_str, from_none], self.integration_id) if self.is_experimental_mode is not None: @@ -19457,40 +22373,30 @@ def to_dict(self) -> dict: result["logInteractiveShells"] = from_union([from_bool, from_none], self.log_interactive_shells) if self.lsp_client_name is not None: result["lspClientName"] = from_union([from_str, from_none], self.lsp_client_name) + if self.manage_schedule_enabled is not None: + result["manageScheduleEnabled"] = from_union([from_bool, from_none], self.manage_schedule_enabled) if self.max_inline_binary_bytes is not None: result["maxInlineBinaryBytes"] = from_union([from_int, from_none], self.max_inline_binary_bytes) - if self.memory is not None: - result["memory"] = from_union([lambda x: to_class(MemoryConfiguration, x), from_none], self.memory) if self.model is not None: result["model"] = from_union([from_str, from_none], self.model) if self.model_capabilities_overrides is not None: result["modelCapabilitiesOverrides"] = from_union([lambda x: to_class(ModelCapabilitiesOverride, x), from_none], self.model_capabilities_overrides) - if self.models is not None: - result["models"] = from_union([lambda x: from_list(lambda x: to_class(ProviderModelConfig, x), x), from_none], self.models) - if self.name is not None: - result["name"] = from_union([from_str, from_none], self.name) + if self.organization_custom_instructions is not None: + result["organizationCustomInstructions"] = from_union([from_str, from_none], self.organization_custom_instructions) if self.provider is not None: result["provider"] = from_union([lambda x: to_class(ProviderConfig, x), from_none], self.provider) - if self.providers is not None: - result["providers"] = from_union([lambda x: from_list(lambda x: to_class(NamedProviderConfig, x), x), from_none], self.providers) if self.reasoning_effort is not None: result["reasoningEffort"] = from_union([from_str, from_none], self.reasoning_effort) if self.reasoning_summary is not None: result["reasoningSummary"] = from_union([lambda x: to_enum(ReasoningSummary, x), from_none], self.reasoning_summary) - if self.remote_defaulted_on is not None: - result["remoteDefaultedOn"] = from_union([from_bool, from_none], self.remote_defaulted_on) - if self.remote_exporting is not None: - result["remoteExporting"] = from_union([from_bool, from_none], self.remote_exporting) - if self.remote_steerable is not None: - result["remoteSteerable"] = from_union([from_bool, from_none], self.remote_steerable) if self.running_in_interactive_mode is not None: result["runningInInteractiveMode"] = from_union([from_bool, from_none], self.running_in_interactive_mode) if self.sandbox_config is not None: result["sandboxConfig"] = from_union([lambda x: to_class(SandboxConfig, x), from_none], self.sandbox_config) if self.session_capabilities is not None: result["sessionCapabilities"] = from_union([lambda x: from_list(lambda x: to_enum(SessionCapability, x), x), from_none], self.session_capabilities) - if self.session_id is not None: - result["sessionId"] = from_union([from_str, from_none], self.session_id) + if self.session_limits is not None: + result["sessionLimits"] = from_union([lambda x: to_class(SessionLimitsConfig, x), from_none], self.session_limits) if self.shell_init_profile is not None: result["shellInitProfile"] = from_union([from_str, from_none], self.shell_init_profile) if self.shell_process_flags is not None: @@ -19499,786 +22405,953 @@ def to_dict(self) -> dict: result["skillDirectories"] = from_union([lambda x: from_list(from_str, x), from_none], self.skill_directories) if self.skip_custom_instructions is not None: result["skipCustomInstructions"] = from_union([from_bool, from_none], self.skip_custom_instructions) + if self.skip_embedding_retrieval is not None: + result["skipEmbeddingRetrieval"] = from_union([from_bool, from_none], self.skip_embedding_retrieval) + if self.suppress_custom_agent_prompt is not None: + result["suppressCustomAgentPrompt"] = from_union([from_bool, from_none], self.suppress_custom_agent_prompt) + if self.tool_filter_precedence is not None: + result["toolFilterPrecedence"] = from_union([lambda x: to_enum(OptionsUpdateToolFilterPrecedence, x), from_none], self.tool_filter_precedence) if self.trajectory_file is not None: result["trajectoryFile"] = from_union([from_str, from_none], self.trajectory_file) + if self.verbosity is not None: + result["verbosity"] = from_union([lambda x: to_enum(Verbosity, x), from_none], self.verbosity) if self.working_directory is not None: result["workingDirectory"] = from_union([from_str, from_none], self.working_directory) - if self.working_directory_context is not None: - result["workingDirectoryContext"] = from_union([lambda x: to_class(SessionContext, x), from_none], self.working_directory_context) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionUpdateOptionsParams: - """Patch of mutable session options to apply to the running session.""" - - additional_content_exclusion_policies: list[OptionsUpdateAdditionalContentExclusionPolicy] | None = None - """Additional content-exclusion policies to merge into the session's policy set.""" +class UIElicitationRequest: + """Prompt message and JSON schema describing the form fields to elicit from the user.""" + + message: str + """Message describing what information is needed from the user""" + + requested_schema: UIElicitationSchema + """JSON Schema describing the form fields to present to the user""" + + @staticmethod + def from_dict(obj: Any) -> 'UIElicitationRequest': + assert isinstance(obj, dict) + message = from_str(obj.get("message")) + requested_schema = UIElicitationSchema.from_dict(obj.get("requestedSchema")) + return UIElicitationRequest(message, requested_schema) + + def to_dict(self) -> dict: + result: dict = {} + result["message"] = from_str(self.message) + result["requestedSchema"] = to_class(UIElicitationSchema, self.requested_schema) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsOpenCreate: + """Parameters for creating a new local session.""" + + kind: ClassVar[str] = "create" + """Create a new local session.""" + + emit_start: bool | None = None + """Whether to emit session.start during creation. Defaults to true.""" + + options: SessionOpenOptions | None = None + """Session construction options.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsOpenCreate': + assert isinstance(obj, dict) + emit_start = from_union([from_bool, from_none], obj.get("emitStart")) + options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) + return SessionsOpenCreate(emit_start, options) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + if self.emit_start is not None: + result["emitStart"] = from_union([from_bool, from_none], self.emit_start) + if self.options is not None: + result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsOpenRemote: + """Parameters for connecting to a live remote session.""" + + kind: ClassVar[str] = "remote" + """Connect to a live remote session.""" + + remote_session_id: str + """Remote session identifier to connect to.""" + + options: SessionOpenOptions | None = None + """Session options for the connection.""" + + repository: RemoteSessionRepository | None = None + """Repository context for the remote session.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsOpenRemote': + assert isinstance(obj, dict) + remote_session_id = from_str(obj.get("remoteSessionId")) + options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) + repository = from_union([RemoteSessionRepository.from_dict, from_none], obj.get("repository")) + return SessionsOpenRemote(remote_session_id, options, repository) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + result["remoteSessionId"] = from_str(self.remote_session_id) + if self.options is not None: + result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) + if self.repository is not None: + result["repository"] = from_union([lambda x: to_class(RemoteSessionRepository, x), from_none], self.repository) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsOpenResume: + """Parameters for resuming a specific local session.""" + + kind: ClassVar[str] = "resume" + """Resume a specific local session by ID or prefix.""" + + session_id: str + """Session ID or unique prefix to resume.""" + + options: SessionOpenOptions | None = None + """Session resume options.""" + + resume: bool | None = None + """Whether to emit session.resume after loading. Defaults to true.""" + + suppress_resume_workspace_metadata_writeback: bool | None = None + """Suppress workspace.yaml metadata writeback when resuming from an incidental cwd.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsOpenResume': + assert isinstance(obj, dict) + session_id = from_str(obj.get("sessionId")) + options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) + resume = from_union([from_bool, from_none], obj.get("resume")) + suppress_resume_workspace_metadata_writeback = from_union([from_bool, from_none], obj.get("suppressResumeWorkspaceMetadataWriteback")) + return SessionsOpenResume(session_id, options, resume, suppress_resume_workspace_metadata_writeback) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + result["sessionId"] = from_str(self.session_id) + if self.options is not None: + result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) + if self.resume is not None: + result["resume"] = from_union([from_bool, from_none], self.resume) + if self.suppress_resume_workspace_metadata_writeback is not None: + result["suppressResumeWorkspaceMetadataWriteback"] = from_union([from_bool, from_none], self.suppress_resume_workspace_metadata_writeback) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsOpenResumeLast: + """Parameters for resuming the most relevant local session.""" - agent_context: str | None = None - """Runtime context discriminator (e.g., `cli`, `actions`).""" + kind: ClassVar[str] = "resumeLast" + """Resume the most relevant existing local session.""" - ask_user_disabled: bool | None = None - """Whether to disable the `ask_user` tool (encourages autonomous behavior).""" + context: SessionContext | None = None + """Working-directory context used to choose the most relevant session.""" - available_tools: list[str] | None = None - """Allowlist of tool names available to this session.""" + options: SessionOpenOptions | None = None + """Session resume options.""" - capi: CapiSessionOptions | None = None - """Options scoped to the built-in CAPI (Copilot API) provider.""" + suppress_resume_workspace_metadata_writeback: bool | None = None + """Suppress workspace.yaml metadata writeback when resuming from an incidental cwd.""" - client_name: str | None = None - """Identifier of the client driving the session.""" + @staticmethod + def from_dict(obj: Any) -> 'SessionsOpenResumeLast': + assert isinstance(obj, dict) + context = from_union([SessionContext.from_dict, from_none], obj.get("context")) + options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) + suppress_resume_workspace_metadata_writeback = from_union([from_bool, from_none], obj.get("suppressResumeWorkspaceMetadataWriteback")) + return SessionsOpenResumeLast(context, options, suppress_resume_workspace_metadata_writeback) - coauthor_enabled: bool | None = None - """Whether to include the `Co-authored-by` trailer in commit messages.""" + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + if self.context is not None: + result["context"] = from_union([lambda x: to_class(SessionContext, x), from_none], self.context) + if self.options is not None: + result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) + if self.suppress_resume_workspace_metadata_writeback is not None: + result["suppressResumeWorkspaceMetadataWriteback"] = from_union([from_bool, from_none], self.suppress_resume_workspace_metadata_writeback) + return result - context_tier: OptionsUpdateContextTier | None = None - """Context tier for models with tiered pricing. The session uses this to derive effective - `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits - honor the selected tier. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CopilotUserResponse: + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. """ - continue_on_auto_mode: bool | None = None - """Whether to allow auto-mode continuation across turns.""" + access_type_sku: str | None = None + """Copilot access SKU identifier (e.g. `free_limited_copilot`, + `copilot_for_business_seat_quota`) used to gate model and feature access. + """ + analytics_tracking_id: str | None = None + """Opaque analytics tracking identifier for the user, forwarded from the Copilot API.""" - copilot_url: str | None = None - """Override URL for the Copilot API endpoint.""" + assigned_date: Any = None + """Date the Copilot seat was assigned to the user, if applicable.""" - custom_agents_local_only: bool | None = None - """Whether to default custom agents to local-only execution.""" + can_signup_for_limited: bool | None = None + """Whether the user is eligible to sign up for the free/limited Copilot tier.""" - disabled_instruction_sources: list[str] | None = None - """Instruction source IDs to exclude from the system prompt.""" + can_upgrade_plan: bool | None = None + """Whether the user is able to upgrade their Copilot plan.""" - disabled_skills: list[str] | None = None - """Skill IDs that should be excluded from this session.""" + chat_enabled: bool | None = None + """Whether Copilot chat is enabled for the user.""" - enable_file_hooks: bool | None = None - """Whether to enable loading of `.github/hooks/` filesystem hooks. Separate from the SDK - callback hook mechanism. - """ - enable_host_git_operations: bool | None = None - """Whether to enable host git operations (context resolution, child repo scanning, git info - in system prompt). - """ - enable_on_demand_instruction_discovery: bool | None = None - """Whether to discover custom instructions on demand after successful file views (AGENTS.md - / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with - `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. - """ - enable_reasoning_summaries: bool | None = None - """Whether to surface reasoning-summary events from the model.""" + cli_remote_control_enabled: bool | None = None + """Whether CLI remote control is enabled for the user.""" - enable_script_safety: bool | None = None - """Whether shell-script safety heuristics are enabled.""" + cloud_session_storage_enabled: bool | None = None + """Whether cloud session storage is enabled for the user.""" - enable_session_store: bool | None = None - """Whether to enable cross-session store writes and reads.""" + codex_agent_enabled: bool | None = None + """Whether the Codex agent is enabled for the user.""" - enable_skills: bool | None = None - """Whether to enable skill directory scanning and loading. Falls back to - enableConfigDiscovery when unset. - """ - enable_streaming: bool | None = None - """Whether to stream model responses.""" + copilot_plan: str | None = None + """Copilot plan name for the user (e.g. `individual`, `business`, `enterprise`).""" - env_value_mode: MCPSetEnvValueModeDetails | None = None - """How env values are passed to MCP servers (`direct` inlines literal values; `indirect` - resolves at launch). - """ - events_log_directory: str | None = None - """Override directory for the session-events log. When unset, the runtime's default events - log directory is used. - """ - excluded_tools: list[str] | None = None - """Denylist of tool names for this session.""" + copilotignore_enabled: bool | None = None + """Whether `.copilotignore` content-exclusion support is enabled for the user.""" - feature_flags: dict[str, bool] | None = None - """Map of feature-flag IDs to their boolean enabled state.""" + endpoints: CopilotUserResponseEndpoints | None = None + """Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough.""" - installed_plugins: list[SessionInstalledPlugin] | None = None - """Full set of installed plugins for the session. Replaces the existing list; the runtime - invalidates the skills cache only when the list materially changes. + is_mcp_enabled: Any = None + """Whether MCP (Model Context Protocol) support is enabled for the user.""" + + is_staff: bool | None = None + """Whether the user is a GitHub/Microsoft staff member.""" + + limited_user_quotas: dict[str, float] | None = None + """Per-category quota allotments for free/limited-tier users, keyed by quota category.""" + + limited_user_reset_date: str | None = None + """Date the free/limited-tier user's quotas next reset, as a raw string from the Copilot API.""" + + login: str | None = None + """GitHub login of the authenticated user.""" + + monthly_quotas: dict[str, float] | None = None + """Per-category monthly quota allotments, keyed by quota category.""" + + organization_list: Any = None + """Organizations the user belongs to, each with an optional login and display name.""" + + organization_login_list: list[str] | None = None + """Logins of the organizations the user belongs to.""" + + quota_reset_date: str | None = None + """Date the user's usage quota next resets, as a raw string from the Copilot API; see + `quota_reset_date_utc` for the UTC-normalized value. """ - integration_id: str | None = None - """Stable integration identifier used for analytics and rate-limit attribution.""" + quota_reset_date_utc: str | None = None + """UTC-normalized form of `quota_reset_date` (the date the user's usage quota next resets).""" - is_experimental_mode: bool | None = None - """Whether experimental capabilities are enabled.""" + quota_snapshots: dict[str, CopilotUserResponseQuotaSnapshots | None] | None = None + """Quota snapshot map from the raw Copilot user-response passthrough, with chat, + completions, premium-interactions, and other entries. + """ + restricted_telemetry: bool | None = None + """Whether the user's telemetry is subject to restricted-data handling.""" - log_interactive_shells: bool | None = None - """Whether interactive shell sessions are logged.""" + te: bool | None = None + """Raw passthrough of the Copilot API `te` flag for the user (an opaque server-side + eligibility signal surfaced in telemetry); not otherwise interpreted by the runtime. + """ + token_based_billing: bool | None = None + """Whether the account is on usage-based (token/AI-credit) billing rather than a fixed + premium-request quota. + """ - lsp_client_name: str | None = None - """Identifier sent to LSP-style integrations.""" + @staticmethod + def from_dict(obj: Any) -> 'CopilotUserResponse': + assert isinstance(obj, dict) + access_type_sku = from_union([from_str, from_none], obj.get("access_type_sku")) + analytics_tracking_id = from_union([from_str, from_none], obj.get("analytics_tracking_id")) + assigned_date = obj.get("assigned_date") + can_signup_for_limited = from_union([from_bool, from_none], obj.get("can_signup_for_limited")) + can_upgrade_plan = from_union([from_bool, from_none], obj.get("can_upgrade_plan")) + chat_enabled = from_union([from_bool, from_none], obj.get("chat_enabled")) + cli_remote_control_enabled = from_union([from_bool, from_none], obj.get("cli_remote_control_enabled")) + cloud_session_storage_enabled = from_union([from_bool, from_none], obj.get("cloud_session_storage_enabled")) + codex_agent_enabled = from_union([from_bool, from_none], obj.get("codex_agent_enabled")) + copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) + copilotignore_enabled = from_union([from_bool, from_none], obj.get("copilotignore_enabled")) + endpoints = from_union([CopilotUserResponseEndpoints.from_dict, from_none], obj.get("endpoints")) + is_mcp_enabled = obj.get("is_mcp_enabled") + is_staff = from_union([from_bool, from_none], obj.get("is_staff")) + limited_user_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("limited_user_quotas")) + limited_user_reset_date = from_union([from_str, from_none], obj.get("limited_user_reset_date")) + login = from_union([from_str, from_none], obj.get("login")) + monthly_quotas = from_union([lambda x: from_dict(from_float, x), from_none], obj.get("monthly_quotas")) + organization_list = obj.get("organization_list") + organization_login_list = from_union([lambda x: from_list(from_str, x), from_none], obj.get("organization_login_list")) + quota_reset_date = from_union([from_str, from_none], obj.get("quota_reset_date")) + quota_reset_date_utc = from_union([from_str, from_none], obj.get("quota_reset_date_utc")) + quota_snapshots = from_union([lambda x: from_dict(lambda x: from_union([CopilotUserResponseQuotaSnapshots.from_dict, from_none], x), x), from_none], obj.get("quota_snapshots")) + restricted_telemetry = from_union([from_bool, from_none], obj.get("restricted_telemetry")) + te = from_union([from_bool, from_none], obj.get("te")) + token_based_billing = from_union([from_bool, from_none], obj.get("token_based_billing")) + return CopilotUserResponse(access_type_sku, analytics_tracking_id, assigned_date, can_signup_for_limited, can_upgrade_plan, chat_enabled, cli_remote_control_enabled, cloud_session_storage_enabled, codex_agent_enabled, copilot_plan, copilotignore_enabled, endpoints, is_mcp_enabled, is_staff, limited_user_quotas, limited_user_reset_date, login, monthly_quotas, organization_list, organization_login_list, quota_reset_date, quota_reset_date_utc, quota_snapshots, restricted_telemetry, te, token_based_billing) + + def to_dict(self) -> dict: + result: dict = {} + if self.access_type_sku is not None: + result["access_type_sku"] = from_union([from_str, from_none], self.access_type_sku) + if self.analytics_tracking_id is not None: + result["analytics_tracking_id"] = from_union([from_str, from_none], self.analytics_tracking_id) + if self.assigned_date is not None: + result["assigned_date"] = self.assigned_date + if self.can_signup_for_limited is not None: + result["can_signup_for_limited"] = from_union([from_bool, from_none], self.can_signup_for_limited) + if self.can_upgrade_plan is not None: + result["can_upgrade_plan"] = from_union([from_bool, from_none], self.can_upgrade_plan) + if self.chat_enabled is not None: + result["chat_enabled"] = from_union([from_bool, from_none], self.chat_enabled) + if self.cli_remote_control_enabled is not None: + result["cli_remote_control_enabled"] = from_union([from_bool, from_none], self.cli_remote_control_enabled) + if self.cloud_session_storage_enabled is not None: + result["cloud_session_storage_enabled"] = from_union([from_bool, from_none], self.cloud_session_storage_enabled) + if self.codex_agent_enabled is not None: + result["codex_agent_enabled"] = from_union([from_bool, from_none], self.codex_agent_enabled) + if self.copilot_plan is not None: + result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) + if self.copilotignore_enabled is not None: + result["copilotignore_enabled"] = from_union([from_bool, from_none], self.copilotignore_enabled) + if self.endpoints is not None: + result["endpoints"] = from_union([lambda x: to_class(CopilotUserResponseEndpoints, x), from_none], self.endpoints) + if self.is_mcp_enabled is not None: + result["is_mcp_enabled"] = self.is_mcp_enabled + if self.is_staff is not None: + result["is_staff"] = from_union([from_bool, from_none], self.is_staff) + if self.limited_user_quotas is not None: + result["limited_user_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.limited_user_quotas) + if self.limited_user_reset_date is not None: + result["limited_user_reset_date"] = from_union([from_str, from_none], self.limited_user_reset_date) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + if self.monthly_quotas is not None: + result["monthly_quotas"] = from_union([lambda x: from_dict(to_float, x), from_none], self.monthly_quotas) + if self.organization_list is not None: + result["organization_list"] = self.organization_list + if self.organization_login_list is not None: + result["organization_login_list"] = from_union([lambda x: from_list(from_str, x), from_none], self.organization_login_list) + if self.quota_reset_date is not None: + result["quota_reset_date"] = from_union([from_str, from_none], self.quota_reset_date) + if self.quota_reset_date_utc is not None: + result["quota_reset_date_utc"] = from_union([from_str, from_none], self.quota_reset_date_utc) + if self.quota_snapshots is not None: + result["quota_snapshots"] = from_union([lambda x: from_dict(lambda x: from_union([lambda x: to_class(CopilotUserResponseQuotaSnapshots, x), from_none], x), x), from_none], self.quota_snapshots) + if self.restricted_telemetry is not None: + result["restricted_telemetry"] = from_union([from_bool, from_none], self.restricted_telemetry) + if self.te is not None: + result["te"] = from_union([from_bool, from_none], self.te) + if self.token_based_billing is not None: + result["token_based_billing"] = from_union([from_bool, from_none], self.token_based_billing) + return result - manage_schedule_enabled: bool | None = None - """Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the - per-session schedule registry; this flag only controls tool exposure (typically gated to - staff users). - """ - max_inline_binary_bytes: int | None = None - """Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) - persisted inline in session events and re-presented to the model on later turns / resume. - Larger results are persisted as a metadata-only marker and shown to the model as a short - text note. Defaults to 10 MB. +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AgentRegistryLiveTargetEntry: + """Full registry entry for the spawned child. Lets the controller call + `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a + TOCTOU window). """ - model: str | None = None - """The model ID to use for assistant turns.""" + copilot_version: str + """Copilot CLI version that wrote the entry""" - model_capabilities_overrides: ModelCapabilitiesOverride | None = None - """Per-property model capability overrides for the selected model.""" + host: str + """Bind host for the entry's JSON-RPC server""" - organization_custom_instructions: str | None = None - """Organization-level custom instructions to inject into the system prompt.""" + kind: AgentRegistryLiveTargetEntryKind + """Process kind tag for the registry entry""" - provider: ProviderConfig | None = None - """Custom model-provider configuration (BYOK).""" + last_seen_ms: int + """Wall-clock milliseconds since the watcher last observed this entry (heartbeat freshness)""" - reasoning_effort: str | None = None - """Reasoning effort for the selected model (model-defined enum).""" + pid: int + """Operating-system pid of the process owning this entry""" - reasoning_summary: ReasoningSummary | None = None - """Reasoning summary mode for supported model clients.""" + port: int + """TCP port the entry's JSON-RPC server is listening on""" - running_in_interactive_mode: bool | None = None - """Whether the session is running in an interactive UI.""" + schema_version: int + """Registry entry schema version (1 = ui-server, 2 = managed-server)""" - sandbox_config: SandboxConfig | None = None - """Resolved sandbox configuration.""" + started_at: str + """ISO 8601 timestamp captured at registration""" - session_capabilities: list[SessionCapability] | None = None - """Replaces the session's capability set with the given list. Use to enable or disable - capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the - field to leave the existing capability set unchanged. + attention_kind: AgentRegistryLiveTargetEntryAttentionKind | None = None + """Kind of attention required when status === "attention". Meaningful only when status === + "attention". """ - shell_init_profile: str | None = None - """Shell init profile (`None` or `NonInteractive`).""" + branch: str | None = None + """Git branch of the session (when known)""" - shell_process_flags: list[str] | None = None - """Per-shell process flags (e.g., `pwsh` arguments).""" + cwd: str | None = None + """Working directory of the session (when known)""" - skill_directories: list[str] | None = None - """Additional directories to search for skills.""" + last_terminal_event: AgentRegistryLiveTargetEntryLastTerminalEvent | None = None + """How the most recent turn ended (clean vs aborted). Lets the renderer distinguish done + from done_cancelled. + """ + model: str | None = None + """Model identifier currently selected for the session""" - skip_custom_instructions: bool | None = None - """Whether to skip loading custom instruction sources.""" + session_id: str | None = None + """Session ID of the foreground session for this entry""" - skip_embedding_retrieval: bool | None = None - """Whether to skip embedding retrieval pipeline initialization and execution.""" + session_name: str | None = None + """Friendly session name (when set)""" - suppress_custom_agent_prompt: bool | None = None - """When true, the selected custom agent's prompt is not injected into the user message - (skill context is still injected). Used by automation triggers where the agent prompt is - already in the problem statement. - """ - tool_filter_precedence: OptionsUpdateToolFilterPrecedence | None = None - """Controls how availableTools (allowlist) and excludedTools (denylist) combine when both - are set. - """ - trajectory_file: str | None = None - """Optional path for trajectory output.""" + status: AgentRegistryLiveTargetEntryStatus | None = None + """Coarse lifecycle status of the foreground session""" - working_directory: str | None = None - """Absolute working-directory path for shell tools.""" + status_revision: int | None = None + """Monotonic per-publisher revision counter incremented on every status update. Lets + watchers detect transient flips. + """ + # Internal: this field is an internal SDK API and is not part of the public surface. + token: str | None = None + """Connection token (null when the target is unauthenticated)""" @staticmethod - def from_dict(obj: Any) -> 'SessionUpdateOptionsParams': + def from_dict(obj: Any) -> 'AgentRegistryLiveTargetEntry': assert isinstance(obj, dict) - additional_content_exclusion_policies = from_union([lambda x: from_list(OptionsUpdateAdditionalContentExclusionPolicy.from_dict, x), from_none], obj.get("additionalContentExclusionPolicies")) - agent_context = from_union([from_str, from_none], obj.get("agentContext")) - ask_user_disabled = from_union([from_bool, from_none], obj.get("askUserDisabled")) - available_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("availableTools")) - capi = from_union([CapiSessionOptions.from_dict, from_none], obj.get("capi")) - client_name = from_union([from_str, from_none], obj.get("clientName")) - coauthor_enabled = from_union([from_bool, from_none], obj.get("coauthorEnabled")) - context_tier = from_union([OptionsUpdateContextTier, from_none], obj.get("contextTier")) - continue_on_auto_mode = from_union([from_bool, from_none], obj.get("continueOnAutoMode")) - copilot_url = from_union([from_str, from_none], obj.get("copilotUrl")) - custom_agents_local_only = from_union([from_bool, from_none], obj.get("customAgentsLocalOnly")) - disabled_instruction_sources = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledInstructionSources")) - disabled_skills = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledSkills")) - enable_file_hooks = from_union([from_bool, from_none], obj.get("enableFileHooks")) - enable_host_git_operations = from_union([from_bool, from_none], obj.get("enableHostGitOperations")) - enable_on_demand_instruction_discovery = from_union([from_bool, from_none], obj.get("enableOnDemandInstructionDiscovery")) - enable_reasoning_summaries = from_union([from_bool, from_none], obj.get("enableReasoningSummaries")) - enable_script_safety = from_union([from_bool, from_none], obj.get("enableScriptSafety")) - enable_session_store = from_union([from_bool, from_none], obj.get("enableSessionStore")) - enable_skills = from_union([from_bool, from_none], obj.get("enableSkills")) - enable_streaming = from_union([from_bool, from_none], obj.get("enableStreaming")) - env_value_mode = from_union([MCPSetEnvValueModeDetails, from_none], obj.get("envValueMode")) - events_log_directory = from_union([from_str, from_none], obj.get("eventsLogDirectory")) - excluded_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedTools")) - feature_flags = from_union([lambda x: from_dict(from_bool, x), from_none], obj.get("featureFlags")) - installed_plugins = from_union([lambda x: from_list(SessionInstalledPlugin.from_dict, x), from_none], obj.get("installedPlugins")) - integration_id = from_union([from_str, from_none], obj.get("integrationId")) - is_experimental_mode = from_union([from_bool, from_none], obj.get("isExperimentalMode")) - log_interactive_shells = from_union([from_bool, from_none], obj.get("logInteractiveShells")) - lsp_client_name = from_union([from_str, from_none], obj.get("lspClientName")) - manage_schedule_enabled = from_union([from_bool, from_none], obj.get("manageScheduleEnabled")) - max_inline_binary_bytes = from_union([from_int, from_none], obj.get("maxInlineBinaryBytes")) + copilot_version = from_str(obj.get("copilotVersion")) + host = from_str(obj.get("host")) + kind = AgentRegistryLiveTargetEntryKind(obj.get("kind")) + last_seen_ms = from_int(obj.get("lastSeenMs")) + pid = from_int(obj.get("pid")) + port = from_int(obj.get("port")) + schema_version = from_int(obj.get("schemaVersion")) + started_at = from_str(obj.get("startedAt")) + attention_kind = from_union([AgentRegistryLiveTargetEntryAttentionKind, from_none], obj.get("attentionKind")) + branch = from_union([from_str, from_none], obj.get("branch")) + cwd = from_union([from_str, from_none], obj.get("cwd")) + last_terminal_event = from_union([AgentRegistryLiveTargetEntryLastTerminalEvent, from_none], obj.get("lastTerminalEvent")) model = from_union([from_str, from_none], obj.get("model")) - model_capabilities_overrides = from_union([ModelCapabilitiesOverride.from_dict, from_none], obj.get("modelCapabilitiesOverrides")) - organization_custom_instructions = from_union([from_str, from_none], obj.get("organizationCustomInstructions")) - provider = from_union([ProviderConfig.from_dict, from_none], obj.get("provider")) - reasoning_effort = from_union([from_str, from_none], obj.get("reasoningEffort")) - reasoning_summary = from_union([ReasoningSummary, from_none], obj.get("reasoningSummary")) - running_in_interactive_mode = from_union([from_bool, from_none], obj.get("runningInInteractiveMode")) - sandbox_config = from_union([SandboxConfig.from_dict, from_none], obj.get("sandboxConfig")) - session_capabilities = from_union([lambda x: from_list(SessionCapability, x), from_none], obj.get("sessionCapabilities")) - shell_init_profile = from_union([from_str, from_none], obj.get("shellInitProfile")) - shell_process_flags = from_union([lambda x: from_list(from_str, x), from_none], obj.get("shellProcessFlags")) - skill_directories = from_union([lambda x: from_list(from_str, x), from_none], obj.get("skillDirectories")) - skip_custom_instructions = from_union([from_bool, from_none], obj.get("skipCustomInstructions")) - skip_embedding_retrieval = from_union([from_bool, from_none], obj.get("skipEmbeddingRetrieval")) - suppress_custom_agent_prompt = from_union([from_bool, from_none], obj.get("suppressCustomAgentPrompt")) - tool_filter_precedence = from_union([OptionsUpdateToolFilterPrecedence, from_none], obj.get("toolFilterPrecedence")) - trajectory_file = from_union([from_str, from_none], obj.get("trajectoryFile")) - working_directory = from_union([from_str, from_none], obj.get("workingDirectory")) - return SessionUpdateOptionsParams(additional_content_exclusion_policies, agent_context, ask_user_disabled, available_tools, capi, client_name, coauthor_enabled, context_tier, continue_on_auto_mode, copilot_url, custom_agents_local_only, disabled_instruction_sources, disabled_skills, enable_file_hooks, enable_host_git_operations, enable_on_demand_instruction_discovery, enable_reasoning_summaries, enable_script_safety, enable_session_store, enable_skills, enable_streaming, env_value_mode, events_log_directory, excluded_tools, feature_flags, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, manage_schedule_enabled, max_inline_binary_bytes, model, model_capabilities_overrides, organization_custom_instructions, provider, reasoning_effort, reasoning_summary, running_in_interactive_mode, sandbox_config, session_capabilities, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, skip_embedding_retrieval, suppress_custom_agent_prompt, tool_filter_precedence, trajectory_file, working_directory) + session_id = from_union([from_str, from_none], obj.get("sessionId")) + session_name = from_union([from_str, from_none], obj.get("sessionName")) + status = from_union([AgentRegistryLiveTargetEntryStatus, from_none], obj.get("status")) + status_revision = from_union([from_int, from_none], obj.get("statusRevision")) + token = from_union([from_none, from_str], obj.get("token")) + return AgentRegistryLiveTargetEntry(copilot_version, host, kind, last_seen_ms, pid, port, schema_version, started_at, attention_kind, branch, cwd, last_terminal_event, model, session_id, session_name, status, status_revision, token) def to_dict(self) -> dict: result: dict = {} - if self.additional_content_exclusion_policies is not None: - result["additionalContentExclusionPolicies"] = from_union([lambda x: from_list(lambda x: to_class(OptionsUpdateAdditionalContentExclusionPolicy, x), x), from_none], self.additional_content_exclusion_policies) - if self.agent_context is not None: - result["agentContext"] = from_union([from_str, from_none], self.agent_context) - if self.ask_user_disabled is not None: - result["askUserDisabled"] = from_union([from_bool, from_none], self.ask_user_disabled) - if self.available_tools is not None: - result["availableTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.available_tools) - if self.capi is not None: - result["capi"] = from_union([lambda x: to_class(CapiSessionOptions, x), from_none], self.capi) - if self.client_name is not None: - result["clientName"] = from_union([from_str, from_none], self.client_name) - if self.coauthor_enabled is not None: - result["coauthorEnabled"] = from_union([from_bool, from_none], self.coauthor_enabled) - if self.context_tier is not None: - result["contextTier"] = from_union([lambda x: to_enum(OptionsUpdateContextTier, x), from_none], self.context_tier) - if self.continue_on_auto_mode is not None: - result["continueOnAutoMode"] = from_union([from_bool, from_none], self.continue_on_auto_mode) - if self.copilot_url is not None: - result["copilotUrl"] = from_union([from_str, from_none], self.copilot_url) - if self.custom_agents_local_only is not None: - result["customAgentsLocalOnly"] = from_union([from_bool, from_none], self.custom_agents_local_only) - if self.disabled_instruction_sources is not None: - result["disabledInstructionSources"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_instruction_sources) - if self.disabled_skills is not None: - result["disabledSkills"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_skills) - if self.enable_file_hooks is not None: - result["enableFileHooks"] = from_union([from_bool, from_none], self.enable_file_hooks) - if self.enable_host_git_operations is not None: - result["enableHostGitOperations"] = from_union([from_bool, from_none], self.enable_host_git_operations) - if self.enable_on_demand_instruction_discovery is not None: - result["enableOnDemandInstructionDiscovery"] = from_union([from_bool, from_none], self.enable_on_demand_instruction_discovery) - if self.enable_reasoning_summaries is not None: - result["enableReasoningSummaries"] = from_union([from_bool, from_none], self.enable_reasoning_summaries) - if self.enable_script_safety is not None: - result["enableScriptSafety"] = from_union([from_bool, from_none], self.enable_script_safety) - if self.enable_session_store is not None: - result["enableSessionStore"] = from_union([from_bool, from_none], self.enable_session_store) - if self.enable_skills is not None: - result["enableSkills"] = from_union([from_bool, from_none], self.enable_skills) - if self.enable_streaming is not None: - result["enableStreaming"] = from_union([from_bool, from_none], self.enable_streaming) - if self.env_value_mode is not None: - result["envValueMode"] = from_union([lambda x: to_enum(MCPSetEnvValueModeDetails, x), from_none], self.env_value_mode) - if self.events_log_directory is not None: - result["eventsLogDirectory"] = from_union([from_str, from_none], self.events_log_directory) - if self.excluded_tools is not None: - result["excludedTools"] = from_union([lambda x: from_list(from_str, x), from_none], self.excluded_tools) - if self.feature_flags is not None: - result["featureFlags"] = from_union([lambda x: from_dict(from_bool, x), from_none], self.feature_flags) - if self.installed_plugins is not None: - result["installedPlugins"] = from_union([lambda x: from_list(lambda x: to_class(SessionInstalledPlugin, x), x), from_none], self.installed_plugins) - if self.integration_id is not None: - result["integrationId"] = from_union([from_str, from_none], self.integration_id) - if self.is_experimental_mode is not None: - result["isExperimentalMode"] = from_union([from_bool, from_none], self.is_experimental_mode) - if self.log_interactive_shells is not None: - result["logInteractiveShells"] = from_union([from_bool, from_none], self.log_interactive_shells) - if self.lsp_client_name is not None: - result["lspClientName"] = from_union([from_str, from_none], self.lsp_client_name) - if self.manage_schedule_enabled is not None: - result["manageScheduleEnabled"] = from_union([from_bool, from_none], self.manage_schedule_enabled) - if self.max_inline_binary_bytes is not None: - result["maxInlineBinaryBytes"] = from_union([from_int, from_none], self.max_inline_binary_bytes) + result["copilotVersion"] = from_str(self.copilot_version) + result["host"] = from_str(self.host) + result["kind"] = to_enum(AgentRegistryLiveTargetEntryKind, self.kind) + result["lastSeenMs"] = from_int(self.last_seen_ms) + result["pid"] = from_int(self.pid) + result["port"] = from_int(self.port) + result["schemaVersion"] = from_int(self.schema_version) + result["startedAt"] = from_str(self.started_at) + if self.attention_kind is not None: + result["attentionKind"] = from_union([lambda x: to_enum(AgentRegistryLiveTargetEntryAttentionKind, x), from_none], self.attention_kind) + if self.branch is not None: + result["branch"] = from_union([from_str, from_none], self.branch) + if self.cwd is not None: + result["cwd"] = from_union([from_str, from_none], self.cwd) + if self.last_terminal_event is not None: + result["lastTerminalEvent"] = from_union([lambda x: to_enum(AgentRegistryLiveTargetEntryLastTerminalEvent, x), from_none], self.last_terminal_event) if self.model is not None: result["model"] = from_union([from_str, from_none], self.model) - if self.model_capabilities_overrides is not None: - result["modelCapabilitiesOverrides"] = from_union([lambda x: to_class(ModelCapabilitiesOverride, x), from_none], self.model_capabilities_overrides) - if self.organization_custom_instructions is not None: - result["organizationCustomInstructions"] = from_union([from_str, from_none], self.organization_custom_instructions) - if self.provider is not None: - result["provider"] = from_union([lambda x: to_class(ProviderConfig, x), from_none], self.provider) - if self.reasoning_effort is not None: - result["reasoningEffort"] = from_union([from_str, from_none], self.reasoning_effort) - if self.reasoning_summary is not None: - result["reasoningSummary"] = from_union([lambda x: to_enum(ReasoningSummary, x), from_none], self.reasoning_summary) - if self.running_in_interactive_mode is not None: - result["runningInInteractiveMode"] = from_union([from_bool, from_none], self.running_in_interactive_mode) - if self.sandbox_config is not None: - result["sandboxConfig"] = from_union([lambda x: to_class(SandboxConfig, x), from_none], self.sandbox_config) - if self.session_capabilities is not None: - result["sessionCapabilities"] = from_union([lambda x: from_list(lambda x: to_enum(SessionCapability, x), x), from_none], self.session_capabilities) - if self.shell_init_profile is not None: - result["shellInitProfile"] = from_union([from_str, from_none], self.shell_init_profile) - if self.shell_process_flags is not None: - result["shellProcessFlags"] = from_union([lambda x: from_list(from_str, x), from_none], self.shell_process_flags) - if self.skill_directories is not None: - result["skillDirectories"] = from_union([lambda x: from_list(from_str, x), from_none], self.skill_directories) - if self.skip_custom_instructions is not None: - result["skipCustomInstructions"] = from_union([from_bool, from_none], self.skip_custom_instructions) - if self.skip_embedding_retrieval is not None: - result["skipEmbeddingRetrieval"] = from_union([from_bool, from_none], self.skip_embedding_retrieval) - if self.suppress_custom_agent_prompt is not None: - result["suppressCustomAgentPrompt"] = from_union([from_bool, from_none], self.suppress_custom_agent_prompt) - if self.tool_filter_precedence is not None: - result["toolFilterPrecedence"] = from_union([lambda x: to_enum(OptionsUpdateToolFilterPrecedence, x), from_none], self.tool_filter_precedence) - if self.trajectory_file is not None: - result["trajectoryFile"] = from_union([from_str, from_none], self.trajectory_file) - if self.working_directory is not None: - result["workingDirectory"] = from_union([from_str, from_none], self.working_directory) + if self.session_id is not None: + result["sessionId"] = from_union([from_str, from_none], self.session_id) + if self.session_name is not None: + result["sessionName"] = from_union([from_str, from_none], self.session_name) + if self.status is not None: + result["status"] = from_union([lambda x: to_enum(AgentRegistryLiveTargetEntryStatus, x), from_none], self.status) + if self.status_revision is not None: + result["statusRevision"] = from_union([from_int, from_none], self.status_revision) + if self.token is not None: + result["token"] = from_union([from_none, from_str], self.token) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class UIElicitationRequest: - """Prompt message and JSON schema describing the form fields to elicit from the user.""" +class AgentRegistrySpawnRequest: + """Inputs to spawn a managed-server child via the controller's spawn delegate.""" - message: str - """Message describing what information is needed from the user""" + cwd: str + """Working directory for the spawned child (must be an existing directory)""" - requested_schema: UIElicitationSchema - """JSON Schema describing the form fields to present to the user""" + agent_name: str | None = None + """Custom or built-in agent name (e.g. 'explore'). When omitted, the child uses its own + default. + """ + initial_prompt: str | None = None + """Optional first user message. Forwarded to the caller (the CLI's spawn wrapper sends it + post-attach via the standard LocalRpcSession.send path). + """ + model: str | None = None + """Model identifier to apply to the new session""" + + name: str | None = None + """Friendly session name. Must satisfy validateSessionName: non-empty, no leading/trailing + whitespace, <=100 chars, no control chars, no double quotes. + """ + permission_mode: AgentRegistrySpawnPermissionMode | None = None + """Permission posture for the new session. 'yolo' requires the controller-local session to + currently be in allow-all mode. + """ @staticmethod - def from_dict(obj: Any) -> 'UIElicitationRequest': + def from_dict(obj: Any) -> 'AgentRegistrySpawnRequest': assert isinstance(obj, dict) - message = from_str(obj.get("message")) - requested_schema = UIElicitationSchema.from_dict(obj.get("requestedSchema")) - return UIElicitationRequest(message, requested_schema) + cwd = from_str(obj.get("cwd")) + agent_name = from_union([from_str, from_none], obj.get("agentName")) + initial_prompt = from_union([from_str, from_none], obj.get("initialPrompt")) + model = from_union([from_str, from_none], obj.get("model")) + name = from_union([from_str, from_none], obj.get("name")) + permission_mode = from_union([AgentRegistrySpawnPermissionMode, from_none], obj.get("permissionMode")) + return AgentRegistrySpawnRequest(cwd, agent_name, initial_prompt, model, name, permission_mode) def to_dict(self) -> dict: result: dict = {} - result["message"] = from_str(self.message) - result["requestedSchema"] = to_class(UIElicitationSchema, self.requested_schema) + result["cwd"] = from_str(self.cwd) + if self.agent_name is not None: + result["agentName"] = from_union([from_str, from_none], self.agent_name) + if self.initial_prompt is not None: + result["initialPrompt"] = from_union([from_str, from_none], self.initial_prompt) + if self.model is not None: + result["model"] = from_union([from_str, from_none], self.model) + if self.name is not None: + result["name"] = from_union([from_str, from_none], self.name) + if self.permission_mode is not None: + result["permissionMode"] = from_union([lambda x: to_enum(AgentRegistrySpawnPermissionMode, x), from_none], self.permission_mode) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionsOpenCreate: - """Parameters for creating a new local session.""" - - kind: ClassVar[str] = "create" - """Create a new local session.""" +class AgentRegistrySpawnSpawned: + """Managed-server child was spawned and registered successfully.""" - emit_start: bool | None = None - """Whether to emit session.start during creation. Defaults to true.""" + entry: AgentRegistryLiveTargetEntry + """Full registry entry for the spawned child. Lets the controller call + `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a + TOCTOU window). + """ + kind: ClassVar[str] = "spawned" + """Discriminator: managed-server child spawned successfully""" - options: SessionOpenOptions | None = None - """Session construction options.""" + initial_prompt_error: str | None = None + """If the delegate attempted to send the initial prompt and failed, the categorized error + message. + """ + initial_prompt_sent: bool | None = None + """Whether the delegate already sent the initial prompt. Always omitted in the current + wiring: the controller sends the prompt post-attach via the standard LocalRpcSession.send + path. + """ + log_capture: AgentRegistryLogCapture | None = None + """Per-spawn log-capture outcome; populated from spawnLiveTarget.""" @staticmethod - def from_dict(obj: Any) -> 'SessionsOpenCreate': + def from_dict(obj: Any) -> 'AgentRegistrySpawnSpawned': assert isinstance(obj, dict) - emit_start = from_union([from_bool, from_none], obj.get("emitStart")) - options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) - return SessionsOpenCreate(emit_start, options) + entry = AgentRegistryLiveTargetEntry.from_dict(obj.get("entry")) + initial_prompt_error = from_union([from_str, from_none], obj.get("initialPromptError")) + initial_prompt_sent = from_union([from_bool, from_none], obj.get("initialPromptSent")) + log_capture = from_union([AgentRegistryLogCapture.from_dict, from_none], obj.get("logCapture")) + return AgentRegistrySpawnSpawned(entry, initial_prompt_error, initial_prompt_sent, log_capture) def to_dict(self) -> dict: result: dict = {} + result["entry"] = to_class(AgentRegistryLiveTargetEntry, self.entry) result["kind"] = self.kind - if self.emit_start is not None: - result["emitStart"] = from_union([from_bool, from_none], self.emit_start) - if self.options is not None: - result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) + if self.initial_prompt_error is not None: + result["initialPromptError"] = from_union([from_str, from_none], self.initial_prompt_error) + if self.initial_prompt_sent is not None: + result["initialPromptSent"] = from_union([from_bool, from_none], self.initial_prompt_sent) + if self.log_capture is not None: + result["logCapture"] = from_union([lambda x: to_class(AgentRegistryLogCapture, x), from_none], self.log_capture) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionsOpenRemote: - """Parameters for connecting to a live remote session.""" - - kind: ClassVar[str] = "remote" - """Connect to a live remote session.""" +class APIKeyAuthInfo: + """Authentication-info variant for API-key authentication to a non-GitHub LLM provider, + carrying the secret `apiKey` and host. + """ + api_key: str + """The API key. Treat as a secret.""" - remote_session_id: str - """Remote session identifier to connect to.""" + host: str + """Authentication host.""" - options: SessionOpenOptions | None = None - """Session options for the connection.""" + type: ClassVar[str] = "api-key" + """API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style).""" - repository: RemoteSessionRepository | None = None - """Repository context for the remote session.""" + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ @staticmethod - def from_dict(obj: Any) -> 'SessionsOpenRemote': + def from_dict(obj: Any) -> 'APIKeyAuthInfo': assert isinstance(obj, dict) - remote_session_id = from_str(obj.get("remoteSessionId")) - options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) - repository = from_union([RemoteSessionRepository.from_dict, from_none], obj.get("repository")) - return SessionsOpenRemote(remote_session_id, options, repository) + api_key = from_str(obj.get("apiKey")) + host = from_str(obj.get("host")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return APIKeyAuthInfo(api_key, host, copilot_user) def to_dict(self) -> dict: result: dict = {} - result["kind"] = self.kind - result["remoteSessionId"] = from_str(self.remote_session_id) - if self.options is not None: - result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) - if self.repository is not None: - result["repository"] = from_union([lambda x: to_class(RemoteSessionRepository, x), from_none], self.repository) + result["apiKey"] = from_str(self.api_key) + result["host"] = from_str(self.host) + result["type"] = self.type + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SessionsOpenResume: - """Parameters for resuming a specific local session.""" - - kind: ClassVar[str] = "resume" - """Resume a specific local session by ID or prefix.""" - - session_id: str - """Session ID or unique prefix to resume.""" - - options: SessionOpenOptions | None = None - """Session resume options.""" - - resume: bool | None = None - """Whether to emit session.resume after loading. Defaults to true.""" +class CopilotAPITokenAuthInfo: + """Authentication-info variant for direct Copilot API token auth sourced from environment + variables, with public GitHub host. + """ + host: Host + """Authentication host (always the public GitHub host).""" - suppress_resume_workspace_metadata_writeback: bool | None = None - """Suppress workspace.yaml metadata writeback when resuming from an incidental cwd.""" + type: ClassVar[str] = "copilot-api-token" + """Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` + environment-variable pair. The token itself is read from the environment by the runtime, + not carried in this struct. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ @staticmethod - def from_dict(obj: Any) -> 'SessionsOpenResume': + def from_dict(obj: Any) -> 'CopilotAPITokenAuthInfo': assert isinstance(obj, dict) - session_id = from_str(obj.get("sessionId")) - options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) - resume = from_union([from_bool, from_none], obj.get("resume")) - suppress_resume_workspace_metadata_writeback = from_union([from_bool, from_none], obj.get("suppressResumeWorkspaceMetadataWriteback")) - return SessionsOpenResume(session_id, options, resume, suppress_resume_workspace_metadata_writeback) + host = Host(obj.get("host")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return CopilotAPITokenAuthInfo(host, copilot_user) def to_dict(self) -> dict: result: dict = {} - result["kind"] = self.kind - result["sessionId"] = from_str(self.session_id) - if self.options is not None: - result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) - if self.resume is not None: - result["resume"] = from_union([from_bool, from_none], self.resume) - if self.suppress_resume_workspace_metadata_writeback is not None: - result["suppressResumeWorkspaceMetadataWriteback"] = from_union([from_bool, from_none], self.suppress_resume_workspace_metadata_writeback) + result["host"] = to_enum(Host, self.host) + result["type"] = self.type + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionsOpenResumeLast: - """Parameters for resuming the most relevant local session.""" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CurrentToolMetadata: + """Lightweight metadata for a currently initialized session tool""" + + description: str + """Tool description""" + + name: str + """Model-facing tool name""" - kind: ClassVar[str] = "resumeLast" - """Resume the most relevant existing local session.""" + defer_loading: bool | None = None + """Whether the tool is loaded on demand via tool search""" - context: SessionContext | None = None - """Working-directory context used to choose the most relevant session.""" + input_schema: dict[str, Any] | None = None + """JSON Schema for tool input""" - options: SessionOpenOptions | None = None - """Session resume options.""" + mcp_server_name: str | None = None + """MCP server name for MCP-backed tools""" - suppress_resume_workspace_metadata_writeback: bool | None = None - """Suppress workspace.yaml metadata writeback when resuming from an incidental cwd.""" + mcp_tool_name: str | None = None + """Raw MCP tool name for MCP-backed tools""" + + namespaced_name: str | None = None + """Optional MCP/config namespaced tool name""" @staticmethod - def from_dict(obj: Any) -> 'SessionsOpenResumeLast': + def from_dict(obj: Any) -> 'CurrentToolMetadata': assert isinstance(obj, dict) - context = from_union([SessionContext.from_dict, from_none], obj.get("context")) - options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) - suppress_resume_workspace_metadata_writeback = from_union([from_bool, from_none], obj.get("suppressResumeWorkspaceMetadataWriteback")) - return SessionsOpenResumeLast(context, options, suppress_resume_workspace_metadata_writeback) + description = from_str(obj.get("description")) + name = from_str(obj.get("name")) + defer_loading = from_union([from_bool, from_none], obj.get("deferLoading")) + input_schema = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("input_schema")) + mcp_server_name = from_union([from_str, from_none], obj.get("mcpServerName")) + mcp_tool_name = from_union([from_str, from_none], obj.get("mcpToolName")) + namespaced_name = from_union([from_str, from_none], obj.get("namespacedName")) + return CurrentToolMetadata(description, name, defer_loading, input_schema, mcp_server_name, mcp_tool_name, namespaced_name) def to_dict(self) -> dict: result: dict = {} - result["kind"] = self.kind - if self.context is not None: - result["context"] = from_union([lambda x: to_class(SessionContext, x), from_none], self.context) - if self.options is not None: - result["options"] = from_union([lambda x: to_class(SessionOpenOptions, x), from_none], self.options) - if self.suppress_resume_workspace_metadata_writeback is not None: - result["suppressResumeWorkspaceMetadataWriteback"] = from_union([from_bool, from_none], self.suppress_resume_workspace_metadata_writeback) + result["description"] = from_str(self.description) + result["name"] = from_str(self.name) + if self.defer_loading is not None: + result["deferLoading"] = from_union([from_bool, from_none], self.defer_loading) + if self.input_schema is not None: + result["input_schema"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.input_schema) + if self.mcp_server_name is not None: + result["mcpServerName"] = from_union([from_str, from_none], self.mcp_server_name) + if self.mcp_tool_name is not None: + result["mcpToolName"] = from_union([from_str, from_none], self.mcp_tool_name) + if self.namespaced_name is not None: + result["namespacedName"] = from_union([from_str, from_none], self.namespaced_name) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class AgentRegistryLiveTargetEntry: - """Full registry entry for the spawned child. Lets the controller call - `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a - TOCTOU window). +class EnvAuthInfo: + """Authentication-info variant for a token sourced from an environment variable, with host, + optional login, token, and env var name. """ - copilot_version: str - """Copilot CLI version that wrote the entry""" + env_var: str + """Name of the environment variable the token was sourced from.""" host: str - """Bind host for the entry's JSON-RPC server""" - - kind: AgentRegistryLiveTargetEntryKind - """Process kind tag for the registry entry""" - - last_seen_ms: int - """Wall-clock milliseconds since the watcher last observed this entry (heartbeat freshness)""" - - pid: int - """Operating-system pid of the process owning this entry""" - - port: int - """TCP port the entry's JSON-RPC server is listening on""" - - schema_version: int - """Registry entry schema version (1 = ui-server, 2 = managed-server)""" + """Authentication host (e.g. https://github.com or a GHES host).""" - started_at: str - """ISO 8601 timestamp captured at registration""" + token: str + """The token value itself. Treat as a secret.""" - attention_kind: AgentRegistryLiveTargetEntryAttentionKind | None = None - """Kind of attention required when status === "attention". Meaningful only when status === - "attention". + type: ClassVar[str] = "env" + """Personal access token (PAT) or server-to-server token sourced from an environment + variable. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + login: str | None = None + """User login associated with the token. Undefined for server-to-server tokens (those + starting with `ghs_`). """ - branch: str | None = None - """Git branch of the session (when known)""" - cwd: str | None = None - """Working directory of the session (when known)""" + @staticmethod + def from_dict(obj: Any) -> 'EnvAuthInfo': + assert isinstance(obj, dict) + env_var = from_str(obj.get("envVar")) + host = from_str(obj.get("host")) + token = from_str(obj.get("token")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + login = from_union([from_str, from_none], obj.get("login")) + return EnvAuthInfo(env_var, host, token, copilot_user, login) - last_terminal_event: AgentRegistryLiveTargetEntryLastTerminalEvent | None = None - """How the most recent turn ended (clean vs aborted). Lets the renderer distinguish done - from done_cancelled. + def to_dict(self) -> dict: + result: dict = {} + result["envVar"] = from_str(self.env_var) + result["host"] = from_str(self.host) + result["token"] = from_str(self.token) + result["type"] = self.type + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class GhCLIAuthInfo: + """Authentication-info variant for GitHub CLI credentials, carrying host, login, and the `gh + auth token` value. """ - model: str | None = None - """Model identifier currently selected for the session""" + host: str + """Authentication host.""" - session_id: str | None = None - """Session ID of the foreground session for this entry""" + login: str + """User login as reported by `gh auth status`.""" - session_name: str | None = None - """Friendly session name (when set)""" + token: str + """The token returned by `gh auth token`. Treat as a secret.""" - status: AgentRegistryLiveTargetEntryStatus | None = None - """Coarse lifecycle status of the foreground session""" + type: ClassVar[str] = "gh-cli" + """Authentication via the `gh` CLI's saved credentials.""" - status_revision: int | None = None - """Monotonic per-publisher revision counter incremented on every status update. Lets - watchers detect transient flips. + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. """ - # Internal: this field is an internal SDK API and is not part of the public surface. - token: str | None = None - """Connection token (null when the target is unauthenticated)""" @staticmethod - def from_dict(obj: Any) -> 'AgentRegistryLiveTargetEntry': + def from_dict(obj: Any) -> 'GhCLIAuthInfo': assert isinstance(obj, dict) - copilot_version = from_str(obj.get("copilotVersion")) host = from_str(obj.get("host")) - kind = AgentRegistryLiveTargetEntryKind(obj.get("kind")) - last_seen_ms = from_int(obj.get("lastSeenMs")) - pid = from_int(obj.get("pid")) - port = from_int(obj.get("port")) - schema_version = from_int(obj.get("schemaVersion")) - started_at = from_str(obj.get("startedAt")) - attention_kind = from_union([AgentRegistryLiveTargetEntryAttentionKind, from_none], obj.get("attentionKind")) - branch = from_union([from_str, from_none], obj.get("branch")) - cwd = from_union([from_str, from_none], obj.get("cwd")) - last_terminal_event = from_union([AgentRegistryLiveTargetEntryLastTerminalEvent, from_none], obj.get("lastTerminalEvent")) - model = from_union([from_str, from_none], obj.get("model")) - session_id = from_union([from_str, from_none], obj.get("sessionId")) - session_name = from_union([from_str, from_none], obj.get("sessionName")) - status = from_union([AgentRegistryLiveTargetEntryStatus, from_none], obj.get("status")) - status_revision = from_union([from_int, from_none], obj.get("statusRevision")) - token = from_union([from_none, from_str], obj.get("token")) - return AgentRegistryLiveTargetEntry(copilot_version, host, kind, last_seen_ms, pid, port, schema_version, started_at, attention_kind, branch, cwd, last_terminal_event, model, session_id, session_name, status, status_revision, token) + login = from_str(obj.get("login")) + token = from_str(obj.get("token")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return GhCLIAuthInfo(host, login, token, copilot_user) def to_dict(self) -> dict: result: dict = {} - result["copilotVersion"] = from_str(self.copilot_version) result["host"] = from_str(self.host) - result["kind"] = to_enum(AgentRegistryLiveTargetEntryKind, self.kind) - result["lastSeenMs"] = from_int(self.last_seen_ms) - result["pid"] = from_int(self.pid) - result["port"] = from_int(self.port) - result["schemaVersion"] = from_int(self.schema_version) - result["startedAt"] = from_str(self.started_at) - if self.attention_kind is not None: - result["attentionKind"] = from_union([lambda x: to_enum(AgentRegistryLiveTargetEntryAttentionKind, x), from_none], self.attention_kind) - if self.branch is not None: - result["branch"] = from_union([from_str, from_none], self.branch) - if self.cwd is not None: - result["cwd"] = from_union([from_str, from_none], self.cwd) - if self.last_terminal_event is not None: - result["lastTerminalEvent"] = from_union([lambda x: to_enum(AgentRegistryLiveTargetEntryLastTerminalEvent, x), from_none], self.last_terminal_event) - if self.model is not None: - result["model"] = from_union([from_str, from_none], self.model) - if self.session_id is not None: - result["sessionId"] = from_union([from_str, from_none], self.session_id) - if self.session_name is not None: - result["sessionName"] = from_union([from_str, from_none], self.session_name) - if self.status is not None: - result["status"] = from_union([lambda x: to_enum(AgentRegistryLiveTargetEntryStatus, x), from_none], self.status) - if self.status_revision is not None: - result["statusRevision"] = from_union([from_int, from_none], self.status_revision) - if self.token is not None: - result["token"] = from_union([from_none, from_str], self.token) + result["login"] = from_str(self.login) + result["token"] = from_str(self.token) + result["type"] = self.type + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class AgentRegistrySpawnRequest: - """Inputs to spawn a managed-server child via the controller's spawn delegate.""" - - cwd: str - """Working directory for the spawned child (must be an existing directory)""" +class GitHubTelemetryEvent: + """A single telemetry event in the runtime's native GitHub-shaped telemetry format, + forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing + GitHubTelemetryNotification distinguishes standard from restricted events; the payload + shape is identical for both. - agent_name: str | None = None - """Custom or built-in agent name (e.g. 'explore'). When omitted, the child uses its own - default. + The telemetry event, in the runtime's native GitHub-shaped telemetry format. """ - initial_prompt: str | None = None - """Optional first user message. Forwarded to the caller (the CLI's spawn wrapper sends it - post-attach via the standard LocalRpcSession.send path). - """ - model: str | None = None - """Model identifier to apply to the new session""" + kind: str + """Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed).""" - name: str | None = None - """Friendly session name. Must satisfy validateSessionName: non-empty, no leading/trailing - whitespace, <=100 chars, no control chars, no double quotes. - """ - permission_mode: AgentRegistrySpawnPermissionMode | None = None - """Permission posture for the new session. 'yolo' requires the controller-local session to - currently be in allow-all mode. - """ + metrics: dict[str, float] + """Numeric metrics as a map from key to value.""" + + properties: dict[str, str] + """String-valued properties as a map from key to value.""" + + client: GitHubTelemetryClientInfo | None = None + """Client environment metadata.""" + + copilot_tracking_id: str | None = None + """Copilot tracking ID for user-level attribution.""" + + created_at: str | None = None + """Timestamp when the event was created (ISO 8601 format).""" + + exp_assignment_context: str | None = None + """Experiment assignment context.""" + + features: dict[str, str] | None = None + """Feature flags enabled for this session, as a map from flag to value.""" + + model_call_id: str | None = None + """Reference to the model call that produced this event.""" + + session_id: str | None = None + """Session identifier the event belongs to.""" @staticmethod - def from_dict(obj: Any) -> 'AgentRegistrySpawnRequest': - assert isinstance(obj, dict) - cwd = from_str(obj.get("cwd")) - agent_name = from_union([from_str, from_none], obj.get("agentName")) - initial_prompt = from_union([from_str, from_none], obj.get("initialPrompt")) - model = from_union([from_str, from_none], obj.get("model")) - name = from_union([from_str, from_none], obj.get("name")) - permission_mode = from_union([AgentRegistrySpawnPermissionMode, from_none], obj.get("permissionMode")) - return AgentRegistrySpawnRequest(cwd, agent_name, initial_prompt, model, name, permission_mode) + def from_dict(obj: Any) -> 'GitHubTelemetryEvent': + assert isinstance(obj, dict) + kind = from_str(obj.get("kind")) + metrics = from_dict(from_float, obj.get("metrics")) + properties = from_dict(from_str, obj.get("properties")) + client = from_union([GitHubTelemetryClientInfo.from_dict, from_none], obj.get("client")) + copilot_tracking_id = from_union([from_str, from_none], obj.get("copilot_tracking_id")) + created_at = from_union([from_str, from_none], obj.get("created_at")) + exp_assignment_context = from_union([from_str, from_none], obj.get("exp_assignment_context")) + features = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("features")) + model_call_id = from_union([from_str, from_none], obj.get("model_call_id")) + session_id = from_union([from_str, from_none], obj.get("session_id")) + return GitHubTelemetryEvent(kind, metrics, properties, client, copilot_tracking_id, created_at, exp_assignment_context, features, model_call_id, session_id) def to_dict(self) -> dict: result: dict = {} - result["cwd"] = from_str(self.cwd) - if self.agent_name is not None: - result["agentName"] = from_union([from_str, from_none], self.agent_name) - if self.initial_prompt is not None: - result["initialPrompt"] = from_union([from_str, from_none], self.initial_prompt) - if self.model is not None: - result["model"] = from_union([from_str, from_none], self.model) - if self.name is not None: - result["name"] = from_union([from_str, from_none], self.name) - if self.permission_mode is not None: - result["permissionMode"] = from_union([lambda x: to_enum(AgentRegistrySpawnPermissionMode, x), from_none], self.permission_mode) + result["kind"] = from_str(self.kind) + result["metrics"] = from_dict(to_float, self.metrics) + result["properties"] = from_dict(from_str, self.properties) + if self.client is not None: + result["client"] = from_union([lambda x: to_class(GitHubTelemetryClientInfo, x), from_none], self.client) + if self.copilot_tracking_id is not None: + result["copilot_tracking_id"] = from_union([from_str, from_none], self.copilot_tracking_id) + if self.created_at is not None: + result["created_at"] = from_union([from_str, from_none], self.created_at) + if self.exp_assignment_context is not None: + result["exp_assignment_context"] = from_union([from_str, from_none], self.exp_assignment_context) + if self.features is not None: + result["features"] = from_union([lambda x: from_dict(from_str, x), from_none], self.features) + if self.model_call_id is not None: + result["model_call_id"] = from_union([from_str, from_none], self.model_call_id) + if self.session_id is not None: + result["session_id"] = from_union([from_str, from_none], self.session_id) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class AgentRegistrySpawnSpawned: - """Managed-server child was spawned and registered successfully.""" - - entry: AgentRegistryLiveTargetEntry - """Full registry entry for the spawned child. Lets the controller call - `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a - TOCTOU window). +class GitHubTelemetryNotification: + """Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the + runtime forwards to a host connection that opted into telemetry forwarding during the + `server.connect` handshake. """ - kind: ClassVar[str] = "spawned" - """Discriminator: managed-server child spawned successfully""" + event: GitHubTelemetryEvent + """The telemetry event, in the runtime's native GitHub-shaped telemetry format.""" - initial_prompt_error: str | None = None - """If the delegate attempted to send the initial prompt and failed, the categorized error - message. + restricted: bool + """Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route + restricted events to first-party Microsoft stores only. """ - initial_prompt_sent: bool | None = None - """Whether the delegate already sent the initial prompt. Always omitted in the current - wiring: the controller sends the prompt post-attach via the standard LocalRpcSession.send - path. + session_id: str | None = None + """Session the telemetry event belongs to, when it is session-scoped. Omitted for + sessionless events (for example, `server.sendTelemetry` calls with no session id), which + are still forwarded to opted-in connections. """ - log_capture: AgentRegistryLogCapture | None = None - """Per-spawn log-capture outcome; populated from spawnLiveTarget.""" @staticmethod - def from_dict(obj: Any) -> 'AgentRegistrySpawnSpawned': + def from_dict(obj: Any) -> 'GitHubTelemetryNotification': assert isinstance(obj, dict) - entry = AgentRegistryLiveTargetEntry.from_dict(obj.get("entry")) - initial_prompt_error = from_union([from_str, from_none], obj.get("initialPromptError")) - initial_prompt_sent = from_union([from_bool, from_none], obj.get("initialPromptSent")) - log_capture = from_union([AgentRegistryLogCapture.from_dict, from_none], obj.get("logCapture")) - return AgentRegistrySpawnSpawned(entry, initial_prompt_error, initial_prompt_sent, log_capture) + event = GitHubTelemetryEvent.from_dict(obj.get("event")) + restricted = from_bool(obj.get("restricted")) + session_id = from_union([from_str, from_none], obj.get("sessionId")) + return GitHubTelemetryNotification(event, restricted, session_id) def to_dict(self) -> dict: result: dict = {} - result["entry"] = to_class(AgentRegistryLiveTargetEntry, self.entry) - result["kind"] = self.kind - if self.initial_prompt_error is not None: - result["initialPromptError"] = from_union([from_str, from_none], self.initial_prompt_error) - if self.initial_prompt_sent is not None: - result["initialPromptSent"] = from_union([from_bool, from_none], self.initial_prompt_sent) - if self.log_capture is not None: - result["logCapture"] = from_union([lambda x: to_class(AgentRegistryLogCapture, x), from_none], self.log_capture) + result["event"] = to_class(GitHubTelemetryEvent, self.event) + result["restricted"] = from_bool(self.restricted) + if self.session_id is not None: + result["sessionId"] = from_union([from_str, from_none], self.session_id) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class CurrentToolMetadata: - """Lightweight metadata for a currently initialized session tool""" - - description: str - """Tool description""" - - name: str - """Model-facing tool name""" - - defer_loading: bool | None = None - """Whether the tool is loaded on demand via tool search""" - - input_schema: dict[str, Any] | None = None - """JSON Schema for tool input""" +class HMACAuthInfo: + """Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub + host and HMAC secret. + """ + hmac: str + """HMAC secret used to sign requests.""" - mcp_server_name: str | None = None - """MCP server name for MCP-backed tools""" + host: Host + """Authentication host. HMAC auth always targets the public GitHub host.""" - mcp_tool_name: str | None = None - """Raw MCP tool name for MCP-backed tools""" + type: ClassVar[str] = "hmac" + """HMAC-based authentication used by GitHub-internal services.""" - namespaced_name: str | None = None - """Optional MCP/config namespaced tool name""" + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ @staticmethod - def from_dict(obj: Any) -> 'CurrentToolMetadata': + def from_dict(obj: Any) -> 'HMACAuthInfo': assert isinstance(obj, dict) - description = from_str(obj.get("description")) - name = from_str(obj.get("name")) - defer_loading = from_union([from_bool, from_none], obj.get("deferLoading")) - input_schema = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("input_schema")) - mcp_server_name = from_union([from_str, from_none], obj.get("mcpServerName")) - mcp_tool_name = from_union([from_str, from_none], obj.get("mcpToolName")) - namespaced_name = from_union([from_str, from_none], obj.get("namespacedName")) - return CurrentToolMetadata(description, name, defer_loading, input_schema, mcp_server_name, mcp_tool_name, namespaced_name) + hmac = from_str(obj.get("hmac")) + host = Host(obj.get("host")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return HMACAuthInfo(hmac, host, copilot_user) def to_dict(self) -> dict: result: dict = {} - result["description"] = from_str(self.description) - result["name"] = from_str(self.name) - if self.defer_loading is not None: - result["deferLoading"] = from_union([from_bool, from_none], self.defer_loading) - if self.input_schema is not None: - result["input_schema"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.input_schema) - if self.mcp_server_name is not None: - result["mcpServerName"] = from_union([from_str, from_none], self.mcp_server_name) - if self.mcp_tool_name is not None: - result["mcpToolName"] = from_union([from_str, from_none], self.mcp_tool_name) - if self.namespaced_name is not None: - result["namespacedName"] = from_union([from_str, from_none], self.namespaced_name) + result["hmac"] = from_str(self.hmac) + result["host"] = to_enum(Host, self.host) + result["type"] = self.type + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -20324,68 +23397,275 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. # Internal: this type is an internal SDK API and is not part of the public surface. @dataclass -class MCPOauthRespondRequest: - """MCP OAuth request id and optional provider response.""" +class MCPRegisterExternalClientRequest: + """Registration parameters for an external MCP client.""" - request_id: str - """OAuth request identifier from mcp.oauth_required""" + server_name: str + """Logical server name for the external client""" + + client: Any = None + """In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC + boundary. + """ + config: Any = None + """In-process server config (MCPServerConfig) paired with the in-process client/transport. + Marked internal alongside its companions. + """ + transport: Any = None + """In-process MCP Transport instance. Marked internal: cannot be serialized across the + JSON-RPC boundary. + """ + + @staticmethod + def from_dict(obj: Any) -> 'MCPRegisterExternalClientRequest': + assert isinstance(obj, dict) + client = obj.get("client") + config = obj.get("config") + server_name = from_str(obj.get("serverName")) + transport = obj.get("transport") + return MCPRegisterExternalClientRequest(client, config, server_name, transport) + + def to_dict(self) -> dict: + result: dict = {} + result["client"] = self.client + result["config"] = self.config + result["serverName"] = from_str(self.server_name) + result["transport"] = self.transport + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourceAnnotations: + """Model/client annotations associated with this resource - provider: Any = None - """In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be - serialized across the JSON-RPC boundary. + Standard MCP resource annotations plus preserved non-standard annotation fields. + + Model/client annotations associated with this template """ + additional_properties: dict[str, Any] | None = None + """Server-provided non-standard annotation fields preserved from the MCP response""" + + audience: list[str] | None = None + """Intended audience roles for this resource""" + + last_modified: str | None = None + """Last-modified timestamp hint""" + + priority: float | None = None + """Priority hint for model/client use""" @staticmethod - def from_dict(obj: Any) -> 'MCPOauthRespondRequest': + def from_dict(obj: Any) -> 'MCPResourceAnnotations': assert isinstance(obj, dict) - request_id = from_str(obj.get("requestId")) - provider = obj.get("provider") - return MCPOauthRespondRequest(request_id, provider) + additional_properties = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("additionalProperties")) + audience = from_union([lambda x: from_list(from_str, x), from_none], obj.get("audience")) + last_modified = from_union([from_str, from_none], obj.get("lastModified")) + priority = from_union([from_float, from_none], obj.get("priority")) + return MCPResourceAnnotations(additional_properties, audience, last_modified, priority) + + def to_dict(self) -> dict: + result: dict = {} + if self.additional_properties is not None: + result["additionalProperties"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.additional_properties) + if self.audience is not None: + result["audience"] = from_union([lambda x: from_list(from_str, x), from_none], self.audience) + if self.last_modified is not None: + result["lastModified"] = from_union([from_str, from_none], self.last_modified) + if self.priority is not None: + result["priority"] = from_union([to_float, from_none], self.priority) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResource: + """An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, + MIME type, size, icons, annotations, and metadata. Server-provided fields outside the + standard descriptor shape are exposed under `additionalProperties`. + """ + name: str + """The programmatic name of the resource""" + + uri: str + """The resource URI (e.g. ui://... or file:///...)""" + + meta: dict[str, Any] | None = None + """Resource-level metadata""" + + additional_properties: dict[str, Any] | None = None + """Server-provided non-standard descriptor fields preserved from the MCP response""" + + annotations: MCPResourceAnnotations | None = None + """Model/client annotations associated with this resource""" + + description: str | None = None + """Optional description of what this resource represents""" + + icons: list[MCPResourceIcon] | None = None + """Icons associated with this resource""" + + mime_type: str | None = None + """MIME type of the resource, if known""" + + size: int | None = None + """Resource size in bytes, when known""" + + title: str | None = None + """Optional human-readable display title""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResource': + assert isinstance(obj, dict) + name = from_str(obj.get("name")) + uri = from_str(obj.get("uri")) + meta = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("_meta")) + additional_properties = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("additionalProperties")) + annotations = from_union([MCPResourceAnnotations.from_dict, from_none], obj.get("annotations")) + description = from_union([from_str, from_none], obj.get("description")) + icons = from_union([lambda x: from_list(MCPResourceIcon.from_dict, x), from_none], obj.get("icons")) + mime_type = from_union([from_str, from_none], obj.get("mimeType")) + size = from_union([from_int, from_none], obj.get("size")) + title = from_union([from_str, from_none], obj.get("title")) + return MCPResource(name, uri, meta, additional_properties, annotations, description, icons, mime_type, size, title) + + def to_dict(self) -> dict: + result: dict = {} + result["name"] = from_str(self.name) + result["uri"] = from_str(self.uri) + if self.meta is not None: + result["_meta"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.meta) + if self.additional_properties is not None: + result["additionalProperties"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.additional_properties) + if self.annotations is not None: + result["annotations"] = from_union([lambda x: to_class(MCPResourceAnnotations, x), from_none], self.annotations) + if self.description is not None: + result["description"] = from_union([from_str, from_none], self.description) + if self.icons is not None: + result["icons"] = from_union([lambda x: from_list(lambda x: to_class(MCPResourceIcon, x), x), from_none], self.icons) + if self.mime_type is not None: + result["mimeType"] = from_union([from_str, from_none], self.mime_type) + if self.size is not None: + result["size"] = from_union([from_int, from_none], self.size) + if self.title is not None: + result["title"] = from_union([from_str, from_none], self.title) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourceTemplate: + """An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, + name, and optional title, description, MIME type, icons, annotations, and metadata. + Server-provided fields outside the standard descriptor shape are exposed under + `additionalProperties`. + """ + name: str + """The programmatic name of the resource template""" + + uri_template: str + """An RFC 6570 URI template for constructing resource URIs""" + + meta: dict[str, Any] | None = None + """Resource-template-level metadata""" + + additional_properties: dict[str, Any] | None = None + """Server-provided non-standard descriptor fields preserved from the MCP response""" + + annotations: MCPResourceAnnotations | None = None + """Model/client annotations associated with this template""" + + description: str | None = None + """Optional description of what this template is for""" + + icons: list[MCPResourceIcon] | None = None + """Icons associated with resources matching this template""" + + mime_type: str | None = None + """MIME type for resources matching this template, if uniform""" + + title: str | None = None + """Optional human-readable display title""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResourceTemplate': + assert isinstance(obj, dict) + name = from_str(obj.get("name")) + uri_template = from_str(obj.get("uriTemplate")) + meta = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("_meta")) + additional_properties = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("additionalProperties")) + annotations = from_union([MCPResourceAnnotations.from_dict, from_none], obj.get("annotations")) + description = from_union([from_str, from_none], obj.get("description")) + icons = from_union([lambda x: from_list(MCPResourceIcon.from_dict, x), from_none], obj.get("icons")) + mime_type = from_union([from_str, from_none], obj.get("mimeType")) + title = from_union([from_str, from_none], obj.get("title")) + return MCPResourceTemplate(name, uri_template, meta, additional_properties, annotations, description, icons, mime_type, title) + + def to_dict(self) -> dict: + result: dict = {} + result["name"] = from_str(self.name) + result["uriTemplate"] = from_str(self.uri_template) + if self.meta is not None: + result["_meta"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.meta) + if self.additional_properties is not None: + result["additionalProperties"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.additional_properties) + if self.annotations is not None: + result["annotations"] = from_union([lambda x: to_class(MCPResourceAnnotations, x), from_none], self.annotations) + if self.description is not None: + result["description"] = from_union([from_str, from_none], self.description) + if self.icons is not None: + result["icons"] = from_union([lambda x: from_list(lambda x: to_class(MCPResourceIcon, x), x), from_none], self.icons) + if self.mime_type is not None: + result["mimeType"] = from_union([from_str, from_none], self.mime_type) + if self.title is not None: + result["title"] = from_union([from_str, from_none], self.title) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPResourcesListResult: + """One page of resources advertised by the named MCP server.""" + + resources: list[MCPResource] + """Resources advertised by the server (proxied MCP `resources/list`)""" + + next_cursor: str | None = None + """Opaque cursor for the next page, if the server has more resources""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPResourcesListResult': + assert isinstance(obj, dict) + resources = from_list(MCPResource.from_dict, obj.get("resources")) + next_cursor = from_union([from_str, from_none], obj.get("nextCursor")) + return MCPResourcesListResult(resources, next_cursor) def to_dict(self) -> dict: result: dict = {} - result["requestId"] = from_str(self.request_id) - if self.provider is not None: - result["provider"] = self.provider + result["resources"] = from_list(lambda x: to_class(MCPResource, x), self.resources) + if self.next_cursor is not None: + result["nextCursor"] = from_union([from_str, from_none], self.next_cursor) return result # Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. @dataclass -class MCPRegisterExternalClientRequest: - """Registration parameters for an external MCP client.""" +class MCPResourcesListTemplatesResult: + """One page of resource templates advertised by the named MCP server.""" - server_name: str - """Logical server name for the external client""" + resource_templates: list[MCPResourceTemplate] + """Resource templates advertised by the server (proxied MCP `resources/templates/list`)""" - client: Any = None - """In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC - boundary. - """ - config: Any = None - """In-process server config (MCPServerConfig) paired with the in-process client/transport. - Marked internal alongside its companions. - """ - transport: Any = None - """In-process MCP Transport instance. Marked internal: cannot be serialized across the - JSON-RPC boundary. - """ + next_cursor: str | None = None + """Opaque cursor for the next page, if the server has more resource templates""" @staticmethod - def from_dict(obj: Any) -> 'MCPRegisterExternalClientRequest': + def from_dict(obj: Any) -> 'MCPResourcesListTemplatesResult': assert isinstance(obj, dict) - client = obj.get("client") - config = obj.get("config") - server_name = from_str(obj.get("serverName")) - transport = obj.get("transport") - return MCPRegisterExternalClientRequest(client, config, server_name, transport) + resource_templates = from_list(MCPResourceTemplate.from_dict, obj.get("resourceTemplates")) + next_cursor = from_union([from_str, from_none], obj.get("nextCursor")) + return MCPResourcesListTemplatesResult(resource_templates, next_cursor) def to_dict(self) -> dict: result: dict = {} - result["client"] = self.client - result["config"] = self.config - result["serverName"] = from_str(self.server_name) - result["transport"] = self.transport + result["resourceTemplates"] = from_list(lambda x: to_class(MCPResourceTemplate, x), self.resource_templates) + if self.next_cursor is not None: + result["nextCursor"] = from_union([from_str, from_none], self.next_cursor) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -20441,6 +23721,7 @@ def to_dict(self) -> dict: result["modelId"] = from_str(self.model_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelCapabilities: """Model capabilities and limits""" @@ -20466,6 +23747,7 @@ def to_dict(self) -> dict: result["supports"] = from_union([lambda x: to_class(ModelCapabilitiesSupports, x), from_none], self.supports) return result +# Experimental: this type is part of an experimental API and may change or be removed. class ModelPickerCategory(Enum): """Model capability category for grouping in the model picker""" @@ -20473,10 +23755,12 @@ class ModelPickerCategory(Enum): POWERFUL = "powerful" VERSATILE = "versatile" +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class Model: - """Schema for the `Model` type.""" - + """Copilot model metadata, including identifier, display name, capabilities, policy, + billing, reasoning efforts, and picker categories. + """ capabilities: ModelCapabilities """Model capabilities and limits""" @@ -20537,6 +23821,7 @@ def to_dict(self) -> dict: result["supportedReasoningEfforts"] = from_union([lambda x: from_list(from_str, x), from_none], self.supported_reasoning_efforts) return result +# Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelList: """List of Copilot models available to the resolved user, including capabilities and billing @@ -20580,6 +23865,9 @@ class ModelSwitchToRequest: reasoning_summary: ReasoningSummary | None = None """Reasoning summary mode to request for supported model clients""" + verbosity: Verbosity | None = None + """Output verbosity level to request for supported models""" + @staticmethod def from_dict(obj: Any) -> 'ModelSwitchToRequest': assert isinstance(obj, dict) @@ -20588,7 +23876,8 @@ def from_dict(obj: Any) -> 'ModelSwitchToRequest': model_capabilities = from_union([ModelCapabilitiesOverride.from_dict, from_none], obj.get("modelCapabilities")) reasoning_effort = from_union([from_str, from_none], obj.get("reasoningEffort")) reasoning_summary = from_union([ReasoningSummary, from_none], obj.get("reasoningSummary")) - return ModelSwitchToRequest(model_id, context_tier, model_capabilities, reasoning_effort, reasoning_summary) + verbosity = from_union([Verbosity, from_none], obj.get("verbosity")) + return ModelSwitchToRequest(model_id, context_tier, model_capabilities, reasoning_effort, reasoning_summary, verbosity) def to_dict(self) -> dict: result: dict = {} @@ -20601,6 +23890,8 @@ def to_dict(self) -> dict: result["reasoningEffort"] = from_union([from_str, from_none], self.reasoning_effort) if self.reasoning_summary is not None: result["reasoningSummary"] = from_union([lambda x: to_enum(ReasoningSummary, x), from_none], self.reasoning_summary) + if self.verbosity is not None: + result["verbosity"] = from_union([lambda x: to_enum(Verbosity, x), from_none], self.verbosity) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -20615,24 +23906,40 @@ class PermissionsSetAAllSource(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsSetAllowAllRequest: - """Whether to enable full allow-all permissions for the session.""" - - enabled: bool - """Whether to enable full allow-all permissions""" + """Allow-all mode to apply for the session.""" + enabled: bool | None = None + """Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is + treated as `mode: "on"` and any other value is treated as `mode: "off"`. + """ + mode: PermissionsAllowAllMode | None = None + """Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM + auto-approval; `off` disables both. + """ + model: str | None = None + """Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when + `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. + """ source: PermissionsSetAAllSource | None = None """Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers.""" @staticmethod def from_dict(obj: Any) -> 'PermissionsSetAllowAllRequest': assert isinstance(obj, dict) - enabled = from_bool(obj.get("enabled")) + enabled = from_union([from_bool, from_none], obj.get("enabled")) + mode = from_union([PermissionsAllowAllMode, from_none], obj.get("mode")) + model = from_union([from_str, from_none], obj.get("model")) source = from_union([PermissionsSetAAllSource, from_none], obj.get("source")) - return PermissionsSetAllowAllRequest(enabled, source) + return PermissionsSetAllowAllRequest(enabled, mode, model, source) def to_dict(self) -> dict: result: dict = {} - result["enabled"] = from_bool(self.enabled) + if self.enabled is not None: + result["enabled"] = from_union([from_bool, from_none], self.enabled) + if self.mode is not None: + result["mode"] = from_union([lambda x: to_enum(PermissionsAllowAllMode, x), from_none], self.mode) + if self.model is not None: + result["model"] = from_union([from_str, from_none], self.model) if self.source is not None: result["source"] = from_union([lambda x: to_enum(PermissionsSetAAllSource, x), from_none], self.source) return result @@ -20767,6 +24074,15 @@ class SessionsOpenHandoff: `sessions.list` with `source: "remote"`). """ # Internal: this field is an internal SDK API and is not part of the public surface. + on_confirm: Any = None + """In-process confirmation callback `(request) => boolean | Promise` invoked when + the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch + between the current working directory and the remote session). Returning `true` proceeds + with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal + because a function reference cannot cross the JSON-RPC boundary, for the same reasons as + `onProgress`. + """ + # Internal: this field is an internal SDK API and is not part of the public surface. on_progress: Any = None """In-process progress callback `(update) => void` invoked for each handoff step. Marked internal because a function reference cannot cross the JSON-RPC boundary. The host-side @@ -20787,15 +24103,18 @@ class SessionsOpenHandoff: def from_dict(obj: Any) -> 'SessionsOpenHandoff': assert isinstance(obj, dict) metadata = RemoteSessionMetadataValue.from_dict(obj.get("metadata")) + on_confirm = obj.get("onConfirm") on_progress = obj.get("onProgress") options = from_union([SessionOpenOptions.from_dict, from_none], obj.get("options")) task_type = from_union([TaskType, from_none], obj.get("taskType")) - return SessionsOpenHandoff(metadata, on_progress, options, task_type) + return SessionsOpenHandoff(metadata, on_confirm, on_progress, options, task_type) def to_dict(self) -> dict: result: dict = {} result["kind"] = self.kind result["metadata"] = to_class(RemoteSessionMetadataValue, self.metadata) + if self.on_confirm is not None: + result["onConfirm"] = self.on_confirm if self.on_progress is not None: result["onProgress"] = self.on_progress if self.options is not None: @@ -20847,12 +24166,21 @@ class SubagentSettings: disabled_subagents: list[str] | None = None """Names of subagents the user has turned off; they cannot be dispatched""" + max_concurrency: int | None = None + """Maximum number of subagents that can run concurrently; applies to usage-based billing + users only + """ + max_depth: int | None = None + """Maximum subagent nesting depth; applies to usage-based billing users only""" + @staticmethod def from_dict(obj: Any) -> 'SubagentSettings': assert isinstance(obj, dict) agents = from_union([lambda x: from_dict(SubagentSettingsEntry.from_dict, x), from_none], obj.get("agents")) disabled_subagents = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledSubagents")) - return SubagentSettings(agents, disabled_subagents) + max_concurrency = from_union([from_int, from_none], obj.get("maxConcurrency")) + max_depth = from_union([from_int, from_none], obj.get("maxDepth")) + return SubagentSettings(agents, disabled_subagents, max_concurrency, max_depth) def to_dict(self) -> dict: result: dict = {} @@ -20860,6 +24188,48 @@ def to_dict(self) -> dict: result["agents"] = from_union([lambda x: from_dict(lambda x: to_class(SubagentSettingsEntry, x), x), from_none], self.agents) if self.disabled_subagents is not None: result["disabledSubagents"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_subagents) + if self.max_concurrency is not None: + result["maxConcurrency"] = from_union([from_int, from_none], self.max_concurrency) + if self.max_depth is not None: + result["maxDepth"] = from_union([from_int, from_none], self.max_depth) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class TokenAuthInfo: + """Authentication-info variant for SDK-configured token authentication, carrying host and + the secret token value. + """ + host: str + """Authentication host.""" + + token: str + """The token value itself. Treat as a secret.""" + + type: ClassVar[str] = "token" + """SDK-side token authentication; the host configured the token directly via the SDK.""" + + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + + @staticmethod + def from_dict(obj: Any) -> 'TokenAuthInfo': + assert isinstance(obj, dict) + host = from_str(obj.get("host")) + token = from_str(obj.get("token")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return TokenAuthInfo(host, token, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["host"] = from_str(self.host) + result["token"] = from_str(self.token) + result["type"] = self.type + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -20939,6 +24309,45 @@ def to_dict(self) -> dict: result["subagents"] = from_union([lambda x: to_class(SubagentSettings, x), from_none], self.subagents) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class UserAuthInfo: + """Authentication-info variant for OAuth user auth, with host and login; the token remains + in the runtime secret store. + """ + host: str + """Authentication host.""" + + login: str + """OAuth user login.""" + + type: ClassVar[str] = "user" + """OAuth user authentication. The token itself is held in the runtime's secret token store + (keyed by host+login) and is NOT carried in this struct. + """ + copilot_user: CopilotUserResponse | None = None + """Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the + GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this + verbatim and does not re-fetch when set. + """ + + @staticmethod + def from_dict(obj: Any) -> 'UserAuthInfo': + assert isinstance(obj, dict) + host = from_str(obj.get("host")) + login = from_str(obj.get("login")) + copilot_user = from_union([CopilotUserResponse.from_dict, from_none], obj.get("copilotUser")) + return UserAuthInfo(host, login, copilot_user) + + def to_dict(self) -> dict: + result: dict = {} + result["host"] = from_str(self.host) + result["login"] = from_str(self.login) + result["type"] = self.type + if self.copilot_user is not None: + result["copilotUser"] = from_union([lambda x: to_class(CopilotUserResponse, x), from_none], self.copilot_user) + return result + @dataclass class RPC: abort_request: AbortRequest @@ -20953,6 +24362,7 @@ class RPC: account_logout_request: AccountLogoutRequest account_logout_result: AccountLogoutResult account_quota_snapshot: AccountQuotaSnapshot + adaptive_thinking_support: AdaptiveThinkingSupport agent_discovery_path: AgentDiscoveryPath agent_discovery_path_list: AgentDiscoveryPathList agent_discovery_path_scope: AgentDiscoveryPathScope @@ -21010,6 +24420,9 @@ class RPC: commands_list_request: CommandsListRequest commands_respond_to_queued_command_request: CommandsRespondToQueuedCommandRequest commands_respond_to_queued_command_result: CommandsRespondToQueuedCommandResult + completions_get_trigger_characters_result: CompletionsGetTriggerCharactersResult + completions_request_request: CompletionsRequestRequest + completions_request_result: CompletionsRequestResult configure_session_extensions_params: _ConfigureSessionExtensionsParams connected_remote_session_metadata: ConnectedRemoteSessionMetadata connected_remote_session_metadata_kind: ConnectedRemoteSessionMetadataKind @@ -21018,6 +24431,7 @@ class RPC: connect_request: _ConnectRequest connect_result: _ConnectResult content_filter_mode: ContentFilterMode + context_heaviest_message: ContextHeaviestMessage copilot_api_token_auth_info: CopilotAPITokenAuthInfo copilot_user_response: CopilotUserResponse copilot_user_response_endpoints: CopilotUserResponseEndpoints @@ -21027,6 +24441,17 @@ class RPC: copilot_user_response_quota_snapshots_premium_interactions: CopilotUserResponseQuotaSnapshotsPremiumInteractions current_model: CurrentModel current_tool_metadata: CurrentToolMetadata + debug_collect_logs_collected_entry: DebugCollectLogsCollectedEntry + debug_collect_logs_destination: DebugCollectLogsDestination + debug_collect_logs_entry: DebugCollectLogsEntry + debug_collect_logs_entry_kind: DebugCollectLogsEntryKind + debug_collect_logs_include: DebugCollectLogsInclude + debug_collect_logs_redaction: DebugCollectLogsRedaction + debug_collect_logs_request: DebugCollectLogsRequest + debug_collect_logs_result: DebugCollectLogsResult + debug_collect_logs_result_kind: DebugCollectLogsResultKind + debug_collect_logs_skipped_entry: DebugCollectLogsSkippedEntry + debug_collect_logs_source: DebugCollectLogsSource discovered_canvas: DiscoveredCanvas discovered_mcp_server: DiscoveredMCPServer discovered_mcp_server_type: DiscoveredMCPServerType @@ -21061,6 +24486,7 @@ class RPC: external_tool_text_result_for_llm_content_resource_link: ExternalToolTextResultForLlmContentResourceLink external_tool_text_result_for_llm_content_resource_link_icon: ExternalToolTextResultForLlmContentResourceLinkIcon external_tool_text_result_for_llm_content_resource_link_icon_theme: Theme + external_tool_text_result_for_llm_content_shell_exit: ExternalToolTextResultForLlmContentShellExit external_tool_text_result_for_llm_content_terminal: ExternalToolTextResultForLlmContentTerminal external_tool_text_result_for_llm_content_text: ExternalToolTextResultForLlmContentText filter_mapping: dict[str, ContentFilterMode] | ContentFilterMode @@ -21070,6 +24496,9 @@ class RPC: folder_trust_check_params: FolderTrustCheckParams folder_trust_check_result: FolderTrustCheckResult gh_cli_auth_info: GhCLIAuthInfo + git_hub_telemetry_client_info: GitHubTelemetryClientInfo + git_hub_telemetry_event: GitHubTelemetryEvent + git_hub_telemetry_notification: GitHubTelemetryNotification handle_pending_tool_call_request: HandlePendingToolCallRequest handle_pending_tool_call_result: HandlePendingToolCallResult history_abort_manual_compaction_result: HistoryAbortManualCompactionResult @@ -21081,6 +24510,9 @@ class RPC: history_truncate_request: HistoryTruncateRequest history_truncate_result: HistoryTruncateResult hmac_auth_info: HMACAuthInfo + hook_invoke_request: _HookInvokeRequest + hook_invoke_response: _HookInvokeResponse + hook_type: _HookType installed_plugin: InstalledPlugin installed_plugin_info: InstalledPluginInfo installed_plugin_source: InstalledPluginSource | str @@ -21088,7 +24520,7 @@ class RPC: installed_plugin_source_local: InstalledPluginSourceLocal installed_plugin_source_url: InstalledPluginSourceURL instruction_discovery_path: InstructionDiscoveryPath - instruction_discovery_path_kind: InstructionDiscoveryPathKind + instruction_discovery_path_kind: DebugCollectLogsEntryKind instruction_discovery_path_list: InstructionDiscoveryPathList instruction_discovery_path_location: InstructionLocation instructions_discover_request: InstructionsDiscoverRequest @@ -21162,6 +24594,9 @@ class RPC: mcp_execute_sampling_request: dict[str, Any] mcp_execute_sampling_result: dict[str, Any] mcp_filtered_server: MCPFilteredServer + mcp_headers_handle_pending_headers_refresh_request: MCPHeadersHandlePendingHeadersRefreshRequest + mcp_headers_handle_pending_headers_refresh_request_request: MCPHeadersHandlePendingHeadersRefreshRequestRequest + mcp_headers_handle_pending_headers_refresh_request_result: MCPHeadersHandlePendingHeadersRefreshRequestResult mcp_host_state: MCPHostState mcp_is_server_running_request: MCPIsServerRunningRequest mcp_is_server_running_result: MCPIsServerRunningResult @@ -21173,11 +24608,20 @@ class RPC: mcp_oauth_login_request: MCPOauthLoginRequest mcp_oauth_login_result: MCPOauthLoginResult mcp_oauth_pending_request_response: MCPOauthPendingRequestResponse - mcp_oauth_respond_request: MCPOauthRespondRequest - mcp_oauth_respond_result: MCPOauthRespondResult mcp_register_external_client_request: MCPRegisterExternalClientRequest mcp_reload_with_config_request: MCPReloadWithConfigRequest mcp_remove_git_hub_result: MCPRemoveGitHubResult + mcp_resource: MCPResource + mcp_resource_annotations: MCPResourceAnnotations + mcp_resource_content: MCPResourceContent + mcp_resource_icon: MCPResourceIcon + mcp_resources_list_request: MCPResourcesListRequest + mcp_resources_list_result: MCPResourcesListResult + mcp_resources_list_templates_request: MCPResourcesListTemplatesRequest + mcp_resources_list_templates_result: MCPResourcesListTemplatesResult + mcp_resources_read_request: MCPResourcesReadRequest + mcp_resources_read_result: MCPResourcesReadResult + mcp_resource_template: MCPResourceTemplate mcp_restart_server_request: MCPRestartServerRequest mcp_sampling_execution_action: MCPSamplingExecutionAction mcp_sampling_execution_result: MCPSamplingExecutionResult @@ -21200,8 +24644,13 @@ class RPC: mcp_start_servers_result: MCPStartServersResult mcp_stop_server_request: MCPStopServerRequest mcp_tools: MCPTools + mcp_tool_ui: MCPToolUI + mcp_tool_ui_visibility: MCPToolUIVisibility mcp_unregister_external_client_request: MCPUnregisterExternalClientRequest memory_configuration: MemoryConfiguration + metadata_context_attribution_result: MetadataContextAttributionResult + metadata_context_heaviest_messages_request: MetadataContextHeaviestMessagesRequest + metadata_context_heaviest_messages_result: MetadataContextHeaviestMessagesResult metadata_context_info_request: MetadataContextInfoRequest metadata_context_info_result: MetadataContextInfoResult metadata_is_processing_result: MetadataIsProcessingResult @@ -21217,6 +24666,7 @@ class RPC: metadata_snapshot_remote_metadata_task_type: TaskType model: Model model_billing: ModelBilling + model_billing_promo: ModelBillingPromo model_billing_token_prices: ModelBillingTokenPrices model_billing_token_prices_long_context: ModelBillingTokenPricesLongContext model_capabilities: ModelCapabilities @@ -21309,6 +24759,7 @@ class RPC: permission_prompt_shown_notification: PermissionPromptShownNotification permission_request_result: PermissionRequestResult permission_rules_set: PermissionRulesSet + permissions_allow_all_mode: PermissionsAllowAllMode permissions_configure_additional_content_exclusion_policy: PermissionsConfigureAdditionalContentExclusionPolicy permissions_configure_additional_content_exclusion_policy_rule: PermissionsConfigureAdditionalContentExclusionPolicyRule permissions_configure_additional_content_exclusion_policy_rule_source: PermissionsConfigureAdditionalContentExclusionPolicyRuleSource @@ -21373,7 +24824,6 @@ class RPC: plugin_update_all_entry: PluginUpdateAllEntry plugin_update_all_result: PluginUpdateAllResult plugin_update_result: PluginUpdateResult - poll_spawned_sessions_result: PollSpawnedSessionsResult provider_add_request: ProviderAddRequest provider_add_result: ProviderAddResult provider_config: ProviderConfig @@ -21395,12 +24845,24 @@ class RPC: push_attachment_directory: PushAttachmentDirectory push_attachment_file: PushAttachmentFile push_attachment_file_line_range: PushAttachmentFileLineRange + push_attachment_git_hub_actions_job: PushAttachmentGitHubActionsJob + push_attachment_git_hub_commit: PushAttachmentGitHubCommit + push_attachment_git_hub_file: PushAttachmentGitHubFile + push_attachment_git_hub_file_diff: PushAttachmentGitHubFileDiff + push_attachment_git_hub_file_diff_side: PushAttachmentGitHubFileDiffSide push_attachment_git_hub_reference: PushAttachmentGitHubReference push_attachment_git_hub_reference_type: PushAttachmentGitHubReferenceTypeEnum + push_attachment_git_hub_release: PushAttachmentGitHubRelease + push_attachment_git_hub_repository: PushAttachmentGitHubRepository + push_attachment_git_hub_snippet: PushAttachmentGitHubSnippet + push_attachment_git_hub_tree_comparison: PushAttachmentGitHubTreeComparison + push_attachment_git_hub_tree_comparison_side: PushAttachmentGitHubTreeComparisonSide + push_attachment_git_hub_url: PushAttachmentGitHubURL push_attachment_selection: PushAttachmentSelection push_attachment_selection_details: PushAttachmentSelectionDetails push_attachment_selection_details_end: PushAttachmentSelectionDetailsEnd push_attachment_selection_details_start: PushAttachmentSelectionDetailsStart + push_git_hub_repo_ref: PushGitHubRepoRef queued_command_handled: QueuedCommandHandled queued_command_not_handled: QueuedCommandNotHandled queued_command_result: QueuedCommandResult @@ -21448,6 +24910,9 @@ class RPC: secrets_add_filter_values_result: SecretsAddFilterValuesResult send_agent_mode: SendAgentMode send_attachments_to_message_params: SendAttachmentsToMessageParams + send_message_item: SendMessageItem + send_messages_request: SendMessagesRequest + send_messages_result: SendMessagesResult send_mode: SendMode send_request: SendRequest send_result: SendResult @@ -21459,6 +24924,7 @@ class RPC: session_auth_status: SessionAuthStatus session_bulk_delete_result: SessionBulkDeleteResult session_capability: SessionCapability + session_completion_item: SessionCompletionItem session_context: SessionContext session_context_host_type: HostType session_enrich_metadata_result: SessionEnrichMetadataResult @@ -21471,7 +24937,7 @@ class RPC: session_fs_readdir_request: SessionFSReaddirRequest session_fs_readdir_result: SessionFSReaddirResult session_fs_readdir_with_types_entry: SessionFSReaddirWithTypesEntry - session_fs_readdir_with_types_entry_type: InstructionDiscoveryPathKind + session_fs_readdir_with_types_entry_type: DebugCollectLogsEntryKind session_fs_readdir_with_types_request: SessionFSReaddirWithTypesRequest session_fs_readdir_with_types_result: SessionFSReaddirWithTypesResult session_fs_read_file_request: SessionFSReadFileRequest @@ -21504,6 +24970,7 @@ class RPC: session_metadata_snapshot: SessionMetadataSnapshot session_mode: SessionMode session_model_list: SessionModelList + session_model_price_category: SessionModelPriceCategory session_open_options: SessionOpenOptions session_open_options_additional_content_exclusion_policy: SessionOpenOptionsAdditionalContentExclusionPolicy session_open_options_additional_content_exclusion_policy_rule: SessionOpenOptionsAdditionalContentExclusionPolicyRule @@ -21522,6 +24989,16 @@ class RPC: sessions_enrich_metadata_request: SessionsEnrichMetadataRequest session_set_credentials_params: SessionSetCredentialsParams session_set_credentials_result: SessionSetCredentialsResult + session_settings_built_in_tool_availability_snapshot: SessionSettingsBuiltInToolAvailabilitySnapshot + session_settings_evaluate_predicate_request: SessionSettingsEvaluatePredicateRequest + session_settings_evaluate_predicate_result: SessionSettingsEvaluatePredicateResult + session_settings_job_snapshot: SessionSettingsJobSnapshot + session_settings_model_snapshot: SessionSettingsModelSnapshot + session_settings_online_evaluation_snapshot: SessionSettingsOnlineEvaluationSnapshot + session_settings_predicate_name: SessionSettingsPredicateName + session_settings_repo_snapshot: SessionSettingsRepoSnapshot + session_settings_snapshot: SessionSettingsSnapshot + session_settings_validation_snapshot: SessionSettingsValidationSnapshot sessions_find_by_prefix_request: SessionsFindByPrefixRequest sessions_find_by_prefix_result: SessionsFindByPrefixResult sessions_find_by_task_id_request: SessionsFindByTaskIDRequest @@ -21552,8 +25029,6 @@ class RPC: sessions_open_resume_last: SessionsOpenResumeLast sessions_open_status: SessionsOpenStatus session_source: SessionSource - sessions_poll_spawned_sessions_event: SessionsPollSpawnedSessionsEvent - sessions_poll_spawned_sessions_request: SessionsPollSpawnedSessionsRequest sessions_prune_old_request: SessionsPruneOldRequest sessions_register_extension_tools_on_session_options: SessionsRegisterExtensionToolsOnSessionOptions sessions_release_lock_request: SessionsReleaseLockRequest @@ -21571,6 +25046,7 @@ class RPC: session_telemetry_engagement: SessionTelemetryEngagement session_update_options_params: SessionUpdateOptionsParams session_update_options_result: SessionUpdateOptionsResult + session_visibility_status: SessionVisibilityStatus session_working_directory_context: SessionWorkingDirectoryContext session_working_directory_context_host_type: HostType shell_cancel_user_requested_request: ShellCancelUserRequestedRequest @@ -21598,6 +25074,7 @@ class RPC: slash_command_completed_result: SlashCommandCompletedResult slash_command_info: SlashCommandInfo slash_command_input: SlashCommandInput + slash_command_input_choice: SlashCommandInputChoice slash_command_input_completion: SlashCommandInputCompletion slash_command_invocation_result: SlashCommandInvocationResult slash_command_kind: SlashCommandKind @@ -21672,8 +25149,11 @@ class RPC: ui_handle_pending_result: UIHandlePendingResult ui_handle_pending_sampling_request: UIHandlePendingSamplingRequest ui_handle_pending_sampling_response: dict[str, Any] + ui_handle_pending_session_limits_exhausted_request: UIHandlePendingSessionLimitsExhaustedRequest ui_handle_pending_user_input_request: UIHandlePendingUserInputRequest ui_register_direct_auto_mode_switch_handler_result: UIRegisterDirectAutoModeSwitchHandlerResult + ui_session_limits_exhausted_response: UISessionLimitsExhaustedResponse + ui_session_limits_exhausted_response_action: UISessionLimitsExhaustedResponseAction ui_unregister_direct_auto_mode_switch_handler_request: UIUnregisterDirectAutoModeSwitchHandlerRequest ui_unregister_direct_auto_mode_switch_handler_result: UIUnregisterDirectAutoModeSwitchHandlerResult ui_user_input_response: UIUserInputResponse @@ -21687,6 +25167,13 @@ class RPC: usage_metrics_token_detail: UsageMetricsTokenDetail user_auth_info: UserAuthInfo user_requested_shell_command_result: UserRequestedShellCommandResult + user_setting_metadata: UserSettingMetadata + user_settings_get_result: UserSettingsGetResult + user_settings_set_request: UserSettingsSetRequest + user_settings_set_result: UserSettingsSetResult + visibility_get_result: VisibilityGetResult + visibility_set_request: VisibilitySetRequest + visibility_set_result: VisibilitySetResult workspace_diff_file_change: WorkspaceDiffFileChange workspace_diff_file_change_type: WorkspaceDiffFileChangeType workspace_diff_mode: WorkspaceDiffMode @@ -21705,6 +25192,7 @@ class RPC: workspaces_save_large_paste_result: WorkspacesSaveLargePasteResult workspace_summary_host_type: HostType workspaces_workspace_details_host_type: HostType + session_context_attribution: SessionContextAttribution | None = None session_context_info: SessionContextInfo | None = None subagent_settings: SubagentSettings | None = None task_progress: TaskProgress | None = None @@ -21725,6 +25213,7 @@ def from_dict(obj: Any) -> 'RPC': account_logout_request = AccountLogoutRequest.from_dict(obj.get("AccountLogoutRequest")) account_logout_result = AccountLogoutResult.from_dict(obj.get("AccountLogoutResult")) account_quota_snapshot = AccountQuotaSnapshot.from_dict(obj.get("AccountQuotaSnapshot")) + adaptive_thinking_support = AdaptiveThinkingSupport(obj.get("AdaptiveThinkingSupport")) agent_discovery_path = AgentDiscoveryPath.from_dict(obj.get("AgentDiscoveryPath")) agent_discovery_path_list = AgentDiscoveryPathList.from_dict(obj.get("AgentDiscoveryPathList")) agent_discovery_path_scope = AgentDiscoveryPathScope(obj.get("AgentDiscoveryPathScope")) @@ -21782,6 +25271,9 @@ def from_dict(obj: Any) -> 'RPC': commands_list_request = CommandsListRequest.from_dict(obj.get("CommandsListRequest")) commands_respond_to_queued_command_request = CommandsRespondToQueuedCommandRequest.from_dict(obj.get("CommandsRespondToQueuedCommandRequest")) commands_respond_to_queued_command_result = CommandsRespondToQueuedCommandResult.from_dict(obj.get("CommandsRespondToQueuedCommandResult")) + completions_get_trigger_characters_result = CompletionsGetTriggerCharactersResult.from_dict(obj.get("CompletionsGetTriggerCharactersResult")) + completions_request_request = CompletionsRequestRequest.from_dict(obj.get("CompletionsRequestRequest")) + completions_request_result = CompletionsRequestResult.from_dict(obj.get("CompletionsRequestResult")) configure_session_extensions_params = _ConfigureSessionExtensionsParams.from_dict(obj.get("ConfigureSessionExtensionsParams")) connected_remote_session_metadata = ConnectedRemoteSessionMetadata.from_dict(obj.get("ConnectedRemoteSessionMetadata")) connected_remote_session_metadata_kind = ConnectedRemoteSessionMetadataKind(obj.get("ConnectedRemoteSessionMetadataKind")) @@ -21790,6 +25282,7 @@ def from_dict(obj: Any) -> 'RPC': connect_request = _ConnectRequest.from_dict(obj.get("ConnectRequest")) connect_result = _ConnectResult.from_dict(obj.get("ConnectResult")) content_filter_mode = ContentFilterMode(obj.get("ContentFilterMode")) + context_heaviest_message = ContextHeaviestMessage.from_dict(obj.get("ContextHeaviestMessage")) copilot_api_token_auth_info = CopilotAPITokenAuthInfo.from_dict(obj.get("CopilotApiTokenAuthInfo")) copilot_user_response = CopilotUserResponse.from_dict(obj.get("CopilotUserResponse")) copilot_user_response_endpoints = CopilotUserResponseEndpoints.from_dict(obj.get("CopilotUserResponseEndpoints")) @@ -21799,6 +25292,17 @@ def from_dict(obj: Any) -> 'RPC': copilot_user_response_quota_snapshots_premium_interactions = CopilotUserResponseQuotaSnapshotsPremiumInteractions.from_dict(obj.get("CopilotUserResponseQuotaSnapshotsPremiumInteractions")) current_model = CurrentModel.from_dict(obj.get("CurrentModel")) current_tool_metadata = CurrentToolMetadata.from_dict(obj.get("CurrentToolMetadata")) + debug_collect_logs_collected_entry = DebugCollectLogsCollectedEntry.from_dict(obj.get("DebugCollectLogsCollectedEntry")) + debug_collect_logs_destination = DebugCollectLogsDestination.from_dict(obj.get("DebugCollectLogsDestination")) + debug_collect_logs_entry = DebugCollectLogsEntry.from_dict(obj.get("DebugCollectLogsEntry")) + debug_collect_logs_entry_kind = DebugCollectLogsEntryKind(obj.get("DebugCollectLogsEntryKind")) + debug_collect_logs_include = DebugCollectLogsInclude.from_dict(obj.get("DebugCollectLogsInclude")) + debug_collect_logs_redaction = DebugCollectLogsRedaction(obj.get("DebugCollectLogsRedaction")) + debug_collect_logs_request = DebugCollectLogsRequest.from_dict(obj.get("DebugCollectLogsRequest")) + debug_collect_logs_result = DebugCollectLogsResult.from_dict(obj.get("DebugCollectLogsResult")) + debug_collect_logs_result_kind = DebugCollectLogsResultKind(obj.get("DebugCollectLogsResultKind")) + debug_collect_logs_skipped_entry = DebugCollectLogsSkippedEntry.from_dict(obj.get("DebugCollectLogsSkippedEntry")) + debug_collect_logs_source = DebugCollectLogsSource(obj.get("DebugCollectLogsSource")) discovered_canvas = DiscoveredCanvas.from_dict(obj.get("DiscoveredCanvas")) discovered_mcp_server = DiscoveredMCPServer.from_dict(obj.get("DiscoveredMcpServer")) discovered_mcp_server_type = DiscoveredMCPServerType(obj.get("DiscoveredMcpServerType")) @@ -21833,6 +25337,7 @@ def from_dict(obj: Any) -> 'RPC': external_tool_text_result_for_llm_content_resource_link = ExternalToolTextResultForLlmContentResourceLink.from_dict(obj.get("ExternalToolTextResultForLlmContentResourceLink")) external_tool_text_result_for_llm_content_resource_link_icon = ExternalToolTextResultForLlmContentResourceLinkIcon.from_dict(obj.get("ExternalToolTextResultForLlmContentResourceLinkIcon")) external_tool_text_result_for_llm_content_resource_link_icon_theme = Theme(obj.get("ExternalToolTextResultForLlmContentResourceLinkIconTheme")) + external_tool_text_result_for_llm_content_shell_exit = ExternalToolTextResultForLlmContentShellExit.from_dict(obj.get("ExternalToolTextResultForLlmContentShellExit")) external_tool_text_result_for_llm_content_terminal = ExternalToolTextResultForLlmContentTerminal.from_dict(obj.get("ExternalToolTextResultForLlmContentTerminal")) external_tool_text_result_for_llm_content_text = ExternalToolTextResultForLlmContentText.from_dict(obj.get("ExternalToolTextResultForLlmContentText")) filter_mapping = from_union([lambda x: from_dict(ContentFilterMode, x), ContentFilterMode], obj.get("FilterMapping")) @@ -21842,6 +25347,9 @@ def from_dict(obj: Any) -> 'RPC': folder_trust_check_params = FolderTrustCheckParams.from_dict(obj.get("FolderTrustCheckParams")) folder_trust_check_result = FolderTrustCheckResult.from_dict(obj.get("FolderTrustCheckResult")) gh_cli_auth_info = GhCLIAuthInfo.from_dict(obj.get("GhCliAuthInfo")) + git_hub_telemetry_client_info = GitHubTelemetryClientInfo.from_dict(obj.get("GitHubTelemetryClientInfo")) + git_hub_telemetry_event = GitHubTelemetryEvent.from_dict(obj.get("GitHubTelemetryEvent")) + git_hub_telemetry_notification = GitHubTelemetryNotification.from_dict(obj.get("GitHubTelemetryNotification")) handle_pending_tool_call_request = HandlePendingToolCallRequest.from_dict(obj.get("HandlePendingToolCallRequest")) handle_pending_tool_call_result = HandlePendingToolCallResult.from_dict(obj.get("HandlePendingToolCallResult")) history_abort_manual_compaction_result = HistoryAbortManualCompactionResult.from_dict(obj.get("HistoryAbortManualCompactionResult")) @@ -21853,6 +25361,9 @@ def from_dict(obj: Any) -> 'RPC': history_truncate_request = HistoryTruncateRequest.from_dict(obj.get("HistoryTruncateRequest")) history_truncate_result = HistoryTruncateResult.from_dict(obj.get("HistoryTruncateResult")) hmac_auth_info = HMACAuthInfo.from_dict(obj.get("HMACAuthInfo")) + hook_invoke_request = _HookInvokeRequest.from_dict(obj.get("HookInvokeRequest")) + hook_invoke_response = _HookInvokeResponse.from_dict(obj.get("HookInvokeResponse")) + hook_type = _HookType(obj.get("HookType")) installed_plugin = InstalledPlugin.from_dict(obj.get("InstalledPlugin")) installed_plugin_info = InstalledPluginInfo.from_dict(obj.get("InstalledPluginInfo")) installed_plugin_source = from_union([InstalledPluginSource.from_dict, from_str], obj.get("InstalledPluginSource")) @@ -21860,7 +25371,7 @@ def from_dict(obj: Any) -> 'RPC': installed_plugin_source_local = InstalledPluginSourceLocal.from_dict(obj.get("InstalledPluginSourceLocal")) installed_plugin_source_url = InstalledPluginSourceURL.from_dict(obj.get("InstalledPluginSourceUrl")) instruction_discovery_path = InstructionDiscoveryPath.from_dict(obj.get("InstructionDiscoveryPath")) - instruction_discovery_path_kind = InstructionDiscoveryPathKind(obj.get("InstructionDiscoveryPathKind")) + instruction_discovery_path_kind = DebugCollectLogsEntryKind(obj.get("InstructionDiscoveryPathKind")) instruction_discovery_path_list = InstructionDiscoveryPathList.from_dict(obj.get("InstructionDiscoveryPathList")) instruction_discovery_path_location = InstructionLocation(obj.get("InstructionDiscoveryPathLocation")) instructions_discover_request = InstructionsDiscoverRequest.from_dict(obj.get("InstructionsDiscoverRequest")) @@ -21934,6 +25445,9 @@ def from_dict(obj: Any) -> 'RPC': mcp_execute_sampling_request = from_dict(lambda x: x, obj.get("McpExecuteSamplingRequest")) mcp_execute_sampling_result = from_dict(lambda x: x, obj.get("McpExecuteSamplingResult")) mcp_filtered_server = MCPFilteredServer.from_dict(obj.get("McpFilteredServer")) + mcp_headers_handle_pending_headers_refresh_request = MCPHeadersHandlePendingHeadersRefreshRequest.from_dict(obj.get("McpHeadersHandlePendingHeadersRefreshRequest")) + mcp_headers_handle_pending_headers_refresh_request_request = MCPHeadersHandlePendingHeadersRefreshRequestRequest.from_dict(obj.get("McpHeadersHandlePendingHeadersRefreshRequestRequest")) + mcp_headers_handle_pending_headers_refresh_request_result = MCPHeadersHandlePendingHeadersRefreshRequestResult.from_dict(obj.get("McpHeadersHandlePendingHeadersRefreshRequestResult")) mcp_host_state = MCPHostState.from_dict(obj.get("McpHostState")) mcp_is_server_running_request = MCPIsServerRunningRequest.from_dict(obj.get("McpIsServerRunningRequest")) mcp_is_server_running_result = MCPIsServerRunningResult.from_dict(obj.get("McpIsServerRunningResult")) @@ -21945,11 +25459,20 @@ def from_dict(obj: Any) -> 'RPC': mcp_oauth_login_request = MCPOauthLoginRequest.from_dict(obj.get("McpOauthLoginRequest")) mcp_oauth_login_result = MCPOauthLoginResult.from_dict(obj.get("McpOauthLoginResult")) mcp_oauth_pending_request_response = MCPOauthPendingRequestResponse.from_dict(obj.get("McpOauthPendingRequestResponse")) - mcp_oauth_respond_request = MCPOauthRespondRequest.from_dict(obj.get("McpOauthRespondRequest")) - mcp_oauth_respond_result = MCPOauthRespondResult.from_dict(obj.get("McpOauthRespondResult")) mcp_register_external_client_request = MCPRegisterExternalClientRequest.from_dict(obj.get("McpRegisterExternalClientRequest")) mcp_reload_with_config_request = MCPReloadWithConfigRequest.from_dict(obj.get("McpReloadWithConfigRequest")) mcp_remove_git_hub_result = MCPRemoveGitHubResult.from_dict(obj.get("McpRemoveGitHubResult")) + mcp_resource = MCPResource.from_dict(obj.get("McpResource")) + mcp_resource_annotations = MCPResourceAnnotations.from_dict(obj.get("McpResourceAnnotations")) + mcp_resource_content = MCPResourceContent.from_dict(obj.get("McpResourceContent")) + mcp_resource_icon = MCPResourceIcon.from_dict(obj.get("McpResourceIcon")) + mcp_resources_list_request = MCPResourcesListRequest.from_dict(obj.get("McpResourcesListRequest")) + mcp_resources_list_result = MCPResourcesListResult.from_dict(obj.get("McpResourcesListResult")) + mcp_resources_list_templates_request = MCPResourcesListTemplatesRequest.from_dict(obj.get("McpResourcesListTemplatesRequest")) + mcp_resources_list_templates_result = MCPResourcesListTemplatesResult.from_dict(obj.get("McpResourcesListTemplatesResult")) + mcp_resources_read_request = MCPResourcesReadRequest.from_dict(obj.get("McpResourcesReadRequest")) + mcp_resources_read_result = MCPResourcesReadResult.from_dict(obj.get("McpResourcesReadResult")) + mcp_resource_template = MCPResourceTemplate.from_dict(obj.get("McpResourceTemplate")) mcp_restart_server_request = MCPRestartServerRequest.from_dict(obj.get("McpRestartServerRequest")) mcp_sampling_execution_action = MCPSamplingExecutionAction(obj.get("McpSamplingExecutionAction")) mcp_sampling_execution_result = MCPSamplingExecutionResult.from_dict(obj.get("McpSamplingExecutionResult")) @@ -21972,8 +25495,13 @@ def from_dict(obj: Any) -> 'RPC': mcp_start_servers_result = MCPStartServersResult.from_dict(obj.get("McpStartServersResult")) mcp_stop_server_request = MCPStopServerRequest.from_dict(obj.get("McpStopServerRequest")) mcp_tools = MCPTools.from_dict(obj.get("McpTools")) + mcp_tool_ui = MCPToolUI.from_dict(obj.get("McpToolUi")) + mcp_tool_ui_visibility = MCPToolUIVisibility(obj.get("McpToolUiVisibility")) mcp_unregister_external_client_request = MCPUnregisterExternalClientRequest.from_dict(obj.get("McpUnregisterExternalClientRequest")) memory_configuration = MemoryConfiguration.from_dict(obj.get("MemoryConfiguration")) + metadata_context_attribution_result = MetadataContextAttributionResult.from_dict(obj.get("MetadataContextAttributionResult")) + metadata_context_heaviest_messages_request = MetadataContextHeaviestMessagesRequest.from_dict(obj.get("MetadataContextHeaviestMessagesRequest")) + metadata_context_heaviest_messages_result = MetadataContextHeaviestMessagesResult.from_dict(obj.get("MetadataContextHeaviestMessagesResult")) metadata_context_info_request = MetadataContextInfoRequest.from_dict(obj.get("MetadataContextInfoRequest")) metadata_context_info_result = MetadataContextInfoResult.from_dict(obj.get("MetadataContextInfoResult")) metadata_is_processing_result = MetadataIsProcessingResult.from_dict(obj.get("MetadataIsProcessingResult")) @@ -21989,6 +25517,7 @@ def from_dict(obj: Any) -> 'RPC': metadata_snapshot_remote_metadata_task_type = TaskType(obj.get("MetadataSnapshotRemoteMetadataTaskType")) model = Model.from_dict(obj.get("Model")) model_billing = ModelBilling.from_dict(obj.get("ModelBilling")) + model_billing_promo = ModelBillingPromo.from_dict(obj.get("ModelBillingPromo")) model_billing_token_prices = ModelBillingTokenPrices.from_dict(obj.get("ModelBillingTokenPrices")) model_billing_token_prices_long_context = ModelBillingTokenPricesLongContext.from_dict(obj.get("ModelBillingTokenPricesLongContext")) model_capabilities = ModelCapabilities.from_dict(obj.get("ModelCapabilities")) @@ -22081,6 +25610,7 @@ def from_dict(obj: Any) -> 'RPC': permission_prompt_shown_notification = PermissionPromptShownNotification.from_dict(obj.get("PermissionPromptShownNotification")) permission_request_result = PermissionRequestResult.from_dict(obj.get("PermissionRequestResult")) permission_rules_set = PermissionRulesSet.from_dict(obj.get("PermissionRulesSet")) + permissions_allow_all_mode = PermissionsAllowAllMode(obj.get("PermissionsAllowAllMode")) permissions_configure_additional_content_exclusion_policy = PermissionsConfigureAdditionalContentExclusionPolicy.from_dict(obj.get("PermissionsConfigureAdditionalContentExclusionPolicy")) permissions_configure_additional_content_exclusion_policy_rule = PermissionsConfigureAdditionalContentExclusionPolicyRule.from_dict(obj.get("PermissionsConfigureAdditionalContentExclusionPolicyRule")) permissions_configure_additional_content_exclusion_policy_rule_source = PermissionsConfigureAdditionalContentExclusionPolicyRuleSource.from_dict(obj.get("PermissionsConfigureAdditionalContentExclusionPolicyRuleSource")) @@ -22145,7 +25675,6 @@ def from_dict(obj: Any) -> 'RPC': plugin_update_all_entry = PluginUpdateAllEntry.from_dict(obj.get("PluginUpdateAllEntry")) plugin_update_all_result = PluginUpdateAllResult.from_dict(obj.get("PluginUpdateAllResult")) plugin_update_result = PluginUpdateResult.from_dict(obj.get("PluginUpdateResult")) - poll_spawned_sessions_result = PollSpawnedSessionsResult.from_dict(obj.get("PollSpawnedSessionsResult")) provider_add_request = ProviderAddRequest.from_dict(obj.get("ProviderAddRequest")) provider_add_result = ProviderAddResult.from_dict(obj.get("ProviderAddResult")) provider_config = ProviderConfig.from_dict(obj.get("ProviderConfig")) @@ -22167,12 +25696,24 @@ def from_dict(obj: Any) -> 'RPC': push_attachment_directory = PushAttachmentDirectory.from_dict(obj.get("PushAttachmentDirectory")) push_attachment_file = PushAttachmentFile.from_dict(obj.get("PushAttachmentFile")) push_attachment_file_line_range = PushAttachmentFileLineRange.from_dict(obj.get("PushAttachmentFileLineRange")) + push_attachment_git_hub_actions_job = PushAttachmentGitHubActionsJob.from_dict(obj.get("PushAttachmentGitHubActionsJob")) + push_attachment_git_hub_commit = PushAttachmentGitHubCommit.from_dict(obj.get("PushAttachmentGitHubCommit")) + push_attachment_git_hub_file = PushAttachmentGitHubFile.from_dict(obj.get("PushAttachmentGitHubFile")) + push_attachment_git_hub_file_diff = PushAttachmentGitHubFileDiff.from_dict(obj.get("PushAttachmentGitHubFileDiff")) + push_attachment_git_hub_file_diff_side = PushAttachmentGitHubFileDiffSide.from_dict(obj.get("PushAttachmentGitHubFileDiffSide")) push_attachment_git_hub_reference = PushAttachmentGitHubReference.from_dict(obj.get("PushAttachmentGitHubReference")) push_attachment_git_hub_reference_type = PushAttachmentGitHubReferenceTypeEnum(obj.get("PushAttachmentGitHubReferenceType")) + push_attachment_git_hub_release = PushAttachmentGitHubRelease.from_dict(obj.get("PushAttachmentGitHubRelease")) + push_attachment_git_hub_repository = PushAttachmentGitHubRepository.from_dict(obj.get("PushAttachmentGitHubRepository")) + push_attachment_git_hub_snippet = PushAttachmentGitHubSnippet.from_dict(obj.get("PushAttachmentGitHubSnippet")) + push_attachment_git_hub_tree_comparison = PushAttachmentGitHubTreeComparison.from_dict(obj.get("PushAttachmentGitHubTreeComparison")) + push_attachment_git_hub_tree_comparison_side = PushAttachmentGitHubTreeComparisonSide.from_dict(obj.get("PushAttachmentGitHubTreeComparisonSide")) + push_attachment_git_hub_url = PushAttachmentGitHubURL.from_dict(obj.get("PushAttachmentGitHubUrl")) push_attachment_selection = PushAttachmentSelection.from_dict(obj.get("PushAttachmentSelection")) push_attachment_selection_details = PushAttachmentSelectionDetails.from_dict(obj.get("PushAttachmentSelectionDetails")) push_attachment_selection_details_end = PushAttachmentSelectionDetailsEnd.from_dict(obj.get("PushAttachmentSelectionDetailsEnd")) push_attachment_selection_details_start = PushAttachmentSelectionDetailsStart.from_dict(obj.get("PushAttachmentSelectionDetailsStart")) + push_git_hub_repo_ref = PushGitHubRepoRef.from_dict(obj.get("PushGitHubRepoRef")) queued_command_handled = QueuedCommandHandled.from_dict(obj.get("QueuedCommandHandled")) queued_command_not_handled = QueuedCommandNotHandled.from_dict(obj.get("QueuedCommandNotHandled")) queued_command_result = _load_QueuedCommandResult(obj.get("QueuedCommandResult")) @@ -22220,6 +25761,9 @@ def from_dict(obj: Any) -> 'RPC': secrets_add_filter_values_result = SecretsAddFilterValuesResult.from_dict(obj.get("SecretsAddFilterValuesResult")) send_agent_mode = SendAgentMode(obj.get("SendAgentMode")) send_attachments_to_message_params = SendAttachmentsToMessageParams.from_dict(obj.get("SendAttachmentsToMessageParams")) + send_message_item = SendMessageItem.from_dict(obj.get("SendMessageItem")) + send_messages_request = SendMessagesRequest.from_dict(obj.get("SendMessagesRequest")) + send_messages_result = SendMessagesResult.from_dict(obj.get("SendMessagesResult")) send_mode = SendMode(obj.get("SendMode")) send_request = SendRequest.from_dict(obj.get("SendRequest")) send_result = SendResult.from_dict(obj.get("SendResult")) @@ -22231,6 +25775,7 @@ def from_dict(obj: Any) -> 'RPC': session_auth_status = SessionAuthStatus.from_dict(obj.get("SessionAuthStatus")) session_bulk_delete_result = SessionBulkDeleteResult.from_dict(obj.get("SessionBulkDeleteResult")) session_capability = SessionCapability(obj.get("SessionCapability")) + session_completion_item = SessionCompletionItem.from_dict(obj.get("SessionCompletionItem")) session_context = SessionContext.from_dict(obj.get("SessionContext")) session_context_host_type = HostType(obj.get("SessionContextHostType")) session_enrich_metadata_result = SessionEnrichMetadataResult.from_dict(obj.get("SessionEnrichMetadataResult")) @@ -22243,7 +25788,7 @@ def from_dict(obj: Any) -> 'RPC': session_fs_readdir_request = SessionFSReaddirRequest.from_dict(obj.get("SessionFsReaddirRequest")) session_fs_readdir_result = SessionFSReaddirResult.from_dict(obj.get("SessionFsReaddirResult")) session_fs_readdir_with_types_entry = SessionFSReaddirWithTypesEntry.from_dict(obj.get("SessionFsReaddirWithTypesEntry")) - session_fs_readdir_with_types_entry_type = InstructionDiscoveryPathKind(obj.get("SessionFsReaddirWithTypesEntryType")) + session_fs_readdir_with_types_entry_type = DebugCollectLogsEntryKind(obj.get("SessionFsReaddirWithTypesEntryType")) session_fs_readdir_with_types_request = SessionFSReaddirWithTypesRequest.from_dict(obj.get("SessionFsReaddirWithTypesRequest")) session_fs_readdir_with_types_result = SessionFSReaddirWithTypesResult.from_dict(obj.get("SessionFsReaddirWithTypesResult")) session_fs_read_file_request = SessionFSReadFileRequest.from_dict(obj.get("SessionFsReadFileRequest")) @@ -22276,6 +25821,7 @@ def from_dict(obj: Any) -> 'RPC': session_metadata_snapshot = SessionMetadataSnapshot.from_dict(obj.get("SessionMetadataSnapshot")) session_mode = SessionMode(obj.get("SessionMode")) session_model_list = SessionModelList.from_dict(obj.get("SessionModelList")) + session_model_price_category = SessionModelPriceCategory.from_dict(obj.get("SessionModelPriceCategory")) session_open_options = SessionOpenOptions.from_dict(obj.get("SessionOpenOptions")) session_open_options_additional_content_exclusion_policy = SessionOpenOptionsAdditionalContentExclusionPolicy.from_dict(obj.get("SessionOpenOptionsAdditionalContentExclusionPolicy")) session_open_options_additional_content_exclusion_policy_rule = SessionOpenOptionsAdditionalContentExclusionPolicyRule.from_dict(obj.get("SessionOpenOptionsAdditionalContentExclusionPolicyRule")) @@ -22294,6 +25840,16 @@ def from_dict(obj: Any) -> 'RPC': sessions_enrich_metadata_request = SessionsEnrichMetadataRequest.from_dict(obj.get("SessionsEnrichMetadataRequest")) session_set_credentials_params = SessionSetCredentialsParams.from_dict(obj.get("SessionSetCredentialsParams")) session_set_credentials_result = SessionSetCredentialsResult.from_dict(obj.get("SessionSetCredentialsResult")) + session_settings_built_in_tool_availability_snapshot = SessionSettingsBuiltInToolAvailabilitySnapshot.from_dict(obj.get("SessionSettingsBuiltInToolAvailabilitySnapshot")) + session_settings_evaluate_predicate_request = SessionSettingsEvaluatePredicateRequest.from_dict(obj.get("SessionSettingsEvaluatePredicateRequest")) + session_settings_evaluate_predicate_result = SessionSettingsEvaluatePredicateResult.from_dict(obj.get("SessionSettingsEvaluatePredicateResult")) + session_settings_job_snapshot = SessionSettingsJobSnapshot.from_dict(obj.get("SessionSettingsJobSnapshot")) + session_settings_model_snapshot = SessionSettingsModelSnapshot.from_dict(obj.get("SessionSettingsModelSnapshot")) + session_settings_online_evaluation_snapshot = SessionSettingsOnlineEvaluationSnapshot.from_dict(obj.get("SessionSettingsOnlineEvaluationSnapshot")) + session_settings_predicate_name = SessionSettingsPredicateName(obj.get("SessionSettingsPredicateName")) + session_settings_repo_snapshot = SessionSettingsRepoSnapshot.from_dict(obj.get("SessionSettingsRepoSnapshot")) + session_settings_snapshot = SessionSettingsSnapshot.from_dict(obj.get("SessionSettingsSnapshot")) + session_settings_validation_snapshot = SessionSettingsValidationSnapshot.from_dict(obj.get("SessionSettingsValidationSnapshot")) sessions_find_by_prefix_request = SessionsFindByPrefixRequest.from_dict(obj.get("SessionsFindByPrefixRequest")) sessions_find_by_prefix_result = SessionsFindByPrefixResult.from_dict(obj.get("SessionsFindByPrefixResult")) sessions_find_by_task_id_request = SessionsFindByTaskIDRequest.from_dict(obj.get("SessionsFindByTaskIDRequest")) @@ -22324,8 +25880,6 @@ def from_dict(obj: Any) -> 'RPC': sessions_open_resume_last = SessionsOpenResumeLast.from_dict(obj.get("SessionsOpenResumeLast")) sessions_open_status = SessionsOpenStatus(obj.get("SessionsOpenStatus")) session_source = SessionSource(obj.get("SessionSource")) - sessions_poll_spawned_sessions_event = SessionsPollSpawnedSessionsEvent.from_dict(obj.get("SessionsPollSpawnedSessionsEvent")) - sessions_poll_spawned_sessions_request = SessionsPollSpawnedSessionsRequest.from_dict(obj.get("SessionsPollSpawnedSessionsRequest")) sessions_prune_old_request = SessionsPruneOldRequest.from_dict(obj.get("SessionsPruneOldRequest")) sessions_register_extension_tools_on_session_options = SessionsRegisterExtensionToolsOnSessionOptions.from_dict(obj.get("SessionsRegisterExtensionToolsOnSessionOptions")) sessions_release_lock_request = SessionsReleaseLockRequest.from_dict(obj.get("SessionsReleaseLockRequest")) @@ -22343,6 +25897,7 @@ def from_dict(obj: Any) -> 'RPC': session_telemetry_engagement = SessionTelemetryEngagement.from_dict(obj.get("SessionTelemetryEngagement")) session_update_options_params = SessionUpdateOptionsParams.from_dict(obj.get("SessionUpdateOptionsParams")) session_update_options_result = SessionUpdateOptionsResult.from_dict(obj.get("SessionUpdateOptionsResult")) + session_visibility_status = SessionVisibilityStatus(obj.get("SessionVisibilityStatus")) session_working_directory_context = SessionWorkingDirectoryContext.from_dict(obj.get("SessionWorkingDirectoryContext")) session_working_directory_context_host_type = HostType(obj.get("SessionWorkingDirectoryContextHostType")) shell_cancel_user_requested_request = ShellCancelUserRequestedRequest.from_dict(obj.get("ShellCancelUserRequestedRequest")) @@ -22370,6 +25925,7 @@ def from_dict(obj: Any) -> 'RPC': slash_command_completed_result = SlashCommandCompletedResult.from_dict(obj.get("SlashCommandCompletedResult")) slash_command_info = SlashCommandInfo.from_dict(obj.get("SlashCommandInfo")) slash_command_input = SlashCommandInput.from_dict(obj.get("SlashCommandInput")) + slash_command_input_choice = SlashCommandInputChoice.from_dict(obj.get("SlashCommandInputChoice")) slash_command_input_completion = SlashCommandInputCompletion(obj.get("SlashCommandInputCompletion")) slash_command_invocation_result = _load_SlashCommandInvocationResult(obj.get("SlashCommandInvocationResult")) slash_command_kind = SlashCommandKind(obj.get("SlashCommandKind")) @@ -22444,8 +26000,11 @@ def from_dict(obj: Any) -> 'RPC': ui_handle_pending_result = UIHandlePendingResult.from_dict(obj.get("UIHandlePendingResult")) ui_handle_pending_sampling_request = UIHandlePendingSamplingRequest.from_dict(obj.get("UIHandlePendingSamplingRequest")) ui_handle_pending_sampling_response = from_dict(lambda x: x, obj.get("UIHandlePendingSamplingResponse")) + ui_handle_pending_session_limits_exhausted_request = UIHandlePendingSessionLimitsExhaustedRequest.from_dict(obj.get("UIHandlePendingSessionLimitsExhaustedRequest")) ui_handle_pending_user_input_request = UIHandlePendingUserInputRequest.from_dict(obj.get("UIHandlePendingUserInputRequest")) ui_register_direct_auto_mode_switch_handler_result = UIRegisterDirectAutoModeSwitchHandlerResult.from_dict(obj.get("UIRegisterDirectAutoModeSwitchHandlerResult")) + ui_session_limits_exhausted_response = UISessionLimitsExhaustedResponse.from_dict(obj.get("UISessionLimitsExhaustedResponse")) + ui_session_limits_exhausted_response_action = UISessionLimitsExhaustedResponseAction(obj.get("UISessionLimitsExhaustedResponseAction")) ui_unregister_direct_auto_mode_switch_handler_request = UIUnregisterDirectAutoModeSwitchHandlerRequest.from_dict(obj.get("UIUnregisterDirectAutoModeSwitchHandlerRequest")) ui_unregister_direct_auto_mode_switch_handler_result = UIUnregisterDirectAutoModeSwitchHandlerResult.from_dict(obj.get("UIUnregisterDirectAutoModeSwitchHandlerResult")) ui_user_input_response = UIUserInputResponse.from_dict(obj.get("UIUserInputResponse")) @@ -22459,6 +26018,13 @@ def from_dict(obj: Any) -> 'RPC': usage_metrics_token_detail = UsageMetricsTokenDetail.from_dict(obj.get("UsageMetricsTokenDetail")) user_auth_info = UserAuthInfo.from_dict(obj.get("UserAuthInfo")) user_requested_shell_command_result = UserRequestedShellCommandResult.from_dict(obj.get("UserRequestedShellCommandResult")) + user_setting_metadata = UserSettingMetadata.from_dict(obj.get("UserSettingMetadata")) + user_settings_get_result = UserSettingsGetResult.from_dict(obj.get("UserSettingsGetResult")) + user_settings_set_request = UserSettingsSetRequest.from_dict(obj.get("UserSettingsSetRequest")) + user_settings_set_result = UserSettingsSetResult.from_dict(obj.get("UserSettingsSetResult")) + visibility_get_result = VisibilityGetResult.from_dict(obj.get("VisibilityGetResult")) + visibility_set_request = VisibilitySetRequest.from_dict(obj.get("VisibilitySetRequest")) + visibility_set_result = VisibilitySetResult.from_dict(obj.get("VisibilitySetResult")) workspace_diff_file_change = WorkspaceDiffFileChange.from_dict(obj.get("WorkspaceDiffFileChange")) workspace_diff_file_change_type = WorkspaceDiffFileChangeType(obj.get("WorkspaceDiffFileChangeType")) workspace_diff_mode = WorkspaceDiffMode(obj.get("WorkspaceDiffMode")) @@ -22477,11 +26043,12 @@ def from_dict(obj: Any) -> 'RPC': workspaces_save_large_paste_result = WorkspacesSaveLargePasteResult.from_dict(obj.get("WorkspacesSaveLargePasteResult")) workspace_summary_host_type = HostType(obj.get("WorkspaceSummaryHostType")) workspaces_workspace_details_host_type = HostType(obj.get("WorkspacesWorkspaceDetailsHostType")) + session_context_attribution = from_union([SessionContextAttribution.from_dict, from_none], obj.get("SessionContextAttribution")) session_context_info = from_union([SessionContextInfo.from_dict, from_none], obj.get("SessionContextInfo")) subagent_settings = from_union([SubagentSettings.from_dict, from_none], obj.get("SubagentSettings")) task_progress = from_union([TaskProgress.from_dict, from_none], obj.get("TaskProgress")) workspace_summary = from_union([WorkspaceSummary.from_dict, from_none], obj.get("WorkspaceSummary")) - return RPC(abort_request, abort_result, account_all_users, account_get_all_users_result, account_get_current_auth_result, account_get_quota_request, account_get_quota_result, account_login_request, account_login_result, account_logout_request, account_logout_result, account_quota_snapshot, agent_discovery_path, agent_discovery_path_list, agent_discovery_path_scope, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_registry_live_target_entry, agent_registry_live_target_entry_attention_kind, agent_registry_live_target_entry_kind, agent_registry_live_target_entry_last_terminal_event, agent_registry_live_target_entry_status, agent_registry_log_capture, agent_registry_log_capture_open_error_reason, agent_registry_spawn_error, agent_registry_spawn_permission_mode, agent_registry_spawn_registry_timeout, agent_registry_spawn_request, agent_registry_spawn_result, agent_registry_spawn_spawned, agent_registry_spawn_validation_error, agent_registry_spawn_validation_error_field, agent_registry_spawn_validation_error_reason, agent_reload_result, agents_discover_request, agent_select_request, agent_select_result, agents_get_discovery_paths_request, allow_all_permission_set_result, allow_all_permission_state, api_key_auth_info, auth_info, auth_info_type, cancel_user_requested_shell_command_result, canvas_action, canvas_action_invoke_request, canvas_action_invoke_result, canvas_close_request, canvas_host_context, canvas_host_context_capabilities, canvas_json_schema, canvas_list, canvas_list_open_result, canvas_open_request, canvas_provider_close_request, canvas_provider_invoke_action_request, canvas_provider_open_request, canvas_provider_open_result, canvas_session_context, capi_session_options, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, configure_session_extensions_params, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, current_tool_metadata, discovered_canvas, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, event_log_types, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_context_push_input, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_request, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, installed_plugin, installed_plugin_info, installed_plugin_source, installed_plugin_source_git_hub, installed_plugin_source_local, installed_plugin_source_url, instruction_discovery_path, instruction_discovery_path_kind, instruction_discovery_path_list, instruction_discovery_path_location, instructions_discover_request, instructions_get_discovery_paths_request, instructions_get_sources_result, instruction_source, instruction_source_location, instruction_source_type, llm_inference_headers, llm_inference_http_request_chunk_request, llm_inference_http_request_chunk_result, llm_inference_http_request_start_request, llm_inference_http_request_start_result, llm_inference_http_request_start_transport, llm_inference_http_response_chunk_error, llm_inference_http_response_chunk_request, llm_inference_http_response_chunk_result, llm_inference_http_response_start_request, llm_inference_http_response_start_result, llm_inference_set_provider_result, local_session_metadata_value, log_request, log_result, lsp_initialize_request, marketplace_add_result, marketplace_browse_result, marketplace_info, marketplace_list_result, marketplace_plugin_info, marketplace_refresh_entry, marketplace_refresh_result, marketplace_remove_result, mcp_allowed_server, mcp_apps_call_tool_request, mcp_apps_diagnose_capability, mcp_apps_diagnose_request, mcp_apps_diagnose_result, mcp_apps_diagnose_server, mcp_apps_host_context, mcp_apps_host_context_details, mcp_apps_host_context_details_available_display_mode, mcp_apps_host_context_details_display_mode, mcp_apps_host_context_details_platform, mcp_apps_host_context_details_theme, mcp_apps_list_tools_request, mcp_apps_list_tools_result, mcp_apps_read_resource_request, mcp_apps_read_resource_result, mcp_apps_resource_content, mcp_apps_set_host_context_details, mcp_apps_set_host_context_details_available_display_mode, mcp_apps_set_host_context_details_display_mode, mcp_apps_set_host_context_details_platform, mcp_apps_set_host_context_details_theme, mcp_apps_set_host_context_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_configure_git_hub_request, mcp_configure_git_hub_result, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_filtered_server, mcp_host_state, mcp_is_server_running_request, mcp_is_server_running_result, mcp_list_tools_request, mcp_list_tools_result, mcp_oauth_handle_pending_request, mcp_oauth_handle_pending_result, mcp_oauth_login_grant_type, mcp_oauth_login_request, mcp_oauth_login_result, mcp_oauth_pending_request_response, mcp_oauth_respond_request, mcp_oauth_respond_result, mcp_register_external_client_request, mcp_reload_with_config_request, mcp_remove_git_hub_result, mcp_restart_server_request, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_auth_config, mcp_server_auth_config_redirect_port, mcp_server_config, mcp_server_config_defer_tools, mcp_server_config_http, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_failure_info, mcp_server_list, mcp_server_needs_auth_info, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, mcp_start_server_request, mcp_start_servers_result, mcp_stop_server_request, mcp_tools, mcp_unregister_external_client_request, memory_configuration, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_token_prices, model_billing_token_prices_long_context, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_list_request, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, named_provider_config, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, open_canvas_instance, options_update_additional_content_exclusion_policy, options_update_additional_content_exclusion_policy_rule, options_update_additional_content_exclusion_policy_rule_source, options_update_additional_content_exclusion_policy_scope, options_update_context_tier, options_update_env_value_mode, options_update_reasoning_summary, options_update_tool_filter_precedence, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_get_allow_all_request, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_allow_all_request, permissions_set_allow_all_source, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_read_sql_todos_result, plan_read_sql_todos_with_dependencies_result, plan_sql_todo_dependency, plan_sql_todos_row, plan_update_request, plugin, plugin_install_result, plugin_list, plugin_list_result, plugins_disable_request, plugins_enable_request, plugins_install_request, plugins_marketplaces_add_request, plugins_marketplaces_browse_request, plugins_marketplaces_refresh_request, plugins_marketplaces_remove_request, plugins_reload_request, plugins_uninstall_request, plugins_update_request, plugin_update_all_entry, plugin_update_all_result, plugin_update_result, poll_spawned_sessions_result, provider_add_request, provider_add_result, provider_config, provider_config_azure, provider_config_transport, provider_config_type, provider_config_wire_api, provider_endpoint, provider_endpoint_transport, provider_endpoint_type, provider_endpoint_wire_api, provider_get_endpoint_request, provider_model_config, provider_session_token, provider_token_acquire_request, provider_token_acquire_result, push_attachment, push_attachment_blob, push_attachment_directory, push_attachment_file, push_attachment_file_line_range, push_attachment_git_hub_reference, push_attachment_git_hub_reference_type, push_attachment_selection, push_attachment_selection_details, push_attachment_selection_details_end, push_attachment_selection_details_start, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, register_extension_tools_params, register_extension_tools_result, release_event_interest_params, remote_control_config, remote_control_config_existing_mc_session, remote_control_status, remote_control_status_active, remote_control_status_connecting, remote_control_status_error, remote_control_status_off, remote_control_status_result, remote_control_stop_result, remote_control_transfer_result, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_metadata_repository, remote_session_metadata_task_type, remote_session_metadata_value, remote_session_mode, remote_session_repository, sandbox_config, sandbox_config_user_policy, sandbox_config_user_policy_experimental, sandbox_config_user_policy_experimental_seatbelt, sandbox_config_user_policy_filesystem, sandbox_config_user_policy_network, sandbox_config_user_policy_seatbelt, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, secrets_add_filter_values_request, secrets_add_filter_values_result, send_agent_mode, send_attachments_to_message_params, send_mode, send_request, send_result, server_agent_list, server_instruction_source_list, server_skill, server_skill_list, session_activity, session_auth_status, session_bulk_delete_result, session_capability, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_git_hub, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_entry, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_mcp_apps_call_tool_result, session_metadata_snapshot, session_mode, session_model_list, session_open_options, session_open_options_additional_content_exclusion_policy, session_open_options_additional_content_exclusion_policy_rule, session_open_options_additional_content_exclusion_policy_rule_source, session_open_options_additional_content_exclusion_policy_scope, session_open_options_env_value_mode, session_open_options_reasoning_summary, session_open_params, session_open_result, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_board_entry_count_request, sessions_get_board_entry_count_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_open_attach, sessions_open_cloud, sessions_open_create, sessions_open_handoff, sessions_open_handoff_task_type, sessions_open_progress, sessions_open_progress_status, sessions_open_progress_step, sessions_open_remote, sessions_open_resume, sessions_open_resume_last, sessions_open_status, session_source, sessions_poll_spawned_sessions_event, sessions_poll_spawned_sessions_request, sessions_prune_old_request, sessions_register_extension_tools_on_session_options, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, sessions_set_remote_control_steering_request, sessions_start_remote_control_request, sessions_stop_remote_control_request, sessions_transfer_remote_control_request, session_telemetry_engagement, session_update_options_params, session_update_options_result, session_working_directory_context, session_working_directory_context_host_type, shell_cancel_user_requested_request, shell_exec_request, shell_exec_result, shell_execute_user_requested_request, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_discovery_path, skill_discovery_path_list, skill_discovery_scope, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_discovery_paths_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, subagent_settings_entry, subagent_settings_entry_context_tier, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_get_current_metadata_result, tools_initialize_and_validate_result, tools_list_request, tools_update_subagent_settings_result, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_ephemeral_query_request, ui_ephemeral_query_result, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, update_subagent_settings_request, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_requested_shell_command_result, workspace_diff_file_change, workspace_diff_file_change_type, workspace_diff_mode, workspace_diff_result, workspaces_checkpoints, workspaces_create_file_request, workspaces_diff_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_info, subagent_settings, task_progress, workspace_summary) + return RPC(abort_request, abort_result, account_all_users, account_get_all_users_result, account_get_current_auth_result, account_get_quota_request, account_get_quota_result, account_login_request, account_login_result, account_logout_request, account_logout_result, account_quota_snapshot, adaptive_thinking_support, agent_discovery_path, agent_discovery_path_list, agent_discovery_path_scope, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_registry_live_target_entry, agent_registry_live_target_entry_attention_kind, agent_registry_live_target_entry_kind, agent_registry_live_target_entry_last_terminal_event, agent_registry_live_target_entry_status, agent_registry_log_capture, agent_registry_log_capture_open_error_reason, agent_registry_spawn_error, agent_registry_spawn_permission_mode, agent_registry_spawn_registry_timeout, agent_registry_spawn_request, agent_registry_spawn_result, agent_registry_spawn_spawned, agent_registry_spawn_validation_error, agent_registry_spawn_validation_error_field, agent_registry_spawn_validation_error_reason, agent_reload_result, agents_discover_request, agent_select_request, agent_select_result, agents_get_discovery_paths_request, allow_all_permission_set_result, allow_all_permission_state, api_key_auth_info, auth_info, auth_info_type, cancel_user_requested_shell_command_result, canvas_action, canvas_action_invoke_request, canvas_action_invoke_result, canvas_close_request, canvas_host_context, canvas_host_context_capabilities, canvas_json_schema, canvas_list, canvas_list_open_result, canvas_open_request, canvas_provider_close_request, canvas_provider_invoke_action_request, canvas_provider_open_request, canvas_provider_open_result, canvas_session_context, capi_session_options, command_list, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, completions_get_trigger_characters_result, completions_request_request, completions_request_result, configure_session_extensions_params, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_filter_mode, context_heaviest_message, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, current_tool_metadata, debug_collect_logs_collected_entry, debug_collect_logs_destination, debug_collect_logs_entry, debug_collect_logs_entry_kind, debug_collect_logs_include, debug_collect_logs_redaction, debug_collect_logs_request, debug_collect_logs_result, debug_collect_logs_result_kind, debug_collect_logs_skipped_entry, debug_collect_logs_source, discovered_canvas, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, event_log_types, events_agent_scope, events_cursor_status, events_read_result, execute_command_params, execute_command_result, extension, extension_context_push_input, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_shell_exit, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, git_hub_telemetry_client_info, git_hub_telemetry_event, git_hub_telemetry_notification, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_compact_context_window, history_compact_request, history_compact_result, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, hook_invoke_request, hook_invoke_response, hook_type, installed_plugin, installed_plugin_info, installed_plugin_source, installed_plugin_source_git_hub, installed_plugin_source_local, installed_plugin_source_url, instruction_discovery_path, instruction_discovery_path_kind, instruction_discovery_path_list, instruction_discovery_path_location, instructions_discover_request, instructions_get_discovery_paths_request, instructions_get_sources_result, instruction_source, instruction_source_location, instruction_source_type, llm_inference_headers, llm_inference_http_request_chunk_request, llm_inference_http_request_chunk_result, llm_inference_http_request_start_request, llm_inference_http_request_start_result, llm_inference_http_request_start_transport, llm_inference_http_response_chunk_error, llm_inference_http_response_chunk_request, llm_inference_http_response_chunk_result, llm_inference_http_response_start_request, llm_inference_http_response_start_result, llm_inference_set_provider_result, local_session_metadata_value, log_request, log_result, lsp_initialize_request, marketplace_add_result, marketplace_browse_result, marketplace_info, marketplace_list_result, marketplace_plugin_info, marketplace_refresh_entry, marketplace_refresh_result, marketplace_remove_result, mcp_allowed_server, mcp_apps_call_tool_request, mcp_apps_diagnose_capability, mcp_apps_diagnose_request, mcp_apps_diagnose_result, mcp_apps_diagnose_server, mcp_apps_host_context, mcp_apps_host_context_details, mcp_apps_host_context_details_available_display_mode, mcp_apps_host_context_details_display_mode, mcp_apps_host_context_details_platform, mcp_apps_host_context_details_theme, mcp_apps_list_tools_request, mcp_apps_list_tools_result, mcp_apps_read_resource_request, mcp_apps_read_resource_result, mcp_apps_resource_content, mcp_apps_set_host_context_details, mcp_apps_set_host_context_details_available_display_mode, mcp_apps_set_host_context_details_display_mode, mcp_apps_set_host_context_details_platform, mcp_apps_set_host_context_details_theme, mcp_apps_set_host_context_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_configure_git_hub_request, mcp_configure_git_hub_result, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_filtered_server, mcp_headers_handle_pending_headers_refresh_request, mcp_headers_handle_pending_headers_refresh_request_request, mcp_headers_handle_pending_headers_refresh_request_result, mcp_host_state, mcp_is_server_running_request, mcp_is_server_running_result, mcp_list_tools_request, mcp_list_tools_result, mcp_oauth_handle_pending_request, mcp_oauth_handle_pending_result, mcp_oauth_login_grant_type, mcp_oauth_login_request, mcp_oauth_login_result, mcp_oauth_pending_request_response, mcp_register_external_client_request, mcp_reload_with_config_request, mcp_remove_git_hub_result, mcp_resource, mcp_resource_annotations, mcp_resource_content, mcp_resource_icon, mcp_resources_list_request, mcp_resources_list_result, mcp_resources_list_templates_request, mcp_resources_list_templates_result, mcp_resources_read_request, mcp_resources_read_result, mcp_resource_template, mcp_restart_server_request, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_auth_config, mcp_server_auth_config_redirect_port, mcp_server_config, mcp_server_config_defer_tools, mcp_server_config_http, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_failure_info, mcp_server_list, mcp_server_needs_auth_info, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, mcp_start_server_request, mcp_start_servers_result, mcp_stop_server_request, mcp_tools, mcp_tool_ui, mcp_tool_ui_visibility, mcp_unregister_external_client_request, memory_configuration, metadata_context_attribution_result, metadata_context_heaviest_messages_request, metadata_context_heaviest_messages_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, model, model_billing, model_billing_promo, model_billing_token_prices, model_billing_token_prices_long_context, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_list_request, model_picker_category, model_picker_price_category, model_policy, model_policy_state, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_to_request, model_switch_to_result, mode_set_request, named_provider_config, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, open_canvas_instance, options_update_additional_content_exclusion_policy, options_update_additional_content_exclusion_policy_rule, options_update_additional_content_exclusion_policy_rule_source, options_update_additional_content_exclusion_policy_scope, options_update_context_tier, options_update_env_value_mode, options_update_reasoning_summary, options_update_tool_filter_precedence, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_reject, permission_decision_request, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_rules_set, permissions_allow_all_mode, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_get_allow_all_request, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_allow_all_request, permissions_set_allow_all_source, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_read_sql_todos_result, plan_read_sql_todos_with_dependencies_result, plan_sql_todo_dependency, plan_sql_todos_row, plan_update_request, plugin, plugin_install_result, plugin_list, plugin_list_result, plugins_disable_request, plugins_enable_request, plugins_install_request, plugins_marketplaces_add_request, plugins_marketplaces_browse_request, plugins_marketplaces_refresh_request, plugins_marketplaces_remove_request, plugins_reload_request, plugins_uninstall_request, plugins_update_request, plugin_update_all_entry, plugin_update_all_result, plugin_update_result, provider_add_request, provider_add_result, provider_config, provider_config_azure, provider_config_transport, provider_config_type, provider_config_wire_api, provider_endpoint, provider_endpoint_transport, provider_endpoint_type, provider_endpoint_wire_api, provider_get_endpoint_request, provider_model_config, provider_session_token, provider_token_acquire_request, provider_token_acquire_result, push_attachment, push_attachment_blob, push_attachment_directory, push_attachment_file, push_attachment_file_line_range, push_attachment_git_hub_actions_job, push_attachment_git_hub_commit, push_attachment_git_hub_file, push_attachment_git_hub_file_diff, push_attachment_git_hub_file_diff_side, push_attachment_git_hub_reference, push_attachment_git_hub_reference_type, push_attachment_git_hub_release, push_attachment_git_hub_repository, push_attachment_git_hub_snippet, push_attachment_git_hub_tree_comparison, push_attachment_git_hub_tree_comparison_side, push_attachment_git_hub_url, push_attachment_selection, push_attachment_selection_details, push_attachment_selection_details_end, push_attachment_selection_details_start, push_git_hub_repo_ref, queued_command_handled, queued_command_not_handled, queued_command_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_most_recent_result, register_event_interest_params, register_event_interest_result, register_extension_tools_params, register_extension_tools_result, release_event_interest_params, remote_control_config, remote_control_config_existing_mc_session, remote_control_status, remote_control_status_active, remote_control_status_connecting, remote_control_status_error, remote_control_status_off, remote_control_status_result, remote_control_stop_result, remote_control_transfer_result, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_metadata_repository, remote_session_metadata_task_type, remote_session_metadata_value, remote_session_mode, remote_session_repository, sandbox_config, sandbox_config_user_policy, sandbox_config_user_policy_experimental, sandbox_config_user_policy_experimental_seatbelt, sandbox_config_user_policy_filesystem, sandbox_config_user_policy_network, sandbox_config_user_policy_seatbelt, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, secrets_add_filter_values_request, secrets_add_filter_values_result, send_agent_mode, send_attachments_to_message_params, send_message_item, send_messages_request, send_messages_result, send_mode, send_request, send_result, server_agent_list, server_instruction_source_list, server_skill, server_skill_list, session_activity, session_auth_status, session_bulk_delete_result, session_capability, session_completion_item, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_git_hub, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_entry, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_mcp_apps_call_tool_result, session_metadata_snapshot, session_mode, session_model_list, session_model_price_category, session_open_options, session_open_options_additional_content_exclusion_policy, session_open_options_additional_content_exclusion_policy_rule, session_open_options_additional_content_exclusion_policy_rule_source, session_open_options_additional_content_exclusion_policy_scope, session_open_options_env_value_mode, session_open_options_reasoning_summary, session_open_params, session_open_result, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, session_settings_built_in_tool_availability_snapshot, session_settings_evaluate_predicate_request, session_settings_evaluate_predicate_result, session_settings_job_snapshot, session_settings_model_snapshot, session_settings_online_evaluation_snapshot, session_settings_predicate_name, session_settings_repo_snapshot, session_settings_snapshot, session_settings_validation_snapshot, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_board_entry_count_request, sessions_get_board_entry_count_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_open_attach, sessions_open_cloud, sessions_open_create, sessions_open_handoff, sessions_open_handoff_task_type, sessions_open_progress, sessions_open_progress_status, sessions_open_progress_step, sessions_open_remote, sessions_open_resume, sessions_open_resume_last, sessions_open_status, session_source, sessions_prune_old_request, sessions_register_extension_tools_on_session_options, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, sessions_set_remote_control_steering_request, sessions_start_remote_control_request, sessions_stop_remote_control_request, sessions_transfer_remote_control_request, session_telemetry_engagement, session_update_options_params, session_update_options_result, session_visibility_status, session_working_directory_context, session_working_directory_context_host_type, shell_cancel_user_requested_request, shell_exec_request, shell_exec_result, shell_execute_user_requested_request, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_discovery_path, skill_discovery_path_list, skill_discovery_scope, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_discovery_paths_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_choice, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_text_result, subagent_settings_entry, subagent_settings_entry_context_tier, task_agent_info, task_agent_progress, task_execution_mode, task_info, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, tool, tool_list, tools_get_current_metadata_result, tools_initialize_and_validate_result, tools_list_request, tools_update_subagent_settings_result, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_ephemeral_query_request, ui_ephemeral_query_result, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_session_limits_exhausted_request, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_session_limits_exhausted_response, ui_session_limits_exhausted_response_action, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, update_subagent_settings_request, usage_get_metrics_result, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_requested_shell_command_result, user_setting_metadata, user_settings_get_result, user_settings_set_request, user_settings_set_result, visibility_get_result, visibility_set_request, visibility_set_result, workspace_diff_file_change, workspace_diff_file_change_type, workspace_diff_mode, workspace_diff_result, workspaces_checkpoints, workspaces_create_file_request, workspaces_diff_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspace_summary_host_type, workspaces_workspace_details_host_type, session_context_attribution, session_context_info, subagent_settings, task_progress, workspace_summary) def to_dict(self) -> dict: result: dict = {} @@ -22497,6 +26064,7 @@ def to_dict(self) -> dict: result["AccountLogoutRequest"] = to_class(AccountLogoutRequest, self.account_logout_request) result["AccountLogoutResult"] = to_class(AccountLogoutResult, self.account_logout_result) result["AccountQuotaSnapshot"] = to_class(AccountQuotaSnapshot, self.account_quota_snapshot) + result["AdaptiveThinkingSupport"] = to_enum(AdaptiveThinkingSupport, self.adaptive_thinking_support) result["AgentDiscoveryPath"] = to_class(AgentDiscoveryPath, self.agent_discovery_path) result["AgentDiscoveryPathList"] = to_class(AgentDiscoveryPathList, self.agent_discovery_path_list) result["AgentDiscoveryPathScope"] = to_enum(AgentDiscoveryPathScope, self.agent_discovery_path_scope) @@ -22554,6 +26122,9 @@ def to_dict(self) -> dict: result["CommandsListRequest"] = to_class(CommandsListRequest, self.commands_list_request) result["CommandsRespondToQueuedCommandRequest"] = to_class(CommandsRespondToQueuedCommandRequest, self.commands_respond_to_queued_command_request) result["CommandsRespondToQueuedCommandResult"] = to_class(CommandsRespondToQueuedCommandResult, self.commands_respond_to_queued_command_result) + result["CompletionsGetTriggerCharactersResult"] = to_class(CompletionsGetTriggerCharactersResult, self.completions_get_trigger_characters_result) + result["CompletionsRequestRequest"] = to_class(CompletionsRequestRequest, self.completions_request_request) + result["CompletionsRequestResult"] = to_class(CompletionsRequestResult, self.completions_request_result) result["ConfigureSessionExtensionsParams"] = to_class(_ConfigureSessionExtensionsParams, self.configure_session_extensions_params) result["ConnectedRemoteSessionMetadata"] = to_class(ConnectedRemoteSessionMetadata, self.connected_remote_session_metadata) result["ConnectedRemoteSessionMetadataKind"] = to_enum(ConnectedRemoteSessionMetadataKind, self.connected_remote_session_metadata_kind) @@ -22562,6 +26133,7 @@ def to_dict(self) -> dict: result["ConnectRequest"] = to_class(_ConnectRequest, self.connect_request) result["ConnectResult"] = to_class(_ConnectResult, self.connect_result) result["ContentFilterMode"] = to_enum(ContentFilterMode, self.content_filter_mode) + result["ContextHeaviestMessage"] = to_class(ContextHeaviestMessage, self.context_heaviest_message) result["CopilotApiTokenAuthInfo"] = to_class(CopilotAPITokenAuthInfo, self.copilot_api_token_auth_info) result["CopilotUserResponse"] = to_class(CopilotUserResponse, self.copilot_user_response) result["CopilotUserResponseEndpoints"] = to_class(CopilotUserResponseEndpoints, self.copilot_user_response_endpoints) @@ -22571,6 +26143,17 @@ def to_dict(self) -> dict: result["CopilotUserResponseQuotaSnapshotsPremiumInteractions"] = to_class(CopilotUserResponseQuotaSnapshotsPremiumInteractions, self.copilot_user_response_quota_snapshots_premium_interactions) result["CurrentModel"] = to_class(CurrentModel, self.current_model) result["CurrentToolMetadata"] = to_class(CurrentToolMetadata, self.current_tool_metadata) + result["DebugCollectLogsCollectedEntry"] = to_class(DebugCollectLogsCollectedEntry, self.debug_collect_logs_collected_entry) + result["DebugCollectLogsDestination"] = to_class(DebugCollectLogsDestination, self.debug_collect_logs_destination) + result["DebugCollectLogsEntry"] = to_class(DebugCollectLogsEntry, self.debug_collect_logs_entry) + result["DebugCollectLogsEntryKind"] = to_enum(DebugCollectLogsEntryKind, self.debug_collect_logs_entry_kind) + result["DebugCollectLogsInclude"] = to_class(DebugCollectLogsInclude, self.debug_collect_logs_include) + result["DebugCollectLogsRedaction"] = to_enum(DebugCollectLogsRedaction, self.debug_collect_logs_redaction) + result["DebugCollectLogsRequest"] = to_class(DebugCollectLogsRequest, self.debug_collect_logs_request) + result["DebugCollectLogsResult"] = to_class(DebugCollectLogsResult, self.debug_collect_logs_result) + result["DebugCollectLogsResultKind"] = to_enum(DebugCollectLogsResultKind, self.debug_collect_logs_result_kind) + result["DebugCollectLogsSkippedEntry"] = to_class(DebugCollectLogsSkippedEntry, self.debug_collect_logs_skipped_entry) + result["DebugCollectLogsSource"] = to_enum(DebugCollectLogsSource, self.debug_collect_logs_source) result["DiscoveredCanvas"] = to_class(DiscoveredCanvas, self.discovered_canvas) result["DiscoveredMcpServer"] = to_class(DiscoveredMCPServer, self.discovered_mcp_server) result["DiscoveredMcpServerType"] = to_enum(DiscoveredMCPServerType, self.discovered_mcp_server_type) @@ -22605,6 +26188,7 @@ def to_dict(self) -> dict: result["ExternalToolTextResultForLlmContentResourceLink"] = to_class(ExternalToolTextResultForLlmContentResourceLink, self.external_tool_text_result_for_llm_content_resource_link) result["ExternalToolTextResultForLlmContentResourceLinkIcon"] = to_class(ExternalToolTextResultForLlmContentResourceLinkIcon, self.external_tool_text_result_for_llm_content_resource_link_icon) result["ExternalToolTextResultForLlmContentResourceLinkIconTheme"] = to_enum(Theme, self.external_tool_text_result_for_llm_content_resource_link_icon_theme) + result["ExternalToolTextResultForLlmContentShellExit"] = to_class(ExternalToolTextResultForLlmContentShellExit, self.external_tool_text_result_for_llm_content_shell_exit) result["ExternalToolTextResultForLlmContentTerminal"] = to_class(ExternalToolTextResultForLlmContentTerminal, self.external_tool_text_result_for_llm_content_terminal) result["ExternalToolTextResultForLlmContentText"] = to_class(ExternalToolTextResultForLlmContentText, self.external_tool_text_result_for_llm_content_text) result["FilterMapping"] = from_union([lambda x: from_dict(lambda x: to_enum(ContentFilterMode, x), x), lambda x: to_enum(ContentFilterMode, x)], self.filter_mapping) @@ -22614,6 +26198,9 @@ def to_dict(self) -> dict: result["FolderTrustCheckParams"] = to_class(FolderTrustCheckParams, self.folder_trust_check_params) result["FolderTrustCheckResult"] = to_class(FolderTrustCheckResult, self.folder_trust_check_result) result["GhCliAuthInfo"] = to_class(GhCLIAuthInfo, self.gh_cli_auth_info) + result["GitHubTelemetryClientInfo"] = to_class(GitHubTelemetryClientInfo, self.git_hub_telemetry_client_info) + result["GitHubTelemetryEvent"] = to_class(GitHubTelemetryEvent, self.git_hub_telemetry_event) + result["GitHubTelemetryNotification"] = to_class(GitHubTelemetryNotification, self.git_hub_telemetry_notification) result["HandlePendingToolCallRequest"] = to_class(HandlePendingToolCallRequest, self.handle_pending_tool_call_request) result["HandlePendingToolCallResult"] = to_class(HandlePendingToolCallResult, self.handle_pending_tool_call_result) result["HistoryAbortManualCompactionResult"] = to_class(HistoryAbortManualCompactionResult, self.history_abort_manual_compaction_result) @@ -22625,6 +26212,9 @@ def to_dict(self) -> dict: result["HistoryTruncateRequest"] = to_class(HistoryTruncateRequest, self.history_truncate_request) result["HistoryTruncateResult"] = to_class(HistoryTruncateResult, self.history_truncate_result) result["HMACAuthInfo"] = to_class(HMACAuthInfo, self.hmac_auth_info) + result["HookInvokeRequest"] = to_class(_HookInvokeRequest, self.hook_invoke_request) + result["HookInvokeResponse"] = to_class(_HookInvokeResponse, self.hook_invoke_response) + result["HookType"] = to_enum(_HookType, self.hook_type) result["InstalledPlugin"] = to_class(InstalledPlugin, self.installed_plugin) result["InstalledPluginInfo"] = to_class(InstalledPluginInfo, self.installed_plugin_info) result["InstalledPluginSource"] = from_union([lambda x: to_class(InstalledPluginSource, x), from_str], self.installed_plugin_source) @@ -22632,7 +26222,7 @@ def to_dict(self) -> dict: result["InstalledPluginSourceLocal"] = to_class(InstalledPluginSourceLocal, self.installed_plugin_source_local) result["InstalledPluginSourceUrl"] = to_class(InstalledPluginSourceURL, self.installed_plugin_source_url) result["InstructionDiscoveryPath"] = to_class(InstructionDiscoveryPath, self.instruction_discovery_path) - result["InstructionDiscoveryPathKind"] = to_enum(InstructionDiscoveryPathKind, self.instruction_discovery_path_kind) + result["InstructionDiscoveryPathKind"] = to_enum(DebugCollectLogsEntryKind, self.instruction_discovery_path_kind) result["InstructionDiscoveryPathList"] = to_class(InstructionDiscoveryPathList, self.instruction_discovery_path_list) result["InstructionDiscoveryPathLocation"] = to_enum(InstructionLocation, self.instruction_discovery_path_location) result["InstructionsDiscoverRequest"] = to_class(InstructionsDiscoverRequest, self.instructions_discover_request) @@ -22706,6 +26296,9 @@ def to_dict(self) -> dict: result["McpExecuteSamplingRequest"] = from_dict(lambda x: x, self.mcp_execute_sampling_request) result["McpExecuteSamplingResult"] = from_dict(lambda x: x, self.mcp_execute_sampling_result) result["McpFilteredServer"] = to_class(MCPFilteredServer, self.mcp_filtered_server) + result["McpHeadersHandlePendingHeadersRefreshRequest"] = to_class(MCPHeadersHandlePendingHeadersRefreshRequest, self.mcp_headers_handle_pending_headers_refresh_request) + result["McpHeadersHandlePendingHeadersRefreshRequestRequest"] = to_class(MCPHeadersHandlePendingHeadersRefreshRequestRequest, self.mcp_headers_handle_pending_headers_refresh_request_request) + result["McpHeadersHandlePendingHeadersRefreshRequestResult"] = to_class(MCPHeadersHandlePendingHeadersRefreshRequestResult, self.mcp_headers_handle_pending_headers_refresh_request_result) result["McpHostState"] = to_class(MCPHostState, self.mcp_host_state) result["McpIsServerRunningRequest"] = to_class(MCPIsServerRunningRequest, self.mcp_is_server_running_request) result["McpIsServerRunningResult"] = to_class(MCPIsServerRunningResult, self.mcp_is_server_running_result) @@ -22717,11 +26310,20 @@ def to_dict(self) -> dict: result["McpOauthLoginRequest"] = to_class(MCPOauthLoginRequest, self.mcp_oauth_login_request) result["McpOauthLoginResult"] = to_class(MCPOauthLoginResult, self.mcp_oauth_login_result) result["McpOauthPendingRequestResponse"] = to_class(MCPOauthPendingRequestResponse, self.mcp_oauth_pending_request_response) - result["McpOauthRespondRequest"] = to_class(MCPOauthRespondRequest, self.mcp_oauth_respond_request) - result["McpOauthRespondResult"] = to_class(MCPOauthRespondResult, self.mcp_oauth_respond_result) result["McpRegisterExternalClientRequest"] = to_class(MCPRegisterExternalClientRequest, self.mcp_register_external_client_request) result["McpReloadWithConfigRequest"] = to_class(MCPReloadWithConfigRequest, self.mcp_reload_with_config_request) result["McpRemoveGitHubResult"] = to_class(MCPRemoveGitHubResult, self.mcp_remove_git_hub_result) + result["McpResource"] = to_class(MCPResource, self.mcp_resource) + result["McpResourceAnnotations"] = to_class(MCPResourceAnnotations, self.mcp_resource_annotations) + result["McpResourceContent"] = to_class(MCPResourceContent, self.mcp_resource_content) + result["McpResourceIcon"] = to_class(MCPResourceIcon, self.mcp_resource_icon) + result["McpResourcesListRequest"] = to_class(MCPResourcesListRequest, self.mcp_resources_list_request) + result["McpResourcesListResult"] = to_class(MCPResourcesListResult, self.mcp_resources_list_result) + result["McpResourcesListTemplatesRequest"] = to_class(MCPResourcesListTemplatesRequest, self.mcp_resources_list_templates_request) + result["McpResourcesListTemplatesResult"] = to_class(MCPResourcesListTemplatesResult, self.mcp_resources_list_templates_result) + result["McpResourcesReadRequest"] = to_class(MCPResourcesReadRequest, self.mcp_resources_read_request) + result["McpResourcesReadResult"] = to_class(MCPResourcesReadResult, self.mcp_resources_read_result) + result["McpResourceTemplate"] = to_class(MCPResourceTemplate, self.mcp_resource_template) result["McpRestartServerRequest"] = to_class(MCPRestartServerRequest, self.mcp_restart_server_request) result["McpSamplingExecutionAction"] = to_enum(MCPSamplingExecutionAction, self.mcp_sampling_execution_action) result["McpSamplingExecutionResult"] = to_class(MCPSamplingExecutionResult, self.mcp_sampling_execution_result) @@ -22744,8 +26346,13 @@ def to_dict(self) -> dict: result["McpStartServersResult"] = to_class(MCPStartServersResult, self.mcp_start_servers_result) result["McpStopServerRequest"] = to_class(MCPStopServerRequest, self.mcp_stop_server_request) result["McpTools"] = to_class(MCPTools, self.mcp_tools) + result["McpToolUi"] = to_class(MCPToolUI, self.mcp_tool_ui) + result["McpToolUiVisibility"] = to_enum(MCPToolUIVisibility, self.mcp_tool_ui_visibility) result["McpUnregisterExternalClientRequest"] = to_class(MCPUnregisterExternalClientRequest, self.mcp_unregister_external_client_request) result["MemoryConfiguration"] = to_class(MemoryConfiguration, self.memory_configuration) + result["MetadataContextAttributionResult"] = to_class(MetadataContextAttributionResult, self.metadata_context_attribution_result) + result["MetadataContextHeaviestMessagesRequest"] = to_class(MetadataContextHeaviestMessagesRequest, self.metadata_context_heaviest_messages_request) + result["MetadataContextHeaviestMessagesResult"] = to_class(MetadataContextHeaviestMessagesResult, self.metadata_context_heaviest_messages_result) result["MetadataContextInfoRequest"] = to_class(MetadataContextInfoRequest, self.metadata_context_info_request) result["MetadataContextInfoResult"] = to_class(MetadataContextInfoResult, self.metadata_context_info_result) result["MetadataIsProcessingResult"] = to_class(MetadataIsProcessingResult, self.metadata_is_processing_result) @@ -22761,6 +26368,7 @@ def to_dict(self) -> dict: result["MetadataSnapshotRemoteMetadataTaskType"] = to_enum(TaskType, self.metadata_snapshot_remote_metadata_task_type) result["Model"] = to_class(Model, self.model) result["ModelBilling"] = to_class(ModelBilling, self.model_billing) + result["ModelBillingPromo"] = to_class(ModelBillingPromo, self.model_billing_promo) result["ModelBillingTokenPrices"] = to_class(ModelBillingTokenPrices, self.model_billing_token_prices) result["ModelBillingTokenPricesLongContext"] = to_class(ModelBillingTokenPricesLongContext, self.model_billing_token_prices_long_context) result["ModelCapabilities"] = to_class(ModelCapabilities, self.model_capabilities) @@ -22853,6 +26461,7 @@ def to_dict(self) -> dict: result["PermissionPromptShownNotification"] = to_class(PermissionPromptShownNotification, self.permission_prompt_shown_notification) result["PermissionRequestResult"] = to_class(PermissionRequestResult, self.permission_request_result) result["PermissionRulesSet"] = to_class(PermissionRulesSet, self.permission_rules_set) + result["PermissionsAllowAllMode"] = to_enum(PermissionsAllowAllMode, self.permissions_allow_all_mode) result["PermissionsConfigureAdditionalContentExclusionPolicy"] = to_class(PermissionsConfigureAdditionalContentExclusionPolicy, self.permissions_configure_additional_content_exclusion_policy) result["PermissionsConfigureAdditionalContentExclusionPolicyRule"] = to_class(PermissionsConfigureAdditionalContentExclusionPolicyRule, self.permissions_configure_additional_content_exclusion_policy_rule) result["PermissionsConfigureAdditionalContentExclusionPolicyRuleSource"] = to_class(PermissionsConfigureAdditionalContentExclusionPolicyRuleSource, self.permissions_configure_additional_content_exclusion_policy_rule_source) @@ -22917,7 +26526,6 @@ def to_dict(self) -> dict: result["PluginUpdateAllEntry"] = to_class(PluginUpdateAllEntry, self.plugin_update_all_entry) result["PluginUpdateAllResult"] = to_class(PluginUpdateAllResult, self.plugin_update_all_result) result["PluginUpdateResult"] = to_class(PluginUpdateResult, self.plugin_update_result) - result["PollSpawnedSessionsResult"] = to_class(PollSpawnedSessionsResult, self.poll_spawned_sessions_result) result["ProviderAddRequest"] = to_class(ProviderAddRequest, self.provider_add_request) result["ProviderAddResult"] = to_class(ProviderAddResult, self.provider_add_result) result["ProviderConfig"] = to_class(ProviderConfig, self.provider_config) @@ -22939,12 +26547,24 @@ def to_dict(self) -> dict: result["PushAttachmentDirectory"] = to_class(PushAttachmentDirectory, self.push_attachment_directory) result["PushAttachmentFile"] = to_class(PushAttachmentFile, self.push_attachment_file) result["PushAttachmentFileLineRange"] = to_class(PushAttachmentFileLineRange, self.push_attachment_file_line_range) + result["PushAttachmentGitHubActionsJob"] = to_class(PushAttachmentGitHubActionsJob, self.push_attachment_git_hub_actions_job) + result["PushAttachmentGitHubCommit"] = to_class(PushAttachmentGitHubCommit, self.push_attachment_git_hub_commit) + result["PushAttachmentGitHubFile"] = to_class(PushAttachmentGitHubFile, self.push_attachment_git_hub_file) + result["PushAttachmentGitHubFileDiff"] = to_class(PushAttachmentGitHubFileDiff, self.push_attachment_git_hub_file_diff) + result["PushAttachmentGitHubFileDiffSide"] = to_class(PushAttachmentGitHubFileDiffSide, self.push_attachment_git_hub_file_diff_side) result["PushAttachmentGitHubReference"] = to_class(PushAttachmentGitHubReference, self.push_attachment_git_hub_reference) result["PushAttachmentGitHubReferenceType"] = to_enum(PushAttachmentGitHubReferenceTypeEnum, self.push_attachment_git_hub_reference_type) + result["PushAttachmentGitHubRelease"] = to_class(PushAttachmentGitHubRelease, self.push_attachment_git_hub_release) + result["PushAttachmentGitHubRepository"] = to_class(PushAttachmentGitHubRepository, self.push_attachment_git_hub_repository) + result["PushAttachmentGitHubSnippet"] = to_class(PushAttachmentGitHubSnippet, self.push_attachment_git_hub_snippet) + result["PushAttachmentGitHubTreeComparison"] = to_class(PushAttachmentGitHubTreeComparison, self.push_attachment_git_hub_tree_comparison) + result["PushAttachmentGitHubTreeComparisonSide"] = to_class(PushAttachmentGitHubTreeComparisonSide, self.push_attachment_git_hub_tree_comparison_side) + result["PushAttachmentGitHubUrl"] = to_class(PushAttachmentGitHubURL, self.push_attachment_git_hub_url) result["PushAttachmentSelection"] = to_class(PushAttachmentSelection, self.push_attachment_selection) result["PushAttachmentSelectionDetails"] = to_class(PushAttachmentSelectionDetails, self.push_attachment_selection_details) result["PushAttachmentSelectionDetailsEnd"] = to_class(PushAttachmentSelectionDetailsEnd, self.push_attachment_selection_details_end) result["PushAttachmentSelectionDetailsStart"] = to_class(PushAttachmentSelectionDetailsStart, self.push_attachment_selection_details_start) + result["PushGitHubRepoRef"] = to_class(PushGitHubRepoRef, self.push_git_hub_repo_ref) result["QueuedCommandHandled"] = to_class(QueuedCommandHandled, self.queued_command_handled) result["QueuedCommandNotHandled"] = to_class(QueuedCommandNotHandled, self.queued_command_not_handled) result["QueuedCommandResult"] = (self.queued_command_result).to_dict() @@ -22992,6 +26612,9 @@ def to_dict(self) -> dict: result["SecretsAddFilterValuesResult"] = to_class(SecretsAddFilterValuesResult, self.secrets_add_filter_values_result) result["SendAgentMode"] = to_enum(SendAgentMode, self.send_agent_mode) result["SendAttachmentsToMessageParams"] = to_class(SendAttachmentsToMessageParams, self.send_attachments_to_message_params) + result["SendMessageItem"] = to_class(SendMessageItem, self.send_message_item) + result["SendMessagesRequest"] = to_class(SendMessagesRequest, self.send_messages_request) + result["SendMessagesResult"] = to_class(SendMessagesResult, self.send_messages_result) result["SendMode"] = to_enum(SendMode, self.send_mode) result["SendRequest"] = to_class(SendRequest, self.send_request) result["SendResult"] = to_class(SendResult, self.send_result) @@ -23003,6 +26626,7 @@ def to_dict(self) -> dict: result["SessionAuthStatus"] = to_class(SessionAuthStatus, self.session_auth_status) result["SessionBulkDeleteResult"] = to_class(SessionBulkDeleteResult, self.session_bulk_delete_result) result["SessionCapability"] = to_enum(SessionCapability, self.session_capability) + result["SessionCompletionItem"] = to_class(SessionCompletionItem, self.session_completion_item) result["SessionContext"] = to_class(SessionContext, self.session_context) result["SessionContextHostType"] = to_enum(HostType, self.session_context_host_type) result["SessionEnrichMetadataResult"] = to_class(SessionEnrichMetadataResult, self.session_enrich_metadata_result) @@ -23015,7 +26639,7 @@ def to_dict(self) -> dict: result["SessionFsReaddirRequest"] = to_class(SessionFSReaddirRequest, self.session_fs_readdir_request) result["SessionFsReaddirResult"] = to_class(SessionFSReaddirResult, self.session_fs_readdir_result) result["SessionFsReaddirWithTypesEntry"] = to_class(SessionFSReaddirWithTypesEntry, self.session_fs_readdir_with_types_entry) - result["SessionFsReaddirWithTypesEntryType"] = to_enum(InstructionDiscoveryPathKind, self.session_fs_readdir_with_types_entry_type) + result["SessionFsReaddirWithTypesEntryType"] = to_enum(DebugCollectLogsEntryKind, self.session_fs_readdir_with_types_entry_type) result["SessionFsReaddirWithTypesRequest"] = to_class(SessionFSReaddirWithTypesRequest, self.session_fs_readdir_with_types_request) result["SessionFsReaddirWithTypesResult"] = to_class(SessionFSReaddirWithTypesResult, self.session_fs_readdir_with_types_result) result["SessionFsReadFileRequest"] = to_class(SessionFSReadFileRequest, self.session_fs_read_file_request) @@ -23048,6 +26672,7 @@ def to_dict(self) -> dict: result["SessionMetadataSnapshot"] = to_class(SessionMetadataSnapshot, self.session_metadata_snapshot) result["SessionMode"] = to_enum(SessionMode, self.session_mode) result["SessionModelList"] = to_class(SessionModelList, self.session_model_list) + result["SessionModelPriceCategory"] = to_class(SessionModelPriceCategory, self.session_model_price_category) result["SessionOpenOptions"] = to_class(SessionOpenOptions, self.session_open_options) result["SessionOpenOptionsAdditionalContentExclusionPolicy"] = to_class(SessionOpenOptionsAdditionalContentExclusionPolicy, self.session_open_options_additional_content_exclusion_policy) result["SessionOpenOptionsAdditionalContentExclusionPolicyRule"] = to_class(SessionOpenOptionsAdditionalContentExclusionPolicyRule, self.session_open_options_additional_content_exclusion_policy_rule) @@ -23066,6 +26691,16 @@ def to_dict(self) -> dict: result["SessionsEnrichMetadataRequest"] = to_class(SessionsEnrichMetadataRequest, self.sessions_enrich_metadata_request) result["SessionSetCredentialsParams"] = to_class(SessionSetCredentialsParams, self.session_set_credentials_params) result["SessionSetCredentialsResult"] = to_class(SessionSetCredentialsResult, self.session_set_credentials_result) + result["SessionSettingsBuiltInToolAvailabilitySnapshot"] = to_class(SessionSettingsBuiltInToolAvailabilitySnapshot, self.session_settings_built_in_tool_availability_snapshot) + result["SessionSettingsEvaluatePredicateRequest"] = to_class(SessionSettingsEvaluatePredicateRequest, self.session_settings_evaluate_predicate_request) + result["SessionSettingsEvaluatePredicateResult"] = to_class(SessionSettingsEvaluatePredicateResult, self.session_settings_evaluate_predicate_result) + result["SessionSettingsJobSnapshot"] = to_class(SessionSettingsJobSnapshot, self.session_settings_job_snapshot) + result["SessionSettingsModelSnapshot"] = to_class(SessionSettingsModelSnapshot, self.session_settings_model_snapshot) + result["SessionSettingsOnlineEvaluationSnapshot"] = to_class(SessionSettingsOnlineEvaluationSnapshot, self.session_settings_online_evaluation_snapshot) + result["SessionSettingsPredicateName"] = to_enum(SessionSettingsPredicateName, self.session_settings_predicate_name) + result["SessionSettingsRepoSnapshot"] = to_class(SessionSettingsRepoSnapshot, self.session_settings_repo_snapshot) + result["SessionSettingsSnapshot"] = to_class(SessionSettingsSnapshot, self.session_settings_snapshot) + result["SessionSettingsValidationSnapshot"] = to_class(SessionSettingsValidationSnapshot, self.session_settings_validation_snapshot) result["SessionsFindByPrefixRequest"] = to_class(SessionsFindByPrefixRequest, self.sessions_find_by_prefix_request) result["SessionsFindByPrefixResult"] = to_class(SessionsFindByPrefixResult, self.sessions_find_by_prefix_result) result["SessionsFindByTaskIDRequest"] = to_class(SessionsFindByTaskIDRequest, self.sessions_find_by_task_id_request) @@ -23096,8 +26731,6 @@ def to_dict(self) -> dict: result["SessionsOpenResumeLast"] = to_class(SessionsOpenResumeLast, self.sessions_open_resume_last) result["SessionsOpenStatus"] = to_enum(SessionsOpenStatus, self.sessions_open_status) result["SessionSource"] = to_enum(SessionSource, self.session_source) - result["SessionsPollSpawnedSessionsEvent"] = to_class(SessionsPollSpawnedSessionsEvent, self.sessions_poll_spawned_sessions_event) - result["SessionsPollSpawnedSessionsRequest"] = to_class(SessionsPollSpawnedSessionsRequest, self.sessions_poll_spawned_sessions_request) result["SessionsPruneOldRequest"] = to_class(SessionsPruneOldRequest, self.sessions_prune_old_request) result["SessionsRegisterExtensionToolsOnSessionOptions"] = to_class(SessionsRegisterExtensionToolsOnSessionOptions, self.sessions_register_extension_tools_on_session_options) result["SessionsReleaseLockRequest"] = to_class(SessionsReleaseLockRequest, self.sessions_release_lock_request) @@ -23115,6 +26748,7 @@ def to_dict(self) -> dict: result["SessionTelemetryEngagement"] = to_class(SessionTelemetryEngagement, self.session_telemetry_engagement) result["SessionUpdateOptionsParams"] = to_class(SessionUpdateOptionsParams, self.session_update_options_params) result["SessionUpdateOptionsResult"] = to_class(SessionUpdateOptionsResult, self.session_update_options_result) + result["SessionVisibilityStatus"] = to_enum(SessionVisibilityStatus, self.session_visibility_status) result["SessionWorkingDirectoryContext"] = to_class(SessionWorkingDirectoryContext, self.session_working_directory_context) result["SessionWorkingDirectoryContextHostType"] = to_enum(HostType, self.session_working_directory_context_host_type) result["ShellCancelUserRequestedRequest"] = to_class(ShellCancelUserRequestedRequest, self.shell_cancel_user_requested_request) @@ -23142,6 +26776,7 @@ def to_dict(self) -> dict: result["SlashCommandCompletedResult"] = to_class(SlashCommandCompletedResult, self.slash_command_completed_result) result["SlashCommandInfo"] = to_class(SlashCommandInfo, self.slash_command_info) result["SlashCommandInput"] = to_class(SlashCommandInput, self.slash_command_input) + result["SlashCommandInputChoice"] = to_class(SlashCommandInputChoice, self.slash_command_input_choice) result["SlashCommandInputCompletion"] = to_enum(SlashCommandInputCompletion, self.slash_command_input_completion) result["SlashCommandInvocationResult"] = (self.slash_command_invocation_result).to_dict() result["SlashCommandKind"] = to_enum(SlashCommandKind, self.slash_command_kind) @@ -23216,8 +26851,11 @@ def to_dict(self) -> dict: result["UIHandlePendingResult"] = to_class(UIHandlePendingResult, self.ui_handle_pending_result) result["UIHandlePendingSamplingRequest"] = to_class(UIHandlePendingSamplingRequest, self.ui_handle_pending_sampling_request) result["UIHandlePendingSamplingResponse"] = from_dict(lambda x: x, self.ui_handle_pending_sampling_response) + result["UIHandlePendingSessionLimitsExhaustedRequest"] = to_class(UIHandlePendingSessionLimitsExhaustedRequest, self.ui_handle_pending_session_limits_exhausted_request) result["UIHandlePendingUserInputRequest"] = to_class(UIHandlePendingUserInputRequest, self.ui_handle_pending_user_input_request) result["UIRegisterDirectAutoModeSwitchHandlerResult"] = to_class(UIRegisterDirectAutoModeSwitchHandlerResult, self.ui_register_direct_auto_mode_switch_handler_result) + result["UISessionLimitsExhaustedResponse"] = to_class(UISessionLimitsExhaustedResponse, self.ui_session_limits_exhausted_response) + result["UISessionLimitsExhaustedResponseAction"] = to_enum(UISessionLimitsExhaustedResponseAction, self.ui_session_limits_exhausted_response_action) result["UIUnregisterDirectAutoModeSwitchHandlerRequest"] = to_class(UIUnregisterDirectAutoModeSwitchHandlerRequest, self.ui_unregister_direct_auto_mode_switch_handler_request) result["UIUnregisterDirectAutoModeSwitchHandlerResult"] = to_class(UIUnregisterDirectAutoModeSwitchHandlerResult, self.ui_unregister_direct_auto_mode_switch_handler_result) result["UIUserInputResponse"] = to_class(UIUserInputResponse, self.ui_user_input_response) @@ -23231,6 +26869,13 @@ def to_dict(self) -> dict: result["UsageMetricsTokenDetail"] = to_class(UsageMetricsTokenDetail, self.usage_metrics_token_detail) result["UserAuthInfo"] = to_class(UserAuthInfo, self.user_auth_info) result["UserRequestedShellCommandResult"] = to_class(UserRequestedShellCommandResult, self.user_requested_shell_command_result) + result["UserSettingMetadata"] = to_class(UserSettingMetadata, self.user_setting_metadata) + result["UserSettingsGetResult"] = to_class(UserSettingsGetResult, self.user_settings_get_result) + result["UserSettingsSetRequest"] = to_class(UserSettingsSetRequest, self.user_settings_set_request) + result["UserSettingsSetResult"] = to_class(UserSettingsSetResult, self.user_settings_set_result) + result["VisibilityGetResult"] = to_class(VisibilityGetResult, self.visibility_get_result) + result["VisibilitySetRequest"] = to_class(VisibilitySetRequest, self.visibility_set_request) + result["VisibilitySetResult"] = to_class(VisibilitySetResult, self.visibility_set_result) result["WorkspaceDiffFileChange"] = to_class(WorkspaceDiffFileChange, self.workspace_diff_file_change) result["WorkspaceDiffFileChangeType"] = to_enum(WorkspaceDiffFileChangeType, self.workspace_diff_file_change_type) result["WorkspaceDiffMode"] = to_enum(WorkspaceDiffMode, self.workspace_diff_mode) @@ -23249,6 +26894,7 @@ def to_dict(self) -> dict: result["WorkspacesSaveLargePasteResult"] = to_class(WorkspacesSaveLargePasteResult, self.workspaces_save_large_paste_result) result["WorkspaceSummaryHostType"] = to_enum(HostType, self.workspace_summary_host_type) result["WorkspacesWorkspaceDetailsHostType"] = to_enum(HostType, self.workspaces_workspace_details_host_type) + result["SessionContextAttribution"] = from_union([lambda x: to_class(SessionContextAttribution, x), from_none], self.session_context_attribution) result["SessionContextInfo"] = from_union([lambda x: to_class(SessionContextInfo, x), from_none], self.session_context_info) result["SubagentSettings"] = from_union([lambda x: to_class(SubagentSettings, x), from_none], self.subagent_settings) result["TaskProgress"] = from_union([lambda x: to_class(TaskProgress, x), from_none], self.task_progress) @@ -23291,7 +26937,7 @@ def _load_AuthInfo(obj: Any) -> "AuthInfo": case _: raise ValueError(f"Unknown AuthInfo type: {kind!r}") # A content block within a tool result, which may be text, terminal output, image, audio, or a resource -ExternalToolTextResultForLlmContent = ExternalToolTextResultForLlmContentText | ExternalToolTextResultForLlmContentTerminal | ExternalToolTextResultForLlmContentImage | ExternalToolTextResultForLlmContentAudio | ExternalToolTextResultForLlmContentResourceLink | ExternalToolTextResultForLlmContentResource +ExternalToolTextResultForLlmContent = ExternalToolTextResultForLlmContentText | ExternalToolTextResultForLlmContentTerminal | ExternalToolTextResultForLlmContentShellExit | ExternalToolTextResultForLlmContentImage | ExternalToolTextResultForLlmContentAudio | ExternalToolTextResultForLlmContentResourceLink | ExternalToolTextResultForLlmContentResource def _load_ExternalToolTextResultForLlmContent(obj: Any) -> "ExternalToolTextResultForLlmContent": assert isinstance(obj, dict) @@ -23299,6 +26945,7 @@ def _load_ExternalToolTextResultForLlmContent(obj: Any) -> "ExternalToolTextResu match kind: case "text": return ExternalToolTextResultForLlmContentText.from_dict(obj) case "terminal": return ExternalToolTextResultForLlmContentTerminal.from_dict(obj) + case "shell_exit": return ExternalToolTextResultForLlmContentShellExit.from_dict(obj) case "image": return ExternalToolTextResultForLlmContentImage.from_dict(obj) case "audio": return ExternalToolTextResultForLlmContentAudio.from_dict(obj) case "resource_link": return ExternalToolTextResultForLlmContentResourceLink.from_dict(obj) @@ -23383,8 +27030,8 @@ def _load_PermissionsLocationsAddToolApprovalDetails(obj: Any) -> "PermissionsLo case "extension-permission-access": return PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess.from_dict(obj) case _: raise ValueError(f"Unknown PermissionsLocationsAddToolApprovalDetails kind: {kind!r}") -# Schema for the `PushAttachment` type. -PushAttachment = PushAttachmentFile | PushAttachmentDirectory | PushAttachmentSelection | PushAttachmentGitHubReference | PushAttachmentBlob | ExtensionContextPushInput +# Attachment union accepted by push input, covering files, directories, GitHub objects, blobs, snippets, and extension context. +PushAttachment = PushAttachmentFile | PushAttachmentDirectory | PushAttachmentSelection | PushAttachmentGitHubReference | PushAttachmentGitHubCommit | PushAttachmentGitHubRelease | PushAttachmentGitHubActionsJob | PushAttachmentGitHubRepository | PushAttachmentGitHubFileDiff | PushAttachmentGitHubTreeComparison | PushAttachmentGitHubURL | PushAttachmentGitHubFile | PushAttachmentGitHubSnippet | PushAttachmentBlob | ExtensionContextPushInput def _load_PushAttachment(obj: Any) -> "PushAttachment": assert isinstance(obj, dict) @@ -23394,6 +27041,15 @@ def _load_PushAttachment(obj: Any) -> "PushAttachment": case "directory": return PushAttachmentDirectory.from_dict(obj) case "selection": return PushAttachmentSelection.from_dict(obj) case "github_reference": return PushAttachmentGitHubReference.from_dict(obj) + case "github_commit": return PushAttachmentGitHubCommit.from_dict(obj) + case "github_release": return PushAttachmentGitHubRelease.from_dict(obj) + case "github_actions_job": return PushAttachmentGitHubActionsJob.from_dict(obj) + case "github_repository": return PushAttachmentGitHubRepository.from_dict(obj) + case "github_file_diff": return PushAttachmentGitHubFileDiff.from_dict(obj) + case "github_tree_comparison": return PushAttachmentGitHubTreeComparison.from_dict(obj) + case "github_url": return PushAttachmentGitHubURL.from_dict(obj) + case "github_file": return PushAttachmentGitHubFile.from_dict(obj) + case "github_snippet": return PushAttachmentGitHubSnippet.from_dict(obj) case "blob": return PushAttachmentBlob.from_dict(obj) case "extension_context": return ExtensionContextPushInput.from_dict(obj) case _: raise ValueError(f"Unknown PushAttachment type: {kind!r}") @@ -23449,7 +27105,7 @@ def _load_SessionOpenParams(obj: Any) -> "SessionOpenParams": case "handoff": return SessionsOpenHandoff.from_dict(obj) case _: raise ValueError(f"Unknown SessionOpenParams kind: {kind!r}") -# Result of invoking the slash command (text output, prompt to send to the agent, or completion). +# Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). SlashCommandInvocationResult = SlashCommandTextResult | SlashCommandAgentPromptResult | SlashCommandCompletedResult | SlashCommandSelectSubcommandResult def _load_SlashCommandInvocationResult(obj: Any) -> "SlashCommandInvocationResult": @@ -23462,7 +27118,7 @@ def _load_SlashCommandInvocationResult(obj: Any) -> "SlashCommandInvocationResul case "select-subcommand": return SlashCommandSelectSubcommandResult.from_dict(obj) case _: raise ValueError(f"Unknown SlashCommandInvocationResult kind: {kind!r}") -# Schema for the `TaskInfo` type. +# Tracked task union returned by task APIs, containing either an agent task or a shell task. TaskInfo = TaskAgentInfo | TaskShellInfo def _load_TaskInfo(obj: Any) -> "TaskInfo": @@ -23480,6 +27136,7 @@ def _load_TaskInfo(obj: Any) -> "TaskInfo": ExternalToolResult = ExternalToolTextResultForLlm ExternalToolTextResultForLlmContentResourceLinkIconTheme = Theme FilterMapping = dict +InstructionDiscoveryPathKind = DebugCollectLogsEntryKind InstructionDiscoveryPathLocation = InstructionLocation InstructionSourceLocation = InstructionLocation LlmInferenceHeaders = dict @@ -23510,7 +27167,7 @@ def _load_TaskInfo(obj: Any) -> "TaskInfo": ProviderEndpointWireApi = ProviderWireAPI RemoteSessionMetadataTaskType = TaskType SessionContextHostType = HostType -SessionFsReaddirWithTypesEntryType = InstructionDiscoveryPathKind +SessionFsReaddirWithTypesEntryType = DebugCollectLogsEntryKind SessionMcpAppsCallToolResult = dict SessionOpenOptionsAdditionalContentExclusionPolicyScope = AdditionalContentExclusionPolicyScope SessionOpenOptionsEnvValueMode = MCPSetEnvValueModeDetails @@ -23550,6 +27207,7 @@ def _patch_model_capabilities(data: dict) -> dict: return data +# Experimental: this API group is experimental and may change or be removed. class ServerModelsApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23560,6 +27218,7 @@ async def list(self, params: ModelsListRequest, *, timeout: float | None = None) return ModelList.from_dict(_patch_model_capabilities(await self._client.request("models.list", params_dict, **_timeout_kwargs(timeout)))) +# Experimental: this API group is experimental and may change or be removed. class ServerToolsApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23570,6 +27229,7 @@ async def list(self, params: ToolsListRequest, *, timeout: float | None = None) return ToolList.from_dict(await self._client.request("tools.list", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. class ServerAccountApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23598,6 +27258,7 @@ async def logout(self, params: AccountLogoutRequest, *, timeout: float | None = return AccountLogoutResult.from_dict(await self._client.request("account.logout", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. class ServerSecretsApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23608,6 +27269,7 @@ async def add_filter_values(self, params: SecretsAddFilterValuesRequest, *, time return SecretsAddFilterValuesResult.from_dict(await self._client.request("secrets.addFilterValues", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. class ServerMcpConfigApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23646,6 +27308,7 @@ async def reload(self, *, timeout: float | None = None) -> None: await self._client.request("mcp.config.reload", {}, **_timeout_kwargs(timeout)) +# Experimental: this API group is experimental and may change or be removed. class ServerMcpApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23667,7 +27330,7 @@ async def list(self, *, timeout: float | None = None) -> MarketplaceListResult: return MarketplaceListResult.from_dict(await self._client.request("plugins.marketplaces.list", {}, **_timeout_kwargs(timeout))) async def add(self, params: PluginsMarketplacesAddRequest, *, timeout: float | None = None) -> MarketplaceAddResult: - "Registers a new marketplace from a source (owner/repo, URL, or local path).\n\nArgs:\n params: Marketplace source to register.\n\nReturns:\n Result of registering a new marketplace." + "Registers a new marketplace from a source (owner/repo, URL, or local path).\n\nArgs:\n params: Marketplace source and optional working directory for relative-path resolution.\n\nReturns:\n Result of registering a new marketplace." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} return MarketplaceAddResult.from_dict(await self._client.request("plugins.marketplaces.add", params_dict, **_timeout_kwargs(timeout))) @@ -23727,6 +27390,7 @@ async def disable(self, params: PluginsDisableRequest, *, timeout: float | None await self._client.request("plugins.disable", params_dict, **_timeout_kwargs(timeout)) +# Experimental: this API group is experimental and may change or be removed. class ServerSkillsConfigApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23737,6 +27401,7 @@ async def set_disabled_skills(self, params: SkillsConfigSetDisabledSkillsRequest await self._client.request("skills.config.setDisabledSkills", params_dict, **_timeout_kwargs(timeout)) +# Experimental: this API group is experimental and may change or be removed. class ServerSkillsApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23748,7 +27413,7 @@ async def discover(self, params: SkillsDiscoverRequest, *, timeout: float | None return ServerSkillList.from_dict(await self._client.request("skills.discover", params_dict, **_timeout_kwargs(timeout))) async def get_discovery_paths(self, params: SkillsGetDiscoveryPathsRequest, *, timeout: float | None = None) -> SkillDiscoveryPathList: - "Returns the canonical directories where a client may create skills that the runtime will recognize, including ones that do not exist yet. Project directories become active once created.\n\nArgs:\n params: Optional project paths to enumerate.\n\nReturns:\n Canonical locations where skills can be created so the runtime will recognize them.\n\n.. warning:: This API is experimental and may change or be removed in future versions." + "Returns the canonical directories where a client may create skills that the runtime will recognize, including ones that do not exist yet. Project directories become active once created.\n\nArgs:\n params: Optional project paths to enumerate.\n\nReturns:\n Canonical locations where skills can be created so the runtime will recognize them." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} return SkillDiscoveryPathList.from_dict(await self._client.request("skills.getDiscoveryPaths", params_dict, **_timeout_kwargs(timeout))) @@ -23785,6 +27450,17 @@ async def get_discovery_paths(self, params: InstructionsGetDiscoveryPathsRequest return InstructionDiscoveryPathList.from_dict(await self._client.request("instructions.getDiscoveryPaths", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class ServerCommandsApi: + def __init__(self, client: "JsonRpcClient"): + self._client = client + + async def list(self, *, timeout: float | None = None) -> CommandList: + "Lists the well-known built-in slash commands that work as the first message in a new session (e.g. /plan, /env), without requiring an active session. Commands that depend on session state, authentication, or a synced session are omitted.\n\nReturns:\n Slash commands available in the session, after applying any include/exclude filters." + return CommandList.from_dict(await self._client.request("commands.list", {}, **_timeout_kwargs(timeout))) + + +# Experimental: this API group is experimental and may change or be removed. class ServerUserSettingsApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23793,13 +27469,24 @@ async def reload(self, *, timeout: float | None = None) -> None: "Drops this runtime process's in-memory user settings cache so the next settings read observes disk." await self._client.request("user.settings.reload", {}, **_timeout_kwargs(timeout)) + async def get(self, *, timeout: float | None = None) -> UserSettingsGetResult: + "Lists every known user setting (settings.json overlaid with the legacy config.json, config.json wins), each with its effective value, its default, and whether it is at the default — so settings the user has never set still appear with their default value. Does not include repository- or enterprise-managed overrides that the runtime layers on top at session time.\n\nReturns:\n Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides." + return UserSettingsGetResult.from_dict(await self._client.request("user.settings.get", {}, **_timeout_kwargs(timeout))) + + async def set(self, params: UserSettingsSetRequest, *, timeout: float | None = None) -> UserSettingsSetResult: + "Writes one or more user settings to settings.json, replacing each provided top-level key. A key whose value is null is removed. Returns the keys whose new value is shadowed by a legacy config.json entry (config.json wins on read), which the runtime leaves in place — such writes do not take effect until the legacy value is removed.\n\nArgs:\n params: Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed.\n\nReturns:\n Outcome of writing user settings." + params_dict = {k: v for k, v in params.to_dict().items() if v is not None} + return UserSettingsSetResult.from_dict(await self._client.request("user.settings.set", params_dict, **_timeout_kwargs(timeout))) + +# Experimental: this API group is experimental and may change or be removed. class ServerUserApi: def __init__(self, client: "JsonRpcClient"): self._client = client self.settings = ServerUserSettingsApi(client) +# Experimental: this API group is experimental and may change or be removed. class ServerRuntimeApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23809,6 +27496,7 @@ async def shutdown(self, *, timeout: float | None = None) -> None: await self._client.request("runtime.shutdown", {}, **_timeout_kwargs(timeout)) +# Experimental: this API group is experimental and may change or be removed. class ServerSessionFsApi: def __init__(self, client: "JsonRpcClient"): self._client = client @@ -23982,6 +27670,7 @@ def __init__(self, client: "JsonRpcClient"): self.skills = ServerSkillsApi(client) self.agents = ServerAgentsApi(client) self.instructions = ServerInstructionsApi(client) + self.commands = ServerCommandsApi(client) self.user = ServerUserApi(client) self.runtime = ServerRuntimeApi(client) self.session_fs = ServerSessionFsApi(client) @@ -23990,7 +27679,7 @@ def __init__(self, client: "JsonRpcClient"): self.agent_registry = ServerAgentRegistryApi(client) async def ping(self, params: PingRequest, *, timeout: float | None = None) -> PingResult: - "Checks server responsiveness and returns protocol information.\n\nArgs:\n params: Optional message to echo back to the caller.\n\nReturns:\n Server liveness response, including the echoed message, current server timestamp, and protocol version." + "Checks server responsiveness and returns protocol information.\n\nArgs:\n params: Optional message to echo back to the caller.\n\nReturns:\n Server liveness response, including the echoed message, current server timestamp, and protocol version.\n\n.. warning:: This API is experimental and may change or be removed in future versions." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} return PingResult.from_dict(await self._client.request("ping", params_dict, **_timeout_kwargs(timeout))) @@ -24015,11 +27704,6 @@ async def _get_board_entry_count(self, params: SessionsGetBoardEntryCountRequest params_dict = {k: v for k, v in params.to_dict().items() if v is not None} return SessionsGetBoardEntryCountResult.from_dict(await self._client.request("sessions.getBoardEntryCount", params_dict, **_timeout_kwargs(timeout))) - async def _poll_spawned_sessions(self, params: SessionsPollSpawnedSessionsRequest, *, timeout: float | None = None) -> PollSpawnedSessionsResult: - "Cursor-based long-poll for sessions spawned by the runtime (e.g. in response to a Mission Control `start_session` command). The cursor is an opaque token; pass it back to receive only spawn events that occurred AFTER the cursor was issued. Omit the cursor on the first call to receive any events buffered since the runtime started. Internal: this is a CLI background-daemon plumbing primitive. SDK consumers that need to react to runtime-spawned sessions should subscribe to a higher-level event stream rather than driving a long-poll loop.\n\nArgs:\n params: Cursor and optional long-poll wait for polling runtime-spawned sessions.\n\nReturns:\n Batch of spawn events plus a cursor for follow-up polls.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." - params_dict = {k: v for k, v in params.to_dict().items() if v is not None} - return PollSpawnedSessionsResult.from_dict(await self._client.request("sessions.pollSpawnedSessions", params_dict, **_timeout_kwargs(timeout))) - async def _register_extension_tools_on_session(self, params: _RegisterExtensionToolsParams, *, timeout: float | None = None) -> _RegisterExtensionToolsResult: "Registers extension-provided tools on the given session, gated by an optional `enabled` callback. Returns an opaque unsubscribe function the caller must invoke to deregister the tools when the extension is torn down. Marked internal because `loader`, `enabled`, and the returned `unsubscribe` are in-process handles that cannot cross the JSON-RPC boundary. Disappears once extension discovery / launch / tool registration are owned by the runtime: SDK consumers will pass pure config (search paths, disabled ids) via `SessionOptions` and the runtime will resolve, launch, register, and tear down extensions itself.\n\nArgs:\n params: Params to attach an extension loader's tools to a session.\n\nReturns:\n Handle for releasing the extension tool registration.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} @@ -24038,26 +27722,39 @@ def __init__(self, client: "JsonRpcClient"): self.sessions = _InternalServerSessionsApi(client) async def _connect(self, params: _ConnectRequest, *, timeout: float | None = None) -> _ConnectResult: - "Performs the SDK server connection handshake and validates the optional connection token. Marked internal because this is JSON-RPC transport plumbing invoked automatically by an SDK client's own `connect()` wrapper, not a user-facing method. Stays internal as long as the SDK client owns the handshake; would only become public if the SDK ever exposed the raw schema surface to consumers without a connection wrapper.\n\nArgs:\n params: Optional connection token presented by the SDK client during the handshake.\n\nReturns:\n Handshake result reporting the server's protocol version and package version on success.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + "Performs the SDK server connection handshake and validates the optional connection token. Marked internal because this is JSON-RPC transport plumbing invoked automatically by an SDK client's own `connect()` wrapper, not a user-facing method. Stays internal as long as the SDK client owns the handshake; would only become public if the SDK ever exposed the raw schema surface to consumers without a connection wrapper.\n\nArgs:\n params: Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding).\n\nReturns:\n Handshake result reporting the server's protocol version and package version on success.\n\n.. warning:: This API is experimental and may change or be removed in future versions.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} return _ConnectResult.from_dict(await self._client.request("connect", params_dict, **_timeout_kwargs(timeout))) # Experimental: this API group is experimental and may change or be removed. -class AuthApi: +class GitHubAuthApi: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id async def get_status(self, *, timeout: float | None = None) -> SessionAuthStatus: "Gets authentication status and account metadata for the session.\n\nReturns:\n Authentication status and account metadata for the session." - return SessionAuthStatus.from_dict(await self._client.request("session.auth.getStatus", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + return SessionAuthStatus.from_dict(await self._client.request("session.gitHubAuth.getStatus", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) async def set_credentials(self, params: SessionSetCredentialsParams, *, timeout: float | None = None) -> SessionSetCredentialsResult: "Updates the session's auth credentials used for outbound model and API requests.\n\nArgs:\n params: New auth credentials to install on the session. Omit to leave credentials unchanged.\n\nReturns:\n Indicates whether the credential update succeeded." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return SessionSetCredentialsResult.from_dict(await self._client.request("session.auth.setCredentials", params_dict, **_timeout_kwargs(timeout))) + return SessionSetCredentialsResult.from_dict(await self._client.request("session.gitHubAuth.setCredentials", params_dict, **_timeout_kwargs(timeout))) + + +# Experimental: this API group is experimental and may change or be removed. +class DebugApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def collect_logs(self, params: DebugCollectLogsRequest, *, timeout: float | None = None) -> DebugCollectLogsResult: + "Collects a redacted session debug log bundle into a local archive or staging directory. The runtime includes session-owned logs by default and accepts caller-provided diagnostic entries so host applications can add their own files without changing this API shape.\n\nArgs:\n params: Options for collecting a redacted session debug bundle.\n\nReturns:\n Result of collecting a redacted debug bundle." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return DebugCollectLogsResult.from_dict(await self._client.request("session.debug.collectLogs", params_dict, **_timeout_kwargs(timeout))) # Experimental: this API group is experimental and may change or be removed. @@ -24248,6 +27945,23 @@ async def diff(self, params: WorkspacesDiffRequest, *, timeout: float | None = N return WorkspaceDiffResult.from_dict(await self._client.request("session.workspaces.diff", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class CompletionsApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def get_trigger_characters(self, *, timeout: float | None = None) -> CompletionsGetTriggerCharactersResult: + "Gets the characters that should trigger host-driven completions for the session. Empty disables host-driven completions (e.g. local sessions, or a relay host that does not advertise them).\n\nReturns:\n Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`)." + return CompletionsGetTriggerCharactersResult.from_dict(await self._client.request("session.completions.getTriggerCharacters", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def request(self, params: CompletionsRequestRequest, *, timeout: float | None = None) -> CompletionsRequestResult: + "Requests host-driven completion items for the current composer input. Returns an empty list when the host has no items or does not support completions.\n\nArgs:\n params: Request host-driven completions for the current composer input.\n\nReturns:\n Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return CompletionsRequestResult.from_dict(await self._client.request("session.completions.request", params_dict, **_timeout_kwargs(timeout))) + + # Experimental: this API group is experimental and may change or be removed. class InstructionsApi: def __init__(self, client: "JsonRpcClient", session_id: str): @@ -24418,6 +28132,19 @@ async def login(self, params: MCPOauthLoginRequest, *, timeout: float | None = N return MCPOauthLoginResult.from_dict(await self._client.request("session.mcp.oauth.login", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class McpHeadersApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def handle_pending_headers_refresh_request(self, params: MCPHeadersHandlePendingHeadersRefreshRequestRequest, *, timeout: float | None = None) -> MCPHeadersHandlePendingHeadersRefreshRequestResult: + "Responds to a pending MCP dynamic headers refresh request. Hosts that subscribe to `mcp.headers_refresh_required` use this to provide short-lived per-server headers or to indicate that no dynamic headers are available for this refresh.\n\nArgs:\n params: MCP headers refresh request id and the host response.\n\nReturns:\n Indicates whether the pending MCP headers refresh response was accepted." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return MCPHeadersHandlePendingHeadersRefreshRequestResult.from_dict(await self._client.request("session.mcp.headers.handlePendingHeadersRefreshRequest", params_dict, **_timeout_kwargs(timeout))) + + # Experimental: this API group is experimental and may change or be removed. class McpAppsApi: def __init__(self, client: "JsonRpcClient", session_id: str): @@ -24459,20 +28186,47 @@ async def diagnose(self, params: MCPAppsDiagnoseRequest, *, timeout: float | Non return MCPAppsDiagnoseResult.from_dict(await self._client.request("session.mcp.apps.diagnose", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class McpResourcesApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def read(self, params: MCPResourcesReadRequest, *, timeout: float | None = None) -> MCPResourcesReadResult: + "Fetch an MCP resource from a connected server by URI (proxies MCP `resources/read`).\n\nArgs:\n params: MCP server and resource URI to fetch.\n\nReturns:\n Resource contents returned by the MCP server." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return MCPResourcesReadResult.from_dict(await self._client.request("session.mcp.resources.read", params_dict, **_timeout_kwargs(timeout))) + + async def list(self, params: MCPResourcesListRequest, *, timeout: float | None = None) -> MCPResourcesListResult: + "Enumerate one page of resources a connected MCP server exposes (proxies MCP `resources/list`). Pass `cursor` to continue from a prior result's `nextCursor`.\n\nArgs:\n params: MCP server whose resources to enumerate.\n\nReturns:\n One page of resources advertised by the named MCP server." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return MCPResourcesListResult.from_dict(await self._client.request("session.mcp.resources.list", params_dict, **_timeout_kwargs(timeout))) + + async def list_templates(self, params: MCPResourcesListTemplatesRequest, *, timeout: float | None = None) -> MCPResourcesListTemplatesResult: + "Enumerate one page of resource templates a connected MCP server exposes (proxies MCP `resources/templates/list`). Pass `cursor` to continue from a prior result's `nextCursor`.\n\nArgs:\n params: MCP server whose resource templates to enumerate.\n\nReturns:\n One page of resource templates advertised by the named MCP server." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return MCPResourcesListTemplatesResult.from_dict(await self._client.request("session.mcp.resources.listTemplates", params_dict, **_timeout_kwargs(timeout))) + + # Experimental: this API group is experimental and may change or be removed. class McpApi: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id self.oauth = McpOauthApi(client, session_id) + self.headers = McpHeadersApi(client, session_id) self.apps = McpAppsApi(client, session_id) + self.resources = McpResourcesApi(client, session_id) async def list(self, *, timeout: float | None = None) -> MCPServerList: "Lists MCP servers configured for the session, their connection status, and host-level state. The host-level state (disabled/filtered servers, failed/needs-auth/pending connections, mcp3p policy, full config) is empty/zero when no MCP host has been initialized for the session.\n\nReturns:\n MCP servers configured for the session, with their connection status and host-level state." return MCPServerList.from_dict(await self._client.request("session.mcp.list", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) async def list_tools(self, params: MCPListToolsRequest, *, timeout: float | None = None) -> MCPListToolsResult: - "Lists the tools exposed by a connected MCP server on this session's host.\n\nArgs:\n params: Server name whose tool list should be returned.\n\nReturns:\n Tools exposed by the connected MCP server. Throws when the server is not connected." + "Lists the tools exposed by a connected MCP server on this session's host. This performs a live `tools/list` request. Tool UI metadata is returned independently of whether MCP Apps rendering is enabled for the session.\n\nArgs:\n params: Server name whose tool list should be returned.\n\nReturns:\n Tools exposed by the connected MCP server. Throws when the server is not connected." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return MCPListToolsResult.from_dict(await self._client.request("session.mcp.listTools", params_dict, **_timeout_kwargs(timeout))) @@ -24515,6 +28269,18 @@ async def remove_git_hub(self, *, timeout: float | None = None) -> MCPRemoveGitH "Removes the auto-managed `github` MCP server when present.\n\nReturns:\n Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove)." return MCPRemoveGitHubResult.from_dict(await self._client.request("session.mcp.removeGitHub", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def start_server(self, params: MCPStartServerRequest, *, timeout: float | None = None) -> None: + "Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server.\n\nArgs:\n params: Server name and configuration for an individual MCP server start." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + await self._client.request("session.mcp.startServer", params_dict, **_timeout_kwargs(timeout)) + + async def restart_server(self, params: MCPRestartServerRequest, *, timeout: float | None = None) -> None: + "Restarts an individual MCP server on the live session (stops then starts). Omit `config` for a config-free restart-by-name of an already-configured server; supply `config` to restart with a replacement configuration. Session-scoped and ephemeral: does NOT modify persistent user configuration (`mcp.config.*`).\n\nArgs:\n params: Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + await self._client.request("session.mcp.restartServer", params_dict, **_timeout_kwargs(timeout)) + async def stop_server(self, params: MCPStopServerRequest, *, timeout: float | None = None) -> None: "Stops an individual MCP server on the session's host.\n\nArgs:\n params: Server name for an individual MCP server stop." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -24663,7 +28429,7 @@ async def list(self, params: CommandsListRequest | None = None, *, timeout: floa return CommandList.from_dict(await self._client.request("session.commands.list", params_dict, **_timeout_kwargs(timeout))) async def invoke(self, params: CommandsInvokeRequest, *, timeout: float | None = None) -> SlashCommandInvocationResult: - "Invokes a slash command in the session.\n\nArgs:\n params: Slash command name and optional raw input string to invoke.\n\nReturns:\n Result of invoking the slash command (text output, prompt to send to the agent, or completion)." + "Invokes a slash command in the session.\n\nArgs:\n params: Slash command name and optional raw input string to invoke.\n\nReturns:\n Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection)." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return _load_SlashCommandInvocationResult(await self._client.request("session.commands.invoke", params_dict, **_timeout_kwargs(timeout))) @@ -24752,6 +28518,12 @@ async def handle_pending_auto_mode_switch(self, params: UIHandlePendingAutoModeS params_dict["sessionId"] = self._session_id return UIHandlePendingResult.from_dict(await self._client.request("session.ui.handlePendingAutoModeSwitch", params_dict, **_timeout_kwargs(timeout))) + async def handle_pending_session_limits_exhausted(self, params: UIHandlePendingSessionLimitsExhaustedRequest, *, timeout: float | None = None) -> UIHandlePendingResult: + "Resolves a pending `session_limits_exhausted.requested` event with the user's selected limit action.\n\nArgs:\n params: Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action.\n\nReturns:\n Indicates whether the pending UI request was resolved by this call." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return UIHandlePendingResult.from_dict(await self._client.request("session.ui.handlePendingSessionLimitsExhausted", params_dict, **_timeout_kwargs(timeout))) + async def handle_pending_exit_plan_mode(self, params: UIHandlePendingExitPlanModeRequest, *, timeout: float | None = None) -> UIHandlePendingResult: "Resolves a pending `exit_plan_mode.requested` event with the user's response.\n\nArgs:\n params: Request ID of a pending `exit_plan_mode.requested` event and the user's response.\n\nReturns:\n Indicates whether the pending UI request was resolved by this call." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -24894,13 +28666,13 @@ async def set_approve_all(self, params: PermissionsSetApproveAllRequest, *, time return PermissionsSetApproveAllResult.from_dict(await self._client.request("session.permissions.setApproveAll", params_dict, **_timeout_kwargs(timeout))) async def set_allow_all(self, params: PermissionsSetAllowAllRequest, *, timeout: float | None = None) -> AllowAllPermissionSetResult: - "Enables or disables full allow-all permissions (tools, paths, and URLs) for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. Unlike `setApproveAll`, this swaps in the unrestricted path and URL managers and emits `session.permissions_changed` on transition. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire.\n\nArgs:\n params: Whether to enable full allow-all permissions for the session.\n\nReturns:\n Indicates whether the operation succeeded and reports the post-mutation state." + "Sets the allow-all permission mode for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. The `on` mode swaps in unrestricted path and URL managers and emits `session.permissions_changed` on transition; the `auto` mode keeps normal prompt paths active while attaching LLM safety recommendations. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire.\n\nArgs:\n params: Allow-all mode to apply for the session.\n\nReturns:\n Indicates whether the operation succeeded and reports the post-mutation state." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return AllowAllPermissionSetResult.from_dict(await self._client.request("session.permissions.setAllowAll", params_dict, **_timeout_kwargs(timeout))) async def get_allow_all(self, *, timeout: float | None = None) -> AllowAllPermissionState: - "Returns whether full allow-all permissions are currently active for the session.\n\nReturns:\n Current full allow-all permission state." + "Returns the current allow-all permission mode for the session.\n\nReturns:\n Current allow-all permission mode." return AllowAllPermissionState.from_dict(await self._client.request("session.permissions.getAllowAll", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) async def modify_rules(self, params: PermissionsModifyRulesParams, *, timeout: float | None = None) -> PermissionsModifyRulesResult: @@ -24950,6 +28722,16 @@ async def context_info(self, params: MetadataContextInfoRequest, *, timeout: flo params_dict["sessionId"] = self._session_id return MetadataContextInfoResult.from_dict(await self._client.request("session.metadata.contextInfo", params_dict, **_timeout_kwargs(timeout))) + async def get_context_attribution(self, *, timeout: float | None = None) -> MetadataContextAttributionResult: + "Returns the experimental per-source attribution breakdown of the session's current context window as a flat list of entries (skills, subagents, MCP servers, built-in tools, plugin rollups, system/tool-definition costs, with nesting via parentId), plus the successful compaction count. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. Returns null until the session has initialized its system prompt and tool metadata.\n\nReturns:\n Per-source attribution breakdown for the session's current context window, or null if uninitialized." + return MetadataContextAttributionResult.from_dict(await self._client.request("session.metadata.getContextAttribution", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def get_context_heaviest_messages(self, params: MetadataContextHeaviestMessagesRequest, *, timeout: float | None = None) -> MetadataContextHeaviestMessagesResult: + "Returns the largest individual messages currently in the session's context window, most-expensive first. Companion to `metadata.getContextAttribution`. Returns an empty list until the session has initialized.\n\nArgs:\n params: Parameters for the heaviest-messages query.\n\nReturns:\n The heaviest individual messages in the session's context window, most-expensive first." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return MetadataContextHeaviestMessagesResult.from_dict(await self._client.request("session.metadata.getContextHeaviestMessages", params_dict, **_timeout_kwargs(timeout))) + async def record_context_change(self, params: MetadataRecordContextChangeRequest, *, timeout: float | None = None) -> MetadataRecordContextChangeResult: "Records a working-directory/git context change and emits a `session.context_changed` event.\n\nArgs:\n params: Updated working-directory/git context to record on the session.\n\nReturns:\n Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode)." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -24957,7 +28739,7 @@ async def record_context_change(self, params: MetadataRecordContextChangeRequest return MetadataRecordContextChangeResult.from_dict(await self._client.request("session.metadata.recordContextChange", params_dict, **_timeout_kwargs(timeout))) async def set_working_directory(self, params: MetadataSetWorkingDirectoryRequest, *, timeout: float | None = None) -> MetadataSetWorkingDirectoryResult: - "Updates the session's recorded working directory.\n\nArgs:\n params: Absolute path to set as the session's new working directory.\n\nReturns:\n Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path." + "Updates the session's working directory. For local sessions the target is validated first (an absolute path that exists on disk) and the permission primary directory is re-based; a rejected validation fails the call before any session state changes.\n\nArgs:\n params: Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is.\n\nReturns:\n Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return MetadataSetWorkingDirectoryResult.from_dict(await self._client.request("session.metadata.setWorkingDirectory", params_dict, **_timeout_kwargs(timeout))) @@ -25113,6 +28895,23 @@ async def notify_steerable_changed(self, params: RemoteNotifySteerableChangedReq return RemoteNotifySteerableChangedResult.from_dict(await self._client.request("session.remote.notifySteerableChanged", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class VisibilityApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def get(self, *, timeout: float | None = None) -> VisibilityGetResult: + "Returns the session's current Mission Control sharing status and shareable GitHub URL. Reflects whether the synced session is visible to repository readers (\"repo\") or restricted to its creator and collaborators (\"unshared\").\n\nReturns:\n Current sharing status and shareable GitHub URL for a session." + return VisibilityGetResult.from_dict(await self._client.request("session.visibility.get", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def set(self, params: VisibilitySetRequest, *, timeout: float | None = None) -> VisibilitySetResult: + "Sets the session's Mission Control sharing status, controlling whether the synced session is visible to repository readers. Returns the effective status and shareable GitHub URL after the change.\n\nArgs:\n params: Desired sharing status for the session.\n\nReturns:\n Effective sharing status and shareable GitHub URL after updating session visibility." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return VisibilitySetResult.from_dict(await self._client.request("session.visibility.set", params_dict, **_timeout_kwargs(timeout))) + + # Experimental: this API group is experimental and may change or be removed. class ScheduleApi: def __init__(self, client: "JsonRpcClient", session_id: str): @@ -25135,13 +28934,15 @@ class SessionRpc: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - self.auth = AuthApi(client, session_id) + self.git_hub_auth = GitHubAuthApi(client, session_id) + self.debug = DebugApi(client, session_id) self.canvas = CanvasApi(client, session_id) self.model = ModelApi(client, session_id) self.mode = ModeApi(client, session_id) self.name = NameApi(client, session_id) self.plan = PlanApi(client, session_id) self.workspaces = WorkspacesApi(client, session_id) + self.completions = CompletionsApi(client, session_id) self.instructions = InstructionsApi(client, session_id) self.fleet = FleetApi(client, session_id) self.agent = AgentApi(client, session_id) @@ -25165,6 +28966,7 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self.event_log = EventLogApi(client, session_id) self.usage = UsageApi(client, session_id) self.remote = RemoteApi(client, session_id) + self.visibility = VisibilityApi(client, session_id) self.schedule = ScheduleApi(client, session_id) async def suspend(self, *, timeout: float | None = None) -> None: @@ -25177,6 +28979,12 @@ async def send(self, params: SendRequest, *, timeout: float | None = None) -> Se params_dict["sessionId"] = self._session_id return SendResult.from_dict(await self._client.request("session.send", params_dict, **_timeout_kwargs(timeout))) + async def send_messages(self, params: SendMessagesRequest, *, timeout: float | None = None) -> SendMessagesResult: + "Sends zero or more user messages to the session in a single turn and returns their message IDs. All provided messages are appended to the conversation in order, then exactly one agent turn runs over the resulting history. When the list is empty, one turn runs over the existing history with no new user message. Remote-backed (Mission Control) sessions do not support this method and will return an error.\n\nArgs:\n params: Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error.\n\nReturns:\n Result of sending zero or more user messages\n\n.. warning:: This API is experimental and may change or be removed in future versions." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return SendMessagesResult.from_dict(await self._client.request("session.sendMessages", params_dict, **_timeout_kwargs(timeout))) + async def abort(self, params: AbortRequest, *, timeout: float | None = None) -> AbortResult: "Aborts the current agent turn.\n\nArgs:\n params: Parameters for aborting the current turn\n\nReturns:\n Result of aborting the current turn\n\n.. warning:: This API is experimental and may change or be removed in future versions." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -25196,25 +29004,11 @@ async def log(self, params: LogRequest, *, timeout: float | None = None) -> LogR return LogResult.from_dict(await self._client.request("session.log", params_dict, **_timeout_kwargs(timeout))) -# Experimental: this API group is experimental and may change or be removed. -class _InternalMcpOauthApi: - def __init__(self, client: "JsonRpcClient", session_id: str): - self._client = client - self._session_id = session_id - - async def _respond(self, params: MCPOauthRespondRequest, *, timeout: float | None = None) -> MCPOauthRespondResult: - "Responds to a pending MCP OAuth request with an in-process provider. This internal CLI-only API accepts a live OAuthClientProvider instance and cannot be used over the SDK JSON-RPC boundary. Use session.mcp.oauth.handlePendingRequest instead for the public SDK-safe response path.\n\nArgs:\n params: MCP OAuth request id and optional provider response.\n\nReturns:\n Empty result after recording the MCP OAuth response.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return MCPOauthRespondResult.from_dict(await self._client.request("session.mcp.oauth.respond", params_dict, **_timeout_kwargs(timeout))) - - # Experimental: this API group is experimental and may change or be removed. class _InternalMcpApi: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - self.oauth = _InternalMcpOauthApi(client, session_id) async def _reload_with_config(self, params: MCPReloadWithConfigRequest, *, timeout: float | None = None) -> MCPStartServersResult: "Reloads MCP server connections for the session with an explicit host-provided configuration.\n\nArgs:\n params: Opaque MCP reload configuration.\n\nReturns:\n MCP server startup filtering result.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." @@ -25228,18 +29022,6 @@ async def _configure_git_hub(self, params: MCPConfigureGitHubRequest, *, timeout params_dict["sessionId"] = self._session_id return MCPConfigureGitHubResult.from_dict(await self._client.request("session.mcp.configureGitHub", params_dict, **_timeout_kwargs(timeout))) - async def _start_server(self, params: MCPStartServerRequest, *, timeout: float | None = None) -> None: - "Starts an individual MCP server on the session's host.\n\nArgs:\n params: Server name and opaque configuration for an individual MCP server start.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - await self._client.request("session.mcp.startServer", params_dict, **_timeout_kwargs(timeout)) - - async def _restart_server(self, params: MCPRestartServerRequest, *, timeout: float | None = None) -> None: - "Restarts an individual MCP server on the session's host (stops then starts).\n\nArgs:\n params: Server name and opaque configuration for an individual MCP server restart.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - await self._client.request("session.mcp.restartServer", params_dict, **_timeout_kwargs(timeout)) - async def _register_external_client(self, params: MCPRegisterExternalClientRequest, *, timeout: float | None = None) -> None: "Registers a pre-connected external MCP client (e.g. IDE) on the session's host. The caller retains lifecycle ownership of the client and transport. Marked internal because the `client` and `transport` arguments are in-process MCP SDK instances that cannot be serialized across the JSON-RPC boundary; once the CLI moves on top of the SDK, external clients will be expressed as transport configs the runtime can construct itself.\n\nArgs:\n params: Registration parameters for an external MCP client.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -25253,12 +29035,30 @@ async def _unregister_external_client(self, params: MCPUnregisterExternalClientR await self._client.request("session.mcp.unregisterExternalClient", params_dict, **_timeout_kwargs(timeout)) +# Experimental: this API group is experimental and may change or be removed. +class _InternalSettingsApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def _snapshot(self, *, timeout: float | None = None) -> SessionSettingsSnapshot: + "Returns a redacted snapshot of session runtime settings, with secrets and raw feature flags excluded. Internal: the runtime settings shape is a runtime-internal surface and is deliberately kept out of the public SDK, because consumers should not depend on the runtime's internal settings layout. It remains callable in-process and is expected to be reworked as the runtime internals are consolidated.\n\nReturns:\n Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + return SessionSettingsSnapshot.from_dict(await self._client.request("session.settings.snapshot", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def _evaluate_predicate(self, params: SessionSettingsEvaluatePredicateRequest, *, timeout: float | None = None) -> SessionSettingsEvaluatePredicateResult: + "Evaluates a named Rust-owned settings predicate without exposing raw feature flags. Internal: the raw feature-flag names and composition are runtime-internal, so this predicate-evaluation helper is kept out of the public SDK surface and is callable in-process only.\n\nArgs:\n params: Named Rust-owned settings predicate to evaluate for this session.\n\nReturns:\n Result of evaluating a Rust-owned settings predicate.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return SessionSettingsEvaluatePredicateResult.from_dict(await self._client.request("session.settings.evaluatePredicate", params_dict, **_timeout_kwargs(timeout))) + + class _InternalSessionRpc: """Internal SDK session-scoped RPC methods. Not part of the public API.""" def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id self.mcp = _InternalMcpApi(client, session_id) + self.settings = _InternalSettingsApi(client, session_id) # Experimental: this API group is experimental and may change or be removed. @@ -25442,6 +29242,12 @@ async def handle_canvas_action_invoke(params: dict) -> dict | None: return result.value if hasattr(result, 'value') else result client.set_request_handler("canvas.action.invoke", handle_canvas_action_invoke) +# Experimental: this API group is experimental and may change or be removed. +class HooksHandler(Protocol): + async def invoke(self, params: _HookInvokeRequest) -> _HookInvokeResponse: + "Dispatches one SDK callback hook from the runtime to the connection that registered it. Internal transport plumbing: clients opt in through session initialization and the Rust hook processor owns ordering, policy, timeout, and callback routing.\n\nArgs:\n params: Runtime-owned wire payload for a server-to-client hook callback invocation.\n\nReturns:\n Optional output returned by an SDK callback hook." + pass + # Experimental: this API group is experimental and may change or be removed. class LlmInferenceHandler(Protocol): async def http_request_start(self, params: LlmInferenceHTTPRequestStartRequest) -> LlmInferenceHTTPRequestStartResult: @@ -25451,9 +29257,17 @@ async def http_request_chunk(self, params: LlmInferenceHTTPRequestChunkRequest) "Delivers a body byte range (or a cancellation signal) for a request previously announced via httpRequestStart, correlated by requestId. The runtime fires at least one chunk per request — when there is no body, a single chunk with empty data and end=true. Mid-stream the runtime may send a chunk with cancel=true to abort the request; the SDK then stops issuing httpResponseChunk frames and may emit a terminal httpResponseChunk with error set.\n\nArgs:\n params: A request body chunk or cancellation signal.\n\nReturns:\n Acknowledgement. The SDK is free to ignore the ack and treat chunk delivery as fire-and-forget." pass +# Experimental: this API group is experimental and may change or be removed. +class GitHubTelemetryHandler(Protocol): + async def event(self, params: GitHubTelemetryNotification) -> None: + "Forwards a single GitHub telemetry event to a host connection that opted into telemetry forwarding during the `server.connect` handshake. Opted-in connections receive every event the runtime emits after the handshake — across all sessions, plus sessionless events (for example, `server.sendTelemetry` calls with no session id).\n\nArgs:\n params: Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake." + pass + @dataclass class ClientGlobalApiHandlers: + hooks: HooksHandler | None = None llm_inference: LlmInferenceHandler | None = None + git_hub_telemetry: GitHubTelemetryHandler | None = None def register_client_global_api_handlers( client: "JsonRpcClient", @@ -25465,6 +29279,13 @@ def register_client_global_api_handlers( session_id dispatch key; a single set of handlers serves the entire connection. """ + async def handle_hooks_invoke(params: dict) -> dict | None: + request = _HookInvokeRequest.from_dict(params) + handler = handlers.hooks + if handler is None: raise RuntimeError("No hooks client-global handler registered") + result = await handler.invoke(request) + return result.to_dict() + client.set_request_handler("hooks.invoke", handle_hooks_invoke) async def handle_llm_inference_http_request_start(params: dict) -> dict | None: request = LlmInferenceHTTPRequestStartRequest.from_dict(params) handler = handlers.llm_inference @@ -25479,6 +29300,13 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: result = await handler.http_request_chunk(request) return result.to_dict() client.set_request_handler("llmInference.httpRequestChunk", handle_llm_inference_http_request_chunk) + async def handle_git_hub_telemetry_event(params: dict) -> None: + request = GitHubTelemetryNotification.from_dict(params) + handler = handlers.git_hub_telemetry + if handler is None: return None + await handler.event(request) + return None + client.set_notification_method_handler("gitHubTelemetry.event", handle_git_hub_telemetry_event) __all__ = [ "APIKeyAuthInfo", @@ -25495,6 +29323,7 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "AccountLogoutRequest", "AccountLogoutResult", "AccountQuotaSnapshot", + "AdaptiveThinkingSupport", "AdditionalContentExclusionPolicyScope", "AgentApi", "AgentDiscoveryPath", @@ -25533,7 +29362,6 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "AllowAllPermissionSetResult", "AllowAllPermissionState", "ApprovalKind", - "AuthApi", "AuthInfo", "AuthInfoType", "CancelUserRequestedShellCommandResult", @@ -25566,11 +29394,17 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "CommandsListRequest", "CommandsRespondToQueuedCommandRequest", "CommandsRespondToQueuedCommandResult", + "Compactions", + "CompletionsApi", + "CompletionsGetTriggerCharactersResult", + "CompletionsRequestRequest", + "CompletionsRequestResult", "ConnectRemoteSessionParams", "ConnectedRemoteSessionMetadata", "ConnectedRemoteSessionMetadataKind", "ConnectedRemoteSessionMetadataRepository", "ContentFilterMode", + "ContextHeaviestMessage", "CopilotAPITokenAuthInfo", "CopilotAPITokenAuthInfoType", "CopilotUserResponse", @@ -25581,11 +29415,24 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "CopilotUserResponseQuotaSnapshotsPremiumInteractions", "CurrentModel", "CurrentToolMetadata", + "DebugApi", + "DebugCollectLogsCollectedEntry", + "DebugCollectLogsDestination", + "DebugCollectLogsEntry", + "DebugCollectLogsEntryKind", + "DebugCollectLogsInclude", + "DebugCollectLogsRedaction", + "DebugCollectLogsRequest", + "DebugCollectLogsResult", + "DebugCollectLogsResultKind", + "DebugCollectLogsSkippedEntry", + "DebugCollectLogsSource", "DiscoveredCanvas", "DiscoveredMCPServer", "DiscoveredMCPServerType", "EnqueueCommandParams", "EnqueueCommandResult", + "Entry", "EnvAuthInfo", "EnvAuthInfoType", "EventLogApi", @@ -25623,6 +29470,8 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "ExternalToolTextResultForLlmContentResourceLinkIconTheme", "ExternalToolTextResultForLlmContentResourceLinkType", "ExternalToolTextResultForLlmContentResourceType", + "ExternalToolTextResultForLlmContentShellExit", + "ExternalToolTextResultForLlmContentShellExitType", "ExternalToolTextResultForLlmContentTerminal", "ExternalToolTextResultForLlmContentTerminalType", "ExternalToolTextResultForLlmContentText", @@ -25637,6 +29486,11 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "FolderTrustCheckResult", "GhCLIAuthInfo", "GhCLIAuthInfoType", + "GitHubAuthApi", + "GitHubTelemetryClientInfo", + "GitHubTelemetryEvent", + "GitHubTelemetryHandler", + "GitHubTelemetryNotification", "HMACAuthInfo", "HMACAuthInfoType", "HandlePendingToolCallRequest", @@ -25650,6 +29504,7 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "HistorySummarizeForHandoffResult", "HistoryTruncateRequest", "HistoryTruncateResult", + "HooksHandler", "Host", "HostType", "InstalledPlugin", @@ -25723,6 +29578,10 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "MCPExecuteSamplingParams", "MCPFilteredServer", "MCPGrantType", + "MCPHeadersHandlePendingHeadersRefreshRequest", + "MCPHeadersHandlePendingHeadersRefreshRequestKind", + "MCPHeadersHandlePendingHeadersRefreshRequestRequest", + "MCPHeadersHandlePendingHeadersRefreshRequestResult", "MCPHostState", "MCPIsServerRunningRequest", "MCPIsServerRunningResult", @@ -25734,11 +29593,20 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "MCPOauthLoginResult", "MCPOauthPendingRequestResponse", "MCPOauthPendingRequestResponseKind", - "MCPOauthRespondRequest", - "MCPOauthRespondResult", "MCPRegisterExternalClientRequest", "MCPReloadWithConfigRequest", "MCPRemoveGitHubResult", + "MCPResource", + "MCPResourceAnnotations", + "MCPResourceContent", + "MCPResourceIcon", + "MCPResourceTemplate", + "MCPResourcesListRequest", + "MCPResourcesListResult", + "MCPResourcesListTemplatesRequest", + "MCPResourcesListTemplatesResult", + "MCPResourcesReadRequest", + "MCPResourcesReadResult", "MCPRestartServerRequest", "MCPSamplingExecutionAction", "MCPSamplingExecutionResult", @@ -25758,6 +29626,8 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "MCPStartServerRequest", "MCPStartServersResult", "MCPStopServerRequest", + "MCPToolUI", + "MCPToolUIVisibility", "MCPTools", "MCPUnregisterExternalClientRequest", "MarketplaceAddResult", @@ -25779,12 +29649,17 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "McpAppsSetHostContextDetailsTheme", "McpExecuteSamplingRequest", "McpExecuteSamplingResult", + "McpHeadersApi", "McpOauthApi", "McpOauthLoginGrantType", + "McpResourcesApi", "McpServerAuthConfig", "McpServerConfigHttpOauthGrantType", "MemoryConfiguration", "MetadataApi", + "MetadataContextAttributionResult", + "MetadataContextHeaviestMessagesRequest", + "MetadataContextHeaviestMessagesResult", "MetadataContextInfoRequest", "MetadataContextInfoResult", "MetadataIsProcessingResult", @@ -25803,6 +29678,7 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "Model", "ModelApi", "ModelBilling", + "ModelBillingPromo", "ModelBillingTokenPrices", "ModelBillingTokenPricesLongContext", "ModelCapabilities", @@ -25924,6 +29800,7 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "PermissionRulesSet", "PermissionUrlsConfig", "PermissionUrlsSetUnrestrictedModeParams", + "PermissionsAllowAllMode", "PermissionsApi", "PermissionsConfigureAdditionalContentExclusionPolicy", "PermissionsConfigureAdditionalContentExclusionPolicyRule", @@ -25994,7 +29871,6 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "PluginsReloadRequest", "PluginsUninstallRequest", "PluginsUpdateRequest", - "PollSpawnedSessionsResult", "ProviderAddRequest", "ProviderAddResult", "ProviderApi", @@ -26024,15 +29900,37 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "PushAttachmentFile", "PushAttachmentFileLineRange", "PushAttachmentFileType", + "PushAttachmentGitHubActionsJob", + "PushAttachmentGitHubActionsJobType", + "PushAttachmentGitHubCommit", + "PushAttachmentGitHubCommitType", + "PushAttachmentGitHubFile", + "PushAttachmentGitHubFileDiff", + "PushAttachmentGitHubFileDiffSide", + "PushAttachmentGitHubFileDiffType", + "PushAttachmentGitHubFileType", "PushAttachmentGitHubReference", "PushAttachmentGitHubReferenceType", "PushAttachmentGitHubReferenceTypeEnum", + "PushAttachmentGitHubRelease", + "PushAttachmentGitHubReleaseType", + "PushAttachmentGitHubRepository", + "PushAttachmentGitHubRepositoryType", + "PushAttachmentGitHubSide", + "PushAttachmentGitHubSnippet", + "PushAttachmentGitHubSnippetType", + "PushAttachmentGitHubTreeComparison", + "PushAttachmentGitHubTreeComparisonSide", + "PushAttachmentGitHubTreeComparisonType", + "PushAttachmentGitHubURL", + "PushAttachmentGitHubURLType", "PushAttachmentSelection", "PushAttachmentSelectionDetails", "PushAttachmentSelectionDetailsEnd", "PushAttachmentSelectionDetailsStart", "PushAttachmentSelectionType", "PushAttachmentType", + "PushGitHubRepoRef", "QueueApi", "QueuePendingItems", "QueuePendingItemsKind", @@ -26088,6 +29986,9 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "SecretsAddFilterValuesResult", "SendAgentMode", "SendAttachmentsToMessageParams", + "SendMessageItem", + "SendMessagesRequest", + "SendMessagesResult", "SendMode", "SendRequest", "SendResult", @@ -26095,6 +29996,7 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "ServerAgentList", "ServerAgentRegistryApi", "ServerAgentsApi", + "ServerCommandsApi", "ServerInstructionSourceList", "ServerInstructionsApi", "ServerLlmInferenceApi", @@ -26119,7 +30021,9 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "SessionAuthStatus", "SessionBulkDeleteResult", "SessionCapability", + "SessionCompletionItem", "SessionContext", + "SessionContextAttribution", "SessionContextHostType", "SessionContextInfo", "SessionEnrichMetadataResult", @@ -26165,6 +30069,7 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "SessionMcpAppsCallToolResult", "SessionMetadataSnapshot", "SessionModelList", + "SessionModelPriceCategory", "SessionOpenOptions", "SessionOpenOptionsAdditionalContentExclusionPolicy", "SessionOpenOptionsAdditionalContentExclusionPolicyRule", @@ -26179,11 +30084,22 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "SessionRpc", "SessionSetCredentialsParams", "SessionSetCredentialsResult", + "SessionSettingsBuiltInToolAvailabilitySnapshot", + "SessionSettingsEvaluatePredicateRequest", + "SessionSettingsEvaluatePredicateResult", + "SessionSettingsJobSnapshot", + "SessionSettingsModelSnapshot", + "SessionSettingsOnlineEvaluationSnapshot", + "SessionSettingsPredicateName", + "SessionSettingsRepoSnapshot", + "SessionSettingsSnapshot", + "SessionSettingsValidationSnapshot", "SessionSizes", "SessionSource", "SessionTelemetryEngagement", "SessionUpdateOptionsParams", "SessionUpdateOptionsResult", + "SessionVisibilityStatus", "SessionWorkingDirectoryContext", "SessionWorkingDirectoryContextHostType", "SessionsBulkDeleteRequest", @@ -26227,8 +30143,6 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "SessionsOpenResumeLast", "SessionsOpenResumeLastKind", "SessionsOpenStatus", - "SessionsPollSpawnedSessionsEvent", - "SessionsPollSpawnedSessionsRequest", "SessionsPruneOldRequest", "SessionsRegisterExtensionToolsOnSessionOptions", "SessionsReleaseLockRequest", @@ -26272,6 +30186,7 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "SlashCommandCompletedResultKind", "SlashCommandInfo", "SlashCommandInput", + "SlashCommandInputChoice", "SlashCommandInputCompletion", "SlashCommandInvocationResult", "SlashCommandInvocationResultKind", @@ -26366,8 +30281,11 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "UIHandlePendingExitPlanModeRequest", "UIHandlePendingResult", "UIHandlePendingSamplingRequest", + "UIHandlePendingSessionLimitsExhaustedRequest", "UIHandlePendingUserInputRequest", "UIRegisterDirectAutoModeSwitchHandlerResult", + "UISessionLimitsExhaustedResponse", + "UISessionLimitsExhaustedResponseAction", "UIUnregisterDirectAutoModeSwitchHandlerRequest", "UIUnregisterDirectAutoModeSwitchHandlerResult", "UIUserInputResponse", @@ -26384,6 +30302,14 @@ async def handle_llm_inference_http_request_chunk(params: dict) -> dict | None: "UserAuthInfo", "UserAuthInfoType", "UserRequestedShellCommandResult", + "UserSettingMetadata", + "UserSettingsGetResult", + "UserSettingsSetRequest", + "UserSettingsSetResult", + "VisibilityApi", + "VisibilityGetResult", + "VisibilitySetRequest", + "VisibilitySetResult", "Workspace", "WorkspaceDiffFileChange", "WorkspaceDiffFileChangeType", diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index 0a3666c094..a7c990e169 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -136,6 +136,7 @@ class SessionEventType(Enum): SESSION_WARNING = "session.warning" SESSION_MODEL_CHANGE = "session.model_change" SESSION_MODE_CHANGED = "session.mode_changed" + SESSION_SESSION_LIMITS_CHANGED = "session.session_limits_changed" SESSION_PERMISSIONS_CHANGED = "session.permissions_changed" SESSION_PLAN_CHANGED = "session.plan_changed" SESSION_TODOS_CHANGED = "session.todos_changed" @@ -144,6 +145,7 @@ class SessionEventType(Enum): SESSION_TRUNCATION = "session.truncation" SESSION_SNAPSHOT_REWIND = "session.snapshot_rewind" SESSION_SHUTDOWN = "session.shutdown" + SESSION_USAGE_CHECKPOINT = "session.usage_checkpoint" SESSION_CONTEXT_CHANGED = "session.context_changed" SESSION_USAGE_INFO = "session.usage_info" SESSION_COMPACTION_START = "session.compaction_start" @@ -153,13 +155,16 @@ class SessionEventType(Enum): PENDING_MESSAGES_MODIFIED = "pending_messages.modified" ASSISTANT_TURN_START = "assistant.turn_start" ASSISTANT_INTENT = "assistant.intent" + ASSISTANT_SERVER_TOOL_PROGRESS = "assistant.server_tool_progress" ASSISTANT_REASONING = "assistant.reasoning" ASSISTANT_REASONING_DELTA = "assistant.reasoning_delta" + ASSISTANT_TOOL_CALL_DELTA = "assistant.tool_call_delta" ASSISTANT_STREAMING_DELTA = "assistant.streaming_delta" ASSISTANT_MESSAGE = "assistant.message" ASSISTANT_MESSAGE_START = "assistant.message_start" ASSISTANT_MESSAGE_DELTA = "assistant.message_delta" ASSISTANT_TURN_END = "assistant.turn_end" + ASSISTANT_IDLE = "assistant.idle" ASSISTANT_USAGE = "assistant.usage" MODEL_CALL_FAILURE = "model.call_failure" ABORT = "abort" @@ -191,6 +196,8 @@ class SessionEventType(Enum): SAMPLING_COMPLETED = "sampling.completed" MCP_OAUTH_REQUIRED = "mcp.oauth_required" MCP_OAUTH_COMPLETED = "mcp.oauth_completed" + MCP_HEADERS_REFRESH_REQUIRED = "mcp.headers_refresh_required" + MCP_HEADERS_REFRESH_COMPLETED = "mcp.headers_refresh_completed" SESSION_CUSTOM_NOTIFICATION = "session.custom_notification" EXTERNAL_TOOL_REQUESTED = "external_tool.requested" EXTERNAL_TOOL_COMPLETED = "external_tool.completed" @@ -199,6 +206,12 @@ class SessionEventType(Enum): COMMAND_COMPLETED = "command.completed" AUTO_MODE_SWITCH_REQUESTED = "auto_mode_switch.requested" AUTO_MODE_SWITCH_COMPLETED = "auto_mode_switch.completed" + SESSION_LIMITS_EXHAUSTED_REQUESTED = "session_limits_exhausted.requested" + SESSION_LIMITS_EXHAUSTED_COMPLETED = "session_limits_exhausted.completed" + # Experimental: this event is part of an experimental API and may change or be removed. + SESSION_AUTO_MODE_RESOLVED = "session.auto_mode_resolved" + # Experimental: this event is part of an experimental API and may change or be removed. + SESSION_MANAGED_SETTINGS_RESOLVED = "session.managed_settings_resolved" COMMANDS_CHANGED = "commands.changed" CAPABILITIES_CHANGED = "capabilities.changed" EXIT_PLAN_MODE_REQUESTED = "exit_plan_mode.requested" @@ -209,6 +222,9 @@ class SessionEventType(Enum): SESSION_CUSTOM_AGENTS_UPDATED = "session.custom_agents_updated" SESSION_MCP_SERVERS_LOADED = "session.mcp_servers_loaded" SESSION_MCP_SERVER_STATUS_CHANGED = "session.mcp_server_status_changed" + MCP_TOOLS_LIST_CHANGED = "mcp.tools.list_changed" + MCP_RESOURCES_LIST_CHANGED = "mcp.resources.list_changed" + MCP_PROMPTS_LIST_CHANGED = "mcp.prompts.list_changed" SESSION_EXTENSIONS_LOADED = "session.extensions_loaded" # Experimental: this event is part of an experimental API and may change or be removed. SESSION_CANVAS_OPENED = "session.canvas.opened" @@ -287,16 +303,63 @@ class Data: def __init__(self, **kwargs: Any): self._values = {key: _compat_from_json_value(value) for key, value in kwargs.items()} + self._json_keys: dict[str, str] = {} + self._json_values: dict[str, Any] | None = None for key, value in self._values.items(): setattr(self, key, value) @staticmethod def from_dict(obj: Any) -> "Data": assert isinstance(obj, dict) - return Data(**{_compat_to_python_key(key): _compat_from_json_value(value) for key, value in obj.items()}) + data = Data() + data._values = {} + data._json_keys = {} + data._json_values = {} + for key, value in obj.items(): + py_key = _compat_to_python_key(key) + json_value = _compat_from_json_value(value) + data._values[py_key] = json_value + data._json_keys[py_key] = key + data._json_values[key] = json_value + setattr(data, py_key, data._values[py_key]) + return data def to_dict(self) -> dict: - return {_compat_to_json_key(key): _compat_to_json_value(value) for key, value in self._values.items() if value is not None} + if self._json_values is not None: + return {key: _compat_to_json_value(value) for key, value in self._json_values.items() if value is not None} + return {(self._json_keys.get(key) or _compat_to_json_key(key)): _compat_to_json_value(value) for key, value in self._values.items() if value is not None} + + +# Deprecated: this type is deprecated and will be removed in a future version. +@dataclass +class ToolExecutionCompleteContentTerminal: + "Deprecated for shell command exit metadata. Use ToolExecutionCompleteContentShellExit instead." + text: str + type: ClassVar[str] = "terminal" + cwd: str | None = None + exit_code: int | None = None + + @staticmethod + def from_dict(obj: Any) -> "ToolExecutionCompleteContentTerminal": + assert isinstance(obj, dict) + text = from_str(obj.get("text")) + cwd = from_union([from_none, from_str], obj.get("cwd")) + exit_code = from_union([from_none, from_int], obj.get("exitCode")) + return ToolExecutionCompleteContentTerminal( + text=text, + cwd=cwd, + exit_code=exit_code, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["text"] = from_str(self.text) + result["type"] = self.type + if self.cwd is not None: + result["cwd"] = from_union([from_none, from_str], self.cwd) + if self.exit_code is not None: + result["exitCode"] = from_union([from_none, to_int], self.exit_code) + return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -384,13 +447,14 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CanvasRegistryChangedCanvas: - "Schema for the `CanvasRegistryChangedCanvas` type." + "A single canvas declaration in `session.canvas.registry_changed`, including provider IDs, display metadata, input schema, and actions." canvas_id: str description: str display_name: str extension_id: str actions: list[CanvasRegistryChangedCanvasAction] | None = None extension_name: str | None = None + icon: str | None = None input_schema: Any = None @staticmethod @@ -402,6 +466,7 @@ def from_dict(obj: Any) -> "CanvasRegistryChangedCanvas": extension_id = from_str(obj.get("extensionId")) actions = from_union([from_none, lambda x: from_list(CanvasRegistryChangedCanvasAction.from_dict, x)], obj.get("actions")) extension_name = from_union([from_none, from_str], obj.get("extensionName")) + icon = from_union([from_none, from_str], obj.get("icon")) input_schema = obj.get("inputSchema") return CanvasRegistryChangedCanvas( canvas_id=canvas_id, @@ -410,6 +475,7 @@ def from_dict(obj: Any) -> "CanvasRegistryChangedCanvas": extension_id=extension_id, actions=actions, extension_name=extension_name, + icon=icon, input_schema=input_schema, ) @@ -423,6 +489,8 @@ def to_dict(self) -> dict: result["actions"] = from_union([from_none, lambda x: from_list(lambda x: to_class(CanvasRegistryChangedCanvasAction, x), x)], self.actions) if self.extension_name is not None: result["extensionName"] = from_union([from_none, from_str], self.extension_name) + if self.icon is not None: + result["icon"] = from_union([from_none, from_str], self.icon) if self.input_schema is not None: result["inputSchema"] = self.input_schema return result @@ -431,7 +499,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CanvasRegistryChangedCanvasAction: - "Schema for the `CanvasRegistryChangedCanvasAction` type." + "A single action within a canvas declaration, with its name, optional description, and optional input schema." name: str description: str | None = None input_schema: Any = None @@ -743,10 +811,80 @@ def to_dict(self) -> dict: return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PermissionAutoApproval: + "Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is \"auto\"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request." + recommendation: AutoApprovalRecommendation + reason: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "PermissionAutoApproval": + assert isinstance(obj, dict) + recommendation = parse_enum(AutoApprovalRecommendation, obj.get("recommendation")) + reason = from_union([from_none, from_str], obj.get("reason")) + return PermissionAutoApproval( + recommendation=recommendation, + reason=reason, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["recommendation"] = to_enum(AutoApprovalRecommendation, self.recommendation) + if self.reason is not None: + result["reason"] = from_union([from_none, from_str], self.reason) + return result + + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionAutoModeResolvedData: + "Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability." + chosen_model: str + candidate_models: list[str] | None = None + category_scores: dict[str, float] | None = None + confidence: float | None = None + predicted_label: str | None = None + reasoning_bucket: AutoModeResolvedReasoningBucket | None = None + + @staticmethod + def from_dict(obj: Any) -> "SessionAutoModeResolvedData": + assert isinstance(obj, dict) + chosen_model = from_str(obj.get("chosenModel")) + candidate_models = from_union([from_none, lambda x: from_list(from_str, x)], obj.get("candidateModels")) + category_scores = from_union([from_none, lambda x: from_dict(from_float, x)], obj.get("categoryScores")) + confidence = from_union([from_none, from_float], obj.get("confidence")) + predicted_label = from_union([from_none, from_str], obj.get("predictedLabel")) + reasoning_bucket = from_union([from_none, lambda x: parse_enum(AutoModeResolvedReasoningBucket, x)], obj.get("reasoningBucket")) + return SessionAutoModeResolvedData( + chosen_model=chosen_model, + candidate_models=candidate_models, + category_scores=category_scores, + confidence=confidence, + predicted_label=predicted_label, + reasoning_bucket=reasoning_bucket, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["chosenModel"] = from_str(self.chosen_model) + if self.candidate_models is not None: + result["candidateModels"] = from_union([from_none, lambda x: from_list(from_str, x)], self.candidate_models) + if self.category_scores is not None: + result["categoryScores"] = from_union([from_none, lambda x: from_dict(to_float, x)], self.category_scores) + if self.confidence is not None: + result["confidence"] = from_union([from_none, to_float], self.confidence) + if self.predicted_label is not None: + result["predictedLabel"] = from_union([from_none, from_str], self.predicted_label) + if self.reasoning_bucket is not None: + result["reasoningBucket"] = from_union([from_none, lambda x: to_enum(AutoModeResolvedReasoningBucket, x)], self.reasoning_bucket) + return result + + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionCanvasClosedData: - "Schema for the `CanvasClosedData` type." + "Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID." canvas_id: str extension_id: str instance_id: str @@ -774,11 +912,12 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionCanvasOpenedData: - "Schema for the `CanvasOpenedData` type." + "Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input." canvas_id: str extension_id: str instance_id: str extension_name: str | None = None + icon: str | None = None input: Any = None status: str | None = None title: str | None = None @@ -791,6 +930,7 @@ def from_dict(obj: Any) -> "SessionCanvasOpenedData": extension_id = from_str(obj.get("extensionId")) instance_id = from_str(obj.get("instanceId")) extension_name = from_union([from_none, from_str], obj.get("extensionName")) + icon = from_union([from_none, from_str], obj.get("icon")) input = obj.get("input") status = from_union([from_none, from_str], obj.get("status")) title = from_union([from_none, from_str], obj.get("title")) @@ -800,6 +940,7 @@ def from_dict(obj: Any) -> "SessionCanvasOpenedData": extension_id=extension_id, instance_id=instance_id, extension_name=extension_name, + icon=icon, input=input, status=status, title=title, @@ -813,6 +954,8 @@ def to_dict(self) -> dict: result["instanceId"] = from_str(self.instance_id) if self.extension_name is not None: result["extensionName"] = from_union([from_none, from_str], self.extension_name) + if self.icon is not None: + result["icon"] = from_union([from_none, from_str], self.icon) if self.input is not None: result["input"] = self.input if self.status is not None: @@ -865,7 +1008,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionCanvasRegistryChangedData: - "Schema for the `CanvasRegistryChangedData` type." + "Payload of `session.canvas.registry_changed` listing the canvas declarations currently available." canvases: list[CanvasRegistryChangedCanvas] @staticmethod @@ -938,6 +1081,51 @@ def to_dict(self) -> dict: return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionManagedSettingsResolvedData: + "Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes." + bypass_permissions_disabled: bool + device_managed: bool + fail_closed: bool + managed_keys: list[str] + server_managed: bool + source: ManagedSettingsResolvedSource + settings: Any = None + + @staticmethod + def from_dict(obj: Any) -> "SessionManagedSettingsResolvedData": + assert isinstance(obj, dict) + bypass_permissions_disabled = from_bool(obj.get("bypassPermissionsDisabled")) + device_managed = from_bool(obj.get("deviceManaged")) + fail_closed = from_bool(obj.get("failClosed")) + managed_keys = from_list(from_str, obj.get("managedKeys")) + server_managed = from_bool(obj.get("serverManaged")) + source = parse_enum(ManagedSettingsResolvedSource, obj.get("source")) + settings = obj.get("settings") + return SessionManagedSettingsResolvedData( + bypass_permissions_disabled=bypass_permissions_disabled, + device_managed=device_managed, + fail_closed=fail_closed, + managed_keys=managed_keys, + server_managed=server_managed, + source=source, + settings=settings, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["bypassPermissionsDisabled"] = from_bool(self.bypass_permissions_disabled) + result["deviceManaged"] = from_bool(self.device_managed) + result["failClosed"] = from_bool(self.fail_closed) + result["managedKeys"] = from_list(from_str, self.managed_keys) + result["serverManaged"] = from_bool(self.server_managed) + result["source"] = to_enum(ManagedSettingsResolvedSource, self.source) + if self.settings is not None: + result["settings"] = self.settings + return result + + @dataclass class AbortData: "Turn abort information including the reason for termination" @@ -957,6 +1145,26 @@ def to_dict(self) -> dict: return result +@dataclass +class AssistantIdleData: + "Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred" + aborted: bool | None = None + + @staticmethod + def from_dict(obj: Any) -> "AssistantIdleData": + assert isinstance(obj, dict) + aborted = from_union([from_none, from_bool], obj.get("aborted")) + return AssistantIdleData( + aborted=aborted, + ) + + def to_dict(self) -> dict: + result: dict = {} + if self.aborted is not None: + result["aborted"] = from_union([from_none, from_bool], self.aborted) + return result + + @dataclass class AssistantIntentData: "Agent intent description for current activity or plan" @@ -984,6 +1192,7 @@ class AssistantMessageData: api_call_id: str | None = None # Experimental: this field is part of an experimental API and may change or be removed. citations: Citations | None = None + client_request_id: str | None = None encrypted_content: str | None = None interaction_id: str | None = None model: str | None = None @@ -993,6 +1202,7 @@ class AssistantMessageData: phase: str | None = None reasoning_opaque: str | None = None reasoning_text: str | None = None + reasoning_wire_field: str | None = None request_id: str | None = None server_tools: AssistantMessageServerTools | None = None service_request_id: str | None = None @@ -1006,6 +1216,7 @@ def from_dict(obj: Any) -> "AssistantMessageData": message_id = from_str(obj.get("messageId")) api_call_id = from_union([from_none, from_str], obj.get("apiCallId")) citations = from_union([from_none, Citations.from_dict], obj.get("citations")) + client_request_id = from_union([from_none, from_str], obj.get("clientRequestId")) encrypted_content = from_union([from_none, from_str], obj.get("encryptedContent")) interaction_id = from_union([from_none, from_str], obj.get("interactionId")) model = from_union([from_none, from_str], obj.get("model")) @@ -1014,6 +1225,7 @@ def from_dict(obj: Any) -> "AssistantMessageData": phase = from_union([from_none, from_str], obj.get("phase")) reasoning_opaque = from_union([from_none, from_str], obj.get("reasoningOpaque")) reasoning_text = from_union([from_none, from_str], obj.get("reasoningText")) + reasoning_wire_field = from_union([from_none, from_str], obj.get("reasoningWireField")) request_id = from_union([from_none, from_str], obj.get("requestId")) server_tools = from_union([from_none, AssistantMessageServerTools.from_dict], obj.get("serverTools")) service_request_id = from_union([from_none, from_str], obj.get("serviceRequestId")) @@ -1024,6 +1236,7 @@ def from_dict(obj: Any) -> "AssistantMessageData": message_id=message_id, api_call_id=api_call_id, citations=citations, + client_request_id=client_request_id, encrypted_content=encrypted_content, interaction_id=interaction_id, model=model, @@ -1032,6 +1245,7 @@ def from_dict(obj: Any) -> "AssistantMessageData": phase=phase, reasoning_opaque=reasoning_opaque, reasoning_text=reasoning_text, + reasoning_wire_field=reasoning_wire_field, request_id=request_id, server_tools=server_tools, service_request_id=service_request_id, @@ -1047,6 +1261,8 @@ def to_dict(self) -> dict: result["apiCallId"] = from_union([from_none, from_str], self.api_call_id) if self.citations is not None: result["citations"] = from_union([from_none, lambda x: to_class(Citations, x)], self.citations) + if self.client_request_id is not None: + result["clientRequestId"] = from_union([from_none, from_str], self.client_request_id) if self.encrypted_content is not None: result["encryptedContent"] = from_union([from_none, from_str], self.encrypted_content) if self.interaction_id is not None: @@ -1063,6 +1279,8 @@ def to_dict(self) -> dict: result["reasoningOpaque"] = from_union([from_none, from_str], self.reasoning_opaque) if self.reasoning_text is not None: result["reasoningText"] = from_union([from_none, from_str], self.reasoning_text) + if self.reasoning_wire_field is not None: + result["reasoningWireField"] = from_union([from_none, from_str], self.reasoning_wire_field) if self.request_id is not None: result["requestId"] = from_union([from_none, from_str], self.request_id) if self.server_tools is not None: @@ -1228,6 +1446,33 @@ def to_dict(self) -> dict: return result +@dataclass +class AssistantServerToolProgressData: + "Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message" + kind: str + output_index: int + status: str + + @staticmethod + def from_dict(obj: Any) -> "AssistantServerToolProgressData": + assert isinstance(obj, dict) + kind = from_str(obj.get("kind")) + output_index = from_int(obj.get("outputIndex")) + status = from_str(obj.get("status")) + return AssistantServerToolProgressData( + kind=kind, + output_index=output_index, + status=status, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = from_str(self.kind) + result["outputIndex"] = to_int(self.output_index) + result["status"] = from_str(self.status) + return result + + @dataclass class AssistantStreamingDeltaData: "Streaming response progress with cumulative byte count" @@ -1247,22 +1492,60 @@ def to_dict(self) -> dict: return result +@dataclass +class AssistantToolCallDeltaData: + "Streaming tool-call input delta for incremental tool-call updates" + input_delta: str + tool_call_id: str + tool_name: str | None = None + tool_type: AssistantMessageToolRequestType | None = None + + @staticmethod + def from_dict(obj: Any) -> "AssistantToolCallDeltaData": + assert isinstance(obj, dict) + input_delta = from_str(obj.get("inputDelta")) + tool_call_id = from_str(obj.get("toolCallId")) + tool_name = from_union([from_none, from_str], obj.get("toolName")) + tool_type = from_union([from_none, lambda x: parse_enum(AssistantMessageToolRequestType, x)], obj.get("toolType")) + return AssistantToolCallDeltaData( + input_delta=input_delta, + tool_call_id=tool_call_id, + tool_name=tool_name, + tool_type=tool_type, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["inputDelta"] = from_str(self.input_delta) + result["toolCallId"] = from_str(self.tool_call_id) + if self.tool_name is not None: + result["toolName"] = from_union([from_none, from_str], self.tool_name) + if self.tool_type is not None: + result["toolType"] = from_union([from_none, lambda x: to_enum(AssistantMessageToolRequestType, x)], self.tool_type) + return result + + @dataclass class AssistantTurnEndData: "Turn completion metadata including the turn identifier" turn_id: str + model: str | None = None @staticmethod def from_dict(obj: Any) -> "AssistantTurnEndData": assert isinstance(obj, dict) turn_id = from_str(obj.get("turnId")) + model = from_union([from_none, from_str], obj.get("model")) return AssistantTurnEndData( turn_id=turn_id, + model=model, ) def to_dict(self) -> dict: result: dict = {} result["turnId"] = from_str(self.turn_id) + if self.model is not None: + result["model"] = from_union([from_none, from_str], self.model) return result @@ -1271,15 +1554,18 @@ class AssistantTurnStartData: "Turn initialization metadata including identifier and interaction tracking" turn_id: str interaction_id: str | None = None + model: str | None = None @staticmethod def from_dict(obj: Any) -> "AssistantTurnStartData": assert isinstance(obj, dict) turn_id = from_str(obj.get("turnId")) interaction_id = from_union([from_none, from_str], obj.get("interactionId")) + model = from_union([from_none, from_str], obj.get("model")) return AssistantTurnStartData( turn_id=turn_id, interaction_id=interaction_id, + model=model, ) def to_dict(self) -> dict: @@ -1287,6 +1573,8 @@ def to_dict(self) -> dict: result["turnId"] = from_str(self.turn_id) if self.interaction_id is not None: result["interactionId"] = from_union([from_none, from_str], self.interaction_id) + if self.model is not None: + result["model"] = from_union([from_none, from_str], self.model) return result @@ -1464,13 +1752,13 @@ def to_dict(self) -> dict: if self.service_request_id is not None: result["serviceRequestId"] = from_union([from_none, from_str], self.service_request_id) if self.time_to_first_token is not None: - result["timeToFirstTokenMs"] = from_union([from_none, to_timedelta_int], self.time_to_first_token) + result["timeToFirstTokenMs"] = from_union([from_none, to_timedelta], self.time_to_first_token) return result @dataclass class _AssistantUsageQuotaSnapshot: - "Schema for the `_AssistantUsageQuotaSnapshot` type." + "Internal per-quota snapshot for assistant usage, including entitlement, consumed requests, overage, reset date, and remaining quota." # Internal: this field is an internal SDK API and is not part of the public surface. _entitlement_requests: int # Internal: this field is an internal SDK API and is not part of the public surface. @@ -1740,6 +2028,172 @@ def to_dict(self) -> dict: return result +@dataclass +class AttachmentGitHubActionsJob: + "Pointer to a GitHub Actions job." + job_id: int + job_name: str + repo: GitHubRepoRef + type: ClassVar[str] = "github_actions_job" + url: str + workflow_name: str + conclusion: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubActionsJob": + assert isinstance(obj, dict) + job_id = from_int(obj.get("jobId")) + job_name = from_str(obj.get("jobName")) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + workflow_name = from_str(obj.get("workflowName")) + conclusion = from_union([from_none, from_str], obj.get("conclusion")) + return AttachmentGitHubActionsJob( + job_id=job_id, + job_name=job_name, + repo=repo, + url=url, + workflow_name=workflow_name, + conclusion=conclusion, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["jobId"] = to_int(self.job_id) + result["jobName"] = from_str(self.job_name) + result["repo"] = to_class(GitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + result["workflowName"] = from_str(self.workflow_name) + if self.conclusion is not None: + result["conclusion"] = from_union([from_none, from_str], self.conclusion) + return result + + +@dataclass +class AttachmentGitHubCommit: + "Pointer to a GitHub commit." + message: str + oid: str + repo: GitHubRepoRef + type: ClassVar[str] = "github_commit" + url: str + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubCommit": + assert isinstance(obj, dict) + message = from_str(obj.get("message")) + oid = from_str(obj.get("oid")) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + return AttachmentGitHubCommit( + message=message, + oid=oid, + repo=repo, + url=url, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["message"] = from_str(self.message) + result["oid"] = from_str(self.oid) + result["repo"] = to_class(GitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + + +@dataclass +class AttachmentGitHubFile: + "Pointer to a file in a GitHub repository at a specific ref." + path: str + ref: str + repo: GitHubRepoRef + type: ClassVar[str] = "github_file" + url: str + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubFile": + assert isinstance(obj, dict) + path = from_str(obj.get("path")) + ref = from_str(obj.get("ref")) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + return AttachmentGitHubFile( + path=path, + ref=ref, + repo=repo, + url=url, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["path"] = from_str(self.path) + result["ref"] = from_str(self.ref) + result["repo"] = to_class(GitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + + +@dataclass +class AttachmentGitHubFileDiff: + "Pointer to a single-file diff. At least one of `head` and `base` must be present." + type: ClassVar[str] = "github_file_diff" + url: str + base: AttachmentGitHubFileDiffSide | None = None + head: AttachmentGitHubFileDiffSide | None = None + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubFileDiff": + assert isinstance(obj, dict) + url = from_str(obj.get("url")) + base = from_union([from_none, AttachmentGitHubFileDiffSide.from_dict], obj.get("base")) + head = from_union([from_none, AttachmentGitHubFileDiffSide.from_dict], obj.get("head")) + return AttachmentGitHubFileDiff( + url=url, + base=base, + head=head, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = self.type + result["url"] = from_str(self.url) + if self.base is not None: + result["base"] = from_union([from_none, lambda x: to_class(AttachmentGitHubFileDiffSide, x)], self.base) + if self.head is not None: + result["head"] = from_union([from_none, lambda x: to_class(AttachmentGitHubFileDiffSide, x)], self.head) + return result + + +@dataclass +class AttachmentGitHubFileDiffSide: + "One side of a file diff (head or base)" + path: str + ref: str + repo: GitHubRepoRef + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubFileDiffSide": + assert isinstance(obj, dict) + path = from_str(obj.get("path")) + ref = from_str(obj.get("ref")) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + return AttachmentGitHubFileDiffSide( + path=path, + ref=ref, + repo=repo, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["path"] = from_str(self.path) + result["ref"] = from_str(self.ref) + result["repo"] = to_class(GitHubRepoRef, self.repo) + return result + + @dataclass class AttachmentGitHubReference: "GitHub issue, pull request, or discussion reference" @@ -1777,6 +2231,184 @@ def to_dict(self) -> dict: return result +@dataclass +class AttachmentGitHubRelease: + "Pointer to a GitHub release." + name: str + repo: GitHubRepoRef + tag_name: str + type: ClassVar[str] = "github_release" + url: str + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubRelease": + assert isinstance(obj, dict) + name = from_str(obj.get("name")) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + tag_name = from_str(obj.get("tagName")) + url = from_str(obj.get("url")) + return AttachmentGitHubRelease( + name=name, + repo=repo, + tag_name=tag_name, + url=url, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["name"] = from_str(self.name) + result["repo"] = to_class(GitHubRepoRef, self.repo) + result["tagName"] = from_str(self.tag_name) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + + +@dataclass +class AttachmentGitHubRepository: + "Pointer to a GitHub repository." + repo: GitHubRepoRef + type: ClassVar[str] = "github_repository" + url: str + description: str | None = None + ref: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubRepository": + assert isinstance(obj, dict) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + description = from_union([from_none, from_str], obj.get("description")) + ref = from_union([from_none, from_str], obj.get("ref")) + return AttachmentGitHubRepository( + repo=repo, + url=url, + description=description, + ref=ref, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["repo"] = to_class(GitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + if self.description is not None: + result["description"] = from_union([from_none, from_str], self.description) + if self.ref is not None: + result["ref"] = from_union([from_none, from_str], self.ref) + return result + + +@dataclass +class AttachmentGitHubSnippet: + "Pointer to a line range inside a file in a GitHub repository." + line_range: AttachmentFileLineRange + path: str + ref: str + repo: GitHubRepoRef + type: ClassVar[str] = "github_snippet" + url: str + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubSnippet": + assert isinstance(obj, dict) + line_range = AttachmentFileLineRange.from_dict(obj.get("lineRange")) + path = from_str(obj.get("path")) + ref = from_str(obj.get("ref")) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + url = from_str(obj.get("url")) + return AttachmentGitHubSnippet( + line_range=line_range, + path=path, + ref=ref, + repo=repo, + url=url, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["lineRange"] = to_class(AttachmentFileLineRange, self.line_range) + result["path"] = from_str(self.path) + result["ref"] = from_str(self.ref) + result["repo"] = to_class(GitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + + +@dataclass +class AttachmentGitHubTreeComparison: + "Pointer to a comparison between two git revisions." + base: AttachmentGitHubTreeComparisonSide + head: AttachmentGitHubTreeComparisonSide + type: ClassVar[str] = "github_tree_comparison" + url: str + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubTreeComparison": + assert isinstance(obj, dict) + base = AttachmentGitHubTreeComparisonSide.from_dict(obj.get("base")) + head = AttachmentGitHubTreeComparisonSide.from_dict(obj.get("head")) + url = from_str(obj.get("url")) + return AttachmentGitHubTreeComparison( + base=base, + head=head, + url=url, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["base"] = to_class(AttachmentGitHubTreeComparisonSide, self.base) + result["head"] = to_class(AttachmentGitHubTreeComparisonSide, self.head) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + + +@dataclass +class AttachmentGitHubTreeComparisonSide: + "One side of a tree comparison (head or base)" + repo: GitHubRepoRef + revision: str + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubTreeComparisonSide": + assert isinstance(obj, dict) + repo = GitHubRepoRef.from_dict(obj.get("repo")) + revision = from_str(obj.get("revision")) + return AttachmentGitHubTreeComparisonSide( + repo=repo, + revision=revision, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["repo"] = to_class(GitHubRepoRef, self.repo) + result["revision"] = from_str(self.revision) + return result + + +@dataclass +class AttachmentGitHubUrl: + "Generic GitHub URL reference." + type: ClassVar[str] = "github_url" + url: str + + @staticmethod + def from_dict(obj: Any) -> "AttachmentGitHubUrl": + assert isinstance(obj, dict) + url = from_str(obj.get("url")) + return AttachmentGitHubUrl( + url=url, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = self.type + result["url"] = from_str(self.url) + return result + + @dataclass class AttachmentSelection: "Code selection attachment from an editor" @@ -2056,7 +2688,7 @@ def to_dict(self) -> dict: @dataclass class CommandsChangedCommand: - "Schema for the `CommandsChangedCommand` type." + "A single slash command available in the session, as listed by the `commands.changed` event." name: str description: str | None = None @@ -2206,7 +2838,7 @@ def to_dict(self) -> dict: @dataclass class CustomAgentsUpdatedAgent: - "Schema for the `CustomAgentsUpdatedAgent` type." + "A single loaded custom agent in `session.custom_agents_updated`, with identity, source, tools, invocability, and model override." description: str display_name: str id: str @@ -2359,7 +2991,7 @@ def to_dict(self) -> dict: @dataclass class EmbeddedBlobResourceContents: - "Schema for the `EmbeddedBlobResourceContents` type." + "Embedded binary resource contents identified by a URI, with an optional MIME type and a base64-encoded blob." blob: str uri: str mime_type: str | None = None @@ -2387,7 +3019,7 @@ def to_dict(self) -> dict: @dataclass class EmbeddedTextResourceContents: - "Schema for the `EmbeddedTextResourceContents` type." + "Embedded text resource contents identified by a URI, with an optional MIME type and a text payload." text: str uri: str mime_type: str | None = None @@ -2489,7 +3121,7 @@ def to_dict(self) -> dict: @dataclass class ExtensionsLoadedExtension: - "Schema for the `ExtensionsLoadedExtension` type." + "A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status." id: str name: str source: ExtensionsLoadedExtensionSource @@ -2588,6 +3220,34 @@ def to_dict(self) -> dict: return result +@dataclass +class GitHubRepoRef: + "Pointer to a GitHub repository." + name: str + owner: str + id: int | None = None + + @staticmethod + def from_dict(obj: Any) -> "GitHubRepoRef": + assert isinstance(obj, dict) + name = from_str(obj.get("name")) + owner = from_str(obj.get("owner")) + id = from_union([from_none, from_int], obj.get("id")) + return GitHubRepoRef( + name=name, + owner=owner, + id=id, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["name"] = from_str(self.name) + result["owner"] = from_str(self.owner) + if self.id is not None: + result["id"] = from_union([from_none, to_int], self.id) + return result + + @dataclass class HandoffRepository: "Repository context for the handed-off session" @@ -2616,6 +3276,29 @@ def to_dict(self) -> dict: return result +@dataclass +class HeaderEntry: + "Single HTTP header entry as a name/value pair." + name: str + value: str + + @staticmethod + def from_dict(obj: Any) -> "HeaderEntry": + assert isinstance(obj, dict) + name = from_str(obj.get("name")) + value = from_str(obj.get("value")) + return HeaderEntry( + name=name, + value=value, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["name"] = from_str(self.name) + result["value"] = from_str(self.value) + return result + + @dataclass class HookEndData: "Hook invocation completion details including output, success status, and error information" @@ -2826,7 +3509,7 @@ def to_dict(self) -> dict: @dataclass class McpAppToolCallCompleteToolMetaUI: - "Schema for the `McpAppToolCallCompleteToolMetaUI` type." + "MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result." resource_uri: str | None = None visibility: list[str] | None = None @@ -2849,6 +3532,60 @@ def to_dict(self) -> dict: return result +@dataclass +class McpHeadersRefreshCompletedData: + "MCP headers refresh request completion notification" + outcome: McpHeadersRefreshCompletedOutcome + request_id: str + + @staticmethod + def from_dict(obj: Any) -> "McpHeadersRefreshCompletedData": + assert isinstance(obj, dict) + outcome = parse_enum(McpHeadersRefreshCompletedOutcome, obj.get("outcome")) + request_id = from_str(obj.get("requestId")) + return McpHeadersRefreshCompletedData( + outcome=outcome, + request_id=request_id, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["outcome"] = to_enum(McpHeadersRefreshCompletedOutcome, self.outcome) + result["requestId"] = from_str(self.request_id) + return result + + +@dataclass +class McpHeadersRefreshRequiredData: + "Dynamic headers refresh request for a remote MCP server" + reason: McpHeadersRefreshRequiredReason + request_id: str + server_name: str + server_url: str + + @staticmethod + def from_dict(obj: Any) -> "McpHeadersRefreshRequiredData": + assert isinstance(obj, dict) + reason = parse_enum(McpHeadersRefreshRequiredReason, obj.get("reason")) + request_id = from_str(obj.get("requestId")) + server_name = from_str(obj.get("serverName")) + server_url = from_str(obj.get("serverUrl")) + return McpHeadersRefreshRequiredData( + reason=reason, + request_id=request_id, + server_name=server_name, + server_url=server_url, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["reason"] = to_enum(McpHeadersRefreshRequiredReason, self.reason) + result["requestId"] = from_str(self.request_id) + result["serverName"] = from_str(self.server_name) + result["serverUrl"] = from_str(self.server_url) + return result + + @dataclass class McpOauthCompletedData: "MCP OAuth request completion notification" @@ -2872,12 +3609,42 @@ def to_dict(self) -> dict: return result +@dataclass +class McpOauthHttpResponse: + "Raw HTTP response details from the OAuth auth challenge, as observed by the runtime." + headers: list[HeaderEntry] + status_code: int + body: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "McpOauthHttpResponse": + assert isinstance(obj, dict) + headers = from_list(HeaderEntry.from_dict, obj.get("headers")) + status_code = from_int(obj.get("statusCode")) + body = from_union([from_none, from_str], obj.get("body")) + return McpOauthHttpResponse( + headers=headers, + status_code=status_code, + body=body, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["headers"] = from_list(lambda x: to_class(HeaderEntry, x), self.headers) + result["statusCode"] = to_int(self.status_code) + if self.body is not None: + result["body"] = from_union([from_none, from_str], self.body) + return result + + @dataclass class McpOauthRequiredData: "OAuth authentication request for an MCP server" + reason: McpOauthRequestReason request_id: str server_name: str server_url: str + http_response: McpOauthHttpResponse | None = None resource_metadata: str | None = None static_client_config: McpOauthRequiredStaticClientConfig | None = None www_authenticate_params: McpOauthWWWAuthenticateParams | None = None @@ -2885,16 +3652,20 @@ class McpOauthRequiredData: @staticmethod def from_dict(obj: Any) -> "McpOauthRequiredData": assert isinstance(obj, dict) + reason = parse_enum(McpOauthRequestReason, obj.get("reason")) request_id = from_str(obj.get("requestId")) server_name = from_str(obj.get("serverName")) server_url = from_str(obj.get("serverUrl")) + http_response = from_union([from_none, McpOauthHttpResponse.from_dict], obj.get("httpResponse")) resource_metadata = from_union([from_none, from_str], obj.get("resourceMetadata")) static_client_config = from_union([from_none, McpOauthRequiredStaticClientConfig.from_dict], obj.get("staticClientConfig")) www_authenticate_params = from_union([from_none, McpOauthWWWAuthenticateParams.from_dict], obj.get("wwwAuthenticateParams")) return McpOauthRequiredData( + reason=reason, request_id=request_id, server_name=server_name, server_url=server_url, + http_response=http_response, resource_metadata=resource_metadata, static_client_config=static_client_config, www_authenticate_params=www_authenticate_params, @@ -2902,9 +3673,12 @@ def from_dict(obj: Any) -> "McpOauthRequiredData": def to_dict(self) -> dict: result: dict = {} + result["reason"] = to_enum(McpOauthRequestReason, self.reason) result["requestId"] = from_str(self.request_id) result["serverName"] = from_str(self.server_name) result["serverUrl"] = from_str(self.server_url) + if self.http_response is not None: + result["httpResponse"] = from_union([from_none, lambda x: to_class(McpOauthHttpResponse, x)], self.http_response) if self.resource_metadata is not None: result["resourceMetadata"] = from_union([from_none, from_str], self.resource_metadata) if self.static_client_config is not None: @@ -2918,6 +3692,7 @@ def to_dict(self) -> dict: class McpOauthRequiredStaticClientConfig: "Static OAuth client configuration, if the server specifies one" client_id: str + client_secret: str | None = None grant_type: str | None = None public_client: bool | None = None @@ -2925,56 +3700,99 @@ class McpOauthRequiredStaticClientConfig: def from_dict(obj: Any) -> "McpOauthRequiredStaticClientConfig": assert isinstance(obj, dict) client_id = from_str(obj.get("clientId")) + client_secret = from_union([from_none, from_str], obj.get("clientSecret")) grant_type = from_union([from_none, from_str], obj.get("grantType")) public_client = from_union([from_none, from_bool], obj.get("publicClient")) return McpOauthRequiredStaticClientConfig( client_id=client_id, + client_secret=client_secret, grant_type=grant_type, public_client=public_client, ) def to_dict(self) -> dict: result: dict = {} - result["clientId"] = from_str(self.client_id) - if self.grant_type is not None: - result["grantType"] = from_union([from_none, from_str], self.grant_type) - if self.public_client is not None: - result["publicClient"] = from_union([from_none, from_bool], self.public_client) + result["clientId"] = from_str(self.client_id) + if self.client_secret is not None: + result["clientSecret"] = from_union([from_none, from_str], self.client_secret) + if self.grant_type is not None: + result["grantType"] = from_union([from_none, from_str], self.grant_type) + if self.public_client is not None: + result["publicClient"] = from_union([from_none, from_bool], self.public_client) + return result + + +@dataclass +class McpOauthWWWAuthenticateParams: + "OAuth WWW-Authenticate parameters parsed from an MCP auth challenge" + error: str | None = None + resource_metadata_url: str | None = None + scope: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "McpOauthWWWAuthenticateParams": + assert isinstance(obj, dict) + error = from_union([from_none, from_str], obj.get("error")) + resource_metadata_url = from_union([from_none, from_str], obj.get("resourceMetadataUrl")) + scope = from_union([from_none, from_str], obj.get("scope")) + return McpOauthWWWAuthenticateParams( + error=error, + resource_metadata_url=resource_metadata_url, + scope=scope, + ) + + def to_dict(self) -> dict: + result: dict = {} + if self.error is not None: + result["error"] = from_union([from_none, from_str], self.error) + if self.resource_metadata_url is not None: + result["resourceMetadataUrl"] = from_union([from_none, from_str], self.resource_metadata_url) + if self.scope is not None: + result["scope"] = from_union([from_none, from_str], self.scope) + return result + + +@dataclass +class McpPromptsListChangedData: + "Payload identifying the MCP server associated with a list change." + server_name: str + + @staticmethod + def from_dict(obj: Any) -> "McpPromptsListChangedData": + assert isinstance(obj, dict) + server_name = from_str(obj.get("serverName")) + return McpPromptsListChangedData( + server_name=server_name, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["serverName"] = from_str(self.server_name) return result @dataclass -class McpOauthWWWAuthenticateParams: - "OAuth WWW-Authenticate parameters parsed from an MCP auth challenge" - resource_metadata_url: str - error: str | None = None - scope: str | None = None +class McpResourcesListChangedData: + "Payload identifying the MCP server associated with a list change." + server_name: str @staticmethod - def from_dict(obj: Any) -> "McpOauthWWWAuthenticateParams": + def from_dict(obj: Any) -> "McpResourcesListChangedData": assert isinstance(obj, dict) - resource_metadata_url = from_str(obj.get("resourceMetadataUrl")) - error = from_union([from_none, from_str], obj.get("error")) - scope = from_union([from_none, from_str], obj.get("scope")) - return McpOauthWWWAuthenticateParams( - resource_metadata_url=resource_metadata_url, - error=error, - scope=scope, + server_name = from_str(obj.get("serverName")) + return McpResourcesListChangedData( + server_name=server_name, ) def to_dict(self) -> dict: result: dict = {} - result["resourceMetadataUrl"] = from_str(self.resource_metadata_url) - if self.error is not None: - result["error"] = from_union([from_none, from_str], self.error) - if self.scope is not None: - result["scope"] = from_union([from_none, from_str], self.scope) + result["serverName"] = from_str(self.server_name) return result @dataclass class McpServersLoadedServer: - "Schema for the `McpServersLoadedServer` type." + "A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata." name: str status: McpServerStatus error: str | None = None @@ -3020,6 +3838,25 @@ def to_dict(self) -> dict: return result +@dataclass +class McpToolsListChangedData: + "Payload identifying the MCP server associated with a list change." + server_name: str + + @staticmethod + def from_dict(obj: Any) -> "McpToolsListChangedData": + assert isinstance(obj, dict) + server_name = from_str(obj.get("serverName")) + return McpToolsListChangedData( + server_name=server_name, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["serverName"] = from_str(self.server_name) + return result + + @dataclass class ModelCallFailureData: "Failed LLM API call metadata for telemetry" @@ -3163,7 +4000,7 @@ def to_dict(self) -> dict: @dataclass class PermissionApproved: - "Schema for the `PermissionApproved` type." + "Permission response variant indicating the request was approved without persisting an approval rule." kind: ClassVar[str] = "approved" @staticmethod @@ -3180,7 +4017,7 @@ def to_dict(self) -> dict: @dataclass class PermissionApprovedForLocation: - "Schema for the `PermissionApprovedForLocation` type." + "Permission response variant that approves a request and persists the provided approval to a project location key." approval: UserToolSessionApproval kind: ClassVar[str] = "approved-for-location" location_key: str @@ -3205,7 +4042,7 @@ def to_dict(self) -> dict: @dataclass class PermissionApprovedForSession: - "Schema for the `PermissionApprovedForSession` type." + "Permission response variant that approves a request and remembers the provided approval for the rest of the session." approval: UserToolSessionApproval kind: ClassVar[str] = "approved-for-session" @@ -3226,7 +4063,7 @@ def to_dict(self) -> dict: @dataclass class PermissionCancelled: - "Schema for the `PermissionCancelled` type." + "Permission response variant indicating the request was cancelled before use, with an optional reason." kind: ClassVar[str] = "cancelled" reason: str | None = None @@ -3276,7 +4113,7 @@ def to_dict(self) -> dict: @dataclass class PermissionDeniedByContentExclusionPolicy: - "Schema for the `PermissionDeniedByContentExclusionPolicy` type." + "Permission response variant denying a path under content exclusion policy, with the path and message." kind: ClassVar[str] = "denied-by-content-exclusion-policy" message: str path: str @@ -3301,7 +4138,7 @@ def to_dict(self) -> dict: @dataclass class PermissionDeniedByPermissionRequestHook: - "Schema for the `PermissionDeniedByPermissionRequestHook` type." + "Permission response variant denied by a permission-request hook, with optional message and interrupt flag." kind: ClassVar[str] = "denied-by-permission-request-hook" interrupt: bool | None = None message: str | None = None @@ -3328,7 +4165,7 @@ def to_dict(self) -> dict: @dataclass class PermissionDeniedByRules: - "Schema for the `PermissionDeniedByRules` type." + "Permission response variant denied because matching approval rules explicitly blocked the request." kind: ClassVar[str] = "denied-by-rules" rules: list[PermissionRule] @@ -3349,7 +4186,7 @@ def to_dict(self) -> dict: @dataclass class PermissionDeniedInteractivelyByUser: - "Schema for the `PermissionDeniedInteractivelyByUser` type." + "Permission response variant denied in an interactive user prompt, with optional feedback and force-reject flag." kind: ClassVar[str] = "denied-interactively-by-user" feedback: str | None = None force_reject: bool | None = None @@ -3376,7 +4213,7 @@ def to_dict(self) -> dict: @dataclass class PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser: - "Schema for the `PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type." + "Permission response variant denied because no approval rule matched and user confirmation was unavailable." kind: ClassVar[str] = "denied-no-approval-rule-and-could-not-request-from-user" @staticmethod @@ -3399,6 +4236,8 @@ class PermissionPromptRequestCommands: full_command_text: str intention: str kind: ClassVar[str] = "commands" + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None tool_call_id: str | None = None warning: str | None = None @@ -3409,6 +4248,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestCommands": command_identifiers = from_list(from_str, obj.get("commandIdentifiers")) full_command_text = from_str(obj.get("fullCommandText")) intention = from_str(obj.get("intention")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) warning = from_union([from_none, from_str], obj.get("warning")) return PermissionPromptRequestCommands( @@ -3416,6 +4256,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestCommands": command_identifiers=command_identifiers, full_command_text=full_command_text, intention=intention, + auto_approval=auto_approval, tool_call_id=tool_call_id, warning=warning, ) @@ -3427,6 +4268,8 @@ def to_dict(self) -> dict: result["fullCommandText"] = from_str(self.full_command_text) result["intention"] = from_str(self.intention) result["kind"] = self.kind + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) if self.warning is not None: @@ -3441,6 +4284,8 @@ class PermissionPromptRequestCustomTool: tool_description: str tool_name: str args: Any = None + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None tool_call_id: str | None = None @staticmethod @@ -3449,11 +4294,13 @@ def from_dict(obj: Any) -> "PermissionPromptRequestCustomTool": tool_description = from_str(obj.get("toolDescription")) tool_name = from_str(obj.get("toolName")) args = obj.get("args") + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestCustomTool( tool_description=tool_description, tool_name=tool_name, args=args, + auto_approval=auto_approval, tool_call_id=tool_call_id, ) @@ -3464,6 +4311,8 @@ def to_dict(self) -> dict: result["toolName"] = from_str(self.tool_name) if self.args is not None: result["args"] = self.args + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -3474,6 +4323,8 @@ class PermissionPromptRequestExtensionManagement: "Extension management permission prompt" kind: ClassVar[str] = "extension-management" operation: str + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None extension_name: str | None = None tool_call_id: str | None = None @@ -3481,10 +4332,12 @@ class PermissionPromptRequestExtensionManagement: def from_dict(obj: Any) -> "PermissionPromptRequestExtensionManagement": assert isinstance(obj, dict) operation = from_str(obj.get("operation")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) extension_name = from_union([from_none, from_str], obj.get("extensionName")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestExtensionManagement( operation=operation, + auto_approval=auto_approval, extension_name=extension_name, tool_call_id=tool_call_id, ) @@ -3493,6 +4346,8 @@ def to_dict(self) -> dict: result: dict = {} result["kind"] = self.kind result["operation"] = from_str(self.operation) + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.extension_name is not None: result["extensionName"] = from_union([from_none, from_str], self.extension_name) if self.tool_call_id is not None: @@ -3506,6 +4361,8 @@ class PermissionPromptRequestExtensionPermissionAccess: capabilities: list[str] extension_name: str kind: ClassVar[str] = "extension-permission-access" + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None tool_call_id: str | None = None @staticmethod @@ -3513,10 +4370,12 @@ def from_dict(obj: Any) -> "PermissionPromptRequestExtensionPermissionAccess": assert isinstance(obj, dict) capabilities = from_list(from_str, obj.get("capabilities")) extension_name = from_str(obj.get("extensionName")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestExtensionPermissionAccess( capabilities=capabilities, extension_name=extension_name, + auto_approval=auto_approval, tool_call_id=tool_call_id, ) @@ -3525,6 +4384,8 @@ def to_dict(self) -> dict: result["capabilities"] = from_list(from_str, self.capabilities) result["extensionName"] = from_str(self.extension_name) result["kind"] = self.kind + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -3535,6 +4396,8 @@ class PermissionPromptRequestHook: "Hook confirmation permission prompt" kind: ClassVar[str] = "hook" tool_name: str + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None hook_message: str | None = None tool_args: Any = None tool_call_id: str | None = None @@ -3543,11 +4406,13 @@ class PermissionPromptRequestHook: def from_dict(obj: Any) -> "PermissionPromptRequestHook": assert isinstance(obj, dict) tool_name = from_str(obj.get("toolName")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) hook_message = from_union([from_none, from_str], obj.get("hookMessage")) tool_args = obj.get("toolArgs") tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestHook( tool_name=tool_name, + auto_approval=auto_approval, hook_message=hook_message, tool_args=tool_args, tool_call_id=tool_call_id, @@ -3557,6 +4422,8 @@ def to_dict(self) -> dict: result: dict = {} result["kind"] = self.kind result["toolName"] = from_str(self.tool_name) + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.hook_message is not None: result["hookMessage"] = from_union([from_none, from_str], self.hook_message) if self.tool_args is not None: @@ -3574,6 +4441,8 @@ class PermissionPromptRequestMcp: tool_name: str tool_title: str args: Any = None + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None tool_call_id: str | None = None @staticmethod @@ -3583,12 +4452,14 @@ def from_dict(obj: Any) -> "PermissionPromptRequestMcp": tool_name = from_str(obj.get("toolName")) tool_title = from_str(obj.get("toolTitle")) args = obj.get("args") + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestMcp( server_name=server_name, tool_name=tool_name, tool_title=tool_title, args=args, + auto_approval=auto_approval, tool_call_id=tool_call_id, ) @@ -3600,6 +4471,8 @@ def to_dict(self) -> dict: result["toolTitle"] = from_str(self.tool_title) if self.args is not None: result["args"] = self.args + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -3611,6 +4484,8 @@ class PermissionPromptRequestMemory: fact: str kind: ClassVar[str] = "memory" action: PermissionRequestMemoryAction | None = None + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None citations: str | None = None direction: PermissionRequestMemoryDirection | None = None reason: str | None = None @@ -3622,6 +4497,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestMemory": assert isinstance(obj, dict) fact = from_str(obj.get("fact")) action = from_union([from_none, lambda x: parse_enum(PermissionRequestMemoryAction, x)], obj.get("action")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) citations = from_union([from_none, from_str], obj.get("citations")) direction = from_union([from_none, lambda x: parse_enum(PermissionRequestMemoryDirection, x)], obj.get("direction")) reason = from_union([from_none, from_str], obj.get("reason")) @@ -3630,6 +4506,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestMemory": return PermissionPromptRequestMemory( fact=fact, action=action, + auto_approval=auto_approval, citations=citations, direction=direction, reason=reason, @@ -3643,6 +4520,8 @@ def to_dict(self) -> dict: result["kind"] = self.kind if self.action is not None: result["action"] = from_union([from_none, lambda x: to_enum(PermissionRequestMemoryAction, x)], self.action) + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.citations is not None: result["citations"] = from_union([from_none, from_str], self.citations) if self.direction is not None: @@ -3662,6 +4541,8 @@ class PermissionPromptRequestPath: access_kind: PermissionPromptRequestPathAccessKind kind: ClassVar[str] = "path" paths: list[str] + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None tool_call_id: str | None = None @staticmethod @@ -3669,10 +4550,12 @@ def from_dict(obj: Any) -> "PermissionPromptRequestPath": assert isinstance(obj, dict) access_kind = parse_enum(PermissionPromptRequestPathAccessKind, obj.get("accessKind")) paths = from_list(from_str, obj.get("paths")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestPath( access_kind=access_kind, paths=paths, + auto_approval=auto_approval, tool_call_id=tool_call_id, ) @@ -3681,6 +4564,8 @@ def to_dict(self) -> dict: result["accessKind"] = to_enum(PermissionPromptRequestPathAccessKind, self.access_kind) result["kind"] = self.kind result["paths"] = from_list(from_str, self.paths) + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -3692,6 +4577,8 @@ class PermissionPromptRequestRead: intention: str kind: ClassVar[str] = "read" path: str + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None tool_call_id: str | None = None @staticmethod @@ -3699,10 +4586,12 @@ def from_dict(obj: Any) -> "PermissionPromptRequestRead": assert isinstance(obj, dict) intention = from_str(obj.get("intention")) path = from_str(obj.get("path")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestRead( intention=intention, path=path, + auto_approval=auto_approval, tool_call_id=tool_call_id, ) @@ -3711,6 +4600,8 @@ def to_dict(self) -> dict: result["intention"] = from_str(self.intention) result["kind"] = self.kind result["path"] = from_str(self.path) + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -3722,6 +4613,10 @@ class PermissionPromptRequestUrl: intention: str kind: ClassVar[str] = "url" url: str + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None + request_sandbox_bypass: bool | None = None + request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @staticmethod @@ -3729,10 +4624,16 @@ def from_dict(obj: Any) -> "PermissionPromptRequestUrl": assert isinstance(obj, dict) intention = from_str(obj.get("intention")) url = from_str(obj.get("url")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) + request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) + request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestUrl( intention=intention, url=url, + auto_approval=auto_approval, + request_sandbox_bypass=request_sandbox_bypass, + request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, ) @@ -3741,6 +4642,12 @@ def to_dict(self) -> dict: result["intention"] = from_str(self.intention) result["kind"] = self.kind result["url"] = from_str(self.url) + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) + if self.request_sandbox_bypass is not None: + result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) + if self.request_sandbox_bypass_reason is not None: + result["requestSandboxBypassReason"] = from_union([from_none, from_str], self.request_sandbox_bypass_reason) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -3754,6 +4661,8 @@ class PermissionPromptRequestWrite: file_name: str intention: str kind: ClassVar[str] = "write" + # Experimental: this field is part of an experimental API and may change or be removed. + auto_approval: PermissionAutoApproval | None = None new_file_contents: str | None = None tool_call_id: str | None = None @@ -3764,6 +4673,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestWrite": diff = from_str(obj.get("diff")) file_name = from_str(obj.get("fileName")) intention = from_str(obj.get("intention")) + auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) new_file_contents = from_union([from_none, from_str], obj.get("newFileContents")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestWrite( @@ -3771,6 +4681,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestWrite": diff=diff, file_name=file_name, intention=intention, + auto_approval=auto_approval, new_file_contents=new_file_contents, tool_call_id=tool_call_id, ) @@ -3782,6 +4693,8 @@ def to_dict(self) -> dict: result["fileName"] = from_str(self.file_name) result["intention"] = from_str(self.intention) result["kind"] = self.kind + if self.auto_approval is not None: + result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) if self.new_file_contents is not None: result["newFileContents"] = from_union([from_none, from_str], self.new_file_contents) if self.tool_call_id is not None: @@ -4021,6 +4934,8 @@ class PermissionRequestRead: intention: str kind: ClassVar[str] = "read" path: str + request_sandbox_bypass: bool | None = None + request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @staticmethod @@ -4028,10 +4943,14 @@ def from_dict(obj: Any) -> "PermissionRequestRead": assert isinstance(obj, dict) intention = from_str(obj.get("intention")) path = from_str(obj.get("path")) + request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) + request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionRequestRead( intention=intention, path=path, + request_sandbox_bypass=request_sandbox_bypass, + request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, ) @@ -4040,6 +4959,10 @@ def to_dict(self) -> dict: result["intention"] = from_str(self.intention) result["kind"] = self.kind result["path"] = from_str(self.path) + if self.request_sandbox_bypass is not None: + result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) + if self.request_sandbox_bypass_reason is not None: + result["requestSandboxBypassReason"] = from_union([from_none, from_str], self.request_sandbox_bypass_reason) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -4112,7 +5035,7 @@ def to_dict(self) -> dict: @dataclass class PermissionRequestShellCommand: - "Schema for the `PermissionRequestShellCommand` type." + "A parsed command identifier in a shell permission request, including whether it is read-only." identifier: str read_only: bool @@ -4135,7 +5058,7 @@ def to_dict(self) -> dict: @dataclass class PermissionRequestShellPossibleUrl: - "Schema for the `PermissionRequestShellPossibleUrl` type." + "A URL that may be accessed by a command in a shell permission request." url: str @staticmethod @@ -4158,6 +5081,8 @@ class PermissionRequestUrl: intention: str kind: ClassVar[str] = "url" url: str + request_sandbox_bypass: bool | None = None + request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @staticmethod @@ -4165,10 +5090,14 @@ def from_dict(obj: Any) -> "PermissionRequestUrl": assert isinstance(obj, dict) intention = from_str(obj.get("intention")) url = from_str(obj.get("url")) + request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) + request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionRequestUrl( intention=intention, url=url, + request_sandbox_bypass=request_sandbox_bypass, + request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, ) @@ -4177,6 +5106,10 @@ def to_dict(self) -> dict: result["intention"] = from_str(self.intention) result["kind"] = self.kind result["url"] = from_str(self.url) + if self.request_sandbox_bypass is not None: + result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) + if self.request_sandbox_bypass_reason is not None: + result["requestSandboxBypassReason"] = from_union([from_none, from_str], self.request_sandbox_bypass_reason) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -4191,6 +5124,8 @@ class PermissionRequestWrite: intention: str kind: ClassVar[str] = "write" new_file_contents: str | None = None + request_sandbox_bypass: bool | None = None + request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @staticmethod @@ -4201,6 +5136,8 @@ def from_dict(obj: Any) -> "PermissionRequestWrite": file_name = from_str(obj.get("fileName")) intention = from_str(obj.get("intention")) new_file_contents = from_union([from_none, from_str], obj.get("newFileContents")) + request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) + request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionRequestWrite( can_offer_session_approval=can_offer_session_approval, @@ -4208,6 +5145,8 @@ def from_dict(obj: Any) -> "PermissionRequestWrite": file_name=file_name, intention=intention, new_file_contents=new_file_contents, + request_sandbox_bypass=request_sandbox_bypass, + request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, ) @@ -4220,6 +5159,10 @@ def to_dict(self) -> dict: result["kind"] = self.kind if self.new_file_contents is not None: result["newFileContents"] = from_union([from_none, from_str], self.new_file_contents) + if self.request_sandbox_bypass is not None: + result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) + if self.request_sandbox_bypass_reason is not None: + result["requestSandboxBypassReason"] = from_union([from_none, from_str], self.request_sandbox_bypass_reason) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -4260,7 +5203,7 @@ def to_dict(self) -> dict: @dataclass class PermissionRule: - "Schema for the `PermissionRule` type." + "A permission approval or denial rule matched against a tool request, identified by a rule kind with an optional argument value." argument: str | None kind: str @@ -4395,7 +5338,7 @@ def to_dict(self) -> dict: @dataclass class SessionBackgroundTasksChangedData: - "Schema for the `BackgroundTasksChangedData` type." + "Empty payload for `session.background_tasks_changed`, indicating background task state changed." @staticmethod def from_dict(obj: Any) -> "SessionBackgroundTasksChangedData": assert isinstance(obj, dict) @@ -4558,6 +5501,7 @@ def to_dict(self) -> dict: class SessionCompactionStartData: "Context window breakdown at the start of LLM-powered conversation compaction" conversation_tokens: int | None = None + model: str | None = None system_tokens: int | None = None tool_definitions_tokens: int | None = None @@ -4565,10 +5509,12 @@ class SessionCompactionStartData: def from_dict(obj: Any) -> "SessionCompactionStartData": assert isinstance(obj, dict) conversation_tokens = from_union([from_none, from_int], obj.get("conversationTokens")) + model = from_union([from_none, from_str], obj.get("model")) system_tokens = from_union([from_none, from_int], obj.get("systemTokens")) tool_definitions_tokens = from_union([from_none, from_int], obj.get("toolDefinitionsTokens")) return SessionCompactionStartData( conversation_tokens=conversation_tokens, + model=model, system_tokens=system_tokens, tool_definitions_tokens=tool_definitions_tokens, ) @@ -4577,6 +5523,8 @@ def to_dict(self) -> dict: result: dict = {} if self.conversation_tokens is not None: result["conversationTokens"] = from_union([from_none, to_int], self.conversation_tokens) + if self.model is not None: + result["model"] = from_union([from_none, from_str], self.model) if self.system_tokens is not None: result["systemTokens"] = from_union([from_none, to_int], self.system_tokens) if self.tool_definitions_tokens is not None: @@ -4640,7 +5588,7 @@ def to_dict(self) -> dict: @dataclass class SessionCustomAgentsUpdatedData: - "Schema for the `CustomAgentsUpdatedData` type." + "Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors." agents: list[CustomAgentsUpdatedAgent] errors: list[str] warnings: list[str] @@ -4762,7 +5710,7 @@ def to_dict(self) -> dict: @dataclass class SessionExtensionsAttachmentsPushedData: - "Schema for the `ExtensionsAttachmentsPushedData` type." + "Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send." attachments: list[Attachment] @staticmethod @@ -4781,7 +5729,7 @@ def to_dict(self) -> dict: @dataclass class SessionExtensionsLoadedData: - "Schema for the `ExtensionsLoadedData` type." + "Payload of `session.extensions_loaded` listing discovered extensions and their statuses." extensions: list[ExtensionsLoadedExtension] @staticmethod @@ -4899,9 +5847,108 @@ def to_dict(self) -> dict: return result +@dataclass +class SessionLimitsConfig: + "Optional session limits." + max_ai_credits: float | None = None + + @staticmethod + def from_dict(obj: Any) -> "SessionLimitsConfig": + assert isinstance(obj, dict) + max_ai_credits = from_union([from_none, from_float], obj.get("maxAiCredits")) + return SessionLimitsConfig( + max_ai_credits=max_ai_credits, + ) + + def to_dict(self) -> dict: + result: dict = {} + if self.max_ai_credits is not None: + result["maxAiCredits"] = from_union([from_none, to_float], self.max_ai_credits) + return result + + +@dataclass +class SessionLimitsExhaustedCompletedData: + "Session limit exhaustion prompt completion notification." + request_id: str + response: SessionLimitsExhaustedResponse + + @staticmethod + def from_dict(obj: Any) -> "SessionLimitsExhaustedCompletedData": + assert isinstance(obj, dict) + request_id = from_str(obj.get("requestId")) + response = SessionLimitsExhaustedResponse.from_dict(obj.get("response")) + return SessionLimitsExhaustedCompletedData( + request_id=request_id, + response=response, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["requestId"] = from_str(self.request_id) + result["response"] = to_class(SessionLimitsExhaustedResponse, self.response) + return result + + +@dataclass +class SessionLimitsExhaustedRequestedData: + "Session limit exhaustion notification requiring user action." + max_ai_credits: float + request_id: str + used_ai_credits: float + + @staticmethod + def from_dict(obj: Any) -> "SessionLimitsExhaustedRequestedData": + assert isinstance(obj, dict) + max_ai_credits = from_float(obj.get("maxAiCredits")) + request_id = from_str(obj.get("requestId")) + used_ai_credits = from_float(obj.get("usedAiCredits")) + return SessionLimitsExhaustedRequestedData( + max_ai_credits=max_ai_credits, + request_id=request_id, + used_ai_credits=used_ai_credits, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["maxAiCredits"] = to_float(self.max_ai_credits) + result["requestId"] = from_str(self.request_id) + result["usedAiCredits"] = to_float(self.used_ai_credits) + return result + + +@dataclass +class SessionLimitsExhaustedResponse: + "The user's selected action for an exhausted session limit." + action: SessionLimitsExhaustedResponseAction + additional_ai_credits: float | None = None + max_ai_credits: float | None = None + + @staticmethod + def from_dict(obj: Any) -> "SessionLimitsExhaustedResponse": + assert isinstance(obj, dict) + action = parse_enum(SessionLimitsExhaustedResponseAction, obj.get("action")) + additional_ai_credits = from_union([from_none, from_float], obj.get("additionalAiCredits")) + max_ai_credits = from_union([from_none, from_float], obj.get("maxAiCredits")) + return SessionLimitsExhaustedResponse( + action=action, + additional_ai_credits=additional_ai_credits, + max_ai_credits=max_ai_credits, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["action"] = to_enum(SessionLimitsExhaustedResponseAction, self.action) + if self.additional_ai_credits is not None: + result["additionalAiCredits"] = from_union([from_none, to_float], self.additional_ai_credits) + if self.max_ai_credits is not None: + result["maxAiCredits"] = from_union([from_none, to_float], self.max_ai_credits) + return result + + @dataclass class SessionMcpServerStatusChangedData: - "Schema for the `McpServerStatusChangedData` type." + "Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error." server_name: str status: McpServerStatus error: str | None = None @@ -4929,7 +5976,7 @@ def to_dict(self) -> dict: @dataclass class SessionMcpServersLoadedData: - "Schema for the `McpServersLoadedData` type." + "Payload of `session.mcp_servers_loaded` listing MCP server status summaries." servers: list[McpServersLoadedServer] @staticmethod @@ -4978,8 +6025,10 @@ class SessionModelChangeData: previous_model: str | None = None previous_reasoning_effort: str | None = None previous_reasoning_summary: ReasoningSummary | None = None + previous_verbosity: Verbosity | None = None reasoning_effort: str | None = None reasoning_summary: ReasoningSummary | None = None + verbosity: Verbosity | None = None @staticmethod def from_dict(obj: Any) -> "SessionModelChangeData": @@ -4990,8 +6039,10 @@ def from_dict(obj: Any) -> "SessionModelChangeData": previous_model = from_union([from_none, from_str], obj.get("previousModel")) previous_reasoning_effort = from_union([from_none, from_str], obj.get("previousReasoningEffort")) previous_reasoning_summary = from_union([from_none, lambda x: parse_enum(ReasoningSummary, x)], obj.get("previousReasoningSummary")) + previous_verbosity = from_union([from_none, lambda x: parse_enum(Verbosity, x)], obj.get("previousVerbosity")) reasoning_effort = from_union([from_none, from_str], obj.get("reasoningEffort")) reasoning_summary = from_union([from_none, lambda x: parse_enum(ReasoningSummary, x)], obj.get("reasoningSummary")) + verbosity = from_union([from_none, lambda x: parse_enum(Verbosity, x)], obj.get("verbosity")) return SessionModelChangeData( new_model=new_model, cause=cause, @@ -4999,8 +6050,10 @@ def from_dict(obj: Any) -> "SessionModelChangeData": previous_model=previous_model, previous_reasoning_effort=previous_reasoning_effort, previous_reasoning_summary=previous_reasoning_summary, + previous_verbosity=previous_verbosity, reasoning_effort=reasoning_effort, reasoning_summary=reasoning_summary, + verbosity=verbosity, ) def to_dict(self) -> dict: @@ -5016,33 +6069,49 @@ def to_dict(self) -> dict: result["previousReasoningEffort"] = from_union([from_none, from_str], self.previous_reasoning_effort) if self.previous_reasoning_summary is not None: result["previousReasoningSummary"] = from_union([from_none, lambda x: to_enum(ReasoningSummary, x)], self.previous_reasoning_summary) + if self.previous_verbosity is not None: + result["previousVerbosity"] = from_union([from_none, lambda x: to_enum(Verbosity, x)], self.previous_verbosity) if self.reasoning_effort is not None: result["reasoningEffort"] = from_union([from_none, from_str], self.reasoning_effort) if self.reasoning_summary is not None: result["reasoningSummary"] = from_union([from_none, lambda x: to_enum(ReasoningSummary, x)], self.reasoning_summary) + if self.verbosity is not None: + result["verbosity"] = from_union([from_none, lambda x: to_enum(Verbosity, x)], self.verbosity) return result @dataclass class SessionPermissionsChangedData: - "Permissions change details carrying the aggregate allow-all boolean transition." + "Permissions change details carrying the aggregate allow-all transition." allow_all_permissions: bool previous_allow_all_permissions: bool + # Experimental: this field is part of an experimental API and may change or be removed. + allow_all_permission_mode: PermissionAllowAllMode | None = None + # Experimental: this field is part of an experimental API and may change or be removed. + previous_allow_all_permission_mode: PermissionAllowAllMode | None = None @staticmethod def from_dict(obj: Any) -> "SessionPermissionsChangedData": assert isinstance(obj, dict) allow_all_permissions = from_bool(obj.get("allowAllPermissions")) previous_allow_all_permissions = from_bool(obj.get("previousAllowAllPermissions")) + allow_all_permission_mode = from_union([from_none, lambda x: parse_enum(PermissionAllowAllMode, x)], obj.get("allowAllPermissionMode")) + previous_allow_all_permission_mode = from_union([from_none, lambda x: parse_enum(PermissionAllowAllMode, x)], obj.get("previousAllowAllPermissionMode")) return SessionPermissionsChangedData( allow_all_permissions=allow_all_permissions, previous_allow_all_permissions=previous_allow_all_permissions, + allow_all_permission_mode=allow_all_permission_mode, + previous_allow_all_permission_mode=previous_allow_all_permission_mode, ) def to_dict(self) -> dict: result: dict = {} result["allowAllPermissions"] = from_bool(self.allow_all_permissions) result["previousAllowAllPermissions"] = from_bool(self.previous_allow_all_permissions) + if self.allow_all_permission_mode is not None: + result["allowAllPermissionMode"] = from_union([from_none, lambda x: to_enum(PermissionAllowAllMode, x)], self.allow_all_permission_mode) + if self.previous_allow_all_permission_mode is not None: + result["previousAllowAllPermissionMode"] = from_union([from_none, lambda x: to_enum(PermissionAllowAllMode, x)], self.previous_allow_all_permission_mode) return result @@ -5098,7 +6167,9 @@ class SessionResumeData: reasoning_summary: ReasoningSummary | None = None remote_steerable: bool | None = None selected_model: str | None = None + session_limits: SessionLimitsConfig | None = None session_was_active: bool | None = None + verbosity: Verbosity | None = None @staticmethod def from_dict(obj: Any) -> "SessionResumeData": @@ -5114,7 +6185,9 @@ def from_dict(obj: Any) -> "SessionResumeData": reasoning_summary = from_union([from_none, lambda x: parse_enum(ReasoningSummary, x)], obj.get("reasoningSummary")) remote_steerable = from_union([from_none, from_bool], obj.get("remoteSteerable")) selected_model = from_union([from_none, from_str], obj.get("selectedModel")) + session_limits = from_union([from_none, SessionLimitsConfig.from_dict], obj.get("sessionLimits")) session_was_active = from_union([from_none, from_bool], obj.get("sessionWasActive")) + verbosity = from_union([from_none, lambda x: parse_enum(Verbosity, x)], obj.get("verbosity")) return SessionResumeData( event_count=event_count, resume_time=resume_time, @@ -5127,7 +6200,9 @@ def from_dict(obj: Any) -> "SessionResumeData": reasoning_summary=reasoning_summary, remote_steerable=remote_steerable, selected_model=selected_model, + session_limits=session_limits, session_was_active=session_was_active, + verbosity=verbosity, ) def to_dict(self) -> dict: @@ -5152,8 +6227,12 @@ def to_dict(self) -> dict: result["remoteSteerable"] = from_union([from_none, from_bool], self.remote_steerable) if self.selected_model is not None: result["selectedModel"] = from_union([from_none, from_str], self.selected_model) + if self.session_limits is not None: + result["sessionLimits"] = from_union([from_none, lambda x: to_class(SessionLimitsConfig, x)], self.session_limits) if self.session_was_active is not None: result["sessionWasActive"] = from_union([from_none, from_bool], self.session_was_active) + if self.verbosity is not None: + result["verbosity"] = from_union([from_none, lambda x: to_enum(Verbosity, x)], self.verbosity) return result @@ -5257,6 +6336,25 @@ def to_dict(self) -> dict: return result +@dataclass +class SessionSessionLimitsChangedData: + "Session limits update details. Null clears the limits." + session_limits: SessionLimitsConfig | None + + @staticmethod + def from_dict(obj: Any) -> "SessionSessionLimitsChangedData": + assert isinstance(obj, dict) + session_limits = from_union([from_none, SessionLimitsConfig.from_dict], obj.get("sessionLimits")) + return SessionSessionLimitsChangedData( + session_limits=session_limits, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["sessionLimits"] = from_union([from_none, lambda x: to_class(SessionLimitsConfig, x)], self.session_limits) + return result + + @dataclass class SessionShutdownData: "Session termination metrics including usage statistics, code changes, and shutdown reason" @@ -5346,7 +6444,7 @@ def to_dict(self) -> dict: @dataclass class SessionSkillsLoadedData: - "Schema for the `SkillsLoadedData` type." + "Payload of `session.skills_loaded` listing resolved skill metadata." skills: list[SkillsLoadedSkill] @staticmethod @@ -5402,6 +6500,8 @@ class SessionStartData: reasoning_summary: ReasoningSummary | None = None remote_steerable: bool | None = None selected_model: str | None = None + session_limits: SessionLimitsConfig | None = None + verbosity: Verbosity | None = None @staticmethod def from_dict(obj: Any) -> "SessionStartData": @@ -5419,6 +6519,8 @@ def from_dict(obj: Any) -> "SessionStartData": reasoning_summary = from_union([from_none, lambda x: parse_enum(ReasoningSummary, x)], obj.get("reasoningSummary")) remote_steerable = from_union([from_none, from_bool], obj.get("remoteSteerable")) selected_model = from_union([from_none, from_str], obj.get("selectedModel")) + session_limits = from_union([from_none, SessionLimitsConfig.from_dict], obj.get("sessionLimits")) + verbosity = from_union([from_none, lambda x: parse_enum(Verbosity, x)], obj.get("verbosity")) return SessionStartData( copilot_version=copilot_version, producer=producer, @@ -5433,6 +6535,8 @@ def from_dict(obj: Any) -> "SessionStartData": reasoning_summary=reasoning_summary, remote_steerable=remote_steerable, selected_model=selected_model, + session_limits=session_limits, + verbosity=verbosity, ) def to_dict(self) -> dict: @@ -5458,6 +6562,10 @@ def to_dict(self) -> dict: result["remoteSteerable"] = from_union([from_none, from_bool], self.remote_steerable) if self.selected_model is not None: result["selectedModel"] = from_union([from_none, from_str], self.selected_model) + if self.session_limits is not None: + result["sessionLimits"] = from_union([from_none, lambda x: to_class(SessionLimitsConfig, x)], self.session_limits) + if self.verbosity is not None: + result["verbosity"] = from_union([from_none, lambda x: to_enum(Verbosity, x)], self.verbosity) return result @@ -5519,7 +6627,7 @@ def to_dict(self) -> dict: @dataclass class SessionToolsUpdatedData: - "Schema for the `ToolsUpdatedData` type." + "Payload of `session.tools_updated` identifying the model whose resolved tools were updated." model: str @staticmethod @@ -5583,6 +6691,31 @@ def to_dict(self) -> dict: return result +@dataclass +class SessionUsageCheckpointData: + "Durable session usage checkpoint for reconstructing aggregate accounting on resume" + total_nano_aiu: float + # Internal: this field is an internal SDK API and is not part of the public surface. + _total_premium_requests: float | None = None + + @staticmethod + def from_dict(obj: Any) -> "SessionUsageCheckpointData": + assert isinstance(obj, dict) + total_nano_aiu = from_float(obj.get("totalNanoAiu")) + _total_premium_requests = from_union([from_none, from_float], obj.get("totalPremiumRequests")) + return SessionUsageCheckpointData( + total_nano_aiu=total_nano_aiu, + _total_premium_requests=_total_premium_requests, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["totalNanoAiu"] = to_float(self.total_nano_aiu) + if self._total_premium_requests is not None: + result["totalPremiumRequests"] = from_union([from_none, to_float], self._total_premium_requests) + return result + + @dataclass class SessionUsageInfoData: "Current context window usage statistics including token and message counts" @@ -5710,7 +6843,7 @@ def to_dict(self) -> dict: @dataclass class ShutdownModelMetric: - "Schema for the `ShutdownModelMetric` type." + "Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details." requests: ShutdownModelMetricRequests usage: ShutdownModelMetricUsage token_details: dict[str, ShutdownModelMetricTokenDetail] | None = None @@ -5771,7 +6904,7 @@ def to_dict(self) -> dict: @dataclass class ShutdownModelMetricTokenDetail: - "Schema for the `ShutdownModelMetricTokenDetail` type." + "A token-type entry in a shutdown model metric, storing the accumulated token count." token_count: int @staticmethod @@ -5826,7 +6959,7 @@ def to_dict(self) -> dict: @dataclass class ShutdownTokenDetail: - "Schema for the `ShutdownTokenDetail` type." + "A session-wide shutdown token-type entry storing the accumulated token count." token_count: int @staticmethod @@ -5851,6 +6984,7 @@ class SkillInvokedData: path: str allowed_tools: list[str] | None = None description: str | None = None + model: str | None = None plugin_name: str | None = None plugin_version: str | None = None source: str | None = None @@ -5864,6 +6998,7 @@ def from_dict(obj: Any) -> "SkillInvokedData": path = from_str(obj.get("path")) allowed_tools = from_union([from_none, lambda x: from_list(from_str, x)], obj.get("allowedTools")) description = from_union([from_none, from_str], obj.get("description")) + model = from_union([from_none, from_str], obj.get("model")) plugin_name = from_union([from_none, from_str], obj.get("pluginName")) plugin_version = from_union([from_none, from_str], obj.get("pluginVersion")) source = from_union([from_none, from_str], obj.get("source")) @@ -5874,6 +7009,7 @@ def from_dict(obj: Any) -> "SkillInvokedData": path=path, allowed_tools=allowed_tools, description=description, + model=model, plugin_name=plugin_name, plugin_version=plugin_version, source=source, @@ -5889,6 +7025,8 @@ def to_dict(self) -> dict: result["allowedTools"] = from_union([from_none, lambda x: from_list(from_str, x)], self.allowed_tools) if self.description is not None: result["description"] = from_union([from_none, from_str], self.description) + if self.model is not None: + result["model"] = from_union([from_none, from_str], self.model) if self.plugin_name is not None: result["pluginName"] = from_union([from_none, from_str], self.plugin_name) if self.plugin_version is not None: @@ -5902,7 +7040,7 @@ def to_dict(self) -> dict: @dataclass class SkillsLoadedSkill: - "Schema for the `SkillsLoadedSkill` type." + "A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint." description: str enabled: bool name: str @@ -6178,7 +7316,7 @@ def to_dict(self) -> dict: @dataclass class SystemNotificationAgentCompleted: - "Schema for the `SystemNotificationAgentCompleted` type." + "System notification metadata for a background agent that completed or failed, including agent ID, type, status, description, and prompt." agent_id: str agent_type: str status: SystemNotificationAgentCompletedStatus @@ -6217,7 +7355,7 @@ def to_dict(self) -> dict: @dataclass class SystemNotificationAgentIdle: - "Schema for the `SystemNotificationAgentIdle` type." + "System notification metadata for a background agent that became idle, including agent ID, type, and description." agent_id: str agent_type: str type: ClassVar[str] = "agent_idle" @@ -6270,7 +7408,7 @@ def to_dict(self) -> dict: @dataclass class SystemNotificationInstructionDiscovered: - "Schema for the `SystemNotificationInstructionDiscovered` type." + "System notification metadata for an instruction file discovered during tool access, including source, trigger file, and tool." source_path: str trigger_file: str trigger_tool: str @@ -6304,7 +7442,7 @@ def to_dict(self) -> dict: @dataclass class SystemNotificationNewInboxMessage: - "Schema for the `SystemNotificationNewInboxMessage` type." + "System notification metadata for a new inbox message, including entry ID, sender details, and summary." entry_id: str sender_name: str sender_type: str @@ -6337,7 +7475,7 @@ def to_dict(self) -> dict: @dataclass class SystemNotificationShellCompleted: - "Schema for the `SystemNotificationShellCompleted` type." + "System notification metadata for a shell session that completed, including shell ID, optional exit code, and description." shell_id: str type: ClassVar[str] = "shell_completed" description: str | None = None @@ -6368,7 +7506,7 @@ def to_dict(self) -> dict: @dataclass class SystemNotificationShellDetachedCompleted: - "Schema for the `SystemNotificationShellDetachedCompleted` type." + "System notification metadata for a detached shell session that completed, including shell ID and description." shell_id: str type: ClassVar[str] = "shell_detached_completed" description: str | None = None @@ -6548,33 +7686,42 @@ def to_dict(self) -> dict: @dataclass -class ToolExecutionCompleteContentTerminal: - "Terminal/shell output content block with optional exit code and working directory" - text: str - type: ClassVar[str] = "terminal" +class ToolExecutionCompleteContentShellExit: + "Shell command exit metadata with optional output preview" + exit_code: int + shell_id: str + type: ClassVar[str] = "shell_exit" cwd: str | None = None - exit_code: int | None = None + output_preview: str | None = None + output_truncated: bool | None = None @staticmethod - def from_dict(obj: Any) -> "ToolExecutionCompleteContentTerminal": + def from_dict(obj: Any) -> "ToolExecutionCompleteContentShellExit": assert isinstance(obj, dict) - text = from_str(obj.get("text")) + exit_code = from_int(obj.get("exitCode")) + shell_id = from_str(obj.get("shellId")) cwd = from_union([from_none, from_str], obj.get("cwd")) - exit_code = from_union([from_none, from_int], obj.get("exitCode")) - return ToolExecutionCompleteContentTerminal( - text=text, - cwd=cwd, + output_preview = from_union([from_none, from_str], obj.get("outputPreview")) + output_truncated = from_union([from_none, from_bool], obj.get("outputTruncated")) + return ToolExecutionCompleteContentShellExit( exit_code=exit_code, + shell_id=shell_id, + cwd=cwd, + output_preview=output_preview, + output_truncated=output_truncated, ) def to_dict(self) -> dict: result: dict = {} - result["text"] = from_str(self.text) + result["exitCode"] = to_int(self.exit_code) + result["shellId"] = from_str(self.shell_id) result["type"] = self.type if self.cwd is not None: result["cwd"] = from_union([from_none, from_str], self.cwd) - if self.exit_code is not None: - result["exitCode"] = from_union([from_none, to_int], self.exit_code) + if self.output_preview is not None: + result["outputPreview"] = from_union([from_none, from_str], self.output_preview) + if self.output_truncated is not None: + result["outputTruncated"] = from_union([from_none, from_bool], self.output_truncated) return result @@ -6607,6 +7754,8 @@ class ToolExecutionCompleteData: error: ToolExecutionCompleteError | None = None interaction_id: str | None = None is_user_requested: bool | None = None + # Experimental: this field is part of an experimental API and may change or be removed. + mcp_meta: Any = None model: str | None = None # Deprecated: this field is deprecated. parent_tool_call_id: str | None = None @@ -6624,6 +7773,7 @@ def from_dict(obj: Any) -> "ToolExecutionCompleteData": error = from_union([from_none, ToolExecutionCompleteError.from_dict], obj.get("error")) interaction_id = from_union([from_none, from_str], obj.get("interactionId")) is_user_requested = from_union([from_none, from_bool], obj.get("isUserRequested")) + mcp_meta = obj.get("mcpMeta") model = from_union([from_none, from_str], obj.get("model")) parent_tool_call_id = from_union([from_none, from_str], obj.get("parentToolCallId")) result = from_union([from_none, ToolExecutionCompleteResult.from_dict], obj.get("result")) @@ -6637,6 +7787,7 @@ def from_dict(obj: Any) -> "ToolExecutionCompleteData": error=error, interaction_id=interaction_id, is_user_requested=is_user_requested, + mcp_meta=mcp_meta, model=model, parent_tool_call_id=parent_tool_call_id, result=result, @@ -6656,6 +7807,8 @@ def to_dict(self) -> dict: result["interactionId"] = from_union([from_none, from_str], self.interaction_id) if self.is_user_requested is not None: result["isUserRequested"] = from_union([from_none, from_bool], self.is_user_requested) + if self.mcp_meta is not None: + result["mcpMeta"] = self.mcp_meta if self.model is not None: result["model"] = from_union([from_none, from_str], self.model) if self.parent_tool_call_id is not None: @@ -6707,6 +7860,8 @@ class ToolExecutionCompleteResult: citable_sources: list[CitableSource] | None = None contents: list[ToolExecutionCompleteContent] | None = None detailed_content: str | None = None + # Experimental: this field is part of an experimental API and may change or be removed. + mcp_meta: Any = None structured_content: Any = None ui_resource: ToolExecutionCompleteUIResource | None = None @@ -6718,6 +7873,7 @@ def from_dict(obj: Any) -> "ToolExecutionCompleteResult": citable_sources = from_union([from_none, lambda x: from_list(CitableSource.from_dict, x)], obj.get("citableSources")) contents = from_union([from_none, lambda x: from_list(_load_ToolExecutionCompleteContent, x)], obj.get("contents")) detailed_content = from_union([from_none, from_str], obj.get("detailedContent")) + mcp_meta = obj.get("mcpMeta") structured_content = obj.get("structuredContent") ui_resource = from_union([from_none, ToolExecutionCompleteUIResource.from_dict], obj.get("uiResource")) return ToolExecutionCompleteResult( @@ -6726,6 +7882,7 @@ def from_dict(obj: Any) -> "ToolExecutionCompleteResult": citable_sources=citable_sources, contents=contents, detailed_content=detailed_content, + mcp_meta=mcp_meta, structured_content=structured_content, ui_resource=ui_resource, ) @@ -6741,6 +7898,8 @@ def to_dict(self) -> dict: result["contents"] = from_union([from_none, lambda x: from_list(lambda x: x.to_dict(), x)], self.contents) if self.detailed_content is not None: result["detailedContent"] = from_union([from_none, from_str], self.detailed_content) + if self.mcp_meta is not None: + result["mcpMeta"] = self.mcp_meta if self.structured_content is not None: result["structuredContent"] = self.structured_content if self.ui_resource is not None: @@ -6799,7 +7958,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteToolDescriptionMetaUI: - "Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type." + "MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`." resource_uri: str | None = None visibility: list[ToolExecutionCompleteToolDescriptionMetaUIVisibility] | None = None @@ -6882,7 +8041,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteUIResourceMetaUI: - "Schema for the `ToolExecutionCompleteUIResourceMetaUI` type." + "MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference." csp: ToolExecutionCompleteUIResourceMetaUICsp | None = None domain: str | None = None permissions: ToolExecutionCompleteUIResourceMetaUIPermissions | None = None @@ -6917,7 +8076,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteUIResourceMetaUICsp: - "Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type." + "CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains." base_uri_domains: list[str] | None = None connect_domains: list[str] | None = None frame_domains: list[str] | None = None @@ -6952,7 +8111,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteUIResourceMetaUIPermissions: - "Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type." + "Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write." camera: ToolExecutionCompleteUIResourceMetaUIPermissionsCamera | None = None clipboard_write: ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite | None = None geolocation: ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation | None = None @@ -6987,7 +8146,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteUIResourceMetaUIPermissionsCamera: - "Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type." + "Marker object for camera permission on an MCP Apps UI resource." @staticmethod def from_dict(obj: Any) -> "ToolExecutionCompleteUIResourceMetaUIPermissionsCamera": assert isinstance(obj, dict) @@ -6999,7 +8158,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite: - "Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type." + "Marker object for clipboard-write permission on an MCP Apps UI resource." @staticmethod def from_dict(obj: Any) -> "ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite": assert isinstance(obj, dict) @@ -7011,7 +8170,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation: - "Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type." + "Marker object for geolocation permission on an MCP Apps UI resource." @staticmethod def from_dict(obj: Any) -> "ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation": assert isinstance(obj, dict) @@ -7023,7 +8182,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone: - "Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type." + "Marker object for microphone permission on an MCP Apps UI resource." @staticmethod def from_dict(obj: Any) -> "ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone": assert isinstance(obj, dict) @@ -7091,6 +8250,7 @@ class ToolExecutionStartData: model: str | None = None # Deprecated: this field is deprecated. parent_tool_call_id: str | None = None + shell_tool_info: ToolExecutionStartShellToolInfo | None = None tool_description: ToolExecutionStartToolDescription | None = None turn_id: str | None = None @@ -7105,6 +8265,7 @@ def from_dict(obj: Any) -> "ToolExecutionStartData": mcp_tool_name = from_union([from_none, from_str], obj.get("mcpToolName")) model = from_union([from_none, from_str], obj.get("model")) parent_tool_call_id = from_union([from_none, from_str], obj.get("parentToolCallId")) + shell_tool_info = from_union([from_none, ToolExecutionStartShellToolInfo.from_dict], obj.get("shellToolInfo")) tool_description = from_union([from_none, ToolExecutionStartToolDescription.from_dict], obj.get("toolDescription")) turn_id = from_union([from_none, from_str], obj.get("turnId")) return ToolExecutionStartData( @@ -7116,6 +8277,7 @@ def from_dict(obj: Any) -> "ToolExecutionStartData": mcp_tool_name=mcp_tool_name, model=model, parent_tool_call_id=parent_tool_call_id, + shell_tool_info=shell_tool_info, tool_description=tool_description, turn_id=turn_id, ) @@ -7136,6 +8298,8 @@ def to_dict(self) -> dict: result["model"] = from_union([from_none, from_str], self.model) if self.parent_tool_call_id is not None: result["parentToolCallId"] = from_union([from_none, from_str], self.parent_tool_call_id) + if self.shell_tool_info is not None: + result["shellToolInfo"] = from_union([from_none, lambda x: to_class(ToolExecutionStartShellToolInfo, x)], self.shell_tool_info) if self.tool_description is not None: result["toolDescription"] = from_union([from_none, lambda x: to_class(ToolExecutionStartToolDescription, x)], self.tool_description) if self.turn_id is not None: @@ -7143,6 +8307,29 @@ def to_dict(self) -> dict: return result +@dataclass +class ToolExecutionStartShellToolInfo: + "Shell-aware path hints for a shell tool's command, captured at start time so consumers can snapshot a file's pre-image before the tool runs." + has_write_file_redirection: bool + possible_paths: list[str] + + @staticmethod + def from_dict(obj: Any) -> "ToolExecutionStartShellToolInfo": + assert isinstance(obj, dict) + has_write_file_redirection = from_bool(obj.get("hasWriteFileRedirection")) + possible_paths = from_list(from_str, obj.get("possiblePaths")) + return ToolExecutionStartShellToolInfo( + has_write_file_redirection=has_write_file_redirection, + possible_paths=possible_paths, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["hasWriteFileRedirection"] = from_bool(self.has_write_file_redirection) + result["possiblePaths"] = from_list(from_str, self.possible_paths) + return result + + @dataclass class ToolExecutionStartToolDescription: "Tool definition metadata, present for MCP tools with MCP Apps support" @@ -7194,7 +8381,7 @@ def to_dict(self) -> dict: @dataclass class ToolExecutionStartToolDescriptionMetaUI: - "Schema for the `ToolExecutionStartToolDescriptionMetaUI` type." + "MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`." resource_uri: str | None = None visibility: list[ToolExecutionStartToolDescriptionMetaUIVisibility] | None = None @@ -7314,10 +8501,11 @@ def to_dict(self) -> dict: @dataclass class UserMessageData: - "Schema for the `UserMessageData` type." + "Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs." content: str agent_mode: UserMessageAgentMode | None = None attachments: list[Attachment] | None = None + delivery: UserMessageDelivery | None = None interaction_id: str | None = None is_autopilot_continuation: bool | None = None native_document_path_fallback_paths: list[str] | None = None @@ -7332,6 +8520,7 @@ def from_dict(obj: Any) -> "UserMessageData": content = from_str(obj.get("content")) agent_mode = from_union([from_none, lambda x: parse_enum(UserMessageAgentMode, x)], obj.get("agentMode")) attachments = from_union([from_none, lambda x: from_list(_load_Attachment, x)], obj.get("attachments")) + delivery = from_union([from_none, lambda x: parse_enum(UserMessageDelivery, x)], obj.get("delivery")) interaction_id = from_union([from_none, from_str], obj.get("interactionId")) is_autopilot_continuation = from_union([from_none, from_bool], obj.get("isAutopilotContinuation")) native_document_path_fallback_paths = from_union([from_none, lambda x: from_list(from_str, x)], obj.get("nativeDocumentPathFallbackPaths")) @@ -7343,6 +8532,7 @@ def from_dict(obj: Any) -> "UserMessageData": content=content, agent_mode=agent_mode, attachments=attachments, + delivery=delivery, interaction_id=interaction_id, is_autopilot_continuation=is_autopilot_continuation, native_document_path_fallback_paths=native_document_path_fallback_paths, @@ -7359,6 +8549,8 @@ def to_dict(self) -> dict: result["agentMode"] = from_union([from_none, lambda x: to_enum(UserMessageAgentMode, x)], self.agent_mode) if self.attachments is not None: result["attachments"] = from_union([from_none, lambda x: from_list(lambda x: x.to_dict(), x)], self.attachments) + if self.delivery is not None: + result["delivery"] = from_union([from_none, lambda x: to_enum(UserMessageDelivery, x)], self.delivery) if self.interaction_id is not None: result["interactionId"] = from_union([from_none, from_str], self.interaction_id) if self.is_autopilot_continuation is not None: @@ -7378,7 +8570,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalCommands: - "Schema for the `UserToolSessionApprovalCommands` type." + "Session-scoped tool-approval rule for specific shell command identifiers." command_identifiers: list[str] kind: ClassVar[str] = "commands" @@ -7399,7 +8591,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalCustomTool: - "Schema for the `UserToolSessionApprovalCustomTool` type." + "Session-scoped tool-approval rule for a custom tool, keyed by tool name." kind: ClassVar[str] = "custom-tool" tool_name: str @@ -7420,7 +8612,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalExtensionManagement: - "Schema for the `UserToolSessionApprovalExtensionManagement` type." + "Session-scoped tool-approval rule for extension-management operations, optionally narrowed by operation." kind: ClassVar[str] = "extension-management" operation: str | None = None @@ -7442,7 +8634,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalExtensionPermissionAccess: - "Schema for the `UserToolSessionApprovalExtensionPermissionAccess` type." + "Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name." extension_name: str kind: ClassVar[str] = "extension-permission-access" @@ -7463,7 +8655,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalMcp: - "Schema for the `UserToolSessionApprovalMcp` type." + "Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null." kind: ClassVar[str] = "mcp" server_name: str tool_name: str | None @@ -7488,7 +8680,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalMemory: - "Schema for the `UserToolSessionApprovalMemory` type." + "Session-scoped tool-approval rule for writes to long-term memory." kind: ClassVar[str] = "memory" @staticmethod @@ -7505,7 +8697,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalRead: - "Schema for the `UserToolSessionApprovalRead` type." + "Session-scoped tool-approval rule for read-only filesystem operations." kind: ClassVar[str] = "read" @staticmethod @@ -7522,7 +8714,7 @@ def to_dict(self) -> dict: @dataclass class UserToolSessionApprovalWrite: - "Schema for the `UserToolSessionApprovalWrite` type." + "Session-scoped tool-approval rule for filesystem write operations." kind: ClassVar[str] = "write" @staticmethod @@ -7599,6 +8791,15 @@ def _load_Attachment(obj: Any) -> "Attachment": case "directory": return AttachmentDirectory.from_dict(obj) case "selection": return AttachmentSelection.from_dict(obj) case "github_reference": return AttachmentGitHubReference.from_dict(obj) + case "github_commit": return AttachmentGitHubCommit.from_dict(obj) + case "github_release": return AttachmentGitHubRelease.from_dict(obj) + case "github_actions_job": return AttachmentGitHubActionsJob.from_dict(obj) + case "github_repository": return AttachmentGitHubRepository.from_dict(obj) + case "github_file_diff": return AttachmentGitHubFileDiff.from_dict(obj) + case "github_tree_comparison": return AttachmentGitHubTreeComparison.from_dict(obj) + case "github_url": return AttachmentGitHubUrl.from_dict(obj) + case "github_file": return AttachmentGitHubFile.from_dict(obj) + case "github_snippet": return AttachmentGitHubSnippet.from_dict(obj) case "blob": return AttachmentBlob.from_dict(obj) case "extension_context": return AttachmentExtensionContext.from_dict(obj) case _: raise ValueError(f"Unknown Attachment type: {kind!r}") @@ -7684,6 +8885,7 @@ def _load_ToolExecutionCompleteContent(obj: Any) -> "ToolExecutionCompleteConten match kind: case "text": return ToolExecutionCompleteContentText.from_dict(obj) case "terminal": return ToolExecutionCompleteContentTerminal.from_dict(obj) + case "shell_exit": return ToolExecutionCompleteContentShellExit.from_dict(obj) case "image": return ToolExecutionCompleteContentImage.from_dict(obj) case "audio": return ToolExecutionCompleteContentAudio.from_dict(obj) case "resource_link": return ToolExecutionCompleteContentResourceLink.from_dict(obj) @@ -7707,15 +8909,15 @@ def _load_UserToolSessionApproval(obj: Any) -> "UserToolSessionApproval": # A content block within a tool result, which may be text, terminal output, image, audio, or a resource -ToolExecutionCompleteContent = ToolExecutionCompleteContentText | ToolExecutionCompleteContentTerminal | ToolExecutionCompleteContentImage | ToolExecutionCompleteContentAudio | ToolExecutionCompleteContentResourceLink | ToolExecutionCompleteContentResource +ToolExecutionCompleteContent = ToolExecutionCompleteContentText | ToolExecutionCompleteContentTerminal | ToolExecutionCompleteContentShellExit | ToolExecutionCompleteContentImage | ToolExecutionCompleteContentAudio | ToolExecutionCompleteContentResourceLink | ToolExecutionCompleteContentResource # A model-facing binary result as persisted: full inline data, a size-omitted marker, or a deduplicated asset reference PersistedBinaryResult = PersistedBinaryImage | OmittedBinaryResult | BinaryAssetReference -# A user message attachment — a file, directory, code selection, blob, GitHub reference, or extension-supplied context payload -Attachment = AttachmentFile | AttachmentDirectory | AttachmentSelection | AttachmentGitHubReference | AttachmentBlob | AttachmentExtensionContext +# A user message attachment — a file, directory, code selection, blob, GitHub reference, GitHub-anchored pointer, or extension-supplied context payload +Attachment = AttachmentFile | AttachmentDirectory | AttachmentSelection | AttachmentGitHubReference | AttachmentGitHubCommit | AttachmentGitHubRelease | AttachmentGitHubActionsJob | AttachmentGitHubRepository | AttachmentGitHubFileDiff | AttachmentGitHubTreeComparison | AttachmentGitHubUrl | AttachmentGitHubFile | AttachmentGitHubSnippet | AttachmentBlob | AttachmentExtensionContext # Derived user-facing permission prompt details for UI consumers @@ -7746,6 +8948,19 @@ def _load_UserToolSessionApproval(obj: Any) -> "UserToolSessionApproval": PermissionResult = PermissionApproved | PermissionApprovedForSession | PermissionApprovedForLocation | PermissionCancelled | PermissionDeniedByRules | PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser | PermissionDeniedInteractivelyByUser | PermissionDeniedByContentExclusionPolicy | PermissionDeniedByPermissionRequestHook +# Experimental: this enum is part of an experimental API and may change or be removed. +class AutoApprovalRecommendation(Enum): + "Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off)." + # The judge evaluated the request and recommends automatically approving it. + APPROVE = "approve" + # The judge evaluated the request and does not recommend auto-approving it; explicit approval is required. Whether that means prompting, denying, or something else is the consumer's decision. + REQUIRE_APPROVAL = "requireApproval" + # Auto mode is enabled, but this request category is never auto-approvable (for example, sandbox-bypass requests), so the judge was not consulted. + EXCLUDED = "excluded" + # The judge was consulted but did not return a usable recommendation, so the request requires explicit approval. + ERROR = "error" + + # Experimental: this enum is part of an experimental API and may change or be removed. class CitationProvider(Enum): "The system that produced a citation." @@ -7757,6 +8972,17 @@ class CitationProvider(Enum): CLIENT = "client" +# Experimental: this enum is part of an experimental API and may change or be removed. +class PermissionAllowAllMode(Enum): + "Allow-all mode for the session." + # Permission requests follow the normal approval flow. + OFF = "off" + # Tool, path, and URL permission requests are automatically approved. + ON = "on" + # Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + AUTO = "auto" + + class AbortReason(Enum): "Finite reason code describing why the current turn was aborted" # The local user requested the abort, for example by pressing Ctrl+C in the CLI. @@ -7797,6 +9023,16 @@ class AttachmentGitHubReferenceType(Enum): DISCUSSION = "discussion" +class AutoModeResolvedReasoningBucket(Enum): + "Coarse request-difficulty bucket for UX explainability" + # The request looks low-reasoning; a lighter model is appropriate. + LOW = "low" + # The request needs a moderate amount of reasoning. + MEDIUM = "medium" + # The request looks high-reasoning; a stronger model is appropriate. + HIGH = "high" + + class AutoModeSwitchResponse(Enum): "The user's auto-mode-switch choice" # Switch models for this request. @@ -7915,6 +9151,36 @@ class HandoffSourceType(Enum): LOCAL = "local" +class ManagedSettingsResolvedSource(Enum): + "Which channel supplied the effective enterprise managed settings (highest-authority present layer wins wholesale)" + # Account/org policy self-fetched from the GitHub managed-settings endpoint (higher authority). + SERVER = "server" + # Device-level MDM policy discovered from plist/registry/file (lower authority). + DEVICE = "device" + # No managed policy is in force (no layer contributed). + NONE = "none" + + +class McpHeadersRefreshCompletedOutcome(Enum): + "How the pending MCP headers refresh request resolved." + # The host supplied dynamic headers. + HEADERS = "headers" + # The host responded with no dynamic headers. + NONE = "none" + # No response arrived within the bounded window. + TIMEOUT = "timeout" + + +class McpHeadersRefreshRequiredReason(Enum): + "Why dynamic headers are being requested." + # The transport is making its first dynamic header request for this server. + STARTUP = "startup" + # The previously cached dynamic headers expired. + TTL_EXPIRED = "ttl-expired" + # The server returned 401 and stale dynamic headers were invalidated. + AUTH_FAILED = "auth-failed" + + class McpOauthCompletionOutcome(Enum): "How the pending MCP OAuth request was completed" # The request completed with a token-backed OAuth provider. @@ -7923,6 +9189,18 @@ class McpOauthCompletionOutcome(Enum): CANCELLED = "cancelled" +class McpOauthRequestReason(Enum): + "Reason the runtime is requesting host-provided MCP OAuth credentials" + # Initial credentials are required before connecting to the MCP server. + INITIAL = "initial" + # The current host-provided credential was rejected and a replacement is requested. + REFRESH = "refresh" + # The server requires a new host authorization flow before continuing. + REAUTH = "reauth" + # The server requires a credential with additional scope or audience. + UPSCOPE = "upscope" + + class McpServerSource(Enum): "Configuration source: user, workspace, plugin, or builtin" # Server configured in the user's global MCP configuration. @@ -8051,6 +9329,18 @@ class ReasoningSummary(Enum): DETAILED = "detailed" +class SessionLimitsExhaustedResponseAction(Enum): + "User action selected for an exhausted session limit." + # Increase the current max by an exact AI Credits amount. + ADD = "add" + # Set a new absolute max AI Credits value. + SET = "set" + # Remove the current session limit. + UNSET = "unset" + # Leave the limit unchanged and cancel the blocked model request. + CANCEL = "cancel" + + class SessionMode(Enum): "The session mode the agent is operating in" # The agent is responding interactively to the user. @@ -8149,6 +9439,26 @@ class UserMessageAgentMode(Enum): SHELL = "shell" +class UserMessageDelivery(Enum): + "How this user message was delivered to the agentic loop, relative to whether the loop was already running. This is the timing axis only; the message's origin (human vs. system/command/schedule/skill/etc.) is carried separately by `source`. A system-injected message has a delivery too — e.g. a background-task notification waking an idle agent is `idle`, the same mechanism as a human starting a fresh turn." + # Delivered while the loop was idle; starts its own run immediately (a human's fresh turn, or a system notification waking an idle agent). + IDLE = "idle" + # Injected into the current in-flight run while the agent was busy (immediate mode). + STEERING = "steering" + # Enqueued while the agent was busy; processed as its own run afterward. + QUEUED = "queued" + + +class Verbosity(Enum): + "Output verbosity level used for supported model calls (e.g. \"low\", \"medium\", \"high\")" + # A terse response was requested. + LOW = "low" + # A medium amount of response detail was requested. + MEDIUM = "medium" + # A more detailed response was requested. + HIGH = "high" + + class WorkingDirectoryContextHostType(Enum): "Hosting platform type of the repository (github or ado)" # Repository is hosted on GitHub. @@ -8165,7 +9475,7 @@ class WorkspaceFileChangedOperation(Enum): UPDATE = "update" -SessionEventData = SessionStartData | SessionResumeData | SessionRemoteSteerableChangedData | SessionErrorData | SessionIdleData | SessionTitleChangedData | SessionScheduleCreatedData | SessionScheduleCancelledData | SessionScheduleRearmedData | SessionAutopilotObjectiveChangedData | SessionInfoData | SessionWarningData | SessionModelChangeData | SessionModeChangedData | SessionPermissionsChangedData | SessionPlanChangedData | SessionTodosChangedData | SessionWorkspaceFileChangedData | SessionHandoffData | SessionTruncationData | SessionSnapshotRewindData | SessionShutdownData | SessionContextChangedData | SessionUsageInfoData | SessionCompactionStartData | SessionCompactionCompleteData | SessionTaskCompleteData | UserMessageData | PendingMessagesModifiedData | AssistantTurnStartData | AssistantIntentData | AssistantReasoningData | AssistantReasoningDeltaData | AssistantStreamingDeltaData | AssistantMessageData | AssistantMessageStartData | AssistantMessageDeltaData | AssistantTurnEndData | AssistantUsageData | ModelCallFailureData | AbortData | ToolUserRequestedData | ToolExecutionStartData | ToolExecutionPartialResultData | ToolExecutionProgressData | ToolExecutionCompleteData | SkillInvokedData | SubagentStartedData | SubagentCompletedData | SubagentFailedData | SubagentSelectedData | SubagentDeselectedData | HookStartData | HookEndData | HookProgressData | SessionBinaryAssetData | SystemMessageData | SystemNotificationData | PermissionRequestedData | PermissionCompletedData | UserInputRequestedData | UserInputCompletedData | ElicitationRequestedData | ElicitationCompletedData | SamplingRequestedData | SamplingCompletedData | McpOauthRequiredData | McpOauthCompletedData | SessionCustomNotificationData | ExternalToolRequestedData | ExternalToolCompletedData | CommandQueuedData | CommandExecuteData | CommandCompletedData | AutoModeSwitchRequestedData | AutoModeSwitchCompletedData | CommandsChangedData | CapabilitiesChangedData | ExitPlanModeRequestedData | ExitPlanModeCompletedData | SessionToolsUpdatedData | SessionBackgroundTasksChangedData | SessionSkillsLoadedData | SessionCustomAgentsUpdatedData | SessionMcpServersLoadedData | SessionMcpServerStatusChangedData | SessionExtensionsLoadedData | SessionCanvasOpenedData | SessionCanvasRegistryChangedData | SessionCanvasClosedData | SessionCanvasUnavailableData | SessionCanvasRecordedData | SessionCanvasRemovedData | SessionExtensionsAttachmentsPushedData | McpAppToolCallCompleteData | RawSessionEventData | Data +SessionEventData = SessionStartData | SessionResumeData | SessionRemoteSteerableChangedData | SessionErrorData | SessionIdleData | SessionTitleChangedData | SessionScheduleCreatedData | SessionScheduleCancelledData | SessionScheduleRearmedData | SessionAutopilotObjectiveChangedData | SessionInfoData | SessionWarningData | SessionModelChangeData | SessionModeChangedData | SessionSessionLimitsChangedData | SessionPermissionsChangedData | SessionPlanChangedData | SessionTodosChangedData | SessionWorkspaceFileChangedData | SessionHandoffData | SessionTruncationData | SessionSnapshotRewindData | SessionShutdownData | SessionUsageCheckpointData | SessionContextChangedData | SessionUsageInfoData | SessionCompactionStartData | SessionCompactionCompleteData | SessionTaskCompleteData | UserMessageData | PendingMessagesModifiedData | AssistantTurnStartData | AssistantIntentData | AssistantServerToolProgressData | AssistantReasoningData | AssistantReasoningDeltaData | AssistantToolCallDeltaData | AssistantStreamingDeltaData | AssistantMessageData | AssistantMessageStartData | AssistantMessageDeltaData | AssistantTurnEndData | AssistantIdleData | AssistantUsageData | ModelCallFailureData | AbortData | ToolUserRequestedData | ToolExecutionStartData | ToolExecutionPartialResultData | ToolExecutionProgressData | ToolExecutionCompleteData | SkillInvokedData | SubagentStartedData | SubagentCompletedData | SubagentFailedData | SubagentSelectedData | SubagentDeselectedData | HookStartData | HookEndData | HookProgressData | SessionBinaryAssetData | SystemMessageData | SystemNotificationData | PermissionRequestedData | PermissionCompletedData | UserInputRequestedData | UserInputCompletedData | ElicitationRequestedData | ElicitationCompletedData | SamplingRequestedData | SamplingCompletedData | McpOauthRequiredData | McpOauthCompletedData | McpHeadersRefreshRequiredData | McpHeadersRefreshCompletedData | SessionCustomNotificationData | ExternalToolRequestedData | ExternalToolCompletedData | CommandQueuedData | CommandExecuteData | CommandCompletedData | AutoModeSwitchRequestedData | AutoModeSwitchCompletedData | SessionLimitsExhaustedRequestedData | SessionLimitsExhaustedCompletedData | SessionAutoModeResolvedData | SessionManagedSettingsResolvedData | CommandsChangedData | CapabilitiesChangedData | ExitPlanModeRequestedData | ExitPlanModeCompletedData | SessionToolsUpdatedData | SessionBackgroundTasksChangedData | SessionSkillsLoadedData | SessionCustomAgentsUpdatedData | SessionMcpServersLoadedData | SessionMcpServerStatusChangedData | McpToolsListChangedData | McpResourcesListChangedData | McpPromptsListChangedData | SessionExtensionsLoadedData | SessionCanvasOpenedData | SessionCanvasRegistryChangedData | SessionCanvasClosedData | SessionCanvasUnavailableData | SessionCanvasRecordedData | SessionCanvasRemovedData | SessionExtensionsAttachmentsPushedData | McpAppToolCallCompleteData | RawSessionEventData | Data @dataclass @@ -8205,6 +9515,7 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.SESSION_WARNING: data = SessionWarningData.from_dict(data_obj) case SessionEventType.SESSION_MODEL_CHANGE: data = SessionModelChangeData.from_dict(data_obj) case SessionEventType.SESSION_MODE_CHANGED: data = SessionModeChangedData.from_dict(data_obj) + case SessionEventType.SESSION_SESSION_LIMITS_CHANGED: data = SessionSessionLimitsChangedData.from_dict(data_obj) case SessionEventType.SESSION_PERMISSIONS_CHANGED: data = SessionPermissionsChangedData.from_dict(data_obj) case SessionEventType.SESSION_PLAN_CHANGED: data = SessionPlanChangedData.from_dict(data_obj) case SessionEventType.SESSION_TODOS_CHANGED: data = SessionTodosChangedData.from_dict(data_obj) @@ -8213,6 +9524,7 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.SESSION_TRUNCATION: data = SessionTruncationData.from_dict(data_obj) case SessionEventType.SESSION_SNAPSHOT_REWIND: data = SessionSnapshotRewindData.from_dict(data_obj) case SessionEventType.SESSION_SHUTDOWN: data = SessionShutdownData.from_dict(data_obj) + case SessionEventType.SESSION_USAGE_CHECKPOINT: data = SessionUsageCheckpointData.from_dict(data_obj) case SessionEventType.SESSION_CONTEXT_CHANGED: data = SessionContextChangedData.from_dict(data_obj) case SessionEventType.SESSION_USAGE_INFO: data = SessionUsageInfoData.from_dict(data_obj) case SessionEventType.SESSION_COMPACTION_START: data = SessionCompactionStartData.from_dict(data_obj) @@ -8222,13 +9534,16 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.PENDING_MESSAGES_MODIFIED: data = PendingMessagesModifiedData.from_dict(data_obj) case SessionEventType.ASSISTANT_TURN_START: data = AssistantTurnStartData.from_dict(data_obj) case SessionEventType.ASSISTANT_INTENT: data = AssistantIntentData.from_dict(data_obj) + case SessionEventType.ASSISTANT_SERVER_TOOL_PROGRESS: data = AssistantServerToolProgressData.from_dict(data_obj) case SessionEventType.ASSISTANT_REASONING: data = AssistantReasoningData.from_dict(data_obj) case SessionEventType.ASSISTANT_REASONING_DELTA: data = AssistantReasoningDeltaData.from_dict(data_obj) + case SessionEventType.ASSISTANT_TOOL_CALL_DELTA: data = AssistantToolCallDeltaData.from_dict(data_obj) case SessionEventType.ASSISTANT_STREAMING_DELTA: data = AssistantStreamingDeltaData.from_dict(data_obj) case SessionEventType.ASSISTANT_MESSAGE: data = AssistantMessageData.from_dict(data_obj) case SessionEventType.ASSISTANT_MESSAGE_START: data = AssistantMessageStartData.from_dict(data_obj) case SessionEventType.ASSISTANT_MESSAGE_DELTA: data = AssistantMessageDeltaData.from_dict(data_obj) case SessionEventType.ASSISTANT_TURN_END: data = AssistantTurnEndData.from_dict(data_obj) + case SessionEventType.ASSISTANT_IDLE: data = AssistantIdleData.from_dict(data_obj) case SessionEventType.ASSISTANT_USAGE: data = AssistantUsageData.from_dict(data_obj) case SessionEventType.MODEL_CALL_FAILURE: data = ModelCallFailureData.from_dict(data_obj) case SessionEventType.ABORT: data = AbortData.from_dict(data_obj) @@ -8259,6 +9574,8 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.SAMPLING_COMPLETED: data = SamplingCompletedData.from_dict(data_obj) case SessionEventType.MCP_OAUTH_REQUIRED: data = McpOauthRequiredData.from_dict(data_obj) case SessionEventType.MCP_OAUTH_COMPLETED: data = McpOauthCompletedData.from_dict(data_obj) + case SessionEventType.MCP_HEADERS_REFRESH_REQUIRED: data = McpHeadersRefreshRequiredData.from_dict(data_obj) + case SessionEventType.MCP_HEADERS_REFRESH_COMPLETED: data = McpHeadersRefreshCompletedData.from_dict(data_obj) case SessionEventType.SESSION_CUSTOM_NOTIFICATION: data = SessionCustomNotificationData.from_dict(data_obj) case SessionEventType.EXTERNAL_TOOL_REQUESTED: data = ExternalToolRequestedData.from_dict(data_obj) case SessionEventType.EXTERNAL_TOOL_COMPLETED: data = ExternalToolCompletedData.from_dict(data_obj) @@ -8267,6 +9584,10 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.COMMAND_COMPLETED: data = CommandCompletedData.from_dict(data_obj) case SessionEventType.AUTO_MODE_SWITCH_REQUESTED: data = AutoModeSwitchRequestedData.from_dict(data_obj) case SessionEventType.AUTO_MODE_SWITCH_COMPLETED: data = AutoModeSwitchCompletedData.from_dict(data_obj) + case SessionEventType.SESSION_LIMITS_EXHAUSTED_REQUESTED: data = SessionLimitsExhaustedRequestedData.from_dict(data_obj) + case SessionEventType.SESSION_LIMITS_EXHAUSTED_COMPLETED: data = SessionLimitsExhaustedCompletedData.from_dict(data_obj) + case SessionEventType.SESSION_AUTO_MODE_RESOLVED: data = SessionAutoModeResolvedData.from_dict(data_obj) + case SessionEventType.SESSION_MANAGED_SETTINGS_RESOLVED: data = SessionManagedSettingsResolvedData.from_dict(data_obj) case SessionEventType.COMMANDS_CHANGED: data = CommandsChangedData.from_dict(data_obj) case SessionEventType.CAPABILITIES_CHANGED: data = CapabilitiesChangedData.from_dict(data_obj) case SessionEventType.EXIT_PLAN_MODE_REQUESTED: data = ExitPlanModeRequestedData.from_dict(data_obj) @@ -8277,6 +9598,9 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.SESSION_CUSTOM_AGENTS_UPDATED: data = SessionCustomAgentsUpdatedData.from_dict(data_obj) case SessionEventType.SESSION_MCP_SERVERS_LOADED: data = SessionMcpServersLoadedData.from_dict(data_obj) case SessionEventType.SESSION_MCP_SERVER_STATUS_CHANGED: data = SessionMcpServerStatusChangedData.from_dict(data_obj) + case SessionEventType.MCP_TOOLS_LIST_CHANGED: data = McpToolsListChangedData.from_dict(data_obj) + case SessionEventType.MCP_RESOURCES_LIST_CHANGED: data = McpResourcesListChangedData.from_dict(data_obj) + case SessionEventType.MCP_PROMPTS_LIST_CHANGED: data = McpPromptsListChangedData.from_dict(data_obj) case SessionEventType.SESSION_EXTENSIONS_LOADED: data = SessionExtensionsLoadedData.from_dict(data_obj) case SessionEventType.SESSION_CANVAS_OPENED: data = SessionCanvasOpenedData.from_dict(data_obj) case SessionEventType.SESSION_CANVAS_REGISTRY_CHANGED: data = SessionCanvasRegistryChangedData.from_dict(data_obj) @@ -8322,6 +9646,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: __all__ = [ "AbortData", "AbortReason", + "AssistantIdleData", "AssistantIntentData", "AssistantMessageData", "AssistantMessageDeltaData", @@ -8331,7 +9656,9 @@ def session_event_to_dict(x: SessionEvent) -> Any: "AssistantMessageToolRequestType", "AssistantReasoningData", "AssistantReasoningDeltaData", + "AssistantServerToolProgressData", "AssistantStreamingDeltaData", + "AssistantToolCallDeltaData", "AssistantTurnEndData", "AssistantTurnStartData", "AssistantUsageApiEndpoint", @@ -8344,12 +9671,25 @@ def session_event_to_dict(x: SessionEvent) -> Any: "AttachmentExtensionContext", "AttachmentFile", "AttachmentFileLineRange", + "AttachmentGitHubActionsJob", + "AttachmentGitHubCommit", + "AttachmentGitHubFile", + "AttachmentGitHubFileDiff", + "AttachmentGitHubFileDiffSide", "AttachmentGitHubReference", "AttachmentGitHubReferenceType", + "AttachmentGitHubRelease", + "AttachmentGitHubRepository", + "AttachmentGitHubSnippet", + "AttachmentGitHubTreeComparison", + "AttachmentGitHubTreeComparisonSide", + "AttachmentGitHubUrl", "AttachmentSelection", "AttachmentSelectionDetails", "AttachmentSelectionDetailsEnd", "AttachmentSelectionDetailsStart", + "AutoApprovalRecommendation", + "AutoModeResolvedReasoningBucket", "AutoModeSwitchCompletedData", "AutoModeSwitchRequestedData", "AutoModeSwitchResponse", @@ -8397,25 +9737,37 @@ def session_event_to_dict(x: SessionEvent) -> Any: "ExtensionsLoadedExtensionStatus", "ExternalToolCompletedData", "ExternalToolRequestedData", + "GitHubRepoRef", "HandoffRepository", "HandoffSourceType", + "HeaderEntry", "HookEndData", "HookEndError", "HookProgressData", "HookStartData", + "ManagedSettingsResolvedSource", "McpAppToolCallCompleteData", "McpAppToolCallCompleteError", "McpAppToolCallCompleteToolMeta", "McpAppToolCallCompleteToolMetaUI", + "McpHeadersRefreshCompletedData", + "McpHeadersRefreshCompletedOutcome", + "McpHeadersRefreshRequiredData", + "McpHeadersRefreshRequiredReason", "McpOauthCompletedData", "McpOauthCompletionOutcome", + "McpOauthHttpResponse", + "McpOauthRequestReason", "McpOauthRequiredData", "McpOauthRequiredStaticClientConfig", "McpOauthWWWAuthenticateParams", + "McpPromptsListChangedData", + "McpResourcesListChangedData", "McpServerSource", "McpServerStatus", "McpServerTransport", "McpServersLoadedServer", + "McpToolsListChangedData", "ModelCallFailureBadRequestKind", "ModelCallFailureData", "ModelCallFailureRequestFingerprint", @@ -8424,9 +9776,11 @@ def session_event_to_dict(x: SessionEvent) -> Any: "OmittedBinaryResult", "OmittedBinaryType", "PendingMessagesModifiedData", + "PermissionAllowAllMode", "PermissionApproved", "PermissionApprovedForLocation", "PermissionApprovedForSession", + "PermissionAutoApproval", "PermissionCancelled", "PermissionCompletedData", "PermissionDeniedByContentExclusionPolicy", @@ -8473,6 +9827,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "ReasoningSummary", "SamplingCompletedData", "SamplingRequestedData", + "SessionAutoModeResolvedData", "SessionAutopilotObjectiveChangedData", "SessionBackgroundTasksChangedData", "SessionBinaryAssetData", @@ -8496,6 +9851,12 @@ def session_event_to_dict(x: SessionEvent) -> Any: "SessionHandoffData", "SessionIdleData", "SessionInfoData", + "SessionLimitsConfig", + "SessionLimitsExhaustedCompletedData", + "SessionLimitsExhaustedRequestedData", + "SessionLimitsExhaustedResponse", + "SessionLimitsExhaustedResponseAction", + "SessionManagedSettingsResolvedData", "SessionMcpServerStatusChangedData", "SessionMcpServersLoadedData", "SessionMode", @@ -8508,6 +9869,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "SessionScheduleCancelledData", "SessionScheduleCreatedData", "SessionScheduleRearmedData", + "SessionSessionLimitsChangedData", "SessionShutdownData", "SessionSkillsLoadedData", "SessionSnapshotRewindData", @@ -8517,6 +9879,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "SessionTodosChangedData", "SessionToolsUpdatedData", "SessionTruncationData", + "SessionUsageCheckpointData", "SessionUsageInfoData", "SessionWarningData", "SessionWorkspaceFileChangedData", @@ -8556,6 +9919,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "ToolExecutionCompleteContentResourceLink", "ToolExecutionCompleteContentResourceLinkIcon", "ToolExecutionCompleteContentResourceLinkIconTheme", + "ToolExecutionCompleteContentShellExit", "ToolExecutionCompleteContentTerminal", "ToolExecutionCompleteContentText", "ToolExecutionCompleteData", @@ -8577,6 +9941,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "ToolExecutionPartialResultData", "ToolExecutionProgressData", "ToolExecutionStartData", + "ToolExecutionStartShellToolInfo", "ToolExecutionStartToolDescription", "ToolExecutionStartToolDescriptionMeta", "ToolExecutionStartToolDescriptionMetaUI", @@ -8586,6 +9951,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "UserInputRequestedData", "UserMessageAgentMode", "UserMessageData", + "UserMessageDelivery", "UserToolSessionApproval", "UserToolSessionApprovalCommands", "UserToolSessionApprovalCustomTool", @@ -8595,6 +9961,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "UserToolSessionApprovalMemory", "UserToolSessionApprovalRead", "UserToolSessionApprovalWrite", + "Verbosity", "WorkingDirectoryContext", "WorkingDirectoryContextHostType", "WorkspaceFileChangedOperation", diff --git a/python/copilot/session.py b/python/copilot/session.py index 0dc569f258..b6736939ac 100644 --- a/python/copilot/session.py +++ b/python/copilot/session.py @@ -39,6 +39,9 @@ ExternalToolTextResultForLlm, HandlePendingToolCallRequest, LogRequest, + MCPOauthHandlePendingRequest, + MCPOauthPendingRequestResponse, + MCPOauthPendingRequestResponseKind, ModelSwitchToRequest, PermissionDecision, PermissionDecisionApproveOnce, @@ -67,6 +70,7 @@ CommandExecuteData, ElicitationRequestedData, ExternalToolRequestedData, + McpOauthRequiredData, PermissionRequest, PermissionRequestedData, SessionCanvasClosedData, @@ -83,6 +87,11 @@ logger = logging.getLogger(__name__) +# Fixed name of the runtime's built-in tool-search tool. A client can replace +# its behavior by registering a tool with this exact name and +# ``overrides_built_in_tool=True``. +_TOOL_SEARCH_TOOL_NAME = "tool_search_tool" + if TYPE_CHECKING: from .session_fs_provider import SessionFsProvider @@ -367,6 +376,72 @@ def approve_all( return PermissionDecisionApproveOnce() +# ============================================================================ +# MCP Auth Types +# ============================================================================ + + +class McpAuthWwwAuthenticateParams(TypedDict, total=False): + """Parsed parameters from an MCP server's WWW-Authenticate response.""" + + resourceMetadataUrl: str + scope: str + error: str + + +class McpAuthStaticClientConfig(TypedDict, total=False): + """Static OAuth client configuration supplied by the MCP server, if available.""" + + clientId: Required[str] + clientSecret: str + grantType: Literal["client_credentials"] + publicClient: bool + + +class McpAuthRequest(TypedDict, total=False): + """MCP OAuth request that the SDK host can satisfy with a host-acquired token.""" + + requestId: Required[str] + serverName: Required[str] + serverUrl: Required[str] + reason: Required[Literal["initial", "refresh", "reauth", "upscope"]] + wwwAuthenticateParams: McpAuthWwwAuthenticateParams + resourceMetadata: str + staticClientConfig: McpAuthStaticClientConfig + + +class McpAuthToken(TypedDict, total=False): + """Host-provided OAuth token data for a pending MCP OAuth request.""" + + accessToken: Required[str] + tokenType: str + expiresIn: int + + +class McpAuthResult(TypedDict, total=False): + """Result returned by an MCP auth request handler.""" + + kind: Required[Literal["token", "cancelled"]] + accessToken: str + tokenType: str + expiresIn: int + + +class McpAuthContext(TypedDict): + """Context for an MCP auth request handler invocation.""" + + sessionId: str + + +McpAuthHandlerResult = McpAuthResult | McpAuthToken | None + + +McpAuthHandler = Callable[ + [McpAuthRequest, McpAuthContext], + McpAuthHandlerResult | Awaitable[McpAuthHandlerResult], +] + + # ============================================================================ # User Input Request Types # ============================================================================ @@ -1005,6 +1080,9 @@ class CustomAgentConfig(TypedDict, total=False): skills: NotRequired[list[str]] # Model identifier (e.g. "claude-haiku-4.5"); runtime falls back to parent model if unavailable model: NotRequired[str] + # Reasoning effort for this agent's model. When omitted, no per-agent override + # is sent and the backend chooses its default; the parent effort is not inherited. + reasoning_effort: NotRequired[ReasoningEffort] class DefaultAgentConfig(TypedDict, total=False): @@ -1040,6 +1118,13 @@ class InfiniteSessionConfig(TypedDict, total=False): buffer_exhaustion_threshold: float +class SessionLimitsConfig(TypedDict, total=False): + """Experimental limits for the session's current accounting window.""" + + # Maximum AI credits available to the session in the current accounting window. + max_ai_credits: float + + class LargeToolOutputConfig(TypedDict, total=False): """ Configuration for handling large tool outputs. @@ -1057,6 +1142,28 @@ class LargeToolOutputConfig(TypedDict, total=False): output_directory: str +class ToolSearchConfig(TypedDict, total=False): + """ + Override for the runtime's built-in tool-search behavior. + + Tool search lets the model discover tools on demand instead of loading every + tool definition up front. When the total tool count exceeds the deferral + threshold, MCP and external tools are marked as deferred and surfaced through + the built-in ``tool_search_tool``. + + To override the tool-search tool's implementation, register a :class:`Tool` + named ``tool_search_tool`` with ``overrides_built_in_tool=True``. To customize + the in-prompt tool-search guidance, use the ``tool_instructions`` section of + the system message in ``"customize"`` mode. + """ + + # Toggle that enables or disables tool search. + enabled: bool + # Overrides the total tool count at which MCP and external tools are + # automatically deferred behind tool search. + defer_threshold: int + + class MemoryConfiguration(TypedDict): """ Configuration for session memory. @@ -1340,6 +1447,8 @@ def __init__( self._tool_handlers_lock = threading.Lock() self._permission_handler: _PermissionHandlerFn | None = None self._permission_handler_lock = threading.Lock() + self._mcp_auth_handler: McpAuthHandler | None = None + self._mcp_auth_handler_lock = threading.Lock() self._user_input_handler: UserInputHandler | None = None self._user_input_handler_lock = threading.Lock() self._exit_plan_mode_handler: ExitPlanModeHandler | None = None @@ -1729,6 +1838,58 @@ def _handle_broadcast_event(self, event: SessionEvent) -> None: ) ) + case McpOauthRequiredData() as data: + with self._mcp_auth_handler_lock: + handler = self._mcp_auth_handler + if not data.request_id: + return + if not handler: + logger.warning( + "Received MCP OAuth request without a registered MCP auth handler. " + "SessionId=%s, RequestId=%s", + self.session_id, + data.request_id, + ) + return + request: McpAuthRequest = { + "requestId": data.request_id, + "serverName": data.server_name, + "serverUrl": data.server_url, + "reason": data.reason.value, + } + if data.www_authenticate_params is not None: + request["wwwAuthenticateParams"] = {} + if data.www_authenticate_params.resource_metadata_url is not None: + request["wwwAuthenticateParams"]["resourceMetadataUrl"] = ( + data.www_authenticate_params.resource_metadata_url + ) + if data.www_authenticate_params.scope is not None: + request["wwwAuthenticateParams"]["scope"] = ( + data.www_authenticate_params.scope + ) + if data.www_authenticate_params.error is not None: + request["wwwAuthenticateParams"]["error"] = ( + data.www_authenticate_params.error + ) + if data.resource_metadata is not None: + request["resourceMetadata"] = data.resource_metadata + if data.static_client_config is not None: + static_client_config: McpAuthStaticClientConfig = { + "clientId": data.static_client_config.client_id, + } + if data.static_client_config.client_secret is not None: + static_client_config["clientSecret"] = ( + data.static_client_config.client_secret + ) + if data.static_client_config.grant_type is not None: + static_client_config["grantType"] = data.static_client_config.grant_type + if data.static_client_config.public_client is not None: + static_client_config["publicClient"] = ( + data.static_client_config.public_client + ) + request["staticClientConfig"] = static_client_config + asyncio.ensure_future(self._execute_mcp_auth_and_respond(request, handler)) + case CommandExecuteData() as data: request_id = data.request_id command_name = data.command_name @@ -1801,11 +1962,25 @@ async def _execute_tool_and_respond( ) -> None: """Execute a tool handler and send the result back via HandlePendingToolCall RPC.""" try: + # The built-in tool-search tool receives a snapshot of the session's + # currently initialized tools so an override can filter the live + # catalog without issuing its own RPC. Fetch it only for that tool to + # avoid a round-trip on every tool call; a failed fetch leaves the + # snapshot as None rather than failing the tool. + available_tools = None + if tool_name == _TOOL_SEARCH_TOOL_NAME: + try: + metadata = await self.rpc.tools.get_current_metadata() + available_tools = metadata.tools + except Exception: + available_tools = None + invocation = ToolInvocation( session_id=self.session_id, tool_call_id=tool_call_id, tool_name=tool_name, arguments=arguments, + available_tools=available_tools, ) with trace_context(traceparent, tracestate): @@ -1866,6 +2041,7 @@ async def _execute_tool_and_respond( text_result_for_llm=tool_result.text_result_for_llm, error=tool_result.error, result_type=tool_result.result_type, + tool_references=tool_result.tool_references, tool_telemetry=tool_result.tool_telemetry, ), ) @@ -1942,6 +2118,59 @@ async def _execute_permission_and_respond( except (JsonRpcError, ProcessExitedError, OSError): pass # Connection lost or RPC error — nothing we can do + async def _execute_mcp_auth_and_respond( + self, + request: McpAuthRequest, + handler: McpAuthHandler, + ) -> None: + """Execute an MCP auth handler and respond via RPC.""" + request_id = request["requestId"] + try: + handler_start = time.perf_counter() + maybe_result = handler(request, {"sessionId": self.session_id}) + if inspect.isawaitable(maybe_result): + result = cast(McpAuthHandlerResult, await maybe_result) + else: + result = maybe_result + log_timing( + logger, + logging.DEBUG, + "CopilotSession._execute_mcp_auth_and_respond dispatch", + handler_start, + session_id=self.session_id, + request_id=request_id, + ) + + if result and result.get("kind", "token") == "token": + rpc_result = MCPOauthPendingRequestResponse( + kind=MCPOauthPendingRequestResponseKind.TOKEN, + access_token=result["accessToken"], + expires_in=result.get("expiresIn"), + token_type=result.get("tokenType"), + ) + else: + rpc_result = MCPOauthPendingRequestResponse( + kind=MCPOauthPendingRequestResponseKind.CANCELLED + ) + await self.rpc.mcp.oauth.handle_pending_request( + MCPOauthHandlePendingRequest( + request_id=request_id, + result=rpc_result, + ) + ) + except Exception: + try: + await self.rpc.mcp.oauth.handle_pending_request( + MCPOauthHandlePendingRequest( + request_id=request_id, + result=MCPOauthPendingRequestResponse( + kind=MCPOauthPendingRequestResponseKind.CANCELLED + ), + ) + ) + except (JsonRpcError, ProcessExitedError, OSError): + pass # Connection lost or RPC error — nothing we can do + async def _execute_command_and_respond( self, request_id: str, @@ -2126,6 +2355,11 @@ def _register_elicitation_handler(self, handler: ElicitationHandler | None) -> N with self._elicitation_handler_lock: self._elicitation_handler = handler + def _register_mcp_auth_handler(self, handler: McpAuthHandler | None) -> None: + """Register the MCP auth handler for this session.""" + with self._mcp_auth_handler_lock: + self._mcp_auth_handler = handler + def _register_exit_plan_mode_handler(self, handler: ExitPlanModeHandler | None) -> None: """Register the exit-plan-mode handler for this session.""" with self._exit_plan_mode_handler_lock: @@ -2661,7 +2895,7 @@ async def set_model( is preserved. Args: - model: Model ID to switch to (e.g., "gpt-4.1", "claude-sonnet-4"). + model: Model ID to switch to (e.g., "gpt-5.4", "claude-sonnet-4"). reasoning_effort: Optional reasoning effort level for the new model (e.g., "low", "medium", "high", "xhigh"). reasoning_summary: Optional reasoning summary mode for supported @@ -2675,7 +2909,7 @@ async def set_model( Exception: If the session has been destroyed or the connection fails. Example: - >>> await session.set_model("gpt-4.1") + >>> await session.set_model("gpt-5.4") >>> await session.set_model("claude-sonnet-4.6", reasoning_effort="high") """ rpc_caps = None diff --git a/python/copilot/tools.py b/python/copilot/tools.py index a82a48b1e9..b96e303e3b 100644 --- a/python/copilot/tools.py +++ b/python/copilot/tools.py @@ -11,9 +11,12 @@ import json from collections.abc import Awaitable, Callable from dataclasses import dataclass, field -from typing import Any, Literal, TypeVar, get_type_hints, overload +from typing import TYPE_CHECKING, Any, Literal, TypeVar, get_type_hints, overload -from pydantic import BaseModel +from pydantic import BaseModel, ValidationError + +if TYPE_CHECKING: + from .generated.rpc import CurrentToolMetadata ToolResultType = Literal["success", "failure", "rejected", "denied", "timeout"] @@ -38,6 +41,7 @@ class ToolResult: binary_results_for_llm: list[ToolBinaryResult] | None = None session_log: str | None = None tool_telemetry: dict[str, Any] | None = None + tool_references: list[str] | None = None _from_exception: bool = field(default=False, repr=False) @@ -49,6 +53,14 @@ class ToolInvocation: tool_call_id: str = "" tool_name: str = "" arguments: Any = None + available_tools: list[CurrentToolMetadata] | None = None + """Snapshot of the session's currently initialized tools. + + Populated by the SDK only when this invocation targets the built-in + tool-search tool (``tool_search_tool``), so a tool-search override can + rank/filter the live catalog -- including MCP tools configured in settings -- + without issuing its own RPC. ``None`` for every other tool invocation. + """ ToolHandler = Callable[[ToolInvocation], ToolResult | Awaitable[ToolResult]] @@ -63,6 +75,7 @@ class Tool: overrides_built_in_tool: bool = False skip_permission: bool = False defer: Literal["auto", "never"] | None = None + metadata: dict[str, Any] | None = None T = TypeVar("T", bound=BaseModel) @@ -77,6 +90,7 @@ def define_tool( overrides_built_in_tool: bool = False, skip_permission: bool = False, defer: Literal["auto", "never"] | None = None, + metadata: dict[str, Any] | None = None, ) -> Callable[[Callable[..., Any]], Tool]: pass @@ -91,6 +105,7 @@ def define_tool( overrides_built_in_tool: bool = False, skip_permission: bool = False, defer: Literal["auto", "never"] | None = None, + metadata: dict[str, Any] | None = None, ) -> Tool: pass @@ -105,6 +120,7 @@ def define_tool( overrides_built_in_tool: bool = False, skip_permission: bool = False, defer: Literal["auto", "never"] | None = None, + metadata: dict[str, Any] | None = None, ) -> Tool: pass @@ -118,6 +134,7 @@ def define_tool( overrides_built_in_tool: bool = False, skip_permission: bool = False, defer: Literal["auto", "never"] | None = None, + metadata: dict[str, Any] | None = None, ) -> Tool | Callable[[Callable[[Any, ToolInvocation], Any]], Tool]: """ Define a tool with automatic JSON schema generation from Pydantic models. @@ -166,6 +183,10 @@ def lookup_issue(params: LookupIssueParams) -> str: rather than always pre-loaded. When "auto", the tool can be deferred and surfaced through tool search. When "never", the tool is always pre-loaded. Optional; defaults to "auto". + metadata: Opaque, host-defined metadata associated with the tool definition. + Keys are namespaced and not part of the stable public API; values + are not interpreted and may be recognized to inform host-specific + behavior. Unknown keys are preserved. Returns: A Tool instance @@ -211,7 +232,21 @@ async def wrapped_handler(invocation: ToolInvocation) -> ToolResult: if takes_params: args = invocation.arguments or {} if ptype is not None and _is_pydantic_model(ptype): - call_args.append(ptype.model_validate(args)) + try: + call_args.append(ptype.model_validate(args)) + except ValidationError as exc: + # Highlight input validation problems to the LLM. + parts = [] + for err in exc.errors(): + loc = ".".join(map(str, err["loc"])) + msg = err["msg"] + parts.append(f"{loc}: {msg}" if loc else msg) + return ToolResult( + text_result_for_llm="Invalid tool arguments:\n" + "\n".join(parts), + result_type="failure", + error=str(exc), + tool_telemetry={}, + ) else: call_args.append(args) if takes_invocation: @@ -246,6 +281,7 @@ async def wrapped_handler(invocation: ToolInvocation) -> ToolResult: overrides_built_in_tool=overrides_built_in_tool, skip_permission=skip_permission, defer=defer, + metadata=metadata, ) # If handler is provided, call decorator immediately @@ -265,6 +301,7 @@ async def wrapped_handler(invocation: ToolInvocation) -> ToolResult: overrides_built_in_tool=overrides_built_in_tool, skip_permission=skip_permission, defer=defer, + metadata=metadata, ) # Otherwise return decorator for @define_tool(...) usage diff --git a/python/e2e/_copilot_request_helpers.py b/python/e2e/_copilot_request_helpers.py index c3c6a06ddc..2d91bc9bc2 100644 --- a/python/e2e/_copilot_request_helpers.py +++ b/python/e2e/_copilot_request_helpers.py @@ -223,6 +223,75 @@ def build_inference_response(request: httpx.Request, text: str = SYNTHETIC_TEXT) content=stream_body.encode(), ) + if url.endswith("/messages"): + if wants_stream: + events = [ + ( + "message_start", + { + "type": "message_start", + "message": { + "id": "msg_stub_1", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4.5", + "content": [], + "stop_reason": None, + "stop_sequence": None, + "usage": {"input_tokens": 5, "output_tokens": 1}, + }, + }, + ), + ( + "content_block_start", + { + "type": "content_block_start", + "index": 0, + "content_block": {"type": "text", "text": ""}, + }, + ), + ( + "content_block_delta", + { + "type": "content_block_delta", + "index": 0, + "delta": {"type": "text_delta", "text": text}, + }, + ), + ("content_block_stop", {"type": "content_block_stop", "index": 0}), + ( + "message_delta", + { + "type": "message_delta", + "delta": {"stop_reason": "end_turn", "stop_sequence": None}, + "usage": {"output_tokens": 7}, + }, + ), + ("message_stop", {"type": "message_stop"}), + ] + stream_body = "".join(sse(event, data) for event, data in events) + return httpx.Response( + 200, + headers={"content-type": "text/event-stream"}, + content=stream_body.encode(), + ) + return httpx.Response( + 200, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "msg_stub_1", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4.5", + "content": [{"type": "text", "text": text}], + "stop_reason": "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 5, "output_tokens": 7}, + } + ).encode(), + ) + return httpx.Response( 200, headers={"content-type": "application/json"}, diff --git a/python/e2e/conftest.py b/python/e2e/conftest.py index 7409cf556b..f441097f32 100644 --- a/python/e2e/conftest.py +++ b/python/e2e/conftest.py @@ -5,7 +5,19 @@ import pytest import pytest_asyncio -from .testharness import E2ETestContext +from .testharness import E2ETestContext, is_inprocess_transport + +# Host-side auth resolution ranks HMAC above the GitHub token, so an ambient +# COPILOT_HMAC_KEY (CI sets one as a job-level credential) would be picked over +# the token the replay snapshots expect, yielding 401s. For the in-process +# transport the runtime is hosted in this test process and can capture the key as +# early as client construction, so neutralize it at module load — the analogue of +# .NET's InProcessEnvIsolation [ModuleInitializer] and Node's module-init guard. +# Out-of-process children resolve auth in their own process where the token already +# outranks HMAC. See https://github.com/github/copilot-sdk/issues/1934. +if is_inprocess_transport(): + os.environ.pop("COPILOT_HMAC_KEY", None) + os.environ.pop("CAPI_HMAC_KEY", None) @pytest.hookimpl(tryfirst=True, hookwrapper=True) diff --git a/python/e2e/test_client_options_e2e.py b/python/e2e/test_client_options_e2e.py index 9a70c6cbfe..bca4dbb722 100644 --- a/python/e2e/test_client_options_e2e.py +++ b/python/e2e/test_client_options_e2e.py @@ -20,11 +20,20 @@ import pytest -from copilot import CopilotClient, RuntimeConnection +from copilot import ( + CanvasDeclaration, + CloudSessionOptions, + CloudSessionRepository, + CopilotClient, + ExtensionInfo, + OpenCanvasInstance, + RemoteSessionMode, + RuntimeConnection, +) from copilot.rpc import PingRequest from copilot.session import PermissionHandler -from .testharness import E2ETestContext +from .testharness import DEFAULT_GITHUB_TOKEN, E2ETestContext pytestmark = pytest.mark.asyncio(loop_scope="module") @@ -56,9 +65,7 @@ def _make_options( "connection": connection, "working_directory": ctx.work_dir, "env": ctx.get_env(), - "github_token": ( - "fake-token-for-e2e-tests" if os.environ.get("GITHUB_ACTIONS") == "true" else None - ), + "github_token": DEFAULT_GITHUB_TOKEN, } base.update(overrides) return base @@ -147,6 +154,16 @@ def _get_available_port() -> int: writeResponse(message.id, { sessionId, workspacePath: null, capabilities: null }); return; } + if (message.method === "session.resume") { + const sessionId = message.params?.sessionId ?? message.params?.session_id ?? "fake-session"; + writeResponse(message.id, { + sessionId, + workspacePath: null, + capabilities: null, + openCanvases: message.params?.openCanvases ?? [], + }); + return; + } writeResponse(message.id, {}); } @@ -164,6 +181,14 @@ def _assert_arg_value(args: list[str], name: str, expected_value: str) -> None: assert args[index + 1] == expected_value +def _get_captured_request(capture_path: str, method: str) -> dict: + with open(capture_path) as f: + capture = json.load(f) + request = next((r for r in capture["requests"] if r["method"] == method), None) + assert request is not None, f"Expected {method} request in capture" + return request["params"] + + class TestClientOptions: async def test_should_listen_on_configured_tcp_port(self, ctx: E2ETestContext): port = _get_available_port() @@ -277,3 +302,287 @@ async def test_should_propagate_process_options_to_spawned_cli(self, ctx: E2ETes await client.stop() except Exception: await client.force_stop() + + async def test_should_forward_advanced_session_options_in_create_wire_request( + self, ctx: E2ETestContext + ): + cli_path = os.path.join(ctx.work_dir, f"fake-cli-advanced-create-{os.getpid()}.js") + capture_path = os.path.join( + ctx.work_dir, f"fake-cli-advanced-create-capture-{os.getpid()}.json" + ) + output_directory = os.path.join(ctx.work_dir, "large-output-create") + with open(cli_path, "w") as f: + f.write(FAKE_STDIO_CLI_SCRIPT) + + client = CopilotClient( + **_make_options( + ctx, + cli_path=cli_path, + cli_args=["--capture-file", capture_path], + use_logged_in_user=False, + ) + ) + try: + await client.start() + session = await client.create_session( + client_name="advanced-create-client", + model="claude-sonnet-4.5", + reasoning_effort="medium", + reasoning_summary="detailed", + context_tier="long_context", + enable_citations=True, + capi={"enable_web_socket_responses": False}, + mcp_oauth_token_storage="persistent", + custom_agents=[ + { + "name": "agent-one", + "display_name": "Agent One", + "description": "Handles agent-one tasks.", + "prompt": "Be agent one.", + "tools": ["view"], + "infer": True, + "skills": ["create-skill"], + "model": "claude-haiku-4.5", + } + ], + default_agent={"excluded_tools": ["edit"]}, + agent="agent-one", + skill_directories=["skills-create"], + disabled_skills=["disabled-create-skill"], + plugin_directories=["plugins-create"], + infinite_sessions={ + "enabled": False, + "background_compaction_threshold": 0.5, + "buffer_exhaustion_threshold": 0.9, + }, + large_output={ + "enabled": True, + "max_size_bytes": 4096, + "output_directory": output_directory, + }, + memory={"enabled": True}, + github_token="session-create-token", + remote_session=RemoteSessionMode.EXPORT, + cloud=CloudSessionOptions( + repository=CloudSessionRepository( + owner="github", + name="copilot-sdk", + branch="main", + ) + ), + enable_mcp_apps=True, + request_canvas_renderer=True, + request_extensions=True, + extension_sdk_path="custom-extension-sdk", + extension_info=ExtensionInfo( + source="python-sdk-tests", + name="advanced-create-extension", + ), + canvases=[ + CanvasDeclaration( + id="advanced-create-canvas", + display_name="Advanced Create Canvas", + description="Covers create-time canvas options.", + ) + ], + providers=[ + { + "name": "create-provider", + "type": "openai", + "wire_api": "responses", + "base_url": "https://create-provider.example.test/v1", + "api_key": "create-provider-key", + "headers": {"X-Create-Provider": "yes"}, + } + ], + models=[ + { + "provider": "create-provider", + "id": "create-model", + "name": "Create Model", + "model_id": "claude-sonnet-4.5", + "wire_model": "create-wire-model", + "max_context_window_tokens": 12_000, + "max_prompt_tokens": 10_000, + "max_output_tokens": 2_000, + } + ], + on_permission_request=PermissionHandler.approve_all, + ) + try: + params = _get_captured_request(capture_path, "session.create") + assert params["clientName"] == "advanced-create-client" + assert params["model"] == "claude-sonnet-4.5" + assert params["reasoningEffort"] == "medium" + assert params["reasoningSummary"] == "detailed" + assert params["contextTier"] == "long_context" + assert params["enableCitations"] is True + assert params["capi"]["enableWebSocketResponses"] is False + assert params["mcpOAuthTokenStorage"] == "persistent" + assert params["agent"] == "agent-one" + assert params["defaultAgent"]["excludedTools"][0] == "edit" + assert params["customAgents"][0]["name"] == "agent-one" + assert params["pluginDirectories"][0] == "plugins-create" + assert params["disabledSkills"][0] == "disabled-create-skill" + assert params["infiniteSessions"]["enabled"] is False + assert params["largeOutput"]["enabled"] is True + assert params["largeOutput"]["maxSizeBytes"] == 4096 + assert params["largeOutput"]["outputDir"] == output_directory + assert params["memory"]["enabled"] is True + assert params["gitHubToken"] == "session-create-token" + assert params["remoteSession"] == "export" + assert params["cloud"]["repository"]["owner"] == "github" + assert params["requestMcpApps"] is True + assert params["requestCanvasRenderer"] is True + assert params["requestExtensions"] is True + assert params["extensionSdkPath"] == "custom-extension-sdk" + assert params["extensionInfo"]["name"] == "advanced-create-extension" + assert params["canvases"][0]["id"] == "advanced-create-canvas" + assert params["providers"][0]["name"] == "create-provider" + assert params["providers"][0]["wireApi"] == "responses" + assert params["models"][0]["id"] == "create-model" + assert params["models"][0]["maxContextWindowTokens"] == 12_000 + finally: + await session.disconnect() + finally: + await client.stop() + + async def test_should_forward_singular_provider_options_in_create_wire_request( + self, ctx: E2ETestContext + ): + cli_path = os.path.join(ctx.work_dir, f"fake-cli-provider-create-{os.getpid()}.js") + capture_path = os.path.join( + ctx.work_dir, f"fake-cli-provider-create-capture-{os.getpid()}.json" + ) + with open(cli_path, "w") as f: + f.write(FAKE_STDIO_CLI_SCRIPT) + + client = CopilotClient( + **_make_options( + ctx, + cli_path=cli_path, + cli_args=["--capture-file", capture_path], + use_logged_in_user=False, + ) + ) + try: + await client.start() + session = await client.create_session( + model="claude-sonnet-4.5", + provider={ + "type": "azure", + "wire_api": "responses", + "transport": "http", + "base_url": "https://azure-provider.example.test/openai", + "api_key": "provider-api-key", + "bearer_token": "provider-bearer-token", + "azure": {"api_version": "2024-02-15-preview"}, + "headers": {"X-Provider-Wire": "yes"}, + "model_id": "claude-sonnet-4.5", + "wire_model": "azure-deployment", + "max_prompt_tokens": 8192, + "max_output_tokens": 1024, + }, + on_permission_request=PermissionHandler.approve_all, + ) + try: + provider = _get_captured_request(capture_path, "session.create")["provider"] + assert provider["type"] == "azure" + assert provider["wireApi"] == "responses" + assert provider["transport"] == "http" + assert provider["baseUrl"] == "https://azure-provider.example.test/openai" + assert provider["apiKey"] == "provider-api-key" + assert provider["bearerToken"] == "provider-bearer-token" + assert provider["azure"]["apiVersion"] == "2024-02-15-preview" + assert provider["headers"]["X-Provider-Wire"] == "yes" + assert provider["modelId"] == "claude-sonnet-4.5" + assert provider["wireModel"] == "azure-deployment" + assert provider["maxPromptTokens"] == 8192 + assert provider["maxOutputTokens"] == 1024 + finally: + await session.disconnect() + finally: + await client.stop() + + async def test_should_forward_advanced_session_options_in_resume_wire_request( + self, ctx: E2ETestContext + ): + cli_path = os.path.join(ctx.work_dir, f"fake-cli-advanced-resume-{os.getpid()}.js") + capture_path = os.path.join( + ctx.work_dir, f"fake-cli-advanced-resume-capture-{os.getpid()}.json" + ) + output_directory = os.path.join(ctx.work_dir, "large-output-resume") + with open(cli_path, "w") as f: + f.write(FAKE_STDIO_CLI_SCRIPT) + + client = CopilotClient( + **_make_options( + ctx, + cli_path=cli_path, + cli_args=["--capture-file", capture_path], + use_logged_in_user=False, + ) + ) + try: + await client.start() + session = await client.resume_session( + "advanced-resume-session", + client_name="advanced-resume-client", + model="claude-haiku-4.5", + reasoning_effort="low", + reasoning_summary="none", + context_tier="default", + continue_pending_work=True, + mcp_oauth_token_storage="persistent", + plugin_directories=["plugins-resume"], + large_output={ + "enabled": False, + "max_size_bytes": 2048, + "output_directory": output_directory, + }, + memory={"enabled": False}, + remote_session=RemoteSessionMode.ON, + open_canvases=[ + OpenCanvasInstance( + canvas_id="resume-canvas", + extension_id="python-sdk-tests/resume-extension", + extension_name="Resume Extension", + instance_id="resume-canvas-1", + input={"start": 41}, + status="ready", + title="Resume Canvas", + url="https://example.com/resume-canvas", + ) + ], + on_permission_request=PermissionHandler.approve_all, + ) + try: + params = _get_captured_request(capture_path, "session.resume") + assert params["sessionId"] == "advanced-resume-session" + assert params["clientName"] == "advanced-resume-client" + assert params["model"] == "claude-haiku-4.5" + assert params["reasoningEffort"] == "low" + assert params["reasoningSummary"] == "none" + assert params["contextTier"] == "default" + assert params["continuePendingWork"] is True + assert params["mcpOAuthTokenStorage"] == "persistent" + assert params["pluginDirectories"][0] == "plugins-resume" + assert params["largeOutput"]["enabled"] is False + assert params["largeOutput"]["maxSizeBytes"] == 2048 + assert params["largeOutput"]["outputDir"] == output_directory + assert params["memory"]["enabled"] is False + assert params["remoteSession"] == "on" + + open_canvas = params["openCanvases"][0] + assert open_canvas["canvasId"] == "resume-canvas" + assert open_canvas["extensionId"] == "python-sdk-tests/resume-extension" + assert open_canvas["extensionName"] == "Resume Extension" + assert open_canvas["instanceId"] == "resume-canvas-1" + assert open_canvas["input"]["start"] == 41 + assert open_canvas["status"] == "ready" + assert open_canvas["title"] == "Resume Canvas" + assert open_canvas["url"] == "https://example.com/resume-canvas" + finally: + await session.disconnect() + finally: + await client.stop() diff --git a/python/e2e/test_copilot_request_session_id_e2e.py b/python/e2e/test_copilot_request_session_id_e2e.py index e40af13a1c..81624d73d0 100644 --- a/python/e2e/test_copilot_request_session_id_e2e.py +++ b/python/e2e/test_copilot_request_session_id_e2e.py @@ -36,6 +36,9 @@ class _InterceptedRequest: url: str session_id: str | None + agent_id: str | None + parent_agent_id: str | None + interaction_type: str | None class _SessionIdHandler(CopilotRequestHandler): @@ -46,7 +49,15 @@ async def send_request( self, request: httpx.Request, ctx: CopilotRequestContext ) -> httpx.Response: url = str(request.url) - self.records.append(_InterceptedRequest(url=url, session_id=ctx.session_id)) + self.records.append( + _InterceptedRequest( + url=url, + session_id=ctx.session_id, + agent_id=ctx.agent_id, + parent_agent_id=ctx.parent_agent_id, + interaction_type=ctx.interaction_type, + ) + ) if is_inference_url(url): return build_inference_response(request) # Force /responses transport so the inference URL is predictable. @@ -56,6 +67,11 @@ async def send_request( session_id_client = isolated_client_fixture(_SessionIdHandler) +def _assert_agent_metadata(record: _InterceptedRequest) -> None: + assert record.agent_id + assert record.interaction_type + + class TestCopilotRequestSessionId: capi_session_id: str | None = None @@ -78,6 +94,7 @@ async def test_threads_session_id_into_capi_session(self, session_id_client): assert r.session_id == session.session_id, ( "CAPI inference request must carry the runtime session id" ) + _assert_agent_metadata(r) # Validate the final assistant response arrived (guards against truncated captures) assert "OK from the synthetic" in text @@ -112,6 +129,7 @@ async def test_threads_session_id_into_byok_session(self, session_id_client): assert r.session_id == byok_session_id, ( "BYOK inference request must carry the runtime session id" ) + _assert_agent_metadata(r) # Session ids are per-session, so the two turns must differ. assert byok_session_id != TestCopilotRequestSessionId.capi_session_id diff --git a/python/e2e/test_github_telemetry_e2e.py b/python/e2e/test_github_telemetry_e2e.py new file mode 100644 index 0000000000..976b0b616e --- /dev/null +++ b/python/e2e/test_github_telemetry_e2e.py @@ -0,0 +1,57 @@ +"""Live CLI E2E coverage for forwarded GitHub telemetry notifications.""" + +from __future__ import annotations + +import asyncio + +import pytest + +from copilot import CopilotClient, GitHubTelemetryNotification, RuntimeConnection +from copilot.session import PermissionHandler + +from .testharness import DEFAULT_GITHUB_TOKEN, E2ETestContext +from .testharness.context import get_cli_path_for_tests + +pytestmark = pytest.mark.asyncio(loop_scope="module") + + +class TestGitHubTelemetryE2E: + async def test_should_receive_session_start_github_telemetry(self, ctx: E2ETestContext): + received: list[GitHubTelemetryNotification] = [] + + def on_github_telemetry(notification: GitHubTelemetryNotification) -> None: + received.append(notification) + + client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=get_cli_path_for_tests(), args=()), + working_directory=ctx.work_dir, + env=ctx.get_env(), + github_token=DEFAULT_GITHUB_TOKEN, + on_github_telemetry=on_github_telemetry, + ) + + session = None + try: + await client.start() + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) + + for _ in range(600): + if received: + break + await asyncio.sleep(0.05) + + assert received + notification = received[0] + assert isinstance(notification.session_id, str) + assert notification.session_id + assert isinstance(notification.restricted, bool) + assert notification.event is not None + assert isinstance(notification.event.kind, str) + finally: + try: + if session is not None: + await session.disconnect() + finally: + await client.stop() diff --git a/python/e2e/test_hooks_e2e.py b/python/e2e/test_hooks_e2e.py index 088379d4c7..d9a67cf030 100644 --- a/python/e2e/test_hooks_e2e.py +++ b/python/e2e/test_hooks_e2e.py @@ -18,10 +18,11 @@ class TestHooks: async def test_should_invoke_pretooluse_hook_when_model_runs_a_tool(self, ctx: E2ETestContext): """Test that preToolUse hook is invoked when model runs a tool""" pre_tool_use_inputs = [] + invocation_session_ids = [] async def on_pre_tool_use(input_data, invocation): pre_tool_use_inputs.append(input_data) - assert invocation["session_id"] == session.session_id + invocation_session_ids.append(invocation["session_id"]) # Allow the tool to run return {"permissionDecision": "allow"} @@ -37,6 +38,7 @@ async def on_pre_tool_use(input_data, invocation): # Should have received at least one preToolUse hook call assert len(pre_tool_use_inputs) > 0 + assert all(session_id == session.session_id for session_id in invocation_session_ids) # Should have received the tool name assert any(inp.get("toolName") for inp in pre_tool_use_inputs) @@ -48,10 +50,11 @@ async def test_should_invoke_posttooluse_hook_after_model_runs_a_tool( ): """Test that postToolUse hook is invoked after model runs a tool""" post_tool_use_inputs = [] + invocation_session_ids = [] async def on_post_tool_use(input_data, invocation): post_tool_use_inputs.append(input_data) - assert invocation["session_id"] == session.session_id + invocation_session_ids.append(invocation["session_id"]) return None session = await ctx.client.create_session( @@ -66,6 +69,7 @@ async def on_post_tool_use(input_data, invocation): # Should have received at least one postToolUse hook call assert len(post_tool_use_inputs) > 0 + assert all(session_id == session.session_id for session_id in invocation_session_ids) # Should have received the tool name and result assert any(inp.get("toolName") for inp in post_tool_use_inputs) diff --git a/python/e2e/test_hooks_extended_e2e.py b/python/e2e/test_hooks_extended_e2e.py index 5ad0ffea43..841c14c77b 100644 --- a/python/e2e/test_hooks_extended_e2e.py +++ b/python/e2e/test_hooks_extended_e2e.py @@ -28,10 +28,11 @@ async def test_should_invoke_userpromptsubmitted_hook_and_modify_prompt( self, ctx: E2ETestContext ): inputs: list[dict] = [] + invocation_session_ids: list[str] = [] async def on_user_prompt_submitted(input_data, invocation): inputs.append(input_data) - assert invocation["session_id"] + invocation_session_ids.append(invocation["session_id"]) return {"modifiedPrompt": "Reply with exactly: HOOKED_PROMPT"} session = await ctx.client.create_session( @@ -41,6 +42,7 @@ async def on_user_prompt_submitted(input_data, invocation): try: response = await session.send_and_wait("Say something else") assert inputs + assert all(session_id == session.session_id for session_id in invocation_session_ids) assert "Say something else" in inputs[0].get("prompt", "") assert "HOOKED_PROMPT" in (response.data.content or "") finally: @@ -48,10 +50,11 @@ async def on_user_prompt_submitted(input_data, invocation): async def test_should_invoke_sessionstart_hook(self, ctx: E2ETestContext): inputs: list[dict] = [] + invocation_session_ids: list[str] = [] async def on_session_start(input_data, invocation): inputs.append(input_data) - assert invocation["session_id"] + invocation_session_ids.append(invocation["session_id"]) return {"additionalContext": "Session start hook context."} session = await ctx.client.create_session( @@ -61,6 +64,7 @@ async def on_session_start(input_data, invocation): try: await session.send_and_wait("Say hi") assert inputs + assert all(session_id == session.session_id for session_id in invocation_session_ids) assert inputs[0].get("source") == "new" assert inputs[0].get("workingDirectory") finally: @@ -68,13 +72,14 @@ async def on_session_start(input_data, invocation): async def test_should_invoke_sessionend_hook(self, ctx: E2ETestContext): inputs: list[dict] = [] + invocation_session_ids: list[str] = [] hook_invoked: asyncio.Future = asyncio.get_event_loop().create_future() async def on_session_end(input_data, invocation): inputs.append(input_data) + invocation_session_ids.append(invocation["session_id"]) if not hook_invoked.done(): hook_invoked.set_result(input_data) - assert invocation["session_id"] return {"sessionSummary": "session ended"} session = await ctx.client.create_session( @@ -85,13 +90,15 @@ async def on_session_end(input_data, invocation): await session.disconnect() await asyncio.wait_for(hook_invoked, 10.0) assert inputs + assert all(session_id == session.session_id for session_id in invocation_session_ids) async def test_should_register_erroroccurred_hook(self, ctx: E2ETestContext): inputs: list[dict] = [] + invocation_session_ids: list[str] = [] async def on_error_occurred(input_data, invocation): inputs.append(input_data) - assert invocation["session_id"] + invocation_session_ids.append(invocation["session_id"]) return {"errorHandling": "skip"} session = await ctx.client.create_session( @@ -102,6 +109,7 @@ async def on_error_occurred(input_data, invocation): await session.send_and_wait("Say hi") # Registration-only test: a healthy turn shouldn't fire OnErrorOccurred. assert not inputs + assert not invocation_session_ids assert session.session_id finally: await session.disconnect() @@ -195,6 +203,7 @@ async def test_should_invoke_posttoolusefailure_hook_for_failed_tool_result( ): failure_inputs: list[dict] = [] post_tool_use_inputs: list[dict] = [] + invocation_session_ids: list[str] = [] async def on_post_tool_use(input_data, invocation): post_tool_use_inputs.append(input_data) @@ -202,7 +211,7 @@ async def on_post_tool_use(input_data, invocation): async def on_post_tool_use_failure(input_data, invocation): failure_inputs.append(input_data) - assert invocation["session_id"] == session.session_id + invocation_session_ids.append(invocation["session_id"]) return {"additionalContext": "HOOK_FAILURE_GUIDANCE_APPLIED"} session = await ctx.client.create_session( @@ -220,6 +229,7 @@ async def on_post_tool_use_failure(input_data, invocation): ) assert not post_tool_use_inputs assert len(failure_inputs) == 1 + assert all(session_id == session.session_id for session_id in invocation_session_ids) failure_input = failure_inputs[0] assert failure_input["toolName"] == "view" assert "does not exist" in failure_input["error"] diff --git a/python/e2e/test_inprocess_ffi_e2e.py b/python/e2e/test_inprocess_ffi_e2e.py new file mode 100644 index 0000000000..c119c4ea4e --- /dev/null +++ b/python/e2e/test_inprocess_ffi_e2e.py @@ -0,0 +1,40 @@ +"""E2E smoke test for the in-process (FFI) transport. + +Starts a client over the in-process FFI transport, performs a ``ping`` +round-trip through the native runtime library, and stops cleanly. Resolution of +the transport from ``COPILOT_SDK_DEFAULT_CONNECTION`` is exercised by the full +E2E suite running under the ``inprocess`` CI matrix cell, not here. + +Mirrors nodejs/test/e2e/inprocess_ffi.e2e.test.ts. +""" + +from __future__ import annotations + +import pytest + +from copilot import CopilotClient, RuntimeConnection + +from .testharness import E2ETestContext +from .testharness.context import get_cli_path_for_tests + +pytestmark = pytest.mark.asyncio(loop_scope="module") + + +class TestInProcessFfi: + async def test_should_start_and_connect_over_in_process_ffi( + self, ctx: E2ETestContext, monkeypatch: pytest.MonkeyPatch + ): + # In-process hosting loads the runtime cdylib next to the resolved CLI + # entrypoint and lets the native host spawn the worker. ``ping`` is a + # purely local RPC round-trip, so no auth or replay proxy is involved. + # If the native library is unavailable, start() raises and the test fails. + monkeypatch.setenv("COPILOT_CLI_PATH", get_cli_path_for_tests()) + client = CopilotClient(connection=RuntimeConnection.for_inprocess()) + await client.start() + + try: + pong = await client.ping("ffi message") + assert pong.message == "pong: ffi message" + assert pong.timestamp is not None + finally: + await client.stop() diff --git a/python/e2e/test_mcp_oauth_e2e.py b/python/e2e/test_mcp_oauth_e2e.py new file mode 100644 index 0000000000..9d70597c3e --- /dev/null +++ b/python/e2e/test_mcp_oauth_e2e.py @@ -0,0 +1,347 @@ +import asyncio +import json +import os +from pathlib import Path +from typing import Any + +import httpx +import pytest + +from copilot.generated.rpc import ( + MCPAppsCallToolRequest, + MCPListToolsRequest, + MCPOauthHandlePendingRequest, + MCPOauthPendingRequestResponse, + MCPOauthPendingRequestResponseKind, +) +from copilot.session import MCPServerConfig, PermissionHandler +from copilot.session_events import McpServerStatus + +from .testharness import E2ETestContext, wait_for_condition + +TEST_MCP_OAUTH_SERVER = str( + (Path(__file__).parents[2] / "test" / "harness" / "test-mcp-oauth-server.mjs").resolve() +) +EXPECTED_TOKEN = "sdk-host-token" +REFRESH_TOKEN = f"{EXPECTED_TOKEN}-refresh" +UPSCOPE_TOKEN = f"{EXPECTED_TOKEN}-upscope" +REAUTH_TOKEN = f"{EXPECTED_TOKEN}-reauth" + +pytestmark = pytest.mark.asyncio(loop_scope="module") + + +async def _start_oauth_mcp_server() -> tuple[str, asyncio.subprocess.Process]: + process = await asyncio.create_subprocess_exec( + "node", + TEST_MCP_OAUTH_SERVER, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + env={**os.environ, "EXPECTED_TOKEN": EXPECTED_TOKEN}, + ) + assert process.stdout is not None + + try: + line = await asyncio.wait_for(process.stdout.readline(), timeout=10) + except TimeoutError as exc: + await _stop_process(process) + assert process.stderr is not None + stderr = (await process.stderr.read()).decode(errors="replace") + raise TimeoutError(f"Timed out waiting for OAuth MCP server: {stderr}") from exc + if not line: + assert process.stderr is not None + stderr = (await process.stderr.read()).decode(errors="replace") + raise RuntimeError(f"OAuth MCP server exited before listening: {stderr}") + text = line.decode().strip() + if text.startswith("Listening: "): + return text.removeprefix("Listening: "), process + + await _stop_process(process) + raise RuntimeError(f"Unexpected OAuth MCP server startup line: {text}") + + +async def _stop_process(process: asyncio.subprocess.Process) -> None: + if process.returncode is not None: + return + process.terminate() + try: + await asyncio.wait_for(process.wait(), timeout=5) + except TimeoutError: + process.kill() + await process.wait() + + +async def _requests(base_url: str) -> list[dict[str, Any]]: + async with httpx.AsyncClient() as client: + response = await client.get(f"{base_url}/__requests") + response.raise_for_status() + return response.json() + + +async def _wait_for_mcp_server_status( + session, server_name: str, expected_status: McpServerStatus = McpServerStatus.CONNECTED +) -> None: + last_status = "" + + async def matches() -> bool: + nonlocal last_status + result = await session.rpc.mcp.list() + server = next((s for s in result.servers if s.name == server_name), None) + last_status = server.status.value if server is not None else "" + return server is not None and server.status == expected_status + + await wait_for_condition( + matches, + timeout=60.0, + poll_interval=0.2, + timeout_message=( + f"{server_name} did not reach {expected_status.value}; last status was {last_status}" + ), + ) + + +class TestMcpOAuth: + async def test_should_satisfy_mcp_oauth_using_host_provided_token(self, ctx: E2ETestContext): + url, process = await _start_oauth_mcp_server() + server_name = "oauth-protected-mcp" + observed_request = None + + def on_mcp_auth_request(request, _invocation): + nonlocal observed_request + observed_request = request + return { + "kind": "token", + "accessToken": EXPECTED_TOKEN, + "tokenType": "Bearer", + "expiresIn": 3600, + } + + try: + mcp_servers: dict[str, MCPServerConfig] = { + server_name: { + "type": "http", + "url": f"{url}/mcp", + "tools": ["*"], + } + } + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=on_mcp_auth_request, + mcp_servers=mcp_servers, + ) as session: + await _wait_for_mcp_server_status(session, server_name) + + tools = await session.rpc.mcp.list_tools( + MCPListToolsRequest(server_name=server_name) + ) + assert [tool.name for tool in tools.tools] == ["whoami"] + + assert observed_request is not None + assert observed_request["serverName"] == server_name + assert observed_request["serverUrl"] == f"{url}/mcp" + assert observed_request["reason"] == "initial" + assert observed_request["wwwAuthenticateParams"] == { + "resourceMetadataUrl": f"{url}/.well-known/oauth-protected-resource", + "scope": "mcp.read", + "error": "invalid_token", + } + assert json.loads(observed_request["resourceMetadata"]) == { + "resource": f"{url}/mcp", + "authorization_servers": [url], + "scopes_supported": ["mcp.read"], + "bearer_methods_supported": ["header"], + } + + requests = await _requests(url) + assert any(request["authorization"] is None for request in requests) + assert any( + request["authorization"] == f"Bearer {EXPECTED_TOKEN}" for request in requests + ) + finally: + await _stop_process(process) + + async def test_should_resolve_pending_mcp_oauth_request_with_direct_rpc( + self, ctx: E2ETestContext + ): + url, process = await _start_oauth_mcp_server() + server_name = "oauth-direct-rpc-mcp" + loop = asyncio.get_running_loop() + observed_request = loop.create_future() + release_handler = asyncio.Event() + + async def on_mcp_auth_request(request, _invocation): + if not observed_request.done(): + observed_request.set_result(request) + await release_handler.wait() + return {"kind": "token", "accessToken": EXPECTED_TOKEN} + + try: + mcp_servers: dict[str, MCPServerConfig] = { + server_name: { + "type": "http", + "url": f"{url}/mcp", + "tools": ["*"], + "oauthClientId": "sdk-e2e-client", + "oauthPublicClient": True, + } + } + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=on_mcp_auth_request, + mcp_servers=mcp_servers, + enable_mcp_apps=True, + ) as session: + connected = asyncio.create_task(_wait_for_mcp_server_status(session, server_name)) + try: + request = await asyncio.wait_for(observed_request, timeout=30.0) + assert request["serverName"] == server_name + assert request["serverUrl"] == f"{url}/mcp" + assert request["reason"] == "initial" + assert request["wwwAuthenticateParams"] == { + "resourceMetadataUrl": f"{url}/.well-known/oauth-protected-resource", + "scope": "mcp.read", + "error": "invalid_token", + } + + handled = await session.rpc.mcp.oauth.handle_pending_request( + MCPOauthHandlePendingRequest( + request_id=request["requestId"], + result=MCPOauthPendingRequestResponse( + kind=MCPOauthPendingRequestResponseKind.TOKEN, + access_token=EXPECTED_TOKEN, + token_type="Bearer", + expires_in=3600, + ), + ) + ) + assert handled.success is True + + connected_result = await asyncio.wait_for(connected, timeout=60.0) + assert connected_result is None + tools = await session.rpc.mcp.list_tools( + MCPListToolsRequest(server_name=server_name) + ) + assert [tool.name for tool in tools.tools] == ["whoami"] + finally: + release_handler.set() + if not connected.done(): + connected.cancel() + finally: + await _stop_process(process) + + async def test_should_request_replacement_tokens_across_mcp_oauth_lifecycle( + self, ctx: E2ETestContext + ): + url, process = await _start_oauth_mcp_server() + server_name = "oauth-lifecycle-mcp" + observed_requests: list[dict[str, Any]] = [] + refresh_count = 0 + + def on_mcp_auth_request(request, _invocation): + nonlocal refresh_count + observed_requests.append(request) + if request["reason"] == "refresh": + refresh_count += 1 + assert request["wwwAuthenticateParams"] == {"error": "invalid_token"} + if refresh_count > 1: + return {"kind": "cancelled"} + return {"kind": "token", "accessToken": REFRESH_TOKEN} + if request["reason"] == "upscope": + assert request["wwwAuthenticateParams"] == { + "resourceMetadataUrl": f"{url}/.well-known/oauth-protected-resource", + "scope": "mcp.write", + "error": "insufficient_scope", + } + return {"kind": "token", "accessToken": UPSCOPE_TOKEN} + if request["reason"] == "reauth": + return {"kind": "token", "accessToken": REAUTH_TOKEN} + return {"kind": "token", "accessToken": EXPECTED_TOKEN} + + try: + mcp_servers: dict[str, MCPServerConfig] = { + server_name: { + "type": "http", + "url": f"{url}/mcp", + "tools": ["*"], + } + } + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=on_mcp_auth_request, + mcp_servers=mcp_servers, + enable_mcp_apps=True, + ) as session: + await _wait_for_mcp_server_status(session, server_name) + + for scenario in ("refresh", "upscope", "reauth"): + result = await session.rpc.mcp.apps.call_tool( + MCPAppsCallToolRequest( + origin_server_name=server_name, + server_name=server_name, + tool_name="whoami", + arguments={"scenario": scenario}, + ) + ) + assert result["content"] == [{"type": "text", "text": "oauth-test-user"}] + + assert [request["reason"] for request in observed_requests] == [ + "initial", + "refresh", + "upscope", + "refresh", + "reauth", + ] + requests = await _requests(url) + assert any( + request["authorization"] == f"Bearer {REFRESH_TOKEN}" for request in requests + ) + assert any( + request["authorization"] == f"Bearer {UPSCOPE_TOKEN}" for request in requests + ) + assert any(request["authorization"] == f"Bearer {REAUTH_TOKEN}" for request in requests) + finally: + await _stop_process(process) + + async def test_should_cancel_pending_mcp_oauth_request(self, ctx: E2ETestContext): + url, process = await _start_oauth_mcp_server() + server_name = "oauth-cancelled-mcp" + observed_request = None + + def on_mcp_auth_request(request, _invocation): + nonlocal observed_request + observed_request = request + return {"kind": "cancelled"} + + try: + mcp_servers: dict[str, MCPServerConfig] = { + server_name: { + "type": "http", + "url": f"{url}/mcp", + "tools": ["*"], + } + } + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=on_mcp_auth_request, + mcp_servers=mcp_servers, + ) as session: + await _wait_for_mcp_server_status(session, server_name, McpServerStatus.NEEDS_AUTH) + + # The MCP connection is kicked off by session.create, but the SDK only registers + # its `mcp.oauth_required` event interest once create returns. If the server's + # initial 401 wins that race, the runtime records `needs-auth` WITHOUT invoking + # the host callback, so `observed_request` is briefly None even after `needs-auth` + # is observed. A later auth retry (now that interest is registered) invokes the + # callback with the same `initial` reason. Wait for the callback rather than + # sampling it the instant `needs-auth` first appears, which made this test flaky. + await wait_for_condition( + lambda: observed_request is not None, + timeout=60.0, + poll_interval=0.2, + timeout_message=f"{server_name} OAuth request did not reach the host callback", + ) + + assert observed_request is not None + assert observed_request["serverName"] == server_name + assert observed_request["reason"] == "initial" + finally: + await _stop_process(process) diff --git a/python/e2e/test_mode_handlers_e2e.py b/python/e2e/test_mode_handlers_e2e.py index 7ef9519f4a..f6173a4a5e 100644 --- a/python/e2e/test_mode_handlers_e2e.py +++ b/python/e2e/test_mode_handlers_e2e.py @@ -35,7 +35,7 @@ async def mode_ctx(ctx: E2ETestContext): """Configure per-token user responses for mode-handler tests.""" proxy_url = ctx.proxy_url - ctx.client._options.env["COPILOT_DEBUG_GITHUB_API_URL"] = proxy_url + ctx.add_runtime_env("COPILOT_DEBUG_GITHUB_API_URL", proxy_url) await ctx.set_copilot_user_by_token( MODE_HANDLER_TOKEN, @@ -119,7 +119,7 @@ async def on_exit_plan_mode_request(request, invocation): assert len(exit_plan_mode_requests) == 1 request = exit_plan_mode_requests[0] assert request["summary"] == PLAN_SUMMARY - assert request["actions"] == ["interactive", "autopilot", "exit_only"] + assert request["actions"] == ["autopilot", "interactive", "exit_only"] assert request["recommendedAction"] == "interactive" assert request.get("planContent") is not None diff --git a/python/e2e/test_per_session_auth_e2e.py b/python/e2e/test_per_session_auth_e2e.py index 0aa42cdaa3..a8d13dc1de 100644 --- a/python/e2e/test_per_session_auth_e2e.py +++ b/python/e2e/test_per_session_auth_e2e.py @@ -18,7 +18,7 @@ async def auth_ctx(ctx: E2ETestContext): # Redirect GitHub API calls to the proxy so per-session auth token # resolution (fetchCopilotUser) is intercepted. Must be set before the # CLI subprocess is spawned (i.e., before the first create_session call). - ctx.client._options.env["COPILOT_DEBUG_GITHUB_API_URL"] = proxy_url + ctx.add_runtime_env("COPILOT_DEBUG_GITHUB_API_URL", proxy_url) await ctx.set_copilot_user_by_token( "token-alice", @@ -58,7 +58,7 @@ async def test_should_create_session_with_github_token_and_check_auth_status( github_token="token-alice", ) - auth_status = await session.rpc.auth.get_status() + auth_status = await session.rpc.git_hub_auth.get_status() assert auth_status.is_authenticated is True assert auth_status.login == "alice" assert auth_status.copilot_plan == "individual_pro" @@ -77,8 +77,8 @@ async def test_should_isolate_auth_between_sessions_with_different_tokens( github_token="token-bob", ) - status_a = await session_a.rpc.auth.get_status() - status_b = await session_b.rpc.auth.get_status() + status_a = await session_a.rpc.git_hub_auth.get_status() + status_b = await session_b.rpc.git_hub_auth.get_status() assert status_a.is_authenticated is True assert status_a.login == "alice" @@ -108,7 +108,7 @@ async def test_should_return_unauthenticated_when_no_token_provided( on_permission_request=PermissionHandler.approve_all, ) - auth_status = await session.rpc.auth.get_status() + auth_status = await session.rpc.git_hub_auth.get_status() # Without a per-session token, there is no per-session identity. # In CI the process-level fake token may still authenticate globally, # so we check login rather than is_authenticated. On some platforms diff --git a/python/e2e/test_rpc_server_e2e.py b/python/e2e/test_rpc_server_e2e.py index 244eb2ec49..bcef26754b 100644 --- a/python/e2e/test_rpc_server_e2e.py +++ b/python/e2e/test_rpc_server_e2e.py @@ -16,7 +16,14 @@ from copilot import CopilotClient, RuntimeConnection from copilot.rpc import ( AccountGetQuotaRequest, + AgentsDiscoverRequest, + AgentsGetDiscoveryPathsRequest, ConnectRemoteSessionParams, + InstructionsDiscoverRequest, + InstructionsGetDiscoveryPathsRequest, + LlmInferenceHTTPResponseChunkError, + LlmInferenceHTTPResponseChunkRequest, + LlmInferenceHTTPResponseStartRequest, LocalSessionMetadataValue, MCPDiscoverRequest, ModelsListRequest, @@ -43,6 +50,7 @@ SessionsSetAdditionalPluginsRequest, SkillsConfigSetDisabledSkillsRequest, SkillsDiscoverRequest, + SkillsGetDiscoveryPathsRequest, ToolsListRequest, ) from copilot.session import PermissionHandler @@ -68,10 +76,16 @@ def _create_skill_directory(work_dir: str, skill_name: str, description: str) -> return str(skills_dir) +def _paths_equal(left: str, right: str | None) -> bool: + if right is None: + return False + return os.path.normcase(os.path.abspath(left)) == os.path.normcase(os.path.abspath(right)) + + @pytest.fixture(scope="module") async def authed_ctx(ctx: E2ETestContext): """Configure proxy to redirect GitHub user lookups so per-token auth works.""" - ctx.client._options.env["COPILOT_DEBUG_GITHUB_API_URL"] = ctx.proxy_url + ctx.add_runtime_env("COPILOT_DEBUG_GITHUB_API_URL", ctx.proxy_url) return ctx @@ -123,6 +137,44 @@ async def test_should_call_rpc_ping_with_typed_params_and_result(self, ctx: E2ET assert result.message == "pong: typed rpc test" assert result.timestamp is not None + async def test_should_reject_llm_inference_response_frames_for_missing_request( + self, ctx: E2ETestContext + ): + await ctx.client.start() + + start = await ctx.client.rpc.llm_inference.http_response_start( + LlmInferenceHTTPResponseStartRequest( + request_id="missing-llm-inference-request", + status=200, + status_text="OK", + headers={"content-type": ["text/event-stream"]}, + ) + ) + assert start.accepted is False + + chunk = await ctx.client.rpc.llm_inference.http_response_chunk( + LlmInferenceHTTPResponseChunkRequest( + request_id="missing-llm-inference-request", + data="data: {}\n\n", + binary=False, + end=False, + ) + ) + assert chunk.accepted is False + + error = await ctx.client.rpc.llm_inference.http_response_chunk( + LlmInferenceHTTPResponseChunkRequest( + request_id="missing-llm-inference-request", + data="", + end=True, + error=LlmInferenceHTTPResponseChunkError( + message="No pending LLM inference request.", + code="missing_request", + ), + ) + ) + assert error.accepted is False + async def test_should_call_rpc_models_list_with_typed_result(self, authed_ctx: E2ETestContext): token = "rpc-models-token" await _configure_user(authed_ctx, token) @@ -444,6 +496,68 @@ async def test_should_discover_server_mcp_and_skills(self, ctx: E2ETestContext): assert discovered.enabled is True assert discovered.path.endswith(os.path.join(skill_name, "SKILL.md")) + skill_paths = await ctx.client.rpc.skills.get_discovery_paths( + SkillsGetDiscoveryPathsRequest( + project_paths=[ctx.work_dir], + exclude_host_skills=True, + ) + ) + project_skill_path = next( + ( + path + for path in skill_paths.paths + if _paths_equal(ctx.work_dir, path.project_path) and path.preferred_for_creation + ), + None, + ) + assert project_skill_path is not None + assert project_skill_path.path.strip() + + agents = await ctx.client.rpc.agents.discover( + AgentsDiscoverRequest(project_paths=[ctx.work_dir], exclude_host_agents=True) + ) + assert all(agent.name.strip() for agent in agents.agents) + + agent_paths = await ctx.client.rpc.agents.get_discovery_paths( + AgentsGetDiscoveryPathsRequest( + project_paths=[ctx.work_dir], + exclude_host_agents=True, + ) + ) + project_agent_path = next( + ( + path + for path in agent_paths.paths + if _paths_equal(ctx.work_dir, path.project_path) and path.preferred_for_creation + ), + None, + ) + assert project_agent_path is not None + assert project_agent_path.path.strip() + + instructions = await ctx.client.rpc.instructions.discover( + InstructionsDiscoverRequest( + project_paths=[ctx.work_dir], + exclude_host_instructions=True, + ) + ) + assert all( + source.id.strip() and source.label.strip() and source.source_path.strip() + for source in instructions.sources + ) + + instruction_paths = await ctx.client.rpc.instructions.get_discovery_paths( + InstructionsGetDiscoveryPathsRequest( + project_paths=[ctx.work_dir], + exclude_host_instructions=True, + ) + ) + assert instruction_paths.paths + assert any( + _paths_equal(ctx.work_dir, path.project_path) for path in instruction_paths.paths + ) + assert all(path.path.strip() for path in instruction_paths.paths) + try: await ctx.client.rpc.skills.config.set_disabled_skills( SkillsConfigSetDisabledSkillsRequest(disabled_skills=[skill_name]) diff --git a/python/e2e/test_rpc_server_misc_e2e.py b/python/e2e/test_rpc_server_misc_e2e.py index 6f3870224a..d5ade1aec1 100644 --- a/python/e2e/test_rpc_server_misc_e2e.py +++ b/python/e2e/test_rpc_server_misc_e2e.py @@ -16,10 +16,13 @@ from copilot import CopilotClient, RuntimeConnection from copilot.rpc import ( + AccountLoginRequest, + AccountLogoutRequest, AgentRegistrySpawnRequest, SendAttachmentsToMessageParams, SessionsOpenResumeLast, SessionsOpenStatus, + UserSettingsSetRequest, ) from copilot.session import PermissionHandler @@ -37,17 +40,24 @@ def _create_dedicated_client(ctx: E2ETestContext) -> CopilotClient: ) -async def _create_isolated_client(ctx: E2ETestContext) -> tuple[CopilotClient, Path]: +async def _create_isolated_client( + ctx: E2ETestContext, github_token: str | None = DEFAULT_GITHUB_TOKEN +) -> tuple[CopilotClient, Path]: home = Path(ctx.work_dir) / f"copilot-e2e-misc-home-{uuid.uuid4().hex}" home.mkdir(parents=True) env = ctx.get_env() for key in ("COPILOT_HOME", "GH_CONFIG_DIR", "XDG_CONFIG_HOME", "XDG_STATE_HOME"): env[key] = str(home) + env["COPILOT_DEBUG_GITHUB_API_URL"] = ctx.proxy_url + if github_token is None: + env["GH_TOKEN"] = "" + env["GITHUB_TOKEN"] = "" client = CopilotClient( connection=RuntimeConnection.for_stdio(path=ctx.cli_path), working_directory=ctx.work_dir, env=env, - github_token=DEFAULT_GITHUB_TOKEN, + github_token=github_token, + use_logged_in_user=False if github_token is None else None, ) await client.start() return client, home @@ -70,6 +80,96 @@ async def test_should_reload_user_settings(self, ctx: E2ETestContext): await ctx.client.rpc.user.settings.reload() + async def test_should_get_set_and_clear_user_settings(self, ctx: E2ETestContext): + client, home = await _create_isolated_client(ctx) + try: + before = await client.rpc.user.settings.get() + assert len(before.settings) > 0 + for key, setting in before.settings.items(): + assert key.strip() + assert isinstance(setting.is_default, bool) + + setting_key, setting = next( + (key, value) + for key, value in before.settings.items() + if isinstance(value.value, bool) + ) + toggled_value = setting.value is not True + + set_result = await client.rpc.user.settings.set( + UserSettingsSetRequest(settings={setting_key: toggled_value}) + ) + assert setting_key not in set_result.shadowed_keys + + await client.rpc.user.settings.reload() + after_set = await client.rpc.user.settings.get() + assert after_set.settings[setting_key].is_default is False + assert after_set.settings[setting_key].value is toggled_value + + await client.rpc.user.settings.set(UserSettingsSetRequest(settings={setting_key: None})) + await client.rpc.user.settings.reload() + after_clear = await client.rpc.user.settings.get() + assert after_clear.settings[setting_key].is_default is True + finally: + await _dispose_isolated(client, home) + + async def test_should_login_list_get_current_auth_and_logout_account(self, ctx: E2ETestContext): + login = f"rpc-account-{uuid.uuid4().hex}" + token = f"rpc-account-token-{uuid.uuid4().hex}" + await ctx.set_copilot_user_by_token( + token, + { + "login": login, + "copilot_plan": "individual_pro", + "endpoints": { + "api": ctx.proxy_url, + "telemetry": "https://localhost:1/telemetry", + }, + "analytics_tracking_id": "rpc-account-tracking-id", + }, + ) + + client, home = await _create_isolated_client(ctx, github_token=None) + try: + initial = await client.rpc.account.get_current_auth() + assert initial.auth_info is None + + login_result = await client.rpc.account.login( + AccountLoginRequest(host="https://github.com", login=login, token=token) + ) + assert isinstance(login_result.stored_in_vault, bool) + + current = await client.rpc.account.get_current_auth() + assert current.auth_errors is None + assert current.auth_info is not None + assert current.auth_info.type == "user" + assert current.auth_info.host == "https://github.com" + assert current.auth_info.login == login + + users = await client.rpc.account.get_all_users() + assert isinstance(users, list) + account = next( + ( + user + for user in users + if user.auth_info.type == "user" + and getattr(user.auth_info, "login", None) == login + ), + None, + ) + if account is not None: + assert account.token == token + + logout = await client.rpc.account.logout( + AccountLogoutRequest(auth_info=current.auth_info) + ) + assert logout.has_more_users is False + + after_logout = await client.rpc.account.get_current_auth() + assert after_logout.auth_info is None + finally: + await _dispose_isolated(client, home) + async def test_should_report_agent_registry_spawn_gate_closed(self, ctx: E2ETestContext): client, home = await _create_isolated_client(ctx) try: diff --git a/python/e2e/test_rpc_server_plugins_e2e.py b/python/e2e/test_rpc_server_plugins_e2e.py index a325242e9e..538d1692fd 100644 --- a/python/e2e/test_rpc_server_plugins_e2e.py +++ b/python/e2e/test_rpc_server_plugins_e2e.py @@ -113,9 +113,7 @@ async def _dispose_isolated(client: CopilotClient, home: Path, fixture_dir: Path class TestRpcServerPlugins: - async def test_should_install_list_and_uninstall_plugin_from_local_marketplace( - self, ctx: E2ETestContext - ): + async def test_should_install_and_list_plugin_from_local_marketplace(self, ctx: E2ETestContext): marketplace_dir = _create_local_marketplace_fixture(ctx) client, home = await _create_isolated_client(ctx) try: @@ -141,13 +139,6 @@ async def test_should_install_list_and_uninstall_plugin_from_local_marketplace( assert len(listed) == 1 assert listed[0].enabled is True - await client.rpc.plugins.uninstall(PluginsUninstallRequest(name=spec)) - - after_uninstall = await client.rpc.plugins.list() - assert not any( - p.name == PLUGIN_NAME and p.marketplace == MARKETPLACE_NAME - for p in after_uninstall.plugins - ) finally: await _dispose_isolated(client, home, marketplace_dir) @@ -229,8 +220,14 @@ async def test_should_install_direct_local_plugin_with_deprecation_warning( after_install = await client.rpc.plugins.list() assert len([p for p in after_install.plugins if p.name == DIRECT_PLUGIN_NAME]) == 1 + assert install.plugin.direct_source_id - await client.rpc.plugins.uninstall(PluginsUninstallRequest(name=DIRECT_PLUGIN_NAME)) + await client.rpc.plugins.uninstall( + PluginsUninstallRequest( + name=DIRECT_PLUGIN_NAME, + direct_source_id=install.plugin.direct_source_id, + ) + ) after_uninstall = await client.rpc.plugins.list() assert not any(p.name == DIRECT_PLUGIN_NAME for p in after_uninstall.plugins) diff --git a/python/e2e/test_rpc_session_state_e2e.py b/python/e2e/test_rpc_session_state_e2e.py index 7bd94679d6..12688f2803 100644 --- a/python/e2e/test_rpc_session_state_e2e.py +++ b/python/e2e/test_rpc_session_state_e2e.py @@ -442,7 +442,7 @@ async def test_should_set_auth_credentials(self, ctx: E2ETestContext): ) try: login = f"sdk-rpc-{uuid.uuid4().hex}" - result = await session.rpc.auth.set_credentials( + result = await session.rpc.git_hub_auth.set_credentials( SessionSetCredentialsParams( credentials=UserAuthInfo( host="https://github.com", @@ -462,7 +462,7 @@ async def test_should_set_auth_credentials(self, ctx: E2ETestContext): ) assert result.success is True - status = await session.rpc.auth.get_status() + status = await session.rpc.git_hub_auth.get_status() assert status.is_authenticated is True assert status.auth_type == AuthInfoType.USER assert status.host == "https://github.com" diff --git a/python/e2e/test_rpc_session_state_extras_e2e.py b/python/e2e/test_rpc_session_state_extras_e2e.py index fb12157849..5d0d881a00 100644 --- a/python/e2e/test_rpc_session_state_extras_e2e.py +++ b/python/e2e/test_rpc_session_state_extras_e2e.py @@ -9,11 +9,28 @@ import contextlib import json +import time import pytest from copilot import CopilotClient, RuntimeConnection -from copilot.rpc import PermissionsSetAllowAllRequest +from copilot.rpc import ( + CompletionsRequestRequest, + MetadataContextHeaviestMessagesRequest, + ModelSwitchToRequest, + NamedProviderConfig, + PermissionsSetAllowAllRequest, + ProviderAddRequest, + ProviderModelConfig, + ProviderType, + ProviderWireAPI, + SessionVisibilityStatus, + SubagentSettings, + SubagentSettingsEntry, + SubagentSettingsEntryContextTier, + UpdateSubagentSettingsRequest, + VisibilitySetRequest, +) from copilot.session import PermissionHandler from .testharness import E2ETestContext @@ -83,6 +100,86 @@ async def test_should_report_session_activity_when_idle(self, ctx: E2ETestContex assert activity.has_active_work is False assert activity.abortable is False + async def test_should_add_byok_provider_and_model_at_runtime(self, ctx: E2ETestContext): + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) as session: + provider_name = f"sdk-runtime-provider-{time.time_ns()}" + model_id = "sdk-runtime-model" + selection_id = f"{provider_name}/{model_id}" + + added = await session.rpc.provider.add( + ProviderAddRequest( + providers=[ + NamedProviderConfig( + name=provider_name, + type=ProviderType.OPENAI, + wire_api=ProviderWireAPI.COMPLETIONS, + base_url="https://api.example.test/v1", + api_key="runtime-provider-secret", + headers={"X-SDK-Provider": "runtime"}, + ) + ], + models=[ + ProviderModelConfig( + provider=provider_name, + id=model_id, + name="SDK Runtime Model", + model_id="claude-sonnet-4.5", + wire_model="wire-sdk-runtime-model", + max_context_window_tokens=4096, + max_prompt_tokens=3072, + max_output_tokens=1024, + ) + ], + ) + ) + + assert len(added.models) == 1 + assert selection_id in json.dumps(added.models[0], sort_keys=True) + assert "SDK Runtime Model" in json.dumps(added.models[0], sort_keys=True) + + listed = await session.rpc.model.list() + assert any(selection_id in json.dumps(model, sort_keys=True) for model in listed.list) + + switched = await session.rpc.model.switch_to( + ModelSwitchToRequest(model_id=selection_id) + ) + assert switched.model_id == selection_id + assert (await session.rpc.model.get_current()).model_id == selection_id + + async def test_should_return_empty_completions_when_host_does_not_provide_them( + self, ctx: E2ETestContext + ): + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) as session: + triggers = await session.rpc.completions.get_trigger_characters() + assert triggers.trigger_characters == [] + + completions = await session.rpc.completions.request( + CompletionsRequestRequest(text="Use @", offset=5) + ) + assert completions.items == [] + + async def test_should_report_visibility_as_unsynced_for_local_session( + self, ctx: E2ETestContext + ): + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) as session: + initial = await session.rpc.visibility.get() + assert initial.synced is False + assert initial.status is None + assert initial.share_url is None + + updated = await session.rpc.visibility.set( + VisibilitySetRequest(status=SessionVisibilityStatus.REPO) + ) + assert updated.synced is False + assert updated.status is None + assert updated.share_url is None + async def test_should_get_and_set_allowall_permissions(self, ctx: E2ETestContext): async with await ctx.client.create_session( on_permission_request=PermissionHandler.approve_all, @@ -110,6 +207,60 @@ async def test_should_get_and_set_allowall_permissions(self, ctx: E2ETestContext PermissionsSetAllowAllRequest(enabled=False) ) + async def test_should_get_context_attribution_and_heaviest_messages_after_turn( + self, ctx: E2ETestContext + ): + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) as session: + answer = await session.send_and_wait("Say CONTEXT_METADATA_OK exactly.", timeout=60.0) + assert answer is not None + assert "CONTEXT_METADATA_OK" in (answer.data.content or "") + + attribution = await session.rpc.metadata.get_context_attribution() + assert attribution.context_attribution is not None + context_attribution = attribution.context_attribution + assert context_attribution.total_tokens > 0 + assert len(context_attribution.entries) > 0 + for entry in context_attribution.entries: + assert entry.id.strip() + assert entry.kind.strip() + assert entry.label.strip() + assert entry.tokens >= 0 + for key in entry.attributes or {}: + assert key.strip() + + heaviest = await session.rpc.metadata.get_context_heaviest_messages( + MetadataContextHeaviestMessagesRequest(limit=2) + ) + assert heaviest.total_tokens > 0 + assert len(heaviest.messages) <= 2 + for message in heaviest.messages: + assert message.id.strip() + assert message.tokens >= 0 + + async def test_should_update_and_clear_live_subagent_settings(self, ctx: E2ETestContext): + async with await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) as session: + await session.rpc.tools.update_subagent_settings( + UpdateSubagentSettingsRequest( + subagents=SubagentSettings( + { + "general-purpose": SubagentSettingsEntry( + model="claude-haiku-4.5", + effort_level="low", + context_tier=SubagentSettingsEntryContextTier.DEFAULT, + ) + } + ) + ) + ) + + await session.rpc.tools.update_subagent_settings( + UpdateSubagentSettingsRequest(subagents=None) + ) + async def test_should_read_empty_sql_todos_for_fresh_session(self, ctx: E2ETestContext): async with await ctx.client.create_session( on_permission_request=PermissionHandler.approve_all, diff --git a/python/e2e/test_rpc_tasks_and_handlers_e2e.py b/python/e2e/test_rpc_tasks_and_handlers_e2e.py index d712580a67..6a99cbb75d 100644 --- a/python/e2e/test_rpc_tasks_and_handlers_e2e.py +++ b/python/e2e/test_rpc_tasks_and_handlers_e2e.py @@ -14,6 +14,9 @@ from copilot.rpc import ( CommandsHandlePendingCommandRequest, HandlePendingToolCallRequest, + MCPHeadersHandlePendingHeadersRefreshRequest, + MCPHeadersHandlePendingHeadersRefreshRequestKind, + MCPHeadersHandlePendingHeadersRefreshRequestRequest, PermissionDecisionApproveForLocation, PermissionDecisionApproveForLocationApprovalCustomTool, PermissionDecisionApproveForSession, @@ -41,7 +44,10 @@ UIHandlePendingElicitationRequest, UIHandlePendingExitPlanModeRequest, UIHandlePendingSamplingRequest, + UIHandlePendingSessionLimitsExhaustedRequest, UIHandlePendingUserInputRequest, + UISessionLimitsExhaustedResponse, + UISessionLimitsExhaustedResponseAction, UIUnregisterDirectAutoModeSwitchHandlerRequest, UIUserInputResponse, ) @@ -253,6 +259,37 @@ async def test_should_return_expected_results_for_missing_pending_handler_reques ) ) assert location_approval.success is False + + session_limits = await session.rpc.ui.handle_pending_session_limits_exhausted( + UIHandlePendingSessionLimitsExhaustedRequest( + request_id="missing-session-limits-request", + response=UISessionLimitsExhaustedResponse( + action=UISessionLimitsExhaustedResponseAction.CANCEL + ), + ) + ) + assert session_limits.success is False + + headers = await session.rpc.mcp.headers.handle_pending_headers_refresh_request( + MCPHeadersHandlePendingHeadersRefreshRequestRequest( + request_id="missing-headers-refresh-request", + result=MCPHeadersHandlePendingHeadersRefreshRequest( + kind=MCPHeadersHandlePendingHeadersRefreshRequestKind.HEADERS, + headers={"X-SDK-Test": "missing"}, + ), + ) + ) + assert headers.success is False + + no_headers = await session.rpc.mcp.headers.handle_pending_headers_refresh_request( + MCPHeadersHandlePendingHeadersRefreshRequestRequest( + request_id="missing-headers-refresh-none-request", + result=MCPHeadersHandlePendingHeadersRefreshRequest( + kind=MCPHeadersHandlePendingHeadersRefreshRequestKind.NONE, + ), + ) + ) + assert no_headers.success is False finally: await session.disconnect() diff --git a/python/e2e/test_session_config_e2e.py b/python/e2e/test_session_config_e2e.py index 2ad34a29a5..62dc671893 100644 --- a/python/e2e/test_session_config_e2e.py +++ b/python/e2e/test_session_config_e2e.py @@ -1,15 +1,29 @@ """E2E tests for session configuration including model capabilities overrides.""" import base64 +import json import os import uuid +import httpx import pytest -from copilot import ModelCapabilitiesOverride, ModelSupportsOverride +from copilot import ( + CopilotClient, + CopilotRequestHandler, + ModelCapabilitiesOverride, + ModelSupportsOverride, + RuntimeConnection, +) +from copilot.copilot_request_handler import CopilotRequestContext from copilot.session import PermissionHandler -from .testharness import E2ETestContext +from ._copilot_request_helpers import ( + build_inference_response, + build_non_inference_response, + is_inference_url, +) +from .testharness import DEFAULT_GITHUB_TOKEN, E2ETestContext pytestmark = pytest.mark.asyncio(loop_scope="module") @@ -86,6 +100,91 @@ def _get_tool_names(exchange: dict) -> list[str]: return names +async def _send_and_get_next_exchange(session, ctx: E2ETestContext, prompt: str) -> dict: + existing_count = len(await ctx.get_exchanges()) + await session.send_and_wait(prompt) + exchanges = await ctx.get_exchanges() + assert len(exchanges) > existing_count + return exchanges[existing_count] + + +def _assert_session_limits_status(exchange: dict, expected_remaining: str) -> None: + for message in exchange.get("request", {}).get("messages", []): + content = message.get("content") + if message.get("role") == "user" and isinstance(content, str): + if "" in content: + assert f"Remaining session limits: {expected_remaining}." in content + assert ( + "Be frugal; avoid optional exploration and unnecessary tool calls." in content + ) + return + raise AssertionError("Expected session limits status message") + + +def _get_task_agent_types(exchange: dict) -> list[str]: + for tool in exchange.get("request", {}).get("tools", []) or []: + function = tool.get("function") if isinstance(tool, dict) else None + if isinstance(function, dict) and function.get("name") == "task": + parameters = function.get("parameters") + assert isinstance(parameters, dict) + values = parameters["properties"]["agent_type"]["enum"] + assert isinstance(values, list) + return [str(value) for value in values] + raise AssertionError("Expected task tool in request") + + +class _RecordingRequestHandler(CopilotRequestHandler): + def __init__(self): + self.records: list[tuple[str, bytes]] = [] + + async def send_request( + self, request: httpx.Request, ctx: CopilotRequestContext + ) -> httpx.Response: + del ctx + self.records.append((str(request.url), request.content)) + if is_inference_url(str(request.url)): + return build_inference_response(request) + return build_non_inference_response(str(request.url)) + + def inference_requests(self) -> list[tuple[str, bytes]]: + return [(url, body) for url, body in self.records if is_inference_url(url)] + + +def _create_pdf_attachment() -> dict: + pdf_text = ( + "%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n" + ) + return { + "type": "blob", + "data": base64.b64encode(pdf_text.encode("ascii")).decode("ascii"), + "displayName": "citation-source.pdf", + "mimeType": "application/pdf", + } + + +def _create_anthropic_provider() -> dict: + return { + "type": "anthropic", + "base_url": "https://anthropic-citations.invalid/v1", + "api_key": "test-provider-key", + "model_id": "claude-sonnet-4.5", + "wire_model": "claude-sonnet-4.5", + } + + +def _assert_anthropic_document_citations_enabled(request_body: bytes) -> None: + body = json.loads(request_body.decode("utf-8")) + document_blocks = [ + block + for message in body["messages"] + for block in message["content"] + if block.get("type") == "document" + ] + assert len(document_blocks) == 1 + assert document_blocks[0]["title"] == "citation-source.pdf" + assert document_blocks[0]["citations"] == {"enabled": True} + + PNG_1X1 = base64.b64decode( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" ) @@ -287,6 +386,161 @@ async def test_should_use_provider_model_id_as_wire_model(self, ctx: E2ETestCont await session.disconnect() + async def test_should_apply_session_limits_on_create(self, ctx: E2ETestContext): + session = await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + session_limits={"max_ai_credits": 30}, + ) + + exchange = await _send_and_get_next_exchange( + session, ctx, "Acknowledge the current session limits." + ) + _assert_session_limits_status(exchange, "30 AI credits") + + await session.disconnect() + + async def test_should_apply_session_limits_on_resume(self, ctx: E2ETestContext): + session1 = await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) + session2 = await ctx.client.resume_session( + session1.session_id, + on_permission_request=PermissionHandler.approve_all, + session_limits={"max_ai_credits": 30}, + ) + + exchange = await _send_and_get_next_exchange( + session2, ctx, "Acknowledge the current session limits." + ) + _assert_session_limits_status(exchange, "30 AI credits") + + await session2.disconnect() + await session1.disconnect() + + async def test_should_apply_excluded_built_in_agents_on_create(self, ctx: E2ETestContext): + excluded_agent = "explore" + prompt = "What is 1+1?" + + baseline_session = await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) + baseline_exchange = await _send_and_get_next_exchange(baseline_session, ctx, prompt) + assert excluded_agent in _get_task_agent_types(baseline_exchange) + await baseline_session.disconnect() + + excluded_session = await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + excluded_builtin_agents=[excluded_agent], + ) + excluded_exchange = await _send_and_get_next_exchange(excluded_session, ctx, prompt) + agent_types = _get_task_agent_types(excluded_exchange) + assert agent_types + assert excluded_agent not in agent_types + + await excluded_session.disconnect() + + async def test_should_apply_excluded_built_in_agents_on_resume(self, ctx: E2ETestContext): + excluded_agent = "explore" + session1 = await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) + session2 = await ctx.client.resume_session( + session1.session_id, + on_permission_request=PermissionHandler.approve_all, + excluded_builtin_agents=[excluded_agent], + ) + + exchange = await _send_and_get_next_exchange(session2, ctx, "What is 1+1?") + agent_types = _get_task_agent_types(exchange) + assert agent_types + assert excluded_agent not in agent_types + + await session2.disconnect() + await session1.disconnect() + + async def test_should_enable_citations_for_anthropic_file_attachments_on_create( + self, ctx: E2ETestContext + ): + handler = _RecordingRequestHandler() + client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=ctx.cli_path), + working_directory=ctx.work_dir, + env=ctx.get_env(), + github_token=DEFAULT_GITHUB_TOKEN, + request_handler=handler, + ) + await client.start() + try: + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + model="claude-sonnet-4.5", + enable_citations=True, + provider=_create_anthropic_provider(), + ) + try: + await session.send_and_wait( + "Summarize the attached PDF with citations enabled.", + attachments=[_create_pdf_attachment()], + ) + inference_requests = handler.inference_requests() + assert len(inference_requests) == 1 + _assert_anthropic_document_citations_enabled(inference_requests[0][1]) + finally: + await session.disconnect() + finally: + await client.stop() + + async def test_should_enable_citations_for_anthropic_file_attachments_on_resume( + self, ctx: E2ETestContext + ): + handler = _RecordingRequestHandler() + connection_token = "python-citation-resume-token" + server_client = CopilotClient( + connection=RuntimeConnection.for_tcp( + path=ctx.cli_path, + connection_token=connection_token, + ), + working_directory=ctx.work_dir, + env=ctx.get_env(), + github_token=DEFAULT_GITHUB_TOKEN, + request_handler=handler, + ) + await server_client.start() + try: + session1 = await server_client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) + assert server_client.runtime_port is not None + resume_client = CopilotClient( + connection=RuntimeConnection.for_uri( + f"localhost:{server_client.runtime_port}", + connection_token=connection_token, + ) + ) + try: + session2 = await resume_client.resume_session( + session1.session_id, + on_permission_request=PermissionHandler.approve_all, + model="claude-sonnet-4.5", + enable_citations=True, + provider=_create_anthropic_provider(), + ) + try: + await session2.send_and_wait( + "Summarize the attached PDF with citations enabled.", + attachments=[_create_pdf_attachment()], + ) + inference_requests = handler.inference_requests() + assert len(inference_requests) == 1 + _assert_anthropic_document_citations_enabled(inference_requests[0][1]) + finally: + await session2.disconnect() + finally: + await resume_client.stop() + await session1.disconnect() + finally: + await server_client.stop() + async def test_should_use_workingdirectory_for_tool_execution(self, ctx: E2ETestContext): sub_dir = os.path.join(ctx.work_dir, "subproject") os.makedirs(sub_dir, exist_ok=True) diff --git a/python/e2e/test_session_e2e.py b/python/e2e/test_session_e2e.py index 2dc7bb1dcb..22f99e4037 100644 --- a/python/e2e/test_session_e2e.py +++ b/python/e2e/test_session_e2e.py @@ -11,7 +11,12 @@ from copilot.session_events import SessionModelChangeData from copilot.tools import Tool, ToolResult -from .testharness import E2ETestContext, get_final_assistant_message, get_next_event_of_type +from .testharness import ( + DEFAULT_GITHUB_TOKEN, + E2ETestContext, + get_final_assistant_message, + get_next_event_of_type, +) pytestmark = pytest.mark.asyncio(loop_scope="module") @@ -275,6 +280,40 @@ async def test_should_resume_a_session_using_a_new_client(self, ctx: E2ETestCont finally: await new_client.force_stop() + async def test_resumes_a_persisted_session_from_a_new_client_when_an_mcp_oauth_handler_is_configured( # noqa: E501 + self, ctx: E2ETestContext + ): + def on_mcp_auth_request(_request, _invocation): + return {"kind": "cancelled"} + + session1 = await ctx.client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=on_mcp_auth_request, + ) + session_id = session1.session_id + answer = await session1.send_and_wait("What is 1+1?") + assert answer is not None + assert "2" in answer.data.content + + github_token = DEFAULT_GITHUB_TOKEN if os.environ.get("GITHUB_ACTIONS") == "true" else None + new_client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=ctx.cli_path), + working_directory=ctx.work_dir, + env=ctx.get_env(), + github_token=github_token, + ) + + try: + session2 = await new_client.resume_session( + session_id, + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=on_mcp_auth_request, + ) + assert session2.session_id == session_id + await session2.disconnect() + finally: + await new_client.force_stop() + async def test_should_throw_error_resuming_nonexistent_session(self, ctx: E2ETestContext): with pytest.raises(Exception): await ctx.client.resume_session( diff --git a/python/e2e/test_session_fs_e2e.py b/python/e2e/test_session_fs_e2e.py index 2fb99e5c42..fbfde6ee78 100644 --- a/python/e2e/test_session_fs_e2e.py +++ b/python/e2e/test_session_fs_e2e.py @@ -613,7 +613,7 @@ async def rm(self, path: str, recursive: bool, force: bool) -> None: async def rename(self, src: str, dest: str) -> None: d = self._path(dest) d.parent.mkdir(parents=True, exist_ok=True) - self._path(src).rename(d) + self._path(src).replace(d) def create_test_session_fs_handler(provider_root: Path): diff --git a/python/e2e/test_subagent_hooks_e2e.py b/python/e2e/test_subagent_hooks_e2e.py index 1ca2a54c12..da70265a04 100644 --- a/python/e2e/test_subagent_hooks_e2e.py +++ b/python/e2e/test_subagent_hooks_e2e.py @@ -3,10 +3,14 @@ fire for tool calls made by sub-agents spawned via the task tool. """ +from __future__ import annotations + import os +import httpx import pytest +from copilot import CopilotRequestContext, CopilotRequestHandler from copilot.client import CopilotClient, RuntimeConnection from copilot.session import PermissionHandler @@ -16,12 +20,56 @@ pytestmark = pytest.mark.asyncio(loop_scope="module") +class _RecordingRequestHandler(CopilotRequestHandler): + def __init__(self) -> None: + self.records: list[dict[str, str | None]] = [] + + async def send_request( + self, request: httpx.Request, ctx: CopilotRequestContext + ) -> httpx.Response: + self.records.append( + { + "url": str(request.url), + "agent_id": ctx.agent_id, + "parent_agent_id": ctx.parent_agent_id, + "interaction_type": ctx.interaction_type, + } + ) + return await super().send_request(request, ctx) + + +def _is_inference_url(url: str) -> bool: + u = url.lower() + return ( + u.endswith("/chat/completions") + or u.endswith("/responses") + or u.endswith("/v1/messages") + or u.endswith("/messages") + ) + + +def _assert_subagent_request_metadata(records: list[dict[str, str | None]]) -> None: + inference = [r for r in records if _is_inference_url(r["url"] or "")] + assert len(inference) > 0, "request handler should observe inference requests" + + subagent_request = next((r for r in inference if r["parent_agent_id"]), None) + assert subagent_request is not None, ( + "sub-agent inference request should carry a parent_agent_id" + ) + assert subagent_request["agent_id"], "sub-agent inference request should carry an agent_id" + assert subagent_request["interaction_type"], ( + "sub-agent inference request should carry an interaction_type" + ) + assert subagent_request["parent_agent_id"] != subagent_request["agent_id"] + + class TestSubagentHooks: async def test_should_invoke_pretooluse_and_posttooluse_hooks_for_sub_agent_tool_calls( self, ctx: E2ETestContext ): """Test that preToolUse/postToolUse hooks fire for sub-agent tool calls""" hook_log = [] + request_handler = _RecordingRequestHandler() async def on_pre_tool_use(input_data, invocation): hook_log.append( @@ -54,6 +102,7 @@ async def on_post_tool_use(input_data, invocation): working_directory=ctx.work_dir, env=env, github_token=github_token, + request_handler=request_handler, ) session = await client.create_session( @@ -87,6 +136,7 @@ async def on_post_tool_use(input_data, invocation): assert view_pre[0]["sessionId"] != task_pre[0]["sessionId"], ( "Sub-agent tool hooks should have a different sessionId than parent tool hooks" ) + _assert_subagent_request_metadata(request_handler.records) await session.disconnect() await client.stop() diff --git a/python/e2e/testharness/__init__.py b/python/e2e/testharness/__init__.py index 83f548eaa0..75ce76d9c5 100644 --- a/python/e2e/testharness/__init__.py +++ b/python/e2e/testharness/__init__.py @@ -1,6 +1,6 @@ """Test harness for E2E tests.""" -from .context import CLI_PATH, DEFAULT_GITHUB_TOKEN, E2ETestContext +from .context import CLI_PATH, DEFAULT_GITHUB_TOKEN, E2ETestContext, is_inprocess_transport from .helper import get_final_assistant_message, get_next_event_of_type, wait_for_condition from .proxy import CapiProxy @@ -12,4 +12,5 @@ "get_final_assistant_message", "get_next_event_of_type", "wait_for_condition", + "is_inprocess_transport", ] diff --git a/python/e2e/testharness/context.py b/python/e2e/testharness/context.py index 735c365c5f..679a36e28c 100644 --- a/python/e2e/testharness/context.py +++ b/python/e2e/testharness/context.py @@ -46,6 +46,15 @@ def get_cli_path_for_tests() -> str: DEFAULT_GITHUB_TOKEN = "fake-token-for-e2e-tests" +def is_inprocess_transport() -> bool: + """Return True when the E2E suite should run over the in-process (FFI) transport. + + Selected by the ``inprocess`` CI matrix cell via + ``COPILOT_SDK_DEFAULT_CONNECTION=inprocess``. Mirrors the Node/.NET harnesses. + """ + return (os.environ.get("COPILOT_SDK_DEFAULT_CONNECTION") or "").lower() == "inprocess" + + class E2ETestContext: """Holds shared resources for E2E tests.""" @@ -56,6 +65,10 @@ def __init__(self): self.proxy_url: str = "" self._proxy: CapiProxy | None = None self._client: CopilotClient | None = None + self._inprocess: bool = is_inprocess_transport() + self._client_inprocess: bool = False + self._restore_env: list[tuple[str, str | None]] = [] + self._restore_cwd: str | None = None async def setup(self, cli_args: list[str] | None = None): """Set up the test context with a shared client. @@ -83,16 +96,87 @@ async def setup(self, cli_args: list[str] | None = None): }, ) - # Create the shared client (like Node.js/Go do) - self._client = CopilotClient( - connection=RuntimeConnection.for_stdio( - path=self.cli_path, - args=tuple(cli_args or []), - ), - working_directory=self.work_dir, - env=self.get_env(), - github_token=DEFAULT_GITHUB_TOKEN, + # Create the shared client (like Node.js/Go do). The in-process (FFI) + # transport loads the runtime into this test host process, so it cannot + # honor a per-client working_directory or env block: the worker inherits + # this process's ambient cwd and environment. We therefore mirror the + # per-test redirects, isolated home, and credentials onto the real process + # (os.environ writes reach native getenv on CPython) and chdir into the + # work dir, then create the client without working_directory/env. This + # matches the Node/.NET in-process harnesses. + self._client_inprocess = self._inprocess and not cli_args + if self._client_inprocess: + self._apply_inprocess_environment() + self._client = CopilotClient( + connection=RuntimeConnection.for_inprocess(), + github_token=DEFAULT_GITHUB_TOKEN, + ) + else: + self._client = CopilotClient( + connection=RuntimeConnection.for_stdio( + path=self.cli_path, + args=tuple(cli_args or []), + ), + working_directory=self.work_dir, + env=self.get_env(), + github_token=DEFAULT_GITHUB_TOKEN, + ) + + def _apply_inprocess_environment(self) -> None: + """Mirror the isolated test environment onto the real process for in-process hosting. + + The in-process worker inherits this process's environment and cwd at + spawn, so the per-test redirects must live on ``os.environ`` and the + process cwd. Auth flows via GH_TOKEN/GITHUB_TOKEN (the FFI argv omits the + stdio ``--auth-token-env`` wiring) and HMAC is disabled so host-side auth + resolution matches the replay snapshots. Restored in ``teardown``. + """ + inprocess_env = dict(self.get_env()) + inprocess_env.update( + { + "GH_TOKEN": DEFAULT_GITHUB_TOKEN, + "GITHUB_TOKEN": DEFAULT_GITHUB_TOKEN, + "COPILOT_CLI_PATH": self.cli_path, + "COPILOT_HMAC_KEY": "", + "CAPI_HMAC_KEY": "", + } ) + for key, value in inprocess_env.items(): + self._restore_env.append((key, os.environ.get(key))) + os.environ[key] = value + + self._restore_cwd = os.getcwd() + os.chdir(self.work_dir) + + def add_runtime_env(self, key: str, value: str) -> None: + """Set an env var seen by the runtime, honoring the active transport. + + Child-process transports read env from the client's env block, but the + in-process worker inherits *this* process's environment, so the var must + live on ``os.environ`` (and be restored in teardown). Must be called + before the runtime starts (i.e., before the first ``create_session``). + """ + if self._client_inprocess: + self._restore_env.append((key, os.environ.get(key))) + os.environ[key] = value + else: + options = self.client._options + if options.env is None: + options.env = {} + options.env[key] = value + + def _restore_inprocess_environment(self) -> None: + """Undo the in-process environment mirror and cwd change from setup.""" + for key, previous in reversed(self._restore_env): + if previous is None: + os.environ.pop(key, None) + else: + os.environ[key] = previous + self._restore_env = [] + if self._restore_cwd is not None: + with contextlib.suppress(OSError): + os.chdir(self._restore_cwd) + self._restore_cwd = None async def teardown(self, test_failed: bool = False): """Clean up the test context. @@ -107,6 +191,9 @@ async def teardown(self, test_failed: bool = False): pass # stop() completes all cleanup before raising; safe to ignore in teardown self._client = None + if self._client_inprocess: + self._restore_inprocess_environment() + if self._proxy: await self._proxy.stop(skip_writing_cache=test_failed) self._proxy = None @@ -168,6 +255,8 @@ def get_env(self) -> dict: "XDG_CONFIG_HOME": self.home_dir, "XDG_STATE_HOME": self.home_dir, "GITHUB_TOKEN": DEFAULT_GITHUB_TOKEN, + "COPILOT_MCP_APPS": "true", + "MCP_APPS": "true", } ) return env diff --git a/python/test_canvas.py b/python/test_canvas.py index 8bcb79a230..684cef6b79 100644 --- a/python/test_canvas.py +++ b/python/test_canvas.py @@ -14,6 +14,7 @@ CanvasDeclaration, CanvasError, CanvasHandler, + CanvasProviderIdentity, ExtensionInfo, OpenCanvasInstance, ) @@ -67,6 +68,16 @@ def test_extension_info_serializes(): assert info.to_dict() == {"source": "github-app", "name": "my-ext"} +def test_canvas_provider_identity_serializes(): + provider = CanvasProviderIdentity(id="app:builtin:window-1", name="Built-in") + assert provider.to_dict() == {"id": "app:builtin:window-1", "name": "Built-in"} + + +def test_canvas_provider_identity_drops_optional_name(): + provider = CanvasProviderIdentity(id="app:builtin:window-1") + assert provider.to_dict() == {"id": "app:builtin:window-1"} + + def test_canvas_open_response_drops_none_fields(): assert CanvasProviderOpenResult().to_dict() == {} assert CanvasProviderOpenResult(url="https://x", status="ok").to_dict() == { diff --git a/python/test_cli_download.py b/python/test_cli_download.py new file mode 100644 index 0000000000..36952919df --- /dev/null +++ b/python/test_cli_download.py @@ -0,0 +1,53 @@ +"""Tests for the in-process runtime library download integrity checks.""" + +from __future__ import annotations + +import base64 +import hashlib +from unittest.mock import patch + +import pytest + +from copilot import _cli_download + + +def _integrity(data: bytes, algo: str = "sha512") -> str: + digest = hashlib.new(algo, data).digest() + return f"{algo}-{base64.b64encode(digest).decode('ascii')}" + + +class TestVerifyIntegrity: + def test_accepts_matching_checksum(self): + data = b"native-library-bytes" + _cli_download._verify_integrity(data, _integrity(data)) + + def test_rejects_mismatched_checksum(self): + with pytest.raises(RuntimeError, match="Integrity mismatch"): + _cli_download._verify_integrity(b"tampered", _integrity(b"original")) + + def test_rejects_unsupported_algorithm(self): + # Fail closed rather than silently skipping verification of native code. + with pytest.raises(RuntimeError, match="Unsupported integrity algorithm"): + _cli_download._verify_integrity(b"bytes", "md5-deadbeef") + + +class TestEnsureRuntimeLibraryFailsClosed: + def test_raises_when_integrity_unavailable(self, tmp_path): + """A missing npm integrity value must abort the download, not load unverified code.""" + cli_path = tmp_path / "copilot" + cli_path.write_bytes(b"#!/bin/sh\n") + + with ( + patch("copilot._ffi_runtime_host.resolve_library_path", return_value=None), + patch.object(_cli_download, "_should_skip_download", return_value=False), + patch.object(_cli_download, "get_npm_platform", return_value="linux-x64"), + patch.object(_cli_download, "get_runtime_lib_url", return_value="https://example/lib"), + patch.object(_cli_download, "_fetch_url_bytes", return_value=b"tarball-bytes"), + patch.object(_cli_download, "_fetch_runtime_integrity", return_value=None), + patch.object(_cli_download, "_extract_runtime_node") as extract, + ): + with pytest.raises(RuntimeError, match="refusing to load unverified native code"): + _cli_download.ensure_runtime_library(str(cli_path), version="1.2.3") + + # The library bytes must never be extracted/written when verification is impossible. + extract.assert_not_called() diff --git a/python/test_client.py b/python/test_client.py index f3f46c4d8b..f2fb059ab2 100644 --- a/python/test_client.py +++ b/python/test_client.py @@ -4,14 +4,18 @@ This file is for unit tests. Where relevant, prefer to add e2e tests in e2e/*.py instead. """ +import asyncio +import inspect from datetime import UTC, datetime from unittest.mock import AsyncMock, Mock, patch import pytest from copilot import ( + CanvasProviderIdentity, CapiSessionOptions, CopilotClient, + ExtensionInfo, ModelBillingTokenPrices, ModelBillingTokenPricesLongContext, RuntimeConnection, @@ -28,9 +32,26 @@ ModelSupports, ) from copilot.session import PermissionHandler +from copilot.session_events import ( + McpOauthRequestReason, + McpOauthRequiredData, + McpOauthRequiredStaticClientConfig, + McpOauthWWWAuthenticateParams, + SessionEvent, + SessionEventType, +) +from copilot.tools import Tool from e2e.testharness import CLI_PATH +def test_inprocess_connection_has_no_child_process_options(): + connection = RuntimeConnection.for_inprocess() + + assert list(inspect.signature(RuntimeConnection.for_inprocess).parameters) == [] + assert not hasattr(connection, "path") + assert not hasattr(connection, "args") + + class TestClientShutdown: @pytest.mark.asyncio async def test_stop_requests_runtime_shutdown_for_owned_process(self): @@ -139,6 +160,307 @@ async def test_resume_session_allows_none_permission_handler(self): class TestCreateSessionConfig: + @pytest.mark.asyncio + async def test_mcp_auth_handler_registers_interest_in_create_session(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured: list[tuple[str, dict]] = [] + + async def mock_request(method, params, **kwargs): + captured.append((method, params)) + if method == "session.eventLog.registerInterest": + return {"id": "interest-1"} + if method == "session.create": + result = {"sessionId": params["sessionId"], "workspacePath": None} + callback = kwargs.get("on_response_inline") + if callback is not None: + callback(result) + return result + return {} + + client._client.request = mock_request + await client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=lambda request: {"kind": "cancelled"}, + ) + + create_method, create_payload = captured[0] + interest_method, interest_payload = captured[1] + assert create_method == "session.create" + assert interest_method == "session.eventLog.registerInterest" + assert interest_payload["eventType"] == "mcp.oauth_required" + assert interest_payload["sessionId"] == create_payload["sessionId"] + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_mcp_auth_interest_is_not_registered_without_handler(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured: list[tuple[str, dict]] = [] + + async def mock_request(method, params, **kwargs): + captured.append((method, params)) + if method == "session.create": + result = {"sessionId": params["sessionId"], "workspacePath": None} + callback = kwargs.get("on_response_inline") + if callback is not None: + callback(result) + return result + if method == "session.resume": + return {"sessionId": params["sessionId"], "workspacePath": None} + return {} + + client._client.request = mock_request + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_event=lambda event: None, + ) + await client.resume_session( + "session-without-auth", + on_permission_request=PermissionHandler.approve_all, + on_event=lambda event: None, + ) + + assert session.session_id + assert not any( + method == "session.eventLog.registerInterest" + and params["eventType"] == "mcp.oauth_required" + for method, params in captured + ) + assert any( + method == "session.create" and params["requestPermission"] is True + for method, params in captured + ) + assert any( + method == "session.resume" and params["requestPermission"] is True + for method, params in captured + ) + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_mcp_auth_handler_registers_interest_after_resume(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured: list[tuple[str, dict]] = [] + + async def mock_request(method, params, **kwargs): + captured.append((method, params)) + if method == "session.eventLog.registerInterest": + return {"id": "interest-1"} + if method == "session.resume": + return {"sessionId": params["sessionId"], "workspacePath": None} + return {} + + client._client.request = mock_request + await client.resume_session( + "session-with-auth", + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=lambda request: {"kind": "cancelled"}, + ) + + resume_method, resume_payload = captured[0] + interest_method, interest_payload = captured[1] + assert resume_method == "session.resume" + assert resume_payload["requestPermission"] is True + assert interest_method == "session.eventLog.registerInterest" + assert interest_payload == { + "sessionId": "session-with-auth", + "eventType": "mcp.oauth_required", + } + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_mcp_auth_handler_registers_interest_after_cloud_create_only_with_handler(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured: list[tuple[str, dict]] = [] + create_count = 0 + + async def mock_request(method, params, **kwargs): + nonlocal create_count + captured.append((method, params)) + if method == "session.eventLog.registerInterest": + return {"id": "interest-1"} + if method == "session.create": + create_count += 1 + result = { + "sessionId": f"server-assigned-session-{create_count}", + "workspacePath": None, + } + callback = kwargs.get("on_response_inline") + if callback is not None: + callback(result) + return result + return {} + + cloud = CloudSessionOptions( + repository=CloudSessionRepository( + owner="github", + name="copilot-sdk", + branch="main", + ) + ) + + client._client.request = mock_request + await client.create_session( + on_permission_request=PermissionHandler.approve_all, + cloud=cloud, + ) + + assert not any( + method == "session.eventLog.registerInterest" + and params["eventType"] == "mcp.oauth_required" + for method, params in captured + ) + + captured.clear() + await client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=lambda request: {"kind": "cancelled"}, + cloud=cloud, + ) + + create_method, _create_payload = captured[0] + interest_method, interest_payload = captured[1] + assert create_method == "session.create" + assert interest_method == "session.eventLog.registerInterest" + assert interest_payload == { + "sessionId": "server-assigned-session-2", + "eventType": "mcp.oauth_required", + } + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_mcp_auth_required_event_sends_host_token(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured: list[tuple[str, dict]] = [] + + async def mock_request(method, params, **kwargs): + if method == "session.mcp.oauth.handlePendingRequest": + captured.append((method, params)) + return {"success": True} + if method == "session.create": + result = {"sessionId": params["sessionId"], "workspacePath": None} + callback = kwargs.get("on_response_inline") + if callback is not None: + callback(result) + return result + if method == "session.eventLog.registerInterest": + return {"id": "interest-1"} + return {} + + client._client.request = mock_request + observed_request = None + + def handle_mcp_auth_request(request, invocation): + nonlocal observed_request + observed_request = request + assert invocation == {"sessionId": session.session_id} + return { + "accessToken": "host-token", + "tokenType": "Bearer", + } + + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + on_mcp_auth_request=handle_mcp_auth_request, + ) + + session._dispatch_event( + SessionEvent( + data=McpOauthRequiredData( + request_id="oauth-request", + server_name="oauth-server", + server_url="https://example.com/mcp", + reason=McpOauthRequestReason.INITIAL, + www_authenticate_params=McpOauthWWWAuthenticateParams( + resource_metadata_url="https://example.com/.well-known/oauth-protected-resource" + ), + resource_metadata='{"resource":"https://example.com/mcp"}', + static_client_config=McpOauthRequiredStaticClientConfig( + client_id="static-client", + client_secret="static-secret", + grant_type="client_credentials", + public_client=False, + ), + ), + id="evt-1", + timestamp="2026-01-01T00:00:00Z", + type=SessionEventType.MCP_OAUTH_REQUIRED, + ephemeral=True, + parent_id=None, + ) + ) + + for _ in range(200): + if captured: + break + await asyncio.sleep(0.005) + + assert observed_request is not None + assert observed_request["resourceMetadata"] == '{"resource":"https://example.com/mcp"}' + assert observed_request["wwwAuthenticateParams"]["resourceMetadataUrl"] == ( + "https://example.com/.well-known/oauth-protected-resource" + ) + assert observed_request["staticClientConfig"] == { + "clientId": "static-client", + "clientSecret": "static-secret", + "grantType": "client_credentials", + "publicClient": False, + } + assert captured == [ + ( + "session.mcp.oauth.handlePendingRequest", + { + "sessionId": session.session_id, + "requestId": "oauth-request", + "result": { + "kind": "token", + "accessToken": "host-token", + "tokenType": "Bearer", + }, + }, + ) + ] + + observed_request = None + session._dispatch_event( + SessionEvent( + data=McpOauthRequiredData( + request_id="oauth-request-without-metadata", + server_name="oauth-server", + server_url="https://example.com/mcp", + reason=McpOauthRequestReason.INITIAL, + ), + id="evt-2", + timestamp="2026-01-01T00:00:00Z", + type=SessionEventType.MCP_OAUTH_REQUIRED, + ephemeral=True, + parent_id=None, + ) + ) + + for _ in range(200): + if observed_request is not None: + break + await asyncio.sleep(0.005) + + assert observed_request is not None + assert "resourceMetadata" not in observed_request + assert "wwwAuthenticateParams" not in observed_request + finally: + await client.force_stop() + @pytest.mark.asyncio async def test_create_session_forwards_cloud_options(self): client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) @@ -246,6 +568,130 @@ async def mock_request(method, params, **kwargs): finally: await client.force_stop() + @pytest.mark.asyncio + async def test_create_and_resume_session_forward_tool_metadata(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured = {} + + async def mock_request(method, params, **kwargs): + captured[method] = params + if method in ("session.create", "session.resume"): + result = {"sessionId": params.get("sessionId") or "session-1"} + callback = kwargs.get("on_response_inline") + if callback is not None: + callback(result) + return result + return {} + + client._client.request = mock_request + metadata = {"github.com/copilot:safeForTelemetry": {"name": True, "inputsNames": False}} + tool = Tool(name="my_tool", description="a tool", metadata=metadata) + plain_tool = Tool(name="plain_tool", description="a tool") + + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + tools=[tool, plain_tool], + ) + await client.resume_session( + session.session_id, + on_permission_request=PermissionHandler.approve_all, + tools=[tool], + ) + + create_tools = captured["session.create"]["tools"] + assert create_tools[0]["metadata"] == metadata + # Omitted when unset. + assert "metadata" not in create_tools[1] + assert captured["session.resume"]["tools"][0]["metadata"] == metadata + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_create_and_resume_session_forward_canvas_provider(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured = {} + + async def mock_request(method, params, **kwargs): + captured[method] = params + if method in ("session.create", "session.resume"): + result = {"sessionId": params.get("sessionId") or "session-1"} + callback = kwargs.get("on_response_inline") + if callback is not None: + callback(result) + return result + return {} + + client._client.request = mock_request + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + extension_info=ExtensionInfo(source="github-app", name="counter"), + canvas_provider=CanvasProviderIdentity(id="app:builtin:window-1", name="Built-in"), + ) + await client.resume_session( + session.session_id, + on_permission_request=PermissionHandler.approve_all, + canvas_provider=CanvasProviderIdentity(id="app:builtin:window-1"), + ) + + assert captured["session.create"]["canvasProvider"] == { + "id": "app:builtin:window-1", + "name": "Built-in", + } + assert captured["session.create"]["extensionInfo"] == { + "source": "github-app", + "name": "counter", + } + assert captured["session.resume"]["canvasProvider"] == { + "id": "app:builtin:window-1", + } + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_create_and_resume_session_forward_new_session_options(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + try: + captured = {} + + async def mock_request(method, params, **kwargs): + captured[method] = params + if method in ("session.create", "session.resume"): + result = {"sessionId": params.get("sessionId") or "session-1"} + callback = kwargs.get("on_response_inline") + if callback is not None: + callback(result) + return result + return {} + + client._client.request = mock_request + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all, + enable_citations=True, + excluded_builtin_agents=["explore"], + session_limits={"max_ai_credits": 30}, + ) + await client.resume_session( + session.session_id, + on_permission_request=PermissionHandler.approve_all, + enable_citations=False, + excluded_builtin_agents=["task"], + session_limits={"max_ai_credits": 15}, + ) + + assert captured["session.create"]["enableCitations"] is True + assert captured["session.create"]["excludedBuiltinAgents"] == ["explore"] + assert captured["session.create"]["sessionLimits"] == {"maxAiCredits": 30} + assert captured["session.resume"]["enableCitations"] is False + assert captured["session.resume"]["excludedBuiltinAgents"] == ["task"] + assert captured["session.resume"]["sessionLimits"] == {"maxAiCredits": 15} + finally: + await client.force_stop() + @pytest.mark.asyncio async def test_create_and_resume_session_forward_capi_options(self): client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) @@ -1840,6 +2286,32 @@ def test_model_field_is_omitted_when_absent(self): wire = client._convert_custom_agent_to_wire_format(agent) assert "model" not in wire + def test_reasoning_effort_is_forwarded_in_camel_case(self): + from copilot.client import CopilotClient + from copilot.session import CustomAgentConfig + + client = CopilotClient.__new__(CopilotClient) + agent: CustomAgentConfig = { + "name": "reasoning-agent", + "prompt": "Think carefully.", + "reasoning_effort": "high", + } + wire = client._convert_custom_agent_to_wire_format(agent) + assert wire["reasoningEffort"] == "high" + assert "reasoning_effort" not in wire + + def test_reasoning_effort_is_omitted_when_absent(self): + from copilot.client import CopilotClient + from copilot.session import CustomAgentConfig + + client = CopilotClient.__new__(CopilotClient) + agent: CustomAgentConfig = { + "name": "default-agent", + "prompt": "Use runtime defaults.", + } + wire = client._convert_custom_agent_to_wire_format(agent) + assert "reasoningEffort" not in wire + class TestPostToolUseFailureHookDispatch: """Unit tests for the postToolUseFailure handler dispatch.""" @@ -1921,3 +2393,282 @@ def on_failure(input_data, invocation): }, ) assert result == {"additionalContext": "sync-ok"} + + +class TestGitHubTelemetry: + """Unit tests for the experimental gitHubTelemetry.event consumer surface.""" + + @pytest.mark.asyncio + async def test_create_session_enables_forwarding_when_handler_registered(self): + client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=CLI_PATH), + on_github_telemetry=lambda _notification: None, + ) + await client.start() + + try: + captured = {} + original_request = client._client.request + + async def mock_request(method, params, **kwargs): + captured[method] = params + return await original_request(method, params, **kwargs) + + client._client.request = mock_request + await client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) + assert captured["session.create"]["enableGitHubTelemetryForwarding"] is True + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_create_session_omits_forwarding_without_handler(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + + try: + captured = {} + original_request = client._client.request + + async def mock_request(method, params, **kwargs): + captured[method] = params + return await original_request(method, params, **kwargs) + + client._client.request = mock_request + await client.create_session( + on_permission_request=PermissionHandler.approve_all, + ) + assert "enableGitHubTelemetryForwarding" not in captured["session.create"] + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_resume_session_enables_forwarding_when_handler_registered(self): + client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=CLI_PATH), + on_github_telemetry=lambda _notification: None, + ) + await client.start() + + try: + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all + ) + + captured = {} + original_request = client._client.request + + async def mock_request(method, params, **kwargs): + captured[method] = params + if method == "session.resume": + return {"sessionId": session.session_id} + return await original_request(method, params, **kwargs) + + client._client.request = mock_request + await client.resume_session( + session.session_id, + on_permission_request=PermissionHandler.approve_all, + ) + assert captured["session.resume"]["enableGitHubTelemetryForwarding"] is True + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_resume_session_omits_forwarding_without_handler(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + + try: + session = await client.create_session( + on_permission_request=PermissionHandler.approve_all + ) + + captured = {} + original_request = client._client.request + + async def mock_request(method, params, **kwargs): + captured[method] = params + if method == "session.resume": + return {"sessionId": session.session_id} + return await original_request(method, params, **kwargs) + + client._client.request = mock_request + await client.resume_session( + session.session_id, + on_permission_request=PermissionHandler.approve_all, + ) + assert "enableGitHubTelemetryForwarding" not in captured["session.resume"] + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_connect_enables_forwarding_when_handler_registered(self): + client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=CLI_PATH), + on_github_telemetry=lambda _notification: None, + ) + captured = {} + + class _FakeClient: + async def request(self, method, params, **kwargs): + captured[method] = params + return {"ok": True, "protocolVersion": 3, "version": "test"} + + client._client = _FakeClient() + await client._verify_protocol_version() + assert captured["connect"]["enableGitHubTelemetryForwarding"] is True + + @pytest.mark.asyncio + async def test_connect_omits_forwarding_without_handler(self): + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + captured = {} + + class _FakeClient: + async def request(self, method, params, **kwargs): + captured[method] = params + return {"ok": True, "protocolVersion": 3, "version": "test"} + + client._client = _FakeClient() + await client._verify_protocol_version() + assert "enableGitHubTelemetryForwarding" not in captured["connect"] + + @pytest.mark.asyncio + async def test_event_routes_to_handler(self): + from copilot.generated.rpc import GitHubTelemetryNotification + + received: list = [] + + def on_telemetry(notification): + received.append(notification) + + client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=CLI_PATH), + on_github_telemetry=on_telemetry, + ) + await client.start() + + try: + # gitHubTelemetry.event is a JSON-RPC *notification*: the generated + # client-global dispatcher wires it into the notification-handler + # table, never the request-handler table. Regressing to request-style + # dispatch would drop the runtime's id-less telemetry frames. + assert "gitHubTelemetry.event" in client._client.notification_method_handlers + assert "gitHubTelemetry.event" not in client._client.request_handlers + + # Drive a real id-less notification frame through the dispatcher to + # exercise the full from_dict decode + adapter + user-callback path. + client._client._handle_message( + { + "jsonrpc": "2.0", + "method": "gitHubTelemetry.event", + "params": { + "sessionId": "sess-telemetry", + "restricted": True, + "event": { + "kind": "tool_call_executed", + "metrics": {"duration_ms": 12.5}, + "properties": {"tool": "shell"}, + "session_id": "sess-telemetry", + }, + }, + } + ) + + # Notifications dispatch onto the event loop; yield until delivered. + for _ in range(100): + if received: + break + await asyncio.sleep(0.01) + + assert len(received) == 1 + notification = received[0] + assert isinstance(notification, GitHubTelemetryNotification) + assert notification.session_id == "sess-telemetry" + assert notification.restricted is True + assert notification.event.kind == "tool_call_executed" + assert notification.event.metrics["duration_ms"] == 12.5 + assert notification.event.properties["tool"] == "shell" + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_event_routes_to_async_handler(self): + from copilot.generated.rpc import GitHubTelemetryNotification + + received: list = [] + delivered = asyncio.Event() + + async def on_telemetry(notification): + await asyncio.sleep(0) + received.append(notification) + delivered.set() + + client = CopilotClient( + connection=RuntimeConnection.for_stdio(path=CLI_PATH), + on_github_telemetry=on_telemetry, + ) + await client.start() + + try: + client._client._handle_message( + { + "jsonrpc": "2.0", + "method": "gitHubTelemetry.event", + "params": { + "sessionId": "sess-async-telemetry", + "restricted": False, + "event": { + "kind": "tool_call_executed", + "metrics": {"duration_ms": 3.5}, + "properties": {"tool": "python"}, + "session_id": "sess-async-telemetry", + }, + }, + } + ) + + await asyncio.wait_for(delivered.wait(), timeout=1) + + assert len(received) == 1 + notification = received[0] + assert isinstance(notification, GitHubTelemetryNotification) + assert notification.session_id == "sess-async-telemetry" + assert notification.restricted is False + assert notification.event.kind == "tool_call_executed" + assert notification.event.metrics["duration_ms"] == 3.5 + assert notification.event.properties["tool"] == "python" + finally: + await client.force_stop() + + @pytest.mark.asyncio + async def test_event_not_forwarded_without_option(self): + # Client-global handlers are always registered (so that hooks.invoke works), + # but without the on_github_telemetry option the telemetry adapter is inert: + # incoming events must not be forwarded to any callback. + client = CopilotClient(connection=RuntimeConnection.for_stdio(path=CLI_PATH)) + await client.start() + + try: + assert client._on_github_telemetry is None + + # Dispatching a telemetry event is a harmless no-op when not opted in. + client._client._handle_message( + { + "jsonrpc": "2.0", + "method": "gitHubTelemetry.event", + "params": { + "sessionId": "sess-no-telemetry", + "restricted": False, + "event": { + "kind": "tool_call_executed", + "metrics": {"duration_ms": 1.0}, + "properties": {"tool": "shell"}, + "session_id": "sess-no-telemetry", + }, + }, + } + ) + await asyncio.sleep(0) + finally: + await client.force_stop() diff --git a/python/test_event_forward_compatibility.py b/python/test_event_forward_compatibility.py index 13fa4f09e5..1ffbd59c54 100644 --- a/python/test_event_forward_compatibility.py +++ b/python/test_event_forward_compatibility.py @@ -49,6 +49,20 @@ def test_unknown_event_type_maps_to_unknown(self): event = session_event_from_dict(unknown_event) assert event.type == SessionEventType.UNKNOWN, f"Expected UNKNOWN, got {event.type}" + def test_internal_event_type_maps_to_unknown(self): + """Internal events should use the forward-compatible raw event path.""" + internal_event = { + "id": str(uuid4()), + "timestamp": datetime.now().isoformat(), + "parentId": None, + "type": "session.memory_changed", + "data": {}, + } + + event = session_event_from_dict(internal_event) + assert event.type == SessionEventType.UNKNOWN + assert session_event_to_dict(event)["type"] == "session.memory_changed" + def test_known_event_preserves_top_level_agent_id(self): """Known events should preserve the top-level sub-agent envelope ID.""" known_event = { @@ -138,6 +152,22 @@ def test_data_shim_preserves_raw_mapping_values(self): constructed = Data(arguments={"tool_call_id": "call-1"}) assert constructed.to_dict() == {"arguments": {"tool_call_id": "call-1"}} + def test_data_shim_preserves_abbreviation_json_keys_on_round_trip(self): + """Data.from_dict(x).to_dict() should preserve JSON keys with abbreviations. + + Regression test for github/copilot-sdk#1138: keys like userURL, sessionID, + and OAuthToken were rewritten on round-trip because _compat_to_json_key could + not reconstruct the original camelCase abbreviation casing. + """ + for key in ["userURL", "sessionID", "XMLPayload", "serverIP", "OAuthToken"]: + incoming = {key: 42} + assert Data.from_dict(incoming).to_dict() == incoming + + def test_data_shim_preserves_colliding_json_keys_on_round_trip(self): + """Data.from_dict(x).to_dict() should preserve keys with the same Python name.""" + colliding_keys = {"userURL": 42, "userUrl": 43} + assert Data.from_dict(colliding_keys).to_dict() == colliding_keys + def test_missing_optional_fields_remain_none_after_parsing(self): """Generated event models should leave missing optional fields as None. diff --git a/python/test_tools.py b/python/test_tools.py index d583b59c01..90498c2b8e 100644 --- a/python/test_tools.py +++ b/python/test_tools.py @@ -3,9 +3,10 @@ import json import pytest -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field, field_validator from copilot import define_tool +from copilot.generated.rpc import ExternalToolTextResultForLlm from copilot.tools import ( ToolInvocation, ToolResult, @@ -197,6 +198,91 @@ def failing_tool(params: Params, invocation: ToolInvocation) -> str: # But the actual error is stored internally assert result.error == "secret error message" + async def test_validation_error_is_surfaced_to_llm(self): + class Params(BaseModel): + username: str + + @field_validator("username") + @classmethod + def check_username(cls, v: str) -> str: + if v == "admin": + raise ValueError("username 'admin' is reserved") + return v + + @define_tool("validate", description="A validating tool") + def validating_tool(params: Params) -> str: + return "ok" + + invocation = ToolInvocation( + session_id="s1", + tool_call_id="c1", + tool_name="validate", + arguments={"username": "admin"}, + ) + + result = await validating_tool.handler(invocation) + + assert result.result_type == "failure" + assert result.text_result_for_llm.startswith("Invalid tool arguments:") + assert "username 'admin' is reserved" in result.text_result_for_llm + # Full detail is retained in the debug field. + assert result.error is not None + + async def test_validation_error_extra_forbid_includes_field_name(self): + class Params(BaseModel): + model_config = ConfigDict(extra="forbid") + + request: str + + @define_tool("strict", description="A strict tool") + def strict_tool(params: Params) -> str: + return "ok" + + invocation = ToolInvocation( + session_id="s1", + tool_call_id="c1", + tool_name="strict", + arguments={"request": "ok", "extra_field": "unexpected"}, + ) + + result = await strict_tool.handler(invocation) + + assert result.result_type == "failure" + assert result.text_result_for_llm.startswith("Invalid tool arguments:") + # The offending key name is carried in `loc` even though the generic + # message is "Extra inputs are not permitted". + assert "extra_field" in result.text_result_for_llm + assert result.error is not None + + async def test_validation_error_from_handler_body_is_redacted(self): + class Params(BaseModel): + pass + + class Internal(BaseModel): + count: int + + @define_tool("body", description="A tool that validates internally") + def body_tool(params: Params) -> str: + Internal.model_validate({"count": "secret-not-an-int"}) + return "ok" + + invocation = ToolInvocation( + session_id="s1", + tool_call_id="c1", + tool_name="body", + arguments={}, + ) + + result = await body_tool.handler(invocation) + + assert result.result_type == "failure" + # A ValidationError from the handler body must not be surfaced as an + # argument-validation error; it stays redacted like any other exception. + assert not result.text_result_for_llm.startswith("Invalid tool arguments:") + assert "secret-not-an-int" not in result.text_result_for_llm + assert "error" in result.text_result_for_llm.lower() + assert result.error is not None + async def test_function_style_api(self): class Params(BaseModel): value: str @@ -427,3 +513,40 @@ def test_call_tool_result_dict_is_json_serialized_by_normalize(self): result = _normalize_result({"content": [{"type": "text", "text": "hello"}]}) parsed = json.loads(result.text_result_for_llm) assert parsed == {"content": [{"type": "text", "text": "hello"}]} + + +class TestToolReferences: + def test_tool_references_pass_through_normalize(self): + input_result = ToolResult( + text_result_for_llm="found 2 tools", + result_type="success", + tool_references=["get_weather", "check_status"], + ) + result = _normalize_result(input_result) + assert result.tool_references == ["get_weather", "check_status"] + + def test_tool_references_serialized_to_wire(self): + wire = ExternalToolTextResultForLlm( + text_result_for_llm="found 2 tools", + result_type="success", + tool_references=["get_weather", "check_status"], + ) + data = wire.to_dict() + assert data["toolReferences"] == ["get_weather", "check_status"] + + def test_tool_references_omitted_when_none(self): + wire = ExternalToolTextResultForLlm( + text_result_for_llm="ok", + result_type="success", + ) + assert "toolReferences" not in wire.to_dict() + + def test_tool_references_round_trip_from_wire(self): + wire = ExternalToolTextResultForLlm.from_dict( + { + "textResultForLlm": "found tools", + "resultType": "success", + "toolReferences": ["alpha", "beta"], + } + ) + assert wire.tool_references == ["alpha", "beta"] diff --git a/rust/.gitignore b/rust/.gitignore index c4095ffc0f..c149fa3946 100644 --- a/rust/.gitignore +++ b/rust/.gitignore @@ -1,3 +1,4 @@ /target Cargo.lock.bak cli-version.txt +cli-version-in-process.txt diff --git a/rust/Cargo.lock b/rust/Cargo.lock index fb7b66e198..8de6797989 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -433,6 +433,9 @@ dependencies = [ "futures-util", "getrandom 0.2.17", "http", + "indexmap", + "libloading", + "native-tls", "parking_lot", "regex", "reqwest", @@ -773,6 +776,16 @@ version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libredox" version = "0.1.16" @@ -1217,9 +1230,7 @@ version = "0.23.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" dependencies = [ - "log", "once_cell", - "ring", "rustls-pki-types", "rustls-webpki", "subtle", @@ -1836,11 +1847,9 @@ checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" dependencies = [ "base64", "log", + "native-tls", "once_cell", - "rustls", - "rustls-pki-types", "url", - "webpki-roots 0.26.11", ] [[package]] @@ -2033,24 +2042,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webpki-roots" -version = "0.26.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" -dependencies = [ - "webpki-roots 1.0.7", -] - -[[package]] -name = "webpki-roots" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "windows-link" version = "0.2.1" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 66ef69ad21..0f18a9b159 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -13,6 +13,7 @@ readme = "README.md" license = "MIT" include = [ "src/**/*", + "build/**/*", "examples/**/*", "tests/**/*", "build.rs", @@ -20,6 +21,7 @@ include = [ "README.md", "LICENSE", "cli-version.txt", + "cli-version-in-process.txt", ] [lib] @@ -28,6 +30,7 @@ name = "github_copilot_sdk" [features] default = ["bundled-cli"] bundled-cli = ["dep:tar", "dep:flate2", "dep:zip"] +bundled-in-process = ["bundled-cli", "dep:libloading"] derive = ["dep:schemars"] test-support = [] @@ -40,6 +43,7 @@ rustdoc-args = ["--cfg", "docsrs"] [dependencies] async-trait = "0.1" +indexmap = { version = "2", features = ["serde"] } schemars = { version = "1", optional = true } serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -48,10 +52,13 @@ tokio-stream = { version = "0.1", features = ["sync"] } tokio-util = { version = "0.7", default-features = false } tracing = "0.1" dirs = "5" +libloading = { version = "0.8", optional = true } parking_lot = "0.12" regex = "1" getrandom = "0.2" uuid = { version = "1", default-features = false, features = ["v4"] } +flate2 = { version = "1", optional = true } +tar = { version = "0.4", optional = true } # LLM inference callback transport: idiomatic HTTP/WebSocket forwarding for the # `CopilotRequestHandler`, plus base64/byte/stream plumbing for the chunk protocol. base64 = "0.22" @@ -64,10 +71,6 @@ tokio-tungstenite = { version = "0.24", default-features = false, features = ["c [target.'cfg(windows)'.dependencies] zip = { version = "2", default-features = false, features = ["deflate"], optional = true } -[target.'cfg(not(windows))'.dependencies] -flate2 = { version = "1", optional = true } -tar = { version = "0.4", optional = true } - [dev-dependencies] rusqlite = { version = "0.35", features = ["bundled"] } schemars = "1" @@ -88,9 +91,12 @@ name = "protocol_version_test" required-features = ["test-support"] [build-dependencies] +base64 = "0.22" dirs = "5" flate2 = "1" +serde_json = "1" sha2 = "0.10" tar = "0.4" -ureq = { version = "2", default-features = false, features = ["tls"] } +ureq = { version = "2", default-features = false, features = ["native-tls"] } +native-tls = "0.2" zip = { version = "2", default-features = false, features = ["deflate"] } diff --git a/rust/README.md b/rust/README.md index 6d92224088..254a2b2167 100644 --- a/rust/README.md +++ b/rust/README.md @@ -72,15 +72,15 @@ client.stop().await?; **`ClientOptions`:** -| Field | Type | Description | -| ------------- | --------------------------- | --------------------------------------------------------------- | -| `program` | `CliProgram` | `Resolve` (default: auto-detect) or `Path(PathBuf)` (explicit) | -| `prefix_args` | `Vec` | Args before `--server` (e.g. script path for node) | -| `cwd` | `PathBuf` | Working directory for CLI process | -| `env` | `Vec<(OsString, OsString)>` | Environment variables for CLI process | -| `env_remove` | `Vec` | Environment variables to remove | -| `extra_args` | `Vec` | Extra CLI flags | -| `transport` | `Transport` | `Stdio` (default), `Tcp { port }`, or `External { host, port }` | +| Field | Type | Description | +| ------------------- | --------------------------- | ----------------------------------------------------------------- | +| `program` | `CliProgram` | `Resolve` (default: auto-detect) or `Path(PathBuf)` (explicit) | +| `prefix_args` | `Vec` | Args before `--server` (e.g. script path for node) | +| `working_directory` | `PathBuf` | Working directory for CLI process (empty = host process's cwd) | +| `env` | `Vec<(OsString, OsString)>` | Environment variables for CLI process | +| `env_remove` | `Vec` | Environment variables to remove | +| `extra_args` | `Vec` | Extra CLI flags | +| `transport` | `Transport` | `Default`, `Stdio`, `InProcess`, `Tcp`, or `External` | With the default `CliProgram::Resolve`, `Client::start()` resolves the CLI in this order: an explicit `CliProgram::Path(path)`, the `COPILOT_CLI_PATH` env var, then the bundled CLI that was embedded at build time. There is no PATH scanning — if you've opted out of bundling (`default-features = false`) you must supply either `CliProgram::Path` or `COPILOT_CLI_PATH`. @@ -749,7 +749,7 @@ none of them are scheduled for removal. caller-supplied `AsyncRead` / `AsyncWrite`. Useful for testing, in-process embedding, or custom transports. Other SDKs are spawn-only or fixed-stdio. -- **`enum Transport { Stdio, Tcp, External }`** — explicit, exhaustive +- **`enum Transport { Default, Stdio, InProcess, Tcp, External }`** — explicit transport selector on `ClientOptions::transport`. Node/Python/Go rely on conditional config field combinations instead. - **Split `prefix_args` / `extra_args`** on `ClientOptions` — separate @@ -776,7 +776,18 @@ none of them are scheduled for removal. ## Embedded CLI -The SDK provisions the Copilot CLI binary at build time. By default the `bundled-cli` feature embeds the verified binary directly in your compiled crate, so end-user binaries are self-contained — no env var setup, no separate install, just `cargo build`. +The SDK provisions its runtime at build time. By default the `bundled-cli` +feature embeds the verified child-process runtime in your compiled crate. +Enable `bundled-in-process` to additionally embed the native runtime library +and use `Transport::InProcess`: + +```toml +github-copilot-sdk = { version = "0.1", features = ["bundled-in-process"] } +``` + +`CliProgram::Path` and raw `ClientOptions::extra_args` apply only to +child-process transports. Set `COPILOT_CLI_PATH` only when using an externally +provisioned compatible runtime package with in-process transport. For builds that prefer a smaller artifact, disable the `bundled-cli` feature: @@ -795,7 +806,7 @@ github-copilot-sdk = { version = "0.1", default-features = false } > together. > > **Convenience on the build machine only.** As a special case, -> `build.rs` downloads and SHA-verifies the compatible CLI version and +> `build.rs` downloads and integrity-verifies the compatible CLI version and > drops it into the build machine's per-user cache; the runtime > resolver on that same machine will pick it up automatically. This > makes local development and CI ergonomic, but it does **not** carry @@ -812,8 +823,11 @@ github-copilot-sdk = { version = "0.1", default-features = false } The resolved version is baked into the crate via `cargo:rustc-env=COPILOT_SDK_CLI_VERSION` regardless of mode. The runtime resolver consumes it to recompute the on-disk path by convention, so no absolute paths leak into the rlib. -2. **Build time:** `build.rs` downloads the platform-appropriate archive from the [`github/copilot-cli` GitHub Releases](https://github.com/github/copilot-cli/releases) (`copilot-{platform}.tar.gz` on macOS/Linux, `.zip` on Windows), live-fetches the matching `SHA256SUMS.txt`, and verifies the archive hash. Then: - - **`bundled-cli` on (default, release):** embeds the raw archive bytes via `include_bytes!()`. Runtime extracts on first `Client::start()`. +2. **Build time:** `build.rs` downloads the platform-specific npm package and + verifies its `sha512` integrity against the lockfile or publish snapshot. + Then: + - **`bundled-cli` on (default):** creates and embeds a minimal archive containing only the CLI executable. + - **`bundled-in-process` on:** the minimal archive additionally contains the platform-native runtime library (`.dll`, `.so`, or `.dylib`); no other npm package files are embedded. - **`bundled-cli` off:** extracts the binary directly into the platform cache (staging file + atomic rename), idempotent across rebuilds. If the extracted binary is already present at the expected path, the download is skipped entirely — the extracted binary *is* the cache. 3. **Runtime:** in both modes the binary lives at: @@ -899,10 +913,11 @@ Supported: `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64` ## Features -| Feature | Default | Description | -| -------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `bundled-cli` | ✓ | Build-time CLI embedding. Pulls in `tar`+`flate2` (Linux/macOS) or `zip` (Windows). Disable via `default-features = false` to opt out (e.g. when shipping a smaller binary or when always supplying the CLI via `CliProgram::Path` / `COPILOT_CLI_PATH`). | -| `derive` | — | `schema_for::()` for generating JSON Schema from Rust types (adds `schemars`). Enable when defining [tool parameters](#tool-registration). | +| Feature | Default | Description | +| ------- | ------- | ----------- | +| `bundled-cli` | ✓ | Embeds only the CLI executable. Disable via `default-features = false` when supplying the CLI via `CliProgram::Path` or `COPILOT_CLI_PATH`. | +| `bundled-in-process` | — | Enables `Transport::InProcess`, implies `bundled-cli`, and additionally embeds only the platform-native runtime library. | +| `derive` | — | `schema_for::()` for generating JSON Schema from Rust types (adds `schemars`). | ```toml # These examples use registry syntax for illustration; until the crate is @@ -911,7 +926,10 @@ Supported: `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64` # Default — bundles the Copilot CLI in your binary. github-copilot-sdk = "0.1" -# Opt out of bundling — resolve CLI from COPILOT_CLI_PATH or system PATH instead. +# Enable the in-process transport and bundle its native runtime library. +github-copilot-sdk = { version = "0.1", features = ["bundled-in-process"] } + +# Opt out of bundling — supply the CLI explicitly at runtime. github-copilot-sdk = { version = "0.1", default-features = false } # Derive JSON Schema for tool parameters (adds to default bundled-cli). diff --git a/rust/build.rs b/rust/build.rs index 66d1de7bc8..d04cf2870b 100644 --- a/rust/build.rs +++ b/rust/build.rs @@ -1,709 +1,11 @@ -use std::io::{Read, Write}; -use std::path::{Path, PathBuf}; -use std::time::Duration; +#[cfg(feature = "bundled-in-process")] +#[path = "build/in_process.rs"] +mod implementation; -use sha2::Digest; +#[cfg(not(feature = "bundled-in-process"))] +#[path = "build/out_of_process.rs"] +mod implementation; fn main() { - println!("cargo:rerun-if-env-changed=DOCS_RS"); - println!("cargo:rerun-if-env-changed=COPILOT_SKIP_CLI_DOWNLOAD"); - println!("cargo:rerun-if-env-changed=COPILOT_CLI_EXTRACT_DIR"); - println!("cargo:rerun-if-env-changed=BUNDLED_CLI_CACHE_DIR"); - println!("cargo::rustc-check-cfg=cfg(has_bundled_cli)"); - println!("cargo::rustc-check-cfg=cfg(has_extracted_cli)"); - println!("cargo:rerun-if-changed=cli-version.txt"); - - // Only declare the lockfile rerun when the lockfile actually exists. - // Cargo treats `rerun-if-changed` for a missing path as "always rerun" - // — so unconditionally declaring this on consumers without a sibling - // `nodejs/` (vendored slots, published crates) would force build.rs - // to re-run on every `cargo build` even when nothing has changed. - // The lockfile path is only the source-of-truth in this repo's - // contributor builds; everywhere else `cli-version.txt` is canonical. - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"); - let lockfile = Path::new(&manifest_dir) - .join("..") - .join("nodejs") - .join("package-lock.json"); - if lockfile.is_file() { - println!("cargo:rerun-if-changed={}", lockfile.display()); - } - - // Hard opt-out: disable the entire download / bundle / cache mechanism - // in one step. For consumers who always supply the CLI via - // `CliProgram::Path` or `COPILOT_CLI_PATH` and don't want build.rs to - // touch the network (offline builds, locked-down CI, etc.). Works - // regardless of the `bundled-cli` cargo feature state — with neither - // `has_bundled_cli` nor `has_extracted_cli` emitted, runtime resolution - // falls straight through to `Error::BinaryNotFound` unless an explicit - // path source resolves first. - if std::env::var_os("COPILOT_SKIP_CLI_DOWNLOAD").is_some() { - println!( - "cargo:warning=COPILOT_SKIP_CLI_DOWNLOAD is set — skipping CLI download/bundle/cache" - ); - return; - } - - // docs.rs builds in a sandboxed environment without network access. - // Skip the CLI download so documentation can be generated successfully. - if std::env::var_os("DOCS_RS").is_some() { - println!("cargo:warning=DOCS_RS is set — skipping CLI download/bundle/cache"); - return; - } - - let Some(platform) = target_platform() else { - println!("cargo:warning=Unsupported target platform for Copilot CLI bundling — skipping"); - return; - }; - - let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is always set by cargo"); - let out = Path::new(&out_dir); - - // Resolve version + per-asset SHA-256 from one of two sources, in order: - // 1. `cli-version.txt` snapshot at the crate root (published-crate - // consumer; generated by the publish workflow). Combined format: - // `version=X` line + per-asset hash lines. Committing the hashes - // makes the publish workflow the trust boundary — an attacker who - // later re-points the release tag can't silently poison consumer - // builds. - // 2. Sibling `../nodejs/package-lock.json` (contributor build inside - // the github/copilot-sdk repo; live SHA256SUMS.txt fetch). Matches - // the .NET `_GetCopilotCliVersion` MSBuild target and the Go - // `cmd/bundler` tool. - let (version, expected_hash) = resolve_version_and_hash(platform.asset_name); - - // Bake the version into the crate regardless of mode. This is the - // single source of truth for "what CLI version did build.rs target", - // consumed by both the embed-mode path computation in embeddedcli.rs - // and the runtime path computation in resolve.rs (when `bundled-cli` - // is off). It's a small, machine-independent datum: no absolute - // paths, no username/home leakage, so sccache / cross-machine - // `target/` reuse stays cache-coherent. - println!("cargo:rustc-env=COPILOT_SDK_CLI_VERSION={version}"); - - let base_url = format!("https://github.com/github/copilot-cli/releases/download/v{version}"); - let cache_dir = std::env::var("BUNDLED_CLI_CACHE_DIR") - .ok() - .map(std::path::PathBuf::from); - - // Versioned cache key since copilot asset names don't include the version. - let cache_key = format!("v{version}-{}", platform.asset_name); - - if std::env::var_os("CARGO_FEATURE_BUNDLED_CLI").is_some() { - // Embed mode: we need the archive bytes to bake into the rlib, so - // always run the download (cache hit short-circuits inside - // `cached_download`). - let archive = cached_download( - &format!("{base_url}/{}", platform.asset_name), - &cache_key, - &expected_hash, - &cache_dir, - ); - verify_binary_present_in_archive(&archive, platform.binary_name, platform.asset_name); - emit_embedded(out, &archive); - println!("cargo:rustc-cfg=has_bundled_cli"); - } else { - // With `bundled-cli` off the extracted binary *is* the cache. - // Skip the upstream download entirely when it already exists at - // the expected path. No two separate caches. - // - // Runtime resolution (see `src/resolve.rs::extracted_cli_path`) - // recomputes this same path from `COPILOT_SDK_CLI_VERSION` + the - // OS-derived binary name + optional `COPILOT_CLI_EXTRACT_DIR`, - // so we don't bake an absolute path into the crate. - let install_dir = extracted_install_dir(&version); - let final_path = install_dir.join(platform.binary_name); - - // Invalidate build.rs whenever the cached binary disappears (cache GC, - // manual rm, OS reset, switching extract dir). Without this, cargo - // replays the saved `has_extracted_cli` cfg from its build-script - // output cache even when the file is gone, and runtime resolution - // fails with BinaryNotFound. - println!("cargo:rerun-if-changed={}", final_path.display()); - - if !final_path.is_file() { - let archive = cached_download( - &format!("{base_url}/{}", platform.asset_name), - &cache_key, - &expected_hash, - &cache_dir, - ); - verify_binary_present_in_archive(&archive, platform.binary_name, platform.asset_name); - extract_to_cache(&archive, &install_dir, platform); - } - - // Re-check after potential download+extract above; not an `else` - // because we need to verify the extraction actually produced the file. - if final_path.is_file() { - println!("cargo:rustc-cfg=has_extracted_cli"); - } - } -} - -/// Install directory used when `bundled-cli` is off. Mirrors the runtime -/// convention in `src/resolve.rs::extracted_cli_path`: both sides MUST -/// compute the same path from the same inputs, otherwise the runtime -/// resolver won't find what build.rs extracted. -/// -/// If `COPILOT_CLI_EXTRACT_DIR` is set the binary lives directly under -/// that directory (no per-version subdir) — useful for vendored slots and -/// for `.cargo/config.toml [env]`-style pinning that's symmetric between -/// build-time write and runtime read. Otherwise the binary lives under -/// `/github-copilot-sdk/cli//`. -fn extracted_install_dir(version: &str) -> PathBuf { - if let Some(custom) = std::env::var_os("COPILOT_CLI_EXTRACT_DIR") { - PathBuf::from(custom) - } else { - let cache = dirs::cache_dir().unwrap_or_else(std::env::temp_dir); - cache - .join("github-copilot-sdk") - .join("cli") - .join(sanitize_version(version)) - } -} - -/// Emit the `bundled_cli.rs` glue + `copilot_cli.archive` blob into `OUT_DIR` -/// for embed mode (`bundled-cli` cargo feature on). The version is exposed -/// crate-wide via the unconditional `cargo:rustc-env=COPILOT_SDK_CLI_VERSION` -/// emit; the binary name is OS-derived at runtime — so all we need to -/// generate here is the archive blob include. -fn emit_embedded(out: &Path, archive: &[u8]) { - std::fs::write(out.join("copilot_cli.archive"), archive) - .expect("failed to write copilot_cli.archive"); - - let generated = r#"// Auto-generated by github-copilot-sdk build.rs. Do not edit. -pub(super) static CLI_ARCHIVE: &[u8] = include_bytes!("copilot_cli.archive"); -"#; - - std::fs::write(out.join("bundled_cli.rs"), generated).expect("failed to write bundled_cli.rs"); -} - -/// Resolve the CLI version and the expected SHA-256 hash for the current -/// target's archive. Picks one of two sources in order. Panics with a clear -/// error if neither is available. -fn resolve_version_and_hash(asset_name: &str) -> (String, String) { - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"); - - // 1. Snapshot file at the crate root (published-crate consumer, - // vendored-slot consumer). Combined version + per-asset hashes. - let snapshot = Path::new(&manifest_dir).join("cli-version.txt"); - if snapshot.is_file() { - let contents = std::fs::read_to_string(&snapshot) - .unwrap_or_else(|e| panic!("failed to read {}: {e}", snapshot.display())); - return parse_snapshot(&contents, asset_name) - .unwrap_or_else(|e| panic!("invalid {}: {e}", snapshot.display())); - } - - // 2. Lockfile fallback (contributor build inside github/copilot-sdk) — - // read version, fetch live SHA256SUMS. - let lockfile = Path::new(&manifest_dir) - .join("..") - .join("nodejs") - .join("package-lock.json"); - if lockfile.is_file() { - let version = read_version_from_package_lock(&lockfile); - let hash = fetch_live_sha256(&version, asset_name); - return (version, hash); - } - - panic!( - "Could not resolve the Copilot CLI version.\n\ - Tried:\n\ - - {} (missing)\n\ - - {} (missing)\n\ - In a published crate or vendored slot, `cli-version.txt` should be present.\n\ - Inside the github/copilot-sdk repo, `../nodejs/package-lock.json` is the source.", - snapshot.display(), - lockfile.display(), - ); -} - -/// Parse the `cli-version.txt` snapshot file. Format is one `key=value` per -/// line. The first non-comment line is `version=X.Y.Z`; subsequent lines map -/// asset filename to hex SHA-256. Blank lines and lines starting with `#` -/// are skipped. -fn parse_snapshot(contents: &str, asset_name: &str) -> Result<(String, String), String> { - let mut version: Option = None; - let mut hash: Option = None; - for (line_no, raw) in contents.lines().enumerate() { - let line = raw.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - let (key, value) = line - .split_once('=') - .ok_or_else(|| format!("line {}: expected `key=value`, got `{raw}`", line_no + 1))?; - match key.trim() { - "version" => version = Some(value.trim().to_string()), - k if k == asset_name => hash = Some(value.trim().to_string()), - _ => {} - } - } - let version = version.ok_or("missing `version=` line")?; - let hash = hash.ok_or_else(|| format!("missing hash for asset `{asset_name}`"))?; - Ok((version, hash)) -} - -/// Read the `@github/copilot` version from `nodejs/package-lock.json`. -fn read_version_from_package_lock(path: &Path) -> String { - let contents = std::fs::read_to_string(path) - .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display())); - // Minimal JSON walk: find `"node_modules/@github/copilot"` object and - // its `"version"` field. Full JSON parsing keeps build.rs dep-light by - // using a regex; the file is generated by npm and we're matching an - // exact key path. - let key = "\"node_modules/@github/copilot\""; - let key_pos = contents - .find(key) - .unwrap_or_else(|| panic!("{} does not contain {key}", path.display())); - let after_key = &contents[key_pos + key.len()..]; - let version_key = "\"version\""; - let v_pos = after_key - .find(version_key) - .unwrap_or_else(|| panic!("no `version` field found near {key} in {}", path.display())); - let after_v = &after_key[v_pos + version_key.len()..]; - let q1 = after_v.find('"').expect("malformed version"); - let after_q1 = &after_v[q1 + 1..]; - let q2 = after_q1.find('"').expect("malformed version"); - after_q1[..q2].to_string() -} - -/// Fetch the live `SHA256SUMS.txt` for the given version from GitHub Releases -/// and pluck out the entry for `asset_name`. -fn fetch_live_sha256(version: &str, asset_name: &str) -> String { - let base_url = format!("https://github.com/github/copilot-cli/releases/download/v{version}"); - let checksums_url = format!("{base_url}/SHA256SUMS.txt"); - let checksums = download_with_retry(&checksums_url); - let checksums_text = - std::str::from_utf8(&checksums).expect("checksums file is not valid UTF-8"); - find_sha256_for_asset(checksums_text, asset_name) -} - -#[derive(Clone, Copy)] -struct Platform { - asset_name: &'static str, - binary_name: &'static str, -} - -fn target_platform() -> Option { - let os = std::env::var("CARGO_CFG_TARGET_OS").ok()?; - let arch = std::env::var("CARGO_CFG_TARGET_ARCH").ok()?; - - match (os.as_str(), arch.as_str()) { - ("macos", "aarch64") => Some(Platform { - asset_name: "copilot-darwin-arm64.tar.gz", - binary_name: "copilot", - }), - ("macos", "x86_64") => Some(Platform { - asset_name: "copilot-darwin-x64.tar.gz", - binary_name: "copilot", - }), - ("linux", "x86_64") => Some(Platform { - asset_name: "copilot-linux-x64.tar.gz", - binary_name: "copilot", - }), - ("linux", "aarch64") => Some(Platform { - asset_name: "copilot-linux-arm64.tar.gz", - binary_name: "copilot", - }), - ("windows", "x86_64") => Some(Platform { - asset_name: "copilot-win32-x64.zip", - binary_name: "copilot.exe", - }), - ("windows", "aarch64") => Some(Platform { - asset_name: "copilot-win32-arm64.zip", - binary_name: "copilot.exe", - }), - _ => None, - } -} - -/// Write the single binary entry from `archive` to -/// `/` and return the resulting path. -/// Idempotent — returns the existing path if a previous build already -/// populated the target. -/// -/// Uses file-level staging + atomic rename so a concurrent reader during -/// a parallel `cargo build` race never observes a partially-written -/// binary. `fs::rename` for files is atomic on both Unix and Windows -/// (Windows uses `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING`); for -/// directories it is not, which is why we stage at file granularity. -fn extract_to_cache(archive: &[u8], install_dir: &Path, platform: Platform) -> PathBuf { - let final_path = install_dir.join(platform.binary_name); - - // Caller already gated on `final_path.is_file()`; this is a safety - // net for any future caller that forgets. - if final_path.is_file() { - return final_path; - } - - std::fs::create_dir_all(install_dir).unwrap_or_else(|e| { - panic!( - "failed to create install dir {}: {e}", - install_dir.display() - ) - }); - - let bytes = extract_binary_bytes(archive, platform); - - // Staging file is a sibling of the final binary so the rename stays - // on the same filesystem (cross-fs rename is not atomic). PID + nanos - // disambiguate concurrent builds racing on the same cache. - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - let staging_path = install_dir.join(format!( - ".{}.staging-{}-{nanos}", - platform.binary_name, - std::process::id(), - )); - - { - let mut f = std::fs::File::create(&staging_path).unwrap_or_else(|e| { - let _ = std::fs::remove_file(&staging_path); - panic!( - "failed to create staging file {}: {e}", - staging_path.display() - ); - }); - - if let Err(e) = f.write_all(&bytes) { - let _ = std::fs::remove_file(&staging_path); - panic!( - "failed to write staging file {}: {e}", - staging_path.display() - ); - } - - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - if let Err(e) = f.set_permissions(std::fs::Permissions::from_mode(0o755)) { - let _ = std::fs::remove_file(&staging_path); - panic!("failed to chmod {}: {e}", staging_path.display()); - } - } - - // Backdate the staged binary to the Unix epoch before it lands. We emit - // `cargo:rerun-if-changed` on `final_path` (see caller) so a *deleted* - // cache binary forces a re-extract — but cargo stamps the build-script - // `output` reference when the script is spawned, seconds before this - // freshly-downloaded binary is written. A current mtime would therefore - // be *newer* than that reference, so the next identical `cargo` - // invocation would see the watched file as "changed" and pointlessly - // rerun build.rs + recompile the crate + relink every downstream crate. - // Pinning to the epoch keeps the file unambiguously older than any real - // build reference; `rename` preserves mtime (same inode), so it lands - // already-backdated and a no-change rebuild stays a true no-op. The - // deleted-file recovery contract is untouched: a missing file can't be - // stat'd, so cargo still treats it as stale and reruns regardless. - // - // Best-effort: a filesystem that refuses the epoch (e.g. FAT's 1980 floor - // clamps it — still older than any real reference) or rejects the call - // just reverts to the pre-fix redundant-rebuild behaviour, never a broken - // build. - if let Err(e) = f.set_modified(std::time::SystemTime::UNIX_EPOCH) { - println!( - "cargo:warning=Could not backdate {} (a redundant rebuild may occur): {e}", - staging_path.display() - ); - } - } - - // Atomic file-replace on both Unix and Windows. If a concurrent build - // already produced the same file the rename overwrites it; the bytes - // are SHA-verified-identical so replacement is safe. - if let Err(e) = std::fs::rename(&staging_path, &final_path) { - let _ = std::fs::remove_file(&staging_path); - panic!( - "failed to rename {} -> {}: {e}", - staging_path.display(), - final_path.display() - ); - } - - // Surface where the binary landed so contributors can find it. Quiet - // on the hot path: the caller's `is_file()` short-circuit (and the - // safety net at the top of this function) means this only fires on a - // true cache miss. - println!( - "cargo:warning=Extracted Copilot CLI to {}", - final_path.display() - ); - - final_path -} - -/// Replace characters outside `[a-zA-Z0-9._-]` with `_` so the version -/// string is always safe to use as a path component. Kept in sync with -/// `embeddedcli::sanitize_version` and `resolve::sanitize_version` so all -/// three resolve to the same cache directory for any given version. -fn sanitize_version(version: &str) -> String { - version - .chars() - .map(|c| match c { - 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' | '-' | '_' => c, - _ => '_', - }) - .collect() -} - -/// Extract the single `binary_name` entry from the release archive. Reused -/// between embed mode's `verify_binary_present_in_archive` and the -/// `extract_to_cache` path used when `bundled-cli` is off. Panics if the -/// entry isn't found — callers have already invoked -/// `verify_binary_present_in_archive`. -fn extract_binary_bytes(archive: &[u8], platform: Platform) -> Vec { - if platform.asset_name.ends_with(".zip") { - let cursor = std::io::Cursor::new(archive); - let mut zip = zip::ZipArchive::new(cursor) - .unwrap_or_else(|e| panic!("failed to open zip archive: {e}")); - for i in 0..zip.len() { - let mut entry = zip - .by_index(i) - .unwrap_or_else(|e| panic!("failed to read zip entry {i}: {e}")); - let name = entry.name().to_string(); - if name == platform.binary_name || name.ends_with(&format!("/{}", platform.binary_name)) - { - let mut bytes = Vec::with_capacity(entry.size() as usize); - std::io::copy(&mut entry, &mut bytes) - .unwrap_or_else(|e| panic!("failed to read zip entry bytes: {e}")); - return bytes; - } - } - } else { - let gz = flate2::read::GzDecoder::new(archive); - let mut tar = tar::Archive::new(gz); - for entry in tar - .entries() - .unwrap_or_else(|e| panic!("failed to read tar entries: {e}")) - { - let mut entry = entry.unwrap_or_else(|e| panic!("failed to read tar entry: {e}")); - let path = entry - .path() - .unwrap_or_else(|e| panic!("failed to read tar entry path: {e}")); - let name = path.to_string_lossy().into_owned(); - if name == platform.binary_name || name.ends_with(&format!("/{}", platform.binary_name)) - { - let mut bytes = Vec::with_capacity(entry.size() as usize); - entry - .read_to_end(&mut bytes) - .unwrap_or_else(|e| panic!("failed to read tar entry bytes: {e}")); - return bytes; - } - } - } - panic!( - "binary `{}` not found in archive `{}`", - platform.binary_name, platform.asset_name - ); -} - -/// Read a file from the download cache, or download it (with retries) and save -/// to cache. Verifies SHA-256 on every path. Evicts stale/corrupt cache entries -/// automatically. Cache I/O failures are treated as cache misses — they never -/// break the build. -fn cached_download( - url: &str, - cache_key: &str, - expected_hash: &str, - cache_dir: &Option, -) -> Vec { - if let Some(dir) = cache_dir { - let cached_path = dir.join(cache_key); - if cached_path.is_file() { - match std::fs::read(&cached_path) { - Ok(data) if hex_sha256(&data) == expected_hash => { - // Silent cache hit — nothing to surface. - return data; - } - Ok(_) => { - println!("cargo:warning=Cached archive hash mismatch, re-downloading"); - let _ = std::fs::remove_file(&cached_path); - } - Err(e) => { - println!( - "cargo:warning=Failed to read cache {}, re-downloading: {e}", - cached_path.display() - ); - } - } - } - } - - println!("cargo:warning=Downloading {url}"); - let data = download_with_retry(url); - let actual_hash = hex_sha256(&data); - if actual_hash != expected_hash { - panic!( - "Archive integrity check failed for {url}!\n expected: {expected_hash}\n actual: {actual_hash}\n \ - This could indicate a corrupted download or a supply-chain attack." - ); - } - - if let Some(dir) = cache_dir { - if let Err(e) = std::fs::create_dir_all(dir) { - println!( - "cargo:warning=Failed to create cache directory {}: {e}", - dir.display() - ); - } else { - let cached_path = dir.join(cache_key); - println!("cargo:warning=Caching archive at {}", cached_path.display()); - if let Err(e) = std::fs::write(&cached_path, &data) { - println!( - "cargo:warning=Failed to write cache file {}: {e}", - cached_path.display() - ); - } - } - } - - data -} - -/// Maximum number of HTTP attempts (one initial + this many retries on transient errors). -const MAX_RETRIES: u32 = 3; - -/// Download `url` with bounded retries on transient network errors. Backoff is -/// exponential starting at 1s. 4xx responses fail fast; 5xx and connect/read -/// errors are retried. -fn download_with_retry(url: &str) -> Vec { - let mut attempt = 0u32; - loop { - attempt += 1; - match try_download(url) { - Ok(bytes) => return bytes, - Err(err) if err.transient && attempt <= MAX_RETRIES => { - let backoff = Duration::from_secs(1u64 << (attempt - 1)); - println!( - "cargo:warning=Transient download failure for {url} (attempt {attempt}/{}): {} — retrying in {}s", - MAX_RETRIES + 1, - err.message, - backoff.as_secs(), - ); - std::thread::sleep(backoff); - } - Err(err) => panic!("Failed to download {url}: {}", err.message), - } - } -} - -struct DownloadError { - message: String, - transient: bool, -} - -fn try_download(url: &str) -> Result, DownloadError> { - let agent = ureq::AgentBuilder::new() - .timeout_connect(Duration::from_secs(30)) - .timeout_read(Duration::from_secs(120)) - .build(); - - match agent.get(url).call() { - Ok(response) => { - let mut bytes = Vec::new(); - response - .into_reader() - .read_to_end(&mut bytes) - .map_err(|e| DownloadError { - message: format!("read error: {e}"), - transient: true, - })?; - Ok(bytes) - } - // 5xx — server-side, treat as transient. - Err(ureq::Error::Status(code, response)) if (500..600).contains(&code) => { - Err(DownloadError { - message: format!("HTTP {code} {}", response.status_text()), - transient: true, - }) - } - // 4xx — client-side, fail fast. - Err(ureq::Error::Status(code, response)) => Err(DownloadError { - message: format!("HTTP {code} {}", response.status_text()), - transient: false, - }), - // Transport-layer (DNS, connect, TLS, read timeout) — treat as transient. - Err(ureq::Error::Transport(t)) => Err(DownloadError { - message: format!("transport error: {t}"), - transient: true, - }), - } -} - -fn find_sha256_for_asset(sums: &str, asset_name: &str) -> String { - for line in sums.lines() { - // Format: " " (two spaces) - if let Some((hash, name)) = line.split_once(" ") - && name.trim() == asset_name - { - return hash.trim().to_string(); - } - } - panic!("SHA256SUMS.txt does not contain an entry for {asset_name}"); -} - -fn sha256(data: &[u8]) -> [u8; 32] { - let mut hasher = sha2::Sha256::new(); - hasher.update(data); - hasher.finalize().into() -} - -/// Walks the downloaded archive at build time to confirm an entry matching -/// `binary_name` exists. Panics with a clear message if not — defends against -/// silent breakage if the upstream archive layout ever changes. -fn verify_binary_present_in_archive(archive: &[u8], binary_name: &str, asset_name: &str) { - let found = if asset_name.ends_with(".zip") { - archive_contains_zip_entry(archive, binary_name) - } else { - archive_contains_tar_entry(archive, binary_name) - }; - if !found { - panic!( - "Copilot CLI archive `{asset_name}` does not contain an entry named `{binary_name}`. \ - The upstream archive layout may have changed; runtime extraction would fail. \ - Update `verify_binary_present_in_archive` in build.rs and the matching `extract_binary` in src/embeddedcli.rs." - ); - } -} - -fn archive_contains_tar_entry(targz: &[u8], binary_name: &str) -> bool { - let gz = flate2::read::GzDecoder::new(targz); - let mut archive = tar::Archive::new(gz); - let Ok(entries) = archive.entries() else { - return false; - }; - for entry in entries.flatten() { - let Ok(path) = entry.path() else { - continue; - }; - let name = path.to_string_lossy(); - if name == binary_name || name.ends_with(&format!("/{binary_name}")) { - return true; - } - } - false -} - -fn archive_contains_zip_entry(zip_bytes: &[u8], binary_name: &str) -> bool { - let cursor = std::io::Cursor::new(zip_bytes); - let Ok(mut archive) = zip::ZipArchive::new(cursor) else { - return false; - }; - for i in 0..archive.len() { - let Ok(entry) = archive.by_index(i) else { - continue; - }; - let name = entry.name(); - if name == binary_name || name.ends_with(&format!("/{binary_name}")) { - return true; - } - } - false -} - -fn hex_sha256(data: &[u8]) -> String { - sha256(data).iter().map(|b| format!("{b:02x}")).collect() + implementation::main(); } diff --git a/rust/build/in_process.rs b/rust/build/in_process.rs new file mode 100644 index 0000000000..5826fbfa76 --- /dev/null +++ b/rust/build/in_process.rs @@ -0,0 +1,726 @@ +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use base64::Engine; +use sha2::Digest; + +pub(crate) fn main() { + println!("cargo:rerun-if-env-changed=DOCS_RS"); + println!("cargo:rerun-if-env-changed=COPILOT_SKIP_CLI_DOWNLOAD"); + println!("cargo:rerun-if-env-changed=COPILOT_CLI_EXTRACT_DIR"); + println!("cargo:rerun-if-env-changed=BUNDLED_CLI_CACHE_DIR"); + println!("cargo::rustc-check-cfg=cfg(has_bundled_cli)"); + println!("cargo::rustc-check-cfg=cfg(has_extracted_cli)"); + println!("cargo:rerun-if-changed=cli-version-in-process.txt"); + + // Only declare the lockfile rerun when the lockfile actually exists. + // Cargo treats `rerun-if-changed` for a missing path as "always rerun" + // — so unconditionally declaring this on consumers without a sibling + // `nodejs/` (vendored slots, published crates) would force build.rs + // to re-run on every `cargo build` even when nothing has changed. + // The lockfile path is only the source-of-truth in this repo's + // contributor builds; everywhere else `cli-version-in-process.txt` is canonical. + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"); + let lockfile = Path::new(&manifest_dir) + .join("..") + .join("nodejs") + .join("package-lock.json"); + if lockfile.is_file() { + println!("cargo:rerun-if-changed={}", lockfile.display()); + } + + // Hard opt-out: disable the entire download / bundle / cache mechanism + // in one step. For consumers who always supply the CLI via + // `CliProgram::Path` or `COPILOT_CLI_PATH` and don't want build.rs to + // touch the network (offline builds, locked-down CI, etc.). Works + // regardless of the `bundled-cli` cargo feature state — with neither + // `has_bundled_cli` nor `has_extracted_cli` emitted, runtime resolution + // falls straight through to `Error::BinaryNotFound` unless an explicit + // path source resolves first. + if std::env::var_os("COPILOT_SKIP_CLI_DOWNLOAD").is_some() { + println!( + "cargo:warning=COPILOT_SKIP_CLI_DOWNLOAD is set — skipping CLI download/bundle/cache" + ); + return; + } + + // docs.rs builds in a sandboxed environment without network access. + // Skip the CLI download so documentation can be generated successfully. + if std::env::var_os("DOCS_RS").is_some() { + println!("cargo:warning=DOCS_RS is set — skipping CLI download/bundle/cache"); + return; + } + + let Some(platform) = target_platform() else { + println!("cargo:warning=Unsupported target platform for Copilot CLI bundling — skipping"); + return; + }; + + let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is always set by cargo"); + let out = Path::new(&out_dir); + + // Resolve version + npm integrity from one of two sources, in order: + // 1. `cli-version-in-process.txt` snapshot at the crate root (published-crate + // consumer; generated by the publish workflow). Combined format: + // `version=X` line + per-package integrity lines. Committing these + // makes the publish workflow the trust boundary — an attacker who + // later re-points the release tag can't silently poison consumer + // builds. + // 2. Sibling `../nodejs/package-lock.json` (contributor build inside + // the github/copilot-sdk repo), whose platform-package integrity is + // the same trust source npm uses. + let (version, expected_integrity) = resolve_version_and_integrity(platform.package_name); + + // Bake the version into the crate regardless of mode. This is the + // single source of truth for "what CLI version did build.rs target", + // consumed by both the embed-mode path computation in embeddedcli.rs + // and the runtime path computation in resolve.rs (when `bundled-cli` + // is off). It's a small, machine-independent datum: no absolute + // paths, no username/home leakage, so sccache / cross-machine + // `target/` reuse stays cache-coherent. + println!("cargo:rustc-env=COPILOT_SDK_CLI_VERSION={version}"); + + let archive_name = format!("{}-{version}.tgz", platform.package_name); + let download_url = format!( + "https://registry.npmjs.org/@github/{}/-/{}", + platform.package_name, archive_name + ); + let cache_dir = std::env::var("BUNDLED_CLI_CACHE_DIR") + .ok() + .map(std::path::PathBuf::from); + + let cache_key = format!("v{version}-{archive_name}"); + let include_runtime = std::env::var_os("CARGO_FEATURE_BUNDLED_IN_PROCESS").is_some(); + + if std::env::var_os("CARGO_FEATURE_BUNDLED_CLI").is_some() { + let archive = cached_download(&download_url, &cache_key, &expected_integrity, &cache_dir); + verify_binary_present_in_archive(&archive, platform.binary_name, &archive_name); + emit_embedded(out, &archive, platform, include_runtime); + println!("cargo:rustc-cfg=has_bundled_cli"); + } else { + // With `bundled-cli` off the extracted binary *is* the cache. + // Skip the upstream download entirely when it already exists at + // the expected path. No two separate caches. + // + // Runtime resolution (see `src/resolve.rs::extracted_cli_path`) + // recomputes this same path from `COPILOT_SDK_CLI_VERSION` + the + // OS-derived binary name + optional `COPILOT_CLI_EXTRACT_DIR`, + // so we don't bake an absolute path into the crate. + let install_dir = extracted_install_dir(&version); + let final_path = install_dir.join(platform.binary_name); + + // Invalidate build.rs whenever the cached binary disappears (cache GC, + // manual rm, OS reset, switching extract dir). Without this, cargo + // replays the saved `has_extracted_cli` cfg from its build-script + // output cache even when the file is gone, and runtime resolution + // fails with BinaryNotFound. + println!("cargo:rerun-if-changed={}", final_path.display()); + + if !final_path.is_file() { + let archive = + cached_download(&download_url, &cache_key, &expected_integrity, &cache_dir); + verify_binary_present_in_archive(&archive, platform.binary_name, &archive_name); + extract_to_cache(&archive, &install_dir, platform); + } + + // Re-check after potential download+extract above; not an `else` + // because we need to verify the extraction actually produced the file. + if final_path.is_file() { + println!("cargo:rustc-cfg=has_extracted_cli"); + } + } +} + +/// Install directory used when `bundled-cli` is off. Mirrors the runtime +/// convention in `src/resolve.rs::extracted_cli_path`: both sides MUST +/// compute the same path from the same inputs, otherwise the runtime +/// resolver won't find what build.rs extracted. +/// +/// If `COPILOT_CLI_EXTRACT_DIR` is set the binary lives directly under +/// that directory (no per-version subdir) — useful for vendored slots and +/// for `.cargo/config.toml [env]`-style pinning that's symmetric between +/// build-time write and runtime read. Otherwise the binary lives under +/// `/github-copilot-sdk/cli//`. +fn extracted_install_dir(version: &str) -> PathBuf { + if let Some(custom) = std::env::var_os("COPILOT_CLI_EXTRACT_DIR") { + PathBuf::from(custom) + } else { + let cache = dirs::cache_dir().unwrap_or_else(std::env::temp_dir); + cache + .join("github-copilot-sdk") + .join("cli") + .join(sanitize_version(version)) + } +} + +/// Emit the `bundled_cli.rs` glue + `copilot_cli.archive` blob into `OUT_DIR` +/// for embed mode (`bundled-cli` cargo feature on). The version is exposed +/// crate-wide via the unconditional `cargo:rustc-env=COPILOT_SDK_CLI_VERSION` +/// emit; the binary name is OS-derived at runtime — so all we need to +/// generate here is the archive blob include. +fn emit_embedded(out: &Path, package: &[u8], platform: Platform, include_runtime: bool) { + let archive = build_embedded_archive(package, platform, include_runtime); + std::fs::write(out.join("copilot_cli.archive"), archive) + .expect("failed to write copilot_cli.archive"); + + let generated = r#"// Auto-generated by github-copilot-sdk build.rs. Do not edit. +pub(super) static CLI_ARCHIVE: &[u8] = include_bytes!("copilot_cli.archive"); +"#; + + std::fs::write(out.join("bundled_cli.rs"), generated).expect("failed to write bundled_cli.rs"); +} + +fn build_embedded_archive(package: &[u8], platform: Platform, include_runtime: bool) -> Vec { + let encoder = flate2::GzBuilder::new() + .mtime(0) + .write(Vec::new(), flate2::Compression::default()); + let mut archive = tar::Builder::new(encoder); + append_archive_file( + &mut archive, + platform.binary_name, + &extract_binary_bytes(package, platform), + 0o755, + ); + if include_runtime { + let runtime = extract_runtime_library_bytes(package).unwrap_or_else(|| { + panic!( + "package `{}` does not contain the native runtime library required by the `bundled-in-process` feature", + platform.package_name + ) + }); + append_archive_file( + &mut archive, + platform.runtime_library_name(), + &runtime, + 0o644, + ); + } + let encoder = archive + .into_inner() + .expect("failed to finish minimal embedded CLI archive"); + encoder + .finish() + .expect("failed to compress minimal embedded CLI archive") +} + +fn append_archive_file( + archive: &mut tar::Builder, + path: &str, + bytes: &[u8], + mode: u32, +) { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(mode); + header.set_uid(0); + header.set_gid(0); + header.set_mtime(0); + header.set_cksum(); + archive + .append_data(&mut header, path, bytes) + .unwrap_or_else(|e| panic!("failed to add `{path}` to embedded CLI archive: {e}")); +} + +/// Resolve the CLI version and npm integrity for the current target's +/// platform package. Picks one of two sources in order. Panics with a clear +/// error if neither is available. +fn resolve_version_and_integrity(package_name: &str) -> (String, String) { + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"); + + // 1. Snapshot file at the crate root (published-crate consumer, + // vendored-slot consumer). Combined version + per-asset hashes. + let snapshot = Path::new(&manifest_dir).join("cli-version-in-process.txt"); + if snapshot.is_file() { + let contents = std::fs::read_to_string(&snapshot) + .unwrap_or_else(|e| panic!("failed to read {}: {e}", snapshot.display())); + return parse_snapshot(&contents, package_name) + .unwrap_or_else(|e| panic!("invalid {}: {e}", snapshot.display())); + } + + // 2. Lockfile fallback (contributor build inside github/copilot-sdk). + let lockfile = Path::new(&manifest_dir) + .join("..") + .join("nodejs") + .join("package-lock.json"); + if lockfile.is_file() { + return read_version_and_integrity_from_package_lock(&lockfile, package_name); + } + + panic!( + "Could not resolve the Copilot CLI version.\n\ + Tried:\n\ + - {} (missing)\n\ + - {} (missing)\n\ + In a published crate or vendored slot, `cli-version-in-process.txt` should be present.\n\ + Inside the github/copilot-sdk repo, `../nodejs/package-lock.json` is the source.", + snapshot.display(), + lockfile.display(), + ); +} + +/// Parse the `cli-version-in-process.txt` snapshot file. Format is one `key=value` per +/// line. The first non-comment line is `version=X.Y.Z`; subsequent lines map +/// platform package name to npm integrity. Blank lines and lines starting with `#` +/// are skipped. +fn parse_snapshot(contents: &str, package_name: &str) -> Result<(String, String), String> { + let mut version: Option = None; + let mut integrity: Option = None; + for (line_no, raw) in contents.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let Some((key, value)) = line.split_once('=') else { + return Err(format!( + "line {}: expected `key=value`, got `{raw}`", + line_no + 1 + )); + }; + match key.trim() { + "version" => version = Some(value.trim().to_string()), + k if k == package_name => integrity = Some(value.trim().to_string()), + _ => {} + } + } + let version = version.ok_or("missing `version=` line")?; + let integrity = + integrity.ok_or_else(|| format!("missing integrity for package `{package_name}`"))?; + Ok((version, integrity)) +} + +fn read_version_and_integrity_from_package_lock( + path: &Path, + package_name: &str, +) -> (String, String) { + let contents = std::fs::read_to_string(path) + .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display())); + let lock: serde_json::Value = serde_json::from_str(&contents) + .unwrap_or_else(|e| panic!("failed to parse {}: {e}", path.display())); + let cli_key = "node_modules/@github/copilot"; + let version = lock["packages"][cli_key]["version"] + .as_str() + .unwrap_or_else(|| panic!("{cli_key} has no version in {}", path.display())); + let platform_key = format!("node_modules/@github/{package_name}"); + let integrity = lock["packages"][&platform_key]["integrity"] + .as_str() + .unwrap_or_else(|| panic!("{platform_key} has no integrity in {}", path.display())); + (version.to_string(), integrity.to_string()) +} + +#[derive(Clone, Copy)] +struct Platform { + package_name: &'static str, + binary_name: &'static str, +} + +impl Platform { + fn runtime_library_name(&self) -> &'static str { + if self.package_name.contains("win32") { + "copilot_runtime.dll" + } else if self.package_name.contains("darwin") { + "libcopilot_runtime.dylib" + } else { + "libcopilot_runtime.so" + } + } +} + +fn target_platform() -> Option { + let os = std::env::var("CARGO_CFG_TARGET_OS").ok()?; + let arch = std::env::var("CARGO_CFG_TARGET_ARCH").ok()?; + let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(); + + match (os.as_str(), arch.as_str(), target_env.as_str()) { + ("macos", "aarch64", _) => Some(Platform { + package_name: "copilot-darwin-arm64", + binary_name: "copilot", + }), + ("macos", "x86_64", _) => Some(Platform { + package_name: "copilot-darwin-x64", + binary_name: "copilot", + }), + ("linux", "x86_64", "musl") => Some(Platform { + package_name: "copilot-linuxmusl-x64", + binary_name: "copilot", + }), + ("linux", "aarch64", "musl") => Some(Platform { + package_name: "copilot-linuxmusl-arm64", + binary_name: "copilot", + }), + ("linux", "x86_64", _) => Some(Platform { + package_name: "copilot-linux-x64", + binary_name: "copilot", + }), + ("linux", "aarch64", _) => Some(Platform { + package_name: "copilot-linux-arm64", + binary_name: "copilot", + }), + ("windows", "x86_64", _) => Some(Platform { + package_name: "copilot-win32-x64", + binary_name: "copilot.exe", + }), + ("windows", "aarch64", _) => Some(Platform { + package_name: "copilot-win32-arm64", + binary_name: "copilot.exe", + }), + _ => None, + } +} + +/// Write the single binary entry from `archive` to +/// `/` and return the resulting path. +/// Idempotent — returns the existing path if a previous build already +/// populated the target. +/// +/// Uses file-level staging + atomic rename so a concurrent reader during +/// a parallel `cargo build` race never observes a partially-written +/// binary. `fs::rename` for files is atomic on both Unix and Windows +/// (Windows uses `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING`); for +/// directories it is not, which is why we stage at file granularity. +fn extract_to_cache(archive: &[u8], install_dir: &Path, platform: Platform) -> PathBuf { + let final_path = install_dir.join(platform.binary_name); + + // Caller already gated on `final_path.is_file()`; this is a safety + // net for any future caller that forgets. + if final_path.is_file() { + return final_path; + } + + std::fs::create_dir_all(install_dir).unwrap_or_else(|e| { + panic!( + "failed to create install dir {}: {e}", + install_dir.display() + ) + }); + + let bytes = extract_binary_bytes(archive, platform); + + // Staging file is a sibling of the final binary so the rename stays + // on the same filesystem (cross-fs rename is not atomic). PID + nanos + // disambiguate concurrent builds racing on the same cache. + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let staging_path = install_dir.join(format!( + ".{}.staging-{}-{nanos}", + platform.binary_name, + std::process::id(), + )); + + { + let mut f = std::fs::File::create(&staging_path).unwrap_or_else(|e| { + let _ = std::fs::remove_file(&staging_path); + panic!( + "failed to create staging file {}: {e}", + staging_path.display() + ); + }); + + if let Err(e) = f.write_all(&bytes) { + let _ = std::fs::remove_file(&staging_path); + panic!( + "failed to write staging file {}: {e}", + staging_path.display() + ); + } + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if let Err(e) = f.set_permissions(std::fs::Permissions::from_mode(0o755)) { + let _ = std::fs::remove_file(&staging_path); + panic!("failed to chmod {}: {e}", staging_path.display()); + } + } + + // Backdate the staged binary to the Unix epoch before it lands. We emit + // `cargo:rerun-if-changed` on `final_path` (see caller) so a *deleted* + // cache binary forces a re-extract — but cargo stamps the build-script + // `output` reference when the script is spawned, seconds before this + // freshly-downloaded binary is written. A current mtime would therefore + // be *newer* than that reference, so the next identical `cargo` + // invocation would see the watched file as "changed" and pointlessly + // rerun build.rs + recompile the crate + relink every downstream crate. + // Pinning to the epoch keeps the file unambiguously older than any real + // build reference; `rename` preserves mtime (same inode), so it lands + // already-backdated and a no-change rebuild stays a true no-op. The + // deleted-file recovery contract is untouched: a missing file can't be + // stat'd, so cargo still treats it as stale and reruns regardless. + // + // Best-effort: a filesystem that refuses the epoch (e.g. FAT's 1980 floor + // clamps it — still older than any real reference) or rejects the call + // just reverts to the pre-fix redundant-rebuild behaviour, never a broken + // build. + if let Err(e) = f.set_modified(std::time::SystemTime::UNIX_EPOCH) { + println!( + "cargo:warning=Could not backdate {} (a redundant rebuild may occur): {e}", + staging_path.display() + ); + } + } + + // Atomic file-replace on both Unix and Windows. If a concurrent build + // already produced the same file the rename overwrites it; the bytes + // are integrity-verified-identical so replacement is safe. + if let Err(e) = std::fs::rename(&staging_path, &final_path) { + let _ = std::fs::remove_file(&staging_path); + panic!( + "failed to rename {} -> {}: {e}", + staging_path.display(), + final_path.display() + ); + } + + // Surface where the binary landed so contributors can find it. Quiet + // on the hot path: the caller's `is_file()` short-circuit (and the + // safety net at the top of this function) means this only fires on a + // true cache miss. + println!( + "cargo:warning=Extracted Copilot CLI to {}", + final_path.display() + ); + + final_path +} + +fn extract_runtime_library_bytes(archive: &[u8]) -> Option> { + let gz = flate2::read::GzDecoder::new(archive); + let mut tar = tar::Archive::new(gz); + for entry in tar.entries().ok()? { + let mut entry = entry.ok()?; + let name = entry.path().ok()?.to_string_lossy().into_owned(); + if name == "runtime.node" || name.ends_with("/runtime.node") { + let mut bytes = Vec::with_capacity(entry.size() as usize); + entry.read_to_end(&mut bytes).ok()?; + return Some(bytes); + } + } + None +} + +/// Replace characters outside `[a-zA-Z0-9._-]` with `_` so the version +/// string is always safe to use as a path component. Kept in sync with +/// `embeddedcli::sanitize_version` and `resolve::sanitize_version` so all +/// three resolve to the same cache directory for any given version. +fn sanitize_version(version: &str) -> String { + version + .chars() + .map(|c| match c { + 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' | '-' | '_' => c, + _ => '_', + }) + .collect() +} + +/// Extract the single `binary_name` entry from the npm package archive. Reused +/// between embed mode's `verify_binary_present_in_archive` and the +/// `extract_to_cache` path used when `bundled-cli` is off. Panics if the +/// entry isn't found — callers have already invoked +/// `verify_binary_present_in_archive`. +fn extract_binary_bytes(archive: &[u8], platform: Platform) -> Vec { + let gz = flate2::read::GzDecoder::new(archive); + let mut tar = tar::Archive::new(gz); + for entry in tar + .entries() + .unwrap_or_else(|e| panic!("failed to read tar entries: {e}")) + { + let mut entry = entry.unwrap_or_else(|e| panic!("failed to read tar entry: {e}")); + let path = entry + .path() + .unwrap_or_else(|e| panic!("failed to read tar entry path: {e}")); + let name = path.to_string_lossy().into_owned(); + if name == platform.binary_name || name.ends_with(&format!("/{}", platform.binary_name)) { + let mut bytes = Vec::with_capacity(entry.size() as usize); + entry + .read_to_end(&mut bytes) + .unwrap_or_else(|e| panic!("failed to read tar entry bytes: {e}")); + return bytes; + } + } + panic!( + "binary `{}` not found in package `{}`", + platform.binary_name, platform.package_name + ); +} + +/// Read a file from the download cache, or download it (with retries) and save +/// to cache. Verifies npm integrity on every path. Evicts stale/corrupt cache entries +/// automatically. Cache I/O failures are treated as cache misses — they never +/// break the build. +fn cached_download( + url: &str, + cache_key: &str, + expected_integrity: &str, + cache_dir: &Option, +) -> Vec { + if let Some(dir) = cache_dir { + let cached_path = dir.join(cache_key); + if cached_path.is_file() { + match std::fs::read(&cached_path) { + Ok(data) if verify_integrity(&data, expected_integrity) => { + // Silent cache hit — nothing to surface. + return data; + } + Ok(_) => { + println!("cargo:warning=Cached archive hash mismatch, re-downloading"); + let _ = std::fs::remove_file(&cached_path); + } + Err(e) => { + println!( + "cargo:warning=Failed to read cache {}, re-downloading: {e}", + cached_path.display() + ); + } + } + } + } + + println!("cargo:warning=Downloading {url}"); + let data = download_with_retry(url); + if !verify_integrity(&data, expected_integrity) { + panic!( + "Archive integrity check failed for {url}!\n expected: {expected_integrity}\n \ + This could indicate a corrupted download or a supply-chain attack." + ); + } + + if let Some(dir) = cache_dir { + if let Err(e) = std::fs::create_dir_all(dir) { + println!( + "cargo:warning=Failed to create cache directory {}: {e}", + dir.display() + ); + } else { + let cached_path = dir.join(cache_key); + println!("cargo:warning=Caching archive at {}", cached_path.display()); + if let Err(e) = std::fs::write(&cached_path, &data) { + println!( + "cargo:warning=Failed to write cache file {}: {e}", + cached_path.display() + ); + } + } + } + + data +} + +/// Maximum number of HTTP attempts (one initial + this many retries on transient errors). +const MAX_RETRIES: u32 = 3; + +/// Download `url` with bounded retries on transient network errors. Backoff is +/// exponential starting at 1s. 4xx responses fail fast; 5xx and connect/read +/// errors are retried. +fn download_with_retry(url: &str) -> Vec { + let mut attempt = 0u32; + loop { + attempt += 1; + match try_download(url) { + Ok(bytes) => return bytes, + Err(err) if err.transient && attempt <= MAX_RETRIES => { + let backoff = Duration::from_secs(1u64 << (attempt - 1)); + println!( + "cargo:warning=Transient download failure for {url} (attempt {attempt}/{}): {} — retrying in {}s", + MAX_RETRIES + 1, + err.message, + backoff.as_secs(), + ); + std::thread::sleep(backoff); + } + Err(err) => panic!("Failed to download {url}: {}", err.message), + } + } +} + +struct DownloadError { + message: String, + transient: bool, +} + +fn try_download(url: &str) -> Result, DownloadError> { + let connector = native_tls::TlsConnector::new().map_err(|e| DownloadError { + message: format!("native-tls init error: {e}"), + transient: false, + })?; + let agent = ureq::AgentBuilder::new() + .tls_connector(std::sync::Arc::new(connector)) + .timeout_connect(Duration::from_secs(30)) + .timeout_read(Duration::from_secs(120)) + .build(); + + match agent.get(url).call() { + Ok(response) => { + let mut bytes = Vec::new(); + response + .into_reader() + .read_to_end(&mut bytes) + .map_err(|e| DownloadError { + message: format!("read error: {e}"), + transient: true, + })?; + Ok(bytes) + } + // 5xx — server-side, treat as transient. + Err(ureq::Error::Status(code, response)) if (500..600).contains(&code) => { + Err(DownloadError { + message: format!("HTTP {code} {}", response.status_text()), + transient: true, + }) + } + // 4xx — client-side, fail fast. + Err(ureq::Error::Status(code, response)) => Err(DownloadError { + message: format!("HTTP {code} {}", response.status_text()), + transient: false, + }), + // Transport-layer (DNS, connect, TLS, read timeout) — treat as transient. + Err(ureq::Error::Transport(t)) => Err(DownloadError { + message: format!("transport error: {t}"), + transient: true, + }), + } +} + +/// Walks the downloaded archive at build time to confirm an entry matching +/// `binary_name` exists. Panics with a clear message if not. +fn verify_binary_present_in_archive(archive: &[u8], binary_name: &str, package_name: &str) { + let found = archive_contains_tar_entry(archive, binary_name); + if !found { + panic!( + "Copilot CLI package `{package_name}` does not contain an entry named `{binary_name}`. \ + The package layout may have changed; runtime extraction would fail. \ + Update `verify_binary_present_in_archive` in build.rs and the matching `extract_binary` in src/embeddedcli.rs." + ); + } +} + +fn archive_contains_tar_entry(targz: &[u8], binary_name: &str) -> bool { + let gz = flate2::read::GzDecoder::new(targz); + let mut archive = tar::Archive::new(gz); + let Ok(entries) = archive.entries() else { + return false; + }; + for entry in entries.flatten() { + let Ok(path) = entry.path() else { + continue; + }; + let name = path.to_string_lossy(); + if name == binary_name || name.ends_with(&format!("/{binary_name}")) { + return true; + } + } + false +} + +fn verify_integrity(data: &[u8], integrity: &str) -> bool { + let Some(encoded) = integrity.strip_prefix("sha512-") else { + return false; + }; + let Ok(expected) = base64::engine::general_purpose::STANDARD.decode(encoded) else { + return false; + }; + let mut hasher = sha2::Sha512::new(); + hasher.update(data); + hasher.finalize().as_slice() == expected +} diff --git a/rust/build/out_of_process.rs b/rust/build/out_of_process.rs new file mode 100644 index 0000000000..b8cd3acc3f --- /dev/null +++ b/rust/build/out_of_process.rs @@ -0,0 +1,717 @@ +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use sha2::Digest; + +pub(crate) fn main() { + println!("cargo:rerun-if-env-changed=DOCS_RS"); + println!("cargo:rerun-if-env-changed=COPILOT_SKIP_CLI_DOWNLOAD"); + println!("cargo:rerun-if-env-changed=COPILOT_CLI_EXTRACT_DIR"); + println!("cargo:rerun-if-env-changed=BUNDLED_CLI_CACHE_DIR"); + println!("cargo::rustc-check-cfg=cfg(has_bundled_cli)"); + println!("cargo::rustc-check-cfg=cfg(has_extracted_cli)"); + println!("cargo:rerun-if-changed=cli-version.txt"); + + // Only declare the lockfile rerun when the lockfile actually exists. + // Cargo treats `rerun-if-changed` for a missing path as "always rerun" + // — so unconditionally declaring this on consumers without a sibling + // `nodejs/` (vendored slots, published crates) would force build.rs + // to re-run on every `cargo build` even when nothing has changed. + // The lockfile path is only the source-of-truth in this repo's + // contributor builds; everywhere else `cli-version.txt` is canonical. + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"); + let lockfile = Path::new(&manifest_dir) + .join("..") + .join("nodejs") + .join("package-lock.json"); + if lockfile.is_file() { + println!("cargo:rerun-if-changed={}", lockfile.display()); + } + + // Hard opt-out: disable the entire download / bundle / cache mechanism + // in one step. For consumers who always supply the CLI via + // `CliProgram::Path` or `COPILOT_CLI_PATH` and don't want build.rs to + // touch the network (offline builds, locked-down CI, etc.). Works + // regardless of the `bundled-cli` cargo feature state — with neither + // `has_bundled_cli` nor `has_extracted_cli` emitted, runtime resolution + // falls straight through to `Error::BinaryNotFound` unless an explicit + // path source resolves first. + if std::env::var_os("COPILOT_SKIP_CLI_DOWNLOAD").is_some() { + println!( + "cargo:warning=COPILOT_SKIP_CLI_DOWNLOAD is set — skipping CLI download/bundle/cache" + ); + return; + } + + // docs.rs builds in a sandboxed environment without network access. + // Skip the CLI download so documentation can be generated successfully. + if std::env::var_os("DOCS_RS").is_some() { + println!("cargo:warning=DOCS_RS is set — skipping CLI download/bundle/cache"); + return; + } + + let Some(platform) = target_platform() else { + println!("cargo:warning=Unsupported target platform for Copilot CLI bundling — skipping"); + return; + }; + + let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is always set by cargo"); + let out = Path::new(&out_dir); + + // Resolve version + per-asset SHA-256 from one of two sources, in order: + // 1. `cli-version.txt` snapshot at the crate root (published-crate + // consumer; generated by the publish workflow). Combined format: + // `version=X` line + per-asset hash lines. Committing the hashes + // makes the publish workflow the trust boundary — an attacker who + // later re-points the release tag can't silently poison consumer + // builds. + // 2. Sibling `../nodejs/package-lock.json` (contributor build inside + // the github/copilot-sdk repo; live SHA256SUMS.txt fetch). Matches + // the .NET `_GetCopilotCliVersion` MSBuild target and the Go + // `cmd/bundler` tool. + let (version, expected_hash) = resolve_version_and_hash(platform.asset_name); + + // Bake the version into the crate regardless of mode. This is the + // single source of truth for "what CLI version did build.rs target", + // consumed by both the embed-mode path computation in embeddedcli.rs + // and the runtime path computation in resolve.rs (when `bundled-cli` + // is off). It's a small, machine-independent datum: no absolute + // paths, no username/home leakage, so sccache / cross-machine + // `target/` reuse stays cache-coherent. + println!("cargo:rustc-env=COPILOT_SDK_CLI_VERSION={version}"); + + let base_url = format!("https://github.com/github/copilot-cli/releases/download/v{version}"); + let cache_dir = std::env::var("BUNDLED_CLI_CACHE_DIR") + .ok() + .map(std::path::PathBuf::from); + + // Versioned cache key since copilot asset names don't include the version. + let cache_key = format!("v{version}-{}", platform.asset_name); + + if std::env::var_os("CARGO_FEATURE_BUNDLED_CLI").is_some() { + // Embed mode: we need the archive bytes to bake into the rlib, so + // always run the download (cache hit short-circuits inside + // `cached_download`). + let archive = cached_download( + &format!("{base_url}/{}", platform.asset_name), + &cache_key, + &expected_hash, + &cache_dir, + ); + verify_binary_present_in_archive(&archive, platform.binary_name, platform.asset_name); + emit_embedded(out, &archive); + println!("cargo:rustc-cfg=has_bundled_cli"); + } else { + // With `bundled-cli` off the extracted binary *is* the cache. + // Skip the upstream download entirely when it already exists at + // the expected path. No two separate caches. + // + // Runtime resolution (see `src/resolve.rs::extracted_cli_path`) + // recomputes this same path from `COPILOT_SDK_CLI_VERSION` + the + // OS-derived binary name + optional `COPILOT_CLI_EXTRACT_DIR`, + // so we don't bake an absolute path into the crate. + let install_dir = extracted_install_dir(&version); + let final_path = install_dir.join(platform.binary_name); + + // Invalidate build.rs whenever the cached binary disappears (cache GC, + // manual rm, OS reset, switching extract dir). Without this, cargo + // replays the saved `has_extracted_cli` cfg from its build-script + // output cache even when the file is gone, and runtime resolution + // fails with BinaryNotFound. + println!("cargo:rerun-if-changed={}", final_path.display()); + + if !final_path.is_file() { + let archive = cached_download( + &format!("{base_url}/{}", platform.asset_name), + &cache_key, + &expected_hash, + &cache_dir, + ); + verify_binary_present_in_archive(&archive, platform.binary_name, platform.asset_name); + extract_to_cache(&archive, &install_dir, platform); + } + + // Re-check after potential download+extract above; not an `else` + // because we need to verify the extraction actually produced the file. + if final_path.is_file() { + println!("cargo:rustc-cfg=has_extracted_cli"); + } + } +} + +/// Install directory used when `bundled-cli` is off. Mirrors the runtime +/// convention in `src/resolve.rs::extracted_cli_path`: both sides MUST +/// compute the same path from the same inputs, otherwise the runtime +/// resolver won't find what build.rs extracted. +/// +/// If `COPILOT_CLI_EXTRACT_DIR` is set the binary lives directly under +/// that directory (no per-version subdir) — useful for vendored slots and +/// for `.cargo/config.toml [env]`-style pinning that's symmetric between +/// build-time write and runtime read. Otherwise the binary lives under +/// `/github-copilot-sdk/cli//`. +fn extracted_install_dir(version: &str) -> PathBuf { + if let Some(custom) = std::env::var_os("COPILOT_CLI_EXTRACT_DIR") { + PathBuf::from(custom) + } else { + let cache = dirs::cache_dir().unwrap_or_else(std::env::temp_dir); + cache + .join("github-copilot-sdk") + .join("cli") + .join(sanitize_version(version)) + } +} + +/// Emit the `bundled_cli.rs` glue + `copilot_cli.archive` blob into `OUT_DIR` +/// for embed mode (`bundled-cli` cargo feature on). The version is exposed +/// crate-wide via the unconditional `cargo:rustc-env=COPILOT_SDK_CLI_VERSION` +/// emit; the binary name is OS-derived at runtime — so all we need to +/// generate here is the archive blob include. +fn emit_embedded(out: &Path, archive: &[u8]) { + std::fs::write(out.join("copilot_cli.archive"), archive) + .expect("failed to write copilot_cli.archive"); + + let generated = r#"// Auto-generated by github-copilot-sdk build.rs. Do not edit. +pub(super) static CLI_ARCHIVE: &[u8] = include_bytes!("copilot_cli.archive"); +"#; + + std::fs::write(out.join("bundled_cli.rs"), generated).expect("failed to write bundled_cli.rs"); +} + +/// Resolve the CLI version and the expected SHA-256 hash for the current +/// target's archive. Picks one of two sources in order. Panics with a clear +/// error if neither is available. +fn resolve_version_and_hash(asset_name: &str) -> (String, String) { + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"); + + // 1. Snapshot file at the crate root (published-crate consumer, + // vendored-slot consumer). Combined version + per-asset hashes. + let snapshot = Path::new(&manifest_dir).join("cli-version.txt"); + if snapshot.is_file() { + let contents = std::fs::read_to_string(&snapshot) + .unwrap_or_else(|e| panic!("failed to read {}: {e}", snapshot.display())); + return parse_snapshot(&contents, asset_name) + .unwrap_or_else(|e| panic!("invalid {}: {e}", snapshot.display())); + } + + // 2. Lockfile fallback (contributor build inside github/copilot-sdk) — + // read version, fetch live SHA256SUMS. + let lockfile = Path::new(&manifest_dir) + .join("..") + .join("nodejs") + .join("package-lock.json"); + if lockfile.is_file() { + let version = read_version_from_package_lock(&lockfile); + let hash = fetch_live_sha256(&version, asset_name); + return (version, hash); + } + + panic!( + "Could not resolve the Copilot CLI version.\n\ + Tried:\n\ + - {} (missing)\n\ + - {} (missing)\n\ + In a published crate or vendored slot, `cli-version.txt` should be present.\n\ + Inside the github/copilot-sdk repo, `../nodejs/package-lock.json` is the source.", + snapshot.display(), + lockfile.display(), + ); +} + +/// Parse the `cli-version.txt` snapshot file. Format is one `key=value` per +/// line. The first non-comment line is `version=X.Y.Z`; subsequent lines map +/// asset filename to hex SHA-256. Blank lines and lines starting with `#` +/// are skipped. +fn parse_snapshot(contents: &str, asset_name: &str) -> Result<(String, String), String> { + let mut version: Option = None; + let mut hash: Option = None; + for (line_no, raw) in contents.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let Some((key, value)) = line.split_once('=') else { + return Err(format!( + "line {}: expected `key=value`, got `{raw}`", + line_no + 1 + )); + }; + match key.trim() { + "version" => version = Some(value.trim().to_string()), + k if k == asset_name => hash = Some(value.trim().to_string()), + _ => {} + } + } + let version = version.ok_or("missing `version=` line")?; + let hash = hash.ok_or_else(|| format!("missing hash for asset `{asset_name}`"))?; + Ok((version, hash)) +} + +/// Read the `@github/copilot` version from `nodejs/package-lock.json`. +fn read_version_from_package_lock(path: &Path) -> String { + let contents = std::fs::read_to_string(path) + .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display())); + // Minimal JSON walk: find `"node_modules/@github/copilot"` object and + // its `"version"` field. Full JSON parsing keeps build.rs dep-light by + // using a regex; the file is generated by npm and we're matching an + // exact key path. + let key = "\"node_modules/@github/copilot\""; + let key_pos = contents + .find(key) + .unwrap_or_else(|| panic!("{} does not contain {key}", path.display())); + let after_key = &contents[key_pos + key.len()..]; + let version_key = "\"version\""; + let v_pos = after_key + .find(version_key) + .unwrap_or_else(|| panic!("no `version` field found near {key} in {}", path.display())); + let after_v = &after_key[v_pos + version_key.len()..]; + let q1 = after_v.find('"').expect("malformed version"); + let after_q1 = &after_v[q1 + 1..]; + let q2 = after_q1.find('"').expect("malformed version"); + after_q1[..q2].to_string() +} + +/// Fetch the live `SHA256SUMS.txt` for the given version from GitHub Releases +/// and pluck out the entry for `asset_name`. +fn fetch_live_sha256(version: &str, asset_name: &str) -> String { + let base_url = format!("https://github.com/github/copilot-cli/releases/download/v{version}"); + let checksums_url = format!("{base_url}/SHA256SUMS.txt"); + let checksums = download_with_retry(&checksums_url); + let checksums_text = + std::str::from_utf8(&checksums).expect("checksums file is not valid UTF-8"); + find_sha256_for_asset(checksums_text, asset_name) +} + +#[derive(Clone, Copy)] +struct Platform { + asset_name: &'static str, + binary_name: &'static str, +} + +fn target_platform() -> Option { + let os = std::env::var("CARGO_CFG_TARGET_OS").ok()?; + let arch = std::env::var("CARGO_CFG_TARGET_ARCH").ok()?; + + match (os.as_str(), arch.as_str()) { + ("macos", "aarch64") => Some(Platform { + asset_name: "copilot-darwin-arm64.tar.gz", + binary_name: "copilot", + }), + ("macos", "x86_64") => Some(Platform { + asset_name: "copilot-darwin-x64.tar.gz", + binary_name: "copilot", + }), + ("linux", "x86_64") => Some(Platform { + asset_name: "copilot-linux-x64.tar.gz", + binary_name: "copilot", + }), + ("linux", "aarch64") => Some(Platform { + asset_name: "copilot-linux-arm64.tar.gz", + binary_name: "copilot", + }), + ("windows", "x86_64") => Some(Platform { + asset_name: "copilot-win32-x64.zip", + binary_name: "copilot.exe", + }), + ("windows", "aarch64") => Some(Platform { + asset_name: "copilot-win32-arm64.zip", + binary_name: "copilot.exe", + }), + _ => None, + } +} + +/// Write the single binary entry from `archive` to +/// `/` and return the resulting path. +/// Idempotent — returns the existing path if a previous build already +/// populated the target. +/// +/// Uses file-level staging + atomic rename so a concurrent reader during +/// a parallel `cargo build` race never observes a partially-written +/// binary. `fs::rename` for files is atomic on both Unix and Windows +/// (Windows uses `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING`); for +/// directories it is not, which is why we stage at file granularity. +fn extract_to_cache(archive: &[u8], install_dir: &Path, platform: Platform) -> PathBuf { + let final_path = install_dir.join(platform.binary_name); + + // Caller already gated on `final_path.is_file()`; this is a safety + // net for any future caller that forgets. + if final_path.is_file() { + return final_path; + } + + std::fs::create_dir_all(install_dir).unwrap_or_else(|e| { + panic!( + "failed to create install dir {}: {e}", + install_dir.display() + ) + }); + + let bytes = extract_binary_bytes(archive, platform); + + // Staging file is a sibling of the final binary so the rename stays + // on the same filesystem (cross-fs rename is not atomic). PID + nanos + // disambiguate concurrent builds racing on the same cache. + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let staging_path = install_dir.join(format!( + ".{}.staging-{}-{nanos}", + platform.binary_name, + std::process::id(), + )); + + { + let mut f = std::fs::File::create(&staging_path).unwrap_or_else(|e| { + let _ = std::fs::remove_file(&staging_path); + panic!( + "failed to create staging file {}: {e}", + staging_path.display() + ); + }); + + if let Err(e) = f.write_all(&bytes) { + let _ = std::fs::remove_file(&staging_path); + panic!( + "failed to write staging file {}: {e}", + staging_path.display() + ); + } + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if let Err(e) = f.set_permissions(std::fs::Permissions::from_mode(0o755)) { + let _ = std::fs::remove_file(&staging_path); + panic!("failed to chmod {}: {e}", staging_path.display()); + } + } + + // Backdate the staged binary to the Unix epoch before it lands. We emit + // `cargo:rerun-if-changed` on `final_path` (see caller) so a *deleted* + // cache binary forces a re-extract — but cargo stamps the build-script + // `output` reference when the script is spawned, seconds before this + // freshly-downloaded binary is written. A current mtime would therefore + // be *newer* than that reference, so the next identical `cargo` + // invocation would see the watched file as "changed" and pointlessly + // rerun build.rs + recompile the crate + relink every downstream crate. + // Pinning to the epoch keeps the file unambiguously older than any real + // build reference; `rename` preserves mtime (same inode), so it lands + // already-backdated and a no-change rebuild stays a true no-op. The + // deleted-file recovery contract is untouched: a missing file can't be + // stat'd, so cargo still treats it as stale and reruns regardless. + // + // Best-effort: a filesystem that refuses the epoch (e.g. FAT's 1980 floor + // clamps it — still older than any real reference) or rejects the call + // just reverts to the pre-fix redundant-rebuild behaviour, never a broken + // build. + if let Err(e) = f.set_modified(std::time::SystemTime::UNIX_EPOCH) { + println!( + "cargo:warning=Could not backdate {} (a redundant rebuild may occur): {e}", + staging_path.display() + ); + } + } + + // Atomic file-replace on both Unix and Windows. If a concurrent build + // already produced the same file the rename overwrites it; the bytes + // are SHA-verified-identical so replacement is safe. + if let Err(e) = std::fs::rename(&staging_path, &final_path) { + let _ = std::fs::remove_file(&staging_path); + panic!( + "failed to rename {} -> {}: {e}", + staging_path.display(), + final_path.display() + ); + } + + // Surface where the binary landed so contributors can find it. Quiet + // on the hot path: the caller's `is_file()` short-circuit (and the + // safety net at the top of this function) means this only fires on a + // true cache miss. + println!( + "cargo:warning=Extracted Copilot CLI to {}", + final_path.display() + ); + + final_path +} + +/// Replace characters outside `[a-zA-Z0-9._-]` with `_` so the version +/// string is always safe to use as a path component. Kept in sync with +/// `embeddedcli::sanitize_version` and `resolve::sanitize_version` so all +/// three resolve to the same cache directory for any given version. +fn sanitize_version(version: &str) -> String { + version + .chars() + .map(|c| match c { + 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' | '-' | '_' => c, + _ => '_', + }) + .collect() +} + +/// Extract the single `binary_name` entry from the release archive. Reused +/// between embed mode's `verify_binary_present_in_archive` and the +/// `extract_to_cache` path used when `bundled-cli` is off. Panics if the +/// entry isn't found — callers have already invoked +/// `verify_binary_present_in_archive`. +fn extract_binary_bytes(archive: &[u8], platform: Platform) -> Vec { + if platform.asset_name.ends_with(".zip") { + let cursor = std::io::Cursor::new(archive); + let mut zip = zip::ZipArchive::new(cursor) + .unwrap_or_else(|e| panic!("failed to open zip archive: {e}")); + for i in 0..zip.len() { + let mut entry = zip + .by_index(i) + .unwrap_or_else(|e| panic!("failed to read zip entry {i}: {e}")); + let name = entry.name().to_string(); + if name == platform.binary_name || name.ends_with(&format!("/{}", platform.binary_name)) + { + let mut bytes = Vec::with_capacity(entry.size() as usize); + std::io::copy(&mut entry, &mut bytes) + .unwrap_or_else(|e| panic!("failed to read zip entry bytes: {e}")); + return bytes; + } + } + } else { + let gz = flate2::read::GzDecoder::new(archive); + let mut tar = tar::Archive::new(gz); + for entry in tar + .entries() + .unwrap_or_else(|e| panic!("failed to read tar entries: {e}")) + { + let mut entry = entry.unwrap_or_else(|e| panic!("failed to read tar entry: {e}")); + let path = entry + .path() + .unwrap_or_else(|e| panic!("failed to read tar entry path: {e}")); + let name = path.to_string_lossy().into_owned(); + if name == platform.binary_name || name.ends_with(&format!("/{}", platform.binary_name)) + { + let mut bytes = Vec::with_capacity(entry.size() as usize); + entry + .read_to_end(&mut bytes) + .unwrap_or_else(|e| panic!("failed to read tar entry bytes: {e}")); + return bytes; + } + } + } + panic!( + "binary `{}` not found in archive `{}`", + platform.binary_name, platform.asset_name + ); +} + +/// Read a file from the download cache, or download it (with retries) and save +/// to cache. Verifies SHA-256 on every path. Evicts stale/corrupt cache entries +/// automatically. Cache I/O failures are treated as cache misses — they never +/// break the build. +fn cached_download( + url: &str, + cache_key: &str, + expected_hash: &str, + cache_dir: &Option, +) -> Vec { + if let Some(dir) = cache_dir { + let cached_path = dir.join(cache_key); + if cached_path.is_file() { + match std::fs::read(&cached_path) { + Ok(data) if hex_sha256(&data) == expected_hash => { + // Silent cache hit — nothing to surface. + return data; + } + Ok(_) => { + println!("cargo:warning=Cached archive hash mismatch, re-downloading"); + let _ = std::fs::remove_file(&cached_path); + } + Err(e) => { + println!( + "cargo:warning=Failed to read cache {}, re-downloading: {e}", + cached_path.display() + ); + } + } + } + } + + println!("cargo:warning=Downloading {url}"); + let data = download_with_retry(url); + let actual_hash = hex_sha256(&data); + if actual_hash != expected_hash { + panic!( + "Archive integrity check failed for {url}!\n expected: {expected_hash}\n actual: {actual_hash}\n \ + This could indicate a corrupted download or a supply-chain attack." + ); + } + + if let Some(dir) = cache_dir { + if let Err(e) = std::fs::create_dir_all(dir) { + println!( + "cargo:warning=Failed to create cache directory {}: {e}", + dir.display() + ); + } else { + let cached_path = dir.join(cache_key); + println!("cargo:warning=Caching archive at {}", cached_path.display()); + if let Err(e) = std::fs::write(&cached_path, &data) { + println!( + "cargo:warning=Failed to write cache file {}: {e}", + cached_path.display() + ); + } + } + } + + data +} + +/// Maximum number of HTTP attempts (one initial + this many retries on transient errors). +const MAX_RETRIES: u32 = 3; + +/// Download `url` with bounded retries on transient network errors. Backoff is +/// exponential starting at 1s. 4xx responses fail fast; 5xx and connect/read +/// errors are retried. +fn download_with_retry(url: &str) -> Vec { + let mut attempt = 0u32; + loop { + attempt += 1; + match try_download(url) { + Ok(bytes) => return bytes, + Err(err) if err.transient && attempt <= MAX_RETRIES => { + let backoff = Duration::from_secs(1u64 << (attempt - 1)); + println!( + "cargo:warning=Transient download failure for {url} (attempt {attempt}/{}): {} — retrying in {}s", + MAX_RETRIES + 1, + err.message, + backoff.as_secs(), + ); + std::thread::sleep(backoff); + } + Err(err) => panic!("Failed to download {url}: {}", err.message), + } + } +} + +struct DownloadError { + message: String, + transient: bool, +} + +fn try_download(url: &str) -> Result, DownloadError> { + let connector = native_tls::TlsConnector::new().map_err(|e| DownloadError { + message: format!("native-tls init error: {e}"), + transient: false, + })?; + let agent = ureq::AgentBuilder::new() + .tls_connector(std::sync::Arc::new(connector)) + .timeout_connect(Duration::from_secs(30)) + .timeout_read(Duration::from_secs(120)) + .build(); + + match agent.get(url).call() { + Ok(response) => { + let mut bytes = Vec::new(); + response + .into_reader() + .read_to_end(&mut bytes) + .map_err(|e| DownloadError { + message: format!("read error: {e}"), + transient: true, + })?; + Ok(bytes) + } + // 5xx — server-side, treat as transient. + Err(ureq::Error::Status(code, response)) if (500..600).contains(&code) => { + Err(DownloadError { + message: format!("HTTP {code} {}", response.status_text()), + transient: true, + }) + } + // 4xx — client-side, fail fast. + Err(ureq::Error::Status(code, response)) => Err(DownloadError { + message: format!("HTTP {code} {}", response.status_text()), + transient: false, + }), + // Transport-layer (DNS, connect, TLS, read timeout) — treat as transient. + Err(ureq::Error::Transport(t)) => Err(DownloadError { + message: format!("transport error: {t}"), + transient: true, + }), + } +} + +fn find_sha256_for_asset(sums: &str, asset_name: &str) -> String { + for line in sums.lines() { + // Format: " " (two spaces) + if let Some((hash, name)) = line.split_once(" ") + && name.trim() == asset_name + { + return hash.trim().to_string(); + } + } + panic!("SHA256SUMS.txt does not contain an entry for {asset_name}"); +} + +fn sha256(data: &[u8]) -> [u8; 32] { + let mut hasher = sha2::Sha256::new(); + hasher.update(data); + hasher.finalize().into() +} + +/// Walks the downloaded archive at build time to confirm an entry matching +/// `binary_name` exists. Panics with a clear message if not — defends against +/// silent breakage if the upstream archive layout ever changes. +fn verify_binary_present_in_archive(archive: &[u8], binary_name: &str, asset_name: &str) { + let found = if asset_name.ends_with(".zip") { + archive_contains_zip_entry(archive, binary_name) + } else { + archive_contains_tar_entry(archive, binary_name) + }; + if !found { + panic!( + "Copilot CLI archive `{asset_name}` does not contain an entry named `{binary_name}`. \ + The upstream archive layout may have changed; runtime extraction would fail. \ + Update `verify_binary_present_in_archive` in build.rs and the matching `extract_binary` in src/embeddedcli.rs." + ); + } +} + +fn archive_contains_tar_entry(targz: &[u8], binary_name: &str) -> bool { + let gz = flate2::read::GzDecoder::new(targz); + let mut archive = tar::Archive::new(gz); + let Ok(entries) = archive.entries() else { + return false; + }; + for entry in entries.flatten() { + let Ok(path) = entry.path() else { + continue; + }; + let name = path.to_string_lossy(); + if name == binary_name || name.ends_with(&format!("/{binary_name}")) { + return true; + } + } + false +} + +fn archive_contains_zip_entry(zip_bytes: &[u8], binary_name: &str) -> bool { + let cursor = std::io::Cursor::new(zip_bytes); + let Ok(mut archive) = zip::ZipArchive::new(cursor) else { + return false; + }; + for i in 0..archive.len() { + let Ok(entry) = archive.by_index(i) else { + continue; + }; + let name = entry.name(); + if name == binary_name || name.ends_with(&format!("/{binary_name}")) { + return true; + } + } + false +} + +fn hex_sha256(data: &[u8]) -> String { + sha256(data).iter().map(|b| format!("{b:02x}")).collect() +} diff --git a/rust/scripts/snapshot-bundled-in-process-version.sh b/rust/scripts/snapshot-bundled-in-process-version.sh new file mode 100755 index 0000000000..8743f9d17a --- /dev/null +++ b/rust/scripts/snapshot-bundled-in-process-version.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# +# Snapshot the Copilot CLI version + per-platform npm integrity values for the +# rust crate's bundled-in-process build path. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +RUST_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" +REPO_ROOT="$(cd "${RUST_DIR}/.." && pwd)" +LOCKFILE="${REPO_ROOT}/nodejs/package-lock.json" +OUTPUT="${RUST_DIR}/cli-version-in-process.txt" + +if [[ ! -f "${LOCKFILE}" ]]; then + echo "error: ${LOCKFILE} not found" >&2 + exit 1 +fi + +VERSION="$(node -e "console.log(require('${LOCKFILE}').packages['node_modules/@github/copilot'].version)")" +if [[ -z "${VERSION}" ]]; then + echo "error: could not read @github/copilot version from ${LOCKFILE}" >&2 + exit 1 +fi + +PACKAGES=( + "copilot-darwin-arm64" + "copilot-darwin-x64" + "copilot-linux-arm64" + "copilot-linux-x64" + "copilot-linuxmusl-arm64" + "copilot-linuxmusl-x64" + "copilot-win32-arm64" + "copilot-win32-x64" +) + +declare -A INTEGRITIES +for package in "${PACKAGES[@]}"; do + integrity="$(node -e "console.log(require('${LOCKFILE}').packages['node_modules/@github/${package}'].integrity)")" + if [[ -z "${integrity}" ]]; then + echo "error: package-lock.json missing integrity for @github/${package}" >&2 + exit 1 + fi + INTEGRITIES[$package]="${integrity}" +done + +{ + echo "# Auto-generated by rust/scripts/snapshot-bundled-in-process-version.sh" + echo "# Do not edit. Regenerated by the publish workflow on every release." + echo "version=${VERSION}" + for package in "${PACKAGES[@]}"; do + echo "${package}=${INTEGRITIES[$package]}" + done +} > "${OUTPUT}" + +echo "Wrote ${OUTPUT} (version=${VERSION}, ${#PACKAGES[@]} integrity values)" diff --git a/rust/src/copilot_request_handler.rs b/rust/src/copilot_request_handler.rs index b686b6eada..961ae3876e 100644 --- a/rust/src/copilot_request_handler.rs +++ b/rust/src/copilot_request_handler.rs @@ -140,6 +140,12 @@ pub struct CopilotRequestContext { /// Id of the runtime session that triggered this request, or `None` when it /// was issued outside any session (for example the startup model catalog). pub session_id: Option, + /// Stable per-agent-instance id for the agent trajectory that issued this request. + pub agent_id: Option, + /// Id of the parent agent when this request was issued by a subagent. + pub parent_agent_id: Option, + /// Runtime classification for the interaction that produced this request. + pub interaction_type: Option, /// Transport the runtime would otherwise use. pub transport: CopilotRequestTransport, /// Absolute request URL. @@ -594,6 +600,9 @@ struct ResponseState { #[derive(Default)] struct RequestMeta { session_id: Option, + agent_id: Option, + parent_agent_id: Option, + interaction_type: Option, method: String, url: String, headers: HeaderMap, @@ -630,6 +639,9 @@ impl CopilotRequestExchange { fn set_context(&self, params: LlmInferenceHttpRequestStartRequest) { let _ = self.meta.set(RequestMeta { session_id: params.session_id.map(SessionId::into_inner), + agent_id: params.agent_id, + parent_agent_id: params.parent_agent_id, + interaction_type: params.interaction_type, method: params.method, url: params.url, headers: headers_from_wire(¶ms.headers), @@ -649,6 +661,9 @@ impl CopilotRequestExchange { CopilotRequestContext { request_id: self.request_id.clone(), session_id: meta.session_id.clone(), + agent_id: meta.agent_id.clone(), + parent_agent_id: meta.parent_agent_id.clone(), + interaction_type: meta.interaction_type.clone(), transport: meta.transport, url: meta.url.clone(), headers: meta.headers.clone(), diff --git a/rust/src/embeddedcli.rs b/rust/src/embeddedcli.rs index 56f97e0c0e..40900a4d22 100644 --- a/rust/src/embeddedcli.rs +++ b/rust/src/embeddedcli.rs @@ -2,14 +2,11 @@ //! crate (gated on the `bundled-cli` cargo feature, which is in the default //! feature set). //! -//! build.rs downloads the platform's `copilot-{platform}.{tar.gz,zip}` -//! archive from GitHub Releases, SHA-256 verifies it against the version -//! pinned in `cli-version.txt` (or `../nodejs/package-lock.json` when -//! building inside the github/copilot-sdk repo itself), and embeds the -//! **raw archive bytes** -//! into the consumer's compiled artifact via `include_bytes!()`. Extraction -//! to a real on-disk path is deferred until the first call to -//! [`path`] / [`install_at`]. +//! Normal builds embed the platform release archive from GitHub Releases. +//! Builds with `bundled-in-process` instead embed a minimal archive from the +//! platform npm package containing the CLI executable and native runtime +//! library. Extraction to a real on-disk path is deferred until the first call +//! to [`path`] / [`install_at`]. //! //! The embedded bytes are part of the consumer's signed binary and therefore //! trusted *as the source of truth* — but the bytes that land on disk are not. @@ -31,7 +28,7 @@ // off but still needs to exercise them. #[cfg(any(has_bundled_cli, test))] use std::fs; -#[cfg(all(has_bundled_cli, not(windows)))] +#[cfg(all(has_bundled_cli, any(feature = "bundled-in-process", not(windows))))] use std::io::Read; #[cfg(any(has_bundled_cli, test))] use std::io::Write; @@ -44,8 +41,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; use tracing::{info, warn}; // When the `bundled-cli` cargo feature is enabled and the target platform is -// supported, build.rs generates `bundled_cli.rs` exposing the raw archive -// bytes. The CLI version is exposed crate-wide via the +// supported, build.rs generates `bundled_cli.rs` exposing the selected archive. +// The CLI version is exposed crate-wide via the // `cargo:rustc-env=COPILOT_SDK_CLI_VERSION` emit (see `build.rs`), and the // binary name is OS-derived — so no other generated constants are needed. #[cfg(has_bundled_cli)] @@ -157,8 +154,53 @@ fn default_install_dir(version: &str) -> PathBuf { #[cfg(has_bundled_cli)] const MAX_PUBLISH_ATTEMPTS: u32 = 3; +// Natural platform shared-library name for the in-process FFI runtime. +#[cfg(all(has_bundled_cli, feature = "bundled-in-process", windows))] +const RUNTIME_LIBRARY_NAME: &str = "copilot_runtime.dll"; +#[cfg(all(has_bundled_cli, feature = "bundled-in-process", target_os = "macos"))] +const RUNTIME_LIBRARY_NAME: &str = "libcopilot_runtime.dylib"; +#[cfg(all( + has_bundled_cli, + feature = "bundled-in-process", + not(windows), + not(target_os = "macos") +))] +const RUNTIME_LIBRARY_NAME: &str = "libcopilot_runtime.so"; + #[cfg(has_bundled_cli)] fn install(install_dir: &Path, archive: &[u8]) -> Result { + let final_path = install_cli(install_dir, archive)?; + #[cfg(feature = "bundled-in-process")] + { + install_runtime_library(install_dir, archive)?; + } + Ok(final_path) +} + +#[cfg(all(has_bundled_cli, feature = "bundled-in-process"))] +fn install_runtime_library(install_dir: &Path, archive: &[u8]) -> Result<(), EmbeddedCliError> { + let target = install_dir.join(RUNTIME_LIBRARY_NAME); + if fs::metadata(&target).map(|m| m.len() > 0).unwrap_or(false) { + return Ok(()); + } + let bytes = extract_binary(archive, RUNTIME_LIBRARY_NAME)?; + if bytes.is_empty() { + return Err(EmbeddedCliError::with_message( + EmbeddedCliErrorKind::Verification, + "embedded runtime library is empty", + )); + } + let tmp = write_temp_file(install_dir, &bytes)?; + if let Err(e) = publish(&tmp, &target) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + tracing::debug!(path = %target.display(), "in-process FFI runtime library installed"); + Ok(()) +} + +#[cfg(has_bundled_cli)] +fn install_cli(install_dir: &Path, archive: &[u8]) -> Result { let verbose = std::env::var("COPILOT_CLI_INSTALL_VERBOSE").ok().as_deref() == Some("1"); fs::create_dir_all(install_dir) @@ -438,7 +480,7 @@ fn read_marker_len(marker_path: &Path) -> Option { .ok() } -#[cfg(all(has_bundled_cli, not(windows)))] +#[cfg(all(has_bundled_cli, any(feature = "bundled-in-process", not(windows))))] fn extract_binary(archive: &[u8], binary_name: &str) -> Result, EmbeddedCliError> { let gz = flate2::read::GzDecoder::new(archive); let mut tar = tar::Archive::new(gz); @@ -463,7 +505,7 @@ fn extract_binary(archive: &[u8], binary_name: &str) -> Result, Embedded Err(EmbeddedCliErrorKind::BinaryNotFoundInArchive.into()) } -#[cfg(all(has_bundled_cli, windows))] +#[cfg(all(has_bundled_cli, not(feature = "bundled-in-process"), windows))] fn extract_binary(archive: &[u8], binary_name: &str) -> Result, EmbeddedCliError> { let cursor = std::io::Cursor::new(archive); let mut zip = zip::ZipArchive::new(cursor) @@ -499,9 +541,9 @@ fn sanitize_version(version: &str) -> String { #[allow(dead_code)] enum EmbeddedCliErrorKind { CreateDir, - #[cfg(not(windows))] + #[cfg(any(feature = "bundled-in-process", not(windows)))] Archive, - #[cfg(windows)] + #[cfg(all(not(feature = "bundled-in-process"), windows))] Zip, BinaryNotFoundInArchive, Io, @@ -519,9 +561,9 @@ impl std::fmt::Display for EmbeddedCliErrorKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { EmbeddedCliErrorKind::CreateDir => f.write_str("failed to create install directory"), - #[cfg(not(windows))] + #[cfg(any(feature = "bundled-in-process", not(windows)))] EmbeddedCliErrorKind::Archive => f.write_str("failed to read archive entry"), - #[cfg(windows)] + #[cfg(all(not(feature = "bundled-in-process"), windows))] EmbeddedCliErrorKind::Zip => f.write_str("failed to read zip archive"), EmbeddedCliErrorKind::BinaryNotFoundInArchive => { f.write_str("CLI binary not found in embedded archive") @@ -626,6 +668,33 @@ impl std::error::Error for EmbeddedCliError { mod tests { use super::*; + #[cfg(all(has_bundled_cli, feature = "bundled-in-process"))] + #[test] + fn embedded_archive_contains_only_expected_files() { + let gz = flate2::read::GzDecoder::new(build_time::CLI_ARCHIVE); + let mut archive = tar::Archive::new(gz); + let mut names: Vec = archive + .entries() + .expect("archive entries") + .map(|entry| { + entry + .expect("archive entry") + .path() + .expect("archive path") + .to_string_lossy() + .into_owned() + }) + .collect(); + names.sort(); + + let mut expected = vec![ + CLI_BINARY_NAME.to_string(), + RUNTIME_LIBRARY_NAME.to_string(), + ]; + expected.sort(); + assert_eq!(names, expected); + } + /// Bytes whose header looks like a valid executable image on the host /// platform, so `looks_like_valid_image` accepts them. `extra` padding /// bytes follow the magic so size checks have something to disagree about. diff --git a/rust/src/errors.rs b/rust/src/errors.rs index 5690f6412c..6e05bbfae1 100644 --- a/rust/src/errors.rs +++ b/rust/src/errors.rs @@ -63,6 +63,12 @@ pub enum ProtocolErrorKind { max: u32, }, + /// The CLI server reported a protocol version that can't be represented by the SDK. + InvalidProtocolVersion { + /// Version reported by the server. + server: i64, + }, + /// The CLI server's protocol version changed between calls. VersionChanged { /// Previously negotiated version. @@ -94,6 +100,9 @@ impl fmt::Display for ProtocolErrorKind { "version mismatch: server={server}, supported={min}\u{2013}{max}" ) } + ProtocolErrorKind::InvalidProtocolVersion { server } => { + write!(f, "invalid protocol version: server={server}") + } ProtocolErrorKind::VersionChanged { previous, current } => { write!(f, "version changed: was {previous}, now {current}") } diff --git a/rust/src/ffi.rs b/rust/src/ffi.rs new file mode 100644 index 0000000000..f784b1a6d1 --- /dev/null +++ b/rust/src/ffi.rs @@ -0,0 +1,633 @@ +//! In-process FFI transport: hosts the Copilot runtime by loading its native +//! library and speaking JSON-RPC over its C ABI, +//! instead of spawning a CLI child process and communicating over stdio/TCP. +//! +//! The runtime's `host_start` export spawns the residual TypeScript worker +//! itself — the packaged single-file CLI (`copilot --embedded-host`) or, for +//! dev, `node dist-cli/index.js --embedded-host`. JSON-RPC frames are pumped +//! across the ABI: writes go to `connection_write`; inbound frames arrive on a +//! native callback that feeds an async reader. The framing is unchanged — the +//! same LSP `Content-Length:` frames the stdio transport uses. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll}; + +use libloading::Library; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::sync::mpsc; +use tracing::debug; + +use crate::{Error, ErrorKind}; + +type OutboundCallback = unsafe extern "C" fn(*mut c_void, *const u8, usize); +type HostStartFn = unsafe extern "C" fn(*const u8, usize, *const u8, usize) -> u32; +type HostShutdownFn = unsafe extern "C" fn(u32) -> bool; +#[allow(clippy::type_complexity)] +type ConnectionOpenFn = unsafe extern "C" fn( + u32, + OutboundCallback, + *mut c_void, + *const u8, + usize, + *const u8, + usize, + *const u8, + usize, +) -> u32; +type ConnectionWriteFn = unsafe extern "C" fn(u32, *const u8, usize) -> bool; +type ConnectionCloseFn = unsafe extern "C" fn(u32) -> bool; + +/// State handed to the native side as `user_data` so the outbound callback can +/// route inbound frames back to the reader. +struct CallbackState { + tx: mpsc::UnboundedSender>, + active_callbacks: AtomicUsize, + closing: AtomicBool, +} + +extern "C" fn on_outbound(user_data: *mut c_void, bytes: *const u8, len: usize) { + if user_data.is_null() || bytes.is_null() || len == 0 { + return; + } + let state = unsafe { &*(user_data as *const CallbackState) }; + state.active_callbacks.fetch_add(1, Ordering::SeqCst); + if state.closing.load(Ordering::SeqCst) { + state.active_callbacks.fetch_sub(1, Ordering::SeqCst); + return; + } + let slice = unsafe { std::slice::from_raw_parts(bytes, len) }; + let _ = state.tx.send(slice.to_vec()); + state.active_callbacks.fetch_sub(1, Ordering::SeqCst); +} + +/// Bound exports and connection lifecycle state, shared between the +/// [`FfiWriter`] and the owning [`Client`]. The cdylib itself is loaded +/// process-globally and never unloaded (see [`load_library`]), so this holds +/// only the bound fn pointers and connection state. +pub(crate) struct FfiShared { + host_shutdown: HostShutdownFn, + connection_write: ConnectionWriteFn, + connection_close: ConnectionCloseFn, + server_id: AtomicU32, + connection_id: AtomicU32, + callback_state: AtomicPtr, + closed: AtomicBool, + operation_lock: parking_lot::Mutex<()>, + library_path: PathBuf, +} + +// The raw fn pointers and the boxed callback state are safe to move across +// threads: the native side copies buffers synchronously and the callback only +// forwards to a thread-safe channel sender. +unsafe impl Send for FfiShared {} +unsafe impl Sync for FfiShared {} + +impl FfiShared { + /// Close the connection, shut the host down, and free the callback state. + /// Idempotent; called from [`Client::stop`], drop, and on startup failure. + pub(crate) fn close(&self) { + let _operation = self.operation_lock.lock(); + if self.closed.swap(true, Ordering::SeqCst) { + return; + } + let state = self.callback_state.load(Ordering::SeqCst); + if !state.is_null() { + unsafe { &*state }.closing.store(true, Ordering::SeqCst); + } + let conn = self.connection_id.swap(0, Ordering::SeqCst); + if conn != 0 { + unsafe { (self.connection_close)(conn) }; + } + let server = self.server_id.swap(0, Ordering::SeqCst); + if server != 0 { + unsafe { (self.host_shutdown)(server) }; + } + // Free the callback state only after the connection is closed and the + // host is shut down, so native can no longer invoke the callback. + let state = self + .callback_state + .swap(std::ptr::null_mut(), Ordering::SeqCst); + if !state.is_null() { + while unsafe { &*state }.active_callbacks.load(Ordering::SeqCst) != 0 { + std::thread::yield_now(); + } + drop(unsafe { Box::from_raw(state) }); + } + debug!(library = %self.library_path.display(), "FFI runtime connection closed"); + } + + fn write_frame(&self, frame: &[u8]) -> bool { + let _operation = self.operation_lock.lock(); + if self.closed.load(Ordering::SeqCst) { + return false; + } + let conn = self.connection_id.load(Ordering::SeqCst); + if conn == 0 { + return false; + } + unsafe { (self.connection_write)(conn, frame.as_ptr(), frame.len()) } + } +} + +impl Drop for FfiShared { + fn drop(&mut self) { + self.close(); + } +} + +/// Read side of the FFI transport, fed by the native outbound callback via an +/// unbounded channel. Implements [`AsyncRead`] for the JSON-RPC read loop. +pub(crate) struct FfiReader { + rx: mpsc::UnboundedReceiver>, + leftover: Vec, + pos: usize, +} + +impl AsyncRead for FfiReader { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + if self.pos >= self.leftover.len() { + match self.rx.poll_recv(cx) { + Poll::Ready(Some(chunk)) => { + self.leftover = chunk; + self.pos = 0; + } + Poll::Ready(None) => return Poll::Ready(Ok(())), + Poll::Pending => return Poll::Pending, + } + } + let available = self.leftover.len() - self.pos; + let n = available.min(buf.remaining()); + let start = self.pos; + buf.put_slice(&self.leftover[start..start + n]); + self.pos += n; + Poll::Ready(Ok(())) + } +} + +/// Write side of the FFI transport. Each frame is forwarded synchronously to +/// the native `connection_write` export (native copies before returning). +pub(crate) struct FfiWriter { + shared: Arc, +} + +impl AsyncWrite for FfiWriter { + fn poll_write( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + if self.shared.write_frame(buf) { + Poll::Ready(Ok(buf.len())) + } else { + Poll::Ready(Err(std::io::Error::new( + std::io::ErrorKind::BrokenPipe, + "failed to write a frame to the in-process runtime connection", + ))) + } + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } +} + +/// Prepared FFI host: the bound cdylib exports plus the spawn arguments needed +/// to start the runtime worker. The cdylib is loaded process-globally and never +/// unloaded (see [`load_library`]). +pub(crate) struct FfiHost { + library_path: PathBuf, + entrypoint: PathBuf, + environment: Vec<(String, String)>, + args: Vec, + host_start: HostStartFn, + host_shutdown: HostShutdownFn, + connection_open: ConnectionOpenFn, + connection_write: ConnectionWriteFn, + connection_close: ConnectionCloseFn, +} + +// SAFETY: as for `FfiShared` — the bound exports are plain fn pointers, safe to +// move to the blocking thread that starts the host. +unsafe impl Send for FfiHost {} + +impl FfiHost { + /// Load the cdylib next to `entrypoint` and bind its exports. + /// + /// `entrypoint` is the packaged single-file CLI binary or, for dev, a + /// `.js` file launched via `node`. The native library is resolved relative + /// to the entrypoint directory, supporting both packaged and development + /// layouts. + pub(crate) fn create( + entrypoint: &Path, + environment: Vec<(String, String)>, + args: Vec, + ) -> Result { + let entrypoint = std::fs::canonicalize(entrypoint) + .map(path_for_child_process) + .map_err(|e| { + Error::with_message( + ErrorKind::InvalidConfig, + format!( + "failed to resolve in-process CLI entrypoint '{}': {e}", + entrypoint.display() + ), + ) + })?; + let library_path = + std::fs::canonicalize(resolve_library_path(&entrypoint)?).map_err(|e| { + Error::with_message( + ErrorKind::InvalidConfig, + format!("failed to resolve in-process runtime library: {e}"), + ) + })?; + let lib = load_library(&library_path)?; + + let host_start = *bind::(lib, b"copilot_runtime_host_start\0", &library_path)?; + let host_shutdown = + *bind::(lib, b"copilot_runtime_host_shutdown\0", &library_path)?; + let connection_open = + *bind::(lib, b"copilot_runtime_connection_open\0", &library_path)?; + let connection_write = + *bind::(lib, b"copilot_runtime_connection_write\0", &library_path)?; + let connection_close = + *bind::(lib, b"copilot_runtime_connection_close\0", &library_path)?; + + Ok(Self { + library_path, + entrypoint, + environment, + args, + host_start, + host_shutdown, + connection_open, + connection_write, + connection_close, + }) + } + + /// Start the runtime worker and open the FFI JSON-RPC connection. + /// + /// `host_start` blocks until the worker connects back and signals + /// readiness (up to ~30s), and must not run on an async executor thread, so + /// the blocking handshake is offloaded to [`tokio::task::spawn_blocking`]. + pub(crate) async fn start(self) -> Result<(FfiReader, FfiWriter, Arc), Error> { + tokio::task::spawn_blocking(move || self.start_blocking()) + .await + .map_err(|e| { + Error::with_message( + ErrorKind::InvalidConfig, + format!("in-process runtime startup task failed: {e}"), + ) + })? + } + + fn start_blocking(self) -> Result<(FfiReader, FfiWriter, Arc), Error> { + let argv = build_argv_json(&self.entrypoint, &self.args); + let env = build_env_json(&self.environment); + + let (env_ptr, env_len) = match &env { + Some(bytes) => (bytes.as_ptr(), bytes.len()), + None => (std::ptr::null(), 0), + }; + + let server_id = unsafe { (self.host_start)(argv.as_ptr(), argv.len(), env_ptr, env_len) }; + + if server_id == 0 { + return Err(Error::with_message( + ErrorKind::InvalidConfig, + format!( + "copilot_runtime_host_start failed (library '{}', entrypoint '{}')", + self.library_path.display(), + self.entrypoint.display() + ), + )); + } + + let (tx, rx) = mpsc::unbounded_channel::>(); + let state_ptr = Box::into_raw(Box::new(CallbackState { + tx, + active_callbacks: AtomicUsize::new(0), + closing: AtomicBool::new(false), + })); + let connection_id = unsafe { + (self.connection_open)( + server_id, + on_outbound, + state_ptr as *mut c_void, + std::ptr::null(), + 0, + std::ptr::null(), + 0, + std::ptr::null(), + 0, + ) + }; + if connection_id == 0 { + drop(unsafe { Box::from_raw(state_ptr) }); + unsafe { (self.host_shutdown)(server_id) }; + return Err(Error::with_message( + ErrorKind::InvalidConfig, + "copilot_runtime_connection_open failed", + )); + } + + let shared = Arc::new(FfiShared { + host_shutdown: self.host_shutdown, + connection_write: self.connection_write, + connection_close: self.connection_close, + server_id: AtomicU32::new(server_id), + connection_id: AtomicU32::new(connection_id), + callback_state: AtomicPtr::new(state_ptr), + closed: AtomicBool::new(false), + operation_lock: parking_lot::Mutex::new(()), + library_path: self.library_path.clone(), + }); + + debug!( + library = %self.library_path.display(), + server_id, connection_id, "FFI runtime host started" + ); + + let reader = FfiReader { + rx, + leftover: Vec::new(), + pos: 0, + }; + let writer = FfiWriter { + shared: Arc::clone(&shared), + }; + Ok((reader, writer, shared)) + } +} + +fn bind<'lib, T>( + lib: &'lib Library, + symbol: &[u8], + library_path: &Path, +) -> Result, Error> { + match unsafe { lib.get::(symbol) } { + Ok(export) => Ok(export), + Err(e) => Err(Error::with_message( + ErrorKind::InvalidConfig, + format!( + "in-process runtime library '{}' is missing an expected export ({}): {e}", + library_path.display(), + String::from_utf8_lossy(symbol.strip_suffix(b"\0").unwrap_or(symbol)) + ), + )), + } +} + +/// Loads the runtime cdylib once per process and never unloads it, returning a +/// `'static` reference. Subsequent loads of the same path reuse the first +/// handle. +/// +/// The library stays mapped because native worker threads can outlive an +/// individual connection teardown. +fn load_library(library_path: &Path) -> Result<&'static Library, Error> { + static LIBRARIES: OnceLock>> = + OnceLock::new(); + let cache = LIBRARIES.get_or_init(|| parking_lot::Mutex::new(HashMap::new())); + + let mut guard = cache.lock(); + if let Some(lib) = guard.get(library_path) { + return Ok(*lib); + } + + let lib = unsafe { Library::new(library_path) }.map_err(|e| { + Error::with_message( + ErrorKind::InvalidConfig, + format!( + "failed to load in-process runtime library '{}': {e}", + library_path.display() + ), + ) + })?; + // Leak the library so it is never unloaded for the process lifetime. + let leaked: &'static Library = Box::leak(Box::new(lib)); + guard.insert(library_path.to_path_buf(), leaked); + Ok(leaked) +} + +/// The natural platform shared-library file name for the runtime cdylib — the +/// `.node` file renamed to what the Rust cdylib would be called on this OS. +fn natural_library_name() -> &'static str { + if cfg!(windows) { + "copilot_runtime.dll" + } else if cfg!(target_os = "macos") { + "libcopilot_runtime.dylib" + } else { + "libcopilot_runtime.so" + } +} + +/// The package prebuild folder name for the current host. +pub(crate) fn prebuilds_folder() -> Option { + let platform = if cfg!(target_os = "windows") { + "win32" + } else if cfg!(target_os = "macos") { + "darwin" + } else if cfg!(target_os = "linux") { + "linux" + } else { + return None; + }; + let arch = if cfg!(target_arch = "x86_64") { + "x64" + } else if cfg!(target_arch = "aarch64") { + "arm64" + } else { + return None; + }; + Some(format!("{platform}-{arch}")) +} + +fn resolve_library_path(entrypoint: &Path) -> Result { + let dir = entrypoint.parent().ok_or_else(|| { + Error::with_message( + ErrorKind::InvalidConfig, + format!( + "could not determine directory for CLI entrypoint '{}'", + entrypoint.display() + ), + ) + })?; + + // Bundled/flat layout: natural shared-library name next to the CLI. + let flat = dir.join(natural_library_name()); + if flat.is_file() { + return Ok(flat); + } + + // Development package layout. + let prebuilds = + prebuilds_folder().map(|folder| dir.join("prebuilds").join(folder).join("runtime.node")); + if let Some(prebuilds_path) = &prebuilds + && prebuilds_path.is_file() + { + return Ok(prebuilds_path.clone()); + } + + Err(Error::with_message( + ErrorKind::BinaryNotFound { + name: natural_library_name().into(), + hint: Some(format!( + "native runtime library not found next to '{}'. Enable the \ + `bundled-in-process` feature or set COPILOT_CLI_PATH to a compatible CLI package.", + entrypoint.display() + )), + }, + "native runtime library not found", + )) +} + +#[cfg(windows)] +fn path_for_child_process(path: PathBuf) -> PathBuf { + use std::ffi::OsString; + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + + const VERBATIM_PREFIX: &[u16] = &[b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; + const UNC_PREFIX: &[u16] = &[b'U' as u16, b'N' as u16, b'C' as u16, b'\\' as u16]; + + let encoded: Vec = path.as_os_str().encode_wide().collect(); + let Some(stripped) = encoded.strip_prefix(VERBATIM_PREFIX) else { + return path; + }; + let normalized = if let Some(unc_path) = stripped.strip_prefix(UNC_PREFIX) { + let mut result = vec![b'\\' as u16, b'\\' as u16]; + result.extend_from_slice(unc_path); + result + } else { + stripped.to_vec() + }; + PathBuf::from(OsString::from_wide(&normalized)) +} + +#[cfg(not(windows))] +fn path_for_child_process(path: PathBuf) -> PathBuf { + path +} + +fn build_argv_json(entrypoint: &Path, extra_args: &[String]) -> Vec { + // A `.js` entrypoint (dev / dist-cli) is launched via node; the packaged + // single-file CLI binary embeds its own Node and is invoked directly. + let entrypoint_str = entrypoint.to_string_lossy().into_owned(); + let is_js = entrypoint + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| ext.eq_ignore_ascii_case("js")); + let mut argv: Vec = if is_js { + vec![ + "node".to_string(), + entrypoint_str, + "--embedded-host".to_string(), + "--no-auto-update".to_string(), + ] + } else { + vec![ + entrypoint_str, + "--embedded-host".to_string(), + "--no-auto-update".to_string(), + ] + }; + argv.extend_from_slice(extra_args); + serde_json::to_vec(&argv).expect("argv serializes") +} + +fn build_env_json(environment: &[(String, String)]) -> Option> { + if environment.is_empty() { + return None; + } + let map: serde_json::Map = environment + .iter() + .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone()))) + .collect(); + Some(serde_json::to_vec(&map).expect("env serializes")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn argv_pins_worker_and_appends_client_options() { + let argv: Vec = serde_json::from_slice(&build_argv_json( + Path::new("copilot"), + &["--log-level".into(), "debug".into()], + )) + .unwrap(); + + assert_eq!( + argv, + [ + "copilot", + "--embedded-host", + "--no-auto-update", + "--log-level", + "debug" + ] + ); + } + + #[test] + fn javascript_entrypoint_uses_node() { + let argv: Vec = + serde_json::from_slice(&build_argv_json(Path::new("index.js"), &[])).unwrap(); + + assert_eq!( + argv, + ["node", "index.js", "--embedded-host", "--no-auto-update"] + ); + } + + #[cfg(windows)] + #[test] + fn child_process_path_removes_windows_verbatim_prefix() { + assert_eq!( + path_for_child_process(PathBuf::from(r"\\?\D:\a\copilot-sdk\index.js")), + PathBuf::from(r"D:\a\copilot-sdk\index.js") + ); + assert_eq!( + path_for_child_process(PathBuf::from(r"\\?\UNC\server\share\copilot-sdk\index.js")), + PathBuf::from(r"\\server\share\copilot-sdk\index.js") + ); + } + + #[test] + fn environment_is_omitted_when_empty() { + assert_eq!(build_env_json(&[]), None); + } + + #[test] + fn environment_serializes_worker_overrides() { + let env: serde_json::Value = serde_json::from_slice( + &build_env_json(&[ + ("COPILOT_HOME".into(), "state".into()), + ("COPILOT_DISABLE_KEYTAR".into(), "1".into()), + ]) + .unwrap(), + ) + .unwrap(); + + assert_eq!( + env, + serde_json::json!({ + "COPILOT_HOME": "state", + "COPILOT_DISABLE_KEYTAR": "1", + }) + ); + } +} diff --git a/rust/src/generated/api_types.rs b/rust/src/generated/api_types.rs index b1d85c0a58..e243ec1dc2 100644 --- a/rust/src/generated/api_types.rs +++ b/rust/src/generated/api_types.rs @@ -1,6 +1,7 @@ //! Auto-generated from api.schema.json — do not edit manually. #![allow(clippy::large_enum_variant)] +#![allow(deprecated)] #![allow(dead_code)] #![allow(rustdoc::invalid_html_tags)] @@ -10,8 +11,8 @@ use serde::{Deserialize, Serialize}; use super::session_events::{ AbortReason, ContextTier, McpServerSource, McpServerStatus, PermissionPromptRequest, - PermissionRule, ReasoningSummary, SessionMode, ShutdownType, SkillSource, - UserToolSessionApproval, + PermissionRule, ReasoningSummary, SessionLimitsConfig, SessionMode, ShutdownType, SkillSource, + UserToolSessionApproval, Verbosity, }; use crate::types::{RequestId, SessionEvent, SessionId}; @@ -91,8 +92,14 @@ pub mod rpc_methods { pub const INSTRUCTIONS_DISCOVER: &str = "instructions.discover"; /// `instructions.getDiscoveryPaths` pub const INSTRUCTIONS_GETDISCOVERYPATHS: &str = "instructions.getDiscoveryPaths"; + /// `commands.list` + pub const COMMANDS_LIST: &str = "commands.list"; /// `user.settings.reload` pub const USER_SETTINGS_RELOAD: &str = "user.settings.reload"; + /// `user.settings.get` + pub const USER_SETTINGS_GET: &str = "user.settings.get"; + /// `user.settings.set` + pub const USER_SETTINGS_SET: &str = "user.settings.set"; /// `runtime.shutdown` pub const RUNTIME_SHUTDOWN: &str = "runtime.shutdown"; /// `sessionFs.setProvider` @@ -155,8 +162,6 @@ pub mod rpc_methods { pub const SESSIONS_STOPREMOTECONTROL: &str = "sessions.stopRemoteControl"; /// `sessions.getRemoteControlStatus` pub const SESSIONS_GETREMOTECONTROLSTATUS: &str = "sessions.getRemoteControlStatus"; - /// `sessions.pollSpawnedSessions` - pub const SESSIONS_POLLSPAWNEDSESSIONS: &str = "sessions.pollSpawnedSessions"; /// `sessions.registerExtensionToolsOnSession` pub const SESSIONS_REGISTEREXTENSIONTOOLSONSESSION: &str = "sessions.registerExtensionToolsOnSession"; @@ -168,14 +173,18 @@ pub mod rpc_methods { pub const SESSION_SUSPEND: &str = "session.suspend"; /// `session.send` pub const SESSION_SEND: &str = "session.send"; + /// `session.sendMessages` + pub const SESSION_SENDMESSAGES: &str = "session.sendMessages"; /// `session.abort` pub const SESSION_ABORT: &str = "session.abort"; /// `session.shutdown` pub const SESSION_SHUTDOWN: &str = "session.shutdown"; - /// `session.auth.getStatus` - pub const SESSION_AUTH_GETSTATUS: &str = "session.auth.getStatus"; - /// `session.auth.setCredentials` - pub const SESSION_AUTH_SETCREDENTIALS: &str = "session.auth.setCredentials"; + /// `session.gitHubAuth.getStatus` + pub const SESSION_GITHUBAUTH_GETSTATUS: &str = "session.gitHubAuth.getStatus"; + /// `session.gitHubAuth.setCredentials` + pub const SESSION_GITHUBAUTH_SETCREDENTIALS: &str = "session.gitHubAuth.setCredentials"; + /// `session.debug.collectLogs` + pub const SESSION_DEBUG_COLLECTLOGS: &str = "session.debug.collectLogs"; /// `session.canvas.list` pub const SESSION_CANVAS_LIST: &str = "session.canvas.list"; /// `session.canvas.listOpen` @@ -231,6 +240,11 @@ pub mod rpc_methods { pub const SESSION_WORKSPACES_SAVELARGEPASTE: &str = "session.workspaces.saveLargePaste"; /// `session.workspaces.diff` pub const SESSION_WORKSPACES_DIFF: &str = "session.workspaces.diff"; + /// `session.completions.getTriggerCharacters` + pub const SESSION_COMPLETIONS_GETTRIGGERCHARACTERS: &str = + "session.completions.getTriggerCharacters"; + /// `session.completions.request` + pub const SESSION_COMPLETIONS_REQUEST: &str = "session.completions.request"; /// `session.instructions.getSources` pub const SESSION_INSTRUCTIONS_GETSOURCES: &str = "session.instructions.getSources"; /// `session.fleet.start` @@ -314,13 +328,14 @@ pub mod rpc_methods { pub const SESSION_MCP_UNREGISTEREXTERNALCLIENT: &str = "session.mcp.unregisterExternalClient"; /// `session.mcp.isServerRunning` pub const SESSION_MCP_ISSERVERRUNNING: &str = "session.mcp.isServerRunning"; - /// `session.mcp.oauth.respond` - pub const SESSION_MCP_OAUTH_RESPOND: &str = "session.mcp.oauth.respond"; /// `session.mcp.oauth.handlePendingRequest` pub const SESSION_MCP_OAUTH_HANDLEPENDINGREQUEST: &str = "session.mcp.oauth.handlePendingRequest"; /// `session.mcp.oauth.login` pub const SESSION_MCP_OAUTH_LOGIN: &str = "session.mcp.oauth.login"; + /// `session.mcp.headers.handlePendingHeadersRefreshRequest` + pub const SESSION_MCP_HEADERS_HANDLEPENDINGHEADERSREFRESHREQUEST: &str = + "session.mcp.headers.handlePendingHeadersRefreshRequest"; /// `session.mcp.apps.readResource` pub const SESSION_MCP_APPS_READRESOURCE: &str = "session.mcp.apps.readResource"; /// `session.mcp.apps.listTools` @@ -333,6 +348,12 @@ pub mod rpc_methods { pub const SESSION_MCP_APPS_GETHOSTCONTEXT: &str = "session.mcp.apps.getHostContext"; /// `session.mcp.apps.diagnose` pub const SESSION_MCP_APPS_DIAGNOSE: &str = "session.mcp.apps.diagnose"; + /// `session.mcp.resources.read` + pub const SESSION_MCP_RESOURCES_READ: &str = "session.mcp.resources.read"; + /// `session.mcp.resources.list` + pub const SESSION_MCP_RESOURCES_LIST: &str = "session.mcp.resources.list"; + /// `session.mcp.resources.listTemplates` + pub const SESSION_MCP_RESOURCES_LISTTEMPLATES: &str = "session.mcp.resources.listTemplates"; /// `session.plugins.list` pub const SESSION_PLUGINS_LIST: &str = "session.plugins.list"; /// `session.plugins.reload` @@ -394,6 +415,9 @@ pub mod rpc_methods { /// `session.ui.handlePendingAutoModeSwitch` pub const SESSION_UI_HANDLEPENDINGAUTOMODESWITCH: &str = "session.ui.handlePendingAutoModeSwitch"; + /// `session.ui.handlePendingSessionLimitsExhausted` + pub const SESSION_UI_HANDLEPENDINGSESSIONLIMITSEXHAUSTED: &str = + "session.ui.handlePendingSessionLimitsExhausted"; /// `session.ui.handlePendingExitPlanMode` pub const SESSION_UI_HANDLEPENDINGEXITPLANMODE: &str = "session.ui.handlePendingExitPlanMode"; /// `session.ui.registerDirectAutoModeSwitchHandler` @@ -463,6 +487,12 @@ pub mod rpc_methods { pub const SESSION_METADATA_ACTIVITY: &str = "session.metadata.activity"; /// `session.metadata.contextInfo` pub const SESSION_METADATA_CONTEXTINFO: &str = "session.metadata.contextInfo"; + /// `session.metadata.getContextAttribution` + pub const SESSION_METADATA_GETCONTEXTATTRIBUTION: &str = + "session.metadata.getContextAttribution"; + /// `session.metadata.getContextHeaviestMessages` + pub const SESSION_METADATA_GETCONTEXTHEAVIESTMESSAGES: &str = + "session.metadata.getContextHeaviestMessages"; /// `session.metadata.recordContextChange` pub const SESSION_METADATA_RECORDCONTEXTCHANGE: &str = "session.metadata.recordContextChange"; /// `session.metadata.setWorkingDirectory` @@ -470,6 +500,10 @@ pub mod rpc_methods { /// `session.metadata.recomputeContextTokens` pub const SESSION_METADATA_RECOMPUTECONTEXTTOKENS: &str = "session.metadata.recomputeContextTokens"; + /// `session.settings.snapshot` + pub const SESSION_SETTINGS_SNAPSHOT: &str = "session.settings.snapshot"; + /// `session.settings.evaluatePredicate` + pub const SESSION_SETTINGS_EVALUATEPREDICATE: &str = "session.settings.evaluatePredicate"; /// `session.shell.exec` pub const SESSION_SHELL_EXEC: &str = "session.shell.exec"; /// `session.shell.kill` @@ -511,6 +545,10 @@ pub mod rpc_methods { pub const SESSION_REMOTE_DISABLE: &str = "session.remote.disable"; /// `session.remote.notifySteerableChanged` pub const SESSION_REMOTE_NOTIFYSTEERABLECHANGED: &str = "session.remote.notifySteerableChanged"; + /// `session.visibility.get` + pub const SESSION_VISIBILITY_GET: &str = "session.visibility.get"; + /// `session.visibility.set` + pub const SESSION_VISIBILITY_SET: &str = "session.visibility.set"; /// `session.schedule.list` pub const SESSION_SCHEDULE_LIST: &str = "session.schedule.list"; /// `session.schedule.stop` @@ -583,7 +621,14 @@ pub struct AbortResult { pub success: bool, } -/// Schema for the `AccountAllUsers` type. +/// Authenticated account entry returned by `account.getAllUsers`, with auth info and an optional associated token. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountAllUsers { @@ -595,6 +640,13 @@ pub struct AccountAllUsers { } /// Current authentication state +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountGetCurrentAuthResult { @@ -607,6 +659,13 @@ pub struct AccountGetCurrentAuthResult { } /// Optional GitHub token used to look up quota for a specific user instead of the global auth context. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountGetQuotaRequest { @@ -615,7 +674,14 @@ pub struct AccountGetQuotaRequest { pub git_hub_token: Option, } -/// Schema for the `AccountQuotaSnapshot` type. +/// Quota usage snapshot for a Copilot quota type, including entitlement, used requests, overage, reset date, and remaining percentage. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountQuotaSnapshot { @@ -639,6 +705,13 @@ pub struct AccountQuotaSnapshot { } /// Quota usage snapshots for the resolved user, keyed by quota type. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountGetQuotaResult { @@ -647,6 +720,13 @@ pub struct AccountGetQuotaResult { } /// Credentials to store after successful authentication +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountLoginRequest { @@ -659,6 +739,13 @@ pub struct AccountLoginRequest { } /// Result of a successful login; throws on failure +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountLoginResult { @@ -667,6 +754,13 @@ pub struct AccountLoginResult { } /// User to log out +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountLogoutRequest { @@ -675,6 +769,13 @@ pub struct AccountLogoutRequest { } /// Logout result indicating if more users remain +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AccountLogoutResult { @@ -682,7 +783,7 @@ pub struct AccountLogoutResult { pub has_more_users: bool, } -/// Schema for the `AgentDiscoveryPath` type. +/// Canonical directory where custom agents can be discovered or created, with scope, preference, and optional project path. /// ///
/// @@ -719,7 +820,7 @@ pub struct AgentDiscoveryPathList { pub paths: Vec, } -/// Schema for the `AgentInfo` type. +/// Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. /// ///
/// @@ -1094,13 +1195,16 @@ pub struct AgentsGetDiscoveryPathsRequest { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AllowAllPermissionSetResult { - /// Authoritative allow-all state after the mutation + /// Authoritative full allow-all state after the mutation pub enabled: bool, + /// Authoritative allow-all mode after the mutation + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, /// Whether the operation succeeded pub success: bool, } -/// Current full allow-all permission state. +/// Current allow-all permission mode. /// ///
/// @@ -1113,9 +1217,19 @@ pub struct AllowAllPermissionSetResult { pub struct AllowAllPermissionState { /// Whether full allow-all permissions are currently active pub enabled: bool, + /// Current allow-all mode + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, } -/// Schema for the `CopilotUserResponseEndpoints` type. +/// Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopilotUserResponseEndpoints { @@ -1129,116 +1243,180 @@ pub struct CopilotUserResponseEndpoints { pub telemetry: Option, } -/// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. +/// Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopilotUserResponseQuotaSnapshotsChat { + /// Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. #[serde(skip_serializing_if = "Option::is_none")] pub entitlement: Option, + /// Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] pub has_quota: Option, + /// Count of additional pay-per-request usage consumed this period beyond the entitlement. #[serde(rename = "overage_count", skip_serializing_if = "Option::is_none")] pub overage_count: Option, + /// Whether usage may continue at pay-per-request rates once the entitlement is exhausted. #[serde(rename = "overage_permitted", skip_serializing_if = "Option::is_none")] pub overage_permitted: Option, + /// Percentage of the entitlement remaining at the snapshot timestamp. #[serde(rename = "percent_remaining", skip_serializing_if = "Option::is_none")] pub percent_remaining: Option, + /// Identifier of the quota bucket this snapshot describes. #[serde(rename = "quota_id", skip_serializing_if = "Option::is_none")] pub quota_id: Option, + /// Amount of quota remaining at the snapshot timestamp. #[serde(rename = "quota_remaining", skip_serializing_if = "Option::is_none")] pub quota_remaining: Option, + /// Unix epoch time, in seconds, when this quota next resets. #[serde(rename = "quota_reset_at", skip_serializing_if = "Option::is_none")] pub quota_reset_at: Option, + /// Remaining entitlement/quota amount at the snapshot timestamp. #[serde(skip_serializing_if = "Option::is_none")] pub remaining: Option, + /// UTC timestamp when this snapshot was captured. #[serde(rename = "timestamp_utc", skip_serializing_if = "Option::is_none")] pub timestamp_utc: Option, + /// Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. #[serde( rename = "token_based_billing", skip_serializing_if = "Option::is_none" )] pub token_based_billing: Option, + /// Whether the entitlement for this category is unlimited. #[serde(skip_serializing_if = "Option::is_none")] pub unlimited: Option, } -/// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. +/// Completions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopilotUserResponseQuotaSnapshotsCompletions { + /// Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. #[serde(skip_serializing_if = "Option::is_none")] pub entitlement: Option, + /// Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] pub has_quota: Option, + /// Count of additional pay-per-request usage consumed this period beyond the entitlement. #[serde(rename = "overage_count", skip_serializing_if = "Option::is_none")] pub overage_count: Option, + /// Whether usage may continue at pay-per-request rates once the entitlement is exhausted. #[serde(rename = "overage_permitted", skip_serializing_if = "Option::is_none")] pub overage_permitted: Option, + /// Percentage of the entitlement remaining at the snapshot timestamp. #[serde(rename = "percent_remaining", skip_serializing_if = "Option::is_none")] pub percent_remaining: Option, + /// Identifier of the quota bucket this snapshot describes. #[serde(rename = "quota_id", skip_serializing_if = "Option::is_none")] pub quota_id: Option, + /// Amount of quota remaining at the snapshot timestamp. #[serde(rename = "quota_remaining", skip_serializing_if = "Option::is_none")] pub quota_remaining: Option, + /// Unix epoch time, in seconds, when this quota next resets. #[serde(rename = "quota_reset_at", skip_serializing_if = "Option::is_none")] pub quota_reset_at: Option, + /// Remaining entitlement/quota amount at the snapshot timestamp. #[serde(skip_serializing_if = "Option::is_none")] pub remaining: Option, + /// UTC timestamp when this snapshot was captured. #[serde(rename = "timestamp_utc", skip_serializing_if = "Option::is_none")] pub timestamp_utc: Option, + /// Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. #[serde( rename = "token_based_billing", skip_serializing_if = "Option::is_none" )] pub token_based_billing: Option, + /// Whether the entitlement for this category is unlimited. #[serde(skip_serializing_if = "Option::is_none")] pub unlimited: Option, } -/// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. +/// Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopilotUserResponseQuotaSnapshotsPremiumInteractions { + /// Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. #[serde(skip_serializing_if = "Option::is_none")] pub entitlement: Option, + /// Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. #[serde(rename = "has_quota", skip_serializing_if = "Option::is_none")] pub has_quota: Option, + /// Count of additional pay-per-request usage consumed this period beyond the entitlement. #[serde(rename = "overage_count", skip_serializing_if = "Option::is_none")] pub overage_count: Option, + /// Whether usage may continue at pay-per-request rates once the entitlement is exhausted. #[serde(rename = "overage_permitted", skip_serializing_if = "Option::is_none")] pub overage_permitted: Option, + /// Percentage of the entitlement remaining at the snapshot timestamp. #[serde(rename = "percent_remaining", skip_serializing_if = "Option::is_none")] pub percent_remaining: Option, + /// Identifier of the quota bucket this snapshot describes. #[serde(rename = "quota_id", skip_serializing_if = "Option::is_none")] pub quota_id: Option, + /// Amount of quota remaining at the snapshot timestamp. #[serde(rename = "quota_remaining", skip_serializing_if = "Option::is_none")] pub quota_remaining: Option, + /// Unix epoch time, in seconds, when this quota next resets. #[serde(rename = "quota_reset_at", skip_serializing_if = "Option::is_none")] pub quota_reset_at: Option, + /// Remaining entitlement/quota amount at the snapshot timestamp. #[serde(skip_serializing_if = "Option::is_none")] pub remaining: Option, + /// UTC timestamp when this snapshot was captured. #[serde(rename = "timestamp_utc", skip_serializing_if = "Option::is_none")] pub timestamp_utc: Option, + /// Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. #[serde( rename = "token_based_billing", skip_serializing_if = "Option::is_none" )] pub token_based_billing: Option, + /// Whether the entitlement for this category is unlimited. #[serde(skip_serializing_if = "Option::is_none")] pub unlimited: Option, } -/// Schema for the `CopilotUserResponseQuotaSnapshots` type. +/// Quota snapshot map from the raw Copilot user-response passthrough, with chat, completions, premium-interactions, and other entries. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopilotUserResponseQuotaSnapshots { - /// Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. + /// Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. #[serde(skip_serializing_if = "Option::is_none")] pub chat: Option, - /// Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. + /// Completions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. #[serde(skip_serializing_if = "Option::is_none")] pub completions: Option, - /// Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. + /// Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. #[serde( rename = "premium_interactions", skip_serializing_if = "Option::is_none" @@ -1247,92 +1425,125 @@ pub struct CopilotUserResponseQuotaSnapshots { } /// Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopilotUserResponse { + /// Copilot access SKU identifier (e.g. `free_limited_copilot`, `copilot_for_business_seat_quota`) used to gate model and feature access. #[serde(rename = "access_type_sku", skip_serializing_if = "Option::is_none")] pub access_type_sku: Option, + /// Opaque analytics tracking identifier for the user, forwarded from the Copilot API. #[serde( rename = "analytics_tracking_id", skip_serializing_if = "Option::is_none" )] pub analytics_tracking_id: Option, + /// Date the Copilot seat was assigned to the user, if applicable. #[serde(rename = "assigned_date", skip_serializing_if = "Option::is_none")] pub assigned_date: Option, + /// Whether the user is eligible to sign up for the free/limited Copilot tier. #[serde( rename = "can_signup_for_limited", skip_serializing_if = "Option::is_none" )] pub can_signup_for_limited: Option, + /// Whether the user is able to upgrade their Copilot plan. #[serde(rename = "can_upgrade_plan", skip_serializing_if = "Option::is_none")] pub can_upgrade_plan: Option, + /// Whether Copilot chat is enabled for the user. #[serde(rename = "chat_enabled", skip_serializing_if = "Option::is_none")] pub chat_enabled: Option, + /// Whether CLI remote control is enabled for the user. #[serde( rename = "cli_remote_control_enabled", skip_serializing_if = "Option::is_none" )] pub cli_remote_control_enabled: Option, + /// Whether cloud session storage is enabled for the user. #[serde( rename = "cloud_session_storage_enabled", skip_serializing_if = "Option::is_none" )] pub cloud_session_storage_enabled: Option, + /// Whether the Codex agent is enabled for the user. #[serde( rename = "codex_agent_enabled", skip_serializing_if = "Option::is_none" )] pub codex_agent_enabled: Option, + /// Copilot plan name for the user (e.g. `individual`, `business`, `enterprise`). #[serde(rename = "copilot_plan", skip_serializing_if = "Option::is_none")] pub copilot_plan: Option, + /// Whether `.copilotignore` content-exclusion support is enabled for the user. #[serde( rename = "copilotignore_enabled", skip_serializing_if = "Option::is_none" )] pub copilotignore_enabled: Option, - /// Schema for the `CopilotUserResponseEndpoints` type. + /// Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. #[serde(skip_serializing_if = "Option::is_none")] pub endpoints: Option, + /// Whether MCP (Model Context Protocol) support is enabled for the user. #[serde(rename = "is_mcp_enabled", skip_serializing_if = "Option::is_none")] pub is_mcp_enabled: Option, + /// Whether the user is a GitHub/Microsoft staff member. #[serde(rename = "is_staff", skip_serializing_if = "Option::is_none")] pub is_staff: Option, + /// Per-category quota allotments for free/limited-tier users, keyed by quota category. #[serde( rename = "limited_user_quotas", skip_serializing_if = "Option::is_none" )] pub limited_user_quotas: Option>, + /// Date the free/limited-tier user's quotas next reset, as a raw string from the Copilot API. #[serde( rename = "limited_user_reset_date", skip_serializing_if = "Option::is_none" )] pub limited_user_reset_date: Option, + /// GitHub login of the authenticated user. #[serde(skip_serializing_if = "Option::is_none")] pub login: Option, + /// Per-category monthly quota allotments, keyed by quota category. #[serde(rename = "monthly_quotas", skip_serializing_if = "Option::is_none")] pub monthly_quotas: Option>, + /// Organizations the user belongs to, each with an optional login and display name. #[serde(rename = "organization_list", skip_serializing_if = "Option::is_none")] pub organization_list: Option, + /// Logins of the organizations the user belongs to. #[serde( rename = "organization_login_list", skip_serializing_if = "Option::is_none" )] pub organization_login_list: Option>, + /// Date the user's usage quota next resets, as a raw string from the Copilot API; see `quota_reset_date_utc` for the UTC-normalized value. #[serde(rename = "quota_reset_date", skip_serializing_if = "Option::is_none")] pub quota_reset_date: Option, + /// UTC-normalized form of `quota_reset_date` (the date the user's usage quota next resets). #[serde( rename = "quota_reset_date_utc", skip_serializing_if = "Option::is_none" )] pub quota_reset_date_utc: Option, - /// Schema for the `CopilotUserResponseQuotaSnapshots` type. + /// Quota snapshot map from the raw Copilot user-response passthrough, with chat, completions, premium-interactions, and other entries. #[serde(rename = "quota_snapshots", skip_serializing_if = "Option::is_none")] pub quota_snapshots: Option, + /// Whether the user's telemetry is subject to restricted-data handling. #[serde( rename = "restricted_telemetry", skip_serializing_if = "Option::is_none" )] pub restricted_telemetry: Option, + /// Raw passthrough of the Copilot API `te` flag for the user (an opaque server-side eligibility signal surfaced in telemetry); not otherwise interpreted by the runtime. + #[serde(skip_serializing_if = "Option::is_none")] + pub te: Option, + /// Whether the account is on usage-based (token/AI-credit) billing rather than a fixed premium-request quota. #[serde( rename = "token_based_billing", skip_serializing_if = "Option::is_none" @@ -1340,7 +1551,14 @@ pub struct CopilotUserResponse { pub token_based_billing: Option, } -/// Schema for the `ApiKeyAuthInfo` type. +/// Authentication-info variant for API-key authentication to a non-GitHub LLM provider, carrying the secret `apiKey` and host. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApiKeyAuthInfo { @@ -1493,7 +1711,7 @@ pub struct AttachmentFile { pub r#type: AttachmentFileType, } -/// GitHub issue, pull request, or discussion reference +/// Pointer to a GitHub repository. /// ///
/// @@ -1503,22 +1721,45 @@ pub struct AttachmentFile { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AttachmentGitHubReference { - /// Issue, pull request, or discussion number - pub number: i64, - /// Type of GitHub reference - pub reference_type: AttachmentGitHubReferenceType, - /// Current state of the referenced item (e.g., open, closed, merged) - pub state: String, - /// Title of the referenced item - pub title: String, +pub struct GitHubRepoRef { + /// Numeric GitHub repository id + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Repository name (without owner) + pub name: String, + /// Repository owner login (user or organization) + pub owner: String, +} + +/// Pointer to a GitHub Actions job. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttachmentGitHubActionsJob { + /// Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. + #[serde(skip_serializing_if = "Option::is_none")] + pub conclusion: Option, + /// Job id within the workflow run + pub job_id: i64, + /// Display name of the job + pub job_name: String, + /// Repository the workflow run belongs to + pub repo: GitHubRepoRef, /// Attachment type discriminator - pub r#type: AttachmentGitHubReferenceType, - /// URL to the referenced item on GitHub + pub r#type: AttachmentGitHubActionsJobType, + /// URL to the job on GitHub pub url: String, + /// Display name of the workflow the job ran in + pub workflow_name: String, } -/// End position of the selection +/// Pointer to a GitHub commit. /// ///
/// @@ -1528,14 +1769,20 @@ pub struct AttachmentGitHubReference { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AttachmentSelectionDetailsEnd { - /// End character offset within the line (0-based) - pub character: i64, - /// End line number (0-based) - pub line: i64, +pub struct AttachmentGitHubCommit { + /// First line of the commit message + pub message: String, + /// Full commit SHA + pub oid: String, + /// Repository the commit belongs to + pub repo: GitHubRepoRef, + /// Attachment type discriminator + pub r#type: AttachmentGitHubCommitType, + /// URL to the commit on GitHub + pub url: String, } -/// Start position of the selection +/// Pointer to a file in a GitHub repository at a specific ref. /// ///
/// @@ -1545,14 +1792,20 @@ pub struct AttachmentSelectionDetailsEnd { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AttachmentSelectionDetailsStart { - /// Start character offset within the line (0-based) - pub character: i64, - /// Start line number (0-based) - pub line: i64, +pub struct AttachmentGitHubFile { + /// Repository-relative path to the file + pub path: String, + /// Git ref the file is read at (branch, tag, or commit SHA) + pub r#ref: String, + /// Repository the file lives in + pub repo: GitHubRepoRef, + /// Attachment type discriminator + pub r#type: AttachmentGitHubFileType, + /// URL to the file on GitHub + pub url: String, } -/// Position range of the selection within the file +/// One side of a file diff (head or base) /// ///
/// @@ -1562,14 +1815,16 @@ pub struct AttachmentSelectionDetailsStart { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AttachmentSelectionDetails { - /// End position of the selection - pub end: AttachmentSelectionDetailsEnd, - /// Start position of the selection - pub start: AttachmentSelectionDetailsStart, +pub struct AttachmentGitHubFileDiffSide { + /// Repository-relative path to the file + pub path: String, + /// Git ref (branch, tag, or commit SHA) the file is read at + pub r#ref: String, + /// Repository the file lives in + pub repo: GitHubRepoRef, } -/// Code selection attachment from an editor +/// Pointer to a single-file diff. At least one of `head` and `base` must be present. /// ///
/// @@ -1579,20 +1834,20 @@ pub struct AttachmentSelectionDetails { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AttachmentSelection { - /// User-facing display name for the selection - pub display_name: String, - /// Absolute path to the file containing the selection - pub file_path: String, - /// Position range of the selection within the file - pub selection: AttachmentSelectionDetails, - /// The selected text content - pub text: String, +pub struct AttachmentGitHubFileDiff { + /// File location on the base side of the diff. Absent for additions. + #[serde(skip_serializing_if = "Option::is_none")] + pub base: Option, + /// File location on the head side of the diff. Absent for deletions. + #[serde(skip_serializing_if = "Option::is_none")] + pub head: Option, /// Attachment type discriminator - pub r#type: AttachmentSelectionType, + pub r#type: AttachmentGitHubFileDiffType, + /// URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) + pub url: String, } -/// Cancellation result for a user-requested shell command. +/// GitHub issue, pull request, or discussion reference /// ///
/// @@ -1602,12 +1857,22 @@ pub struct AttachmentSelection { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CancelUserRequestedShellCommandResult { - /// Whether an in-flight execution was found and signalled to cancel - pub cancelled: bool, +pub struct AttachmentGitHubReference { + /// Issue, pull request, or discussion number + pub number: i64, + /// Type of GitHub reference + pub reference_type: AttachmentGitHubReferenceType, + /// Current state of the referenced item (e.g., open, closed, merged) + pub state: String, + /// Title of the referenced item + pub title: String, + /// Attachment type discriminator + pub r#type: AttachmentGitHubReferenceType, + /// URL to the referenced item on GitHub + pub url: String, } -/// Canvas action that the agent or host can invoke. To discover the input schema for a particular action, call the list_canvas_capabilities tool. +/// Pointer to a GitHub release. /// ///
/// @@ -1617,18 +1882,20 @@ pub struct CancelUserRequestedShellCommandResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CanvasAction { - /// Description of the action - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// JSON Schema for the action input - #[serde(skip_serializing_if = "Option::is_none")] - pub input_schema: Option, - /// Action name exposed by the canvas provider +pub struct AttachmentGitHubRelease { + /// Human-readable release name pub name: String, + /// Repository the release belongs to + pub repo: GitHubRepoRef, + /// Git tag the release is anchored to + pub tag_name: String, + /// Attachment type discriminator + pub r#type: AttachmentGitHubReleaseType, + /// URL to the release on GitHub + pub url: String, } -/// Canvas action invocation parameters. +/// Pointer to a GitHub repository. /// ///
/// @@ -1638,17 +1905,22 @@ pub struct CanvasAction { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CanvasActionInvokeRequest { - /// Action name to invoke - pub action_name: String, - /// Action input +pub struct AttachmentGitHubRepository { + /// Short description of the repository #[serde(skip_serializing_if = "Option::is_none")] - pub input: Option, - /// Open canvas instance identifier - pub instance_id: String, + pub description: Option, + /// Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. + #[serde(skip_serializing_if = "Option::is_none")] + pub r#ref: Option, + /// Repository pointer + pub repo: GitHubRepoRef, + /// Attachment type discriminator + pub r#type: AttachmentGitHubRepositoryType, + /// URL to the repository on GitHub + pub url: String, } -/// Canvas action invocation result. +/// Pointer to a line range inside a file in a GitHub repository. /// ///
/// @@ -1658,13 +1930,22 @@ pub struct CanvasActionInvokeRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CanvasActionInvokeResult { - /// Provider-supplied action result - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, +pub struct AttachmentGitHubSnippet { + /// Line range the snippet covers + pub line_range: AttachmentFileLineRange, + /// Repository-relative path to the file + pub path: String, + /// Git ref the file is read at (branch, tag, or commit SHA) + pub r#ref: String, + /// Repository the file lives in + pub repo: GitHubRepoRef, + /// Attachment type discriminator + pub r#type: AttachmentGitHubSnippetType, + /// URL to the snippet on GitHub (with line anchor) + pub url: String, } -/// Canvas close parameters. +/// One side of a tree comparison (head or base) /// ///
/// @@ -1674,12 +1955,14 @@ pub struct CanvasActionInvokeResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CanvasCloseRequest { - /// Open canvas instance identifier - pub instance_id: String, +pub struct AttachmentGitHubTreeComparisonSide { + /// Repository the revision belongs to + pub repo: GitHubRepoRef, + /// Git revision (branch, tag, or commit SHA) + pub revision: String, } -/// Host capabilities +/// Pointer to a comparison between two git revisions. /// ///
/// @@ -1689,13 +1972,18 @@ pub struct CanvasCloseRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CanvasHostContextCapabilities { - /// Whether canvas rendering is supported - #[serde(skip_serializing_if = "Option::is_none")] - pub canvases: Option, +pub struct AttachmentGitHubTreeComparison { + /// Base side of the comparison + pub base: AttachmentGitHubTreeComparisonSide, + /// Head side of the comparison + pub head: AttachmentGitHubTreeComparisonSide, + /// Attachment type discriminator + pub r#type: AttachmentGitHubTreeComparisonType, + /// URL to the comparison on GitHub + pub url: String, } -/// Host context supplied by the runtime. +/// Generic GitHub URL reference. /// ///
/// @@ -1705,13 +1993,14 @@ pub struct CanvasHostContextCapabilities { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CanvasHostContext { - /// Host capabilities - #[serde(skip_serializing_if = "Option::is_none")] - pub capabilities: Option, +pub struct AttachmentGitHubUrl { + /// Attachment type discriminator + pub r#type: AttachmentGitHubUrlType, + /// URL to the GitHub resource + pub url: String, } -/// Canvas available in the current session. +/// End position of the selection /// ///
/// @@ -1721,11 +2010,204 @@ pub struct CanvasHostContext { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct DiscoveredCanvas { - /// Actions the agent or host may invoke on an open instance - #[serde(skip_serializing_if = "Option::is_none")] - pub actions: Option>, - /// Provider-local canvas identifier +pub struct AttachmentSelectionDetailsEnd { + /// End character offset within the line (0-based) + pub character: i64, + /// End line number (0-based) + pub line: i64, +} + +/// Start position of the selection +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttachmentSelectionDetailsStart { + /// Start character offset within the line (0-based) + pub character: i64, + /// Start line number (0-based) + pub line: i64, +} + +/// Position range of the selection within the file +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttachmentSelectionDetails { + /// End position of the selection + pub end: AttachmentSelectionDetailsEnd, + /// Start position of the selection + pub start: AttachmentSelectionDetailsStart, +} + +/// Code selection attachment from an editor +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttachmentSelection { + /// User-facing display name for the selection + pub display_name: String, + /// Absolute path to the file containing the selection + pub file_path: String, + /// Position range of the selection within the file + pub selection: AttachmentSelectionDetails, + /// The selected text content + pub text: String, + /// Attachment type discriminator + pub r#type: AttachmentSelectionType, +} + +/// Cancellation result for a user-requested shell command. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CancelUserRequestedShellCommandResult { + /// Whether an in-flight execution was found and signalled to cancel + pub cancelled: bool, +} + +/// Canvas action that the agent or host can invoke. To discover the input schema for a particular action, call the list_canvas_capabilities tool. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CanvasAction { + /// Description of the action + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// JSON Schema for the action input + #[serde(skip_serializing_if = "Option::is_none")] + pub input_schema: Option, + /// Action name exposed by the canvas provider + pub name: String, +} + +/// Canvas action invocation parameters. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CanvasActionInvokeRequest { + /// Action name to invoke + pub action_name: String, + /// Action input + #[serde(skip_serializing_if = "Option::is_none")] + pub input: Option, + /// Open canvas instance identifier + pub instance_id: String, +} + +/// Canvas action invocation result. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CanvasActionInvokeResult { + /// Provider-supplied action result + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, +} + +/// Canvas close parameters. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CanvasCloseRequest { + /// Open canvas instance identifier + pub instance_id: String, +} + +/// Host capabilities +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CanvasHostContextCapabilities { + /// Whether canvas rendering is supported + #[serde(skip_serializing_if = "Option::is_none")] + pub canvases: Option, +} + +/// Host context supplied by the runtime. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CanvasHostContext { + /// Host capabilities + #[serde(skip_serializing_if = "Option::is_none")] + pub capabilities: Option, +} + +/// Canvas available in the current session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DiscoveredCanvas { + /// Actions the agent or host may invoke on an open instance + #[serde(skip_serializing_if = "Option::is_none")] + pub actions: Option>, + /// Provider-local canvas identifier pub canvas_id: String, /// Short, single-sentence description shown to the agent in canvas catalogs. pub description: String, @@ -1736,6 +2218,9 @@ pub struct DiscoveredCanvas { /// Owning extension display name, when available #[serde(skip_serializing_if = "Option::is_none")] pub extension_name: Option, + /// Host-local PNG path for the canvas icon, when supplied + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, /// JSON Schema for canvas open input #[serde(skip_serializing_if = "Option::is_none")] pub input_schema: Option, @@ -1774,6 +2259,9 @@ pub struct OpenCanvasInstance { /// Owning extension display name, when available #[serde(skip_serializing_if = "Option::is_none")] pub extension_name: Option, + /// Host-local PNG path for the canvas icon, when supplied + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, /// Input supplied when the instance was opened #[serde(skip_serializing_if = "Option::is_none")] pub input: Option, @@ -1971,6 +2459,23 @@ pub struct CapiSessionOptions { pub enable_web_socket_responses: Option, } +/// A literal choice the command input accepts, with a human-facing description +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SlashCommandInputChoice { + /// Human-readable description shown alongside the choice + pub description: String, + /// The literal choice value (e.g. 'on', 'off', 'show') + pub name: String, +} + /// Optional unstructured input hint /// ///
@@ -1982,6 +2487,9 @@ pub struct CapiSessionOptions { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SlashCommandInput { + /// Optional literal choices the input accepts, each with a human-facing description; clients may render these as selectable options + #[serde(skip_serializing_if = "Option::is_none")] + pub choices: Option>, /// Optional completion hint for the input (e.g. 'directory' for filesystem path completion) #[serde(skip_serializing_if = "Option::is_none")] pub completion: Option, @@ -1995,7 +2503,7 @@ pub struct SlashCommandInput { pub required: Option, } -/// Schema for the `SlashCommandInfo` type. +/// Slash-command metadata with name, aliases, description, kind, input hint, execution allowance, and schedulability. /// ///
/// @@ -2148,7 +2656,7 @@ pub struct CommandsRespondToQueuedCommandResult { pub success: bool, } -/// Params to attach or detach an in-process ExtensionController delegate. +/// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). /// ///
/// @@ -2158,16 +2666,12 @@ pub struct CommandsRespondToQueuedCommandResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct ConfigureSessionExtensionsParams { - /// In-process ExtensionController delegate (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. The post-SDK extension surface exposes list/enable/disable/reload via dedicated RPCs served by the runtime. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) controller: Option, - /// Session to attach the extension controller delegate to. - pub session_id: SessionId, +pub struct CompletionsGetTriggerCharactersResult { + /// Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. + pub trigger_characters: Vec, } -/// Repository associated with the connected remote session. +/// Request host-driven completions for the current composer input. /// ///
/// @@ -2177,16 +2681,14 @@ pub(crate) struct ConfigureSessionExtensionsParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ConnectedRemoteSessionMetadataRepository { - /// Branch associated with the remote session. - pub branch: String, - /// Repository name. - pub name: String, - /// Repository owner or organization login. - pub owner: String, +pub struct CompletionsRequestRequest { + /// Cursor offset within `text`, in UTF-16 code units. + pub offset: i64, + /// The full composed composer input. + pub text: String, } -/// Metadata for a connected remote session. +/// A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` (UTF-16 code units) in the composer with `insertText`; when the range is absent, the active token around the cursor is replaced. /// ///
/// @@ -2196,33 +2698,113 @@ pub struct ConnectedRemoteSessionMetadataRepository { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ConnectedRemoteSessionMetadata { - /// Neutral SDK discriminator for the connected remote session kind. - pub kind: ConnectedRemoteSessionMetadataKind, - /// Last session update time as an ISO 8601 string. - pub modified_time: String, - /// Optional friendly session name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Pull request number associated with the session. - #[serde(skip_serializing_if = "Option::is_none")] - pub pull_request_number: Option, - /// Repository associated with the connected remote session. - pub repository: ConnectedRemoteSessionMetadataRepository, - /// Original remote resource identifier. +pub struct SessionCompletionItem { + /// Text spliced into the composer when the item is accepted. + pub insert_text: String, + /// Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the host's display kind. #[serde(skip_serializing_if = "Option::is_none")] - pub resource_id: Option, - /// SDK session ID for the connected remote session. - pub session_id: SessionId, - /// Remote session staleness deadline as an ISO 8601 string. + pub kind: Option, + /// Primary display label for the picker row. Falls back to `insertText` when absent. #[serde(skip_serializing_if = "Option::is_none")] - pub stale_at: Option, - /// Session start time as an ISO 8601 string. - pub start_time: String, - /// Remote session state returned by the backing service. + pub label: Option, + /// End (exclusive) of the replacement range in `text`, in UTF-16 code units. #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - /// Optional session summary. + pub range_end: Option, + /// Start of the replacement range in `text`, in UTF-16 code units. + #[serde(skip_serializing_if = "Option::is_none")] + pub range_start: Option, +} + +/// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionsRequestResult { + /// Completion items in host-ranked order. + pub items: Vec, +} + +/// Params to attach or detach an in-process ExtensionController delegate. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ConfigureSessionExtensionsParams { + /// In-process ExtensionController delegate (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. The post-SDK extension surface exposes list/enable/disable/reload via dedicated RPCs served by the runtime. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) controller: Option, + /// Session to attach the extension controller delegate to. + pub session_id: SessionId, +} + +/// Repository associated with the connected remote session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConnectedRemoteSessionMetadataRepository { + /// Branch associated with the remote session. + pub branch: String, + /// Repository name. + pub name: String, + /// Repository owner or organization login. + pub owner: String, +} + +/// Metadata for a connected remote session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConnectedRemoteSessionMetadata { + /// Neutral SDK discriminator for the connected remote session kind. + pub kind: ConnectedRemoteSessionMetadataKind, + /// Last session update time as an ISO 8601 string. + pub modified_time: String, + /// Optional friendly session name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Pull request number associated with the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub pull_request_number: Option, + /// Repository associated with the connected remote session. + pub repository: ConnectedRemoteSessionMetadataRepository, + /// Original remote resource identifier. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_id: Option, + /// SDK session ID for the connected remote session. + pub session_id: SessionId, + /// Remote session staleness deadline as an ISO 8601 string. + #[serde(skip_serializing_if = "Option::is_none")] + pub stale_at: Option, + /// Session start time as an ISO 8601 string. + pub start_time: String, + /// Remote session state returned by the backing service. + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option, + /// Optional session summary. #[serde(skip_serializing_if = "Option::is_none")] pub summary: Option, } @@ -2242,16 +2824,33 @@ pub struct ConnectRemoteSessionParams { pub session_id: SessionId, } -/// Optional connection token presented by the SDK client during the handshake. +/// Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct ConnectRequest { + /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_git_hub_telemetry_forwarding: Option, /// Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN #[serde(skip_serializing_if = "Option::is_none")] pub token: Option, } /// Handshake result reporting the server's protocol version and package version on success. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct ConnectResult { @@ -2263,7 +2862,35 @@ pub(crate) struct ConnectResult { pub version: String, } -/// Schema for the `CopilotApiTokenAuthInfo` type. +/// A single large message currently in context. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ContextHeaviestMessage { + /// Stable identifier for this message within the snapshot. + pub id: String, + /// Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. + pub label: String, + /// Role of the chat message (`user`, `assistant`, or `tool`). + pub role: String, + /// Token count currently in context for this individual message. + pub tokens: i64, +} + +/// Authentication-info variant for direct Copilot API token auth sourced from environment variables, with public GitHub host. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CopilotApiTokenAuthInfo { @@ -2330,7 +2957,174 @@ pub struct CurrentToolMetadata { pub namespaced_name: Option, } -/// Schema for the `DiscoveredMcpServer` type. +/// A file included in the redacted debug bundle. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsCollectedEntry { + /// Relative path of the file in the staged bundle/archive. + pub bundle_path: String, + /// Redacted output size in bytes. + pub size_bytes: i64, + /// Source category for this entry. + pub source: DebugCollectLogsSource, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsDestinationArchive { + pub kind: DebugCollectLogsDestinationArchiveKind, + /// When true, create the archive atomically without overwriting an existing file by appending ` (N)` before the extension as needed. Defaults to false. + #[serde(skip_serializing_if = "Option::is_none")] + pub no_overwrite: Option, + /// Absolute or server-relative path for the .tgz archive to create. + pub output_path: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsDestinationDirectory { + pub kind: DebugCollectLogsDestinationDirectoryKind, + /// Directory where redacted files should be staged. The directory is created if needed. + pub output_directory: String, +} + +/// A caller-provided server-local file or directory to include in the debug bundle. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsEntry { + /// Relative path to use inside the staged bundle/archive. + pub bundle_path: String, + /// Kind of source path to include. + pub kind: DebugCollectLogsEntryKind, + /// Server-local source path to read. + pub path: String, + /// How text content from this entry should be redacted. Defaults to plain-text. + #[serde(skip_serializing_if = "Option::is_none")] + pub redaction: Option, + /// When true, collection fails if this entry cannot be read. Defaults to false, which records the entry in `skippedEntries`. + #[serde(skip_serializing_if = "Option::is_none")] + pub required: Option, +} + +/// Built-in session diagnostics to include in the bundle. Omitted fields default to true. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsInclude { + /// Server-local path to the current process log. When set, it is included as `process.log` and its directory is searched for prior logs from the same session. + #[serde(skip_serializing_if = "Option::is_none")] + pub current_process_log_path: Option, + /// Include the session event log (`events.jsonl`). Defaults to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub events: Option, + /// Server-local path to the session's events.jsonl file. Internal callers normally omit this and let the runtime derive it from the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub events_path: Option, + /// Maximum number of previous process logs to include. Defaults to 5. + #[serde(skip_serializing_if = "Option::is_none")] + pub previous_process_log_limit: Option, + /// Server-local process log directory to search when `currentProcessLogPath` is unavailable, useful for collecting logs for inactive sessions. + #[serde(skip_serializing_if = "Option::is_none")] + pub process_log_directory: Option, + /// Include process logs for the session. Defaults to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub process_logs: Option, + /// Include interactive shell logs written under the session's `shell-logs` directory. Defaults to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub shell_logs: Option, +} + +/// Options for collecting a redacted session debug bundle. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsRequest { + /// Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_entries: Option>, + /// Where the redacted bundle should be written. Use `archive` to produce a .tgz, or `directory` to stage redacted files for caller-managed upload/post-processing. + pub destination: DebugCollectLogsDestination, + /// Which built-in session diagnostics to include. Omitted fields default to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub include: Option, +} + +/// An optional debug bundle entry that could not be included. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsSkippedEntry { + /// Relative path requested for this bundle entry. + pub bundle_path: String, + /// Server-local source path that could not be read. + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + /// Reason the entry was skipped. + pub reason: String, +} + +/// Result of collecting a redacted debug bundle. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugCollectLogsResult { + /// Files included in the redacted bundle. + pub entries: Vec, + /// Destination kind that was written. + pub kind: DebugCollectLogsResultKind, + /// Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. + pub path: String, + /// Optional files or directories that could not be included. + #[serde(skip_serializing_if = "Option::is_none")] + pub skipped_entries: Option>, +} + +/// MCP server discovered by `mcp.discover`, with config source, optional plugin source, transport type, and enabled state. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DiscoveredMcpServer { @@ -2381,7 +3175,14 @@ pub struct EnqueueCommandResult { pub queued: bool, } -/// Schema for the `EnvAuthInfo` type. +/// Authentication-info variant for a token sourced from an environment variable, with host, optional login, token, and env var name. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EnvAuthInfo { @@ -2513,7 +3314,7 @@ pub struct ExecuteCommandResult { pub error: Option, } -/// Schema for the `Extension` type. +/// Discovered extension metadata, including source-qualified ID, name, discovery source, status, and optional process ID. /// ///
/// @@ -2654,6 +3455,9 @@ pub struct ExternalToolTextResultForLlm { pub session_log: Option, /// Text result returned to the model pub text_result_for_llm: String, + /// Tool references returned by a tool-search override: names of deferred tools to surface to the model. When set, the tool result is materialized as `tool_reference` content blocks (rather than plain text) so the model knows which deferred tools are now available. + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_references: Option>, /// Optional tool-specific telemetry #[serde(skip_serializing_if = "Option::is_none")] pub tool_telemetry: Option>, @@ -2772,6 +3576,34 @@ pub struct ExternalToolTextResultForLlmContentResourceLink { pub uri: String, } +/// Shell command exit metadata with optional output preview +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExternalToolTextResultForLlmContentShellExit { + /// Working directory where the shell command was executed + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// Exit code from the completed shell command + pub exit_code: i64, + /// Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. + #[serde(skip_serializing_if = "Option::is_none")] + pub output_preview: Option, + /// Whether outputPreview is known to be incomplete or truncated + #[serde(skip_serializing_if = "Option::is_none")] + pub output_truncated: Option, + /// Shell id, as assigned by Copilot runtime + pub shell_id: String, + /// Content block type discriminator + pub r#type: ExternalToolTextResultForLlmContentShellExitType, +} + /// Terminal/shell output content block with optional exit code and working directory /// ///
@@ -2888,7 +3720,14 @@ pub struct FolderTrustCheckResult { pub trusted: bool, } -/// Schema for the `GhCliAuthInfo` type. +/// Authentication-info variant for GitHub CLI credentials, carrying host, login, and the `gh auth token` value. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GhCliAuthInfo { @@ -2905,6 +3744,115 @@ pub struct GhCliAuthInfo { pub r#type: GhCliAuthInfoType, } +/// Client environment metadata describing the process that produced a telemetry event. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitHubTelemetryClientInfo { + /// Copilot CLI version string. + #[serde(rename = "cli_version")] + pub cli_version: String, + /// Name of the client application. + #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] + pub client_name: Option, + /// Type of client. + #[serde(rename = "client_type", skip_serializing_if = "Option::is_none")] + pub client_type: Option, + /// Copilot subscription plan, when known. + #[serde(rename = "copilot_plan", skip_serializing_if = "Option::is_none")] + pub copilot_plan: Option, + /// Stable machine identifier for the device. + #[serde(rename = "dev_device_id", skip_serializing_if = "Option::is_none")] + pub dev_device_id: Option, + /// Whether the user is a GitHub/Microsoft staff member. + #[serde(rename = "is_staff", skip_serializing_if = "Option::is_none")] + pub is_staff: Option, + /// Node.js runtime version string. + #[serde(rename = "node_version")] + pub node_version: String, + /// Operating system architecture (e.g. arm64, x64). + #[serde(rename = "os_arch")] + pub os_arch: String, + /// Operating system platform (e.g. darwin, linux, win32). + #[serde(rename = "os_platform")] + pub os_platform: String, + /// Operating system version string. + #[serde(rename = "os_version")] + pub os_version: String, +} + +/// A single telemetry event in the runtime's native GitHub-shaped telemetry format, forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing GitHubTelemetryNotification distinguishes standard from restricted events; the payload shape is identical for both. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitHubTelemetryEvent { + /// Client environment metadata. + #[serde(skip_serializing_if = "Option::is_none")] + pub client: Option, + /// Copilot tracking ID for user-level attribution. + #[serde( + rename = "copilot_tracking_id", + skip_serializing_if = "Option::is_none" + )] + pub copilot_tracking_id: Option, + /// Timestamp when the event was created (ISO 8601 format). + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + /// Experiment assignment context. + #[serde( + rename = "exp_assignment_context", + skip_serializing_if = "Option::is_none" + )] + pub exp_assignment_context: Option, + /// Feature flags enabled for this session, as a map from flag to value. + #[serde(skip_serializing_if = "Option::is_none")] + pub features: Option>, + /// Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed). + pub kind: String, + /// Numeric metrics as a map from key to value. + pub metrics: HashMap, + /// Reference to the model call that produced this event. + #[serde(rename = "model_call_id", skip_serializing_if = "Option::is_none")] + pub model_call_id: Option, + /// String-valued properties as a map from key to value. + pub properties: HashMap, + /// Session identifier the event belongs to. + #[serde(rename = "session_id", skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} + +/// Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitHubTelemetryNotification { + /// The telemetry event, in the runtime's native GitHub-shaped telemetry format. + pub event: GitHubTelemetryEvent, + /// Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route restricted events to first-party Microsoft stores only. + pub restricted: bool, + /// Session the telemetry event belongs to, when it is session-scoped. Omitted for sessionless events (for example, `server.sendTelemetry` calls with no session id), which are still forwarded to opted-in connections. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} + /// Pending external tool call request ID, with the tool result or an error describing why it failed. /// ///
@@ -3085,7 +4033,14 @@ pub struct HistoryTruncateResult { pub events_removed: i64, } -/// Schema for the `HMACAuthInfo` type. +/// Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub host and HMAC secret. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HMACAuthInfo { @@ -3100,7 +4055,25 @@ pub struct HMACAuthInfo { pub r#type: HMACAuthInfoType, } -/// Schema for the `InstalledPlugin` type. +/// Runtime-owned wire payload for a server-to-client hook callback invocation. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct HookInvokeRequest { + #[doc(hidden)] + pub(crate) hook_type: HookType, + pub input: serde_json::Value, + pub session_id: SessionId, +} + +/// Optional output returned by an SDK callback hook. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct HookInvokeResponse { + #[serde(skip_serializing_if = "Option::is_none")] + pub output: Option, +} + +/// Installed plugin record from global state, with marketplace, version, install time, enabled state, cache path, and source. /// ///
/// @@ -3142,6 +4115,9 @@ pub struct InstalledPlugin { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct InstalledPluginInfo { + /// Opaque, stable hash identifying a direct (non-marketplace) install source. Present only for direct repo / URL / local installs; absent for marketplace plugins. Same source yields the same id; distinct sources never collide. + #[serde(skip_serializing_if = "Option::is_none")] + pub direct_source_id: Option, /// Whether the plugin is currently enabled for new sessions pub enabled: bool, /// Marketplace the plugin came from. Empty string ("") for direct repo / URL / local installs. @@ -3153,7 +4129,7 @@ pub struct InstalledPluginInfo { pub version: Option, } -/// Schema for the `InstalledPluginSourceGitHub` type. +/// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. /// ///
/// @@ -3173,7 +4149,7 @@ pub struct InstalledPluginSourceGitHub { pub source: InstalledPluginSourceGitHubSource, } -/// Schema for the `InstalledPluginSourceLocal` type. +/// Source descriptor for a direct local plugin install, with a local filesystem path. /// ///
/// @@ -3189,7 +4165,7 @@ pub struct InstalledPluginSourceLocal { pub source: InstalledPluginSourceLocalSource, } -/// Schema for the `InstalledPluginSourceUrl` type. +/// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. /// ///
/// @@ -3209,7 +4185,7 @@ pub struct InstalledPluginSourceUrl { pub url: String, } -/// Schema for the `InstructionDiscoveryPath` type. +/// Canonical file or directory where custom instructions can be discovered or created, with location, kind, preference, and project path. /// ///
/// @@ -3286,7 +4262,7 @@ pub struct InstructionsGetDiscoveryPathsRequest { pub project_paths: Option>, } -/// Schema for the `InstructionSource` type. +/// Loaded instruction source for a session, including path, content, category, location, applicability, and optional description. /// ///
/// @@ -3369,9 +4345,18 @@ pub struct LlmInferenceHttpRequestChunkResult {} #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LlmInferenceHttpRequestStartRequest { + /// Stable per-agent-instance id attributing this request to a specific agent trajectory. Present when the request originates from an agent turn; absent for requests issued outside any agent context (e.g. some SDK callers). A request with an `agentId` but no `parentAgentId` is a root-agent request; one carrying both is a subagent request. Sourced from the runtime's per-request agent context and surfaced on the envelope independently of transport, so it is available for both first-party (CAPI) and BYOK/custom-provider requests; on the CAPI transport the runtime derives the upstream `X-Agent-Task-Id` header from this same context. Consumers routing each provider call to a training trajectory should key on this rather than on lifecycle events, since it is available on the request path before sampling. + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_id: Option, pub headers: HashMap>, + /// Coarse classification of the interaction that produced this request. Open string for forward-compatibility; known values include `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, and `conversation-user`. Absent when the runtime did not classify the request. Comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` header from this same context. + #[serde(skip_serializing_if = "Option::is_none")] + pub interaction_type: Option, /// HTTP method, e.g. GET, POST. pub method: String, + /// Id of the parent agent that spawned the agent issuing this request. Present only for subagent requests; absent for root-agent requests and non-agent requests. Combined with `agentId`, this lets consumers attribute a call to a child trajectory versus the root. Like `agentId`, it comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Parent-Agent-Id` header from this same context. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_agent_id: Option, /// Opaque runtime-minted id, unique per in-flight request. The SDK uses this to correlate httpRequestChunk frames and to address its httpResponseStart / httpResponseChunk replies back to the runtime. pub request_id: RequestId, /// Id of the runtime session that triggered this request, when one is in scope. Absent for requests issued outside any session (e.g. startup model-catalog or capability resolution). This is a payload field — not a dispatch key — because the client-global API is registered process-wide rather than per session. @@ -3526,7 +4511,7 @@ pub struct SessionContext { pub repository: Option, } -/// Schema for the `LocalSessionMetadataValue` type. +/// Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. /// ///
/// @@ -3715,7 +4700,7 @@ pub struct MarketplaceListResult { pub marketplaces: Vec, } -/// Schema for the `MarketplaceRefreshEntry` type. +/// Per-marketplace refresh result, including marketplace name, success flag, and optional failure error. /// ///
/// @@ -3768,7 +4753,7 @@ pub struct MarketplaceRemoveResult { pub removed: bool, } -/// Schema for the `McpAllowedServer` type. +/// MCP server allowed by policy, with server name and optional PII-free explanatory note. /// ///
/// @@ -3978,7 +4963,7 @@ pub struct McpAppsReadResourceRequest { pub uri: String, } -/// Schema for the `McpAppsResourceContent` type. +/// MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource metadata. /// ///
/// @@ -4100,6 +5085,13 @@ pub struct McpCancelSamplingExecutionResult { } /// MCP server name and configuration to add to user configuration. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigAddRequest { @@ -4110,6 +5102,13 @@ pub struct McpConfigAddRequest { } /// MCP server names to disable for new sessions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigDisableRequest { @@ -4118,6 +5117,13 @@ pub struct McpConfigDisableRequest { } /// MCP server names to enable for new sessions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigEnableRequest { @@ -4126,6 +5132,13 @@ pub struct McpConfigEnableRequest { } /// User-configured MCP servers, keyed by server name. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigList { @@ -4134,6 +5147,13 @@ pub struct McpConfigList { } /// MCP server name to remove from user configuration. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigRemoveRequest { @@ -4142,6 +5162,13 @@ pub struct McpConfigRemoveRequest { } /// MCP server name and replacement configuration to write to user configuration. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigUpdateRequest { @@ -4198,6 +5225,13 @@ pub struct McpDisableRequest { } /// Optional working directory used as context for MCP server discovery. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpDiscoverRequest { @@ -4207,6 +5241,13 @@ pub struct McpDiscoverRequest { } /// MCP servers discovered from user, workspace, plugin, and built-in sources. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpDiscoverResult { @@ -4262,7 +5303,7 @@ pub struct McpExecuteSamplingParams { pub server_name: String, } -/// Schema for the `McpFilteredServer` type. +/// MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. /// ///
/// @@ -4285,6 +5326,52 @@ pub struct McpFilteredServer { pub redacted_reason: Option, } +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpHeadersHandlePendingHeadersRefreshRequestHeaders { + /// Headers to overlay onto the MCP request. Dynamic headers override static config headers but do not replace SDK-managed request headers. + pub headers: HashMap, + pub kind: McpHeadersHandlePendingHeadersRefreshRequestHeadersKind, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpHeadersHandlePendingHeadersRefreshRequestNone { + pub kind: McpHeadersHandlePendingHeadersRefreshRequestNoneKind, +} + +/// MCP headers refresh request id and the host response. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpHeadersHandlePendingHeadersRefreshRequestRequest { + /// Headers refresh request identifier from mcp.headers_refresh_required + pub request_id: RequestId, + /// Host response: supply dynamic headers or decline this refresh. + pub result: McpHeadersHandlePendingHeadersRefreshRequest, +} + +/// Indicates whether the pending MCP headers refresh response was accepted. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpHeadersHandlePendingHeadersRefreshRequestResult { + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + pub success: bool, +} + /// Recorded MCP server connection failure. /// ///
@@ -4389,7 +5476,26 @@ pub struct McpListToolsRequest { pub server_name: String, } -/// Schema for the `McpTools` type. +/// Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpToolUi { + /// URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use `session.mcp.resources.read` to fetch its HTML and resource metadata. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_uri: Option, + /// Tool visibility advertised by the server. When absent, MCP Apps defaults apply. + #[serde(skip_serializing_if = "Option::is_none")] + pub visibility: Option>, +} + +/// MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery metadata. /// ///
/// @@ -4405,6 +5511,9 @@ pub struct McpTools { pub description: Option, /// Tool name. pub name: String, + /// Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` block was present without recognized fields. + #[serde(skip_serializing_if = "Option::is_none")] + pub ui: Option, } /// Tools exposed by the connected MCP server. Throws when the server is not connected. @@ -4431,9 +5540,6 @@ pub struct McpOauthPendingRequestResponseToken { #[serde(skip_serializing_if = "Option::is_none")] pub expires_in: Option, pub kind: McpOauthPendingRequestResponseTokenKind, - /// Refresh token supplied by the host, if available. - #[serde(skip_serializing_if = "Option::is_none")] - pub refresh_token: Option, /// OAuth token type. Defaults to Bearer when omitted. #[serde(skip_serializing_if = "Option::is_none")] pub token_type: Option, @@ -4529,7 +5635,31 @@ pub struct McpOauthLoginResult { pub authorization_url: Option, } -/// MCP OAuth request id and optional provider response. +/// Registration parameters for an external MCP client. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct McpRegisterExternalClientRequest { + /// In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC boundary. + #[doc(hidden)] + pub(crate) client: serde_json::Value, + /// In-process server config (MCPServerConfig) paired with the in-process client/transport. Marked internal alongside its companions. + #[doc(hidden)] + pub(crate) config: serde_json::Value, + /// Logical server name for the external client + pub server_name: String, + /// In-process MCP Transport instance. Marked internal: cannot be serialized across the JSON-RPC boundary. + #[doc(hidden)] + pub(crate) transport: serde_json::Value, +} + +/// Opaque MCP reload configuration. /// ///
/// @@ -4539,16 +5669,53 @@ pub struct McpOauthLoginResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct McpOauthRespondRequest { - /// In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be serialized across the JSON-RPC boundary. +pub(crate) struct McpReloadWithConfigRequest { + /// Opaque runtime MCP reload configuration. Marked internal: an in-process runtime shape (reloadMcpServers throws over the wire). #[doc(hidden)] + pub(crate) config: serde_json::Value, +} + +/// Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove). +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpRemoveGitHubResult { + /// True when the auto-managed `github` MCP server was removed; false when no removal happened (e.g. user has explicitly configured a `github` server, or the server was not registered). + pub removed: bool, +} + +/// Standard MCP resource annotations plus preserved non-standard annotation fields. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourceAnnotations { + /// Server-provided non-standard annotation fields preserved from the MCP response #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) provider: Option, - /// OAuth request identifier from mcp.oauth_required - pub request_id: RequestId, + pub additional_properties: Option>, + /// Intended audience roles for this resource + #[serde(skip_serializing_if = "Option::is_none")] + pub audience: Option>, + /// Last-modified timestamp hint + #[serde(skip_serializing_if = "Option::is_none")] + pub last_modified: Option, + /// Priority hint for model/client use + #[serde(skip_serializing_if = "Option::is_none")] + pub priority: Option, } -/// Empty result after recording the MCP OAuth response. +/// A resource icon descriptor plus preserved non-standard icon fields. /// ///
/// @@ -4558,9 +5725,24 @@ pub(crate) struct McpOauthRespondRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct McpOauthRespondResult {} +pub struct McpResourceIcon { + /// Server-provided non-standard icon fields preserved from the MCP response + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_properties: Option>, + /// Icon MIME type, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub mime_type: Option, + /// Icon sizes hint + #[serde(skip_serializing_if = "Option::is_none")] + pub sizes: Option, + /// Icon URI + pub src: String, + /// Theme hint for this icon + #[serde(skip_serializing_if = "Option::is_none")] + pub theme: Option, +} -/// Registration parameters for an external MCP client. +/// An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, MIME type, size, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. /// ///
/// @@ -4570,21 +5752,175 @@ pub struct McpOauthRespondResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct McpRegisterExternalClientRequest { - /// In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC boundary. - #[doc(hidden)] - pub(crate) client: serde_json::Value, - /// In-process server config (MCPServerConfig) paired with the in-process client/transport. Marked internal alongside its companions. - #[doc(hidden)] - pub(crate) config: serde_json::Value, - /// Logical server name for the external client +pub struct McpResource { + /// Resource-level metadata + #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option>, + /// Server-provided non-standard descriptor fields preserved from the MCP response + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_properties: Option>, + /// Model/client annotations associated with this resource + #[serde(skip_serializing_if = "Option::is_none")] + pub annotations: Option, + /// Optional description of what this resource represents + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Icons associated with this resource + #[serde(skip_serializing_if = "Option::is_none")] + pub icons: Option>, + /// MIME type of the resource, if known + #[serde(skip_serializing_if = "Option::is_none")] + pub mime_type: Option, + /// The programmatic name of the resource + pub name: String, + /// Resource size in bytes, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub size: Option, + /// Optional human-readable display title + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// The resource URI (e.g. ui://... or file:///...) + pub uri: String, +} + +/// MCP resource content with URI, optional MIME type, text or base64 blob, and resource metadata. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourceContent { + /// Resource-level metadata (CSP, permissions, etc.) + #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option>, + /// Base64-encoded binary content + #[serde(skip_serializing_if = "Option::is_none")] + pub blob: Option, + /// MIME type of the content + #[serde(skip_serializing_if = "Option::is_none")] + pub mime_type: Option, + /// Text content (e.g. HTML) + #[serde(skip_serializing_if = "Option::is_none")] + pub text: Option, + /// The resource URI + pub uri: String, +} + +/// MCP server whose resources to enumerate. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourcesListRequest { + /// Opaque MCP pagination cursor from a prior `nextCursor` value + #[serde(skip_serializing_if = "Option::is_none")] + pub cursor: Option, + /// Name of the MCP server whose resources to enumerate pub server_name: String, - /// In-process MCP Transport instance. Marked internal: cannot be serialized across the JSON-RPC boundary. - #[doc(hidden)] - pub(crate) transport: serde_json::Value, } -/// Opaque MCP reload configuration. +/// One page of resources advertised by the named MCP server. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourcesListResult { + /// Opaque cursor for the next page, if the server has more resources + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Resources advertised by the server (proxied MCP `resources/list`) + pub resources: Vec, +} + +/// MCP server whose resource templates to enumerate. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourcesListTemplatesRequest { + /// Opaque MCP pagination cursor from a prior `nextCursor` value + #[serde(skip_serializing_if = "Option::is_none")] + pub cursor: Option, + /// Name of the MCP server whose resource templates to enumerate + pub server_name: String, +} + +/// An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, name, and optional title, description, MIME type, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourceTemplate { + /// Resource-template-level metadata + #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option>, + /// Server-provided non-standard descriptor fields preserved from the MCP response + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_properties: Option>, + /// Model/client annotations associated with this template + #[serde(skip_serializing_if = "Option::is_none")] + pub annotations: Option, + /// Optional description of what this template is for + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Icons associated with resources matching this template + #[serde(skip_serializing_if = "Option::is_none")] + pub icons: Option>, + /// MIME type for resources matching this template, if uniform + #[serde(skip_serializing_if = "Option::is_none")] + pub mime_type: Option, + /// The programmatic name of the resource template + pub name: String, + /// Optional human-readable display title + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// An RFC 6570 URI template for constructing resource URIs + pub uri_template: String, +} + +/// One page of resource templates advertised by the named MCP server. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourcesListTemplatesResult { + /// Opaque cursor for the next page, if the server has more resource templates + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Resource templates advertised by the server (proxied MCP `resources/templates/list`) + pub resource_templates: Vec, +} + +/// MCP server and resource URI to fetch. /// ///
/// @@ -4594,13 +5930,14 @@ pub(crate) struct McpRegisterExternalClientRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct McpReloadWithConfigRequest { - /// Opaque runtime MCP reload configuration. Marked internal: an in-process runtime shape (reloadMcpServers throws over the wire). - #[doc(hidden)] - pub(crate) config: serde_json::Value, +pub struct McpResourcesReadRequest { + /// Name of the MCP server hosting the resource + pub server_name: String, + /// Resource URI + pub uri: String, } -/// Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove). +/// Resource contents returned by the MCP server. /// ///
/// @@ -4610,12 +5947,12 @@ pub(crate) struct McpReloadWithConfigRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct McpRemoveGitHubResult { - /// True when the auto-managed `github` MCP server was removed; false when no removal happened (e.g. user has explicitly configured a `github` server, or the server was not registered). - pub removed: bool, +pub struct McpResourcesReadResult { + /// Resource contents returned by the server + pub contents: Vec, } -/// Server name and opaque configuration for an individual MCP server restart. +/// Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. /// ///
/// @@ -4625,10 +5962,10 @@ pub struct McpRemoveGitHubResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct McpRestartServerRequest { - /// Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. - #[doc(hidden)] - pub(crate) config: serde_json::Value, +pub struct McpRestartServerRequest { + /// Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). + #[serde(skip_serializing_if = "Option::is_none")] + pub config: Option, /// Name of the MCP server to restart pub server_name: String, } @@ -4654,7 +5991,7 @@ pub struct McpSamplingExecutionResult { pub result: Option, } -/// Schema for the `McpServer` type. +/// MCP server status entry, including config source/plugin source and any connection error. /// ///
/// @@ -4684,6 +6021,13 @@ pub struct McpServer { } /// Authentication settings with optional redirect port configuration. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpServerAuthConfigRedirectPort { @@ -4693,6 +6037,13 @@ pub struct McpServerAuthConfigRedirectPort { } /// Remote MCP server configuration accessed over HTTP or SSE. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpServerConfigHttp { @@ -4737,6 +6088,13 @@ pub struct McpServerConfigHttp { } /// Stdio MCP server configuration launched as a child process. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpServerConfigStdio { @@ -4822,7 +6180,7 @@ pub struct McpSetEnvValueModeResult { pub mode: McpSetEnvValueModeDetails, } -/// Server name and opaque configuration for an individual MCP server start. +/// Server name and configuration for an individual MCP server start. /// ///
/// @@ -4832,10 +6190,9 @@ pub struct McpSetEnvValueModeResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct McpStartServerRequest { - /// Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. - #[doc(hidden)] - pub(crate) config: serde_json::Value, +pub struct McpStartServerRequest { + /// MCP server configuration (stdio process or remote HTTP/SSE) + pub config: serde_json::Value, /// Name of the MCP server to start pub server_name: String, } @@ -4903,6 +6260,93 @@ pub struct MemoryConfiguration { pub enabled: bool, } +/// Successful compaction history for the session. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MetadataContextAttributionResultContextAttributionCompactions { + /// Number of successful compactions in this session. + pub count: i64, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MetadataContextAttributionResultContextAttributionEntriesItem { + /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option>, + /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + pub id: String, + /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + pub kind: String, + /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + pub label: String, + /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + /// Token count currently in context attributable to this entry. + pub tokens: i64, +} + +/// Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MetadataContextAttributionResultContextAttribution { + /// Successful compaction history for the session. + pub compactions: MetadataContextAttributionResultContextAttributionCompactions, + /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + pub entries: Vec, + /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + pub total_tokens: i64, +} + +/// Per-source attribution breakdown for the session's current context window, or null if uninitialized. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MetadataContextAttributionResult { + /// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + pub context_attribution: Option, +} + +/// Parameters for the heaviest-messages query. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MetadataContextHeaviestMessagesRequest { + /// Maximum number of messages to return, most-expensive first. Omit for the server default. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// The heaviest individual messages in the session's context window, most-expensive first. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MetadataContextHeaviestMessagesResult { + /// Heaviest messages, most-expensive first. + pub messages: Vec, + /// Total token count of the current context window, so callers can compute each message's share without a second call. + pub total_tokens: i64, +} + /// Model identifier and token limits used to compute the context-info breakdown. /// ///
@@ -5076,7 +6520,7 @@ pub struct MetadataRecordContextChangeRequest { #[serde(rename_all = "camelCase")] pub struct MetadataRecordContextChangeResult {} -/// Absolute path to set as the session's new working directory. +/// Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. /// ///
/// @@ -5091,7 +6535,7 @@ pub struct MetadataSetWorkingDirectoryRequest { pub working_directory: String, } -/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. +/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. /// ///
/// @@ -5149,7 +6593,38 @@ pub struct MetadataSnapshotRemoteMetadata { pub task_type: Option, } +/// Active server-driven promotion for a model, including its discount and expiry. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelBillingPromo { + /// Percentage discount (0-100) applied while the promotion is active. May be fractional. + #[serde(skip_serializing_if = "Option::is_none")] + pub discount_percent: Option, + /// UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. + pub ends_at: String, + /// Stable identifier for the promotion campaign. + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, +} + /// Long context tier pricing (available for models with extended context windows) +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelBillingTokenPricesLongContext { @@ -5181,6 +6656,13 @@ pub struct ModelBillingTokenPricesLongContext { } /// Token-level pricing information for this model +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelBillingTokenPrices { @@ -5218,18 +6700,38 @@ pub struct ModelBillingTokenPrices { } /// Billing information +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelBilling { + /// Whole-number percentage discount (0-100) applied to usage billed through this model. Populated for the synthetic `auto` model, where requests routed by auto-mode are billed at a reduced rate; absent for concrete models. + #[serde(skip_serializing_if = "Option::is_none")] + pub discount_percent: Option, /// Billing cost multiplier relative to the base rate #[serde(skip_serializing_if = "Option::is_none")] pub multiplier: Option, + /// Active server-driven promotion for this model, if any. Present when the model is being promoted with a time-boxed discount. + #[serde(skip_serializing_if = "Option::is_none")] + pub promo: Option, /// Token-level pricing information for this model #[serde(skip_serializing_if = "Option::is_none")] pub token_prices: Option, } /// Vision-specific limits +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelCapabilitiesLimitsVision { @@ -5245,6 +6747,13 @@ pub struct ModelCapabilitiesLimitsVision { } /// Token limits for prompts, outputs, and context window +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelCapabilitiesLimits { @@ -5266,9 +6775,19 @@ pub struct ModelCapabilitiesLimits { } /// Feature flags indicating what the model supports +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelCapabilitiesSupports { + /// Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + #[serde(rename = "adaptive_thinking", skip_serializing_if = "Option::is_none")] + pub adaptive_thinking: Option, /// Whether this model supports reasoning effort configuration #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, @@ -5278,6 +6797,13 @@ pub struct ModelCapabilitiesSupports { } /// Model capabilities and limits +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelCapabilities { @@ -5290,6 +6816,13 @@ pub struct ModelCapabilities { } /// Policy state (if applicable) +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelPolicy { @@ -5300,7 +6833,14 @@ pub struct ModelPolicy { pub terms: Option, } -/// Schema for the `Model` type. +/// Copilot model metadata, including identifier, display name, capabilities, policy, billing, reasoning efforts, and picker categories. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Model { @@ -5397,6 +6937,9 @@ pub struct ModelCapabilitiesOverrideLimits { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelCapabilitiesOverrideSupports { + /// Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + #[serde(rename = "adaptive_thinking", skip_serializing_if = "Option::is_none")] + pub adaptive_thinking: Option, /// Whether this model supports reasoning effort configuration #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, @@ -5425,6 +6968,13 @@ pub struct ModelCapabilitiesOverride { } /// List of Copilot models available to the resolved user, including capabilities and billing metadata. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelList { @@ -5479,6 +7029,13 @@ pub struct ModelSetReasoningEffortResult { } /// Optional GitHub token used to list models for a specific user instead of the global auth context. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelsListRequest { @@ -5512,6 +7069,9 @@ pub struct ModelSwitchToRequest { /// Reasoning summary mode to request for supported model clients #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_summary: Option, + /// Output verbosity level to request for supported models + #[serde(skip_serializing_if = "Option::is_none")] + pub verbosity: Option, } /// The model identifier active on the session after the switch. @@ -5662,7 +7222,7 @@ pub struct NameSetRequest { pub name: String, } -/// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. +/// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. /// ///
/// @@ -5677,7 +7237,7 @@ pub struct OptionsUpdateAdditionalContentExclusionPolicyRuleSource { pub r#type: String, } -/// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRule` type. +/// Single content-exclusion rule supplied to `session.options.update`, with paths, match conditions, and source. /// ///
/// @@ -5693,11 +7253,11 @@ pub struct OptionsUpdateAdditionalContentExclusionPolicyRule { #[serde(skip_serializing_if = "Option::is_none")] pub if_none_match: Option>, pub paths: Vec, - /// Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. + /// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. pub source: OptionsUpdateAdditionalContentExclusionPolicyRuleSource, } -/// Schema for the `OptionsUpdateAdditionalContentExclusionPolicy` type. +/// Content-exclusion policy supplied to `session.options.update`, with rules, last-updated data, and scope. /// ///
/// @@ -5715,7 +7275,7 @@ pub struct OptionsUpdateAdditionalContentExclusionPolicy { pub scope: OptionsUpdateAdditionalContentExclusionPolicyScope, } -/// Schema for the `PendingPermissionRequest` type. +/// Pending permission prompt reconstructed from event history, with request ID and user-facing prompt details. /// ///
/// @@ -5747,7 +7307,7 @@ pub struct PendingPermissionRequestList { pub items: Vec, } -/// Schema for the `PermissionDecisionApproveOnce` type. +/// Permission-decision request variant to approve only the current permission request. /// ///
/// @@ -5762,7 +7322,7 @@ pub struct PermissionDecisionApproveOnce { pub kind: PermissionDecisionApproveOnceKind, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalCommands` type. +/// Session-scoped approval details for specific command identifiers. /// ///
/// @@ -5779,7 +7339,7 @@ pub struct PermissionDecisionApproveForSessionApprovalCommands { pub kind: PermissionDecisionApproveForSessionApprovalCommandsKind, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalRead` type. +/// Session-scoped approval details for read-only filesystem operations. /// ///
/// @@ -5794,7 +7354,7 @@ pub struct PermissionDecisionApproveForSessionApprovalRead { pub kind: PermissionDecisionApproveForSessionApprovalReadKind, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalWrite` type. +/// Session-scoped approval details for filesystem write operations. /// ///
/// @@ -5809,7 +7369,7 @@ pub struct PermissionDecisionApproveForSessionApprovalWrite { pub kind: PermissionDecisionApproveForSessionApprovalWriteKind, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalMcp` type. +/// Session-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. /// ///
/// @@ -5828,7 +7388,7 @@ pub struct PermissionDecisionApproveForSessionApprovalMcp { pub tool_name: Option, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalMcpSampling` type. +/// Session-scoped approval details for MCP sampling requests from a server. /// ///
/// @@ -5845,7 +7405,7 @@ pub struct PermissionDecisionApproveForSessionApprovalMcpSampling { pub server_name: String, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalMemory` type. +/// Session-scoped approval details for writes to long-term memory. /// ///
/// @@ -5860,7 +7420,7 @@ pub struct PermissionDecisionApproveForSessionApprovalMemory { pub kind: PermissionDecisionApproveForSessionApprovalMemoryKind, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalCustomTool` type. +/// Session-scoped approval details for a custom tool, keyed by tool name. /// ///
/// @@ -5877,7 +7437,7 @@ pub struct PermissionDecisionApproveForSessionApprovalCustomTool { pub tool_name: String, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalExtensionManagement` type. +/// Session-scoped approval details for extension-management operations, optionally narrowed by operation. /// ///
/// @@ -5895,7 +7455,7 @@ pub struct PermissionDecisionApproveForSessionApprovalExtensionManagement { pub operation: Option, } -/// Schema for the `PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess` type. +/// Session-scoped approval details for an extension's permission-gated capability access, keyed by extension name. /// ///
/// @@ -5912,7 +7472,7 @@ pub struct PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess pub kind: PermissionDecisionApproveForSessionApprovalExtensionPermissionAccessKind, } -/// Schema for the `PermissionDecisionApproveForSession` type. +/// Permission-decision request variant to approve for the rest of the session, with optional tool approval or URL domain. /// ///
/// @@ -5933,7 +7493,7 @@ pub struct PermissionDecisionApproveForSession { pub kind: PermissionDecisionApproveForSessionKind, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalCommands` type. +/// Location-scoped approval details for specific command identifiers. /// ///
/// @@ -5950,7 +7510,7 @@ pub struct PermissionDecisionApproveForLocationApprovalCommands { pub kind: PermissionDecisionApproveForLocationApprovalCommandsKind, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalRead` type. +/// Location-scoped approval details for read-only filesystem operations. /// ///
/// @@ -5965,7 +7525,7 @@ pub struct PermissionDecisionApproveForLocationApprovalRead { pub kind: PermissionDecisionApproveForLocationApprovalReadKind, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalWrite` type. +/// Location-scoped approval details for filesystem write operations. /// ///
/// @@ -5980,7 +7540,7 @@ pub struct PermissionDecisionApproveForLocationApprovalWrite { pub kind: PermissionDecisionApproveForLocationApprovalWriteKind, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalMcp` type. +/// Location-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. /// ///
/// @@ -5999,7 +7559,7 @@ pub struct PermissionDecisionApproveForLocationApprovalMcp { pub tool_name: Option, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalMcpSampling` type. +/// Location-scoped approval details for MCP sampling requests from a server. /// ///
/// @@ -6016,7 +7576,7 @@ pub struct PermissionDecisionApproveForLocationApprovalMcpSampling { pub server_name: String, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalMemory` type. +/// Location-scoped approval details for writes to long-term memory. /// ///
/// @@ -6031,7 +7591,7 @@ pub struct PermissionDecisionApproveForLocationApprovalMemory { pub kind: PermissionDecisionApproveForLocationApprovalMemoryKind, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalCustomTool` type. +/// Location-scoped approval details for a custom tool, keyed by tool name. /// ///
/// @@ -6048,7 +7608,7 @@ pub struct PermissionDecisionApproveForLocationApprovalCustomTool { pub tool_name: String, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalExtensionManagement` type. +/// Location-scoped approval details for extension-management operations, optionally narrowed by operation. /// ///
/// @@ -6066,7 +7626,7 @@ pub struct PermissionDecisionApproveForLocationApprovalExtensionManagement { pub operation: Option, } -/// Schema for the `PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess` type. +/// Location-scoped approval details for an extension's permission-gated capability access, keyed by extension name. /// ///
/// @@ -6083,7 +7643,7 @@ pub struct PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess pub kind: PermissionDecisionApproveForLocationApprovalExtensionPermissionAccessKind, } -/// Schema for the `PermissionDecisionApproveForLocation` type. +/// Permission-decision request variant to approve and persist a permission for a project location, with approval details and location key. /// ///
/// @@ -6102,7 +7662,7 @@ pub struct PermissionDecisionApproveForLocation { pub location_key: String, } -/// Schema for the `PermissionDecisionApprovePermanently` type. +/// Permission-decision request variant to permanently approve a URL domain across sessions. /// ///
/// @@ -6119,7 +7679,7 @@ pub struct PermissionDecisionApprovePermanently { pub kind: PermissionDecisionApprovePermanentlyKind, } -/// Schema for the `PermissionDecisionReject` type. +/// Permission-decision request variant to reject a pending permission request, with optional feedback. /// ///
/// @@ -6137,7 +7697,7 @@ pub struct PermissionDecisionReject { pub kind: PermissionDecisionRejectKind, } -/// Schema for the `PermissionDecisionUserNotAvailable` type. +/// Permission-decision variant indicating no user was available to confirm the request. /// ///
/// @@ -6152,7 +7712,7 @@ pub struct PermissionDecisionUserNotAvailable { pub kind: PermissionDecisionUserNotAvailableKind, } -/// Schema for the `PermissionDecisionApproved` type. +/// Permission-decision variant indicating the request was approved. /// ///
/// @@ -6167,7 +7727,7 @@ pub struct PermissionDecisionApproved { pub kind: PermissionDecisionApprovedKind, } -/// Schema for the `PermissionDecisionApprovedForSession` type. +/// Permission-decision variant indicating approval was remembered for the session, with approval details. /// ///
/// @@ -6184,7 +7744,7 @@ pub struct PermissionDecisionApprovedForSession { pub kind: PermissionDecisionApprovedForSessionKind, } -/// Schema for the `PermissionDecisionApprovedForLocation` type. +/// Permission-decision variant indicating approval was persisted for a project location, with approval details and location key. /// ///
/// @@ -6203,7 +7763,7 @@ pub struct PermissionDecisionApprovedForLocation { pub location_key: String, } -/// Schema for the `PermissionDecisionCancelled` type. +/// Permission-decision variant indicating the request was cancelled before use, with an optional reason. /// ///
/// @@ -6221,7 +7781,7 @@ pub struct PermissionDecisionCancelled { pub reason: Option, } -/// Schema for the `PermissionDecisionDeniedByRules` type. +/// Permission-decision variant indicating explicit denial by permission rules, with the matching rules. /// ///
/// @@ -6238,7 +7798,7 @@ pub struct PermissionDecisionDeniedByRules { pub rules: Vec, } -/// Schema for the `PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. +/// Permission-decision variant indicating no approval rule matched and user confirmation was unavailable. /// ///
/// @@ -6253,7 +7813,7 @@ pub struct PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser { pub kind: PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUserKind, } -/// Schema for the `PermissionDecisionDeniedInteractivelyByUser` type. +/// Permission-decision variant indicating the user denied an interactive prompt, with optional feedback and force-reject flag. /// ///
/// @@ -6274,7 +7834,7 @@ pub struct PermissionDecisionDeniedInteractivelyByUser { pub kind: PermissionDecisionDeniedInteractivelyByUserKind, } -/// Schema for the `PermissionDecisionDeniedByContentExclusionPolicy` type. +/// Permission-decision variant indicating denial by content-exclusion policy, with path and message. /// ///
/// @@ -6293,7 +7853,7 @@ pub struct PermissionDecisionDeniedByContentExclusionPolicy { pub path: String, } -/// Schema for the `PermissionDecisionDeniedByPermissionRequestHook` type. +/// Permission-decision variant indicating denial by a permission request hook, with optional message and interrupt flag. /// ///
/// @@ -6331,7 +7891,7 @@ pub struct PermissionDecisionRequest { pub result: PermissionDecision, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsCommands` type. +/// Location-persisted tool approval details for specific command identifiers. /// ///
/// @@ -6348,7 +7908,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsCommands { pub kind: PermissionsLocationsAddToolApprovalDetailsCommandsKind, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsRead` type. +/// Location-persisted tool approval details for read-only filesystem operations. /// ///
/// @@ -6363,7 +7923,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsRead { pub kind: PermissionsLocationsAddToolApprovalDetailsReadKind, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsWrite` type. +/// Location-persisted tool approval details for filesystem write operations. /// ///
/// @@ -6378,7 +7938,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsWrite { pub kind: PermissionsLocationsAddToolApprovalDetailsWriteKind, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsMcp` type. +/// Location-persisted tool approval details for an MCP server tool, or all tools when `toolName` is null. /// ///
/// @@ -6397,7 +7957,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsMcp { pub tool_name: Option, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsMcpSampling` type. +/// Location-persisted tool approval details for MCP sampling requests from a server. /// ///
/// @@ -6414,7 +7974,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsMcpSampling { pub server_name: String, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsMemory` type. +/// Location-persisted tool approval details for writes to long-term memory. /// ///
/// @@ -6429,7 +7989,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsMemory { pub kind: PermissionsLocationsAddToolApprovalDetailsMemoryKind, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsCustomTool` type. +/// Location-persisted tool approval details for a custom tool, keyed by tool name. /// ///
/// @@ -6446,7 +8006,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsCustomTool { pub tool_name: String, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionManagement` type. +/// Location-persisted tool approval details for extension-management operations, optionally narrowed by operation. /// ///
/// @@ -6464,7 +8024,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsExtensionManagement { pub operation: Option, } -/// Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess` type. +/// Location-persisted tool approval details for an extension's permission-gated capability access, keyed by extension name. /// ///
/// @@ -6749,7 +8309,7 @@ pub struct PermissionRulesSet { pub denied: Vec, } -/// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. +/// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. /// ///
/// @@ -6764,7 +8324,7 @@ pub struct PermissionsConfigureAdditionalContentExclusionPolicyRuleSource { pub r#type: String, } -/// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRule` type. +/// Single content-exclusion rule supplied to `session.permissions.configure`, with paths, match conditions, and source. /// ///
/// @@ -6780,11 +8340,11 @@ pub struct PermissionsConfigureAdditionalContentExclusionPolicyRule { #[serde(skip_serializing_if = "Option::is_none")] pub if_none_match: Option>, pub paths: Vec, - /// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. + /// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. pub source: PermissionsConfigureAdditionalContentExclusionPolicyRuleSource, } -/// Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. +/// Content-exclusion policy supplied to `session.permissions.configure`, with rules, last-updated data, and scope. /// ///
/// @@ -7045,7 +8605,7 @@ pub struct PermissionsResetSessionApprovalsResult { pub success: bool, } -/// Whether to enable full allow-all permissions for the session. +/// Allow-all mode to apply for the session. /// ///
/// @@ -7056,8 +8616,15 @@ pub struct PermissionsResetSessionApprovalsResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionsSetAllowAllRequest { - /// Whether to enable full allow-all permissions - pub enabled: bool, + /// Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled: Option, + /// Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM auto-approval; `off` disables both. + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + /// Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, /// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. #[serde(skip_serializing_if = "Option::is_none")] pub source: Option, @@ -7157,6 +8724,13 @@ pub struct PermissionUrlsSetUnrestrictedModeParams { } /// Optional message to echo back to the caller. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PingRequest { @@ -7166,6 +8740,13 @@ pub struct PingRequest { } /// Server liveness response, including the echoed message, current server timestamp, and protocol version. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PingResult { @@ -7285,7 +8866,7 @@ pub struct PlanUpdateRequest { pub content: String, } -/// Schema for the `Plugin` type. +/// Session plugin metadata, with name, marketplace, optional version, and enabled state. /// ///
/// @@ -7408,7 +8989,7 @@ pub struct PluginsInstallRequest { pub working_directory: Option, } -/// Marketplace source to register. +/// Marketplace source and optional working directory for relative-path resolution. /// ///
/// @@ -7421,6 +9002,9 @@ pub struct PluginsInstallRequest { pub struct PluginsMarketplacesAddRequest { /// Marketplace source. Accepts the same forms as the CLI: "owner/repo" or "owner/repo#ref" (GitHub), an http/https/ssh URL (optionally with #ref), a git scp-style URL (user@host:path), or a local path. The marketplace's own name (from its manifest) is used as the registration key. pub source: String, + /// Working directory used to resolve relative local paths in `source`. Defaults to the server's current working directory. + #[serde(skip_serializing_if = "Option::is_none")] + pub working_directory: Option, } /// Name of the marketplace whose plugin catalog to fetch. @@ -7489,6 +9073,9 @@ pub struct PluginsReloadRequest { /// Re-run custom-agent discovery after refreshing plugins. Defaults to true. #[serde(skip_serializing_if = "Option::is_none")] pub reload_custom_agents: Option, + /// Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + #[serde(skip_serializing_if = "Option::is_none")] + pub reload_extensions: Option, /// Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). #[serde(skip_serializing_if = "Option::is_none")] pub reload_hooks: Option, @@ -7508,6 +9095,9 @@ pub struct PluginsReloadRequest { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PluginsUninstallRequest { + /// Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall when multiple installed plugins share the same name. + #[serde(skip_serializing_if = "Option::is_none")] + pub direct_source_id: Option, /// Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the fully-qualified spec. pub name: String, } @@ -7527,7 +9117,7 @@ pub struct PluginsUpdateRequest { pub name: String, } -/// Schema for the `PluginUpdateAllEntry` type. +/// Per-plugin result from updating all plugins, with versions, skills installed, success flag, and optional error. /// ///
/// @@ -7553,48 +9143,12 @@ pub struct PluginUpdateAllEntry { pub previous_version: Option, /// Number of skills installed after the update (success only) #[serde(skip_serializing_if = "Option::is_none")] - pub skills_installed: Option, - /// Whether the update succeeded for this plugin - pub success: bool, -} - -/// Result of updating all installed plugins. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PluginUpdateAllResult { - /// Per-plugin update results in deterministic order. - pub results: Vec, -} - -/// Result of updating a single plugin. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PluginUpdateResult { - /// Version after the update, when reported by the plugin manifest - #[serde(skip_serializing_if = "Option::is_none")] - pub new_version: Option, - /// Version that was previously installed, when available - #[serde(skip_serializing_if = "Option::is_none")] - pub previous_version: Option, - /// Number of skills discovered and installed after the update - pub skills_installed: i64, + pub skills_installed: Option, + /// Whether the update succeeded for this plugin + pub success: bool, } -/// Schema for the `SessionsPollSpawnedSessionsEvent` type. +/// Result of updating all installed plugins. /// ///
/// @@ -7604,12 +9158,12 @@ pub struct PluginUpdateResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsPollSpawnedSessionsEvent { - /// Session id of the newly-spawned session. - pub session_id: SessionId, +pub struct PluginUpdateAllResult { + /// Per-plugin update results in deterministic order. + pub results: Vec, } -/// Batch of spawn events plus a cursor for follow-up polls. +/// Result of updating a single plugin. /// ///
/// @@ -7619,11 +9173,15 @@ pub struct SessionsPollSpawnedSessionsEvent { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PollSpawnedSessionsResult { - /// Opaque cursor to pass back to receive only events after this batch. - pub cursor: String, - /// Spawn events emitted since the supplied cursor. - pub events: Vec, +pub struct PluginUpdateResult { + /// Version after the update, when reported by the plugin manifest + #[serde(skip_serializing_if = "Option::is_none")] + pub new_version: Option, + /// Version that was previously installed, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub previous_version: Option, + /// Number of skills discovered and installed after the update + pub skills_installed: i64, } /// A BYOK model definition referencing a named provider. @@ -7934,6 +9492,142 @@ pub struct PushAttachmentFile { pub r#type: PushAttachmentFileType, } +/// Pointer to a GitHub repository. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushGitHubRepoRef { + /// Numeric GitHub repository id + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Repository name (without owner) + pub name: String, + /// Repository owner login (user or organization) + pub owner: String, +} + +/// Pointer to a GitHub Actions job. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubActionsJob { + /// Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. + #[serde(skip_serializing_if = "Option::is_none")] + pub conclusion: Option, + /// Job id within the workflow run + pub job_id: i64, + /// Display name of the job + pub job_name: String, + /// Repository the workflow run belongs to + pub repo: PushGitHubRepoRef, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubActionsJobType, + /// URL to the job on GitHub + pub url: String, + /// Display name of the workflow the job ran in + pub workflow_name: String, +} + +/// Pointer to a GitHub commit. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubCommit { + /// First line of the commit message + pub message: String, + /// Full commit SHA + pub oid: String, + /// Repository the commit belongs to + pub repo: PushGitHubRepoRef, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubCommitType, + /// URL to the commit on GitHub + pub url: String, +} + +/// Pointer to a file in a GitHub repository at a specific ref. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubFile { + /// Repository-relative path to the file + pub path: String, + /// Git ref the file is read at (branch, tag, or commit SHA) + pub r#ref: String, + /// Repository the file lives in + pub repo: PushGitHubRepoRef, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubFileType, + /// URL to the file on GitHub + pub url: String, +} + +/// One side of a file diff (head or base) +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubFileDiffSide { + /// Repository-relative path to the file + pub path: String, + /// Git ref (branch, tag, or commit SHA) the file is read at + pub r#ref: String, + /// Repository the file lives in + pub repo: PushGitHubRepoRef, +} + +/// Pointer to a single-file diff. At least one of `head` and `base` must be present. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubFileDiff { + /// File location on the base side of the diff. Absent for additions. + #[serde(skip_serializing_if = "Option::is_none")] + pub base: Option, + /// File location on the head side of the diff. Absent for deletions. + #[serde(skip_serializing_if = "Option::is_none")] + pub head: Option, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubFileDiffType, + /// URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) + pub url: String, +} + /// GitHub issue, pull request, or discussion reference /// ///
@@ -7959,6 +9653,134 @@ pub struct PushAttachmentGitHubReference { pub url: String, } +/// Pointer to a GitHub release. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubRelease { + /// Human-readable release name + pub name: String, + /// Repository the release belongs to + pub repo: PushGitHubRepoRef, + /// Git tag the release is anchored to + pub tag_name: String, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubReleaseType, + /// URL to the release on GitHub + pub url: String, +} + +/// Pointer to a GitHub repository. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubRepository { + /// Short description of the repository + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. + #[serde(skip_serializing_if = "Option::is_none")] + pub r#ref: Option, + /// Repository pointer + pub repo: PushGitHubRepoRef, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubRepositoryType, + /// URL to the repository on GitHub + pub url: String, +} + +/// Pointer to a line range inside a file in a GitHub repository. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubSnippet { + /// Line range the snippet covers + pub line_range: PushAttachmentFileLineRange, + /// Repository-relative path to the file + pub path: String, + /// Git ref the file is read at (branch, tag, or commit SHA) + pub r#ref: String, + /// Repository the file lives in + pub repo: PushGitHubRepoRef, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubSnippetType, + /// URL to the snippet on GitHub (with line anchor) + pub url: String, +} + +/// One side of a tree comparison (head or base) +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubTreeComparisonSide { + /// Repository the revision belongs to + pub repo: PushGitHubRepoRef, + /// Git revision (branch, tag, or commit SHA) + pub revision: String, +} + +/// Pointer to a comparison between two git revisions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubTreeComparison { + /// Base side of the comparison + pub base: PushAttachmentGitHubTreeComparisonSide, + /// Head side of the comparison + pub head: PushAttachmentGitHubTreeComparisonSide, + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubTreeComparisonType, + /// URL to the comparison on GitHub + pub url: String, +} + +/// Generic GitHub URL reference. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PushAttachmentGitHubUrl { + /// Attachment type discriminator + pub r#type: PushAttachmentGitHubUrlType, + /// URL to the GitHub resource + pub url: String, +} + /// End position of the selection /// ///
@@ -8033,7 +9855,7 @@ pub struct PushAttachmentSelection { pub r#type: PushAttachmentSelectionType, } -/// Schema for the `QueuedCommandHandled` type. +/// Queued-command response indicating the host executed the command, with an optional flag to stop queue processing. /// ///
/// @@ -8051,7 +9873,7 @@ pub struct QueuedCommandHandled { pub stop_processing_queue: Option, } -/// Schema for the `QueuedCommandNotHandled` type. +/// Queued-command response indicating the host did not execute the command and the queue may continue. /// ///
/// @@ -8066,7 +9888,7 @@ pub struct QueuedCommandNotHandled { pub handled: bool, } -/// Schema for the `QueuePendingItems` type. +/// User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. /// ///
/// @@ -8126,7 +9948,7 @@ pub struct QueueRemoveMostRecentResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RegisterEventInterestParams { - /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates the full interactive OAuth flow to the consumer; when no interest is registered the runtime installs a browserless fallback that silently reuses cached tokens). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. + /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. pub event_type: String, } @@ -8271,6 +10093,10 @@ pub struct RemoteControlConfig { pub struct RemoteControlStatusActive { /// Session id remote control is pointed at. pub attached_session_id: String, + /// True while a read-only/session-sync export is deferred, awaiting the first `user.message` before its MC session exists. Marked internal: this field is excluded from the public SDK surface and is populated only on the CLI in-process path. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) awaiting_first_message: Option, /// MC frontend URL for this session, when known. #[serde(skip_serializing_if = "Option::is_none")] pub frontend_url: Option, @@ -8619,18 +10445,12 @@ pub struct SandboxConfigUserPolicyFilesystem { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SandboxConfigUserPolicyNetwork { - /// Hosts allowed in addition to the base policy. - #[serde(skip_serializing_if = "Option::is_none")] - pub allowed_hosts: Option>, /// Whether traffic to local/loopback addresses is allowed. #[serde(skip_serializing_if = "Option::is_none")] pub allow_local_network: Option, /// Whether outbound network traffic is allowed at all. #[serde(skip_serializing_if = "Option::is_none")] pub allow_outbound: Option, - /// Hosts explicitly blocked. - #[serde(skip_serializing_if = "Option::is_none")] - pub blocked_hosts: Option>, } /// macOS seatbelt-specific options. @@ -8695,7 +10515,7 @@ pub struct SandboxConfig { pub user_policy: Option, } -/// Schema for the `ScheduleEntry` type. +/// Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. /// ///
/// @@ -8781,6 +10601,13 @@ pub struct ScheduleStopResult { } /// Secret values to add to the redaction filter. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SecretsAddFilterValuesRequest { @@ -8788,15 +10615,108 @@ pub struct SecretsAddFilterValuesRequest { pub values: Vec, } -/// Confirmation that the secret values were registered. +/// Confirmation that the secret values were registered. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SecretsAddFilterValuesResult { + /// Whether the values were successfully registered + pub ok: bool, +} + +/// Parameters for session.extensions.sendAttachmentsToMessage. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SendAttachmentsToMessageParams { + /// Attachments to push into the next user-message turn. extension_context entries take the slim shape; standard variants take their full AttachmentSchema shape. + pub attachments: Vec, + /// Optional canvas instance binding the push for provenance. When supplied, the runtime resolves the canvas, verifies it is owned by the calling extension, and stamps canvasId/instanceId onto each extension_context entry. When omitted, no resolution runs and those fields stay unset on the attachment. + #[serde(skip_serializing_if = "Option::is_none")] + pub instance_id: Option, +} + +/// A single user message to append to the session as part of a `session.sendMessages` turn +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SendMessageItem { + /// Optional attachments (files, directories, selections, blobs, GitHub references) to include with this message + #[serde(skip_serializing_if = "Option::is_none")] + pub attachments: Option>, + /// If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) billable: Option, + /// If provided, this is shown in the timeline instead of `prompt` + #[serde(skip_serializing_if = "Option::is_none")] + pub display_prompt: Option, + /// The user message text + pub prompt: String, + /// If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange + #[serde(skip_serializing_if = "Option::is_none")] + pub required_tool: Option, + /// Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) source: Option, +} + +/// Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SecretsAddFilterValuesResult { - /// Whether the values were successfully registered - pub ok: bool, +pub struct SendMessagesRequest { + /// The UI mode the agent was in when these messages were sent. Defaults to the session's current mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_mode: Option, + /// The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. + pub messages: Vec, + /// How to deliver the messages. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + /// If true, adds the messages to the front of the queue instead of the end + #[serde(skip_serializing_if = "Option::is_none")] + pub prepend: Option, + /// Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_headers: Option>, + /// W3C Trace Context traceparent header for distributed tracing of this agent turn + #[serde(skip_serializing_if = "Option::is_none")] + pub traceparent: Option, + /// W3C Trace Context tracestate header for distributed tracing + #[serde(skip_serializing_if = "Option::is_none")] + pub tracestate: Option, + /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. + #[serde(skip_serializing_if = "Option::is_none")] + pub wait: Option, } -/// Parameters for session.extensions.sendAttachmentsToMessage. +/// Result of sending zero or more user messages /// ///
/// @@ -8806,12 +10726,9 @@ pub struct SecretsAddFilterValuesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SendAttachmentsToMessageParams { - /// Attachments to push into the next user-message turn. extension_context entries take the slim shape; standard variants take their full AttachmentSchema shape. - pub attachments: Vec, - /// Optional canvas instance binding the push for provenance. When supplied, the runtime resolves the canvas, verifies it is owned by the calling extension, and stamps canvasId/instanceId onto each extension_context entry. When omitted, no resolution runs and those fields stay unset on the attachment. - #[serde(skip_serializing_if = "Option::is_none")] - pub instance_id: Option, +pub struct SendMessagesResult { + /// Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. + pub message_ids: Vec, } /// Parameters for sending a user message to the session @@ -8911,7 +10828,14 @@ pub struct ServerInstructionSourceList { pub sources: Vec, } -/// Schema for the `ServerSkill` type. +/// Server-side skill metadata, including name, description, source, enabled/invocable state, path, project path, and argument hint. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ServerSkill { @@ -8937,6 +10861,13 @@ pub struct ServerSkill { } /// Skills discovered across global and project sources. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ServerSkillList { @@ -9006,6 +10937,52 @@ pub struct SessionBulkDeleteResult { pub freed_bytes: HashMap, } +/// Successful compaction history for the session. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionContextAttributionCompactions { + /// Number of successful compactions in this session. + pub count: i64, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionContextAttributionEntriesItem { + /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option>, + /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + pub id: String, + /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + pub kind: String, + /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + pub label: String, + /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + /// Token count currently in context attributable to this entry. + pub tokens: i64, +} + +/// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionContextAttribution { + /// Successful compaction history for the session. + pub compactions: SessionContextAttributionCompactions, + /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + pub entries: Vec, + /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + pub total_tokens: i64, +} + /// Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). /// ///
@@ -9184,7 +11161,7 @@ pub struct SessionFsReaddirResult { pub error: Option, } -/// Schema for the `SessionFsReaddirWithTypesEntry` type. +/// Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. /// ///
/// @@ -9314,6 +11291,13 @@ pub struct SessionFsRmRequest { } /// Optional capabilities declared by the provider +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionFsSetProviderCapabilities { @@ -9323,6 +11307,13 @@ pub struct SessionFsSetProviderCapabilities { } /// Initial working directory, session-state path layout, and path conventions used to register the calling SDK client as the session filesystem provider. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionFsSetProviderRequest { @@ -9338,6 +11329,13 @@ pub struct SessionFsSetProviderRequest { } /// Indicates whether the calling client was registered as the session filesystem provider. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionFsSetProviderResult { @@ -9472,7 +11470,7 @@ pub struct SessionFsWriteFileRequest { pub mode: Option, } -/// Schema for the `SessionInstalledPlugin` type. +/// Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. /// ///
/// @@ -9503,7 +11501,7 @@ pub struct SessionInstalledPlugin { pub version: Option, } -/// Schema for the `SessionInstalledPluginSourceGitHub` type. +/// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. /// ///
/// @@ -9523,7 +11521,7 @@ pub struct SessionInstalledPluginSourceGitHub { pub source: SessionInstalledPluginSourceGitHubSource, } -/// Schema for the `SessionInstalledPluginSourceLocal` type. +/// Source descriptor for a direct local plugin install, with a local filesystem path. /// ///
/// @@ -9539,7 +11537,7 @@ pub struct SessionInstalledPluginSourceLocal { pub source: SessionInstalledPluginSourceLocalSource, } -/// Schema for the `SessionInstalledPluginSourceUrl` type. +/// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. /// ///
/// @@ -9684,6 +11682,8 @@ pub struct SessionMetadataSnapshot { pub selected_model: Option, /// The unique identifier of the session pub session_id: SessionId, + /// Current session limits, or null when no limits are active + pub session_limits: Option, /// ISO 8601 timestamp of when the session started pub start_time: String, /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. @@ -9697,6 +11697,21 @@ pub struct SessionMetadataSnapshot { pub workspace_path: Option, } +/// Cost-category metadata for a CAPI model. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionModelPriceCategory { + pub id: String, + pub price_category: ModelPickerPriceCategory, +} + /// The list of models available to this session. /// ///
@@ -9710,12 +11725,15 @@ pub struct SessionMetadataSnapshot { pub struct SessionModelList { /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). pub list: Vec, + /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_price_categories: Option>, /// Per-quota snapshots returned alongside the model list, keyed by quota type. #[serde(skip_serializing_if = "Option::is_none")] pub quota_snapshots: Option>, } -/// Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type. +/// Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. /// ///
/// @@ -9730,7 +11748,7 @@ pub struct SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource { pub r#type: String, } -/// Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRule` type. +/// Single content-exclusion rule supplied to `sessions.open` options, with paths, match conditions, and source. /// ///
/// @@ -9746,11 +11764,11 @@ pub struct SessionOpenOptionsAdditionalContentExclusionPolicyRule { #[serde(skip_serializing_if = "Option::is_none")] pub if_none_match: Option>, pub paths: Vec, - /// Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type. + /// Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. pub source: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource, } -/// Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicy` type. +/// Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated data, and scope. /// ///
/// @@ -9793,6 +11811,9 @@ pub struct SessionOpenOptions { /// Runtime context discriminator for agent filtering. #[serde(skip_serializing_if = "Option::is_none")] pub agent_context: Option, + /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. + #[serde(skip_serializing_if = "Option::is_none")] + pub allow_all_mcp_server_instructions: Option, /// Whether ask_user is explicitly disabled. #[serde(skip_serializing_if = "Option::is_none")] pub ask_user_disabled: Option, @@ -9848,6 +11869,9 @@ pub struct SessionOpenOptions { ///
#[serde(skip_serializing_if = "Option::is_none")] pub enable_citations: Option, + /// Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_managed_settings: Option, /// Whether on-demand custom instruction discovery is enabled. #[serde(skip_serializing_if = "Option::is_none")] pub enable_on_demand_instruction_discovery: Option, @@ -9863,6 +11887,9 @@ pub struct SessionOpenOptions { /// Override directory for session event logs. #[serde(skip_serializing_if = "Option::is_none")] pub events_log_directory: Option, + /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. + #[serde(skip_serializing_if = "Option::is_none")] + pub excluded_builtin_agents: Option>, /// Denylist of tool names. #[serde(skip_serializing_if = "Option::is_none")] pub excluded_tools: Option>, @@ -9873,6 +11900,9 @@ pub struct SessionOpenOptions { /// Feature-flag values resolved by the host. #[serde(skip_serializing_if = "Option::is_none")] pub feature_flags: Option>, + /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. + #[serde(skip_serializing_if = "Option::is_none")] + pub included_builtin_agents: Option>, /// Installed plugins visible to the session. #[serde(skip_serializing_if = "Option::is_none")] pub installed_plugins: Option>, @@ -9953,6 +11983,9 @@ pub struct SessionOpenOptions { /// Optional stable session identifier to use for a new session. #[serde(skip_serializing_if = "Option::is_none")] pub session_id: Option, + /// Initial session limits. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_limits: Option, /// Shell init profile. #[serde(skip_serializing_if = "Option::is_none")] pub shell_init_profile: Option, @@ -9968,6 +12001,9 @@ pub struct SessionOpenOptions { /// Optional trajectory output file path. #[serde(skip_serializing_if = "Option::is_none")] pub trajectory_file: Option, + /// Initial output verbosity level for supported models. + #[serde(skip_serializing_if = "Option::is_none")] + pub verbosity: Option, /// Working directory to anchor the session. #[serde(skip_serializing_if = "Option::is_none")] pub working_directory: Option, @@ -10130,6 +12166,10 @@ pub struct SessionsOpenHandoff { pub kind: SessionsOpenHandoffKind, /// Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). pub metadata: RemoteSessionMetadataValue, + /// In-process confirmation callback `(request) => boolean | Promise` invoked when the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch between the current working directory and the remote session). Returning `true` proceeds with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal because a function reference cannot cross the JSON-RPC boundary, for the same reasons as `onProgress`. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) on_confirm: Option, /// In-process progress callback `(update) => void` invoked for each handoff step. Marked internal because a function reference cannot cross the JSON-RPC boundary. The host-side `handoffSession` is already declared as `AsyncGenerator`; the schema layer flattens it because it does not yet support streaming methods. The wire-clean replacement is to expose the AsyncGenerator directly (or use vscode-jsonrpc `$/progress` notifications) once the schema/transport layer supports it. #[doc(hidden)] #[serde(skip_serializing_if = "Option::is_none")] @@ -10142,7 +12182,7 @@ pub struct SessionsOpenHandoff { pub task_type: Option, } -/// Schema for the `SessionsOpenProgress` type. +/// `sessions.open` handoff progress update with step, status, and optional message. /// ///
/// @@ -10306,7 +12346,184 @@ pub struct SessionsEnrichMetadataRequest { pub sessions: Vec, } -/// New auth credentials to install on the session. Omit to leave credentials unchanged. +/// New auth credentials to install on the session. Omit to leave credentials unchanged. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSetCredentialsParams { + /// The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime installs the supplied value immediately for outbound model/API requests. When the credential carries a raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous install) so plan/quota/billing metadata regains fidelity; on resolution failure the verbatim credential remains installed. It does NOT otherwise validate the credential. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. + #[serde(skip_serializing_if = "Option::is_none")] + pub credentials: Option, +} + +/// Indicates whether the credential update succeeded. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSetCredentialsResult { + /// Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_user_resolved: Option, + /// Whether the operation succeeded + pub success: bool, +} + +/// Availability of built-in job tools surfaced to boundary consumers. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsBuiltInToolAvailabilitySnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub create_pull_request: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub report_progress: Option, +} + +/// Named Rust-owned settings predicate to evaluate for this session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsEvaluatePredicateRequest { + /// Predicate name. The runtime owns the raw feature-flag names and composition logic. + pub name: SessionSettingsPredicateName, + /// Tool name for tool-scoped predicates such as trivial-change handling. + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_name: Option, +} + +/// Result of evaluating a Rust-owned settings predicate. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsEvaluatePredicateResult { + pub enabled: bool, +} + +/// Redacted job settings for a session. The job nonce is excluded. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsJobSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub built_in_tool_availability: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub event_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub is_trigger_job: Option, +} + +/// Redacted model routing settings for a session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsModelSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub callback_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub default_reasoning_effort: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub instance_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, +} + +/// Online-evaluation settings safe to expose across the SDK boundary. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsOnlineEvaluationSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub disable_online_evaluation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_online_evaluation_output_file: Option, +} + +/// Redacted repository and GitHub host settings for a session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsRepoSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub commit: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub host_protocol: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub owner_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub owner_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub pr_commit_count: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub read_write: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub secret_scanning_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub server_url: Option, +} + +/// Redacted validation and memory-tool settings for a session. /// ///
/// @@ -10316,13 +12533,28 @@ pub struct SessionsEnrichMetadataRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSetCredentialsParams { - /// The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime stores the value verbatim and uses it for outbound model/API requests; it does NOT re-validate or re-fetch the associated Copilot user response. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. +pub struct SessionSettingsValidationSnapshot { #[serde(skip_serializing_if = "Option::is_none")] - pub credentials: Option, + pub advisory_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub codeql_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub code_review_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub code_review_model: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dependabot_timeout: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub memory_store_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub memory_vote_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub secret_scanning_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout: Option, } -/// Indicates whether the credential update succeeded. +/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. /// ///
/// @@ -10332,9 +12564,20 @@ pub struct SessionSetCredentialsParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSetCredentialsResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionSettingsSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub client_name: Option, + pub job: SessionSettingsJobSnapshot, + pub model: SessionSettingsModelSnapshot, + pub online_evaluation: SessionSettingsOnlineEvaluationSnapshot, + pub repo: SessionSettingsRepoSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_time_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_ms: Option, + pub validation: SessionSettingsValidationSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, } /// UUID prefix to resolve to a unique session ID. @@ -10620,25 +12863,6 @@ pub struct SessionsLoadDeferredRepoHooksRequest { pub session_id: SessionId, } -/// Cursor and optional long-poll wait for polling runtime-spawned sessions. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionsPollSpawnedSessionsRequest { - /// Opaque cursor returned by a previous poll. Omit on the first call to receive any spawn events buffered since the runtime started. - #[serde(skip_serializing_if = "Option::is_none")] - pub cursor: Option, - /// Milliseconds to wait for new spawn events when the cursor is at the tail. 0 (default) returns immediately even if no events are buffered. Capped at 60000ms. - #[serde(skip_serializing_if = "Option::is_none")] - pub wait_ms: Option, -} - /// Age threshold and optional flags controlling which old sessions are pruned (or simulated when dryRun is true). /// ///
@@ -10884,6 +13108,9 @@ pub struct SessionUpdateOptionsParams { /// Runtime context discriminator (e.g., `cli`, `actions`). #[serde(skip_serializing_if = "Option::is_none")] pub agent_context: Option, + /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. + #[serde(skip_serializing_if = "Option::is_none")] + pub allow_all_mcp_server_instructions: Option, /// Whether to disable the `ask_user` tool (encourages autonomous behavior). #[serde(skip_serializing_if = "Option::is_none")] pub ask_user_disabled: Option, @@ -10947,12 +13174,18 @@ pub struct SessionUpdateOptionsParams { /// Override directory for the session-events log. When unset, the runtime's default events log directory is used. #[serde(skip_serializing_if = "Option::is_none")] pub events_log_directory: Option, + /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. + #[serde(skip_serializing_if = "Option::is_none")] + pub excluded_builtin_agents: Option>, /// Denylist of tool names for this session. #[serde(skip_serializing_if = "Option::is_none")] pub excluded_tools: Option>, /// Map of feature-flag IDs to their boolean enabled state. #[serde(skip_serializing_if = "Option::is_none")] pub feature_flags: Option>, + /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. + #[serde(skip_serializing_if = "Option::is_none")] + pub included_builtin_agents: Option>, /// Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. #[serde(skip_serializing_if = "Option::is_none")] pub installed_plugins: Option>, @@ -11001,6 +13234,9 @@ pub struct SessionUpdateOptionsParams { /// Replaces the session's capability set with the given list. Use to enable or disable capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the field to leave the existing capability set unchanged. #[serde(skip_serializing_if = "Option::is_none")] pub session_capabilities: Option>, + /// Optional session limits. Pass null to clear the session limits. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_limits: Option, /// Shell init profile (`None` or `NonInteractive`). #[serde(skip_serializing_if = "Option::is_none")] pub shell_init_profile: Option, @@ -11025,6 +13261,9 @@ pub struct SessionUpdateOptionsParams { /// Optional path for trajectory output. #[serde(skip_serializing_if = "Option::is_none")] pub trajectory_file: Option, + /// Output verbosity level for supported models. + #[serde(skip_serializing_if = "Option::is_none")] + pub verbosity: Option, /// Absolute working-directory path for shell tools. #[serde(skip_serializing_if = "Option::is_none")] pub working_directory: Option, @@ -11041,6 +13280,9 @@ pub struct SessionUpdateOptionsParams { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionUpdateOptionsResult { + /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated + #[serde(skip_serializing_if = "Option::is_none")] + pub plugin_hook_count: Option, /// Whether the operation succeeded pub success: bool, } @@ -11165,7 +13407,7 @@ pub struct ShutdownRequest { pub r#type: Option, } -/// Schema for the `Skill` type. +/// Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. /// ///
/// @@ -11197,7 +13439,7 @@ pub struct Skill { pub user_invocable: bool, } -/// Schema for the `SkillDiscoveryPath` type. +/// Canonical directory where skills can be discovered or created, with scope, preference, and optional project path. /// ///
/// @@ -11250,6 +13492,13 @@ pub struct SkillList { } /// Skill names to mark as disabled in global configuration, replacing any previous list. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SkillsConfigSetDisabledSkillsRequest { @@ -11273,6 +13522,13 @@ pub struct SkillsDisableRequest { } /// Optional project paths and additional skill directories to include in discovery. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SkillsDiscoverRequest { @@ -11321,7 +13577,7 @@ pub struct SkillsGetDiscoveryPathsRequest { pub project_paths: Option>, } -/// Schema for the `SkillsInvokedSkill` type. +/// Skill invocation record with name, path, content, allowed tools, and turn number. /// ///
/// @@ -11377,7 +13633,7 @@ pub struct SkillsLoadDiagnostics { pub warnings: Vec, } -/// Schema for the `SlashCommandAgentPromptResult` type. +/// Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. /// ///
/// @@ -11395,6 +13651,9 @@ pub struct SlashCommandAgentPromptResult { /// Optional target session mode for the agent prompt #[serde(skip_serializing_if = "Option::is_none")] pub mode: Option, + /// Optional user-facing notice to show before the prompt is submitted + #[serde(skip_serializing_if = "Option::is_none")] + pub notice: Option, /// Prompt to submit to the agent pub prompt: String, /// True when the invocation mutated user runtime settings; consumers caching settings should refresh @@ -11402,7 +13661,7 @@ pub struct SlashCommandAgentPromptResult { pub runtime_settings_changed: Option, } -/// Schema for the `SlashCommandCompletedResult` type. +/// Slash-command invocation result indicating completion, with optional message and settings-change flag. /// ///
/// @@ -11423,7 +13682,7 @@ pub struct SlashCommandCompletedResult { pub runtime_settings_changed: Option, } -/// Schema for the `SlashCommandTextResult` type. +/// Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. /// ///
/// @@ -11449,7 +13708,7 @@ pub struct SlashCommandTextResult { pub text: String, } -/// Schema for the `SlashCommandSelectSubcommandOption` type. +/// Selectable slash-command subcommand option with name, description, and optional group label. /// ///
/// @@ -11469,7 +13728,7 @@ pub struct SlashCommandSelectSubcommandOption { pub name: String, } -/// Schema for the `SlashCommandSelectSubcommandResult` type. +/// Slash-command invocation result asking the client to present subcommand options for a parent command. /// ///
/// @@ -11532,9 +13791,15 @@ pub struct SubagentSettings { /// Names of subagents the user has turned off; they cannot be dispatched #[serde(skip_serializing_if = "Option::is_none")] pub disabled_subagents: Option>, + /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only + #[serde(skip_serializing_if = "Option::is_none")] + pub max_concurrency: Option, + /// Maximum subagent nesting depth; applies to usage-based billing users only + #[serde(skip_serializing_if = "Option::is_none")] + pub max_depth: Option, } -/// Schema for the `TaskAgentInfo` type. +/// Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. /// ///
/// @@ -11596,7 +13861,7 @@ pub struct TaskAgentInfo { pub r#type: TaskAgentInfoType, } -/// Schema for the `TaskProgressLine` type. +/// Timestamped display line for task progress output or recent agent activity. /// ///
/// @@ -11613,7 +13878,7 @@ pub struct TaskProgressLine { pub timestamp: String, } -/// Schema for the `TaskAgentProgress` type. +/// Progress snapshot for an agent task, with recent activity lines and optional latest intent. /// ///
/// @@ -11724,7 +13989,7 @@ pub struct TasksGetProgressResult { pub progress: Option, } -/// Schema for the `TaskShellInfo` type. +/// Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. /// ///
/// @@ -11766,7 +14031,7 @@ pub struct TaskShellInfo { pub r#type: TaskShellInfoType, } -/// Schema for the `TaskShellProgress` type. +/// Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. /// ///
/// @@ -11979,7 +14244,14 @@ pub struct TelemetrySetFeatureOverridesRequest { pub features: HashMap, } -/// Schema for the `TokenAuthInfo` type. +/// Authentication-info variant for SDK-configured token authentication, carrying host and the secret token value. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenAuthInfo { @@ -11994,7 +14266,14 @@ pub struct TokenAuthInfo { pub r#type: TokenAuthInfoType, } -/// Schema for the `Tool` type. +/// Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Tool { @@ -12014,6 +14293,13 @@ pub struct Tool { } /// Built-in tools available for the requested model, with their parameters and instructions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolList { @@ -12049,6 +14335,13 @@ pub struct ToolsGetCurrentMetadataResult { pub struct ToolsInitializeAndValidateResult {} /// Optional model identifier whose tool overrides should be applied to the listing. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolsListRequest { @@ -12069,7 +14362,7 @@ pub struct ToolsListRequest { #[serde(rename_all = "camelCase")] pub struct ToolsUpdateSubagentSettingsResult {} -/// Schema for the `UIElicitationArrayAnyOfFieldItemsAnyOf` type. +/// Selectable option for a UI elicitation multi-select array item, with submitted value and display label. /// ///
/// @@ -12368,7 +14661,7 @@ pub struct UIElicitationStringEnumField { pub r#type: UIElicitationStringEnumFieldType, } -/// Schema for the `UIElicitationStringOneOfFieldOneOf` type. +/// Selectable option for a UI elicitation single-select string field, with submitted value and display label. /// ///
/// @@ -12449,7 +14742,7 @@ pub struct UIEphemeralQueryResult { pub answer: String, } -/// Schema for the `UIExitPlanModeResponse` type. +/// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. /// ///
/// @@ -12520,7 +14813,7 @@ pub struct UIHandlePendingElicitationRequest { pub struct UIHandlePendingExitPlanModeRequest { /// The unique request ID from the exit_plan_mode.requested event pub request_id: RequestId, - /// Schema for the `UIExitPlanModeResponse` type. + /// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. pub response: UIExitPlanModeResponse, } @@ -12569,7 +14862,45 @@ pub struct UIHandlePendingSamplingRequest { pub response: Option, } -/// Schema for the `UIUserInputResponse` type. +/// The user's selected action for an exhausted session limit. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UISessionLimitsExhaustedResponse { + /// Action selected by the user. + pub action: UISessionLimitsExhaustedResponseAction, + /// AI Credits to add to the current max when action is 'add'. + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_ai_credits: Option, + /// New absolute max AI Credits when action is 'set'. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_ai_credits: Option, +} + +/// Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UIHandlePendingSessionLimitsExhaustedRequest { + /// The unique request ID from the session_limits_exhausted.requested event + pub request_id: RequestId, + /// The selected session-limit action. + pub response: UISessionLimitsExhaustedResponse, +} + +/// User response for a pending user-input request, with answer text and whether it was typed freeform. /// ///
/// @@ -12599,7 +14930,7 @@ pub struct UIUserInputResponse { pub struct UIHandlePendingUserInputRequest { /// The unique request ID from the user_input.requested event pub request_id: RequestId, - /// Schema for the `UIUserInputResponse` type. + /// User response for a pending user-input request, with answer text and whether it was typed freeform. pub response: UIUserInputResponse, } @@ -12658,6 +14989,12 @@ pub struct UpdateSubagentSettingsRequestSubagents { /// Names of subagents the user has turned off; they cannot be dispatched #[serde(skip_serializing_if = "Option::is_none")] pub disabled_subagents: Option>, + /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only + #[serde(skip_serializing_if = "Option::is_none")] + pub max_concurrency: Option, + /// Maximum subagent nesting depth; applies to usage-based billing users only + #[serde(skip_serializing_if = "Option::is_none")] + pub max_depth: Option, } /// Subagent settings to apply to the current session @@ -12713,7 +15050,7 @@ pub struct UsageMetricsModelMetricRequests { pub count: i64, } -/// Schema for the `UsageMetricsModelMetricTokenDetail` type. +/// Per-model token-detail entry containing the accumulated token count for one token type. /// ///
/// @@ -12752,7 +15089,7 @@ pub struct UsageMetricsModelMetricUsage { pub reasoning_tokens: Option, } -/// Schema for the `UsageMetricsModelMetric` type. +/// Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. /// ///
/// @@ -12775,7 +15112,7 @@ pub struct UsageMetricsModelMetric { pub usage: UsageMetricsModelMetricUsage, } -/// Schema for the `UsageMetricsTokenDetail` type. +/// Session-wide token-detail entry containing the accumulated token count for one token type. /// ///
/// @@ -12828,7 +15165,14 @@ pub struct UsageGetMetricsResult { pub total_user_requests: i64, } -/// Schema for the `UserAuthInfo` type. +/// Authentication-info variant for OAuth user auth, with host and login; the token remains in the runtime secret store. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserAuthInfo { @@ -12868,6 +15212,127 @@ pub struct UserRequestedShellCommandResult { pub tool_call_id: String, } +/// A single user setting's effective value alongside its default, so consumers can render settings left at their default. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UserSettingMetadata { + /// The centrally-known default for this setting (null when no default is registered). + pub default: serde_json::Value, + /// True when the user has not set an explicit value for this setting (i.e. it is left at its default). Reflects whether the user has overridden the key, not whether the effective value happens to equal the default — a key explicitly set to a value identical to the default still reports false. + pub is_default: bool, + /// The effective value: the user's value if set, otherwise the default. + pub value: serde_json::Value, +} + +/// Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UserSettingsGetResult { + /// Every known user setting keyed by setting name, each with its effective value, default, and whether it is at the default. + pub settings: HashMap, +} + +/// Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UserSettingsSetRequest { + /// Partial user settings to write, as a free-form object keyed by setting name + pub settings: serde_json::Value, +} + +/// Outcome of writing user settings. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UserSettingsSetResult { + /// Top-level keys whose write landed in settings.json but is shadowed by a value still present in the legacy config.json (config.json wins on read). The write does not take effect until the legacy value is removed. + pub shadowed_keys: Vec, +} + +/// Current sharing status and shareable GitHub URL for a session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VisibilityGetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub share_url: Option, + /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. + pub synced: bool, +} + +/// Desired sharing status for the session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VisibilitySetRequest { + /// Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. + pub status: SessionVisibilityStatus, +} + +/// Effective sharing status and shareable GitHub URL after updating session visibility. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VisibilitySetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub share_url: Option, + /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. + pub synced: bool, +} + /// A single changed file and its unified diff. /// ///
@@ -12917,7 +15382,7 @@ pub struct WorkspaceDiffResult { pub requested_mode: WorkspaceDiffMode, } -/// Schema for the `WorkspacesCheckpoints` type. +/// Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. /// ///
/// @@ -13205,6 +15670,13 @@ pub struct WorkspaceSummary { } /// List of Copilot models available to the resolved user, including capabilities and billing metadata. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelsListResult { @@ -13213,6 +15685,13 @@ pub struct ModelsListResult { } /// Built-in tools available for the requested model, with their parameters and instructions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolsListResult { @@ -13221,6 +15700,13 @@ pub struct ToolsListResult { } /// User-configured MCP servers, keyed by server name. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpConfigListResult { @@ -13381,6 +15867,13 @@ pub struct PluginsMarketplacesRefreshResult { } /// Skills discovered across global and project sources. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SkillsDiscoverResult { @@ -13463,6 +15956,21 @@ pub struct InstructionsGetDiscoveryPathsResult { pub paths: Vec, } +/// Slash commands available in the session, after applying any include/exclude filters. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CommandsListResult { + /// Commands available in this session + pub commands: Vec, +} + /// Result of opening a session. /// ///
@@ -13709,23 +16217,6 @@ pub struct SessionsGetRemoteControlStatusResult { pub status: serde_json::Value, } -/// Batch of spawn events plus a cursor for follow-up polls. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionsPollSpawnedSessionsResult { - /// Opaque cursor to pass back to receive only events after this batch. - pub cursor: String, - /// Spawn events emitted since the supplied cursor. - pub events: Vec, -} - /// Handle for releasing the extension tool registration. /// ///
@@ -13772,6 +16263,21 @@ pub struct SessionSendResult { pub message_id: String, } +/// Result of sending zero or more user messages +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSendMessagesResult { + /// Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. + pub message_ids: Vec, +} + /// Result of aborting the current turn /// ///
@@ -13800,7 +16306,7 @@ pub struct SessionAbortResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAuthGetStatusParams { +pub struct SessionGitHubAuthGetStatusParams { /// Target session identifier pub session_id: SessionId, } @@ -13815,7 +16321,7 @@ pub struct SessionAuthGetStatusParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAuthGetStatusResult { +pub struct SessionGitHubAuthGetStatusResult { /// Authentication type #[serde(skip_serializing_if = "Option::is_none")] pub auth_type: Option, @@ -13845,11 +16351,36 @@ pub struct SessionAuthGetStatusResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAuthSetCredentialsResult { +pub struct SessionGitHubAuthSetCredentialsResult { + /// Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_user_resolved: Option, /// Whether the operation succeeded pub success: bool, } +/// Result of collecting a redacted debug bundle. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionDebugCollectLogsResult { + /// Files included in the redacted bundle. + pub entries: Vec, + /// Destination kind that was written. + pub kind: DebugCollectLogsResultKind, + /// Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. + pub path: String, + /// Optional files or directories that could not be included. + #[serde(skip_serializing_if = "Option::is_none")] + pub skipped_entries: Option>, +} + /// Identifies the target session. /// ///
@@ -13928,6 +16459,9 @@ pub struct SessionCanvasOpenResult { /// Owning extension display name, when available #[serde(skip_serializing_if = "Option::is_none")] pub extension_name: Option, + /// Host-local PNG path for the canvas icon, when supplied + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, /// Input supplied when the instance was opened #[serde(skip_serializing_if = "Option::is_none")] pub input: Option, @@ -14041,6 +16575,9 @@ pub struct SessionModelSetReasoningEffortResult { pub struct SessionModelListResult { /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). pub list: Vec, + /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_price_categories: Option>, /// Per-quota snapshots returned alongside the model list, keyed by quota type. #[serde(skip_serializing_if = "Option::is_none")] pub quota_snapshots: Option>, @@ -14432,6 +16969,51 @@ pub struct SessionWorkspacesDiffResult { pub requested_mode: WorkspaceDiffMode, } +/// Identifies the target session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionCompletionsGetTriggerCharactersParams { + /// Target session identifier + pub session_id: SessionId, +} + +/// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionCompletionsGetTriggerCharactersResult { + /// Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. + pub trigger_characters: Vec, +} + +/// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionCompletionsRequestResult { + /// Completion items in host-ranked order. + pub items: Vec, +} + /// Identifies the target session. /// ///
@@ -15135,7 +17717,7 @@ pub struct SessionMcpIsServerRunningResult { pub running: bool, } -/// Empty result after recording the MCP OAuth response. +/// Indicates whether the pending MCP OAuth response was accepted. /// ///
/// @@ -15145,9 +17727,12 @@ pub struct SessionMcpIsServerRunningResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpOauthRespondResult {} +pub struct SessionMcpOauthHandlePendingRequestResult { + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + pub success: bool, +} -/// Indicates whether the pending MCP OAuth response was accepted. +/// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. /// ///
/// @@ -15157,12 +17742,13 @@ pub struct SessionMcpOauthRespondResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpOauthHandlePendingRequestResult { - /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. - pub success: bool, +pub struct SessionMcpOauthLoginResult { + /// URL the caller should open in a browser to complete OAuth. Omitted when cached tokens were still valid and no browser interaction was needed — the server is already reconnected in that case. When present, the runtime starts the callback listener before returning and continues the flow in the background; completion is signaled via session.mcp_server_status_changed. + #[serde(skip_serializing_if = "Option::is_none")] + pub authorization_url: Option, } -/// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. +/// Indicates whether the pending MCP headers refresh response was accepted. /// ///
/// @@ -15172,10 +17758,9 @@ pub struct SessionMcpOauthHandlePendingRequestResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpOauthLoginResult { - /// URL the caller should open in a browser to complete OAuth. Omitted when cached tokens were still valid and no browser interaction was needed — the server is already reconnected in that case. When present, the runtime starts the callback listener before returning and continues the flow in the background; completion is signaled via session.mcp_server_status_changed. - #[serde(skip_serializing_if = "Option::is_none")] - pub authorization_url: Option, +pub struct SessionMcpHeadersHandlePendingHeadersRefreshRequestResult { + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + pub success: bool, } /// Resource contents returned by the MCP server. @@ -15255,6 +17840,57 @@ pub struct SessionMcpAppsDiagnoseResult { pub server: McpAppsDiagnoseServer, } +/// Resource contents returned by the MCP server. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMcpResourcesReadResult { + /// Resource contents returned by the server + pub contents: Vec, +} + +/// One page of resources advertised by the named MCP server. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMcpResourcesListResult { + /// Opaque cursor for the next page, if the server has more resources + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Resources advertised by the server (proxied MCP `resources/list`) + pub resources: Vec, +} + +/// One page of resource templates advertised by the named MCP server. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMcpResourcesListTemplatesResult { + /// Opaque cursor for the next page, if the server has more resource templates + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Resource templates advertised by the server (proxied MCP `resources/templates/list`) + pub resource_templates: Vec, +} + /// Identifies the target session. /// ///
@@ -15342,6 +17978,9 @@ pub struct SessionProviderAddResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionOptionsUpdateResult { + /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated + #[serde(skip_serializing_if = "Option::is_none")] + pub plugin_hook_count: Option, /// Whether the operation succeeded pub success: bool, } @@ -15675,6 +18314,21 @@ pub struct SessionUiHandlePendingAutoModeSwitchResult { pub success: bool, } +/// Indicates whether the pending UI request was resolved by this call. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionUiHandlePendingSessionLimitsExhaustedResult { + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + pub success: bool, +} + /// Indicates whether the pending UI request was resolved by this call. /// ///
@@ -15806,13 +18460,16 @@ pub struct SessionPermissionsSetApproveAllResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionPermissionsSetAllowAllResult { - /// Authoritative allow-all state after the mutation + /// Authoritative full allow-all state after the mutation pub enabled: bool, + /// Authoritative allow-all mode after the mutation + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, /// Whether the operation succeeded pub success: bool, } -/// Current full allow-all permission state. +/// Current allow-all permission mode. /// ///
/// @@ -15825,6 +18482,9 @@ pub struct SessionPermissionsSetAllowAllResult { pub struct SessionPermissionsGetAllowAllResult { /// Whether full allow-all permissions are currently active pub enabled: bool, + /// Current allow-all mode + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, } /// Indicates whether the operation succeeded. @@ -16164,6 +18824,8 @@ pub struct SessionMetadataSnapshotResult { pub selected_model: Option, /// The unique identifier of the session pub session_id: SessionId, + /// Current session limits, or null when no limits are active + pub session_limits: Option, /// ISO 8601 timestamp of when the session started pub start_time: String, /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. @@ -16280,6 +18942,92 @@ pub struct SessionMetadataContextInfoResult { pub context_info: Option, } +/// Identifies the target session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataGetContextAttributionParams { + /// Target session identifier + pub session_id: SessionId, +} + +/// Successful compaction history for the session. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataGetContextAttributionResultContextAttributionCompactions { + /// Number of successful compactions in this session. + pub count: i64, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataGetContextAttributionResultContextAttributionEntriesItem { + /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option>, + /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + pub id: String, + /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + pub kind: String, + /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + pub label: String, + /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + /// Token count currently in context attributable to this entry. + pub tokens: i64, +} + +/// Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataGetContextAttributionResultContextAttribution { + /// Successful compaction history for the session. + pub compactions: SessionMetadataGetContextAttributionResultContextAttributionCompactions, + /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + pub entries: Vec, + /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + pub total_tokens: i64, +} + +/// Per-source attribution breakdown for the session's current context window, or null if uninitialized. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataGetContextAttributionResult { + /// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + pub context_attribution: Option, +} + +/// The heaviest individual messages in the session's context window, most-expensive first. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataGetContextHeaviestMessagesResult { + /// Heaviest messages, most-expensive first. + pub messages: Vec, + /// Total token count of the current context window, so callers can compute each message's share without a second call. + pub total_tokens: i64, +} + /// Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). /// ///
@@ -16292,7 +19040,7 @@ pub struct SessionMetadataContextInfoResult { #[serde(rename_all = "camelCase")] pub struct SessionMetadataRecordContextChangeResult {} -/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. +/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. /// ///
/// @@ -16326,6 +19074,47 @@ pub struct SessionMetadataRecomputeContextTokensResult { pub total_tokens: i64, } +/// Identifies the target session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsSnapshotParams { + /// Target session identifier + pub session_id: SessionId, +} + +/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSettingsSnapshotResult { + #[serde(skip_serializing_if = "Option::is_none")] + pub client_name: Option, + pub job: SessionSettingsJobSnapshot, + pub model: SessionSettingsModelSnapshot, + pub online_evaluation: SessionSettingsOnlineEvaluationSnapshot, + pub repo: SessionSettingsRepoSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_time_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_ms: Option, + pub validation: SessionSettingsValidationSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + /// Identifier of the spawned process, used to correlate streamed output and exit notifications. /// ///
@@ -16747,13 +19536,40 @@ pub struct SessionUsageGetMetricsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionRemoteEnableResult { - /// Whether remote steering is enabled - pub remote_steerable: bool, - /// GitHub frontend URL for this session - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} +pub struct SessionRemoteEnableResult { + /// Whether remote steering is enabled + pub remote_steerable: bool, + /// GitHub frontend URL for this session + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +/// Identifies the target session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionRemoteDisableParams { + /// Target session identifier + pub session_id: SessionId, +} + +/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionRemoteNotifySteerableChangedResult {} /// Identifies the target session. /// @@ -16765,12 +19581,12 @@ pub struct SessionRemoteEnableResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionRemoteDisableParams { +pub struct SessionVisibilityGetParams { /// Target session identifier pub session_id: SessionId, } -/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. +/// Current sharing status and shareable GitHub URL for a session. /// ///
/// @@ -16780,7 +19596,37 @@ pub struct SessionRemoteDisableParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionRemoteNotifySteerableChangedResult {} +pub struct SessionVisibilityGetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub share_url: Option, + /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. + pub synced: bool, +} + +/// Effective sharing status and shareable GitHub URL after updating session visibility. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionVisibilitySetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub share_url: Option, + /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. + pub synced: bool, +} /// Identifies the target session. /// @@ -16911,6 +19757,13 @@ pub type McpExecuteSamplingResult = HashMap; pub type UIElicitationResponseContent = HashMap; /// List of all authenticated users +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
pub type AccountGetAllUsersResult = Vec; /// Standard MCP CallToolResult @@ -16923,6 +19776,31 @@ pub type AccountGetAllUsersResult = Vec; ///
pub type SessionMcpAppsCallToolResult = HashMap; +/// Resolved Anthropic adaptive-thinking capability for a model. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AdaptiveThinkingSupport { + /// The model does not accept thinking.type='adaptive' + #[serde(rename = "unsupported")] + Unsupported, + /// The model accepts adaptive thinking but also accepts thinking.type='enabled' + #[serde(rename = "optional")] + Optional, + /// The model only accepts adaptive thinking and rejects thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8) + #[serde(rename = "required")] + Required, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Which tier this directory belongs to /// ///
@@ -17243,6 +20121,31 @@ pub enum AgentRegistrySpawnResult { ValidationError(AgentRegistrySpawnValidationError), } +/// Current or requested allow-all mode. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PermissionsAllowAllMode { + /// Permission requests follow the normal approval flow. + #[serde(rename = "off")] + Off, + /// Tool, path, and URL permission requests are automatically approved. + #[serde(rename = "on")] + On, + /// Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + #[serde(rename = "auto")] + Auto, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ApiKeyAuthInfoType { @@ -17305,6 +20208,38 @@ pub enum AttachmentFileType { File, } +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubActionsJobType { + #[serde(rename = "github_actions_job")] + #[default] + GitHubActionsJob, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubCommitType { + #[serde(rename = "github_commit")] + #[default] + GitHubCommit, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubFileType { + #[serde(rename = "github_file")] + #[default] + GitHubFile, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubFileDiffType { + #[serde(rename = "github_file_diff")] + #[default] + GitHubFileDiff, +} + /// Type of GitHub reference /// ///
@@ -17330,6 +20265,46 @@ pub enum AttachmentGitHubReferenceType { Unknown, } +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubReleaseType { + #[serde(rename = "github_release")] + #[default] + GitHubRelease, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubRepositoryType { + #[serde(rename = "github_repository")] + #[default] + GitHubRepository, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubSnippetType { + #[serde(rename = "github_snippet")] + #[default] + GitHubSnippet, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubTreeComparisonType { + #[serde(rename = "github_tree_comparison")] + #[default] + GitHubTreeComparison, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AttachmentGitHubUrlType { + #[serde(rename = "github_url")] + #[default] + GitHubUrl, +} + /// Attachment type discriminator #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AttachmentSelectionType { @@ -17375,7 +20350,171 @@ pub enum AuthInfoType { Unknown, } -/// Optional completion hint for the input (e.g. 'directory' for filesystem path completion) +/// Optional completion hint for the input (e.g. 'directory' for filesystem path completion) +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SlashCommandInputCompletion { + /// Input should complete filesystem directories. + #[serde(rename = "directory")] + Directory, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SlashCommandKind { + /// Command implemented by the runtime. + #[serde(rename = "builtin")] + Builtin, + /// Command backed by a skill. + #[serde(rename = "skill")] + Skill, + /// Command registered by an SDK client or extension. + #[serde(rename = "client")] + Client, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Neutral SDK discriminator for the connected remote session kind. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ConnectedRemoteSessionMetadataKind { + /// Remote CLI session. + #[serde(rename = "remote-session")] + RemoteSession, + /// GitHub Copilot coding agent session. + #[serde(rename = "coding-agent")] + CodingAgent, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Controls how MCP tool result content is filtered: none leaves content unchanged, markdown sanitizes HTML while preserving Markdown-friendly output, and hidden_characters removes characters that can hide directives. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ContentFilterMode { + /// Leave MCP tool result content unchanged. + #[serde(rename = "none")] + None, + /// Sanitize HTML while preserving Markdown-friendly output. + #[serde(rename = "markdown")] + Markdown, + /// Remove characters that can hide directives. + #[serde(rename = "hidden_characters")] + HiddenCharacters, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Authentication host (always the public GitHub host). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CopilotApiTokenAuthInfoHost { + #[serde(rename = "https://github.com")] + #[default] + HttpsGitHubCom, +} + +/// Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` environment-variable pair. The token itself is read from the environment by the runtime, not carried in this struct. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CopilotApiTokenAuthInfoType { + #[serde(rename = "copilot-api-token")] + #[default] + CopilotApiToken, +} + +/// Source category for a collected debug bundle entry. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum DebugCollectLogsSource { + /// Session event log. + #[serde(rename = "events")] + Events, + /// Process log for the session. + #[serde(rename = "process-log")] + ProcessLog, + /// Interactive shell log for the session. + #[serde(rename = "shell-log")] + ShellLog, + /// Caller-provided diagnostic entry. + #[serde(rename = "additional")] + Additional, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum DebugCollectLogsDestinationArchiveKind { + #[serde(rename = "archive")] + #[default] + Archive, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum DebugCollectLogsDestinationDirectoryKind { + #[serde(rename = "directory")] + #[default] + Directory, +} + +/// Destination for the redacted debug bundle. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DebugCollectLogsDestination { + Archive(DebugCollectLogsDestinationArchive), + Directory(DebugCollectLogsDestinationDirectory), +} + +/// Kind of caller-provided debug log entry. /// ///
/// @@ -17384,8 +20523,11 @@ pub enum AuthInfoType { /// ///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum SlashCommandInputCompletion { - /// Input should complete filesystem directories. +pub enum DebugCollectLogsEntryKind { + /// Include a single server-local file. + #[serde(rename = "file")] + File, + /// Include files from a server-local directory recursively. #[serde(rename = "directory")] Directory, /// Unknown variant for forward compatibility. @@ -17394,7 +20536,7 @@ pub enum SlashCommandInputCompletion { Unknown, } -/// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command +/// How a collected debug entry should be redacted before being staged. /// ///
/// @@ -17403,23 +20545,20 @@ pub enum SlashCommandInputCompletion { /// ///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum SlashCommandKind { - /// Command implemented by the runtime. - #[serde(rename = "builtin")] - Builtin, - /// Command backed by a skill. - #[serde(rename = "skill")] - Skill, - /// Command registered by an SDK client or extension. - #[serde(rename = "client")] - Client, +pub enum DebugCollectLogsRedaction { + /// Redact the file as plain UTF-8 log text. + #[serde(rename = "plain-text")] + PlainText, + /// Redact each non-empty line as a session event JSON object, falling back to plain-text redaction for malformed lines. + #[serde(rename = "events-jsonl")] + EventsJsonl, /// Unknown variant for forward compatibility. #[default] #[serde(other)] Unknown, } -/// Neutral SDK discriminator for the connected remote session kind. +/// Destination kind that was written. /// ///
/// @@ -17428,54 +20567,27 @@ pub enum SlashCommandKind { /// ///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum ConnectedRemoteSessionMetadataKind { - /// Remote CLI session. - #[serde(rename = "remote-session")] - RemoteSession, - /// GitHub Copilot coding agent session. - #[serde(rename = "coding-agent")] - CodingAgent, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - -/// Controls how MCP tool result content is filtered: none leaves content unchanged, markdown sanitizes HTML while preserving Markdown-friendly output, and hidden_characters removes characters that can hide directives. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum ContentFilterMode { - /// Leave MCP tool result content unchanged. - #[serde(rename = "none")] - None, - /// Sanitize HTML while preserving Markdown-friendly output. - #[serde(rename = "markdown")] - Markdown, - /// Remove characters that can hide directives. - #[serde(rename = "hidden_characters")] - HiddenCharacters, +pub enum DebugCollectLogsResultKind { + /// A .tgz archive was written. + #[serde(rename = "archive")] + Archive, + /// A directory containing redacted files was written. + #[serde(rename = "directory")] + Directory, /// Unknown variant for forward compatibility. #[default] #[serde(other)] Unknown, } -/// Authentication host (always the public GitHub host). -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum CopilotApiTokenAuthInfoHost { - #[serde(rename = "https://github.com")] - #[default] - HttpsGitHubCom, -} - -/// Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` environment-variable pair. The token itself is read from the environment by the runtime, not carried in this struct. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum CopilotApiTokenAuthInfoType { - #[serde(rename = "copilot-api-token")] - #[default] - CopilotApiToken, -} - /// Server transport type: stdio, http, sse (deprecated), or memory +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum DiscoveredMcpServerType { /// Server communicates over stdio with a local child process. @@ -17688,6 +20800,14 @@ pub enum ExternalToolTextResultForLlmContentResourceLinkType { ResourceLink, } +/// Content block type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ExternalToolTextResultForLlmContentShellExitType { + #[serde(rename = "shell_exit")] + #[default] + ShellExit, +} + /// Content block type discriminator #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ExternalToolTextResultForLlmContentTerminalType { @@ -17728,6 +20848,63 @@ pub enum HMACAuthInfoType { Hmac, } +/// Hook event name dispatched through the SDK callback transport. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum HookType { + /// Runs before a tool is invoked. + #[serde(rename = "preToolUse")] + PreToolUse, + /// Runs before an MCP tool is invoked. + #[serde(rename = "preMcpToolCall")] + PreMcpToolCall, + /// Runs after a tool completes successfully. + #[serde(rename = "postToolUse")] + PostToolUse, + /// Runs after a tool fails. + #[serde(rename = "postToolUseFailure")] + PostToolUseFailure, + /// Runs after the user submits a prompt. + #[serde(rename = "userPromptSubmitted")] + UserPromptSubmitted, + /// Runs when a session starts. + #[serde(rename = "sessionStart")] + SessionStart, + /// Runs when a session ends. + #[serde(rename = "sessionEnd")] + SessionEnd, + /// Runs after an agent result is produced. + #[serde(rename = "postResult")] + PostResult, + /// Runs before a pull request description is generated. + #[serde(rename = "prePRDescription")] + PrePRDescription, + /// Runs when the agent encounters an error. + #[serde(rename = "errorOccurred")] + ErrorOccurred, + /// Runs when the agent stops. + #[serde(rename = "agentStop")] + AgentStop, + /// Runs when a subagent starts. + #[serde(rename = "subagentStart")] + SubagentStart, + /// Runs when a subagent stops. + #[serde(rename = "subagentStop")] + SubagentStop, + /// Runs before conversation context is compacted. + #[serde(rename = "preCompact")] + PreCompact, + /// Runs when the agent requests permission. + #[serde(rename = "permissionRequest")] + PermissionRequest, + /// Runs when the agent emits a notification. + #[serde(rename = "notification")] + Notification, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Constant value. Always "github". #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum InstalledPluginSourceGitHubSource { @@ -18123,6 +21300,57 @@ pub enum McpAppsSetHostContextDetailsTheme { Unknown, } +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum McpHeadersHandlePendingHeadersRefreshRequestHeadersKind { + #[serde(rename = "headers")] + #[default] + Headers, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum McpHeadersHandlePendingHeadersRefreshRequestNoneKind { + #[serde(rename = "none")] + #[default] + None, +} + +/// Host response: supply dynamic headers or decline this refresh. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum McpHeadersHandlePendingHeadersRefreshRequest { + Headers(McpHeadersHandlePendingHeadersRefreshRequestHeaders), + None(McpHeadersHandlePendingHeadersRefreshRequestNone), +} + +/// Consumer allowed to call an MCP tool. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum McpToolUiVisibility { + /// The model may call the tool. + #[serde(rename = "model")] + Model, + /// An MCP App view may call the tool. + #[serde(rename = "app")] + App, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum McpOauthPendingRequestResponseTokenKind { #[serde(rename = "token")] @@ -18200,6 +21428,13 @@ pub enum McpSamplingExecutionAction { } /// Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum McpServerConfigDeferTools { /// Tools may be deferred under certain conditions @@ -18215,6 +21450,13 @@ pub enum McpServerConfigDeferTools { } /// OAuth grant type to use when authenticating to the remote MCP server. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum McpServerConfigHttpOauthGrantType { /// Interactive browser-based authorization code flow with PKCE. @@ -18230,6 +21472,13 @@ pub enum McpServerConfigHttpOauthGrantType { } /// Remote transport type. Defaults to "http" when omitted. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum McpServerConfigHttpType { /// Streamable HTTP transport. @@ -18336,6 +21585,13 @@ pub enum MetadataSnapshotRemoteMetadataTaskType { } /// Model capability category for grouping in the model picker +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ModelPickerCategory { /// Lightweight model category optimized for faster, lower-cost interactions. @@ -18354,6 +21610,13 @@ pub enum ModelPickerCategory { } /// Relative cost tier for token-based billing users +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ModelPickerPriceCategory { /// Lowest relative token cost tier. @@ -18375,6 +21638,13 @@ pub enum ModelPickerPriceCategory { } /// Current policy state for this model +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ModelPolicyState { /// The model is enabled by policy. @@ -19223,6 +22493,38 @@ pub enum PushAttachmentFileType { File, } +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubActionsJobType { + #[serde(rename = "github_actions_job")] + #[default] + GitHubActionsJob, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubCommitType { + #[serde(rename = "github_commit")] + #[default] + GitHubCommit, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubFileType { + #[serde(rename = "github_file")] + #[default] + GitHubFile, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubFileDiffType { + #[serde(rename = "github_file_diff")] + #[default] + GitHubFileDiff, +} + /// Type of GitHub reference /// ///
@@ -19248,6 +22550,46 @@ pub enum PushAttachmentGitHubReferenceType { Unknown, } +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubReleaseType { + #[serde(rename = "github_release")] + #[default] + GitHubRelease, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubRepositoryType { + #[serde(rename = "github_repository")] + #[default] + GitHubRepository, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubSnippetType { + #[serde(rename = "github_snippet")] + #[default] + GitHubSnippet, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubTreeComparisonType { + #[serde(rename = "github_tree_comparison")] + #[default] + GitHubTreeComparison, +} + +/// Attachment type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PushAttachmentGitHubUrlType { + #[serde(rename = "github_url")] + #[default] + GitHubUrl, +} + /// Attachment type discriminator #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum PushAttachmentSelectionType { @@ -19499,6 +22841,13 @@ pub enum SessionFsReaddirWithTypesEntryType { } /// Path conventions used by this filesystem +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum SessionFsSetProviderConventions { /// Paths use Windows path conventions. @@ -19838,6 +23187,79 @@ pub enum SessionsOpenStatus { Unknown, } +/// Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names are intentionally not part of the contract. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionSettingsPredicateName { + /// Whether the security-tools feature flag enables security tool wiring. + #[serde(rename = "securityToolsEnabled")] + SecurityToolsEnabled, + /// Whether third-party security tools should receive the security prompt. + #[serde(rename = "thirdPartySecurityPromptEnabled")] + ThirdPartySecurityPromptEnabled, + /// Whether validation may run in parallel. + #[serde(rename = "parallelValidationEnabled")] + ParallelValidationEnabled, + /// Whether runtime timing telemetry is enabled. + #[serde(rename = "runtimeTimingTelemetryEnabled")] + RuntimeTimingTelemetryEnabled, + /// Whether the co-author hook is enabled. + #[serde(rename = "coAuthorHookEnabled")] + CoAuthorHookEnabled, + /// Whether Chronicle integration is enabled. + #[serde(rename = "chronicleEnabled")] + ChronicleEnabled, + /// Whether content-exclusion policy may self-fetch data. + #[serde(rename = "contentExclusionSelfFetchEnabled")] + ContentExclusionSelfFetchEnabled, + /// Whether Claude Opus token-limit caps should be applied. + #[serde(rename = "capClaudeOpusTokenLimitsEnabled")] + CapClaudeOpusTokenLimitsEnabled, + /// Whether code-review behavior is enabled. + #[serde(rename = "codeReviewFeatureEnabled")] + CodeReviewFeatureEnabled, + /// Whether CCA should use the TypeScript autofind behavior. + #[serde(rename = "ccaUseTsAutofindEnabled")] + CcaUseTsAutofindEnabled, + /// Whether the dependency checker is enabled. + #[serde(rename = "dependencyCheckerEnabled")] + DependencyCheckerEnabled, + /// Whether the Dependabot checker is enabled. + #[serde(rename = "dependabotCheckerEnabled")] + DependabotCheckerEnabled, + /// Whether the CodeQL checker is enabled. + #[serde(rename = "codeqlCheckerEnabled")] + CodeqlCheckerEnabled, + /// Whether trivial-change handling is enabled. + #[serde(rename = "trivialChangeEnabled")] + TrivialChangeEnabled, + /// Whether trivial-change skip behavior is enabled. + #[serde(rename = "trivialChangeSkipEnabled")] + TrivialChangeSkipEnabled, + /// Whether trivial-change handling is enabled for code review. + #[serde(rename = "trivialChangeEnabledForCodeReview")] + TrivialChangeEnabledForCodeReview, + /// Whether trivial-change skip behavior is enabled for code review. + #[serde(rename = "trivialChangeSkipEnabledForCodeReview")] + TrivialChangeSkipEnabledForCodeReview, + /// Whether trivial-change handling is enabled for a specific tool. + #[serde(rename = "trivialChangeEnabledForTool")] + TrivialChangeEnabledForTool, + /// Whether trivial-change skip behavior is enabled for a specific tool. + #[serde(rename = "trivialChangeSkipEnabledForTool")] + TrivialChangeSkipEnabledForTool, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Which session sources to include. Defaults to `local` for backward compatibility. /// ///
@@ -19863,6 +23285,28 @@ pub enum SessionSource { Unknown, } +/// Sharing status for a synced session. "repo" makes the session visible to anyone with read access to the repository; "unshared" restricts it to the creator and collaborators. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionVisibilityStatus { + /// The session is visible to repository readers. + #[serde(rename = "repo")] + Repo, + /// The session is restricted to its creator and collaborators. + #[serde(rename = "unshared")] + Unshared, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Signal to send (default: SIGTERM) /// ///
@@ -19945,7 +23389,7 @@ pub enum SlashCommandSelectSubcommandResultKind { SelectSubcommand, } -/// Result of invoking the slash command (text output, prompt to send to the agent, or completion). +/// Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). /// ///
/// @@ -20294,6 +23738,34 @@ pub enum UIExitPlanModeAction { Unknown, } +/// User action selected for an exhausted session limit. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum UISessionLimitsExhaustedResponseAction { + /// Increase the current max by an exact AI Credits amount. + #[serde(rename = "add")] + Add, + /// Set a new absolute max AI Credits value. + #[serde(rename = "set")] + Set, + /// Remove the current session limit. + #[serde(rename = "unset")] + Unset, + /// Leave the limit unchanged and cancel the blocked model request. + #[serde(rename = "cancel")] + Cancel, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// OAuth user authentication. The token itself is held in the runtime's secret token store (keyed by host+login) and is NOT carried in this struct. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum UserAuthInfoType { diff --git a/rust/src/generated/rpc.rs b/rust/src/generated/rpc.rs index 57a5192dca..403933a27c 100644 --- a/rust/src/generated/rpc.rs +++ b/rust/src/generated/rpc.rs @@ -7,6 +7,7 @@ #![allow(missing_docs)] #![allow(clippy::too_many_arguments)] +#![allow(deprecated)] #![allow(dead_code)] use super::api_types::{rpc_methods, *}; @@ -42,6 +43,13 @@ impl<'a> ClientRpc<'a> { } } + /// `commands.*` sub-namespace. + pub fn commands(&self) -> ClientRpcCommands<'a> { + ClientRpcCommands { + client: self.client, + } + } + /// `instructions.*` sub-namespace. pub fn instructions(&self) -> ClientRpcInstructions<'a> { ClientRpcInstructions { @@ -137,6 +145,14 @@ impl<'a> ClientRpc<'a> { /// # Returns /// /// Server liveness response, including the echoed message, current server timestamp, and protocol version. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn ping(&self, params: PingRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -152,11 +168,19 @@ impl<'a> ClientRpc<'a> { /// /// # Parameters /// - /// * `params` - Optional connection token presented by the SDK client during the handshake. + /// * `params` - Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). /// /// # Returns /// /// Handshake result reporting the server's protocol version and package version on success. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub(crate) async fn connect(&self, params: ConnectRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -181,6 +205,14 @@ impl<'a> ClientRpcAccount<'a> { /// # Returns /// /// Quota usage snapshots for the resolved user, keyed by quota type. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn get_quota(&self) -> Result { let wire_params = serde_json::json!({}); let _value = self @@ -201,6 +233,14 @@ impl<'a> ClientRpcAccount<'a> { /// # Returns /// /// Quota usage snapshots for the resolved user, keyed by quota type. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn get_quota_with_params( &self, params: AccountGetQuotaRequest, @@ -220,6 +260,14 @@ impl<'a> ClientRpcAccount<'a> { /// # Returns /// /// Current authentication state + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn get_current_auth(&self) -> Result { let wire_params = serde_json::json!({}); let _value = self @@ -236,6 +284,14 @@ impl<'a> ClientRpcAccount<'a> { /// # Returns /// /// List of all authenticated users + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn get_all_users(&self) -> Result { let wire_params = serde_json::json!({}); let _value = self @@ -256,6 +312,14 @@ impl<'a> ClientRpcAccount<'a> { /// # Returns /// /// Result of a successful login; throws on failure + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn login(&self, params: AccountLoginRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -276,6 +340,14 @@ impl<'a> ClientRpcAccount<'a> { /// # Returns /// /// Logout result indicating if more users remain + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn logout(&self, params: AccountLogoutRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -392,6 +464,38 @@ impl<'a> ClientRpcAgents<'a> { } } +/// `commands.*` RPCs. +#[derive(Clone, Copy)] +pub struct ClientRpcCommands<'a> { + pub(crate) client: &'a Client, +} + +impl<'a> ClientRpcCommands<'a> { + /// Lists the well-known built-in slash commands that work as the first message in a new session (e.g. /plan, /env), without requiring an active session. Commands that depend on session state, authentication, or a synced session are omitted. + /// + /// Wire method: `commands.list`. + /// + /// # Returns + /// + /// Slash commands available in the session, after applying any include/exclude filters. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn list(&self) -> Result { + let wire_params = serde_json::json!({}); + let _value = self + .client + .call(rpc_methods::COMMANDS_LIST, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + /// `instructions.*` RPCs. #[derive(Clone, Copy)] pub struct ClientRpcInstructions<'a> { @@ -590,6 +694,14 @@ impl<'a> ClientRpcMcp<'a> { /// # Returns /// /// MCP servers discovered from user, workspace, plugin, and built-in sources. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn discover(&self, params: McpDiscoverRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -614,6 +726,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Returns /// /// User-configured MCP servers, keyed by server name. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn list(&self) -> Result { let wire_params = serde_json::json!({}); let _value = self @@ -630,6 +750,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server name and configuration to add to user configuration. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn add(&self, params: McpConfigAddRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self @@ -646,6 +774,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server name and replacement configuration to write to user configuration. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn update(&self, params: McpConfigUpdateRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self @@ -662,6 +798,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server name to remove from user configuration. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn remove(&self, params: McpConfigRemoveRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self @@ -678,6 +822,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server names to enable for new sessions. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn enable(&self, params: McpConfigEnableRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self @@ -694,6 +846,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// # Parameters /// /// * `params` - MCP server names to disable for new sessions. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn disable(&self, params: McpConfigDisableRequest) -> Result<(), Error> { let wire_params = serde_json::to_value(params)?; let _value = self @@ -706,6 +866,14 @@ impl<'a> ClientRpcMcpConfig<'a> { /// Drops this runtime process's in-memory MCP server-definition cache so the next MCP config read observes disk. /// /// Wire method: `mcp.config.reload`. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn reload(&self) -> Result<(), Error> { let wire_params = serde_json::json!({}); let _value = self @@ -730,6 +898,14 @@ impl<'a> ClientRpcModels<'a> { /// # Returns /// /// List of Copilot models available to the resolved user, including capabilities and billing metadata. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn list(&self) -> Result { let wire_params = serde_json::json!({}); let _value = self @@ -750,6 +926,14 @@ impl<'a> ClientRpcModels<'a> { /// # Returns /// /// List of Copilot models available to the resolved user, including capabilities and billing metadata. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn list_with_params(&self, params: ModelsListRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -991,7 +1175,7 @@ impl<'a> ClientRpcPluginsMarketplaces<'a> { /// /// # Parameters /// - /// * `params` - Marketplace source to register. + /// * `params` - Marketplace source and optional working directory for relative-path resolution. /// /// # Returns /// @@ -1144,6 +1328,14 @@ impl<'a> ClientRpcRuntime<'a> { /// Gracefully shuts down an SDK-owned runtime. The response is sent only after cleanup completes; callers may then terminate the owned runtime process. /// /// Wire method: `runtime.shutdown`. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn shutdown(&self) -> Result<(), Error> { let wire_params = serde_json::json!({}); let _value = self @@ -1172,6 +1364,14 @@ impl<'a> ClientRpcSecrets<'a> { /// # Returns /// /// Confirmation that the secret values were registered. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn add_filter_values( &self, params: SecretsAddFilterValuesRequest, @@ -1203,6 +1403,14 @@ impl<'a> ClientRpcSessionFs<'a> { /// # Returns /// /// Indicates whether the calling client was registered as the session filesystem provider. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn set_provider( &self, params: SessionFsSetProviderRequest, @@ -2065,61 +2273,6 @@ impl<'a> ClientRpcSessions<'a> { Ok(serde_json::from_value(_value)?) } - /// Cursor-based long-poll for sessions spawned by the runtime (e.g. in response to a Mission Control `start_session` command). The cursor is an opaque token; pass it back to receive only spawn events that occurred AFTER the cursor was issued. Omit the cursor on the first call to receive any events buffered since the runtime started. Internal: this is a CLI background-daemon plumbing primitive. SDK consumers that need to react to runtime-spawned sessions should subscribe to a higher-level event stream rather than driving a long-poll loop. - /// - /// Wire method: `sessions.pollSpawnedSessions`. - /// - /// # Returns - /// - /// Batch of spawn events plus a cursor for follow-up polls. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub(crate) async fn poll_spawned_sessions(&self) -> Result { - let wire_params = serde_json::json!({}); - let _value = self - .client - .call(rpc_methods::SESSIONS_POLLSPAWNEDSESSIONS, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Cursor-based long-poll for sessions spawned by the runtime (e.g. in response to a Mission Control `start_session` command). The cursor is an opaque token; pass it back to receive only spawn events that occurred AFTER the cursor was issued. Omit the cursor on the first call to receive any events buffered since the runtime started. Internal: this is a CLI background-daemon plumbing primitive. SDK consumers that need to react to runtime-spawned sessions should subscribe to a higher-level event stream rather than driving a long-poll loop. - /// - /// Wire method: `sessions.pollSpawnedSessions`. - /// - /// # Parameters - /// - /// * `params` - Cursor and optional long-poll wait for polling runtime-spawned sessions. - /// - /// # Returns - /// - /// Batch of spawn events plus a cursor for follow-up polls. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub(crate) async fn poll_spawned_sessions_with_params( - &self, - params: SessionsPollSpawnedSessionsRequest, - ) -> Result { - let wire_params = serde_json::to_value(params)?; - let _value = self - .client - .call(rpc_methods::SESSIONS_POLLSPAWNEDSESSIONS, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - /// Registers extension-provided tools on the given session, gated by an optional `enabled` callback. Returns an opaque unsubscribe function the caller must invoke to deregister the tools when the extension is torn down. Marked internal because `loader`, `enabled`, and the returned `unsubscribe` are in-process handles that cannot cross the JSON-RPC boundary. Disappears once extension discovery / launch / tool registration are owned by the runtime: SDK consumers will pass pure config (search paths, disabled ids) via `SessionOptions` and the runtime will resolve, launch, register, and tear down extensions itself. /// /// Wire method: `sessions.registerExtensionToolsOnSession`. @@ -2210,6 +2363,14 @@ impl<'a> ClientRpcSkills<'a> { /// # Returns /// /// Skills discovered across global and project sources. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn discover(&self, params: SkillsDiscoverRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -2265,6 +2426,14 @@ impl<'a> ClientRpcSkillsConfig<'a> { /// # Parameters /// /// * `params` - Skill names to mark as disabled in global configuration, replacing any previous list. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn set_disabled_skills( &self, params: SkillsConfigSetDisabledSkillsRequest, @@ -2299,6 +2468,14 @@ impl<'a> ClientRpcTools<'a> { /// # Returns /// /// Built-in tools available for the requested model, with their parameters and instructions. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn list(&self, params: ToolsListRequest) -> Result { let wire_params = serde_json::to_value(params)?; let _value = self @@ -2334,6 +2511,14 @@ impl<'a> ClientRpcUserSettings<'a> { /// Drops this runtime process's in-memory user settings cache so the next settings read observes disk. /// /// Wire method: `user.settings.reload`. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
pub async fn reload(&self) -> Result<(), Error> { let wire_params = serde_json::json!({}); let _value = self @@ -2342,6 +2527,61 @@ impl<'a> ClientRpcUserSettings<'a> { .await?; Ok(()) } + + /// Lists every known user setting (settings.json overlaid with the legacy config.json, config.json wins), each with its effective value, its default, and whether it is at the default — so settings the user has never set still appear with their default value. Does not include repository- or enterprise-managed overrides that the runtime layers on top at session time. + /// + /// Wire method: `user.settings.get`. + /// + /// # Returns + /// + /// Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get(&self) -> Result { + let wire_params = serde_json::json!({}); + let _value = self + .client + .call(rpc_methods::USER_SETTINGS_GET, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Writes one or more user settings to settings.json, replacing each provided top-level key. A key whose value is null is removed. Returns the keys whose new value is shadowed by a legacy config.json entry (config.json wins on read), which the runtime leaves in place — such writes do not take effect until the legacy value is removed. + /// + /// Wire method: `user.settings.set`. + /// + /// # Parameters + /// + /// * `params` - Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. + /// + /// # Returns + /// + /// Outcome of writing user settings. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn set( + &self, + params: UserSettingsSetRequest, + ) -> Result { + let wire_params = serde_json::to_value(params)?; + let _value = self + .client + .call(rpc_methods::USER_SETTINGS_SET, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } } /// Typed view over a [`Session`]'s RPC namespace. @@ -2358,13 +2598,6 @@ impl<'a> SessionRpc<'a> { } } - /// `session.auth.*` sub-namespace. - pub fn auth(&self) -> SessionRpcAuth<'a> { - SessionRpcAuth { - session: self.session, - } - } - /// `session.canvas.*` sub-namespace. pub fn canvas(&self) -> SessionRpcCanvas<'a> { SessionRpcCanvas { @@ -2379,6 +2612,20 @@ impl<'a> SessionRpc<'a> { } } + /// `session.completions.*` sub-namespace. + pub fn completions(&self) -> SessionRpcCompletions<'a> { + SessionRpcCompletions { + session: self.session, + } + } + + /// `session.debug.*` sub-namespace. + pub fn debug(&self) -> SessionRpcDebug<'a> { + SessionRpcDebug { + session: self.session, + } + } + /// `session.eventLog.*` sub-namespace. pub fn event_log(&self) -> SessionRpcEventLog<'a> { SessionRpcEventLog { @@ -2400,6 +2647,13 @@ impl<'a> SessionRpc<'a> { } } + /// `session.gitHubAuth.*` sub-namespace. + pub fn git_hub_auth(&self) -> SessionRpcGitHubAuth<'a> { + SessionRpcGitHubAuth { + session: self.session, + } + } + /// `session.history.*` sub-namespace. pub fn history(&self) -> SessionRpcHistory<'a> { SessionRpcHistory { @@ -2512,6 +2766,13 @@ impl<'a> SessionRpc<'a> { } } + /// `session.settings.*` sub-namespace. + pub fn settings(&self) -> SessionRpcSettings<'a> { + SessionRpcSettings { + session: self.session, + } + } + /// `session.shell.*` sub-namespace. pub fn shell(&self) -> SessionRpcShell<'a> { SessionRpcShell { @@ -2561,6 +2822,13 @@ impl<'a> SessionRpc<'a> { } } + /// `session.visibility.*` sub-namespace. + pub fn visibility(&self) -> SessionRpcVisibility<'a> { + SessionRpcVisibility { + session: self.session, + } + } + /// `session.workspaces.*` sub-namespace. pub fn workspaces(&self) -> SessionRpcWorkspaces<'a> { SessionRpcWorkspaces { @@ -2619,6 +2887,39 @@ impl<'a> SessionRpc<'a> { Ok(serde_json::from_value(_value)?) } + /// Sends zero or more user messages to the session in a single turn and returns their message IDs. All provided messages are appended to the conversation in order, then exactly one agent turn runs over the resulting history. When the list is empty, one turn runs over the existing history with no new user message. Remote-backed (Mission Control) sessions do not support this method and will return an error. + /// + /// Wire method: `session.sendMessages`. + /// + /// # Parameters + /// + /// * `params` - Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. + /// + /// # Returns + /// + /// Result of sending zero or more user messages + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn send_messages( + &self, + params: SendMessagesRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_SENDMESSAGES, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Aborts the current agent turn. /// /// Wire method: `session.abort`. @@ -2840,72 +3141,6 @@ impl<'a> SessionRpcAgent<'a> { } } -/// `session.auth.*` RPCs. -#[derive(Clone, Copy)] -pub struct SessionRpcAuth<'a> { - pub(crate) session: &'a Session, -} - -impl<'a> SessionRpcAuth<'a> { - /// Gets authentication status and account metadata for the session. - /// - /// Wire method: `session.auth.getStatus`. - /// - /// # Returns - /// - /// Authentication status and account metadata for the session. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn get_status(&self) -> Result { - let wire_params = serde_json::json!({ "sessionId": self.session.id() }); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_AUTH_GETSTATUS, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Updates the session's auth credentials used for outbound model and API requests. - /// - /// Wire method: `session.auth.setCredentials`. - /// - /// # Parameters - /// - /// * `params` - New auth credentials to install on the session. Omit to leave credentials unchanged. - /// - /// # Returns - /// - /// Indicates whether the credential update succeeded. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn set_credentials( - &self, - params: SessionSetCredentialsParams, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_AUTH_SETCREDENTIALS, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } -} - /// `session.canvas.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcCanvas<'a> { @@ -3143,7 +3378,7 @@ impl<'a> SessionRpcCommands<'a> { /// /// # Returns /// - /// Result of invoking the slash command (text output, prompt to send to the agent, or completion). + /// Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). /// ///
/// @@ -3305,6 +3540,118 @@ impl<'a> SessionRpcCommands<'a> { } } +/// `session.completions.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcCompletions<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcCompletions<'a> { + /// Gets the characters that should trigger host-driven completions for the session. Empty disables host-driven completions (e.g. local sessions, or a relay host that does not advertise them). + /// + /// Wire method: `session.completions.getTriggerCharacters`. + /// + /// # Returns + /// + /// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get_trigger_characters( + &self, + ) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_COMPLETIONS_GETTRIGGERCHARACTERS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Requests host-driven completion items for the current composer input. Returns an empty list when the host has no items or does not support completions. + /// + /// Wire method: `session.completions.request`. + /// + /// # Parameters + /// + /// * `params` - Request host-driven completions for the current composer input. + /// + /// # Returns + /// + /// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn request( + &self, + params: CompletionsRequestRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_COMPLETIONS_REQUEST, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + +/// `session.debug.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcDebug<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcDebug<'a> { + /// Collects a redacted session debug log bundle into a local archive or staging directory. The runtime includes session-owned logs by default and accepts caller-provided diagnostic entries so host applications can add their own files without changing this API shape. + /// + /// Wire method: `session.debug.collectLogs`. + /// + /// # Parameters + /// + /// * `params` - Options for collecting a redacted session debug bundle. + /// + /// # Returns + /// + /// Result of collecting a redacted debug bundle. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn collect_logs( + &self, + params: DebugCollectLogsRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_DEBUG_COLLECTLOGS, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + /// `session.eventLog.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcEventLog<'a> { @@ -3616,6 +3963,75 @@ impl<'a> SessionRpcFleet<'a> { } } +/// `session.gitHubAuth.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcGitHubAuth<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcGitHubAuth<'a> { + /// Gets authentication status and account metadata for the session. + /// + /// Wire method: `session.gitHubAuth.getStatus`. + /// + /// # Returns + /// + /// Authentication status and account metadata for the session. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get_status(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_GITHUBAUTH_GETSTATUS, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Updates the session's auth credentials used for outbound model and API requests. + /// + /// Wire method: `session.gitHubAuth.setCredentials`. + /// + /// # Parameters + /// + /// * `params` - New auth credentials to install on the session. Omit to leave credentials unchanged. + /// + /// # Returns + /// + /// Indicates whether the credential update succeeded. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn set_credentials( + &self, + params: SessionSetCredentialsParams, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_GITHUBAUTH_SETCREDENTIALS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + /// `session.history.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcHistory<'a> { @@ -3887,6 +4303,13 @@ impl<'a> SessionRpcMcp<'a> { } } + /// `session.mcp.headers.*` sub-namespace. + pub fn headers(&self) -> SessionRpcMcpHeaders<'a> { + SessionRpcMcpHeaders { + session: self.session, + } + } + /// `session.mcp.oauth.*` sub-namespace. pub fn oauth(&self) -> SessionRpcMcpOauth<'a> { SessionRpcMcpOauth { @@ -3894,6 +4317,13 @@ impl<'a> SessionRpcMcp<'a> { } } + /// `session.mcp.resources.*` sub-namespace. + pub fn resources(&self) -> SessionRpcMcpResources<'a> { + SessionRpcMcpResources { + session: self.session, + } + } + /// Lists MCP servers configured for the session, their connection status, and host-level state. The host-level state (disabled/filtered servers, failed/needs-auth/pending connections, mcp3p policy, full config) is empty/zero when no MCP host has been initialized for the session. /// /// Wire method: `session.mcp.list`. @@ -3919,7 +4349,7 @@ impl<'a> SessionRpcMcp<'a> { Ok(serde_json::from_value(_value)?) } - /// Lists the tools exposed by a connected MCP server on this session's host. + /// Lists the tools exposed by a connected MCP server on this session's host. This performs a live `tools/list` request. Tool UI metadata is returned independently of whether MCP Apps rendering is enabled for the session. /// /// Wire method: `session.mcp.listTools`. /// @@ -4218,13 +4648,13 @@ impl<'a> SessionRpcMcp<'a> { Ok(serde_json::from_value(_value)?) } - /// Starts an individual MCP server on the session's host. + /// Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. /// /// Wire method: `session.mcp.startServer`. /// /// # Parameters /// - /// * `params` - Server name and opaque configuration for an individual MCP server start. + /// * `params` - Server name and configuration for an individual MCP server start. /// ///
/// @@ -4233,7 +4663,7 @@ impl<'a> SessionRpcMcp<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub(crate) async fn start_server(&self, params: McpStartServerRequest) -> Result<(), Error> { + pub async fn start_server(&self, params: McpStartServerRequest) -> Result<(), Error> { let mut wire_params = serde_json::to_value(params)?; wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); let _value = self @@ -4244,13 +4674,13 @@ impl<'a> SessionRpcMcp<'a> { Ok(()) } - /// Restarts an individual MCP server on the session's host (stops then starts). + /// Restarts an individual MCP server on the live session (stops then starts). Omit `config` for a config-free restart-by-name of an already-configured server; supply `config` to restart with a replacement configuration. Session-scoped and ephemeral: does NOT modify persistent user configuration (`mcp.config.*`). /// /// Wire method: `session.mcp.restartServer`. /// /// # Parameters /// - /// * `params` - Server name and opaque configuration for an individual MCP server restart. + /// * `params` - Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. /// ///
/// @@ -4259,10 +4689,7 @@ impl<'a> SessionRpcMcp<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub(crate) async fn restart_server( - &self, - params: McpRestartServerRequest, - ) -> Result<(), Error> { + pub async fn restart_server(&self, params: McpRestartServerRequest) -> Result<(), Error> { let mut wire_params = serde_json::to_value(params)?; wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); let _value = self @@ -4531,20 +4958,137 @@ impl<'a> SessionRpcMcpApps<'a> { .session .client() .call( - rpc_methods::SESSION_MCP_APPS_SETHOSTCONTEXT, + rpc_methods::SESSION_MCP_APPS_SETHOSTCONTEXT, + Some(wire_params), + ) + .await?; + Ok(()) + } + + /// Read the current host context advertised to MCP App guests. + /// + /// Wire method: `session.mcp.apps.getHostContext`. + /// + /// # Returns + /// + /// Current host context advertised to MCP App guests. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get_host_context(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_MCP_APPS_GETHOSTCONTEXT, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Diagnose MCP Apps wiring for a specific MCP server. Reports the session capability, feature-flag state, advertised extension, and how many tools have `_meta.ui` populated. + /// + /// Wire method: `session.mcp.apps.diagnose`. + /// + /// # Parameters + /// + /// * `params` - MCP server to diagnose MCP Apps wiring for. + /// + /// # Returns + /// + /// Diagnostic snapshot of MCP Apps wiring for the named server. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn diagnose( + &self, + params: McpAppsDiagnoseRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_MCP_APPS_DIAGNOSE, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + +/// `session.mcp.headers.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcMcpHeaders<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcMcpHeaders<'a> { + /// Responds to a pending MCP dynamic headers refresh request. Hosts that subscribe to `mcp.headers_refresh_required` use this to provide short-lived per-server headers or to indicate that no dynamic headers are available for this refresh. + /// + /// Wire method: `session.mcp.headers.handlePendingHeadersRefreshRequest`. + /// + /// # Parameters + /// + /// * `params` - MCP headers refresh request id and the host response. + /// + /// # Returns + /// + /// Indicates whether the pending MCP headers refresh response was accepted. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn handle_pending_headers_refresh_request( + &self, + params: McpHeadersHandlePendingHeadersRefreshRequestRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_MCP_HEADERS_HANDLEPENDINGHEADERSREFRESHREQUEST, Some(wire_params), ) .await?; - Ok(()) + Ok(serde_json::from_value(_value)?) } +} - /// Read the current host context advertised to MCP App guests. +/// `session.mcp.oauth.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcMcpOauth<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcMcpOauth<'a> { + /// Resolves a pending MCP OAuth request with a host-provided token or cancellation. The pending request is emitted as mcp.oauth_required with the data necessary to authorize the request. /// - /// Wire method: `session.mcp.apps.getHostContext`. + /// Wire method: `session.mcp.oauth.handlePendingRequest`. + /// + /// # Parameters + /// + /// * `params` - Pending MCP OAuth request ID and host-provided token or cancellation response. /// /// # Returns /// - /// Current host context advertised to MCP App guests. + /// Indicates whether the pending MCP OAuth response was accepted. /// ///
/// @@ -4553,30 +5097,34 @@ impl<'a> SessionRpcMcpApps<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn get_host_context(&self) -> Result { - let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + pub async fn handle_pending_request( + &self, + params: McpOauthHandlePendingRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); let _value = self .session .client() .call( - rpc_methods::SESSION_MCP_APPS_GETHOSTCONTEXT, + rpc_methods::SESSION_MCP_OAUTH_HANDLEPENDINGREQUEST, Some(wire_params), ) .await?; Ok(serde_json::from_value(_value)?) } - /// Diagnose MCP Apps wiring for a specific MCP server. Reports the session capability, feature-flag state, advertised extension, and how many tools have `_meta.ui` populated. + /// Starts OAuth authentication for a remote MCP server. /// - /// Wire method: `session.mcp.apps.diagnose`. + /// Wire method: `session.mcp.oauth.login`. /// /// # Parameters /// - /// * `params` - MCP server to diagnose MCP Apps wiring for. + /// * `params` - Remote MCP server name and optional overrides controlling reauthentication, OAuth client display name, callback success-page copy, and static OAuth client selection. /// /// # Returns /// - /// Diagnostic snapshot of MCP Apps wiring for the named server. + /// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. /// ///
/// @@ -4585,39 +5133,36 @@ impl<'a> SessionRpcMcpApps<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn diagnose( - &self, - params: McpAppsDiagnoseRequest, - ) -> Result { + pub async fn login(&self, params: McpOauthLoginRequest) -> Result { let mut wire_params = serde_json::to_value(params)?; wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); let _value = self .session .client() - .call(rpc_methods::SESSION_MCP_APPS_DIAGNOSE, Some(wire_params)) + .call(rpc_methods::SESSION_MCP_OAUTH_LOGIN, Some(wire_params)) .await?; Ok(serde_json::from_value(_value)?) } } -/// `session.mcp.oauth.*` RPCs. +/// `session.mcp.resources.*` RPCs. #[derive(Clone, Copy)] -pub struct SessionRpcMcpOauth<'a> { +pub struct SessionRpcMcpResources<'a> { pub(crate) session: &'a Session, } -impl<'a> SessionRpcMcpOauth<'a> { - /// Responds to a pending MCP OAuth request with an in-process provider. This internal CLI-only API accepts a live OAuthClientProvider instance and cannot be used over the SDK JSON-RPC boundary. Use session.mcp.oauth.handlePendingRequest instead for the public SDK-safe response path. +impl<'a> SessionRpcMcpResources<'a> { + /// Fetch an MCP resource from a connected server by URI (proxies MCP `resources/read`). /// - /// Wire method: `session.mcp.oauth.respond`. + /// Wire method: `session.mcp.resources.read`. /// /// # Parameters /// - /// * `params` - MCP OAuth request id and optional provider response. + /// * `params` - MCP server and resource URI to fetch. /// /// # Returns /// - /// Empty result after recording the MCP OAuth response. + /// Resource contents returned by the MCP server. /// ///
/// @@ -4626,31 +5171,31 @@ impl<'a> SessionRpcMcpOauth<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub(crate) async fn respond( + pub async fn read( &self, - params: McpOauthRespondRequest, - ) -> Result { + params: McpResourcesReadRequest, + ) -> Result { let mut wire_params = serde_json::to_value(params)?; wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); let _value = self .session .client() - .call(rpc_methods::SESSION_MCP_OAUTH_RESPOND, Some(wire_params)) + .call(rpc_methods::SESSION_MCP_RESOURCES_READ, Some(wire_params)) .await?; Ok(serde_json::from_value(_value)?) } - /// Resolves a pending MCP OAuth request with a host-provided token or cancellation. The pending request is emitted as mcp.oauth_required with the data necessary to authorize the request. + /// Enumerate one page of resources a connected MCP server exposes (proxies MCP `resources/list`). Pass `cursor` to continue from a prior result's `nextCursor`. /// - /// Wire method: `session.mcp.oauth.handlePendingRequest`. + /// Wire method: `session.mcp.resources.list`. /// /// # Parameters /// - /// * `params` - Pending MCP OAuth request ID and host-provided token or cancellation response. + /// * `params` - MCP server whose resources to enumerate. /// /// # Returns /// - /// Indicates whether the pending MCP OAuth response was accepted. + /// One page of resources advertised by the named MCP server. /// ///
/// @@ -4659,34 +5204,31 @@ impl<'a> SessionRpcMcpOauth<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn handle_pending_request( + pub async fn list( &self, - params: McpOauthHandlePendingRequest, - ) -> Result { + params: McpResourcesListRequest, + ) -> Result { let mut wire_params = serde_json::to_value(params)?; wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); let _value = self .session .client() - .call( - rpc_methods::SESSION_MCP_OAUTH_HANDLEPENDINGREQUEST, - Some(wire_params), - ) + .call(rpc_methods::SESSION_MCP_RESOURCES_LIST, Some(wire_params)) .await?; Ok(serde_json::from_value(_value)?) } - /// Starts OAuth authentication for a remote MCP server. + /// Enumerate one page of resource templates a connected MCP server exposes (proxies MCP `resources/templates/list`). Pass `cursor` to continue from a prior result's `nextCursor`. /// - /// Wire method: `session.mcp.oauth.login`. + /// Wire method: `session.mcp.resources.listTemplates`. /// /// # Parameters /// - /// * `params` - Remote MCP server name and optional overrides controlling reauthentication, OAuth client display name, callback success-page copy, and static OAuth client selection. + /// * `params` - MCP server whose resource templates to enumerate. /// /// # Returns /// - /// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. + /// One page of resource templates advertised by the named MCP server. /// ///
/// @@ -4695,13 +5237,19 @@ impl<'a> SessionRpcMcpOauth<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn login(&self, params: McpOauthLoginRequest) -> Result { + pub async fn list_templates( + &self, + params: McpResourcesListTemplatesRequest, + ) -> Result { let mut wire_params = serde_json::to_value(params)?; wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); let _value = self .session .client() - .call(rpc_methods::SESSION_MCP_OAUTH_LOGIN, Some(wire_params)) + .call( + rpc_methods::SESSION_MCP_RESOURCES_LISTTEMPLATES, + Some(wire_params), + ) .await?; Ok(serde_json::from_value(_value)?) } @@ -4825,6 +5373,70 @@ impl<'a> SessionRpcMetadata<'a> { Ok(serde_json::from_value(_value)?) } + /// Returns the experimental per-source attribution breakdown of the session's current context window as a flat list of entries (skills, subagents, MCP servers, built-in tools, plugin rollups, system/tool-definition costs, with nesting via parentId), plus the successful compaction count. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. Returns null until the session has initialized its system prompt and tool metadata. + /// + /// Wire method: `session.metadata.getContextAttribution`. + /// + /// # Returns + /// + /// Per-source attribution breakdown for the session's current context window, or null if uninitialized. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get_context_attribution(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_METADATA_GETCONTEXTATTRIBUTION, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Returns the largest individual messages currently in the session's context window, most-expensive first. Companion to `metadata.getContextAttribution`. Returns an empty list until the session has initialized. + /// + /// Wire method: `session.metadata.getContextHeaviestMessages`. + /// + /// # Parameters + /// + /// * `params` - Parameters for the heaviest-messages query. + /// + /// # Returns + /// + /// The heaviest individual messages in the session's context window, most-expensive first. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get_context_heaviest_messages( + &self, + params: MetadataContextHeaviestMessagesRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_METADATA_GETCONTEXTHEAVIESTMESSAGES, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Records a working-directory/git context change and emits a `session.context_changed` event. /// /// Wire method: `session.metadata.recordContextChange`. @@ -4861,17 +5473,17 @@ impl<'a> SessionRpcMetadata<'a> { Ok(serde_json::from_value(_value)?) } - /// Updates the session's recorded working directory. + /// Updates the session's working directory. For local sessions the target is validated first (an absolute path that exists on disk) and the permission primary directory is re-based; a rejected validation fails the call before any session state changes. /// /// Wire method: `session.metadata.setWorkingDirectory`. /// /// # Parameters /// - /// * `params` - Absolute path to set as the session's new working directory. + /// * `params` - Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. /// /// # Returns /// - /// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded path. + /// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. /// ///
/// @@ -5454,13 +6066,13 @@ impl<'a> SessionRpcPermissions<'a> { Ok(serde_json::from_value(_value)?) } - /// Enables or disables full allow-all permissions (tools, paths, and URLs) for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. Unlike `setApproveAll`, this swaps in the unrestricted path and URL managers and emits `session.permissions_changed` on transition. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire. + /// Sets the allow-all permission mode for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. The `on` mode swaps in unrestricted path and URL managers and emits `session.permissions_changed` on transition; the `auto` mode keeps normal prompt paths active while attaching LLM safety recommendations. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire. /// /// Wire method: `session.permissions.setAllowAll`. /// /// # Parameters /// - /// * `params` - Whether to enable full allow-all permissions for the session. + /// * `params` - Allow-all mode to apply for the session. /// /// # Returns /// @@ -5490,13 +6102,13 @@ impl<'a> SessionRpcPermissions<'a> { Ok(serde_json::from_value(_value)?) } - /// Returns whether full allow-all permissions are currently active for the session. + /// Returns the current allow-all permission mode for the session. /// /// Wire method: `session.permissions.getAllowAll`. /// /// # Returns /// - /// Current full allow-all permission state. + /// Current allow-all permission mode. /// ///
/// @@ -6628,6 +7240,75 @@ impl<'a> SessionRpcSchedule<'a> { } } +/// `session.settings.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcSettings<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcSettings<'a> { + /// Returns a redacted snapshot of session runtime settings, with secrets and raw feature flags excluded. Internal: the runtime settings shape is a runtime-internal surface and is deliberately kept out of the public SDK, because consumers should not depend on the runtime's internal settings layout. It remains callable in-process and is expected to be reworked as the runtime internals are consolidated. + /// + /// Wire method: `session.settings.snapshot`. + /// + /// # Returns + /// + /// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub(crate) async fn snapshot(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_SETTINGS_SNAPSHOT, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Evaluates a named Rust-owned settings predicate without exposing raw feature flags. Internal: the raw feature-flag names and composition are runtime-internal, so this predicate-evaluation helper is kept out of the public SDK surface and is callable in-process only. + /// + /// Wire method: `session.settings.evaluatePredicate`. + /// + /// # Parameters + /// + /// * `params` - Named Rust-owned settings predicate to evaluate for this session. + /// + /// # Returns + /// + /// Result of evaluating a Rust-owned settings predicate. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub(crate) async fn evaluate_predicate( + &self, + params: SessionSettingsEvaluatePredicateRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_SETTINGS_EVALUATEPREDICATE, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + /// `session.shell.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcShell<'a> { @@ -7681,6 +8362,42 @@ impl<'a> SessionRpcUi<'a> { Ok(serde_json::from_value(_value)?) } + /// Resolves a pending `session_limits_exhausted.requested` event with the user's selected limit action. + /// + /// Wire method: `session.ui.handlePendingSessionLimitsExhausted`. + /// + /// # Parameters + /// + /// * `params` - Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. + /// + /// # Returns + /// + /// Indicates whether the pending UI request was resolved by this call. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn handle_pending_session_limits_exhausted( + &self, + params: UIHandlePendingSessionLimitsExhaustedRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_UI_HANDLEPENDINGSESSIONLIMITSEXHAUSTED, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Resolves a pending `exit_plan_mode.requested` event with the user's response. /// /// Wire method: `session.ui.handlePendingExitPlanMode`. @@ -7817,6 +8534,69 @@ impl<'a> SessionRpcUsage<'a> { } } +/// `session.visibility.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcVisibility<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcVisibility<'a> { + /// Returns the session's current Mission Control sharing status and shareable GitHub URL. Reflects whether the synced session is visible to repository readers ("repo") or restricted to its creator and collaborators ("unshared"). + /// + /// Wire method: `session.visibility.get`. + /// + /// # Returns + /// + /// Current sharing status and shareable GitHub URL for a session. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_VISIBILITY_GET, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Sets the session's Mission Control sharing status, controlling whether the synced session is visible to repository readers. Returns the effective status and shareable GitHub URL after the change. + /// + /// Wire method: `session.visibility.set`. + /// + /// # Parameters + /// + /// * `params` - Desired sharing status for the session. + /// + /// # Returns + /// + /// Effective sharing status and shareable GitHub URL after updating session visibility. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn set(&self, params: VisibilitySetRequest) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_VISIBILITY_SET, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + /// `session.workspaces.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcWorkspaces<'a> { diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index e094ec3655..cf670c4856 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -1,5 +1,7 @@ //! Auto-generated from session-events.schema.json — do not edit manually. +#![allow(deprecated)] + use std::collections::HashMap; use serde::{Deserialize, Serialize}; @@ -37,6 +39,8 @@ pub enum SessionEventType { SessionModelChange, #[serde(rename = "session.mode_changed")] SessionModeChanged, + #[serde(rename = "session.session_limits_changed")] + SessionSessionLimitsChanged, #[serde(rename = "session.permissions_changed")] SessionPermissionsChanged, #[serde(rename = "session.plan_changed")] @@ -53,6 +57,8 @@ pub enum SessionEventType { SessionSnapshotRewind, #[serde(rename = "session.shutdown")] SessionShutdown, + #[serde(rename = "session.usage_checkpoint")] + SessionUsageCheckpoint, #[serde(rename = "session.context_changed")] SessionContextChanged, #[serde(rename = "session.usage_info")] @@ -71,10 +77,14 @@ pub enum SessionEventType { AssistantTurnStart, #[serde(rename = "assistant.intent")] AssistantIntent, + #[serde(rename = "assistant.server_tool_progress")] + AssistantServerToolProgress, #[serde(rename = "assistant.reasoning")] AssistantReasoning, #[serde(rename = "assistant.reasoning_delta")] AssistantReasoningDelta, + #[serde(rename = "assistant.tool_call_delta")] + AssistantToolCallDelta, #[serde(rename = "assistant.streaming_delta")] AssistantStreamingDelta, #[serde(rename = "assistant.message")] @@ -85,6 +95,8 @@ pub enum SessionEventType { AssistantMessageDelta, #[serde(rename = "assistant.turn_end")] AssistantTurnEnd, + #[serde(rename = "assistant.idle")] + AssistantIdle, #[serde(rename = "assistant.usage")] AssistantUsage, #[serde(rename = "model.call_failure")] @@ -152,6 +164,10 @@ pub enum SessionEventType { McpOauthRequired, #[serde(rename = "mcp.oauth_completed")] McpOauthCompleted, + #[serde(rename = "mcp.headers_refresh_required")] + McpHeadersRefreshRequired, + #[serde(rename = "mcp.headers_refresh_completed")] + McpHeadersRefreshCompleted, #[serde(rename = "session.custom_notification")] SessionCustomNotification, #[serde(rename = "external_tool.requested")] @@ -168,6 +184,28 @@ pub enum SessionEventType { AutoModeSwitchRequested, #[serde(rename = "auto_mode_switch.completed")] AutoModeSwitchCompleted, + #[serde(rename = "session_limits_exhausted.requested")] + SessionLimitsExhaustedRequested, + #[serde(rename = "session_limits_exhausted.completed")] + SessionLimitsExhaustedCompleted, + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(rename = "session.auto_mode_resolved")] + SessionAutoModeResolved, + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(rename = "session.managed_settings_resolved")] + SessionManagedSettingsResolved, #[serde(rename = "commands.changed")] CommandsChanged, #[serde(rename = "capabilities.changed")] @@ -188,6 +226,12 @@ pub enum SessionEventType { SessionMcpServersLoaded, #[serde(rename = "session.mcp_server_status_changed")] SessionMcpServerStatusChanged, + #[serde(rename = "mcp.tools.list_changed")] + McpToolsListChanged, + #[serde(rename = "mcp.resources.list_changed")] + McpResourcesListChanged, + #[serde(rename = "mcp.prompts.list_changed")] + McpPromptsListChanged, #[serde(rename = "session.extensions_loaded")] SessionExtensionsLoaded, /// @@ -288,6 +332,8 @@ pub enum SessionEventData { SessionModelChange(SessionModelChangeData), #[serde(rename = "session.mode_changed")] SessionModeChanged(SessionModeChangedData), + #[serde(rename = "session.session_limits_changed")] + SessionSessionLimitsChanged(SessionSessionLimitsChangedData), #[serde(rename = "session.permissions_changed")] SessionPermissionsChanged(SessionPermissionsChangedData), #[serde(rename = "session.plan_changed")] @@ -304,6 +350,8 @@ pub enum SessionEventData { SessionSnapshotRewind(SessionSnapshotRewindData), #[serde(rename = "session.shutdown")] SessionShutdown(SessionShutdownData), + #[serde(rename = "session.usage_checkpoint")] + SessionUsageCheckpoint(SessionUsageCheckpointData), #[serde(rename = "session.context_changed")] SessionContextChanged(SessionContextChangedData), #[serde(rename = "session.usage_info")] @@ -322,10 +370,14 @@ pub enum SessionEventData { AssistantTurnStart(AssistantTurnStartData), #[serde(rename = "assistant.intent")] AssistantIntent(AssistantIntentData), + #[serde(rename = "assistant.server_tool_progress")] + AssistantServerToolProgress(AssistantServerToolProgressData), #[serde(rename = "assistant.reasoning")] AssistantReasoning(AssistantReasoningData), #[serde(rename = "assistant.reasoning_delta")] AssistantReasoningDelta(AssistantReasoningDeltaData), + #[serde(rename = "assistant.tool_call_delta")] + AssistantToolCallDelta(AssistantToolCallDeltaData), #[serde(rename = "assistant.streaming_delta")] AssistantStreamingDelta(AssistantStreamingDeltaData), #[serde(rename = "assistant.message")] @@ -336,6 +388,8 @@ pub enum SessionEventData { AssistantMessageDelta(AssistantMessageDeltaData), #[serde(rename = "assistant.turn_end")] AssistantTurnEnd(AssistantTurnEndData), + #[serde(rename = "assistant.idle")] + AssistantIdle(AssistantIdleData), #[serde(rename = "assistant.usage")] AssistantUsage(AssistantUsageData), #[serde(rename = "model.call_failure")] @@ -396,6 +450,10 @@ pub enum SessionEventData { McpOauthRequired(McpOauthRequiredData), #[serde(rename = "mcp.oauth_completed")] McpOauthCompleted(McpOauthCompletedData), + #[serde(rename = "mcp.headers_refresh_required")] + McpHeadersRefreshRequired(McpHeadersRefreshRequiredData), + #[serde(rename = "mcp.headers_refresh_completed")] + McpHeadersRefreshCompleted(McpHeadersRefreshCompletedData), #[serde(rename = "session.custom_notification")] SessionCustomNotification(SessionCustomNotificationData), #[serde(rename = "external_tool.requested")] @@ -412,6 +470,28 @@ pub enum SessionEventData { AutoModeSwitchRequested(AutoModeSwitchRequestedData), #[serde(rename = "auto_mode_switch.completed")] AutoModeSwitchCompleted(AutoModeSwitchCompletedData), + #[serde(rename = "session_limits_exhausted.requested")] + SessionLimitsExhaustedRequested(SessionLimitsExhaustedRequestedData), + #[serde(rename = "session_limits_exhausted.completed")] + SessionLimitsExhaustedCompleted(SessionLimitsExhaustedCompletedData), + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(rename = "session.auto_mode_resolved")] + SessionAutoModeResolved(SessionAutoModeResolvedData), + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(rename = "session.managed_settings_resolved")] + SessionManagedSettingsResolved(SessionManagedSettingsResolvedData), #[serde(rename = "commands.changed")] CommandsChanged(CommandsChangedData), #[serde(rename = "capabilities.changed")] @@ -432,6 +512,12 @@ pub enum SessionEventData { SessionMcpServersLoaded(SessionMcpServersLoadedData), #[serde(rename = "session.mcp_server_status_changed")] SessionMcpServerStatusChanged(SessionMcpServerStatusChangedData), + #[serde(rename = "mcp.tools.list_changed")] + McpToolsListChanged(McpToolsListChangedData), + #[serde(rename = "mcp.resources.list_changed")] + McpResourcesListChanged(McpResourcesListChangedData), + #[serde(rename = "mcp.prompts.list_changed")] + McpPromptsListChanged(McpPromptsListChangedData), #[serde(rename = "session.extensions_loaded")] SessionExtensionsLoaded(SessionExtensionsLoadedData), /// @@ -550,6 +636,15 @@ pub struct WorkingDirectoryContext { pub repository_host: Option, } +/// Optional session limits. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLimitsConfig { + /// Maximum AI Credits allowed across the session's current accounting window. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_ai_credits: Option, +} + /// Session event "session.start". Session initialization metadata including context and configuration #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -584,8 +679,14 @@ pub struct SessionStartData { pub selected_model: Option, /// Unique identifier for the session pub session_id: SessionId, + /// Session limits configured at session creation time, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub session_limits: Option, /// ISO 8601 timestamp when the session was created pub start_time: String, + /// Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") + #[serde(skip_serializing_if = "Option::is_none")] + pub verbosity: Option, /// Schema version number for the session event format pub version: i64, } @@ -625,9 +726,15 @@ pub struct SessionResumeData { /// Model currently selected at resume time #[serde(skip_serializing_if = "Option::is_none")] pub selected_model: Option, + /// Session limits currently configured at resume time; null when no limits are active + #[serde(skip_serializing_if = "Option::is_none")] + pub session_limits: Option, /// True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. #[serde(skip_serializing_if = "Option::is_none")] pub session_was_active: Option, + /// Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") + #[serde(skip_serializing_if = "Option::is_none")] + pub verbosity: Option, } /// Session event "session.remote_steerable_changed". Notifies that the session's remote steering capability has changed @@ -799,12 +906,18 @@ pub struct SessionModelChangeData { /// Reasoning summary mode before the model change, if applicable #[serde(skip_serializing_if = "Option::is_none")] pub previous_reasoning_summary: Option, + /// Output verbosity level before the model change, if applicable + #[serde(skip_serializing_if = "Option::is_none")] + pub previous_verbosity: Option, /// Reasoning effort level after the model change, if applicable #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, /// Reasoning summary mode after the model change, if applicable #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_summary: Option, + /// Output verbosity level after the model change, if applicable + #[serde(skip_serializing_if = "Option::is_none")] + pub verbosity: Option, } /// Session event "session.mode_changed". Agent mode change details including previous and new modes @@ -817,12 +930,40 @@ pub struct SessionModeChangedData { pub previous_mode: SessionMode, } -/// Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all boolean transition. +/// Session event "session.session_limits_changed". Session limits update details. Null clears the limits. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSessionLimitsChangedData { + /// Current session limits, or null when no limits are active + pub session_limits: Option, +} + +/// Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all transition. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionPermissionsChangedData { + /// Allow-all mode after the change + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub allow_all_permission_mode: Option, /// Aggregate allow-all flag after the change pub allow_all_permissions: bool, + /// Allow-all mode before the change + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub previous_allow_all_permission_mode: Option, /// Aggregate allow-all flag before the change pub previous_allow_all_permissions: bool, } @@ -958,7 +1099,7 @@ pub struct ShutdownModelMetricRequests { pub count: Option, } -/// Schema for the `ShutdownModelMetricTokenDetail` type. +/// A token-type entry in a shutdown model metric, storing the accumulated token count. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShutdownModelMetricTokenDetail { @@ -983,7 +1124,7 @@ pub struct ShutdownModelMetricUsage { pub reasoning_tokens: Option, } -/// Schema for the `ShutdownModelMetric` type. +/// Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShutdownModelMetric { @@ -1006,7 +1147,7 @@ pub struct ShutdownModelMetric { pub usage: ShutdownModelMetricUsage, } -/// Schema for the `ShutdownTokenDetail` type. +/// A session-wide shutdown token-type entry storing the accumulated token count. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShutdownTokenDetail { @@ -1068,6 +1209,18 @@ pub struct SessionShutdownData { pub(crate) total_premium_requests: Option, } +/// Session event "session.usage_checkpoint". Durable session usage checkpoint for reconstructing aggregate accounting on resume +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionUsageCheckpointData { + /// Session-wide accumulated nano-AI units cost at checkpoint time + pub total_nano_aiu: f64, + /// Total number of premium API requests used at checkpoint time + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) total_premium_requests: Option, +} + /// Session event "session.context_changed". Updated working directory and git context after the change #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1128,6 +1281,9 @@ pub struct SessionCompactionStartData { /// Token count from non-system messages (user, assistant, tool) at compaction start #[serde(skip_serializing_if = "Option::is_none")] pub conversation_tokens: Option, + /// Model identifier used for compaction, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, /// Token count from system message(s) at compaction start #[serde(skip_serializing_if = "Option::is_none")] pub system_tokens: Option, @@ -1262,7 +1418,7 @@ pub struct SessionTaskCompleteData { pub summary: Option, } -/// Session event "user.message". +/// Session event "user.message". Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserMessageData { @@ -1274,6 +1430,9 @@ pub struct UserMessageData { pub attachments: Option>, /// The user's message text as displayed in the timeline pub content: String, + /// How this message was delivered to the agentic loop relative to loop state (idle-start vs. steering/queued while busy). The timing axis; combine with `source` (origin) for the full picture. Used for telemetry attribution. + #[serde(skip_serializing_if = "Option::is_none")] + pub delivery: Option, /// CAPI interaction ID for correlating this user message with its turn #[serde(skip_serializing_if = "Option::is_none")] pub interaction_id: Option, @@ -1309,6 +1468,9 @@ pub struct AssistantTurnStartData { /// CAPI interaction ID for correlating this turn with upstream telemetry #[serde(skip_serializing_if = "Option::is_none")] pub interaction_id: Option, + /// Model identifier used for this turn, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, /// Identifier for this turn within the agentic loop, typically a stringified turn number pub turn_id: String, } @@ -1321,6 +1483,18 @@ pub struct AssistantIntentData { pub intent: String, } +/// Session event "assistant.server_tool_progress". Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AssistantServerToolProgressData { + /// Kind of hosted server tool that is running. Only `web_search` is emitted today. + pub kind: String, + /// Position of the hosted tool call in the response output. Stable across the call's lifecycle events (unlike the provider's per-event item id, which CAPI rotates), so the host keys the live in-progress row on it. + pub output_index: i64, + /// Lifecycle status of the hosted call: `in_progress`, `searching`, or `completed`. + pub status: String, +} + /// Session event "assistant.reasoning". Assistant reasoning content for timeline display with complete thinking text #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1341,6 +1515,22 @@ pub struct AssistantReasoningDeltaData { pub reasoning_id: String, } +/// Session event "assistant.tool_call_delta". Streaming tool-call input delta for incremental tool-call updates +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AssistantToolCallDeltaData { + /// Raw provider tool input fragment to append for this tool call. Function/tool-use providers stream serialized JSON argument text (so newlines inside JSON string values may appear as escaped `\n` until the accumulated JSON is parsed); custom tool calls stream raw custom input. + pub input_delta: String, + /// Tool call ID this delta belongs to, matching the corresponding assistant.message tool request + pub tool_call_id: String, + /// Name of the tool being invoked, when known from the stream + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_name: Option, + /// Tool call type, when known from the stream + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_type: Option, +} + /// Session event "assistant.streaming_delta". Streaming response progress with cumulative byte count #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1502,6 +1692,9 @@ pub struct AssistantMessageData { ///
#[serde(skip_serializing_if = "Option::is_none")] pub citations: Option, + /// Client-minted request id (x-request-id header) echoed by the server. Distinct from requestId (x-github-request-id) and serviceRequestId (x-copilot-service-request-id). + #[serde(skip_serializing_if = "Option::is_none")] + pub client_request_id: Option, /// The assistant's text response content pub content: String, /// Encrypted reasoning content from OpenAI models. Session-bound and stripped on resume. @@ -1532,6 +1725,9 @@ pub struct AssistantMessageData { /// Readable reasoning text from the model's extended thinking #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_text: Option, + /// OpenAI-compatible wire field the provider used for reasoning (e.g. reasoning_content/reasoning). Populated only when non-canonical, so the dialect round-trips across turns. + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_wire_field: Option, /// GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs #[serde(skip_serializing_if = "Option::is_none")] pub request_id: Option, @@ -1579,10 +1775,22 @@ pub struct AssistantMessageDeltaData { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AssistantTurnEndData { + /// Model identifier used for this turn, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, /// Identifier of the turn that has ended, matching the corresponding assistant.turn_start event pub turn_id: String, } +/// Session event "assistant.idle". Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AssistantIdleData { + /// True when the preceding agentic loop was cancelled via abort signal + #[serde(skip_serializing_if = "Option::is_none")] + pub aborted: Option, +} + /// Token usage detail for a single billing category #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1609,7 +1817,7 @@ pub struct AssistantUsageCopilotUsage { pub total_nano_aiu: f64, } -/// Schema for the `AssistantUsageQuotaSnapshot` type. +/// Internal per-quota snapshot for assistant usage, including entitlement, consumed requests, overage, reset date, and remaining quota. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct AssistantUsageQuotaSnapshot { @@ -1727,7 +1935,7 @@ pub struct AssistantUsageData { pub service_request_id: Option, /// Time to first token in milliseconds. Only available for streaming requests #[serde(skip_serializing_if = "Option::is_none")] - pub time_to_first_token_ms: Option, + pub time_to_first_token_ms: Option, } /// Content-free structural summary of the failing request for diagnosing malformed 4xx calls @@ -1820,7 +2028,17 @@ pub struct ToolUserRequestedData { pub tool_name: String, } -/// Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. +/// Shell-aware path hints for a shell tool's command, captured at start time so consumers can snapshot a file's pre-image before the tool runs. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ToolExecutionStartShellToolInfo { + /// Whether the command includes a file write redirection (e.g., > or >>). + pub has_write_file_redirection: bool, + /// File paths the command may read or write, derived from the command at start time. Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. + pub possible_paths: Vec, +} + +/// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionStartToolDescriptionMetaUI { @@ -1836,7 +2054,7 @@ pub struct ToolExecutionStartToolDescriptionMetaUI { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionStartToolDescriptionMeta { - /// Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. + /// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. #[serde(skip_serializing_if = "Option::is_none")] pub ui: Option, } @@ -1879,6 +2097,9 @@ pub struct ToolExecutionStartData { #[deprecated] #[serde(skip_serializing_if = "Option::is_none")] pub parent_tool_call_id: Option, + /// Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. + #[serde(skip_serializing_if = "Option::is_none")] + pub shell_tool_info: Option, /// Unique identifier for this tool call pub tool_call_id: String, /// Tool definition metadata, present for MCP tools with MCP Apps support @@ -1958,7 +2179,9 @@ pub struct ToolExecutionCompleteContentText { pub r#type: ToolExecutionCompleteContentTextType, } -/// Terminal/shell output content block with optional exit code and working directory +/// Deprecated for shell command exit metadata. Use ToolExecutionCompleteContentShellExit instead. +#[doc(hidden)] +#[deprecated] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteContentTerminal { @@ -1974,6 +2197,27 @@ pub struct ToolExecutionCompleteContentTerminal { pub r#type: ToolExecutionCompleteContentTerminalType, } +/// Shell command exit metadata with optional output preview +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ToolExecutionCompleteContentShellExit { + /// Working directory where the shell command was executed + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// Exit code from the completed shell command + pub exit_code: i64, + /// Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. + #[serde(skip_serializing_if = "Option::is_none")] + pub output_preview: Option, + /// Whether outputPreview is known to be incomplete or truncated + #[serde(skip_serializing_if = "Option::is_none")] + pub output_truncated: Option, + /// Shell id, as assigned by Copilot runtime + pub shell_id: String, + /// Content block type discriminator + pub r#type: ToolExecutionCompleteContentShellExitType, +} + /// Image content block with base64-encoded data #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -2042,7 +2286,7 @@ pub struct ToolExecutionCompleteContentResourceLink { pub uri: String, } -/// Schema for the `EmbeddedTextResourceContents` type. +/// Embedded text resource contents identified by a URI, with an optional MIME type and a text payload. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EmbeddedTextResourceContents { @@ -2055,7 +2299,7 @@ pub struct EmbeddedTextResourceContents { pub uri: String, } -/// Schema for the `EmbeddedBlobResourceContents` type. +/// Embedded binary resource contents identified by a URI, with an optional MIME type and a base64-encoded blob. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EmbeddedBlobResourceContents { @@ -2078,7 +2322,7 @@ pub struct ToolExecutionCompleteContentResource { pub r#type: ToolExecutionCompleteContentResourceType, } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. +/// CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMetaUICsp { @@ -2092,54 +2336,54 @@ pub struct ToolExecutionCompleteUIResourceMetaUICsp { pub resource_domains: Option>, } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. +/// Marker object for camera permission on an MCP Apps UI resource. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMetaUIPermissionsCamera {} -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. +/// Marker object for clipboard-write permission on an MCP Apps UI resource. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite {} -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. +/// Marker object for geolocation permission on an MCP Apps UI resource. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation {} -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. +/// Marker object for microphone permission on an MCP Apps UI resource. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone {} -/// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. +/// Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMetaUIPermissions { - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. + /// Marker object for camera permission on an MCP Apps UI resource. #[serde(skip_serializing_if = "Option::is_none")] pub camera: Option, - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. + /// Marker object for clipboard-write permission on an MCP Apps UI resource. #[serde(skip_serializing_if = "Option::is_none")] pub clipboard_write: Option, - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. + /// Marker object for geolocation permission on an MCP Apps UI resource. #[serde(skip_serializing_if = "Option::is_none")] pub geolocation: Option, - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. + /// Marker object for microphone permission on an MCP Apps UI resource. #[serde(skip_serializing_if = "Option::is_none")] pub microphone: Option, } -/// Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. +/// MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMetaUI { - /// Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. + /// CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. #[serde(skip_serializing_if = "Option::is_none")] pub csp: Option, #[serde(skip_serializing_if = "Option::is_none")] pub domain: Option, - /// Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. + /// Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. #[serde(skip_serializing_if = "Option::is_none")] pub permissions: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -2150,7 +2394,7 @@ pub struct ToolExecutionCompleteUIResourceMetaUI { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteUIResourceMeta { - /// Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. + /// MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. #[serde(skip_serializing_if = "Option::is_none")] pub ui: Option, } @@ -2206,6 +2450,16 @@ pub struct ToolExecutionCompleteResult { /// Full detailed tool result for UI/timeline display, preserving complete content such as diffs. Falls back to content when absent. #[serde(skip_serializing_if = "Option::is_none")] pub detailed_content: Option, + /// FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels) — persisted as `{ ifc: ... }` (only the `ifc` key, not the whole `_meta`). Persisted so the FIDES IFC label survives session resume: the engine rehydrates accumulated taint by replaying these on load. Populated for ingress sources when FIDES IFC is on. Experimental. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub mcp_meta: Option, /// Structured content (arbitrary JSON) returned verbatim by the MCP tool #[serde(skip_serializing_if = "Option::is_none")] pub structured_content: Option, @@ -2214,7 +2468,7 @@ pub struct ToolExecutionCompleteResult { pub ui_resource: Option, } -/// Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. +/// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteToolDescriptionMetaUI { @@ -2230,7 +2484,7 @@ pub struct ToolExecutionCompleteToolDescriptionMetaUI { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolExecutionCompleteToolDescriptionMeta { - /// Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. + /// MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. #[serde(skip_serializing_if = "Option::is_none")] pub ui: Option, } @@ -2262,6 +2516,16 @@ pub struct ToolExecutionCompleteData { /// Whether this tool call was explicitly requested by the user rather than the assistant #[serde(skip_serializing_if = "Option::is_none")] pub is_user_requested: Option, + /// FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels). Persisted as `{ ifc: ... }` so the label survives session resume, including model-visible failure results. Experimental. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub mcp_meta: Option, /// Model identifier that generated this tool call #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, @@ -2303,6 +2567,9 @@ pub struct SkillInvokedData { /// Description of the skill from its SKILL.md frontmatter #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, + /// Model identifier active when the skill was invoked, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, /// Name of the invoked skill pub name: String, /// File path to the SKILL.md definition @@ -2521,7 +2788,7 @@ pub struct SystemNotificationData { pub kind: serde_json::Value, } -/// Schema for the `PermissionRequestShellCommand` type. +/// A parsed command identifier in a shell permission request, including whether it is read-only. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionRequestShellCommand { @@ -2531,7 +2798,7 @@ pub struct PermissionRequestShellCommand { pub read_only: bool, } -/// Schema for the `PermissionRequestShellPossibleUrl` type. +/// A URL that may be accessed by a command in a shell permission request. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionRequestShellPossibleUrl { @@ -2590,6 +2857,12 @@ pub struct PermissionRequestWrite { /// Complete new file contents for newly created files #[serde(skip_serializing_if = "Option::is_none")] pub new_file_contents: Option, + /// True when a built-in file tool (apply_patch / str_replace_editor) asked to write a path the sandbox filesystem policy would block, and the host opted in via sandbox.allowBypass. This is a request, not a grant: the write happens unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass: Option, + /// Justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass_reason: Option, /// Tool call ID that triggered this permission request #[serde(skip_serializing_if = "Option::is_none")] pub tool_call_id: Option, @@ -2605,6 +2878,12 @@ pub struct PermissionRequestRead { pub kind: PermissionRequestReadKind, /// Path of the file or directory being read pub path: String, + /// True when the model has requested to run this search outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the search runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass: Option, + /// Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass_reason: Option, /// Tool call ID that triggered this permission request #[serde(skip_serializing_if = "Option::is_none")] pub tool_call_id: Option, @@ -2640,6 +2919,12 @@ pub struct PermissionRequestUrl { pub intention: String, /// Permission kind discriminator pub kind: PermissionRequestUrlKind, + /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass: Option, + /// Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass_reason: Option, /// Tool call ID that triggered this permission request #[serde(skip_serializing_if = "Option::is_none")] pub tool_call_id: Option, @@ -2743,10 +3028,38 @@ pub struct PermissionRequestExtensionPermissionAccess { pub tool_call_id: Option, } +/// Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is "auto"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PermissionAutoApproval { + /// Human-readable reason for the judge's recommendation, when available. + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// The auto-approval safety judge's outcome for this request. + pub recommendation: AutoApprovalRecommendation, +} + /// Shell command permission prompt #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionPromptRequestCommands { + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Whether the UI can offer session-wide approval for this command pattern pub can_offer_session_approval: bool, /// Command identifiers covered by this approval prompt @@ -2769,6 +3082,16 @@ pub struct PermissionPromptRequestCommands { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionPromptRequestWrite { + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Whether the UI can offer session-wide approval for file write operations pub can_offer_session_approval: bool, /// Unified diff showing the proposed changes @@ -2791,6 +3114,16 @@ pub struct PermissionPromptRequestWrite { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionPromptRequestRead { + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Human-readable description of why the file is being read pub intention: String, /// Prompt kind discriminator @@ -2809,6 +3142,16 @@ pub struct PermissionPromptRequestMcp { /// Arguments to pass to the MCP tool #[serde(skip_serializing_if = "Option::is_none")] pub args: Option, + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Prompt kind discriminator pub kind: PermissionPromptRequestMcpKind, /// Name of the MCP server providing the tool @@ -2826,10 +3169,26 @@ pub struct PermissionPromptRequestMcp { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionPromptRequestUrl { + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Human-readable description of why the URL is being accessed pub intention: String, /// Prompt kind discriminator pub kind: PermissionPromptRequestUrlKind, + /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass: Option, + /// Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_sandbox_bypass_reason: Option, /// Tool call ID that triggered this permission request #[serde(skip_serializing_if = "Option::is_none")] pub tool_call_id: Option, @@ -2844,6 +3203,16 @@ pub struct PermissionPromptRequestMemory { /// Whether this is a store or vote memory operation #[serde(skip_serializing_if = "Option::is_none")] pub action: Option, + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Source references for the stored fact (store only) #[serde(skip_serializing_if = "Option::is_none")] pub citations: Option, @@ -2872,6 +3241,16 @@ pub struct PermissionPromptRequestCustomTool { /// Arguments to pass to the custom tool #[serde(skip_serializing_if = "Option::is_none")] pub args: Option, + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Prompt kind discriminator pub kind: PermissionPromptRequestCustomToolKind, /// Tool call ID that triggered this permission request @@ -2889,6 +3268,16 @@ pub struct PermissionPromptRequestCustomTool { pub struct PermissionPromptRequestPath { /// Underlying permission kind that needs path approval pub access_kind: PermissionPromptRequestPathAccessKind, + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Prompt kind discriminator pub kind: PermissionPromptRequestPathKind, /// File paths that require explicit approval @@ -2902,6 +3291,16 @@ pub struct PermissionPromptRequestPath { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionPromptRequestHook { + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Optional message from the hook explaining why confirmation is needed #[serde(skip_serializing_if = "Option::is_none")] pub hook_message: Option, @@ -2921,6 +3320,16 @@ pub struct PermissionPromptRequestHook { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionPromptRequestExtensionManagement { + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Name of the extension being managed #[serde(skip_serializing_if = "Option::is_none")] pub extension_name: Option, @@ -2937,6 +3346,16 @@ pub struct PermissionPromptRequestExtensionManagement { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionPromptRequestExtensionPermissionAccess { + /// Auto-approval judge information for this request; present only when auto mode is enabled. + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(skip_serializing_if = "Option::is_none")] + pub auto_approval: Option, /// Capabilities the extension is requesting pub capabilities: Vec, /// Name of the extension requesting permission access @@ -2964,7 +3383,7 @@ pub struct PermissionRequestedData { pub resolved_by_hook: Option, } -/// Schema for the `PermissionApproved` type. +/// Permission response variant indicating the request was approved without persisting an approval rule. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionApproved { @@ -2972,7 +3391,7 @@ pub struct PermissionApproved { pub kind: PermissionApprovedKind, } -/// Schema for the `UserToolSessionApprovalCommands` type. +/// Session-scoped tool-approval rule for specific shell command identifiers. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalCommands { @@ -2982,7 +3401,7 @@ pub struct UserToolSessionApprovalCommands { pub kind: UserToolSessionApprovalCommandsKind, } -/// Schema for the `UserToolSessionApprovalRead` type. +/// Session-scoped tool-approval rule for read-only filesystem operations. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalRead { @@ -2990,7 +3409,7 @@ pub struct UserToolSessionApprovalRead { pub kind: UserToolSessionApprovalReadKind, } -/// Schema for the `UserToolSessionApprovalWrite` type. +/// Session-scoped tool-approval rule for filesystem write operations. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalWrite { @@ -2998,7 +3417,7 @@ pub struct UserToolSessionApprovalWrite { pub kind: UserToolSessionApprovalWriteKind, } -/// Schema for the `UserToolSessionApprovalMcp` type. +/// Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalMcp { @@ -3010,7 +3429,7 @@ pub struct UserToolSessionApprovalMcp { pub tool_name: Option, } -/// Schema for the `UserToolSessionApprovalMemory` type. +/// Session-scoped tool-approval rule for writes to long-term memory. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalMemory { @@ -3018,7 +3437,7 @@ pub struct UserToolSessionApprovalMemory { pub kind: UserToolSessionApprovalMemoryKind, } -/// Schema for the `UserToolSessionApprovalCustomTool` type. +/// Session-scoped tool-approval rule for a custom tool, keyed by tool name. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalCustomTool { @@ -3028,7 +3447,7 @@ pub struct UserToolSessionApprovalCustomTool { pub tool_name: String, } -/// Schema for the `UserToolSessionApprovalExtensionManagement` type. +/// Session-scoped tool-approval rule for extension-management operations, optionally narrowed by operation. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalExtensionManagement { @@ -3039,7 +3458,7 @@ pub struct UserToolSessionApprovalExtensionManagement { pub operation: Option, } -/// Schema for the `UserToolSessionApprovalExtensionPermissionAccess` type. +/// Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UserToolSessionApprovalExtensionPermissionAccess { @@ -3049,7 +3468,7 @@ pub struct UserToolSessionApprovalExtensionPermissionAccess { pub kind: UserToolSessionApprovalExtensionPermissionAccessKind, } -/// Schema for the `PermissionApprovedForSession` type. +/// Permission response variant that approves a request and remembers the provided approval for the rest of the session. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionApprovedForSession { @@ -3059,7 +3478,7 @@ pub struct PermissionApprovedForSession { pub kind: PermissionApprovedForSessionKind, } -/// Schema for the `PermissionApprovedForLocation` type. +/// Permission response variant that approves a request and persists the provided approval to a project location key. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionApprovedForLocation { @@ -3071,7 +3490,7 @@ pub struct PermissionApprovedForLocation { pub location_key: String, } -/// Schema for the `PermissionCancelled` type. +/// Permission response variant indicating the request was cancelled before use, with an optional reason. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionCancelled { @@ -3082,7 +3501,7 @@ pub struct PermissionCancelled { pub reason: Option, } -/// Schema for the `PermissionRule` type. +/// A permission approval or denial rule matched against a tool request, identified by a rule kind with an optional argument value. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionRule { @@ -3092,7 +3511,7 @@ pub struct PermissionRule { pub kind: String, } -/// Schema for the `PermissionDeniedByRules` type. +/// Permission response variant denied because matching approval rules explicitly blocked the request. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionDeniedByRules { @@ -3102,7 +3521,7 @@ pub struct PermissionDeniedByRules { pub rules: Vec, } -/// Schema for the `PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. +/// Permission response variant denied because no approval rule matched and user confirmation was unavailable. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser { @@ -3110,7 +3529,7 @@ pub struct PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser { pub kind: PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUserKind, } -/// Schema for the `PermissionDeniedInteractivelyByUser` type. +/// Permission response variant denied in an interactive user prompt, with optional feedback and force-reject flag. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionDeniedInteractivelyByUser { @@ -3124,7 +3543,7 @@ pub struct PermissionDeniedInteractivelyByUser { pub kind: PermissionDeniedInteractivelyByUserKind, } -/// Schema for the `PermissionDeniedByContentExclusionPolicy` type. +/// Permission response variant denying a path under content exclusion policy, with the path and message. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionDeniedByContentExclusionPolicy { @@ -3136,7 +3555,7 @@ pub struct PermissionDeniedByContentExclusionPolicy { pub path: String, } -/// Schema for the `PermissionDeniedByPermissionRequestHook` type. +/// Permission response variant denied by a permission-request hook, with optional message and interrupt flag. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionDeniedByPermissionRequestHook { @@ -3268,12 +3687,38 @@ pub struct SamplingCompletedData { pub request_id: RequestId, } +/// Single HTTP header entry as a name/value pair. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeaderEntry { + /// HTTP response header name as observed by the runtime. + pub name: String, + /// HTTP response header value as observed by the runtime. + pub value: String, +} + +/// Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpOauthHttpResponse { + /// Complete UTF-8 response body for host-specific challenge handling, including an empty string for an empty body. Omitted when the complete body is not valid UTF-8; body read failures fail the HTTP operation rather than exposing a partial response. + #[serde(skip_serializing_if = "Option::is_none")] + pub body: Option, + /// HTTP response headers as observed by the runtime. Order and casing are transport-dependent, and duplicate header names may appear multiple times. + pub headers: Vec, + /// HTTP status code returned with the auth challenge. + pub status_code: i32, +} + /// Static OAuth client configuration, if the server specifies one #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpOauthRequiredStaticClientConfig { /// OAuth client ID for the server pub client_id: String, + /// Optional OAuth client secret for confidential static clients, when the runtime can resolve one + #[serde(skip_serializing_if = "Option::is_none")] + pub client_secret: Option, /// Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). #[serde(skip_serializing_if = "Option::is_none")] pub grant_type: Option, @@ -3289,8 +3734,9 @@ pub struct McpOauthWWWAuthenticateParams { /// OAuth error from the WWW-Authenticate error parameter, if present #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, - /// Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter - pub resource_metadata_url: String, + /// Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter, if present + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_metadata_url: Option, /// Requested OAuth scopes from the WWW-Authenticate scope parameter, if present #[serde(skip_serializing_if = "Option::is_none")] pub scope: Option, @@ -3300,6 +3746,11 @@ pub struct McpOauthWWWAuthenticateParams { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpOauthRequiredData { + /// Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. Header order and casing are transport-dependent, and duplicate header names may appear multiple times. + #[serde(skip_serializing_if = "Option::is_none")] + pub http_response: Option, + /// Why the runtime is requesting host-provided OAuth credentials. + pub reason: McpOauthRequestReason, /// Unique identifier for this OAuth request; used to respond via session.mcp.oauth.handlePendingRequest pub request_id: RequestId, /// Raw OAuth protected-resource metadata document fetched for the MCP server, if available @@ -3327,6 +3778,30 @@ pub struct McpOauthCompletedData { pub request_id: RequestId, } +/// Session event "mcp.headers_refresh_required". Dynamic headers refresh request for a remote MCP server +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpHeadersRefreshRequiredData { + /// Why dynamic headers are being requested. + pub reason: McpHeadersRefreshRequiredReason, + /// Unique identifier for this headers refresh request; used to respond via session.mcp.headers.handlePendingHeadersRefreshRequest() + pub request_id: RequestId, + /// Display name of the remote MCP server requesting headers + pub server_name: String, + /// URL of the remote MCP server requesting headers + pub server_url: String, +} + +/// Session event "mcp.headers_refresh_completed". MCP headers refresh request completion notification +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpHeadersRefreshCompletedData { + /// How the pending MCP headers refresh request resolved. + pub outcome: McpHeadersRefreshCompletedOutcome, + /// Request ID of the resolved headers refresh request + pub request_id: RequestId, +} + /// Session event "session.custom_notification". Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -3435,7 +3910,101 @@ pub struct AutoModeSwitchCompletedData { pub response: AutoModeSwitchResponse, } -/// Schema for the `CommandsChangedCommand` type. +/// Session event "session_limits_exhausted.requested". Session limit exhaustion notification requiring user action. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLimitsExhaustedRequestedData { + /// Configured max AI Credits for the current accounting window. + pub max_ai_credits: f64, + /// Unique identifier for this request; used to respond via session.ui.handlePendingSessionLimitsExhausted(). + pub request_id: RequestId, + /// AI Credits already consumed in the current accounting window. + pub used_ai_credits: f64, +} + +/// The user's selected action for an exhausted session limit. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLimitsExhaustedResponse { + /// Action selected by the user. + pub action: SessionLimitsExhaustedResponseAction, + /// AI Credits to add to the current max when action is 'add'. + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_ai_credits: Option, + /// New absolute max AI Credits when action is 'set'. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_ai_credits: Option, +} + +/// Session event "session_limits_exhausted.completed". Session limit exhaustion prompt completion notification. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLimitsExhaustedCompletedData { + /// Request ID of the resolved request; clients should dismiss any UI for this request. + pub request_id: RequestId, + /// The user's selected session-limit action. + pub response: SessionLimitsExhaustedResponse, +} + +/// Session event "session.auto_mode_resolved". Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionAutoModeResolvedData { + /// Ordered candidate model list the router returned, when not a fallback + #[serde(skip_serializing_if = "Option::is_none")] + pub candidate_models: Option>, + /// Per-category classifier scores (0-1) behind the bucket: the granular HYDRA capability scores (reasoning, code_gen, debugging, tool_use), or the binary needs_reasoning/no_reasoning scores when HYDRA didn't run. Lets clients show a breakdown rather than just the bucket. + #[serde(skip_serializing_if = "Option::is_none")] + pub category_scores: Option>, + /// The concrete model the session will use after any intent refinement + pub chosen_model: String, + /// Classifier confidence for the predicted label, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub confidence: Option, + /// The predicted classifier label (e.g. `needs_reasoning`), when available + #[serde(skip_serializing_if = "Option::is_none")] + pub predicted_label: Option, + /// Coarse request-difficulty bucket, for explaining why a model was chosen ("picked X because this looks like high-reasoning work") + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_bucket: Option, +} + +/// Session event "session.managed_settings_resolved". Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionManagedSettingsResolvedData { + /// Whether enterprise policy disables bypass-permissions ("yolo") mode for this session. Deny-wins across layers, and forced on when `failClosed` is true. + pub bypass_permissions_disabled: bool, + /// Whether the device (MDM/plist/registry/file) managed-settings layer was present + pub device_managed: bool, + /// Whether managed policy could not be determined (e.g. a failed server fetch) and the session fell back to the fail-closed restriction. When true, restrictions such as disabling bypass-permissions are enforced even though `settings` may be absent. + pub fail_closed: bool, + /// The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. + pub managed_keys: Vec, + /// Whether the server (account/org) managed-settings layer was present + pub server_managed: bool, + /// The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. + #[serde(skip_serializing_if = "Option::is_none")] + pub settings: Option, + /// Which channel supplied the effective managed settings (the winning layer), or `none` when no policy is in force + pub source: ManagedSettingsResolvedSource, +} + +/// A single slash command available in the session, as listed by the `commands.changed` event. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CommandsChangedCommand { @@ -3514,7 +4083,7 @@ pub struct ExitPlanModeCompletedData { pub selected_action: Option, } -/// Session event "session.tools_updated". +/// Session event "session.tools_updated". Payload of `session.tools_updated` identifying the model whose resolved tools were updated. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionToolsUpdatedData { @@ -3522,12 +4091,12 @@ pub struct SessionToolsUpdatedData { pub model: String, } -/// Session event "session.background_tasks_changed". +/// Session event "session.background_tasks_changed". Empty payload for `session.background_tasks_changed`, indicating background task state changed. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionBackgroundTasksChangedData {} -/// Schema for the `SkillsLoadedSkill` type. +/// A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SkillsLoadedSkill { @@ -3549,7 +4118,7 @@ pub struct SkillsLoadedSkill { pub user_invocable: bool, } -/// Session event "session.skills_loaded". +/// Session event "session.skills_loaded". Payload of `session.skills_loaded` listing resolved skill metadata. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionSkillsLoadedData { @@ -3557,7 +4126,7 @@ pub struct SessionSkillsLoadedData { pub skills: Vec, } -/// Schema for the `CustomAgentsUpdatedAgent` type. +/// A single loaded custom agent in `session.custom_agents_updated`, with identity, source, tools, invocability, and model override. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CustomAgentsUpdatedAgent { @@ -3580,7 +4149,7 @@ pub struct CustomAgentsUpdatedAgent { pub user_invocable: bool, } -/// Session event "session.custom_agents_updated". +/// Session event "session.custom_agents_updated". Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionCustomAgentsUpdatedData { @@ -3592,7 +4161,7 @@ pub struct SessionCustomAgentsUpdatedData { pub warnings: Vec, } -/// Schema for the `McpServersLoadedServer` type. +/// A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpServersLoadedServer { @@ -3617,7 +4186,7 @@ pub struct McpServersLoadedServer { pub transport: Option, } -/// Session event "session.mcp_servers_loaded". +/// Session event "session.mcp_servers_loaded". Payload of `session.mcp_servers_loaded` listing MCP server status summaries. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionMcpServersLoadedData { @@ -3625,7 +4194,7 @@ pub struct SessionMcpServersLoadedData { pub servers: Vec, } -/// Session event "session.mcp_server_status_changed". +/// Session event "session.mcp_server_status_changed". Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionMcpServerStatusChangedData { @@ -3638,7 +4207,31 @@ pub struct SessionMcpServerStatusChangedData { pub status: McpServerStatus, } -/// Schema for the `ExtensionsLoadedExtension` type. +/// Session event "mcp.tools.list_changed". Payload identifying the MCP server associated with a list change. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpToolsListChangedData { + /// Name of the MCP server whose list changed + pub server_name: String, +} + +/// Session event "mcp.resources.list_changed". Payload identifying the MCP server associated with a list change. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpResourcesListChangedData { + /// Name of the MCP server whose list changed + pub server_name: String, +} + +/// Session event "mcp.prompts.list_changed". Payload identifying the MCP server associated with a list change. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct McpPromptsListChangedData { + /// Name of the MCP server whose list changed + pub server_name: String, +} + +/// A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ExtensionsLoadedExtension { @@ -3652,7 +4245,7 @@ pub struct ExtensionsLoadedExtension { pub status: ExtensionsLoadedExtensionStatus, } -/// Session event "session.extensions_loaded". +/// Session event "session.extensions_loaded". Payload of `session.extensions_loaded` listing discovered extensions and their statuses. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionExtensionsLoadedData { @@ -3660,7 +4253,7 @@ pub struct SessionExtensionsLoadedData { pub extensions: Vec, } -/// Session event "session.canvas.opened". +/// Session event "session.canvas.opened". Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. /// ///
/// @@ -3678,6 +4271,9 @@ pub struct SessionCanvasOpenedData { /// Owning extension display name, when available #[serde(skip_serializing_if = "Option::is_none")] pub extension_name: Option, + /// Host-local PNG path for the canvas icon, when supplied + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, /// Input supplied when the instance was opened #[serde(skip_serializing_if = "Option::is_none")] pub input: Option, @@ -3694,7 +4290,7 @@ pub struct SessionCanvasOpenedData { pub url: Option, } -/// Schema for the `CanvasRegistryChangedCanvasAction` type. +/// A single action within a canvas declaration, with its name, optional description, and optional input schema. /// ///
/// @@ -3715,7 +4311,7 @@ pub struct CanvasRegistryChangedCanvasAction { pub name: String, } -/// Schema for the `CanvasRegistryChangedCanvas` type. +/// A single canvas declaration in `session.canvas.registry_changed`, including provider IDs, display metadata, input schema, and actions. /// ///
/// @@ -3740,12 +4336,15 @@ pub struct CanvasRegistryChangedCanvas { /// Owning extension display name, when available #[serde(skip_serializing_if = "Option::is_none")] pub extension_name: Option, + /// Host-local PNG path for the canvas icon, when supplied + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, /// JSON Schema for canvas open input #[serde(skip_serializing_if = "Option::is_none")] pub input_schema: Option, } -/// Session event "session.canvas.registry_changed". +/// Session event "session.canvas.registry_changed". Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. /// ///
/// @@ -3760,7 +4359,7 @@ pub struct SessionCanvasRegistryChangedData { pub canvases: Vec, } -/// Session event "session.canvas.closed". +/// Session event "session.canvas.closed". Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. /// ///
/// @@ -3842,7 +4441,7 @@ pub struct SessionCanvasRemovedData { pub instance_id: String, } -/// Session event "session.extensions.attachments_pushed". +/// Session event "session.extensions.attachments_pushed". Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionExtensionsAttachmentsPushedData { @@ -3858,7 +4457,7 @@ pub struct McpAppToolCallCompleteError { pub message: String, } -/// Schema for the `McpAppToolCallCompleteToolMetaUI` type. +/// MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpAppToolCallCompleteToolMetaUI { @@ -3874,7 +4473,7 @@ pub struct McpAppToolCallCompleteToolMetaUI { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpAppToolCallCompleteToolMeta { - /// Schema for the `McpAppToolCallCompleteToolMetaUI` type. + /// MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. #[serde(skip_serializing_if = "Option::is_none")] pub ui: Option, } @@ -3953,6 +4552,24 @@ pub enum ReasoningSummary { Unknown, } +/// Output verbosity level used for supported model calls (e.g. "low", "medium", "high") +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Verbosity { + /// A terse response was requested. + #[serde(rename = "low")] + Low, + /// A medium amount of response detail was requested. + #[serde(rename = "medium")] + Medium, + /// A more detailed response was requested. + #[serde(rename = "high")] + High, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// The type of operation performed on the autopilot objective state file #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AutopilotObjectiveChangedOperation { @@ -4010,6 +4627,31 @@ pub enum SessionMode { Unknown, } +/// Allow-all mode for the session. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PermissionAllowAllMode { + /// Permission requests follow the normal approval flow. + #[serde(rename = "off")] + Off, + /// Tool, path, and URL permission requests are automatically approved. + #[serde(rename = "on")] + On, + /// Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + #[serde(rename = "auto")] + Auto, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// The type of operation performed on the plan file #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum PlanChangedOperation { @@ -4094,6 +4736,39 @@ pub enum UserMessageAgentMode { Unknown, } +/// How this user message was delivered to the agentic loop, relative to whether the loop was already running. This is the timing axis only; the message's origin (human vs. system/command/schedule/skill/etc.) is carried separately by `source`. A system-injected message has a delivery too — e.g. a background-task notification waking an idle agent is `idle`, the same mechanism as a human starting a fresh turn. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum UserMessageDelivery { + /// Delivered while the loop was idle; starts its own run immediately (a human's fresh turn, or a system notification waking an idle agent). + #[serde(rename = "idle")] + Idle, + /// Injected into the current in-flight run while the agent was busy (immediate mode). + #[serde(rename = "steering")] + Steering, + /// Enqueued while the agent was busy; processed as its own run afterward. + #[serde(rename = "queued")] + Queued, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AssistantMessageToolRequestType { + /// Standard function-style tool call. + #[serde(rename = "function")] + Function, + /// Custom grammar-based tool call. + #[serde(rename = "custom")] + Custom, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// The system that produced a citation. /// ///
@@ -4119,21 +4794,6 @@ pub enum CitationProvider { Unknown, } -/// Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum AssistantMessageToolRequestType { - /// Standard function-style tool call. - #[serde(rename = "function")] - Function, - /// Custom grammar-based tool call. - #[serde(rename = "custom")] - Custom, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - /// API endpoint used for this model call, matching CAPI supported_endpoints vocabulary #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AssistantUsageApiEndpoint { @@ -4237,6 +4897,14 @@ pub enum ToolExecutionCompleteContentTerminalType { Terminal, } +/// Content block type discriminator +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ToolExecutionCompleteContentShellExitType { + #[serde(rename = "shell_exit")] + #[default] + ShellExit, +} + /// Content block type discriminator #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ToolExecutionCompleteContentImageType { @@ -4298,6 +4966,7 @@ pub enum ToolExecutionCompleteContentResourceType { pub enum ToolExecutionCompleteContent { Text(ToolExecutionCompleteContentText), Terminal(ToolExecutionCompleteContentTerminal), + ShellExit(ToolExecutionCompleteContentShellExit), Image(ToolExecutionCompleteContentImage), Audio(ToolExecutionCompleteContentAudio), ResourceLink(ToolExecutionCompleteContentResourceLink), @@ -4493,6 +5162,34 @@ pub enum PermissionRequest { ExtensionPermissionAccess(PermissionRequestExtensionPermissionAccess), } +/// Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AutoApprovalRecommendation { + /// The judge evaluated the request and recommends automatically approving it. + #[serde(rename = "approve")] + Approve, + /// The judge evaluated the request and does not recommend auto-approving it; explicit approval is required. Whether that means prompting, denying, or something else is the consumer's decision. + #[serde(rename = "requireApproval")] + RequireApproval, + /// Auto mode is enabled, but this request category is never auto-approvable (for example, sandbox-bypass requests), so the judge was not consulted. + #[serde(rename = "excluded")] + Excluded, + /// The judge was consulted but did not return a usable recommendation, so the request requires explicit approval. + #[serde(rename = "error")] + Error, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Prompt kind discriminator #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum PermissionPromptRequestCommandsKind { @@ -4824,6 +5521,27 @@ pub enum ElicitationCompletedAction { Unknown, } +/// Reason the runtime is requesting host-provided MCP OAuth credentials +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum McpOauthRequestReason { + /// Initial credentials are required before connecting to the MCP server. + #[serde(rename = "initial")] + Initial, + /// The current host-provided credential was rejected and a replacement is requested. + #[serde(rename = "refresh")] + Refresh, + /// The server requires a new host authorization flow before continuing. + #[serde(rename = "reauth")] + Reauth, + /// The server requires a credential with additional scope or audience. + #[serde(rename = "upscope")] + Upscope, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum McpOauthRequiredStaticClientConfigGrantType { @@ -4847,6 +5565,42 @@ pub enum McpOauthCompletionOutcome { Unknown, } +/// Why dynamic headers are being requested. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum McpHeadersRefreshRequiredReason { + /// The transport is making its first dynamic header request for this server. + #[serde(rename = "startup")] + Startup, + /// The previously cached dynamic headers expired. + #[serde(rename = "ttl-expired")] + TtlExpired, + /// The server returned 401 and stale dynamic headers were invalidated. + #[serde(rename = "auth-failed")] + AuthFailed, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// How the pending MCP headers refresh request resolved. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum McpHeadersRefreshCompletedOutcome { + /// The host supplied dynamic headers. + #[serde(rename = "headers")] + Headers, + /// The host responded with no dynamic headers. + #[serde(rename = "none")] + None, + /// No response arrived within the bounded window. + #[serde(rename = "timeout")] + Timeout, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// The user's auto-mode-switch choice #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AutoModeSwitchResponse { @@ -4865,6 +5619,63 @@ pub enum AutoModeSwitchResponse { Unknown, } +/// User action selected for an exhausted session limit. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionLimitsExhaustedResponseAction { + /// Increase the current max by an exact AI Credits amount. + #[serde(rename = "add")] + Add, + /// Set a new absolute max AI Credits value. + #[serde(rename = "set")] + Set, + /// Remove the current session limit. + #[serde(rename = "unset")] + Unset, + /// Leave the limit unchanged and cancel the blocked model request. + #[serde(rename = "cancel")] + Cancel, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Coarse request-difficulty bucket for UX explainability +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AutoModeResolvedReasoningBucket { + /// The request looks low-reasoning; a lighter model is appropriate. + #[serde(rename = "low")] + Low, + /// The request needs a moderate amount of reasoning. + #[serde(rename = "medium")] + Medium, + /// The request looks high-reasoning; a stronger model is appropriate. + #[serde(rename = "high")] + High, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Which channel supplied the effective enterprise managed settings (highest-authority present layer wins wholesale) +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ManagedSettingsResolvedSource { + /// Account/org policy self-fetched from the GitHub managed-settings endpoint (higher authority). + #[serde(rename = "server")] + Server, + /// Device-level MDM policy discovered from plist/registry/file (lower authority). + #[serde(rename = "device")] + Device, + /// No managed policy is in force (no layer contributed). + #[serde(rename = "none")] + None, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Exit plan mode action #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum ExitPlanModeAction { diff --git a/rust/src/github_telemetry.rs b/rust/src/github_telemetry.rs new file mode 100644 index 0000000000..9ef5c6e2e8 --- /dev/null +++ b/rust/src/github_telemetry.rs @@ -0,0 +1,28 @@ +//! GitHub telemetry forwarding callback surface. +//! +//! The runtime forwards per-session GitHub (hydro) telemetry to opted-in host +//! connections via the `gitHubTelemetry.event` JSON-RPC notification. The +//! payload types (`GitHubTelemetryNotification`, `GitHubTelemetryEvent`, +//! `GitHubTelemetryClientInfo`) are generated from the protocol schema and +//! re-exported here so consumers can register a callback against them via +//! [`ClientOptions::on_github_telemetry`](crate::ClientOptions::on_github_telemetry). +//! +//! Experimental: this surface is part of the GitHub telemetry forwarding +//! feature and may change or be removed without notice. + +use std::sync::Arc; + +#[doc(hidden)] +pub use crate::generated::api_types::{ + GitHubTelemetryClientInfo, GitHubTelemetryEvent, GitHubTelemetryNotification, +}; + +/// Callback invoked for each `gitHubTelemetry.event` notification forwarded by +/// the runtime to a connection that opted into telemetry forwarding. +/// +/// Set via +/// [`ClientOptions::on_github_telemetry`](crate::ClientOptions::on_github_telemetry). +/// Registering a callback auto-enables telemetry forwarding on every session +/// created or resumed by the client. +#[doc(hidden)] +pub type GitHubTelemetryCallback = Arc; diff --git a/rust/src/handler.rs b/rust/src/handler.rs index dadd1706ff..3287a4f093 100644 --- a/rust/src/handler.rs +++ b/rust/src/handler.rs @@ -19,8 +19,13 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; use crate::generated::api_types::{ - PermissionDecision, PermissionDecisionApproveOnce, PermissionDecisionReject, - PermissionDecisionUserNotAvailable, + McpOauthPendingRequestResponse, McpOauthPendingRequestResponseCancelled, + McpOauthPendingRequestResponseCancelledKind, McpOauthPendingRequestResponseToken, + McpOauthPendingRequestResponseTokenKind, PermissionDecision, PermissionDecisionApproveOnce, + PermissionDecisionReject, PermissionDecisionUserNotAvailable, +}; +use crate::session_events::{ + McpOauthRequestReason, McpOauthRequiredStaticClientConfig, McpOauthWWWAuthenticateParams, }; use crate::types::{ ElicitationRequest, ElicitationResult, ExitPlanModeData, PermissionRequestData, RequestId, @@ -159,6 +164,75 @@ pub trait ElicitationHandler: Send + Sync + 'static { ) -> ElicitationResult; } +/// MCP OAuth request that the SDK host can satisfy with a host-acquired token. +#[derive(Debug, Clone)] +pub struct McpAuthRequest { + /// Identifier for the pending MCP OAuth request. + pub request_id: RequestId, + /// Display name of the MCP server that requires OAuth. + pub server_name: String, + /// URL of the MCP server that requires OAuth. + pub server_url: String, + /// Why the runtime is requesting host-provided OAuth credentials. + pub reason: McpOauthRequestReason, + /// Parsed WWW-Authenticate parameters from the MCP server, if available. + pub www_authenticate_params: Option, + /// Raw RFC 9728 protected-resource metadata JSON fetched by the runtime, if available. + pub resource_metadata: Option, + /// Static OAuth client configuration, if the server specifies one. + pub static_client_config: Option, +} + +/// Result returned by an MCP auth request handler. +#[derive(Debug, Clone)] +pub enum McpAuthResult { + /// Supplies host-acquired OAuth token data. + Token { + /// Access token acquired by the SDK host. + access_token: String, + /// OAuth token type. Defaults to Bearer when omitted. + token_type: Option, + /// Token lifetime in seconds, if known. + expires_in: Option, + }, + /// Declines or cancels the pending OAuth request. + Cancelled, +} + +impl McpAuthResult { + pub(crate) fn into_wire(self) -> McpOauthPendingRequestResponse { + match self { + Self::Token { + access_token, + token_type, + expires_in, + } => McpOauthPendingRequestResponse::Token(McpOauthPendingRequestResponseToken { + access_token, + token_type, + expires_in, + kind: McpOauthPendingRequestResponseTokenKind::Token, + }), + Self::Cancelled => { + McpOauthPendingRequestResponse::Cancelled(McpOauthPendingRequestResponseCancelled { + kind: McpOauthPendingRequestResponseCancelledKind::Cancelled, + }) + } + } + } +} + +/// Handler for MCP server OAuth requests. +#[async_trait] +pub trait McpAuthHandler: Send + Sync + 'static { + /// Resolve an MCP OAuth request with host token data or cancellation. + async fn handle( + &self, + session_id: SessionId, + request_id: RequestId, + request: McpAuthRequest, + ) -> McpAuthResult; +} + /// Handler for `user_input.requested` events from the `ask_user` tool. /// /// When unset, `requestUserInput: false` goes on the wire and the @@ -266,4 +340,23 @@ mod tests { PermissionResult::Decision(PermissionDecision::Reject(_)) )); } + + #[test] + fn mcp_auth_result_token_converts_to_wire_response() { + let wire = McpAuthResult::Token { + access_token: "host-token".to_string(), + token_type: Some("Bearer".to_string()), + expires_in: Some(3600), + } + .into_wire(); + + match wire { + McpOauthPendingRequestResponse::Token(token) => { + assert_eq!(token.access_token, "host-token"); + assert_eq!(token.token_type.as_deref(), Some("Bearer")); + assert_eq!(token.expires_in, Some(3600)); + } + McpOauthPendingRequestResponse::Cancelled(_) => panic!("expected token response"), + } + } } diff --git a/rust/src/hooks.rs b/rust/src/hooks.rs index ec8cdfa3a3..0c3d64076f 100644 --- a/rust/src/hooks.rs +++ b/rust/src/hooks.rs @@ -27,8 +27,8 @@ pub struct HookContext { pub struct PreToolUseInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, @@ -65,8 +65,8 @@ pub struct PreToolUseOutput { pub struct PreMcpToolCallInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, @@ -104,8 +104,8 @@ pub struct PreMcpToolCallOutput { pub struct PostToolUseInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, @@ -144,8 +144,8 @@ pub struct PostToolUseOutput { pub struct PostToolUseFailureInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, @@ -175,8 +175,8 @@ pub struct PostToolUseFailureOutput { pub struct UserPromptSubmittedInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, @@ -205,8 +205,8 @@ pub struct UserPromptSubmittedOutput { pub struct SessionStartInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, @@ -235,8 +235,8 @@ pub struct SessionStartOutput { pub struct SessionEndInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, @@ -271,8 +271,8 @@ pub struct SessionEndOutput { pub struct ErrorOccurredInput { /// The runtime session ID of the session that triggered the hook. pub session_id: String, - /// Unix timestamp (ms). - pub timestamp: i64, + /// Unix timestamp in ms (the runtime serializes this as a JSON float). + pub timestamp: f64, /// Working directory. #[serde(rename = "cwd")] pub working_directory: PathBuf, diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 22fdc53d78..65d9dab215 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -10,11 +10,18 @@ mod canvas_dispatch; #[cfg(feature = "bundled-cli")] pub(crate) mod embeddedcli; mod errors; +/// In-process FFI transport hosting the runtime cdylib (`Transport::InProcess`). +#[cfg(feature = "bundled-in-process")] +pub(crate) mod ffi; pub use errors::*; /// Connection-level Copilot request handler — intercept and replace the /// model-layer HTTP and WebSocket traffic the runtime issues for both CAPI and /// BYOK sessions. pub mod copilot_request_handler; +/// GitHub telemetry forwarding callback surface (experimental). Public but +/// `#[doc(hidden)]` — re-exports the generated telemetry payload types. +#[doc(hidden)] +pub mod github_telemetry; /// Event handler traits for session lifecycle. pub mod handler; /// Lifecycle hook callbacks (pre/post tool use, prompt submission, session start/end). @@ -69,7 +76,11 @@ use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use async_trait::async_trait; -// JSON-RPC wire types are internal transport details (like Go SDK's internal/jsonrpc2/). +/// Re-export of [`indexmap::IndexMap`], used for order-preserving maps in the +/// public API (e.g. [`Tool::parameters`](types::Tool::parameters) and +/// `SessionConfig::mcp_servers`) so serialized key order stays deterministic. +pub use indexmap::IndexMap; +// JSON-RPC wire types are internal transport details. // External callers interact via Client/Session methods, not raw RPC. pub(crate) use jsonrpc::{ JsonRpcClient, JsonRpcError, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, error_codes, @@ -105,9 +116,25 @@ const RUNTIME_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); #[derive(Debug, Default)] #[non_exhaustive] pub enum Transport { - /// Communicate over stdin/stdout pipes (default). + /// Resolve the transport from `COPILOT_SDK_DEFAULT_CONNECTION`, falling + /// back to [`Transport::Stdio`] when the variable is unset. #[default] + Default, + /// Communicate over stdin/stdout pipes (default). Stdio, + /// Host the runtime in-process over FFI (no child process). + /// + /// Loads the native runtime library and speaks JSON-RPC over its C ABI. + /// This is **experimental**. Per-client [`ClientOptions::program`], + /// [`ClientOptions::extra_args`], [`ClientOptions::working_directory`], + /// [`ClientOptions::env`]/[`ClientOptions::env_remove`], + /// and [`ClientOptions::telemetry`] are not supported because native + /// runtime code shares the host process. Typed runtime options such as + /// authentication, log level, and [`ClientOptions::base_directory`] remain + /// supported. + /// + /// Requires the `bundled-in-process` Cargo feature. + InProcess, /// Spawn the CLI with `--port` and connect via TCP. Tcp { /// Port to listen on (0 for OS-assigned). @@ -199,17 +226,19 @@ pub fn install_bundled_cli() -> Option { /// This skips auto-resolution entirely. #[non_exhaustive] pub struct ClientOptions { - /// How to locate the CLI binary. + /// How to locate the child-process runtime. pub program: CliProgram, /// Arguments prepended before `--server` (e.g. the script path for node). pub prefix_args: Vec, /// Working directory for the CLI process. + /// + /// Setting this option is not supported with [`Transport::InProcess`]. pub working_directory: PathBuf, /// Environment variables set on the child process. pub env: Vec<(OsString, OsString)>, /// Environment variable names to remove from the child process. pub env_remove: Vec, - /// Extra CLI flags appended after the transport-specific arguments. + /// Extra flags for child-process transports. pub extra_args: Vec, /// Transport mode used to communicate with the CLI server. pub transport: Transport, @@ -257,6 +286,15 @@ pub struct ClientOptions { /// [`CopilotRequestHandler`] /// instead of issuing the calls itself. pub request_handler: Option>, + /// Connection-level GitHub telemetry forwarding callback (experimental). + /// + /// When set, every session created or resumed on this client opts into + /// telemetry forwarding (`enableGitHubTelemetryForwarding`) and the + /// callback is invoked for each `gitHubTelemetry.event` notification the + /// runtime forwards. `#[doc(hidden)]`, consistent with the experimental + /// telemetry payload types. + #[doc(hidden)] + pub on_github_telemetry: Option, /// Optional [`TraceContextProvider`] used to inject W3C Trace Context /// headers (`traceparent` / `tracestate`) on outbound `session.create`, /// `session.resume`, and `session.send` requests. @@ -336,6 +374,10 @@ impl std::fmt::Debug for ClientOptions { "request_handler", &self.request_handler.as_ref().map(|_| ""), ) + .field( + "on_github_telemetry", + &self.on_github_telemetry.as_ref().map(|_| ""), + ) .field( "on_get_trace_context", &self.on_get_trace_context.as_ref().map(|_| ""), @@ -572,7 +614,7 @@ impl Default for ClientOptions { Self { program: CliProgram::Resolve, prefix_args: Vec::new(), - working_directory: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), + working_directory: PathBuf::new(), env: Vec::new(), env_remove: Vec::new(), extra_args: Vec::new(), @@ -584,6 +626,7 @@ impl Default for ClientOptions { on_list_models: None, session_fs: None, request_handler: None, + on_github_telemetry: None, on_get_trace_context: None, telemetry: None, base_directory: None, @@ -614,7 +657,7 @@ impl ClientOptions { Self::default() } - /// How to locate the CLI binary. See [`CliProgram`]. + /// How to locate the child-process runtime. See [`CliProgram`]. pub fn with_program(mut self, program: impl Into) -> Self { self.program = program.into(); self @@ -728,6 +771,20 @@ impl ClientOptions { self } + /// Register a connection-level GitHub telemetry forwarding callback + /// (internal/experimental). Registering a callback auto-enables telemetry + /// forwarding on every session created or resumed on this client; the + /// callback fires for each forwarded `gitHubTelemetry.event` notification. + /// The callback is wrapped in `Arc` internally. + #[doc(hidden)] + pub fn with_on_github_telemetry(mut self, callback: F) -> Self + where + F: Fn(crate::github_telemetry::GitHubTelemetryNotification) + Send + Sync + 'static, + { + self.on_github_telemetry = Some(Arc::new(callback)); + self + } + /// Set the [`TraceContextProvider`] used to inject W3C Trace Context /// headers on outbound `session.create` / `session.resume` / /// `session.send` requests. The provider is wrapped in `Arc` internally. @@ -818,6 +875,85 @@ fn generate_connection_token() -> String { hex } +/// Environment variable that overrides the transport used when the caller +/// leaves [`ClientOptions::transport`] at [`Transport::Default`]. +/// Accepts `"inprocess"` or `"stdio"` (case-insensitive); unset preserves +/// stdio. Any other value is an error. +const DEFAULT_CONNECTION_ENV_VAR: &str = "COPILOT_SDK_DEFAULT_CONNECTION"; + +/// Resolve a transport override from [`DEFAULT_CONNECTION_ENV_VAR`]. +fn resolve_default_transport(options: &ClientOptions) -> Result { + let configured = options + .env + .iter() + .find(|(key, _)| { + key.to_string_lossy() + .eq_ignore_ascii_case(DEFAULT_CONNECTION_ENV_VAR) + }) + .map(|(_, value)| value.to_string_lossy().into_owned()); + let process = std::env::var(DEFAULT_CONNECTION_ENV_VAR).ok(); + resolve_default_transport_value(configured.as_deref().or(process.as_deref())) +} + +fn resolve_default_transport_value(value: Option<&str>) -> Result { + match value { + None => Ok(Transport::Stdio), + Some(v) if v.is_empty() || v.eq_ignore_ascii_case("stdio") => Ok(Transport::Stdio), + Some(v) if v.eq_ignore_ascii_case("inprocess") => Ok(Transport::InProcess), + Some(v) => Err(Error::with_message( + ErrorKind::InvalidConfig, + format!( + "invalid {DEFAULT_CONNECTION_ENV_VAR} value '{v}'. \ + Expected 'inprocess', 'stdio', or unset." + ), + )), + } +} + +#[cfg(any(feature = "bundled-in-process", test))] +fn validate_inprocess_options(options: &ClientOptions) -> Result<()> { + if !matches!(&options.program, CliProgram::Resolve) { + return Err(Error::with_message( + ErrorKind::InvalidConfig, + "ClientOptions::program is not supported with Transport::InProcess; \ + set COPILOT_CLI_PATH only when using an externally provisioned runtime package", + )); + } + if !options.extra_args.is_empty() { + return Err(Error::with_message( + ErrorKind::InvalidConfig, + "ClientOptions::extra_args is not supported with Transport::InProcess; \ + use typed client options instead", + )); + } + + let unsupported = if !options.working_directory.as_os_str().is_empty() { + Some("working_directory") + } else if !options.env.is_empty() { + Some("env") + } else if !options.env_remove.is_empty() { + Some("env_remove") + } else if options.telemetry.is_some() { + Some("telemetry") + } else if !options.prefix_args.is_empty() { + Some("prefix_args") + } else { + None + }; + + if let Some(option) = unsupported { + return Err(Error::with_message( + ErrorKind::InvalidConfig, + format!( + "ClientOptions::{option} is not supported with Transport::InProcess; \ + configure process-global settings on the host process instead" + ), + )); + } + + Ok(()) +} + /// Connection to a GitHub Copilot CLI server (stdio, TCP, or external). /// /// Cheaply cloneable — cloning shares the underlying connection. @@ -838,6 +974,10 @@ impl std::fmt::Debug for Client { struct ClientInner { child: parking_lot::Mutex>, + #[cfg(feature = "bundled-in-process")] + /// In-process FFI runtime host, set only for [`Transport::InProcess`]. + /// Closing it tears down the native runtime connection. + ffi_host: parking_lot::Mutex>>, rpc: JsonRpcClient, cwd: PathBuf, request_rx: parking_lot::Mutex>>, @@ -853,6 +993,11 @@ struct ClientInner { /// Inbound `llmInference.*` dispatcher, installed when /// [`ClientOptions::request_handler`] is set. llm_inference: OnceLock>, + /// Connection-level GitHub telemetry forwarding callback, set from + /// [`ClientOptions::on_github_telemetry`]. Drives the + /// `enableGitHubTelemetryForwarding` wire flag and the + /// `gitHubTelemetry.event` notification dispatch. + on_github_telemetry: Option, on_get_trace_context: Option>, /// Token sent in the `connect` handshake. Auto-generated when the /// SDK spawns its own CLI in TCP mode and no explicit token is set; @@ -879,6 +1024,21 @@ impl Client { /// backend. pub async fn start(options: ClientOptions) -> Result { let start_time = Instant::now(); + let mut options = options; + if matches!(options.transport, Transport::Default) { + options.transport = resolve_default_transport(&options)?; + } + if matches!(options.transport, Transport::InProcess) { + #[cfg(not(feature = "bundled-in-process"))] + { + return Err(Error::with_message( + ErrorKind::InvalidConfig, + "Transport::InProcess requires the `bundled-in-process` Cargo feature", + )); + } + #[cfg(feature = "bundled-in-process")] + validate_inprocess_options(&options)?; + } if options.mode == ClientMode::Empty && options.base_directory.is_none() && options.session_fs.is_none() @@ -933,9 +1093,9 @@ impl Client { // to the server. For Tcp, the SDK auto-generates one when the // caller leaves it unset so the loopback listener is safe by // default. - let mut options = options; let effective_connection_token: Option = match &mut options.transport { - Transport::Stdio => None, + Transport::Default => unreachable!("default transport resolved above"), + Transport::Stdio | Transport::InProcess => None, Transport::Tcp { connection_token, .. } => Some( @@ -979,8 +1139,17 @@ impl Client { resolved } }; + let working_directory = { + let cwd = options.working_directory.clone(); + if cwd.as_os_str().is_empty() { + std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")) + } else { + cwd + } + }; let client = match options.transport { + Transport::Default => unreachable!("default transport resolved above"), Transport::External { ref host, port, @@ -1000,11 +1169,12 @@ impl Client { reader, writer, None, - options.working_directory, + working_directory, options.on_list_models, session_fs_config.is_some(), session_fs_sqlite_declared, options.on_get_trace_context, + options.on_github_telemetry, effective_connection_token.clone(), options.mode, )? @@ -1013,7 +1183,8 @@ impl Client { port, connection_token: _, } => { - let (mut child, actual_port) = Self::spawn_tcp(&program, &options, port).await?; + let (mut child, actual_port) = + Self::spawn_tcp(&program, &options, &working_directory, port).await?; let connect_start = Instant::now(); let stream = TcpStream::connect(("127.0.0.1", actual_port)).await?; debug!( @@ -1027,17 +1198,18 @@ impl Client { reader, writer, Some(child), - options.working_directory, + working_directory, options.on_list_models, session_fs_config.is_some(), session_fs_sqlite_declared, options.on_get_trace_context, + options.on_github_telemetry, effective_connection_token.clone(), options.mode, )? } Transport::Stdio => { - let mut child = Self::spawn_stdio(&program, &options)?; + let mut child = Self::spawn_stdio(&program, &options, &working_directory)?; let stdin = child.stdin.take().expect("stdin is piped"); let stdout = child.stdout.take().expect("stdout is piped"); Self::drain_stderr(&mut child); @@ -1045,17 +1217,79 @@ impl Client { stdout, stdin, Some(child), - options.working_directory, + working_directory, options.on_list_models, session_fs_config.is_some(), session_fs_sqlite_declared, options.on_get_trace_context, + options.on_github_telemetry, effective_connection_token.clone(), options.mode, )? } + Transport::InProcess => { + #[cfg(feature = "bundled-in-process")] + { + info!(runtime_path = %program.display(), "hosting copilot runtime in-process (FFI)"); + let mut environment = Vec::new(); + if let Some(base_directory) = &options.base_directory { + let value = base_directory.to_str().ok_or_else(|| { + Error::with_message( + ErrorKind::InvalidConfig, + "base_directory must be valid UTF-8 for Transport::InProcess", + ) + })?; + environment.push(("COPILOT_HOME".to_string(), value.to_string())); + } + if options.mode == ClientMode::Empty { + environment.push(("COPILOT_DISABLE_KEYTAR".to_string(), "1".to_string())); + } + if let Some(github_token) = &options.github_token { + environment + .push(("COPILOT_SDK_AUTH_TOKEN".to_string(), github_token.clone())); + } + let mut args = Vec::new(); + args.extend( + Self::log_level_args(&options) + .into_iter() + .map(str::to_string), + ); + args.extend(Self::session_idle_timeout_args(&options)); + args.extend(Self::remote_args(&options)); + if options.github_token.is_some() { + args.extend([ + "--auth-token-env".to_string(), + "COPILOT_SDK_AUTH_TOKEN".to_string(), + ]); + } + let use_logged_in_user = options + .use_logged_in_user + .unwrap_or(options.github_token.is_none()); + if !use_logged_in_user { + args.push("--no-auto-login".to_string()); + } + let host = crate::ffi::FfiHost::create(&program, environment, args)?; + let (reader, writer, shared) = host.start().await?; + let client = Self::from_transport( + reader, + writer, + None, + working_directory, + options.on_list_models, + session_fs_config.is_some(), + session_fs_sqlite_declared, + options.on_get_trace_context, + options.on_github_telemetry, + effective_connection_token.clone(), + options.mode, + )?; + *client.inner.ffi_host.lock() = Some(shared); + client + } + #[cfg(not(feature = "bundled-in-process"))] + unreachable!("in-process feature validation returned above") + } }; - debug!( elapsed_ms = start_time.elapsed().as_millis(), "Client::start transport setup complete" @@ -1097,6 +1331,7 @@ impl Client { &client.inner.notification_tx, &client.inner.request_rx, Some(dispatcher.clone()), + client.inner.on_github_telemetry.clone(), ); client.rpc().llm_inference().set_provider().await?; debug!( @@ -1129,6 +1364,7 @@ impl Client { false, None, None, + None, ClientMode::default(), ) } @@ -1157,6 +1393,7 @@ impl Client { false, Some(provider), None, + None, ClientMode::default(), ) } @@ -1180,11 +1417,37 @@ impl Client { false, false, None, + None, token, ClientMode::default(), ) } + /// Construct a [`Client`] from raw streams with a preset GitHub telemetry + /// callback, for integration testing telemetry forwarding. + #[doc(hidden)] + #[cfg(any(test, feature = "test-support"))] + pub fn from_streams_with_github_telemetry( + reader: impl AsyncRead + Unpin + Send + 'static, + writer: impl AsyncWrite + Unpin + Send + 'static, + cwd: PathBuf, + on_github_telemetry: crate::github_telemetry::GitHubTelemetryCallback, + ) -> Result { + Self::from_transport( + reader, + writer, + None, + cwd, + None, + false, + false, + None, + Some(on_github_telemetry), + None, + ClientMode::default(), + ) + } + /// Public test-only wrapper around the random connection-token /// generator used by [`Client::start`] when the SDK spawns a TCP /// server without an explicit token. Lets integration tests @@ -1205,6 +1468,7 @@ impl Client { session_fs_configured: bool, session_fs_sqlite_declared: bool, on_get_trace_context: Option>, + on_github_telemetry: Option, effective_connection_token: Option, mode: ClientMode, ) -> Result { @@ -1224,6 +1488,8 @@ impl Client { let client = Self { inner: Arc::new(ClientInner { child: parking_lot::Mutex::new(child), + #[cfg(feature = "bundled-in-process")] + ffi_host: parking_lot::Mutex::new(None), rpc, cwd, request_rx: parking_lot::Mutex::new(Some(request_rx)), @@ -1237,6 +1503,7 @@ impl Client { session_fs_configured, session_fs_sqlite_declared, llm_inference: OnceLock::new(), + on_github_telemetry, on_get_trace_context, effective_connection_token, mode, @@ -1291,7 +1558,7 @@ impl Client { }); } - fn build_command(program: &Path, options: &ClientOptions) -> Command { + fn build_command(program: &Path, options: &ClientOptions, working_directory: &Path) -> Command { let mut command = Command::new(program); for arg in &options.prefix_args { command.arg(arg); @@ -1349,7 +1616,7 @@ impl Client { command.env_remove(key); } command - .current_dir(&options.working_directory) + .current_dir(working_directory) .stdout(Stdio::piped()) .stderr(Stdio::piped()); @@ -1412,9 +1679,13 @@ impl Client { } } - fn spawn_stdio(program: &Path, options: &ClientOptions) -> Result { - info!(cwd = ?options.working_directory, program = %program.display(), "spawning copilot CLI (stdio)"); - let mut command = Self::build_command(program, options); + fn spawn_stdio( + program: &Path, + options: &ClientOptions, + working_directory: &Path, + ) -> Result { + info!(cwd = ?working_directory, program = %program.display(), "spawning copilot CLI (stdio)"); + let mut command = Self::build_command(program, options, working_directory); command .args(["--server", "--stdio", "--no-auto-update"]) .args(Self::log_level_args(options)) @@ -1432,9 +1703,14 @@ impl Client { Ok(child) } - async fn spawn_tcp(program: &Path, options: &ClientOptions, port: u16) -> Result<(Child, u16)> { - info!(cwd = ?options.working_directory, program = %program.display(), port = %port, "spawning copilot CLI (tcp)"); - let mut command = Self::build_command(program, options); + async fn spawn_tcp( + program: &Path, + options: &ClientOptions, + working_directory: &Path, + port: u16, + ) -> Result<(Child, u16)> { + info!(cwd = ?working_directory, program = %program.display(), port = %port, "spawning copilot CLI (tcp)"); + let mut command = Self::build_command(program, options, working_directory); command .args(["--server", "--port", &port.to_string(), "--no-auto-update"]) .args(Self::log_level_args(options)) @@ -1646,6 +1922,7 @@ impl Client { &self.inner.notification_tx, &self.inner.request_rx, self.inner.llm_inference.get().cloned(), + self.inner.on_github_telemetry.clone(), ); self.inner.router.register(session_id) } @@ -1746,13 +2023,26 @@ impl Client { /// param. Server-side, the token is required when the server was /// started with `COPILOT_CONNECTION_TOKEN`. async fn connect_handshake(&self) -> Result> { - let result = self - .rpc() - .connect(crate::generated::api_types::ConnectRequest { - token: self.inner.effective_connection_token.clone(), - }) + let params = crate::generated::api_types::ConnectRequest { + token: self.inner.effective_connection_token.clone(), + enable_git_hub_telemetry_forwarding: self + .inner + .on_github_telemetry + .is_some() + .then_some(true), + }; + let value = self + .call( + crate::generated::api_types::rpc_methods::CONNECT, + Some(serde_json::to_value(params)?), + ) .await?; - Ok(u32::try_from(result.protocol_version).ok()) + let result: crate::generated::api_types::ConnectResult = serde_json::from_value(value)?; + Ok(Some(u32::try_from(result.protocol_version).map_err( + |_| ProtocolErrorKind::InvalidProtocolVersion { + server: result.protocol_version, + }, + )?)) } /// Send a `ping` RPC and return the typed [`PingResponse`]. @@ -1979,6 +2269,9 @@ impl Client { } let should_shutdown_runtime = self.inner.child.lock().is_some(); + #[cfg(feature = "bundled-in-process")] + let should_shutdown_runtime = + should_shutdown_runtime || self.inner.ffi_host.lock().is_some(); if should_shutdown_runtime { let runtime_shutdown_start = Instant::now(); match tokio::time::timeout(RUNTIME_SHUTDOWN_TIMEOUT, self.rpc().runtime().shutdown()) @@ -2035,6 +2328,16 @@ impl Client { } } + // The runtime.shutdown RPC above already asked the runtime to clean up; + // closing here tears down the transport. + #[cfg(feature = "bundled-in-process")] + { + if let Some(host) = self.inner.ffi_host.lock().take() { + self.inner.rpc.force_close(); + host.close(); + } + } + info!(pid = ?pid, errors = errors.len(), "CLI process stopped"); if errors.is_empty() { Ok(()) @@ -2081,6 +2384,12 @@ impl Client { error!(pid = ?pid, error = %e, "failed to send kill signal"); } self.inner.rpc.force_close(); + #[cfg(feature = "bundled-in-process")] + { + if let Some(host) = self.inner.ffi_host.lock().take() { + host.close(); + } + } // Drop all session channels so any awaiters see a closed channel // instead of waiting for responses that will never arrive. self.inner.router.clear(); @@ -2137,6 +2446,13 @@ impl Drop for ClientInner { info!(pid = ?pid, "kill signal sent for CLI process on drop"); } } + #[cfg(feature = "bundled-in-process")] + { + if let Some(host) = self.ffi_host.lock().take() { + self.rpc.force_close(); + host.close(); + } + } } } @@ -2201,6 +2517,63 @@ mod tests { assert!(opts.enable_remote_sessions); } + #[test] + fn default_transport_values_resolve_without_process_state() { + assert!(matches!( + resolve_default_transport_value(None).unwrap(), + Transport::Stdio + )); + assert!(matches!( + resolve_default_transport_value(Some("stdio")).unwrap(), + Transport::Stdio + )); + assert!(matches!( + resolve_default_transport_value(Some("INPROCESS")).unwrap(), + Transport::InProcess + )); + assert!(resolve_default_transport_value(Some("tcp")).is_err()); + } + + #[test] + fn inprocess_rejects_process_scoped_options() { + let invalid = [ + ClientOptions::new().with_cwd("."), + ClientOptions::new().with_env([("KEY", "value")]), + ClientOptions::new().with_env_remove(["KEY"]), + ClientOptions::new().with_telemetry(TelemetryConfig::default()), + ClientOptions::new().with_prefix_args(["index.js"]), + ClientOptions::new().with_program(CliProgram::Path("copilot".into())), + ClientOptions::new().with_extra_args(["--verbose"]), + ]; + + for options in invalid { + assert!(validate_inprocess_options(&options).is_err()); + } + } + + #[test] + fn inprocess_allows_typed_runtime_options() { + let options = ClientOptions::new() + .with_base_directory("state") + .with_log_level(LogLevel::Debug) + .with_session_idle_timeout_seconds(10) + .with_github_token("token") + .with_use_logged_in_user(false) + .with_enable_remote_sessions(true); + + assert!(validate_inprocess_options(&options).is_ok()); + } + + #[cfg(not(feature = "bundled-in-process"))] + #[tokio::test] + async fn inprocess_requires_cargo_feature() { + let error = Client::start(ClientOptions::new().with_transport(Transport::InProcess)) + .await + .unwrap_err(); + + assert!(error.to_string().contains("bundled-in-process")); + } + #[test] fn is_transport_failure_rejects_other_protocol_errors() { let err = Error::from(ErrorKind::Protocol(ProtocolErrorKind::CliStartupTimeout)); @@ -2214,7 +2587,7 @@ mod tests { env_remove: vec![std::ffi::OsString::from("COPILOT_SDK_AUTH_TOKEN")], ..Default::default() }; - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); // get_envs() iter yields the latest action per key — None means removed. let action = cmd .as_std() @@ -2238,7 +2611,7 @@ mod tests { )], ..Default::default() }; - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); let value = cmd .as_std() .get_envs() @@ -2253,7 +2626,7 @@ mod tests { github_token: Some("just-the-token".to_string()), ..Default::default() }; - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); let value = cmd .as_std() .get_envs() @@ -2321,7 +2694,7 @@ mod tests { }), ..Default::default() }; - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); assert_eq!( env_value(&cmd, "COPILOT_OTEL_ENABLED"), Some(std::ffi::OsStr::new("true")), @@ -2355,7 +2728,7 @@ mod tests { #[test] fn build_command_omits_otel_env_when_telemetry_none() { let opts = ClientOptions::default(); - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); for key in [ "COPILOT_OTEL_ENABLED", "OTEL_EXPORTER_OTLP_ENDPOINT", @@ -2381,7 +2754,7 @@ mod tests { }), ..Default::default() }; - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); // The one set field plus the implicit enabled flag should propagate. assert_eq!( env_value(&cmd, "COPILOT_OTEL_ENABLED"), @@ -2416,7 +2789,7 @@ mod tests { )], ..Default::default() }; - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); assert_eq!( env_value(&cmd, "OTEL_EXPORTER_OTLP_ENDPOINT"), Some(std::ffi::OsStr::new("http://from-user-env:4318")), @@ -2427,14 +2800,14 @@ mod tests { #[test] fn build_command_sets_copilot_home_env_when_configured() { let opts = ClientOptions::new().with_base_directory(PathBuf::from("/custom/copilot")); - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); assert_eq!( env_value(&cmd, "COPILOT_HOME"), Some(std::ffi::OsStr::new("/custom/copilot")), ); let opts = ClientOptions::default(); - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); assert!(env_value(&cmd, "COPILOT_HOME").is_none()); } @@ -2444,14 +2817,14 @@ mod tests { port: 0, connection_token: Some("secret-token".to_string()), }); - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); assert_eq!( env_value(&cmd, "COPILOT_CONNECTION_TOKEN"), Some(std::ffi::OsStr::new("secret-token")), ); let opts = ClientOptions::default(); - let cmd = Client::build_command(Path::new("/bin/echo"), &opts); + let cmd = Client::build_command(Path::new("/bin/echo"), &opts, Path::new("/tmp")); assert!(env_value(&cmd, "COPILOT_CONNECTION_TOKEN").is_none()); } @@ -2502,8 +2875,9 @@ mod tests { }), ..Default::default() }; - let cmd_true = Client::build_command(Path::new("/bin/echo"), &opts_true); - let cmd_false = Client::build_command(Path::new("/bin/echo"), &opts_false); + let cmd_true = Client::build_command(Path::new("/bin/echo"), &opts_true, Path::new("/tmp")); + let cmd_false = + Client::build_command(Path::new("/bin/echo"), &opts_false, Path::new("/tmp")); assert_eq!( env_value( &cmd_true, @@ -2713,6 +3087,8 @@ mod tests { Client { inner: Arc::new(ClientInner { child: parking_lot::Mutex::new(None), + #[cfg(feature = "bundled-in-process")] + ffi_host: parking_lot::Mutex::new(None), rpc: { let (req_tx, _req_rx) = mpsc::unbounded_channel(); let (notif_tx, _notif_rx) = broadcast::channel(16); @@ -2732,6 +3108,7 @@ mod tests { session_fs_configured: false, session_fs_sqlite_declared: false, llm_inference: OnceLock::new(), + on_github_telemetry: None, on_get_trace_context: None, effective_connection_token: None, mode: ClientMode::default(), diff --git a/rust/src/router.rs b/rust/src/router.rs index cc621c287c..adc1923824 100644 --- a/rust/src/router.rs +++ b/rust/src/router.rs @@ -86,6 +86,7 @@ impl SessionRouter { notification_tx: &broadcast::Sender, request_rx: &Mutex>>, llm_inference: Option>, + github_telemetry: Option, ) { let mut started = self.started.lock(); if *started { @@ -100,6 +101,40 @@ impl SessionRouter { loop { match notif_rx.recv().await { Ok(notification) => { + // Client-global `gitHubTelemetry.event` notifications carry + // no routable session and are surfaced to the consumer + // callback (if any) registered at client construction. + if notification.method == "gitHubTelemetry.event" { + if let Some(ref callback) = github_telemetry { + let Some(ref params) = notification.params else { + continue; + }; + match serde_json::from_value::< + crate::github_telemetry::GitHubTelemetryNotification, + >(params.clone()) + { + Ok(telemetry) => { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe( + || callback(telemetry), + )) + .is_err() + { + warn!( + "gitHubTelemetry.event callback panicked; \ + continuing notification routing" + ); + } + } + Err(e) => { + warn!( + error = %e, + "failed to deserialize gitHubTelemetry.event notification" + ); + } + } + } + continue; + } if notification.method != "session.event" { continue; } diff --git a/rust/src/session.rs b/rust/src/session.rs index 18b91b4377..35656c657f 100644 --- a/rust/src/session.rs +++ b/rust/src/session.rs @@ -11,14 +11,18 @@ use tokio_util::sync::CancellationToken; use tracing::{Instrument, warn}; use crate::canvas::CanvasHandler; -use crate::generated::api_types::{LogRequest, ModelSwitchToRequest, OpenCanvasInstance}; +use crate::generated::api_types::{ + LogRequest, ModelSwitchToRequest, OpenCanvasInstance, RegisterEventInterestParams, + ToolsGetCurrentMetadataResult, rpc_methods, +}; use crate::generated::session_events::{ - CommandExecuteData, ElicitationRequestedData, ExternalToolRequestedData, + CommandExecuteData, ElicitationRequestedData, ExternalToolRequestedData, McpOauthRequiredData, SessionCanvasClosedData, SessionErrorData, SessionEventType, }; use crate::handler::{ AutoModeSwitchHandler, AutoModeSwitchResponse, ElicitationHandler, ExitPlanModeHandler, - PermissionHandler, PermissionResult, UserInputHandler, UserInputResponse, + McpAuthHandler, McpAuthRequest, McpAuthResult, PermissionHandler, PermissionResult, + UserInputHandler, UserInputResponse, }; use crate::hooks::SessionHooks; use crate::provider_token::BearerTokenProvider; @@ -38,6 +42,11 @@ use crate::{ error_codes, }; +/// Fixed name of the runtime's built-in tool-search tool. A client can replace +/// its behavior by registering a tool with this exact name and +/// `overrides_built_in_tool` set to `true`. +const TOOL_SEARCH_TOOL_NAME: &str = "tool_search_tool"; + /// Bundle of the per-session callbacks the SDK dispatches to. Built from a /// [`SessionConfig`] / [`ResumeSessionConfig`] at /// [`Client::create_session`] / [`Client::resume_session`] time. Each @@ -49,6 +58,7 @@ use crate::{ pub(crate) struct SessionHandlers { pub permission: Option>, pub elicitation: Option>, + pub mcp_auth: Option>, pub user_input: Option>, pub exit_plan_mode: Option>, pub auto_mode_switch: Option>, @@ -525,6 +535,7 @@ impl Session { model_id: model.to_string(), reasoning_effort: opts.reasoning_effort, reasoning_summary: opts.reasoning_summary, + verbosity: None, context_tier: opts.context_tier, model_capabilities: opts.model_capabilities, }; @@ -872,7 +883,9 @@ impl Client { let opt_custom_agents_local_only = config.custom_agents_local_only; let opt_coauthor_enabled = config.coauthor_enabled; let opt_manage_schedule_enabled = config.manage_schedule_enabled; - let (wire, mut runtime) = config.into_wire(local_session_id.clone())?; + let (mut wire, mut runtime) = config.into_wire(local_session_id.clone())?; + wire.enable_github_telemetry_forwarding = + self.inner.on_github_telemetry.is_some().then_some(true); let permission_handler = crate::permission::resolve_handler( runtime.permission_handler.take(), @@ -881,6 +894,7 @@ impl Client { let handlers = SessionHandlers { permission: permission_handler, elicitation: runtime.elicitation_handler.take(), + mcp_auth: runtime.mcp_auth_handler.take(), user_input: runtime.user_input_handler.take(), exit_plan_mode: runtime.exit_plan_mode_handler.take(), auto_mode_switch: runtime.auto_mode_switch_handler.take(), @@ -895,6 +909,7 @@ impl Client { let canvas_handler = runtime.canvas_handler.take(); let session_fs_provider = runtime.session_fs_provider.take(); let bearer_token_providers = std::mem::take(&mut runtime.bearer_token_providers); + let has_mcp_auth_handler = handlers.mcp_auth.is_some(); if self.inner.session_fs_configured && session_fs_provider.is_none() { return Err(ErrorKind::Session(SessionErrorKind::SessionFsProviderRequired).into()); } @@ -1030,6 +1045,9 @@ impl Client { "Client::create_session local setup complete" ); *capabilities.write() = create_result.capabilities.unwrap_or_default(); + if has_mcp_auth_handler { + register_mcp_auth_interest(self, &session_id).await?; + } tracing::debug!( elapsed_ms = total_start.elapsed().as_millis(), @@ -1130,7 +1148,9 @@ impl Client { let opt_custom_agents_local_only = config.custom_agents_local_only; let opt_coauthor_enabled = config.coauthor_enabled; let opt_manage_schedule_enabled = config.manage_schedule_enabled; - let (wire, mut runtime) = config.into_wire()?; + let (mut wire, mut runtime) = config.into_wire()?; + wire.enable_github_telemetry_forwarding = + self.inner.on_github_telemetry.is_some().then_some(true); let permission_handler = crate::permission::resolve_handler( runtime.permission_handler.take(), @@ -1139,6 +1159,7 @@ impl Client { let handlers = SessionHandlers { permission: permission_handler, elicitation: runtime.elicitation_handler.take(), + mcp_auth: runtime.mcp_auth_handler.take(), user_input: runtime.user_input_handler.take(), exit_plan_mode: runtime.exit_plan_mode_handler.take(), auto_mode_switch: runtime.auto_mode_switch_handler.take(), @@ -1153,6 +1174,7 @@ impl Client { let canvas_handler = runtime.canvas_handler.take(); let session_fs_provider = runtime.session_fs_provider.take(); let bearer_token_providers = std::mem::take(&mut runtime.bearer_token_providers); + let has_mcp_auth_handler = handlers.mcp_auth.is_some(); if self.inner.session_fs_configured && session_fs_provider.is_none() { return Err(ErrorKind::Session(SessionErrorKind::SessionFsProviderRequired).into()); } @@ -1239,6 +1261,9 @@ impl Client { }) .into()); } + if has_mcp_auth_handler { + register_mcp_auth_interest(self, &session_id).await?; + } // Reload skills after resume (best-effort). let skills_reload_start = Instant::now(); @@ -1477,6 +1502,17 @@ fn notification_permission_payload(result: &PermissionResult) -> Option { } } +async fn register_mcp_auth_interest(client: &Client, session_id: &SessionId) -> Result<(), Error> { + let mut params = serde_json::to_value(RegisterEventInterestParams { + event_type: "mcp.oauth_required".to_string(), + })?; + params["sessionId"] = Value::String(session_id.to_string()); + client + .call(rpc_methods::SESSION_EVENTLOG_REGISTERINTEREST, Some(params)) + .await?; + Ok(()) +} + fn tool_failure_result(message: impl Into) -> ToolResult { let message = message.into(); ToolResult::Expanded(ToolResultExpanded { @@ -1486,6 +1522,7 @@ fn tool_failure_result(message: impl Into) -> ToolResult { session_log: None, error: Some(message), tool_telemetry: None, + tool_references: None, }) } @@ -1777,6 +1814,30 @@ async fn handle_notification( } let tool_call_id = data.tool_call_id.clone(); let tool_name = data.tool_name.clone(); + // The built-in tool-search tool receives a snapshot of the + // session's currently initialized tools so an override can + // filter the live catalog without issuing its own RPC. Fetch + // it only for that tool to avoid a round-trip on every tool + // call; a failed fetch leaves the snapshot `None` rather than + // failing the tool. + let available_tools = if tool_name == TOOL_SEARCH_TOOL_NAME { + match client + .call( + rpc_methods::SESSION_TOOLS_GETCURRENTMETADATA, + Some(serde_json::json!({ "sessionId": sid })), + ) + .await + { + Ok(value) => { + serde_json::from_value::(value) + .ok() + .and_then(|result| result.tools) + } + Err(_) => None, + } + } else { + None + }; let invocation = ToolInvocation { session_id: sid.clone(), tool_call_id: data.tool_call_id, @@ -1784,6 +1845,7 @@ async fn handle_notification( arguments: data .arguments .unwrap_or(Value::Object(serde_json::Map::new())), + available_tools, traceparent: data.traceparent, tracestate: data.tracestate, }; @@ -1944,6 +2006,91 @@ async fn handle_notification( .instrument(span), ); } + SessionEventType::McpOauthRequired => { + let Some(request_id) = extract_request_id(¬ification.event.data) else { + return; + }; + let Some(mcp_auth_handler) = handlers.mcp_auth.clone() else { + warn!( + session_id = %session_id, + request_id = %request_id, + "received MCP OAuth request without a registered MCP auth handler" + ); + return; + }; + let data: McpOauthRequiredData = + match serde_json::from_value(notification.event.data.clone()) { + Ok(d) => d, + Err(e) => { + warn!(error = %e, "failed to deserialize MCP OAuth request"); + return; + } + }; + let request = McpAuthRequest { + request_id: request_id.clone(), + server_name: data.server_name, + server_url: data.server_url, + reason: data.reason, + www_authenticate_params: data.www_authenticate_params, + resource_metadata: data.resource_metadata, + static_client_config: data.static_client_config, + }; + let client = client.clone(); + let sid = session_id.clone(); + let span = tracing::error_span!( + "mcp_auth_request_handler", + session_id = %sid, + request_id = %request_id + ); + tokio::spawn( + async move { + let cancel = McpAuthResult::Cancelled; + let handler_task = tokio::spawn({ + let sid = sid.clone(); + let request_id = request_id.clone(); + let span = tracing::error_span!( + "mcp_auth_callback", + session_id = %sid, + request_id = %request_id + ); + async move { + let handler_start = Instant::now(); + let response = mcp_auth_handler + .handle(sid.clone(), request_id.clone(), request) + .await; + tracing::debug!( + elapsed_ms = handler_start.elapsed().as_millis(), + session_id = %sid, + request_id = %request_id, + "McpAuthHandler::handle dispatch" + ); + response + } + .instrument(span) + }); + let result = match handler_task.await { + Ok(result) => result, + Err(_) => cancel, + }; + let rpc_start = Instant::now(); + let _ = client + .call( + "session.mcp.oauth.handlePendingRequest", + Some(serde_json::json!({ + "sessionId": sid, + "requestId": request_id, + "result": result.into_wire(), + })), + ) + .await; + tracing::debug!( + elapsed_ms = rpc_start.elapsed().as_millis(), + "Session::handle_notification MCP auth response sent" + ); + } + .instrument(span), + ); + } SessionEventType::CommandExecute => { let data: CommandExecuteData = match serde_json::from_value(notification.event.data.clone()) { diff --git a/rust/src/tool.rs b/rust/src/tool.rs index 189bc6f21a..344d2894ca 100644 --- a/rust/src/tool.rs +++ b/rust/src/tool.rs @@ -13,9 +13,8 @@ //! Enable the `derive` feature for `schema_for`, which generates JSON //! Schema from Rust types via `schemars`. -use std::collections::HashMap; - use async_trait::async_trait; +use indexmap::IndexMap; /// Re-export of [`schemars::JsonSchema`] for deriving tool parameter schemas. #[cfg(feature = "derive")] pub use schemars::JsonSchema; @@ -80,14 +79,14 @@ pub fn schema_for() -> serde_json::Value { /// tool.parameters = tool_parameters(serde_json::json!({"type": "object"})); /// # let _ = tool; /// ``` -pub fn tool_parameters(schema: serde_json::Value) -> HashMap { +pub fn tool_parameters(schema: serde_json::Value) -> IndexMap { try_tool_parameters(schema).expect("tool parameter schema must be a JSON object") } /// Fallible variant of [`tool_parameters`] for callers handling dynamic schema input. pub fn try_tool_parameters( schema: serde_json::Value, -) -> Result, serde_json::Error> { +) -> Result, serde_json::Error> { serde_json::from_value(schema) } @@ -174,6 +173,7 @@ pub fn convert_mcp_call_tool_result(value: &serde_json::Value) -> Option = tool.parameters.keys().map(String::as_str).collect(); + assert_eq!( + keys, + ["additionalProperties", "properties", "required", "type"] + ); + } + #[test] fn convert_mcp_call_tool_result_collects_text_and_binary_content() { let result = convert_mcp_call_tool_result(&serde_json::json!({ @@ -566,6 +604,7 @@ mod tests { tool_call_id: "tc1".to_string(), tool_name: "echo".to_string(), arguments: serde_json::json!({"msg": "hello"}), + available_tools: None, traceparent: None, tracestate: None, }; @@ -606,6 +645,7 @@ mod tests { tool_call_id: "tc1".to_string(), tool_name: "weather".to_string(), arguments: serde_json::json!({"city": "Seattle"}), + available_tools: None, traceparent: None, tracestate: None, }; @@ -688,6 +728,7 @@ mod tests { tool_call_id: "tc1".to_string(), tool_name: "get_weather".to_string(), arguments: serde_json::json!({"city": "Seattle", "unit": "celsius"}), + available_tools: None, traceparent: None, tracestate: None, }; @@ -707,6 +748,7 @@ mod tests { tool_call_id: "tc1".to_string(), tool_name: "get_weather".to_string(), arguments: serde_json::json!({"wrong_field": 42}), + available_tools: None, traceparent: None, tracestate: None, }; @@ -728,6 +770,7 @@ mod tests { tool_call_id: "tc1".to_string(), tool_name: "get_weather".to_string(), arguments: serde_json::json!({"city": "Portland"}), + available_tools: None, traceparent: None, tracestate: None, }) diff --git a/rust/src/types.rs b/rust/src/types.rs index 75408db026..028702655f 100644 --- a/rust/src/types.rs +++ b/rust/src/types.rs @@ -9,6 +9,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; +use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -19,13 +20,13 @@ pub use crate::copilot_request_handler::{ CopilotWebSocketForwarderBuilder, CopilotWebSocketHandler, CopilotWebSocketMessage, CopilotWebSocketResponse, WebSocketTransform, forward_http, }; -use crate::generated::api_types::OpenCanvasInstance; -/// Context window tier for models that support tiered context windows. -pub use crate::generated::session_events::ContextTier; +use crate::generated::api_types::{CurrentToolMetadata, OpenCanvasInstance}; use crate::generated::session_events::ReasoningSummary; +/// Context window tier for models that support tiered context windows. +pub use crate::generated::session_events::{ContextTier, SessionLimitsConfig}; use crate::handler::{ - AutoModeSwitchHandler, ElicitationHandler, ExitPlanModeHandler, PermissionHandler, - UserInputHandler, + AutoModeSwitchHandler, ElicitationHandler, ExitPlanModeHandler, McpAuthHandler, + PermissionHandler, UserInputHandler, }; use crate::hooks::SessionHooks; use crate::provider_token::BearerTokenProvider; @@ -332,8 +333,8 @@ pub struct Tool { #[serde(default, skip_serializing_if = "Option::is_none")] pub instructions: Option, /// JSON Schema for the tool's input parameters. - #[serde(default, skip_serializing_if = "HashMap::is_empty")] - pub parameters: HashMap, + #[serde(default, skip_serializing_if = "IndexMap::is_empty")] + pub parameters: IndexMap, /// When `true`, this tool replaces a built-in tool of the same name /// (e.g. supplying a custom `grep` that the agent uses in place of the /// CLI's built-in implementation). @@ -351,6 +352,12 @@ pub struct Tool { /// runtime decide. #[serde(default, skip_serializing_if = "Option::is_none")] pub defer: Option, + /// Opaque, host-defined metadata associated with the tool definition. + /// Keys are namespaced and not part of the stable public API; values are + /// not interpreted and may be recognized to inform host-specific behavior. + /// Unknown keys are preserved and round-tripped untouched. + #[serde(default, skip_serializing_if = "IndexMap::is_empty")] + pub metadata: IndexMap, /// Optional runtime implementation. When `Some`, the SDK dispatches /// matching `external_tool.requested` broadcasts to this handler. /// When `None`, the tool is declaration-only. @@ -470,6 +477,13 @@ impl Tool { self } + /// Set opaque, host-defined metadata for the tool. Keys are namespaced and + /// not part of the stable public API. Replaces any previously-set metadata. + pub fn with_metadata(mut self, metadata: IndexMap) -> Self { + self.metadata = metadata; + self + } + /// Attach a runtime implementation. The SDK will dispatch matching /// `external_tool.requested` broadcasts to `handler` for this tool's /// name. Without a handler the tool is declaration-only. @@ -498,6 +512,7 @@ impl std::fmt::Debug for Tool { .field("overrides_built_in_tool", &self.overrides_built_in_tool) .field("skip_permission", &self.skip_permission) .field("defer", &self.defer) + .field("metadata", &self.metadata) .field( "handler", &self.handler.as_ref().map(|_| "").unwrap_or("None"), @@ -614,7 +629,7 @@ pub struct CustomAgentConfig { pub prompt: String, /// MCP servers specific to this agent. #[serde(default, skip_serializing_if = "Option::is_none")] - pub mcp_servers: Option>, + pub mcp_servers: Option>, /// Whether the agent is available for model inference. #[serde(default, skip_serializing_if = "Option::is_none")] pub infer: Option, @@ -627,6 +642,12 @@ pub struct CustomAgentConfig { /// falling back to the parent session model if unavailable. #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, + /// Reasoning effort level for this agent's model. + /// + /// When unset, no per-agent override is sent and the backend chooses its + /// default. The parent session effort is not inherited. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_effort: Option, } impl CustomAgentConfig { @@ -668,7 +689,7 @@ impl CustomAgentConfig { } /// Configure agent-specific MCP servers. - pub fn with_mcp_servers(mut self, mcp_servers: HashMap) -> Self { + pub fn with_mcp_servers(mut self, mcp_servers: IndexMap) -> Self { self.mcp_servers = Some(mcp_servers); self } @@ -694,6 +715,12 @@ impl CustomAgentConfig { self.model = Some(model.into()); self } + + /// Set the reasoning effort level for this agent's model. + pub fn with_reasoning_effort(mut self, reasoning_effort: impl Into) -> Self { + self.reasoning_effort = Some(reasoning_effort.into()); + self + } } /// Configures the default (built-in) agent that handles turns when no @@ -758,6 +785,45 @@ impl LargeToolOutputConfig { } } +/// Overrides the runtime's built-in tool-search behavior. +/// +/// Tool search defers tools to keep the model's active tool set small. +/// To override the tool-search tool's implementation, register a [`Tool`] +/// named `"tool_search_tool"` with [`Tool::overrides_built_in_tool`] set to `true`. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct ToolSearchConfig { + /// Toggle to enable/disable tool search. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enabled: Option, + /// The tool count above which MCP and external tools are deferred behind + /// tool search. When unset, the runtime default (30) applies. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub defer_threshold: Option, +} + +impl ToolSearchConfig { + /// Construct an empty [`ToolSearchConfig`]; all fields default to unset + /// (the runtime applies its own defaults). + pub fn new() -> Self { + Self::default() + } + + /// Toggle that enables or disables tool search. + pub fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = Some(enabled); + self + } + + /// Set the tool count above which MCP and external tools are deferred + /// behind tool search. + pub fn with_defer_threshold(mut self, defer_threshold: u32) -> Self { + self.defer_threshold = Some(defer_threshold); + self + } +} + /// Configures infinite sessions: persistent workspaces with automatic /// context-window compaction. /// @@ -916,6 +982,42 @@ impl ExtensionInfo { } } +/// Stable identity for a host/SDK connection that supplies built-in canvases. +/// +/// When set on session create or resume, the runtime uses [`id`] verbatim as +/// the agent-facing canvas extension id, so canvases declared on a control +/// connection survive stdio reconnect and CLI process restart instead of being +/// re-keyed to a per-connection id. The id is opaque to the runtime; a +/// per-window-stable value such as `app:builtin:` is recommended. An +/// id beginning with `connection:` is reserved and ignored by the runtime. +/// +/// [`id`]: CanvasProviderIdentity::id +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CanvasProviderIdentity { + /// Opaque, stable provider id used verbatim as the canvas extension id. + pub id: String, + /// Optional display name surfaced as the canvas extension name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, +} + +impl CanvasProviderIdentity { + /// Create a canvas provider identity from a stable opaque id. + pub fn new(id: impl Into) -> Self { + Self { + id: id.into(), + name: None, + } + } + + /// Set the optional display name surfaced as the canvas extension name. + pub fn with_name(mut self, name: impl Into) -> Self { + self.name = Some(name.into()); + self + } +} + /// Configuration for a single MCP server. /// /// MCP (Model Context Protocol) servers expose external tools to the @@ -929,8 +1031,8 @@ impl ExtensionInfo { /// /// ``` /// # use github_copilot_sdk::types::{McpServerConfig, McpStdioServerConfig, McpHttpServerConfig}; -/// # use std::collections::HashMap; -/// let mut servers = HashMap::new(); +/// # use github_copilot_sdk::IndexMap; +/// let mut servers = IndexMap::new(); /// servers.insert( /// "playwright".to_string(), /// McpServerConfig::Stdio(McpStdioServerConfig { @@ -1598,12 +1700,21 @@ pub struct SessionConfig { pub extension_sdk_path: Option, /// Stable extension identity for canvas/tool providers on this connection. pub extension_info: Option, + /// Stable identity for a host/SDK connection that supplies built-in + /// canvases, so they survive reconnect and CLI restart. + pub canvas_provider: Option, /// Allowlist of built-in tool names the agent may use. pub available_tools: Option>, /// Blocklist of built-in tool names the agent must not use. pub excluded_tools: Option>, + /// Names of built-in agents to exclude from the session. + /// + /// Excluded built-in agents are hidden from discovery and cannot be + /// selected or invoked unless a custom agent with the same name is + /// configured. + pub excluded_builtin_agents: Option>, /// MCP server configurations passed through to the CLI. - pub mcp_servers: Option>, + pub mcp_servers: Option>, /// Controls how MCP OAuth tokens are stored for this session. /// /// - `"persistent"` — tokens are stored in the OS keychain (shared across sessions). @@ -1668,6 +1779,10 @@ pub struct SessionConfig { pub plugin_directories: Option>, /// Configuration for large tool output handling, forwarded to the CLI. pub large_output: Option, + /// Overrides the runtime's built-in tool-search behavior, which defers + /// rarely used tools behind a searchable index. When unset, the runtime + /// default applies. + pub tool_search: Option, /// Skill names to disable. Skills in this set will not be available /// even if found in skill directories. pub disabled_skills: Option>, @@ -1718,6 +1833,10 @@ pub struct SessionConfig { /// telemetry is always disabled regardless of this setting. This is /// independent of [`ClientOptions::telemetry`](crate::ClientOptions::telemetry). pub enable_session_telemetry: Option, + /// **Experimental.** Enables native model citations for supported providers. + pub enable_citations: Option, + /// **Experimental.** Limits applied to this session's current accounting window. + pub session_limits: Option, /// Per-property overrides for model capabilities, deep-merged over /// runtime defaults. pub model_capabilities: Option, @@ -1760,6 +1879,13 @@ pub struct SessionConfig { /// [`with_exp_assignments`](Self::with_exp_assignments). #[doc(hidden)] pub exp_assignments: Option, + /// Opt-in: when `Some(true)`, the runtime self-fetches enterprise managed + /// settings (bypass-permissions policy) at session bootstrap using the + /// session's [`github_token`](Self::github_token). Requires `github_token` + /// to be set; if omitted, the runtime is expected to reject session creation + /// (fail-closed). When `None`, behaves exactly as before. Set via + /// [`with_enable_managed_settings`](Self::with_enable_managed_settings). + pub enable_managed_settings: Option, /// Custom session filesystem provider for this session. Required when /// the [`Client`](crate::Client) was started with /// [`ClientOptions::session_fs`](crate::ClientOptions::session_fs) set. @@ -1772,6 +1898,9 @@ pub struct SessionConfig { /// Optional elicitation-request handler. When `None`, /// `requestElicitation: false` goes on the wire. pub elicitation_handler: Option>, + /// Optional MCP OAuth request handler. When set, the SDK can satisfy MCP + /// server OAuth requests with host-acquired token data or cancellation. + pub mcp_auth_handler: Option>, /// Optional user-input handler. When `None`, /// `requestUserInput: false` goes on the wire and the `ask_user` /// tool is disabled. @@ -1834,8 +1963,10 @@ impl std::fmt::Debug for SessionConfig { .field("request_extensions", &self.request_extensions) .field("extension_sdk_path", &self.extension_sdk_path) .field("extension_info", &self.extension_info) + .field("canvas_provider", &self.canvas_provider) .field("available_tools", &self.available_tools) .field("excluded_tools", &self.excluded_tools) + .field("excluded_builtin_agents", &self.excluded_builtin_agents) .field("mcp_servers", &self.mcp_servers) .field("mcp_oauth_token_storage", &self.mcp_oauth_token_storage) .field("embedding_cache_storage", &self.embedding_cache_storage) @@ -1864,6 +1995,7 @@ impl std::fmt::Debug for SessionConfig { .field("instruction_directories", &self.instruction_directories) .field("plugin_directories", &self.plugin_directories) .field("large_output", &self.large_output) + .field("tool_search", &self.tool_search) .field("disabled_skills", &self.disabled_skills) .field("hooks", &self.hooks) .field("custom_agents", &self.custom_agents) @@ -1873,6 +2005,8 @@ impl std::fmt::Debug for SessionConfig { .field("provider", &self.provider) .field("capi", &self.capi) .field("enable_session_telemetry", &self.enable_session_telemetry) + .field("enable_citations", &self.enable_citations) + .field("session_limits", &self.session_limits) .field("model_capabilities", &self.model_capabilities) .field("memory", &self.memory) .field("config_directory", &self.config_directory) @@ -1889,6 +2023,7 @@ impl std::fmt::Debug for SessionConfig { ) .field("commands", &self.commands) .field("exp_assignments", &self.exp_assignments) + .field("enable_managed_settings", &self.enable_managed_settings) .field( "session_fs_provider", &self.session_fs_provider.as_ref().map(|_| ""), @@ -1901,6 +2036,10 @@ impl std::fmt::Debug for SessionConfig { "elicitation_handler", &self.elicitation_handler.as_ref().map(|_| ""), ) + .field( + "mcp_auth_handler", + &self.mcp_auth_handler.as_ref().map(|_| ""), + ) .field( "user_input_handler", &self.user_input_handler.as_ref().map(|_| ""), @@ -1948,8 +2087,10 @@ impl Default for SessionConfig { request_extensions: None, extension_sdk_path: None, extension_info: None, + canvas_provider: None, available_tools: None, excluded_tools: None, + excluded_builtin_agents: None, mcp_servers: None, mcp_oauth_token_storage: None, enable_config_discovery: None, @@ -1966,6 +2107,7 @@ impl Default for SessionConfig { instruction_directories: None, plugin_directories: None, large_output: None, + tool_search: None, disabled_skills: None, hooks: None, custom_agents: None, @@ -1977,6 +2119,8 @@ impl Default for SessionConfig { providers: None, models: None, enable_session_telemetry: None, + enable_citations: None, + session_limits: None, model_capabilities: None, memory: None, config_directory: None, @@ -1987,9 +2131,11 @@ impl Default for SessionConfig { include_sub_agent_streaming_events: None, commands: None, exp_assignments: None, + enable_managed_settings: None, session_fs_provider: None, permission_handler: None, elicitation_handler: None, + mcp_auth_handler: None, user_input_handler: None, exit_plan_mode_handler: None, auto_mode_switch_handler: None, @@ -2013,6 +2159,7 @@ pub(crate) struct SessionConfigRuntime { pub permission_handler: Option>, pub permission_policy: Option, pub elicitation_handler: Option>, + pub mcp_auth_handler: Option>, pub user_input_handler: Option>, pub exit_plan_mode_handler: Option>, pub auto_mode_switch_handler: Option>, @@ -2032,7 +2179,7 @@ impl SessionConfig { /// /// Wire-format flags are derived from handler presence and the policy /// field; runtime fields are moved out into the returned runtime so - /// the deep `Vec` / `HashMap` clones the previous + /// the deep `Vec` / `IndexMap` clones the previous /// `&self`-based shape required are eliminated, and the order of /// reading-vs-moving is enforced at compile time. /// @@ -2091,8 +2238,10 @@ impl SessionConfig { request_extensions: self.request_extensions, extension_sdk_path: self.extension_sdk_path, extension_info: self.extension_info, + canvas_provider: self.canvas_provider, available_tools: self.available_tools, excluded_tools: self.excluded_tools, + excluded_builtin_agents: self.excluded_builtin_agents, tool_filter_precedence: "excluded", mcp_servers: self.mcp_servers, mcp_oauth_token_storage: self.mcp_oauth_token_storage, @@ -2117,6 +2266,7 @@ impl SessionConfig { instruction_directories: self.instruction_directories, plugin_directories: self.plugin_directories, large_output: self.large_output, + tool_search: self.tool_search, disabled_skills: self.disabled_skills, custom_agents: self.custom_agents, default_agent: self.default_agent, @@ -2127,6 +2277,8 @@ impl SessionConfig { providers: self.providers, models: self.models, enable_session_telemetry: self.enable_session_telemetry, + enable_citations: self.enable_citations, + session_limits: self.session_limits, model_capabilities: self.model_capabilities, memory: self.memory, config_dir: self.config_directory, @@ -2135,14 +2287,17 @@ impl SessionConfig { remote_session: self.remote_session, cloud: self.cloud, include_sub_agent_streaming_events: self.include_sub_agent_streaming_events, + enable_github_telemetry_forwarding: None, commands: wire_commands, exp_assignments: self.exp_assignments, + enable_managed_settings: self.enable_managed_settings, }; let runtime = SessionConfigRuntime { permission_handler: self.permission_handler, permission_policy: self.permission_policy, elicitation_handler: self.elicitation_handler, + mcp_auth_handler: self.mcp_auth_handler, user_input_handler: self.user_input_handler, exit_plan_mode_handler: self.exit_plan_mode_handler, auto_mode_switch_handler: self.auto_mode_switch_handler, @@ -2173,6 +2328,12 @@ impl SessionConfig { self } + /// Install an [`McpAuthHandler`] for host-provided MCP OAuth tokens. + pub fn with_mcp_auth_handler(mut self, handler: Arc) -> Self { + self.mcp_auth_handler = Some(handler); + self + } + /// Install a [`UserInputHandler`]. Required for the `ask_user` tool /// to be enabled. pub fn with_user_input_handler(mut self, handler: Arc) -> Self { @@ -2354,6 +2515,13 @@ impl SessionConfig { self } + /// Set the canvas provider identity for this connection so host-supplied + /// canvases survive reconnect and CLI restart. + pub fn with_canvas_provider(mut self, canvas_provider: CanvasProviderIdentity) -> Self { + self.canvas_provider = Some(canvas_provider); + self + } + /// Set the allowlist of built-in tool names the agent may use. pub fn with_available_tools(mut self, tools: I) -> Self where @@ -2374,8 +2542,18 @@ impl SessionConfig { self } + /// Set the built-in agent names to exclude from the session. + pub fn with_excluded_builtin_agents(mut self, agents: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.excluded_builtin_agents = Some(agents.into_iter().map(Into::into).collect()); + self + } + /// Set MCP server configurations passed through to the CLI. - pub fn with_mcp_servers(mut self, servers: HashMap) -> Self { + pub fn with_mcp_servers(mut self, servers: IndexMap) -> Self { self.mcp_servers = Some(servers); self } @@ -2500,6 +2678,13 @@ impl SessionConfig { self } + /// Set the [`ToolSearchConfig`] overriding the runtime's built-in + /// tool-search behavior on session create. + pub fn with_tool_search(mut self, config: ToolSearchConfig) -> Self { + self.tool_search = Some(config); + self + } + /// Set the names of skills to disable (overrides skill discovery). pub fn with_disabled_skills(mut self, names: I) -> Self where @@ -2579,6 +2764,18 @@ impl SessionConfig { self } + /// **Experimental.** Enable native model citations for supported providers. + pub fn with_enable_citations(mut self, enable: bool) -> Self { + self.enable_citations = Some(enable); + self + } + + /// **Experimental.** Set limits for this session's current accounting window. + pub fn with_session_limits(mut self, limits: SessionLimitsConfig) -> Self { + self.session_limits = Some(limits); + self + } + /// Set per-property overrides for model capabilities. pub fn with_model_capabilities( mut self, @@ -2674,6 +2871,16 @@ impl SessionConfig { self.exp_assignments = Some(assignments); self } + + /// Opt the runtime into self-fetching enterprise managed settings + /// (bypass-permissions policy) at session bootstrap using the session's + /// [`github_token`](Self::github_token). Requires `github_token` to be set; + /// if omitted, the runtime is expected to reject session creation + /// (fail-closed). + pub fn with_enable_managed_settings(mut self, enabled: bool) -> Self { + self.enable_managed_settings = Some(enabled); + self + } } /// /// See [`SessionConfig`] for the construction patterns (chained `with_*` @@ -2686,6 +2893,9 @@ impl SessionConfig { pub struct ResumeSessionConfig { /// ID of the session to resume. pub session_id: SessionId, + /// Model to use for this session (e.g. `"gpt-4"`, `"claude-sonnet-4"`). + /// Can change the model when resuming. + pub model: Option, /// Application name sent as User-Agent context. pub client_name: Option, /// Desired reasoning effort to apply after resuming the session. @@ -2721,12 +2931,21 @@ pub struct ResumeSessionConfig { pub extension_sdk_path: Option, /// Stable extension identity for canvas/tool providers on this connection. pub extension_info: Option, + /// Stable identity for a host/SDK connection that supplies built-in + /// canvases, so they rehydrate against a stable extension id on resume. + pub canvas_provider: Option, /// Allowlist of tool names the agent may use. pub available_tools: Option>, /// Blocklist of built-in tool names. pub excluded_tools: Option>, + /// Names of built-in agents to exclude from the resumed session. + /// + /// Excluded built-in agents are hidden from discovery and cannot be + /// selected or invoked unless a custom agent with the same name is + /// configured. + pub excluded_builtin_agents: Option>, /// Re-supply MCP servers so they remain available after app restart. - pub mcp_servers: Option>, + pub mcp_servers: Option>, /// Controls how MCP OAuth tokens are stored for this session. /// See [`SessionConfig::mcp_oauth_token_storage`] for details. pub mcp_oauth_token_storage: Option, @@ -2763,6 +2982,9 @@ pub struct ResumeSessionConfig { pub plugin_directories: Option>, /// Configuration for large tool output handling, forwarded to the CLI on resume. pub large_output: Option, + /// Overrides the runtime's built-in tool-search behavior on resume. When + /// unset, the runtime default applies. + pub tool_search: Option, /// Skill names to disable on resume. pub disabled_skills: Option>, /// Enable session hooks on resume. @@ -2803,6 +3025,10 @@ pub struct ResumeSessionConfig { /// telemetry is always disabled regardless of this setting. This is /// independent of [`ClientOptions::telemetry`](crate::ClientOptions::telemetry). pub enable_session_telemetry: Option, + /// **Experimental.** Enables native model citations for supported providers. + pub enable_citations: Option, + /// **Experimental.** Limits applied to this session's current accounting window. + pub session_limits: Option, /// Per-property model capability overrides on resume. pub model_capabilities: Option, /// Per-session configuration for the runtime memory feature on resume. @@ -2829,6 +3055,12 @@ pub struct ResumeSessionConfig { /// [`with_exp_assignments`](Self::with_exp_assignments). #[doc(hidden)] pub exp_assignments: Option, + /// Opt-in flag injected on resume. See + /// [`SessionConfig::enable_managed_settings`]. Re-supply on resume so + /// the runtime re-applies the managed-settings self-fetch after a CLI + /// process restart. Set via + /// [`with_enable_managed_settings`](Self::with_enable_managed_settings). + pub enable_managed_settings: Option, /// Custom session filesystem provider. Required on resume when the /// [`Client`](crate::Client) was started with /// [`ClientOptions::session_fs`](crate::ClientOptions::session_fs). @@ -2851,6 +3083,8 @@ pub struct ResumeSessionConfig { /// Optional elicitation handler. See /// [`SessionConfig::elicitation_handler`]. pub elicitation_handler: Option>, + /// Optional MCP OAuth handler. See [`SessionConfig::mcp_auth_handler`]. + pub mcp_auth_handler: Option>, /// Optional user-input handler. See /// [`SessionConfig::user_input_handler`]. pub user_input_handler: Option>, @@ -2880,6 +3114,7 @@ impl std::fmt::Debug for ResumeSessionConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ResumeSessionConfig") .field("session_id", &self.session_id) + .field("model", &self.model) .field("client_name", &self.client_name) .field("reasoning_effort", &self.reasoning_effort) .field("reasoning_summary", &self.reasoning_summary) @@ -2897,8 +3132,10 @@ impl std::fmt::Debug for ResumeSessionConfig { .field("request_extensions", &self.request_extensions) .field("extension_sdk_path", &self.extension_sdk_path) .field("extension_info", &self.extension_info) + .field("canvas_provider", &self.canvas_provider) .field("available_tools", &self.available_tools) .field("excluded_tools", &self.excluded_tools) + .field("excluded_builtin_agents", &self.excluded_builtin_agents) .field("mcp_servers", &self.mcp_servers) .field("mcp_oauth_token_storage", &self.mcp_oauth_token_storage) .field("embedding_cache_storage", &self.embedding_cache_storage) @@ -2927,6 +3164,7 @@ impl std::fmt::Debug for ResumeSessionConfig { .field("instruction_directories", &self.instruction_directories) .field("plugin_directories", &self.plugin_directories) .field("large_output", &self.large_output) + .field("tool_search", &self.tool_search) .field("disabled_skills", &self.disabled_skills) .field("hooks", &self.hooks) .field("custom_agents", &self.custom_agents) @@ -2936,6 +3174,8 @@ impl std::fmt::Debug for ResumeSessionConfig { .field("provider", &self.provider) .field("capi", &self.capi) .field("enable_session_telemetry", &self.enable_session_telemetry) + .field("enable_citations", &self.enable_citations) + .field("session_limits", &self.session_limits) .field("model_capabilities", &self.model_capabilities) .field("memory", &self.memory) .field("config_directory", &self.config_directory) @@ -2951,6 +3191,7 @@ impl std::fmt::Debug for ResumeSessionConfig { ) .field("commands", &self.commands) .field("exp_assignments", &self.exp_assignments) + .field("enable_managed_settings", &self.enable_managed_settings) .field( "session_fs_provider", &self.session_fs_provider.as_ref().map(|_| ""), @@ -3037,6 +3278,7 @@ impl ResumeSessionConfig { let wire = crate::wire::SessionResumeWire { session_id: self.session_id, + model: self.model, client_name: self.client_name, reasoning_effort: self.reasoning_effort, reasoning_summary: self.reasoning_summary, @@ -3050,8 +3292,10 @@ impl ResumeSessionConfig { request_extensions: self.request_extensions, extension_sdk_path: self.extension_sdk_path, extension_info: self.extension_info, + canvas_provider: self.canvas_provider, available_tools: self.available_tools, excluded_tools: self.excluded_tools, + excluded_builtin_agents: self.excluded_builtin_agents, tool_filter_precedence: "excluded", mcp_servers: self.mcp_servers, mcp_oauth_token_storage: self.mcp_oauth_token_storage, @@ -3076,6 +3320,7 @@ impl ResumeSessionConfig { instruction_directories: self.instruction_directories, plugin_directories: self.plugin_directories, large_output: self.large_output, + tool_search: self.tool_search, disabled_skills: self.disabled_skills, custom_agents: self.custom_agents, default_agent: self.default_agent, @@ -3086,6 +3331,8 @@ impl ResumeSessionConfig { providers: self.providers, models: self.models, enable_session_telemetry: self.enable_session_telemetry, + enable_citations: self.enable_citations, + session_limits: self.session_limits, model_capabilities: self.model_capabilities, memory: self.memory, config_dir: self.config_directory, @@ -3093,8 +3340,10 @@ impl ResumeSessionConfig { github_token: self.github_token, remote_session: self.remote_session, include_sub_agent_streaming_events: self.include_sub_agent_streaming_events, + enable_github_telemetry_forwarding: None, commands: wire_commands, exp_assignments: self.exp_assignments, + enable_managed_settings: self.enable_managed_settings, suppress_resume_event: self.suppress_resume_event, continue_pending_work: self.continue_pending_work, }; @@ -3103,6 +3352,7 @@ impl ResumeSessionConfig { permission_handler: self.permission_handler, permission_policy: self.permission_policy, elicitation_handler: self.elicitation_handler, + mcp_auth_handler: self.mcp_auth_handler, user_input_handler: self.user_input_handler, exit_plan_mode_handler: self.exit_plan_mode_handler, auto_mode_switch_handler: self.auto_mode_switch_handler, @@ -3125,6 +3375,7 @@ impl ResumeSessionConfig { pub fn new(session_id: SessionId) -> Self { Self { session_id, + model: None, client_name: None, reasoning_effort: None, reasoning_summary: None, @@ -3139,8 +3390,10 @@ impl ResumeSessionConfig { request_extensions: None, extension_sdk_path: None, extension_info: None, + canvas_provider: None, available_tools: None, excluded_tools: None, + excluded_builtin_agents: None, mcp_servers: None, mcp_oauth_token_storage: None, enable_config_discovery: None, @@ -3157,6 +3410,7 @@ impl ResumeSessionConfig { instruction_directories: None, plugin_directories: None, large_output: None, + tool_search: None, disabled_skills: None, hooks: None, custom_agents: None, @@ -3168,6 +3422,8 @@ impl ResumeSessionConfig { providers: None, models: None, enable_session_telemetry: None, + enable_citations: None, + session_limits: None, model_capabilities: None, memory: None, config_directory: None, @@ -3177,11 +3433,13 @@ impl ResumeSessionConfig { include_sub_agent_streaming_events: None, commands: None, exp_assignments: None, + enable_managed_settings: None, session_fs_provider: None, suppress_resume_event: None, continue_pending_work: None, permission_handler: None, elicitation_handler: None, + mcp_auth_handler: None, user_input_handler: None, exit_plan_mode_handler: None, auto_mode_switch_handler: None, @@ -3207,6 +3465,12 @@ impl ResumeSessionConfig { self } + /// Install an [`McpAuthHandler`] for host-provided MCP OAuth tokens. + pub fn with_mcp_auth_handler(mut self, handler: Arc) -> Self { + self.mcp_auth_handler = Some(handler); + self + } + /// Install a [`UserInputHandler`] for the resumed session. pub fn with_user_input_handler(mut self, handler: Arc) -> Self { self.user_input_handler = Some(handler); @@ -3283,6 +3547,12 @@ impl ResumeSessionConfig { self } + /// Set the model identifier to switch to on resume (e.g. `"claude-sonnet-4"`). + pub fn with_model(mut self, model: impl Into) -> Self { + self.model = Some(model.into()); + self + } + /// Set the application name sent as `User-Agent` context. pub fn with_client_name(mut self, name: impl Into) -> Self { self.client_name = Some(name.into()); @@ -3374,6 +3644,13 @@ impl ResumeSessionConfig { self } + /// Set the canvas provider identity for this connection on resume so + /// host-supplied canvases rehydrate against a stable extension id. + pub fn with_canvas_provider(mut self, canvas_provider: CanvasProviderIdentity) -> Self { + self.canvas_provider = Some(canvas_provider); + self + } + /// Set the allowlist of tool names the agent may use. pub fn with_available_tools(mut self, tools: I) -> Self where @@ -3394,8 +3671,18 @@ impl ResumeSessionConfig { self } + /// Set the built-in agent names to exclude from the resumed session. + pub fn with_excluded_builtin_agents(mut self, agents: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.excluded_builtin_agents = Some(agents.into_iter().map(Into::into).collect()); + self + } + /// Re-supply MCP server configurations on resume. - pub fn with_mcp_servers(mut self, servers: HashMap) -> Self { + pub fn with_mcp_servers(mut self, servers: IndexMap) -> Self { self.mcp_servers = Some(servers); self } @@ -3515,6 +3802,13 @@ impl ResumeSessionConfig { self } + /// Set the [`ToolSearchConfig`] overriding the runtime's built-in + /// tool-search behavior on resume. + pub fn with_tool_search(mut self, config: ToolSearchConfig) -> Self { + self.tool_search = Some(config); + self + } + /// Set the names of skills to disable on resume. pub fn with_disabled_skills(mut self, names: I) -> Self where @@ -3592,6 +3886,18 @@ impl ResumeSessionConfig { self } + /// **Experimental.** Enable native model citations for supported providers on resume. + pub fn with_enable_citations(mut self, enable: bool) -> Self { + self.enable_citations = Some(enable); + self + } + + /// **Experimental.** Set limits for this session's current accounting window. + pub fn with_session_limits(mut self, limits: SessionLimitsConfig) -> Self { + self.session_limits = Some(limits); + self + } + /// Set per-property model capability overrides on resume. pub fn with_model_capabilities( mut self, @@ -3691,6 +3997,13 @@ impl ResumeSessionConfig { self.exp_assignments = Some(assignments); self } + + /// Opt the runtime into self-fetching enterprise managed settings on resume. + /// See [`SessionConfig::with_enable_managed_settings`]. + pub fn with_enable_managed_settings(mut self, enabled: bool) -> Self { + self.enable_managed_settings = Some(enabled); + self + } } /// Controls how the system message is constructed. @@ -3956,6 +4269,55 @@ pub enum GitHubReferenceType { Discussion, } +/// Pointer to a GitHub repository (owner/name plus optional numeric id). +/// +/// Used by the GitHub-anchored [`Attachment`] variants. Mirrors the field +/// shape of the generated `GitHubRepoRef`, but defined locally so it can +/// derive `Eq` for use inside the `Attachment` enum. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitHubRepoPointer { + /// Numeric GitHub repository id. + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Repository name (without owner). + pub name: String, + /// Repository owner login (user or organization). + pub owner: String, +} + +/// One side (head or base) of a GitHub single-file diff. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitHubFileDiffSide { + /// Repository-relative path to the file. + pub path: String, + /// Git ref (branch, tag, or commit SHA) the file is read at. + pub r#ref: String, + /// Repository the file lives in. + pub repo: GitHubRepoPointer, +} + +/// One side (head or base) of a GitHub tree comparison. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitHubTreeComparisonSide { + /// Repository the revision belongs to. + pub repo: GitHubRepoPointer, + /// Git revision (branch, tag, or commit SHA). + pub revision: String, +} + +/// Line range covered by a GitHub snippet attachment (1-based, inclusive end). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitHubSnippetLineRange { + /// Start line number (1-based). + pub start: i64, + /// End line number (1-based, inclusive). + pub end: i64, +} + /// An attachment included with a user message. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde( @@ -4020,6 +4382,117 @@ pub enum Attachment { /// URL to the referenced item. url: String, }, + /// A pointer to a GitHub commit. + #[serde(rename = "github_commit")] + GitHubCommit { + /// First line of the commit message. + message: String, + /// Full commit SHA. + oid: String, + /// Repository the commit belongs to. + repo: GitHubRepoPointer, + /// URL to the commit on GitHub. + url: String, + }, + /// A pointer to a GitHub release. + #[serde(rename = "github_release")] + GitHubRelease { + /// Human-readable release name. + name: String, + /// Repository the release belongs to. + repo: GitHubRepoPointer, + /// Git tag the release is anchored to. + tag_name: String, + /// URL to the release on GitHub. + url: String, + }, + /// A pointer to a GitHub Actions job. + #[serde(rename = "github_actions_job")] + GitHubActionsJob { + /// Terminal conclusion of the job when finished (e.g. "success", + /// "failure", "cancelled"). Absent for in-progress jobs. + #[serde(skip_serializing_if = "Option::is_none")] + conclusion: Option, + /// Job id within the workflow run. + job_id: i64, + /// Display name of the job. + job_name: String, + /// Repository the workflow run belongs to. + repo: GitHubRepoPointer, + /// URL to the job on GitHub. + url: String, + /// Display name of the workflow the job ran in. + workflow_name: String, + }, + /// A pointer to a GitHub repository. + #[serde(rename = "github_repository")] + GitHubRepository { + /// Short description of the repository. + #[serde(skip_serializing_if = "Option::is_none")] + description: Option, + /// Git ref this attachment is anchored at (branch, tag, or commit). + /// When absent the default branch is implied. + #[serde(skip_serializing_if = "Option::is_none")] + r#ref: Option, + /// Repository pointer. + repo: GitHubRepoPointer, + /// URL to the repository on GitHub. + url: String, + }, + /// A pointer to a single-file diff. At least one of `head` and `base` is present. + #[serde(rename = "github_file_diff")] + GitHubFileDiff { + /// File location on the base side of the diff. Absent for additions. + #[serde(skip_serializing_if = "Option::is_none")] + base: Option, + /// File location on the head side of the diff. Absent for deletions. + #[serde(skip_serializing_if = "Option::is_none")] + head: Option, + /// URL to the diff on GitHub (e.g. a commit, compare, or PR-file URL). + url: String, + }, + /// A pointer to a comparison between two git revisions. + #[serde(rename = "github_tree_comparison")] + GitHubTreeComparison { + /// Base side of the comparison. + base: GitHubTreeComparisonSide, + /// Head side of the comparison. + head: GitHubTreeComparisonSide, + /// URL to the comparison on GitHub. + url: String, + }, + /// A generic GitHub URL reference. + #[serde(rename = "github_url")] + GitHubUrl { + /// URL to the GitHub resource. + url: String, + }, + /// A pointer to a file in a GitHub repository at a specific ref. + #[serde(rename = "github_file")] + GitHubFile { + /// Repository-relative path to the file. + path: String, + /// Git ref the file is read at (branch, tag, or commit SHA). + r#ref: String, + /// Repository the file lives in. + repo: GitHubRepoPointer, + /// URL to the file on GitHub. + url: String, + }, + /// A pointer to a line range inside a file in a GitHub repository. + #[serde(rename = "github_snippet")] + GitHubSnippet { + /// Line range the snippet covers. + line_range: GitHubSnippetLineRange, + /// Repository-relative path to the file. + path: String, + /// Git ref the file is read at (branch, tag, or commit SHA). + r#ref: String, + /// Repository the file lives in. + repo: GitHubRepoPointer, + /// URL to the snippet on GitHub (with line anchor). + url: String, + }, } impl Attachment { @@ -4030,7 +4503,16 @@ impl Attachment { | Self::Directory { display_name, .. } | Self::Selection { display_name, .. } | Self::Blob { display_name, .. } => display_name.as_deref(), - Self::GitHubReference { .. } => None, + Self::GitHubReference { .. } + | Self::GitHubCommit { .. } + | Self::GitHubRelease { .. } + | Self::GitHubActionsJob { .. } + | Self::GitHubRepository { .. } + | Self::GitHubFileDiff { .. } + | Self::GitHubTreeComparison { .. } + | Self::GitHubUrl { .. } + | Self::GitHubFile { .. } + | Self::GitHubSnippet { .. } => None, } } @@ -4073,7 +4555,16 @@ impl Attachment { | Self::Directory { display_name, .. } | Self::Selection { display_name, .. } | Self::Blob { display_name, .. } => *display_name = Some(derived_display_name), - Self::GitHubReference { .. } => {} + Self::GitHubReference { .. } + | Self::GitHubCommit { .. } + | Self::GitHubRelease { .. } + | Self::GitHubActionsJob { .. } + | Self::GitHubRepository { .. } + | Self::GitHubFileDiff { .. } + | Self::GitHubTreeComparison { .. } + | Self::GitHubUrl { .. } + | Self::GitHubFile { .. } + | Self::GitHubSnippet { .. } => {} } } @@ -4084,7 +4575,16 @@ impl Attachment { } Self::Selection { file_path, .. } => Some(attachment_name_from_path(file_path)), Self::Blob { .. } => Some("attachment".to_string()), - Self::GitHubReference { .. } => None, + Self::GitHubReference { .. } + | Self::GitHubCommit { .. } + | Self::GitHubRelease { .. } + | Self::GitHubActionsJob { .. } + | Self::GitHubRepository { .. } + | Self::GitHubFileDiff { .. } + | Self::GitHubTreeComparison { .. } + | Self::GitHubUrl { .. } + | Self::GitHubFile { .. } + | Self::GitHubSnippet { .. } => None, } } } @@ -4435,6 +4935,15 @@ pub struct ToolInvocation { pub tool_name: String, /// Tool arguments as JSON. pub arguments: Value, + /// Snapshot of the session's currently initialized tools. + /// + /// The SDK populates this only when the invocation targets the built-in + /// tool-search tool (`tool_search_tool`), so a tool-search override can + /// rank/filter the live catalog — including MCP tools configured in + /// settings — without issuing its own RPC. `None` for every other tool + /// invocation. This field is not part of the wire protocol. + #[serde(skip)] + pub available_tools: Option>, /// W3C Trace Context `traceparent` header propagated from the CLI's /// `execute_tool` span. Pass through to OpenTelemetry-aware code so /// child spans created inside the handler are parented to the CLI @@ -4498,8 +5007,14 @@ pub struct ToolBinaryResult { } /// Expanded tool result with metadata for the LLM and session log. +/// +/// This type is `#[non_exhaustive]`: it mirrors a growing wire shape, so +/// construct it via [`ToolResultExpanded::new`] plus the `with_*` chain +/// rather than a struct literal, allowing new fields to land without +/// breaking callers. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct ToolResultExpanded { /// Result text sent back to the LLM. pub text_result_for_llm: String, @@ -4517,6 +5032,60 @@ pub struct ToolResultExpanded { /// Tool-specific telemetry emitted with the result. #[serde(default, skip_serializing_if = "Option::is_none")] pub tool_telemetry: Option>, + /// Names of tools returned by a tool-search tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_references: Option>, +} + +impl ToolResultExpanded { + /// Construct an expanded result with the required `text_result_for_llm` + /// and `result_type` (`"success"` or `"failure"`). All optional metadata + /// fields start unset; populate them with the `with_*` builders. + pub fn new(text_result_for_llm: impl Into, result_type: impl Into) -> Self { + Self { + text_result_for_llm: text_result_for_llm.into(), + result_type: result_type.into(), + binary_results_for_llm: None, + session_log: None, + error: None, + tool_telemetry: None, + tool_references: None, + } + } + + /// Set the binary payloads returned to the LLM. + pub fn with_binary_results(mut self, results: Vec) -> Self { + self.binary_results_for_llm = Some(results); + self + } + + /// Set the log message for the session timeline. + pub fn with_session_log(mut self, session_log: impl Into) -> Self { + self.session_log = Some(session_log.into()); + self + } + + /// Set the error message, marking the tool as failed. + pub fn with_error(mut self, error: impl Into) -> Self { + self.error = Some(error.into()); + self + } + + /// Set the tool-specific telemetry emitted with the result. + pub fn with_tool_telemetry(mut self, telemetry: HashMap) -> Self { + self.tool_telemetry = Some(telemetry); + self + } + + /// Set the names of tools returned by a tool-search tool. + pub fn with_tool_references(mut self, references: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.tool_references = Some(references.into_iter().map(Into::into).collect()); + self + } } /// Result of a tool invocation — either a plain text string or an expanded result. @@ -4859,10 +5428,11 @@ mod tests { AgentMode, Attachment, AttachmentLineRange, AttachmentSelectionPosition, AttachmentSelectionRange, AzureProviderOptions, CapiSessionOptions, ConnectionState, CustomAgentConfig, DeliveryMode, ExtensionInfo, GitHubReferenceType, InfiniteSessionConfig, - LargeToolOutputConfig, MemoryConfiguration, NamedProviderConfig, ProviderConfig, - ProviderModelConfig, ReasoningSummary, ResumeSessionConfig, SessionConfig, SessionEvent, - SessionId, SystemMessageConfig, Tool, ToolBinaryResult, ToolResult, ToolResultExpanded, - ToolResultResponse, ensure_attachment_display_names, + LargeToolOutputConfig, McpServerConfig, McpStdioServerConfig, MemoryConfiguration, + NamedProviderConfig, ProviderConfig, ProviderModelConfig, ReasoningSummary, + ResumeSessionConfig, SessionConfig, SessionEvent, SessionId, SystemMessageConfig, Tool, + ToolBinaryResult, ToolResult, ToolResultExpanded, ToolResultResponse, + ensure_attachment_display_names, }; use crate::generated::session_events::TypedSessionEvent; @@ -4900,6 +5470,32 @@ mod tests { assert!(value.get("defer").is_none()); } + #[test] + fn tool_metadata_serialization() { + use indexmap::IndexMap; + + let mut metadata = IndexMap::new(); + metadata.insert( + "github.com/copilot:safeForTelemetry".to_string(), + json!({ "name": true, "inputsNames": false }), + ); + let tool = Tool::new("lookup").with_metadata(metadata); + let value = serde_json::to_value(&tool).unwrap(); + assert_eq!( + value + .get("metadata") + .unwrap() + .get("github.com/copilot:safeForTelemetry") + .unwrap(), + &json!({ "name": true, "inputsNames": false }) + ); + + // Empty metadata is omitted on the wire. + let plain = Tool::new("plain"); + let value = serde_json::to_value(&plain).unwrap(); + assert!(value.get("metadata").is_none()); + } + #[test] fn custom_agent_config_builder_with_model() { let agent = CustomAgentConfig::new("my-agent", "You are helpful.") @@ -4925,6 +5521,28 @@ mod tests { assert!(wire.get("model").is_none()); } + #[test] + fn custom_agent_config_builder_with_reasoning_effort() { + let agent = + CustomAgentConfig::new("reasoning-agent", "prompt").with_reasoning_effort("high"); + assert_eq!(agent.reasoning_effort.as_deref(), Some("high")); + } + + #[test] + fn custom_agent_config_serializes_reasoning_effort() { + let agent = + CustomAgentConfig::new("reasoning-agent", "prompt").with_reasoning_effort("high"); + let wire = serde_json::to_value(&agent).unwrap(); + assert_eq!(wire["reasoningEffort"], "high"); + } + + #[test] + fn custom_agent_config_omits_reasoning_effort_when_none() { + let agent = CustomAgentConfig::new("default-agent", "prompt"); + let wire = serde_json::to_value(&agent).unwrap(); + assert!(wire.get("reasoningEffort").is_none()); + } + #[test] #[should_panic(expected = "tool parameter schema must be a JSON object")] fn tool_with_parameters_panics_on_non_object_value() { @@ -4946,6 +5564,7 @@ mod tests { session_log: None, error: None, tool_telemetry: None, + tool_references: None, }), }; @@ -4980,6 +5599,7 @@ mod tests { session_log: None, error: None, tool_telemetry: None, + tool_references: None, }), }; @@ -4989,6 +5609,70 @@ mod tests { assert!(wire["result"].get("binaryResultsForLlm").is_none()); } + #[test] + fn tool_result_expanded_serializes_tool_references() { + let response = ToolResultResponse { + result: ToolResult::Expanded( + ToolResultExpanded::new("found 2 tools", "success") + .with_tool_references(["get_weather", "check_status"]), + ), + }; + + let wire = serde_json::to_value(&response).unwrap(); + + assert_eq!( + wire, + json!({ + "result": { + "textResultForLlm": "found 2 tools", + "resultType": "success", + "toolReferences": ["get_weather", "check_status"] + } + }) + ); + } + + #[test] + fn tool_result_expanded_omits_tool_references_when_none() { + let response = ToolResultResponse { + result: ToolResult::Expanded(ToolResultExpanded::new("ok", "success")), + }; + + let wire = serde_json::to_value(&response).unwrap(); + + assert_eq!(wire["result"]["textResultForLlm"], "ok"); + assert!(wire["result"].get("toolReferences").is_none()); + } + + #[test] + fn tool_result_expanded_with_tool_references_accepts_owned_strings() { + // The builder is generic over `Into`, so an owned `Vec` + // must compile and populate the field just like a `&str` array. + let names: Vec = vec!["alpha".to_string(), "beta".to_string()]; + let expanded = ToolResultExpanded::new("ok", "success").with_tool_references(names); + + assert_eq!( + expanded.tool_references.as_deref(), + Some(["alpha".to_string(), "beta".to_string()].as_slice()) + ); + } + + #[test] + fn tool_result_expanded_deserializes_tool_references() { + let wire = json!({ + "textResultForLlm": "found tools", + "resultType": "success", + "toolReferences": ["alpha", "beta"] + }); + + let expanded: ToolResultExpanded = serde_json::from_value(wire).unwrap(); + + assert_eq!( + expanded.tool_references.as_deref(), + Some(["alpha".to_string(), "beta".to_string()].as_slice()) + ); + } + #[test] fn session_config_default_wire_flags_off_without_handlers() { let cfg = SessionConfig::default(); @@ -5411,7 +6095,7 @@ mod tests { #[test] fn session_config_builder_composes() { - use std::collections::HashMap; + use indexmap::IndexMap; let cfg = SessionConfig::default() .with_session_id(SessionId::from("sess-1")) @@ -5424,7 +6108,7 @@ mod tests { .with_tools([Tool::new("greet")]) .with_available_tools(["bash", "view"]) .with_excluded_tools(["dangerous"]) - .with_mcp_servers(HashMap::new()) + .with_mcp_servers(IndexMap::new()) .with_mcp_oauth_token_storage("persistent") .with_enable_config_discovery(true) .with_enable_on_demand_instruction_discovery(true) @@ -5485,7 +6169,7 @@ mod tests { #[test] fn resume_session_config_builder_composes() { - use std::collections::HashMap; + use indexmap::IndexMap; let cfg = ResumeSessionConfig::new(SessionId::from("sess-2")) .with_client_name("test-app") @@ -5495,7 +6179,7 @@ mod tests { .with_tools([Tool::new("greet")]) .with_available_tools(["bash", "view"]) .with_excluded_tools(["dangerous"]) - .with_mcp_servers(HashMap::new()) + .with_mcp_servers(IndexMap::new()) .with_mcp_oauth_token_storage("persistent") .with_enable_config_discovery(true) .with_enable_on_demand_instruction_discovery(false) @@ -5633,13 +6317,13 @@ mod tests { #[test] fn custom_agent_config_builder_composes() { - use std::collections::HashMap; + use indexmap::IndexMap; let cfg = CustomAgentConfig::new("researcher", "You are a research assistant.") .with_display_name("Research Assistant") .with_description("Investigates technical questions.") .with_tools(["bash", "view"]) - .with_mcp_servers(HashMap::new()) + .with_mcp_servers(IndexMap::new()) .with_infer(true) .with_skills(["rust-coding-skill"]); @@ -5662,6 +6346,51 @@ mod tests { ); } + #[test] + fn mcp_servers_serialize_in_insertion_order() { + use indexmap::IndexMap; + + // Regression: `mcp_servers` was a `HashMap`, so the server keys (and + // thus the `session.create` payload) serialized in a per-process + // random order; `IndexMap` pins them to insertion order. The long + // sequence makes a `HashMap` regression reproduce this exact order by + // chance only 1/N!, avoiding a flaky false pass. + let order = [ + "zebra", "quartz", "delta", "ivy", "mango", "bravo", "xenon", "amber", "falcon", + "ceres", "nova", "kelp", "otter", "yodel", "plum", "garnet", + ]; + let mut servers = IndexMap::new(); + for name in order { + servers.insert( + name.to_string(), + McpServerConfig::Stdio(McpStdioServerConfig { + command: "run".to_string(), + ..Default::default() + }), + ); + } + + let (wire, _runtime) = SessionConfig::default() + .with_mcp_servers(servers) + .into_wire(None) + .expect("into_wire should succeed"); + let json = serde_json::to_string(&wire).expect("serialize wire"); + + let positions: Vec = order + .iter() + .map(|name| { + json.find(&format!("\"{name}\"")) + .unwrap_or_else(|| panic!("server {name} missing from wire JSON")) + }) + .collect(); + let mut ascending = positions.clone(); + ascending.sort_unstable(); + assert_eq!( + positions, ascending, + "mcp server keys must serialize in insertion order: {json}" + ); + } + #[test] fn infinite_session_config_builder_composes() { let cfg = InfiniteSessionConfig::new() @@ -6040,6 +6769,153 @@ mod tests { Some("Track regressions".to_string()) ); } + + #[test] + fn github_anchored_attachment_variants_round_trip() { + let cases = vec![ + ( + "github_commit", + json!({ + "type": "github_commit", + "message": "Fix the thing", + "oid": "abc123", + "repo": { "id": 1, "name": "repo", "owner": "octocat" }, + "url": "https://github.com/octocat/repo/commit/abc123" + }), + ), + ( + "github_release", + json!({ + "type": "github_release", + "name": "v1.2.3", + "repo": { "name": "repo", "owner": "octocat" }, + "tagName": "v1.2.3", + "url": "https://github.com/octocat/repo/releases/tag/v1.2.3" + }), + ), + ( + "github_actions_job", + json!({ + "type": "github_actions_job", + "conclusion": "failure", + "jobId": 99, + "jobName": "build", + "repo": { "name": "repo", "owner": "octocat" }, + "url": "https://github.com/octocat/repo/actions/runs/1/job/99", + "workflowName": "CI" + }), + ), + ( + "github_repository", + json!({ + "type": "github_repository", + "description": "An example repository", + "ref": "main", + "repo": { "name": "repo", "owner": "octocat" }, + "url": "https://github.com/octocat/repo" + }), + ), + ( + "github_file_diff", + json!({ + "type": "github_file_diff", + "base": { + "path": "src/lib.rs", + "ref": "main", + "repo": { "name": "repo", "owner": "octocat" } + }, + "head": { + "path": "src/lib.rs", + "ref": "feature", + "repo": { "name": "repo", "owner": "octocat" } + }, + "url": "https://github.com/octocat/repo/compare/main...feature" + }), + ), + ( + "github_tree_comparison", + json!({ + "type": "github_tree_comparison", + "base": { + "repo": { "name": "repo", "owner": "octocat" }, + "revision": "main" + }, + "head": { + "repo": { "name": "repo", "owner": "octocat" }, + "revision": "feature" + }, + "url": "https://github.com/octocat/repo/compare/main...feature" + }), + ), + ( + "github_url", + json!({ + "type": "github_url", + "url": "https://github.com/octocat/repo/wiki" + }), + ), + ( + "github_file", + json!({ + "type": "github_file", + "path": "src/main.rs", + "ref": "main", + "repo": { "name": "repo", "owner": "octocat" }, + "url": "https://github.com/octocat/repo/blob/main/src/main.rs" + }), + ), + ( + "github_snippet", + json!({ + "type": "github_snippet", + "lineRange": { "start": 10, "end": 20 }, + "path": "src/main.rs", + "ref": "main", + "repo": { "name": "repo", "owner": "octocat" }, + "url": "https://github.com/octocat/repo/blob/main/src/main.rs#L10-L20" + }), + ), + ]; + + for (expected_type, input) in cases { + let attachment: Attachment = serde_json::from_value(input.clone()) + .unwrap_or_else(|err| panic!("{expected_type} should deserialize: {err}")); + + // Serialize to a string first: parsing into `serde_json::Value` would + // silently dedupe a duplicate `type` key, hiding the exact regression + // this test guards against (e.g. a wrapped generated struct emitting its + // own `type` alongside the enum tag). + let serialized_string = serde_json::to_string(&attachment) + .unwrap_or_else(|err| panic!("{expected_type} should serialize: {err}")); + + // Exactly one `type` key, carrying the expected discriminator. + assert_eq!( + serialized_string.matches("\"type\":").count(), + 1, + "{expected_type} must serialize a single `type` key" + ); + + let serialized: serde_json::Value = serde_json::from_str(&serialized_string) + .unwrap_or_else(|err| panic!("{expected_type} should reparse: {err}")); + assert_eq!( + serialized.get("type").and_then(|value| value.as_str()), + Some(expected_type), + "{expected_type} must serialize the correct discriminator" + ); + + // Round-trips without dropping fields. + assert_eq!( + serialized, input, + "{expected_type} should round-trip without data loss" + ); + let reparsed: Attachment = serde_json::from_value(serialized) + .unwrap_or_else(|err| panic!("{expected_type} should re-deserialize: {err}")); + assert_eq!( + reparsed, attachment, + "{expected_type} should re-deserialize to the same value" + ); + } + } } #[cfg(test)] diff --git a/rust/src/wire.rs b/rust/src/wire.rs index e6dad66d58..43188bc274 100644 --- a/rust/src/wire.rs +++ b/rust/src/wire.rs @@ -13,9 +13,9 @@ //! configs hold trait-object handlers, the wire structs hold only the //! plain data the runtime needs. -use std::collections::HashMap; use std::path::PathBuf; +use indexmap::IndexMap; use serde::Serialize; use crate::canvas::CanvasDeclaration; @@ -24,9 +24,10 @@ use crate::generated::api_types::{ }; use crate::generated::session_events::ReasoningSummary; use crate::types::{ - CapiSessionOptions, CloudSessionOptions, CustomAgentConfig, DefaultAgentConfig, ExtensionInfo, - InfiniteSessionConfig, LargeToolOutputConfig, McpServerConfig, MemoryConfiguration, - NamedProviderConfig, ProviderConfig, ProviderModelConfig, SessionId, SystemMessageConfig, Tool, + CanvasProviderIdentity, CapiSessionOptions, CloudSessionOptions, CustomAgentConfig, + DefaultAgentConfig, ExtensionInfo, InfiniteSessionConfig, LargeToolOutputConfig, + McpServerConfig, MemoryConfiguration, NamedProviderConfig, ProviderConfig, ProviderModelConfig, + SessionId, SessionLimitsConfig, SystemMessageConfig, Tool, ToolSearchConfig, }; /// Wire representation of a slash command (name + description only). The @@ -73,14 +74,18 @@ pub(crate) struct SessionCreateWire { #[serde(skip_serializing_if = "Option::is_none")] pub extension_info: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub canvas_provider: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub available_tools: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub excluded_tools: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub excluded_builtin_agents: Option>, /// SDK always sends `"excluded"` so include + exclude lists compose /// naturally (everything matching X except Y). pub tool_filter_precedence: &'static str, #[serde(skip_serializing_if = "Option::is_none")] - pub mcp_servers: Option>, + pub mcp_servers: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub mcp_oauth_token_storage: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -118,6 +123,8 @@ pub(crate) struct SessionCreateWire { #[serde(skip_serializing_if = "Option::is_none")] pub large_output: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub tool_search: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub disabled_skills: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub custom_agents: Option>, @@ -138,6 +145,10 @@ pub(crate) struct SessionCreateWire { #[serde(skip_serializing_if = "Option::is_none")] pub enable_session_telemetry: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub enable_citations: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub session_limits: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub model_capabilities: Option, #[serde(skip_serializing_if = "Option::is_none")] pub memory: Option, @@ -153,10 +164,17 @@ pub(crate) struct SessionCreateWire { pub cloud: Option, #[serde(skip_serializing_if = "Option::is_none")] pub include_sub_agent_streaming_events: Option, + #[serde( + rename = "enableGitHubTelemetryForwarding", + skip_serializing_if = "Option::is_none" + )] + pub enable_github_telemetry_forwarding: Option, #[serde(skip_serializing_if = "Option::is_none")] pub commands: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub exp_assignments: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_managed_settings: Option, } /// The exact JSON shape sent on the `session.resume` JSON-RPC request. @@ -165,6 +183,8 @@ pub(crate) struct SessionCreateWire { pub(crate) struct SessionResumeWire { pub session_id: SessionId, #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub client_name: Option, #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, @@ -191,13 +211,17 @@ pub(crate) struct SessionResumeWire { #[serde(skip_serializing_if = "Option::is_none")] pub extension_info: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub canvas_provider: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub available_tools: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub excluded_tools: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub excluded_builtin_agents: Option>, /// SDK always sends `"excluded"`. See create-wire docs. pub tool_filter_precedence: &'static str, #[serde(skip_serializing_if = "Option::is_none")] - pub mcp_servers: Option>, + pub mcp_servers: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub mcp_oauth_token_storage: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -235,6 +259,8 @@ pub(crate) struct SessionResumeWire { #[serde(skip_serializing_if = "Option::is_none")] pub large_output: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub tool_search: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub disabled_skills: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub custom_agents: Option>, @@ -255,6 +281,10 @@ pub(crate) struct SessionResumeWire { #[serde(skip_serializing_if = "Option::is_none")] pub enable_session_telemetry: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub enable_citations: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub session_limits: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub model_capabilities: Option, #[serde(skip_serializing_if = "Option::is_none")] pub memory: Option, @@ -268,6 +298,11 @@ pub(crate) struct SessionResumeWire { pub remote_session: Option, #[serde(skip_serializing_if = "Option::is_none")] pub include_sub_agent_streaming_events: Option, + #[serde( + rename = "enableGitHubTelemetryForwarding", + skip_serializing_if = "Option::is_none" + )] + pub enable_github_telemetry_forwarding: Option, #[serde(skip_serializing_if = "Option::is_none")] pub commands: Option>, /// Maps to wire field `disableResume`. @@ -277,4 +312,6 @@ pub(crate) struct SessionResumeWire { pub continue_pending_work: Option, #[serde(skip_serializing_if = "Option::is_none")] pub exp_assignments: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_managed_settings: Option, } diff --git a/rust/tests/cli_resolution_test.rs b/rust/tests/cli_resolution_test.rs index c3044a9e75..9e4927e676 100644 --- a/rust/tests/cli_resolution_test.rs +++ b/rust/tests/cli_resolution_test.rs @@ -196,21 +196,27 @@ async fn extract_dir_runtime_override_is_honored() { let _ = fake; } -/// Build-time version pin: `cli-version.txt` (when present) must be a -/// combined snapshot — a `version=X.Y.Z` line plus per-asset hash lines. +/// Build-time version pins, when present, must match the selected bundling +/// implementation's checksum format. /// When absent, build.rs falls through to `../nodejs/package-lock.json` — /// both are accepted, this test only checks the pin file's format if it's /// there. #[test] fn pin_file_when_present_is_well_formed() { let manifest_dir = env!("CARGO_MANIFEST_DIR"); - let pin = PathBuf::from(manifest_dir).join("cli-version.txt"); + let (filename, value_prefix) = if cfg!(feature = "bundled-in-process") { + ("cli-version-in-process.txt", Some("sha512-")) + } else { + ("cli-version.txt", None) + }; + let pin = PathBuf::from(manifest_dir).join(filename); if !pin.is_file() { // Contributor build path — no assertion needed. return; } - let contents = std::fs::read_to_string(&pin).expect("read cli-version.txt"); + let contents = std::fs::read_to_string(&pin).expect("read CLI version snapshot"); let mut saw_version = false; + let mut package_count = 0; for raw in contents.lines() { let line = raw.trim(); if line.is_empty() || line.starts_with('#') { @@ -222,9 +228,28 @@ fn pin_file_when_present_is_well_formed() { assert!(!value.trim().is_empty(), "empty value for key {key:?}"); if key.trim() == "version" { saw_version = true; + } else { + if let Some(prefix) = value_prefix { + assert!( + value.trim().starts_with(prefix), + "invalid npm integrity for key {key:?}" + ); + } else { + assert_eq!( + value.trim().len(), + 64, + "invalid SHA-256 hash for key {key:?}" + ); + assert!( + value.trim().bytes().all(|byte| byte.is_ascii_hexdigit()), + "invalid SHA-256 hash for key {key:?}" + ); + } + package_count += 1; } } - assert!(saw_version, "cli-version.txt missing `version=` line"); + assert!(saw_version, "{filename} missing `version=` line"); + assert_eq!(package_count, 6); } /// With `bundled-cli` on AND a supported target, `install_bundled_cli` @@ -246,6 +271,26 @@ fn install_bundled_cli_returns_extracted_path() { first, second, "install_bundled_cli must be idempotent across calls" ); + + #[cfg(feature = "bundled-in-process")] + { + let runtime_name = if cfg!(windows) { + "copilot_runtime.dll" + } else if cfg!(target_os = "macos") { + "libcopilot_runtime.dylib" + } else { + "libcopilot_runtime.so" + }; + let runtime = first + .parent() + .expect("install directory") + .join(runtime_name); + assert!( + runtime.is_file(), + "bundled runtime library was not installed: {}", + runtime.display() + ); + } } /// `install_bundled_cli` returns the same path the runtime resolver diff --git a/rust/tests/e2e.rs b/rust/tests/e2e.rs index 59b83ab27c..3a698abd18 100644 --- a/rust/tests/e2e.rs +++ b/rust/tests/e2e.rs @@ -31,12 +31,19 @@ mod elicitation; mod error_resilience; #[path = "e2e/event_fidelity.rs"] mod event_fidelity; +#[path = "e2e/github_telemetry.rs"] +mod github_telemetry; #[path = "e2e/hooks.rs"] mod hooks; #[path = "e2e/hooks_extended.rs"] mod hooks_extended; +#[cfg(feature = "bundled-in-process")] +#[path = "e2e/inprocess.rs"] +mod inprocess; #[path = "e2e/mcp_and_agents.rs"] mod mcp_and_agents; +#[path = "e2e/mcp_oauth.rs"] +mod mcp_oauth; #[path = "e2e/mode_empty.rs"] mod mode_empty; #[path = "e2e/mode_handlers.rs"] diff --git a/rust/tests/e2e/byok_bearer_token_provider.rs b/rust/tests/e2e/byok_bearer_token_provider.rs index fc3ef89d94..a7989d157f 100644 --- a/rust/tests/e2e/byok_bearer_token_provider.rs +++ b/rust/tests/e2e/byok_bearer_token_provider.rs @@ -142,6 +142,21 @@ async fn run_turn( #[tokio::test] async fn callback_token_is_applied_as_authorization_header() { + // The runtime's LLM inference provider slot is process-global and is never released + // when the registering connection disconnects (runtime `shared_api/llm_inference.rs`). + // Over the in-process transport all clients share this process's runtime, so once a + // BYOK provider is registered here and the client stops, the dangling registration + // routes every later model-inference request (list-models, tool-using turns, hooks, + // …) to the dead connection and hangs them. Registering a BYOK provider in-process + // therefore poisons the shared runtime for the rest of the suite. The BYOK bearer-token + // wiring is covered over stdio (a separate child process per test); the SDK-side + // request/response plumbing is transport-agnostic. + if super::support::skip_inprocess( + "registering a BYOK LLM inference provider is process-global in-process and is never \ + released on disconnect, poisoning later model-inference tests", + ) { + return; + } with_e2e_context_no_snapshot(|ctx| { Box::pin(async move { ctx.set_default_copilot_user(); @@ -189,6 +204,18 @@ async fn callback_token_is_applied_as_authorization_header() { #[tokio::test] async fn reacquires_a_fresh_token_for_each_request() { + // The runtime registers the LLM inference provider per connection and, by design, + // never releases the slot on disconnect (runtime `shared_api/llm_inference.rs`). Over + // the in-process transport every client shares this process's runtime, so a second + // provider-registering client is refused ("Another client is already the LLM + // inference provider"). The BYOK bearer-token behavior over the in-process transport + // is covered by `callback_token_is_applied_as_authorization_header`; this scenario's + // provider-dispatch logic is transport-agnostic and is covered over stdio. + if super::support::skip_inprocess( + "llmInference.setProvider is process-global in-process; a second provider client is refused", + ) { + return; + } with_e2e_context_no_snapshot(|ctx| { Box::pin(async move { ctx.set_default_copilot_user(); @@ -252,6 +279,16 @@ async fn reacquires_a_fresh_token_for_each_request() { #[tokio::test] async fn dispatches_token_acquisition_per_provider() { + // See `reacquires_a_fresh_token_for_each_request`: in-process, the process-global LLM + // inference provider registration is not released on disconnect, so this additional + // provider-registering client is refused. The BYOK transport path is covered in-process + // by `callback_token_is_applied_as_authorization_header`; the per-provider dispatch + // logic exercised here is transport-agnostic and covered over stdio. + if super::support::skip_inprocess( + "llmInference.setProvider is process-global in-process; a second provider client is refused", + ) { + return; + } with_e2e_context_no_snapshot(|ctx| { Box::pin(async move { ctx.set_default_copilot_user(); diff --git a/rust/tests/e2e/client.rs b/rust/tests/e2e/client.rs index 114e828ac9..6dd0f27acf 100644 --- a/rust/tests/e2e/client.rs +++ b/rust/tests/e2e/client.rs @@ -64,8 +64,7 @@ async fn should_get_authenticated_status() { Box::pin(async move { ctx.set_default_copilot_user(); let client = Client::start( - ctx.client_options() - .with_github_token(super::support::DEFAULT_TEST_TOKEN), + ctx.client_options_with_github_token(super::support::DEFAULT_TEST_TOKEN), ) .await .expect("start client"); @@ -85,8 +84,7 @@ async fn should_list_models_when_authenticated() { Box::pin(async move { ctx.set_default_copilot_user(); let client = Client::start( - ctx.client_options() - .with_github_token(super::support::DEFAULT_TEST_TOKEN), + ctx.client_options_with_github_token(super::support::DEFAULT_TEST_TOKEN), ) .await .expect("start client"); diff --git a/rust/tests/e2e/client_options.rs b/rust/tests/e2e/client_options.rs index 8b13789179..85ef835025 100644 --- a/rust/tests/e2e/client_options.rs +++ b/rust/tests/e2e/client_options.rs @@ -1 +1,487 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use github_copilot_sdk::canvas::CanvasDeclaration; +use github_copilot_sdk::rpc::{OpenCanvasInstance, RemoteSessionMode}; +use github_copilot_sdk::session_events::{ReasoningSummary, SessionLimitsConfig}; +use github_copilot_sdk::{ + CliProgram, Client, ClientOptions, ExtensionInfo, ProviderConfig, ResumeSessionConfig, + SessionConfig, SessionId, Transport, +}; +use serde::Deserialize; +use serde_json::{Value, json}; +use tempfile::TempDir; + +#[tokio::test] +async fn should_forward_advanced_session_creation_options_to_the_cli() { + let fake = FakeCli::new(); + let client = Client::start(fake.client_options("advanced-create-client-token")) + .await + .expect("start fake CLI client"); + + let config_dir = fake.path("config"); + let working_dir = fake.path("workspace"); + let extension_sdk_path = fake.path("extension-sdk"); + let session = client + .create_session( + SessionConfig::default() + .with_session_id("advanced-session-id") + .with_client_name("rust-sdk-e2e-client") + .with_model("claude-sonnet-4.5") + .with_reasoning_effort("low") + .with_reasoning_summary(ReasoningSummary::None) + .with_context_tier("long_context") + .with_config_directory(config_dir.clone()) + .with_enable_config_discovery(true) + .with_skip_embedding_retrieval(true) + .with_embedding_cache_storage("in-memory") + .with_organization_custom_instructions("organization guidance") + .with_enable_on_demand_instruction_discovery(true) + .with_enable_file_hooks(false) + .with_enable_host_git_operations(false) + .with_enable_session_store(false) + .with_enable_skills(false) + .with_working_directory(working_dir.clone()) + .with_streaming(true) + .with_include_sub_agent_streaming_events(false) + .with_available_tools(["read_file"]) + .with_excluded_tools(["bash"]) + .with_excluded_builtin_agents(["legacy-agent"]) + .with_enable_session_telemetry(false) + .with_enable_citations(true) + .with_session_limits(SessionLimitsConfig { + max_ai_credits: Some(42.0), + }) + .with_skip_custom_instructions(true) + .with_custom_agents_local_only(true) + .with_coauthor_enabled(false) + .with_manage_schedule_enabled(false) + .with_github_token("advanced-create-session-token") + .with_remote_session(RemoteSessionMode::Export) + .with_skill_directories([PathBuf::from("skills")]) + .with_plugin_directories([PathBuf::from("plugins")]) + .with_instruction_directories([PathBuf::from("instructions")]) + .with_disabled_skills(["disabled-skill"]) + .with_enable_mcp_apps(true) + .with_canvases([CanvasDeclaration::new( + "canvas", + "Canvas", + "Canvas description", + )]) + .with_request_canvas_renderer(true) + .with_request_extensions(true) + .with_extension_sdk_path(path_string(&extension_sdk_path)) + .with_extension_info(ExtensionInfo::new("github-app", "rust-e2e-extension")) + .with_exp_assignments(json!({ "feature": "enabled" })), + ) + .await + .expect("create session"); + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + + let create = fake.captured_request("session.create"); + let params = create.params.as_object().expect("session.create params"); + assert_json_values( + params, + [ + ("sessionId", json!("advanced-session-id")), + ("clientName", json!("rust-sdk-e2e-client")), + ("model", json!("claude-sonnet-4.5")), + ("reasoningEffort", json!("low")), + ("reasoningSummary", json!("none")), + ("contextTier", json!("long_context")), + ("configDir", json!(path_string(&config_dir))), + ("enableConfigDiscovery", json!(true)), + ("skipEmbeddingRetrieval", json!(true)), + ("embeddingCacheStorage", json!("in-memory")), + ( + "organizationCustomInstructions", + json!("organization guidance"), + ), + ("enableOnDemandInstructionDiscovery", json!(true)), + ("enableFileHooks", json!(false)), + ("enableHostGitOperations", json!(false)), + ("enableSessionStore", json!(false)), + ("enableSkills", json!(false)), + ("workingDirectory", json!(path_string(&working_dir))), + ("streaming", json!(true)), + ("includeSubAgentStreamingEvents", json!(false)), + ("enableSessionTelemetry", json!(false)), + ("enableCitations", json!(true)), + ("gitHubToken", json!("advanced-create-session-token")), + ("remoteSession", json!("export")), + ("requestMcpApps", json!(true)), + ("requestCanvasRenderer", json!(true)), + ("requestExtensions", json!(true)), + ("extensionSdkPath", json!(path_string(&extension_sdk_path))), + ("envValueMode", json!("direct")), + ], + ); + assert_eq!(params["availableTools"], json!(["read_file"])); + assert_eq!(params["excludedTools"], json!(["bash"])); + assert_eq!(params["excludedBuiltinAgents"], json!(["legacy-agent"])); + assert_eq!(params["skillDirectories"], json!(["skills"])); + assert_eq!(params["pluginDirectories"], json!(["plugins"])); + assert_eq!(params["instructionDirectories"], json!(["instructions"])); + assert_eq!(params["disabledSkills"], json!(["disabled-skill"])); + assert_eq!(params["sessionLimits"]["maxAiCredits"], json!(42)); + assert_eq!( + params["extensionInfo"], + json!({ "source": "github-app", "name": "rust-e2e-extension" }) + ); + assert_eq!(params["canvases"][0]["id"], json!("canvas")); + assert_eq!(params["canvases"][0]["displayName"], json!("Canvas")); + assert_eq!( + params["canvases"][0]["description"], + json!("Canvas description") + ); + assert_eq!(params["expAssignments"]["feature"], json!("enabled")); + + let update = fake.captured_request("session.options.update"); + let update_params = update.params.as_object().expect("options update params"); + assert_json_values( + update_params, + [ + ("sessionId", json!("advanced-session-id")), + ("skipCustomInstructions", json!(true)), + ("customAgentsLocalOnly", json!(true)), + ("coauthorEnabled", json!(false)), + ("manageScheduleEnabled", json!(false)), + ], + ); +} + +#[tokio::test] +async fn should_forward_singular_provider_configuration_on_session_creation() { + let fake = FakeCli::new(); + let client = Client::start(fake.client_options("provider-client-token")) + .await + .expect("start fake CLI client"); + + let session = client + .create_session( + SessionConfig::default().with_provider( + ProviderConfig::new("https://models.example.test/v1") + .with_provider_type("openai") + .with_wire_api("responses") + .with_transport("websockets") + .with_api_key("provider-key") + .with_model_id("base-model") + .with_wire_model("wire-model") + .with_max_prompt_tokens(1000) + .with_max_output_tokens(2000) + .with_headers(HashMap::from([( + "x-provider".to_string(), + "rust".to_string(), + )])), + ), + ) + .await + .expect("create session"); + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + + let create = fake.captured_request("session.create"); + let provider = create.params["provider"] + .as_object() + .expect("provider params"); + assert_json_values( + provider, + [ + ("type", json!("openai")), + ("wireApi", json!("responses")), + ("transport", json!("websockets")), + ("baseUrl", json!("https://models.example.test/v1")), + ("apiKey", json!("provider-key")), + ("modelId", json!("base-model")), + ("wireModel", json!("wire-model")), + ("maxPromptTokens", json!(1000)), + ("maxOutputTokens", json!(2000)), + ], + ); + assert_eq!(provider["headers"]["x-provider"], json!("rust")); +} + +#[tokio::test] +async fn should_forward_advanced_session_resume_options_to_the_cli() { + let fake = FakeCli::new(); + let client = Client::start(fake.client_options("advanced-resume-client-token")) + .await + .expect("start fake CLI client"); + + let config_dir = fake.path("resume-config"); + let working_dir = fake.path("resume-workspace"); + let extension_sdk_path = fake.path("resume-extension-sdk"); + let session = client + .resume_session( + ResumeSessionConfig::new(SessionId::from("resume-session-id")) + .with_model("gpt-5-mini") + .with_reasoning_effort("low") + .with_reasoning_summary(ReasoningSummary::None) + .with_context_tier("long_context") + .with_working_directory(working_dir.clone()) + .with_config_directory(config_dir.clone()) + .with_enable_config_discovery(false) + .with_suppress_resume_event(true) + .with_continue_pending_work(false) + .with_streaming(true) + .with_include_sub_agent_streaming_events(false) + .with_github_token("advanced-resume-session-token") + .with_canvases([CanvasDeclaration::new( + "resume-canvas", + "Resume Canvas", + "Resume canvas description", + )]) + .with_open_canvases([OpenCanvasInstance { + canvas_id: "resume-canvas".to_string(), + extension_id: "github-app/rust-e2e-extension".to_string(), + extension_name: None, + icon: None, + input: Some(json!({ "value": "from-resume" })), + instance_id: "resume-instance".to_string(), + status: None, + title: None, + url: None, + }]) + .with_request_canvas_renderer(true) + .with_request_extensions(true) + .with_extension_sdk_path(path_string(&extension_sdk_path)) + .with_extension_info(ExtensionInfo::new("github-app", "rust-e2e-extension")) + .with_skip_custom_instructions(true) + .with_custom_agents_local_only(true) + .with_coauthor_enabled(false) + .with_manage_schedule_enabled(false) + .with_exp_assignments(json!({ "resumeFeature": "enabled" })), + ) + .await + .expect("resume session"); + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + + let resume = fake.captured_request("session.resume"); + let params = resume.params.as_object().expect("session.resume params"); + assert_json_values( + params, + [ + ("sessionId", json!("resume-session-id")), + ("model", json!("gpt-5-mini")), + ("reasoningEffort", json!("low")), + ("reasoningSummary", json!("none")), + ("contextTier", json!("long_context")), + ("workingDirectory", json!(path_string(&working_dir))), + ("configDir", json!(path_string(&config_dir))), + ("enableConfigDiscovery", json!(false)), + ("disableResume", json!(true)), + ("continuePendingWork", json!(false)), + ("streaming", json!(true)), + ("includeSubAgentStreamingEvents", json!(false)), + ("gitHubToken", json!("advanced-resume-session-token")), + ("requestCanvasRenderer", json!(true)), + ("requestExtensions", json!(true)), + ("extensionSdkPath", json!(path_string(&extension_sdk_path))), + ("envValueMode", json!("direct")), + ], + ); + assert_eq!( + params["openCanvases"][0]["canvasId"], + json!("resume-canvas") + ); + assert_eq!( + params["openCanvases"][0]["extensionId"], + json!("github-app/rust-e2e-extension") + ); + assert_eq!( + params["openCanvases"][0]["instanceId"], + json!("resume-instance") + ); + assert_eq!( + params["extensionInfo"], + json!({ "source": "github-app", "name": "rust-e2e-extension" }) + ); + assert_eq!(params["expAssignments"]["resumeFeature"], json!("enabled")); + + let update = fake.captured_request("session.options.update"); + let update_params = update.params.as_object().expect("options update params"); + assert_json_values( + update_params, + [ + ("sessionId", json!("resume-session-id")), + ("skipCustomInstructions", json!(true)), + ("customAgentsLocalOnly", json!(true)), + ("coauthorEnabled", json!(false)), + ("manageScheduleEnabled", json!(false)), + ], + ); +} + +struct FakeCli { + _dir: TempDir, + script_path: PathBuf, + capture_path: PathBuf, + work_dir: PathBuf, +} + +impl FakeCli { + fn new() -> Self { + let dir = tempfile::tempdir().expect("create fake CLI temp dir"); + let script_path = dir.path().join("fake-cli.js"); + let capture_path = dir.path().join("fake-cli-capture.json"); + let work_dir = dir.path().join("cwd"); + std::fs::create_dir(&work_dir).expect("create fake CLI cwd"); + std::fs::write(&script_path, FAKE_STDIO_CLI_SCRIPT).expect("write fake CLI script"); + Self { + _dir: dir, + script_path, + capture_path, + work_dir, + } + } + + fn client_options(&self, token: &str) -> ClientOptions { + ClientOptions::new() + .with_program(CliProgram::Path(PathBuf::from("node"))) + .with_prefix_args([self.script_path.as_os_str().to_owned()]) + .with_cwd(&self.work_dir) + .with_extra_args([ + "--capture-file".to_string(), + self.capture_path.to_string_lossy().into_owned(), + ]) + .with_github_token(token) + .with_use_logged_in_user(false) + .with_transport(Transport::Stdio) + } + + fn path(&self, name: &str) -> PathBuf { + let path = self.work_dir.join(name); + std::fs::create_dir_all(&path).expect("create fake CLI test path"); + path + } + + fn captured_request(&self, method: &str) -> CapturedRequest { + let capture = self.capture(); + capture + .requests + .iter() + .find(|request| request.method == method) + .cloned() + .unwrap_or_else(|| panic!("expected {method} request in {capture:?}")) + } + + fn capture(&self) -> CapturedCli { + let text = std::fs::read_to_string(&self.capture_path).expect("read fake CLI capture file"); + serde_json::from_str(&text).expect("parse fake CLI capture file") + } +} + +#[derive(Debug, Deserialize)] +struct CapturedCli { + requests: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +struct CapturedRequest { + method: String, + #[serde(default)] + params: Value, +} + +fn assert_json_values<'a>( + object: &serde_json::Map, + expected: impl IntoIterator, +) { + for (key, expected_value) in expected { + assert_eq!( + object.get(key), + Some(&expected_value), + "unexpected value for key {key} in {object:?}" + ); + } +} + +fn path_string(path: &std::path::Path) -> String { + path.to_string_lossy().into_owned() +} + +const FAKE_STDIO_CLI_SCRIPT: &str = r#" +const fs = require("fs"); + +const captureIndex = process.argv.indexOf("--capture-file"); +const captureFile = captureIndex >= 0 ? process.argv[captureIndex + 1] : undefined; +const requests = []; + +function saveCapture() { + if (!captureFile) { + return; + } + fs.writeFileSync(captureFile, JSON.stringify({ + requests, + args: process.argv.slice(2), + cwd: process.cwd(), + env: { + COPILOT_SDK_AUTH_TOKEN: process.env.COPILOT_SDK_AUTH_TOKEN, + }, + })); +} + +saveCapture(); + +let buffer = Buffer.alloc(0); +process.stdin.on("data", chunk => { + buffer = Buffer.concat([buffer, chunk]); + processBuffer(); +}); +process.stdin.resume(); + +function processBuffer() { + while (true) { + const headerEnd = buffer.indexOf("\r\n\r\n"); + if (headerEnd < 0) return; + const header = buffer.subarray(0, headerEnd).toString("utf8"); + const match = /Content-Length:\s*(\d+)/i.exec(header); + if (!match) throw new Error("Missing Content-Length header"); + const length = Number(match[1]); + const bodyStart = headerEnd + 4; + const bodyEnd = bodyStart + length; + if (buffer.length < bodyEnd) return; + const body = buffer.subarray(bodyStart, bodyEnd).toString("utf8"); + buffer = buffer.subarray(bodyEnd); + handleMessage(JSON.parse(body)); + } +} + +function handleMessage(message) { + if (!Object.prototype.hasOwnProperty.call(message, "id")) { + return; + } + requests.push({ method: message.method, params: message.params }); + saveCapture(); + if (message.method === "connect") { + writeResponse(message.id, { ok: true, protocolVersion: 3, version: "fake" }); + return; + } + if (message.method === "ping") { + writeResponse(message.id, { message: "pong", protocolVersion: 3, timestamp: Date.now() }); + return; + } + if (message.method === "session.create") { + const sessionId = (message.params && message.params.sessionId) || "fake-session"; + writeResponse(message.id, { sessionId, workspacePath: null, capabilities: null }); + return; + } + if (message.method === "session.resume") { + const sessionId = (message.params && message.params.sessionId) || "fake-session"; + writeResponse(message.id, { sessionId, workspacePath: null, capabilities: null, openCanvases: [] }); + return; + } + if (message.method === "session.options.update") { + writeResponse(message.id, { success: true }); + return; + } + writeResponse(message.id, {}); +} + +function writeResponse(id, result) { + const body = JSON.stringify({ jsonrpc: "2.0", id, result }); + process.stdout.write("Content-Length: " + Buffer.byteLength(body, "utf8") + "\r\n\r\n" + body); +} +"#; diff --git a/rust/tests/e2e/copilot_request_handler.rs b/rust/tests/e2e/copilot_request_handler.rs index 6ca99393bf..46b4e510cd 100644 --- a/rust/tests/e2e/copilot_request_handler.rs +++ b/rust/tests/e2e/copilot_request_handler.rs @@ -502,6 +502,9 @@ async fn start_ws_upstream(counters: HandlerCounters) -> String { #[tokio::test] async fn services_http_and_websocket_via_handler() { + if super::support::skip_inprocess("LLM inference providers are process-global in-process") { + return; + } with_e2e_context_no_snapshot(|ctx| { Box::pin(async move { ctx.set_default_copilot_user(); @@ -572,16 +575,25 @@ async fn services_http_and_websocket_via_handler() { #[derive(Default)] struct RecordingHandler { - records: std::sync::Mutex)>>, + records: std::sync::Mutex>, +} + +#[derive(Clone)] +struct InterceptedRequest { + url: String, + session_id: Option, + agent_id: Option, + parent_agent_id: Option, + interaction_type: Option, } impl RecordingHandler { - fn inference_records(&self) -> Vec<(String, Option)> { + fn inference_records(&self) -> Vec { self.records .lock() .unwrap() .iter() - .filter(|(url, _)| is_inference_url(url)) + .filter(|record| is_inference_url(&record.url)) .cloned() .collect() } @@ -594,10 +606,13 @@ impl CopilotRequestHandler for RecordingHandler { request: CopilotHttpRequest, ctx: &CopilotRequestContext, ) -> Result { - self.records - .lock() - .unwrap() - .push((request.url.clone(), ctx.session_id.clone())); + self.records.lock().unwrap().push(InterceptedRequest { + url: request.url.clone(), + session_id: ctx.session_id.clone(), + agent_id: ctx.agent_id.clone(), + parent_agent_id: ctx.parent_agent_id.clone(), + interaction_type: ctx.interaction_type.clone(), + }); if is_inference_url(&request.url) { Ok(synth_inference_response( &request.url, @@ -612,6 +627,9 @@ impl CopilotRequestHandler for RecordingHandler { #[tokio::test] async fn threads_session_id_into_inference() { + if super::support::skip_inprocess("LLM inference providers are process-global in-process") { + return; + } with_e2e_context_no_snapshot(|ctx| { Box::pin(async move { ctx.set_default_copilot_user(); @@ -632,12 +650,13 @@ async fn threads_session_id_into_inference() { !inference.is_empty(), "expected at least one intercepted inference request" ); - for (_, session_id) in &inference { + for record in &inference { assert_eq!( - session_id.as_deref(), + record.session_id.as_deref(), Some(capi_session_id.as_str()), "CAPI inference request must carry the session id" ); + assert_agent_metadata(record); } assert!( assistant_text(&result).contains("OK from the synthetic"), @@ -671,12 +690,13 @@ async fn threads_session_id_into_inference() { inference.len() > before, "expected at least one intercepted BYOK inference request" ); - for (_, session_id) in &inference[before..] { + for record in &inference[before..] { assert_eq!( - session_id.as_deref(), + record.session_id.as_deref(), Some(byok_session_id.as_str()), "BYOK inference request must carry the session id" ); + assert_agent_metadata(record); } assert_ne!( byok_session_id, capi_session_id, @@ -694,6 +714,26 @@ async fn threads_session_id_into_inference() { .await; } +fn assert_agent_metadata(record: &InterceptedRequest) { + assert!( + record.agent_id.as_deref().is_some_and(|id| !id.is_empty()), + "inference request must carry an agent id" + ); + if let Some(parent_agent_id) = record.parent_agent_id.as_deref() { + assert!( + !parent_agent_id.is_empty(), + "parent agent id must be non-empty when present" + ); + } + assert!( + record + .interaction_type + .as_deref() + .is_some_and(|kind| !kind.is_empty()), + "inference request must carry an interaction type" + ); +} + // --------------------------------------------------------------------------- // Scenario 3a: errors — a handler that returns `Err` on an inference request // surfaces a transport error rather than hanging the turn. @@ -723,6 +763,9 @@ impl CopilotRequestHandler for ThrowingHandler { #[tokio::test] async fn surfaces_handler_errors() { + if super::support::skip_inprocess("LLM inference providers are process-global in-process") { + return; + } with_e2e_context_no_snapshot(|ctx| { Box::pin(async move { ctx.set_default_copilot_user(); @@ -789,6 +832,9 @@ impl CopilotRequestHandler for CancellingHandler { #[tokio::test] async fn observes_runtime_driven_cancel() { + if super::support::skip_inprocess("LLM inference providers are process-global in-process") { + return; + } with_e2e_context_no_snapshot(|ctx| { Box::pin(async move { ctx.set_default_copilot_user(); diff --git a/rust/tests/e2e/github_telemetry.rs b/rust/tests/e2e/github_telemetry.rs new file mode 100644 index 0000000000..2047ee34ff --- /dev/null +++ b/rust/tests/e2e/github_telemetry.rs @@ -0,0 +1,65 @@ +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use github_copilot_sdk::github_telemetry::GitHubTelemetryNotification; +use github_copilot_sdk::handler::ApproveAllHandler; +use github_copilot_sdk::{Client, SessionConfig}; + +use super::support::{DEFAULT_TEST_TOKEN, with_e2e_context_no_snapshot}; + +#[tokio::test] +async fn should_forward_github_telemetry_on_session_create() { + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + + let notifications = Arc::new(Mutex::new(Vec::::new())); + let collected = notifications.clone(); + let client = Client::start(ctx.client_options().with_on_github_telemetry(move |n| { + collected.lock().unwrap().push(n); + })) + .await + .expect("start client"); + let session = client + .create_session( + SessionConfig::default() + .with_github_token(DEFAULT_TEST_TOKEN) + .with_permission_handler(Arc::new(ApproveAllHandler)), + ) + .await + .expect("create session"); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + if !notifications.lock().unwrap().is_empty() { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "timed out waiting for github telemetry notification" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } + + { + let notifications = notifications.lock().unwrap(); + assert!(!notifications.is_empty()); + let first = notifications + .first() + .expect("github telemetry notification"); + assert!( + first + .session_id + .as_deref() + .is_some_and(|session_id| !session_id.is_empty()) + ); + let _: bool = first.restricted; + assert!(!first.event.kind.is_empty()); + } + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }) + .await; +} diff --git a/rust/tests/e2e/hooks_extended.rs b/rust/tests/e2e/hooks_extended.rs index ef53987fff..ab93a0c3cd 100644 --- a/rust/tests/e2e/hooks_extended.rs +++ b/rust/tests/e2e/hooks_extended.rs @@ -36,7 +36,7 @@ async fn should_invoke_onsessionstart_hook_on_new_session() { session.send_and_wait("Say hi").await.expect("send"); let input = recv_with_timeout(&mut rx, "sessionStart hook").await; assert_eq!(input.source, "new"); - assert!(input.timestamp > 0); + assert!(input.timestamp > 0.0); assert!(!input.working_directory.as_os_str().is_empty()); session.disconnect().await.expect("disconnect session"); @@ -68,7 +68,7 @@ async fn should_invoke_onuserpromptsubmitted_hook_when_sending_a_message() { session.send_and_wait("Say hello").await.expect("send"); let input = recv_with_timeout(&mut rx, "userPromptSubmitted hook").await; assert!(input.prompt.contains("Say hello")); - assert!(input.timestamp > 0); + assert!(input.timestamp > 0.0); assert!(!input.working_directory.as_os_str().is_empty()); session.disconnect().await.expect("disconnect session"); @@ -100,7 +100,7 @@ async fn should_invoke_onsessionend_hook_when_session_is_disconnected() { session.send_and_wait("Say hi").await.expect("send"); session.disconnect().await.expect("disconnect session"); let input = recv_with_timeout(&mut rx, "sessionEnd hook").await; - assert!(input.timestamp > 0); + assert!(input.timestamp > 0.0); assert!(!input.working_directory.as_os_str().is_empty()); client.stop().await.expect("stop client"); @@ -129,7 +129,9 @@ async fn should_invoke_onerroroccurred_hook_when_error_occurs() { .expect("create session"); session.send_and_wait("Say hi").await.expect("send"); - assert!(rx.try_recv().is_err()); + rx.try_recv() + .map(drop) + .expect_err("errorOccurred hook should not run"); session.disconnect().await.expect("disconnect session"); client.stop().await.expect("stop client"); @@ -235,7 +237,7 @@ async fn should_invoke_sessionend_hook() { session.send_and_wait("Say bye").await.expect("send"); session.disconnect().await.expect("disconnect session"); let input = recv_with_timeout(&mut rx, "sessionEnd hook").await; - assert!(input.timestamp > 0); + assert!(input.timestamp > 0.0); client.stop().await.expect("stop client"); }) @@ -267,7 +269,9 @@ async fn should_register_erroroccurred_hook() { .expect("create session"); session.send_and_wait("Say hi").await.expect("send"); - assert!(rx.try_recv().is_err()); + rx.try_recv() + .map(drop) + .expect_err("errorOccurred hook should not run"); session.disconnect().await.expect("disconnect session"); client.stop().await.expect("stop client"); @@ -397,7 +401,10 @@ async fn should_invoke_posttoolusefailure_hook_for_failed_tool_result() { .expect("assistant message"); let input = recv_with_timeout(&mut failure_rx, "postToolUseFailure hook").await; - assert!(post_rx.try_recv().is_err()); + post_rx + .try_recv() + .map(drop) + .expect_err("postToolUse hook should not run"); assert_eq!(input.tool_name, "view"); assert!(input.error.contains("does not exist")); assert!( @@ -405,7 +412,7 @@ async fn should_invoke_posttoolusefailure_hook_for_failed_tool_result() { .as_str() .is_some_and(|path| path.contains("missing.txt")) ); - assert!(input.timestamp > 0); + assert!(input.timestamp > 0.0); assert!(!input.working_directory.as_os_str().is_empty()); assert!( assistant_message_content(&answer).contains("HOOK_FAILURE_GUIDANCE_APPLIED") diff --git a/rust/tests/e2e/inprocess.rs b/rust/tests/e2e/inprocess.rs new file mode 100644 index 0000000000..0c183a27df --- /dev/null +++ b/rust/tests/e2e/inprocess.rs @@ -0,0 +1,25 @@ +use super::support::with_e2e_context; + +/// Starts an in-process client, performs a round-trip, and stops cleanly. +/// Fails hard if the in-process runtime library cannot be loaded. +#[tokio::test] +async fn should_start_ping_and_stop_inprocess_client() { + with_e2e_context("client", "should_start_ping_and_stop_stdio_client", |ctx| { + Box::pin(async move { + let client = ctx.start_inprocess_client().await; + + let response = client + .ping(Some("hello from rust in-process")) + .await + .expect("ping over in-process FFI transport"); + assert_eq!(response.message, "pong: hello from rust in-process"); + assert!(!response.timestamp.is_empty()); + + let status = client.get_status().await.expect("get status"); + assert!(status.protocol_version > 0); + + client.stop().await.expect("stop in-process client"); + }) + }) + .await; +} diff --git a/rust/tests/e2e/mcp_oauth.rs b/rust/tests/e2e/mcp_oauth.rs new file mode 100644 index 0000000000..fb202536c7 --- /dev/null +++ b/rust/tests/e2e/mcp_oauth.rs @@ -0,0 +1,574 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::process::Stdio; +use std::sync::Arc; + +use async_trait::async_trait; +use github_copilot_sdk::handler::{McpAuthHandler, McpAuthRequest, McpAuthResult}; +use github_copilot_sdk::rpc::{McpAppsCallToolRequest, McpListToolsRequest}; +use github_copilot_sdk::session::Session; +use github_copilot_sdk::session_events::{McpOauthRequestReason, McpServerStatus}; +use github_copilot_sdk::{IndexMap, McpHttpServerConfig, McpServerConfig, RequestId, SessionId}; +use parking_lot::Mutex; +use serde::Deserialize; +use serde_json::Value; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::{Child, Command}; +use tokio::sync::Notify; + +use super::support::{wait_for_condition, with_e2e_context_no_snapshot}; + +const EXPECTED_TOKEN: &str = "sdk-host-token"; +const REFRESH_TOKEN: &str = "sdk-host-token-refresh"; +const UPSCOPE_TOKEN: &str = "sdk-host-token-upscope"; +const REAUTH_TOKEN: &str = "sdk-host-token-reauth"; + +#[tokio::test] +async fn should_satisfy_mcp_oauth_using_host_provided_token() { + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let mut oauth_server = OAuthMcpServer::start( + ctx.repo_root() + .join("test/harness/test-mcp-oauth-server.mjs"), + ) + .await; + let server_name = "oauth-protected-mcp"; + let handler = Arc::new(TokenAuthHandler::default()); + let client = ctx.start_client().await; + let session = client + .create_session( + ctx.approve_all_session_config() + .with_mcp_auth_handler(handler.clone()) + .with_mcp_servers(IndexMap::from([( + server_name.to_string(), + McpServerConfig::Http(McpHttpServerConfig { + tools: Some(vec!["*".to_string()]), + timeout: None, + url: format!("{}/mcp", oauth_server.url), + headers: HashMap::new(), + }), + )])), + ) + .await + .expect("create session"); + + wait_for_mcp_server_status(&session, server_name, McpServerStatus::Connected).await; + let tools = session + .rpc() + .mcp() + .list_tools(McpListToolsRequest { + server_name: server_name.to_string(), + }) + .await + .expect("list MCP tools"); + assert!(tools.tools.iter().any(|tool| tool.name == "whoami")); + + let request = handler + .request + .lock() + .clone() + .expect("MCP auth handler should be invoked"); + assert_eq!(request.server_name, server_name); + assert_eq!(request.server_url, format!("{}/mcp", oauth_server.url)); + assert_eq!(request.reason, McpOauthRequestReason::Initial); + let www_authenticate = request + .www_authenticate_params + .expect("WWW-Authenticate params"); + assert_eq!( + www_authenticate.resource_metadata_url, + Some(format!( + "{}/.well-known/oauth-protected-resource", + oauth_server.url + )) + ); + assert_eq!(www_authenticate.scope.as_deref(), Some("mcp.read")); + assert_eq!(www_authenticate.error.as_deref(), Some("invalid_token")); + let metadata: Value = serde_json::from_str( + request + .resource_metadata + .as_deref() + .expect("resource metadata"), + ) + .expect("parse resource metadata"); + assert_eq!(metadata["resource"], format!("{}/mcp", oauth_server.url)); + + let requests = oauth_server.requests().await; + assert!( + requests + .iter() + .any(|request| request.authorization.is_none()) + ); + assert!(requests.iter().any(|request| { + request.authorization.as_deref() == Some(&format!("Bearer {EXPECTED_TOKEN}")) + })); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + oauth_server.stop().await; + }) + }) + .await; +} + +#[tokio::test] +async fn should_request_replacement_tokens_across_mcp_oauth_lifecycle() { + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let mut oauth_server = OAuthMcpServer::start( + ctx.repo_root() + .join("test/harness/test-mcp-oauth-server.mjs"), + ) + .await; + let server_name = "oauth-lifecycle-mcp"; + let handler = Arc::new(LifecycleAuthHandler::default()); + let client = ctx.start_client().await; + let session = client + .create_session( + ctx.approve_all_session_config() + .with_enable_mcp_apps(true) + .with_mcp_auth_handler(handler.clone()) + .with_mcp_servers(IndexMap::from([( + server_name.to_string(), + McpServerConfig::Http(McpHttpServerConfig { + tools: Some(vec!["*".to_string()]), + timeout: None, + url: format!("{}/mcp", oauth_server.url), + headers: HashMap::new(), + }), + )])), + ) + .await + .expect("create session"); + + wait_for_mcp_server_status(&session, server_name, McpServerStatus::Connected).await; + call_whoami(&session, server_name, "refresh").await; + call_whoami(&session, server_name, "upscope").await; + call_whoami(&session, server_name, "reauth").await; + + assert_eq!( + handler.reasons.lock().as_slice(), + [ + McpOauthRequestReason::Initial, + McpOauthRequestReason::Refresh, + McpOauthRequestReason::Upscope, + McpOauthRequestReason::Refresh, + McpOauthRequestReason::Reauth, + ] + ); + + let requests = oauth_server.requests().await; + assert!(requests.iter().any(|request| { + request.authorization.as_deref() == Some(&format!("Bearer {REFRESH_TOKEN}")) + })); + assert!(requests.iter().any(|request| { + request.authorization.as_deref() == Some(&format!("Bearer {UPSCOPE_TOKEN}")) + })); + assert!(requests.iter().any(|request| { + request.authorization.as_deref() == Some(&format!("Bearer {REAUTH_TOKEN}")) + })); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + oauth_server.stop().await; + }) + }) + .await; +} + +#[tokio::test] +async fn should_cancel_pending_mcp_oauth_request() { + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let mut oauth_server = OAuthMcpServer::start( + ctx.repo_root() + .join("test/harness/test-mcp-oauth-server.mjs"), + ) + .await; + let server_name = "oauth-cancelled-mcp"; + let handler = Arc::new(CancelAuthHandler::default()); + let client = ctx.start_client().await; + let session = client + .create_session( + ctx.approve_all_session_config() + .with_mcp_auth_handler(handler.clone()) + .with_mcp_servers(IndexMap::from([( + server_name.to_string(), + McpServerConfig::Http(McpHttpServerConfig { + tools: Some(vec!["*".to_string()]), + timeout: None, + url: format!("{}/mcp", oauth_server.url), + headers: HashMap::new(), + }), + )])), + ) + .await + .expect("create session"); + + wait_for_mcp_server_status(&session, server_name, McpServerStatus::NeedsAuth).await; + + // The MCP connection is kicked off by session.create, but the SDK only registers its + // `mcp.oauth_required` event interest once create returns. If the server's initial 401 + // wins that race, the runtime records `needs-auth` WITHOUT invoking the host callback, + // so `handler.request` is briefly `None` even after `needs-auth` is observed. A later + // auth retry (now that interest is registered) invokes the callback with the same + // `Initial` reason. Wait for the callback rather than sampling it the instant + // `needs-auth` first appears, which is what made this test flaky. + wait_for_condition("MCP OAuth request reaching the host callback", || async { + handler.request.lock().is_some() + }) + .await; + + let request = handler + .request + .lock() + .clone() + .expect("MCP auth handler should be invoked"); + assert_eq!(request.server_name, server_name); + assert_eq!(request.reason, McpOauthRequestReason::Initial); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + oauth_server.stop().await; + }) + }) + .await; +} + +#[tokio::test] +async fn should_resolve_pending_mcp_oauth_request_through_rpc() { + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let mut oauth_server = OAuthMcpServer::start( + ctx.repo_root() + .join("test/harness/test-mcp-oauth-server.mjs"), + ) + .await; + let server_name = "oauth-direct-rpc-mcp"; + let observed_request = Arc::new(Mutex::new(None)); + let request_observed = Arc::new(Notify::new()); + let release_handler = Arc::new(Notify::new()); + let handler = Arc::new(BlockingAuthHandler { + request: observed_request.clone(), + request_observed: request_observed.clone(), + release: release_handler.clone(), + }); + let client = ctx.start_client().await; + let session = client + .create_session( + ctx.approve_all_session_config() + .with_enable_mcp_apps(true) + .with_mcp_auth_handler(handler) + .with_mcp_servers(IndexMap::from([( + server_name.to_string(), + McpServerConfig::Http(McpHttpServerConfig { + tools: Some(vec!["*".to_string()]), + timeout: None, + url: format!("{}/mcp", oauth_server.url), + headers: HashMap::new(), + }), + )])), + ) + .await + .expect("create session"); + + let connected = + wait_for_mcp_server_status(&session, server_name, McpServerStatus::Connected); + tokio::pin!(connected); + tokio::select! { + () = request_observed.notified() => {} + () = &mut connected => panic!("MCP server connected before OAuth request was observed"), + } + let request = observed_request + .lock() + .clone() + .expect("MCP auth request"); + assert_eq!(request.server_name, server_name); + assert_eq!(request.server_url, format!("{}/mcp", oauth_server.url)); + assert_eq!(request.reason, McpOauthRequestReason::Initial); + let www_authenticate = request + .www_authenticate_params + .as_ref() + .expect("WWW-Authenticate params"); + assert_eq!( + www_authenticate.resource_metadata_url, + Some(format!( + "{}/.well-known/oauth-protected-resource", + oauth_server.url + )) + ); + assert_eq!(www_authenticate.scope.as_deref(), Some("mcp.read")); + assert_eq!(www_authenticate.error.as_deref(), Some("invalid_token")); + + let handled = session + .rpc() + .mcp() + .oauth() + .handle_pending_request(github_copilot_sdk::rpc::McpOauthHandlePendingRequest { + request_id: request.request_id, + result: github_copilot_sdk::rpc::McpOauthPendingRequestResponse::Token( + github_copilot_sdk::rpc::McpOauthPendingRequestResponseToken { + access_token: EXPECTED_TOKEN.to_string(), + expires_in: Some(3600), + kind: github_copilot_sdk::rpc::McpOauthPendingRequestResponseTokenKind::Token, + token_type: Some("Bearer".to_string()), + }, + ), + }) + .await + .expect("handle pending MCP OAuth request"); + assert!(handled.success); + + release_handler.notify_one(); + connected.await; + let tools = session + .rpc() + .mcp() + .list_tools(McpListToolsRequest { + server_name: server_name.to_string(), + }) + .await + .expect("list MCP tools"); + assert!(tools.tools.iter().any(|tool| tool.name == "whoami")); + let requests = oauth_server.requests().await; + assert!( + requests + .iter() + .any(|request| { + request.authorization.as_deref() == Some(&format!("Bearer {EXPECTED_TOKEN}")) + }) + ); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + oauth_server.stop().await; + }) + }) + .await; +} + +#[derive(Default)] +struct TokenAuthHandler { + request: Mutex>, +} + +#[async_trait] +impl McpAuthHandler for TokenAuthHandler { + async fn handle( + &self, + _session_id: SessionId, + request_id: RequestId, + request: McpAuthRequest, + ) -> McpAuthResult { + assert_eq!(request.request_id, request_id); + *self.request.lock() = Some(request); + McpAuthResult::Token { + access_token: EXPECTED_TOKEN.to_string(), + token_type: Some("Bearer".to_string()), + expires_in: Some(3600), + } + } +} + +#[derive(Default)] +struct LifecycleAuthHandler { + reasons: Mutex>, + refresh_count: Mutex, +} + +#[async_trait] +impl McpAuthHandler for LifecycleAuthHandler { + async fn handle( + &self, + _session_id: SessionId, + request_id: RequestId, + request: McpAuthRequest, + ) -> McpAuthResult { + assert_eq!(request.request_id, request_id); + let reason = request.reason.clone(); + self.reasons.lock().push(reason.clone()); + let token = match reason { + McpOauthRequestReason::Refresh => { + let www_authenticate = request + .www_authenticate_params + .as_ref() + .expect("refresh WWW-Authenticate params"); + assert_eq!(www_authenticate.resource_metadata_url, None); + assert_eq!(www_authenticate.error.as_deref(), Some("invalid_token")); + let mut refresh_count = self.refresh_count.lock(); + *refresh_count += 1; + if *refresh_count > 1 { + return McpAuthResult::Cancelled; + } + REFRESH_TOKEN + } + McpOauthRequestReason::Upscope => { + let www_authenticate = request + .www_authenticate_params + .as_ref() + .expect("upscope WWW-Authenticate params"); + assert!( + www_authenticate + .resource_metadata_url + .as_deref() + .is_some_and(|url| url.ends_with("/.well-known/oauth-protected-resource")) + ); + assert_eq!(www_authenticate.scope.as_deref(), Some("mcp.write")); + assert_eq!( + www_authenticate.error.as_deref(), + Some("insufficient_scope") + ); + UPSCOPE_TOKEN + } + McpOauthRequestReason::Reauth => REAUTH_TOKEN, + _ => EXPECTED_TOKEN, + }; + McpAuthResult::Token { + access_token: token.to_string(), + token_type: None, + expires_in: None, + } + } +} + +#[derive(Default)] +struct CancelAuthHandler { + request: Mutex>, +} + +#[async_trait] +impl McpAuthHandler for CancelAuthHandler { + async fn handle( + &self, + _session_id: SessionId, + request_id: RequestId, + request: McpAuthRequest, + ) -> McpAuthResult { + assert_eq!(request.request_id, request_id); + *self.request.lock() = Some(request); + McpAuthResult::Cancelled + } +} + +struct BlockingAuthHandler { + request: Arc>>, + request_observed: Arc, + release: Arc, +} + +#[async_trait] +impl McpAuthHandler for BlockingAuthHandler { + async fn handle( + &self, + _session_id: SessionId, + request_id: RequestId, + request: McpAuthRequest, + ) -> McpAuthResult { + assert_eq!(request.request_id, request_id); + *self.request.lock() = Some(request); + self.request_observed.notify_one(); + self.release.notified().await; + McpAuthResult::Token { + access_token: EXPECTED_TOKEN.to_string(), + token_type: Some("Bearer".to_string()), + expires_in: Some(3600), + } + } +} + +#[derive(Deserialize)] +struct OAuthMcpRequest { + authorization: Option, +} + +struct OAuthMcpServer { + child: Child, + url: String, +} + +impl OAuthMcpServer { + async fn start(script: PathBuf) -> Self { + let mut child = Command::new("node") + .arg(script) + .env("EXPECTED_TOKEN", EXPECTED_TOKEN) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .expect("start OAuth MCP server"); + let stdout = child.stdout.take().expect("OAuth MCP stdout"); + let mut lines = BufReader::new(stdout).lines(); + let line = tokio::time::timeout(std::time::Duration::from_secs(10), lines.next_line()) + .await + .expect("OAuth MCP server startup timeout") + .expect("read OAuth MCP startup line") + .expect("OAuth MCP server stdout closed"); + let url = line + .strip_prefix("Listening: ") + .unwrap_or_else(|| panic!("unexpected OAuth MCP startup line: {line}")) + .to_string(); + Self { child, url } + } + + async fn requests(&self) -> Vec { + let text = reqwest::get(format!("{}/__requests", self.url)) + .await + .expect("fetch OAuth MCP requests") + .error_for_status() + .expect("OAuth MCP request status") + .text() + .await + .expect("read OAuth MCP requests"); + serde_json::from_str(&text).expect("decode OAuth MCP requests") + } + + async fn stop(&mut self) { + let _ = self.child.kill().await; + let _ = self.child.wait().await; + } +} + +async fn wait_for_mcp_server_status( + session: &Session, + server_name: &str, + expected_status: McpServerStatus, +) { + wait_for_condition("MCP server status", || async { + session + .rpc() + .mcp() + .list() + .await + .expect("list MCP servers") + .servers + .iter() + .any(|server| server.name == server_name && server.status == expected_status) + }) + .await; +} + +async fn call_whoami(session: &Session, server_name: &str, scenario: &str) { + let result = session + .rpc() + .mcp() + .apps() + .call_tool(McpAppsCallToolRequest { + arguments: Some(HashMap::from([( + "scenario".to_string(), + serde_json::Value::String(scenario.to_string()), + )])), + origin_server_name: server_name.to_string(), + server_name: server_name.to_string(), + tool_name: "whoami".to_string(), + }) + .await + .expect("call whoami"); + let content = result.get("content").expect("whoami content"); + assert_eq!( + content, + &serde_json::json!([{ "type": "text", "text": "oauth-test-user" }]) + ); +} diff --git a/rust/tests/e2e/mode_handlers.rs b/rust/tests/e2e/mode_handlers.rs index fbaaf5158d..b4089ca28a 100644 --- a/rust/tests/e2e/mode_handlers.rs +++ b/rust/tests/e2e/mode_handlers.rs @@ -134,7 +134,7 @@ async fn should_invoke_exit_plan_mode_handler_when_model_uses_tool() { assert_eq!(request.summary, PLAN_SUMMARY); assert_eq!( request.actions, - ["interactive", "autopilot", "exit_only"].map(str::to_string) + ["autopilot", "interactive", "exit_only"].map(str::to_string) ); assert_eq!(request.recommended_action, "interactive"); @@ -146,8 +146,8 @@ async fn should_invoke_exit_plan_mode_handler_when_model_uses_tool() { assert_eq!( requested_data.actions, [ - ExitPlanModeAction::Interactive, ExitPlanModeAction::Autopilot, + ExitPlanModeAction::Interactive, ExitPlanModeAction::ExitOnly, ] ); diff --git a/rust/tests/e2e/per_session_auth.rs b/rust/tests/e2e/per_session_auth.rs index 24d3794484..efb005b590 100644 --- a/rust/tests/e2e/per_session_auth.rs +++ b/rust/tests/e2e/per_session_auth.rs @@ -7,6 +7,9 @@ use super::support::with_e2e_context; #[tokio::test] async fn session_uses_client_token_when_no_session_token_is_supplied() { + if super::support::skip_inprocess("client-level GitHub tokens are not supported in-process") { + return; + } with_e2e_context( "per-session-auth", "session_uses_client_token_when_no_session_token_is_supplied", @@ -29,7 +32,7 @@ async fn session_uses_client_token_when_no_session_token_is_supplied() { .expect("create session"); let status = session .rpc() - .auth() + .git_hub_auth() .get_status() .await .expect("auth status"); @@ -47,6 +50,9 @@ async fn session_uses_client_token_when_no_session_token_is_supplied() { #[tokio::test] async fn session_token_overrides_client_token() { + if super::support::skip_inprocess("client-level GitHub tokens are not supported in-process") { + return; + } with_e2e_context( "per-session-auth", "session_token_overrides_client_token", @@ -70,7 +76,7 @@ async fn session_token_overrides_client_token() { .expect("create session"); let status = session .rpc() - .auth() + .git_hub_auth() .get_status() .await .expect("auth status"); @@ -93,7 +99,11 @@ async fn session_auth_status_is_unauthenticated_without_token() { "session_auth_status_is_unauthenticated_without_token", |ctx| { Box::pin(async move { - let client = ctx.start_client().await; + let client = github_copilot_sdk::Client::start( + ctx.client_options().with_use_logged_in_user(false), + ) + .await + .expect("start client"); let session = client .create_session( SessionConfig::default() @@ -103,7 +113,7 @@ async fn session_auth_status_is_unauthenticated_without_token() { .expect("create session"); let status = session .rpc() - .auth() + .git_hub_auth() .get_status() .await .expect("auth status"); diff --git a/rust/tests/e2e/pre_mcp_tool_call_hook.rs b/rust/tests/e2e/pre_mcp_tool_call_hook.rs index 973672f709..fd05796fcd 100644 --- a/rust/tests/e2e/pre_mcp_tool_call_hook.rs +++ b/rust/tests/e2e/pre_mcp_tool_call_hook.rs @@ -1,23 +1,22 @@ -use std::collections::HashMap; use std::sync::Arc; use async_trait::async_trait; use github_copilot_sdk::hooks::{ HookContext, PreMcpToolCallInput, PreMcpToolCallOutput, SessionHooks, }; -use github_copilot_sdk::{McpServerConfig, McpStdioServerConfig}; +use github_copilot_sdk::{IndexMap, McpServerConfig, McpStdioServerConfig}; use serde_json::{Value, json}; use tokio::sync::mpsc; use super::support::{assistant_message_content, recv_with_timeout, with_e2e_context}; -fn meta_echo_mcp_servers(repo_root: &std::path::Path) -> HashMap { +fn meta_echo_mcp_servers(repo_root: &std::path::Path) -> IndexMap { let harness_dir = repo_root.join("test").join("harness"); let server_path = harness_dir .join("test-mcp-meta-echo-server.mjs") .to_string_lossy() .to_string(); - HashMap::from([( + IndexMap::from([( "meta-echo".to_string(), McpServerConfig::Stdio(McpStdioServerConfig { tools: Some(vec!["*".to_string()]), @@ -127,7 +126,7 @@ async fn should_set_meta_via_premcptoolcall_hook() { assert_eq!(input.server_name, "meta-echo"); assert_eq!(input.tool_name, "echo_meta"); assert!(!input.working_directory.as_os_str().is_empty()); - assert!(input.timestamp > 0); + assert!(input.timestamp > 0.0); session.disconnect().await.expect("disconnect session"); client.stop().await.expect("stop client"); diff --git a/rust/tests/e2e/provider_endpoint.rs b/rust/tests/e2e/provider_endpoint.rs index df6d5941dd..3953aad669 100644 --- a/rust/tests/e2e/provider_endpoint.rs +++ b/rust/tests/e2e/provider_endpoint.rs @@ -15,6 +15,7 @@ fn opt_in_env() -> (OsString, OsString) { } #[tokio::test] +#[allow(deprecated)] async fn byok_provider_endpoint_returns_configured_endpoint() { with_e2e_context( "provider-endpoint", @@ -22,7 +23,9 @@ async fn byok_provider_endpoint_returns_configured_endpoint() { |ctx| { Box::pin(async move { let mut options = ctx.client_options(); - options.env.push(opt_in_env()); + if !super::support::is_inprocess_default() { + options.env.push(opt_in_env()); + } let client = github_copilot_sdk::Client::start(options) .await .expect("start client"); @@ -86,6 +89,7 @@ async fn byok_provider_endpoint_returns_configured_endpoint() { } #[tokio::test] +#[allow(deprecated)] async fn capi_provider_endpoint_returns_resolved_credentials() { with_e2e_context( "provider-endpoint", @@ -93,8 +97,10 @@ async fn capi_provider_endpoint_returns_resolved_credentials() { |ctx| { Box::pin(async move { ctx.set_default_copilot_user(); - let mut options = ctx.client_options().with_github_token(DEFAULT_TEST_TOKEN); - options.env.push(opt_in_env()); + let mut options = ctx.client_options_with_github_token(DEFAULT_TEST_TOKEN); + if !super::support::is_inprocess_default() { + options.env.push(opt_in_env()); + } let client = github_copilot_sdk::Client::start(options) .await .expect("start client"); diff --git a/rust/tests/e2e/rpc_mcp_and_skills.rs b/rust/tests/e2e/rpc_mcp_and_skills.rs index 3f6cc05025..eb8368ebcd 100644 --- a/rust/tests/e2e/rpc_mcp_and_skills.rs +++ b/rust/tests/e2e/rpc_mcp_and_skills.rs @@ -3,16 +3,16 @@ use std::path::Path; use github_copilot_sdk::rpc::{ ExtensionsDisableRequest, ExtensionsEnableRequest, McpAppsCallToolRequest, - McpAppsDiagnoseRequest, McpAppsListToolsRequest, McpAppsReadResourceRequest, - McpAppsSetHostContextDetails, McpAppsSetHostContextDetailsAvailableDisplayMode, - McpAppsSetHostContextDetailsDisplayMode, McpAppsSetHostContextDetailsPlatform, - McpAppsSetHostContextDetailsTheme, McpAppsSetHostContextRequest, - McpCancelSamplingExecutionParams, McpDisableRequest, McpEnableRequest, - McpExecuteSamplingParams, McpExecuteSamplingRequest, McpOauthLoginRequest, - McpSamplingExecutionAction, McpSetEnvValueModeDetails, McpSetEnvValueModeParams, + McpAppsDiagnoseRequest, McpAppsListToolsRequest, McpAppsSetHostContextDetails, + McpAppsSetHostContextDetailsAvailableDisplayMode, McpAppsSetHostContextDetailsDisplayMode, + McpAppsSetHostContextDetailsPlatform, McpAppsSetHostContextDetailsTheme, + McpAppsSetHostContextRequest, McpCancelSamplingExecutionParams, McpDisableRequest, + McpEnableRequest, McpExecuteSamplingParams, McpExecuteSamplingRequest, McpOauthLoginRequest, + McpResourcesReadRequest, McpSamplingExecutionAction, McpSetEnvValueModeDetails, + McpSetEnvValueModeParams, PermissionsAllowAllMode, PermissionsSetAllowAllRequest, SkillsDisableRequest, SkillsEnableRequest, }; -use github_copilot_sdk::{McpServerConfig, McpStdioServerConfig}; +use github_copilot_sdk::{IndexMap, McpServerConfig, McpStdioServerConfig}; use super::support::with_e2e_context; @@ -340,14 +340,22 @@ async fn should_list_extensions() { with_e2e_context("rpc_mcp_and_skills", "should_list_extensions", |ctx| { Box::pin(async move { ctx.set_default_copilot_user(); - let client = - github_copilot_sdk::Client::start(ctx.client_options().with_extra_args(["--yolo"])) - .await - .expect("start yolo client"); + let client = ctx.start_client().await; let session = client .create_session(ctx.approve_all_session_config()) .await .expect("create session"); + session + .rpc() + .permissions() + .set_allow_all(PermissionsSetAllowAllRequest { + enabled: None, + mode: Some(PermissionsAllowAllMode::On), + model: None, + source: None, + }) + .await + .expect("enable allow-all"); let result = session .rpc() @@ -510,8 +518,8 @@ async fn should_report_error_when_mcp_app_resource_is_not_available() { let err = session .rpc() .mcp() - .apps() - .read_resource(McpAppsReadResourceRequest { + .resources() + .read(McpResourcesReadRequest { server_name: "missing-app-server".to_string(), uri: "ui://missing/resource.html".to_string(), }) @@ -678,15 +686,22 @@ async fn should_report_error_when_extensions_are_not_available() { |ctx| { Box::pin(async move { ctx.set_default_copilot_user(); - let client = github_copilot_sdk::Client::start( - ctx.client_options().with_extra_args(["--yolo"]), - ) - .await - .expect("start client"); + let client = ctx.start_client().await; let session = client .create_session(ctx.approve_all_session_config()) .await .expect("create session"); + session + .rpc() + .permissions() + .set_allow_all(PermissionsSetAllowAllRequest { + enabled: None, + mode: Some(PermissionsAllowAllMode::On), + model: None, + source: None, + }) + .await + .expect("enable allow-all"); expect_err_contains( session.rpc().extensions().enable(ExtensionsEnableRequest { @@ -761,14 +776,14 @@ fn assert_skill( skill } -fn test_mcp_servers(repo_root: &Path, server_name: &str) -> HashMap { +fn test_mcp_servers(repo_root: &Path, server_name: &str) -> IndexMap { let harness_dir = repo_root.join("test").join("harness"); let server_path = harness_dir .join("test-mcp-server.mjs") .to_string_lossy() .to_string(); - HashMap::from([( + IndexMap::from([( server_name.to_string(), McpServerConfig::Stdio(McpStdioServerConfig { tools: Some(vec!["*".to_string()]), diff --git a/rust/tests/e2e/rpc_mcp_lifecycle.rs b/rust/tests/e2e/rpc_mcp_lifecycle.rs index fc79828320..028b5a527f 100644 --- a/rust/tests/e2e/rpc_mcp_lifecycle.rs +++ b/rust/tests/e2e/rpc_mcp_lifecycle.rs @@ -1,4 +1,3 @@ -use std::collections::HashMap; use std::path::Path; use github_copilot_sdk::rpc::{ @@ -7,7 +6,7 @@ use github_copilot_sdk::rpc::{ }; use github_copilot_sdk::session::Session; use github_copilot_sdk::session_events::McpServerStatus; -use github_copilot_sdk::{Error, McpServerConfig, McpStdioServerConfig}; +use github_copilot_sdk::{Error, IndexMap, McpServerConfig, McpStdioServerConfig}; use serde::de::DeserializeOwned; use serde_json::{Value, json}; @@ -327,49 +326,11 @@ async fn should_configure_github_mcp_server() { .await; } -#[tokio::test] -async fn should_respond_to_mcp_oauth_request_without_pending_request() { - with_e2e_context( - "rpc_mcp_lifecycle", - "should_respond_to_mcp_oauth_request_without_pending_request", - |ctx| { - Box::pin(async move { - ctx.set_default_copilot_user(); - let host_server = "rpc-lifecycle-oauth-host"; - let client = ctx.start_client().await; - let session = - client - .create_session(ctx.approve_all_session_config().with_mcp_servers( - create_test_mcp_servers(ctx.repo_root(), host_server), - )) - .await - .expect("create session"); - wait_for_mcp_server_status(&session, host_server, McpServerStatus::Connected).await; - - let result = call_session_rpc( - &session, - "session.mcp.oauth.respond", - json!({ - "requestId": format!("missing-{}", uuid::Uuid::new_v4().simple()) - }), - ) - .await - .expect("respond to missing MCP OAuth request"); - assert!(result.is_object()); - - session.disconnect().await.expect("disconnect session"); - client.stop().await.expect("stop client"); - }) - }, - ) - .await; -} - fn create_test_mcp_servers( repo_root: &Path, server_name: &str, -) -> HashMap { - HashMap::from([(server_name.to_string(), test_mcp_server_config(repo_root))]) +) -> IndexMap { + IndexMap::from([(server_name.to_string(), test_mcp_server_config(repo_root))]) } fn test_mcp_server_config(repo_root: &Path) -> McpServerConfig { diff --git a/rust/tests/e2e/rpc_server.rs b/rust/tests/e2e/rpc_server.rs index 27cad2f69a..d0beab2452 100644 --- a/rust/tests/e2e/rpc_server.rs +++ b/rust/tests/e2e/rpc_server.rs @@ -1,18 +1,23 @@ -use github_copilot_sdk::Client; +use std::collections::HashMap; + use github_copilot_sdk::rpc::{ - ConnectRemoteSessionParams, LocalSessionMetadataValue, McpDiscoverRequest, NameSetRequest, - PingRequest, SecretsAddFilterValuesRequest, SessionContext, SessionFsSetProviderConventions, + AgentsDiscoverRequest, AgentsGetDiscoveryPathsRequest, ConnectRemoteSessionParams, + InstructionsDiscoverRequest, InstructionsGetDiscoveryPathsRequest, + LlmInferenceHttpResponseChunkRequest, LlmInferenceHttpResponseStartRequest, + LocalSessionMetadataValue, McpDiscoverRequest, NameSetRequest, PingRequest, + SecretsAddFilterValuesRequest, SessionContext, SessionFsSetProviderConventions, SessionFsSetProviderRequest, SessionListFilter, SessionsBulkDeleteRequest, SessionsCheckInUseRequest, SessionsCloseRequest, SessionsEnrichMetadataRequest, SessionsFindByPrefixRequest, SessionsFindByTaskIDRequest, SessionsGetLastForContextRequest, SessionsListRequest, SessionsLoadDeferredRepoHooksRequest, SessionsPruneOldRequest, SessionsReleaseLockRequest, SessionsReloadPluginHooksRequest, SessionsSaveRequest, SessionsSetAdditionalPluginsRequest, SkillsConfigSetDisabledSkillsRequest, - SkillsDiscoverRequest, ToolsListRequest, + SkillsDiscoverRequest, SkillsGetDiscoveryPathsRequest, ToolsListRequest, }; +use github_copilot_sdk::{Client, RequestId}; use serde_json::json; -use super::support::with_e2e_context; +use super::support::{with_e2e_context, with_e2e_context_no_snapshot}; #[tokio::test] async fn should_call_rpc_ping_with_typed_params_and_result() { @@ -49,7 +54,7 @@ async fn should_call_rpc_models_list_with_typed_result() { Box::pin(async move { let token = "rpc-models-token"; ctx.set_copilot_user_by_token_with_login(token, "rpc-user"); - let client = Client::start(ctx.client_options().with_github_token(token)) + let client = Client::start(ctx.client_options_with_github_token(token)) .await .expect("start client"); @@ -90,7 +95,7 @@ async fn should_call_rpc_account_get_quota_when_authenticated() { } })), ); - let client = Client::start(ctx.client_options().with_github_token(token)) + let client = Client::start(ctx.client_options_with_github_token(token)) .await .expect("start client"); @@ -136,6 +141,49 @@ async fn should_call_rpc_tools_list_with_typed_result() { .await; } +#[tokio::test] +async fn should_reject_llm_response_frames_for_unknown_request() { + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + let client = ctx.start_client().await; + let request_id = RequestId::from("missing-llm-response-request"); + + let start = client + .rpc() + .llm_inference() + .http_response_start(LlmInferenceHttpResponseStartRequest { + headers: HashMap::from([( + "content-type".to_string(), + vec!["application/json".to_string()], + )]), + request_id: request_id.clone(), + status: 200, + status_text: Some("OK".to_string()), + }) + .await + .expect("send unknown LLM response start"); + assert!(!start.accepted); + + let chunk = client + .rpc() + .llm_inference() + .http_response_chunk(LlmInferenceHttpResponseChunkRequest { + binary: Some(false), + data: "{}".to_string(), + end: Some(true), + error: None, + request_id, + }) + .await + .expect("send unknown LLM response chunk"); + assert!(!chunk.accepted); + + client.stop().await.expect("stop client"); + }) + }) + .await; +} + #[tokio::test] async fn should_discover_server_mcp_and_skills() { with_e2e_context( @@ -150,12 +198,13 @@ async fn should_discover_server_mcp_and_skills() { "Skill discovered by server-scoped RPC tests.", ); let client = ctx.start_client().await; + let project_path = ctx.work_dir().to_string_lossy().to_string(); let mcp = client .rpc() .mcp() .discover(McpDiscoverRequest { - working_directory: Some(ctx.work_dir().to_string_lossy().to_string()), + working_directory: Some(project_path.clone()), }) .await .expect("mcp discover"); @@ -179,6 +228,101 @@ async fn should_discover_server_mcp_and_skills() { "Skill discovered by server-scoped RPC tests." ); + let skill_paths = client + .rpc() + .skills() + .get_discovery_paths(SkillsGetDiscoveryPathsRequest { + exclude_host_skills: Some(true), + project_paths: Some(vec![project_path.clone()]), + }) + .await + .expect("skills discovery paths"); + let project_skill_path = skill_paths + .paths + .iter() + .find(|path| { + path.project_path + .as_deref() + .is_some_and(|path| paths_equal(path, &project_path)) + && path.preferred_for_creation + }) + .expect("project skill discovery path"); + assert!(!project_skill_path.path.trim().is_empty()); + + let agents = client + .rpc() + .agents() + .discover(AgentsDiscoverRequest { + exclude_host_agents: Some(true), + project_paths: Some(vec![project_path.clone()]), + }) + .await + .expect("agents discover"); + assert!( + agents + .agents + .iter() + .all(|agent| !agent.name.trim().is_empty()) + ); + + let agent_paths = client + .rpc() + .agents() + .get_discovery_paths(AgentsGetDiscoveryPathsRequest { + exclude_host_agents: Some(true), + project_paths: Some(vec![project_path.clone()]), + }) + .await + .expect("agents discovery paths"); + let project_agent_path = agent_paths + .paths + .iter() + .find(|path| { + path.project_path + .as_deref() + .is_some_and(|path| paths_equal(path, &project_path)) + && path.preferred_for_creation + }) + .expect("project agent discovery path"); + assert!(!project_agent_path.path.trim().is_empty()); + + let instructions = client + .rpc() + .instructions() + .discover(InstructionsDiscoverRequest { + exclude_host_instructions: Some(true), + project_paths: Some(vec![project_path.clone()]), + }) + .await + .expect("instructions discover"); + assert!(instructions.sources.iter().all(|source| { + !source.id.trim().is_empty() + && !source.label.trim().is_empty() + && !source.source_path.trim().is_empty() + })); + + let instruction_paths = client + .rpc() + .instructions() + .get_discovery_paths(InstructionsGetDiscoveryPathsRequest { + exclude_host_instructions: Some(true), + project_paths: Some(vec![project_path.clone()]), + }) + .await + .expect("instructions discovery paths"); + assert!(!instruction_paths.paths.is_empty()); + assert!(instruction_paths.paths.iter().any(|path| { + path.project_path + .as_deref() + .is_some_and(|path| paths_equal(path, &project_path)) + })); + assert!( + instruction_paths + .paths + .iter() + .all(|path| !path.path.trim().is_empty()) + ); + client .rpc() .skills() @@ -701,3 +845,19 @@ fn assert_server_skill( ); skill } + +fn paths_equal(left: &str, right: &str) -> bool { + fn normalize(path: &str) -> String { + let mut normalized = path.replace('\\', "/"); + while normalized.ends_with('/') && normalized.len() > 1 { + normalized.pop(); + } + if cfg!(windows) { + normalized.to_ascii_lowercase() + } else { + normalized + } + } + + normalize(left) == normalize(right) +} diff --git a/rust/tests/e2e/rpc_server_misc.rs b/rust/tests/e2e/rpc_server_misc.rs index 2886aff280..b9e5cdf5c4 100644 --- a/rust/tests/e2e/rpc_server_misc.rs +++ b/rust/tests/e2e/rpc_server_misc.rs @@ -1,7 +1,9 @@ use github_copilot_sdk::Client; use github_copilot_sdk::rpc::{ - AgentRegistrySpawnRequest, SendAttachmentsToMessageParams, SessionsOpenStatus, + AccountLoginRequest, AccountLogoutRequest, AgentRegistrySpawnRequest, + SendAttachmentsToMessageParams, SessionsOpenStatus, UserSettingsSetRequest, }; +use serde_json::{Map, Value, json}; use super::support::{wait_for_condition, with_e2e_context}; @@ -25,6 +27,183 @@ async fn should_reload_user_settings() { .await; } +#[tokio::test] +async fn should_get_set_and_clear_user_settings() { + with_e2e_context( + "rpc_server_misc", + "should_get_set_and_clear_user_settings", + |ctx| { + Box::pin(async move { + let client = ctx.start_client().await; + + let initial = client + .rpc() + .user() + .settings() + .get() + .await + .expect("get initial user settings"); + let (key, value) = initial + .settings + .iter() + .find_map(|(key, setting)| { + setting.value.as_bool().map(|value| (key.clone(), value)) + }) + .expect("at least one boolean user setting"); + let toggled = !value; + + let set = client + .rpc() + .user() + .settings() + .set(UserSettingsSetRequest { + settings: setting_patch(&key, json!(toggled)), + }) + .await + .expect("set user setting"); + assert!(set.shadowed_keys.is_empty()); + client + .rpc() + .user() + .settings() + .reload() + .await + .expect("reload after set"); + let after_set = client + .rpc() + .user() + .settings() + .get() + .await + .expect("get after set"); + let metadata = after_set.settings.get(&key).expect("updated setting"); + assert_eq!(metadata.value, json!(toggled)); + assert!(!metadata.is_default); + + let clear = client + .rpc() + .user() + .settings() + .set(UserSettingsSetRequest { + settings: setting_patch(&key, Value::Null), + }) + .await + .expect("clear user setting"); + assert!(clear.shadowed_keys.is_empty()); + client + .rpc() + .user() + .settings() + .reload() + .await + .expect("reload after clear"); + let after_clear = client + .rpc() + .user() + .settings() + .get() + .await + .expect("get after clear"); + assert!( + after_clear + .settings + .get(&key) + .expect("cleared setting") + .is_default + ); + + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_login_list_getcurrentauth_and_logout_account() { + with_e2e_context( + "rpc_server_misc", + "should_login_list_getcurrentauth_and_logout_account", + |ctx| { + Box::pin(async move { + ctx.set_copilot_user_by_token_with_login("rust-account-token", "rust-account-user"); + let client = Client::start(ctx.client_options().with_use_logged_in_user(false)) + .await + .expect("start no-token client"); + + let initial = client + .rpc() + .account() + .get_current_auth() + .await + .expect("get initial auth"); + assert!(initial.auth_info.is_none()); + + let login = client + .rpc() + .account() + .login(AccountLoginRequest { + host: "https://github.com".to_string(), + login: "rust-account-user".to_string(), + token: "rust-account-token".to_string(), + }) + .await + .expect("account login"); + let _stored_in_vault = login.stored_in_vault; + + let current = client + .rpc() + .account() + .get_current_auth() + .await + .expect("get current auth after login"); + let auth_info = current.auth_info.expect("auth info after login"); + assert_eq!(auth_info["login"], json!("rust-account-user")); + assert_eq!(auth_info["host"], json!("https://github.com")); + + let users = client + .rpc() + .account() + .get_all_users() + .await + .expect("get all users"); + if let Some(user) = users + .iter() + .find(|user| user.auth_info["login"] == json!("rust-account-user")) + { + user.token + .as_deref() + .filter(|token| *token == "rust-account-token") + .unwrap_or_else(|| { + panic!("expected stored account token, got {:?}", user.token) + }); + } + + let logout = client + .rpc() + .account() + .logout(AccountLogoutRequest { auth_info }) + .await + .expect("account logout"); + assert!(!logout.has_more_users); + assert!( + client + .rpc() + .account() + .get_current_auth() + .await + .expect("get auth after logout") + .auth_info + .is_none() + ); + + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + #[tokio::test] async fn should_report_agent_registry_spawn_gate_closed() { with_e2e_context( @@ -168,3 +347,9 @@ fn assert_not_unhandled(message: &str) { "{message}" ); } + +fn setting_patch(key: &str, value: Value) -> Value { + let mut settings = Map::new(); + settings.insert(key.to_string(), value); + Value::Object(settings) +} diff --git a/rust/tests/e2e/rpc_server_plugins.rs b/rust/tests/e2e/rpc_server_plugins.rs index 895ab28014..054ffa3599 100644 --- a/rust/tests/e2e/rpc_server_plugins.rs +++ b/rust/tests/e2e/rpc_server_plugins.rs @@ -15,10 +15,10 @@ const PLUGIN_NAME: &str = "csharp-e2e-plugin"; const DIRECT_PLUGIN_NAME: &str = "csharp-e2e-direct"; #[tokio::test] -async fn should_install_list_and_uninstall_plugin_from_local_marketplace() { +async fn should_install_and_list_plugin_from_local_marketplace() { with_e2e_context( "rpc_server_plugins", - "should_install_list_and_uninstall_plugin_from_local_marketplace", + "should_install_and_list_plugin_from_local_marketplace", |ctx| { Box::pin(async move { let marketplace = create_local_marketplace_fixture(); @@ -31,6 +31,7 @@ async fn should_install_list_and_uninstall_plugin_from_local_marketplace() { .marketplaces() .add(PluginsMarketplacesAddRequest { source: marketplace.source(), + working_directory: None, }) .await .expect("add marketplace"); @@ -39,7 +40,7 @@ async fn should_install_list_and_uninstall_plugin_from_local_marketplace() { .rpc() .plugins() .install(PluginsInstallRequest { - source: spec.clone(), + source: spec, working_directory: None, }) .await @@ -55,25 +56,6 @@ async fn should_install_list_and_uninstall_plugin_from_local_marketplace() { let listed = single_plugin(&after_install, PLUGIN_NAME, MARKETPLACE_NAME); assert!(listed.enabled); - client - .rpc() - .plugins() - .uninstall(PluginsUninstallRequest { name: spec }) - .await - .expect("uninstall marketplace plugin"); - - let after_uninstall = client - .rpc() - .plugins() - .list() - .await - .expect("list after uninstall"); - assert!(!contains_plugin( - &after_uninstall, - PLUGIN_NAME, - MARKETPLACE_NAME - )); - client.stop().await.expect("stop client"); }) }, @@ -98,6 +80,7 @@ async fn should_enable_and_disable_marketplace_plugin() { .marketplaces() .add(PluginsMarketplacesAddRequest { source: marketplace.source(), + working_directory: None, }) .await .expect("add marketplace"); @@ -167,6 +150,7 @@ async fn should_update_single_marketplace_plugin() { .marketplaces() .add(PluginsMarketplacesAddRequest { source: marketplace.source(), + working_directory: None, }) .await .expect("add marketplace"); @@ -215,6 +199,7 @@ async fn should_update_all_installed_plugins() { .marketplaces() .add(PluginsMarketplacesAddRequest { source: marketplace.source(), + working_directory: None, }) .await .expect("add marketplace"); @@ -293,11 +278,17 @@ async fn should_install_direct_local_plugin_with_deprecation_warning() { direct_matches, 1, "expected direct plugin in {after_install:?}" ); + let direct_source_id = install.plugin.direct_source_id.clone(); + assert!( + direct_source_id.is_some(), + "expected direct plugin install to include direct_source_id" + ); client .rpc() .plugins() .uninstall(PluginsUninstallRequest { + direct_source_id, name: DIRECT_PLUGIN_NAME.to_string(), }) .await @@ -339,6 +330,7 @@ async fn should_list_browse_refresh_and_remove_local_marketplace() { .marketplaces() .add(PluginsMarketplacesAddRequest { source: marketplace.source(), + working_directory: None, }) .await .expect("add marketplace"); @@ -546,9 +538,3 @@ fn single_plugin<'a>( assert_eq!(matches.len(), 1, "expected one plugin in {list:?}"); matches[0] } - -fn contains_plugin(list: &PluginListResult, name: &str, marketplace: &str) -> bool { - list.plugins - .iter() - .any(|plugin| plugin.name == name && plugin.marketplace == marketplace) -} diff --git a/rust/tests/e2e/rpc_session_state.rs b/rust/tests/e2e/rpc_session_state.rs index 8b68aeb3a8..199ff2a2b5 100644 --- a/rust/tests/e2e/rpc_session_state.rs +++ b/rust/tests/e2e/rpc_session_state.rs @@ -867,7 +867,7 @@ async fn should_set_auth_credentials() { let set = session .rpc() - .auth() + .git_hub_auth() .set_credentials(SessionSetCredentialsParams { credentials: Some(json!({ "type": "user", @@ -880,7 +880,7 @@ async fn should_set_auth_credentials() { assert!(set.success); let status = session .rpc() - .auth() + .git_hub_auth() .get_status() .await .expect("auth status"); diff --git a/rust/tests/e2e/rpc_session_state_extras.rs b/rust/tests/e2e/rpc_session_state_extras.rs index 10954b4e27..3bd6c99bee 100644 --- a/rust/tests/e2e/rpc_session_state_extras.rs +++ b/rust/tests/e2e/rpc_session_state_extras.rs @@ -1,5 +1,13 @@ +use std::collections::HashMap; + use github_copilot_sdk::Client; -use github_copilot_sdk::rpc::PermissionsSetAllowAllRequest; +use github_copilot_sdk::rpc::{ + CompletionsRequestRequest, MetadataContextHeaviestMessagesRequest, ModelSwitchToRequest, + NamedProviderConfig, PermissionsSetAllowAllRequest, ProviderAddRequest, ProviderConfigType, + ProviderConfigWireApi, ProviderModelConfig, SessionVisibilityStatus, SubagentSettingsEntry, + SubagentSettingsEntryContextTier, UpdateSubagentSettingsRequest, + UpdateSubagentSettingsRequestSubagents, VisibilitySetRequest, +}; use super::support::{assistant_message_content, with_e2e_context}; @@ -14,7 +22,7 @@ async fn should_list_models_for_session() { Box::pin(async move { let token = "rpc-session-model-list-token"; ctx.set_copilot_user_by_token_with_login(token, "rpc-session-extras-user"); - let client = Client::start(ctx.client_options().with_github_token(token)) + let client = Client::start(ctx.client_options_with_github_token(token)) .await .expect("start authenticated client"); let session = client @@ -102,7 +110,9 @@ async fn should_get_and_set_allowall_permissions() { .rpc() .permissions() .set_allow_all(PermissionsSetAllowAllRequest { - enabled: true, + enabled: Some(true), + mode: None, + model: None, source: None, }) .await @@ -123,7 +133,9 @@ async fn should_get_and_set_allowall_permissions() { .rpc() .permissions() .set_allow_all(PermissionsSetAllowAllRequest { - enabled: false, + enabled: Some(false), + mode: None, + model: None, source: None, }) .await @@ -248,6 +260,258 @@ async fn should_get_current_tool_metadata_after_initialization() { .await; } +#[tokio::test] +async fn should_add_byok_provider_and_model_at_runtime() { + with_e2e_context( + "rpc_session_state_extras", + "should_add_byok_provider_and_model_at_runtime", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + + let result = session + .rpc() + .provider() + .add(ProviderAddRequest { + providers: Some(vec![NamedProviderConfig { + api_key: Some("provider-key".to_string()), + azure: None, + base_url: "https://models.example.test/v1".to_string(), + bearer_token: None, + has_bearer_token_provider: None, + headers: Some(HashMap::from([( + "x-provider".to_string(), + "rust".to_string(), + )])), + name: "rust-e2e-provider".to_string(), + transport: None, + r#type: Some(ProviderConfigType::Openai), + wire_api: Some(ProviderConfigWireApi::Completions), + }]), + models: Some(vec![ProviderModelConfig { + capabilities: None, + id: "small".to_string(), + max_context_window_tokens: None, + max_output_tokens: None, + max_prompt_tokens: Some(4096.0), + model_id: None, + name: Some("Rust Added Model".to_string()), + provider: "rust-e2e-provider".to_string(), + wire_model: None, + }]), + }) + .await + .expect("add provider model"); + assert_eq!(result.models.len(), 1); + + let selection_id = "rust-e2e-provider/small"; + session + .rpc() + .model() + .switch_to(ModelSwitchToRequest { + context_tier: None, + model_capabilities: None, + model_id: selection_id.to_string(), + reasoning_effort: None, + reasoning_summary: None, + verbosity: None, + }) + .await + .expect("switch to added model"); + let current = session + .rpc() + .model() + .get_current() + .await + .expect("get current model"); + assert_eq!(current.model_id.as_deref(), Some(selection_id)); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_return_empty_completions_when_host_does_not_provide_them() { + with_e2e_context( + "rpc_session_state_extras", + "should_return_empty_completions_when_host_does_not_provide_them", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + + let result = session + .rpc() + .completions() + .request(CompletionsRequestRequest { + offset: 5, + text: "Use @ to mention context".to_string(), + }) + .await + .expect("request completions"); + assert!(result.items.is_empty()); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_report_visibility_as_unsynced_for_local_session() { + with_e2e_context( + "rpc_session_state_extras", + "should_report_visibility_as_unsynced_for_local_session", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + + let set = session + .rpc() + .visibility() + .set(VisibilitySetRequest { + status: SessionVisibilityStatus::Unshared, + }) + .await + .expect("set visibility"); + assert!(!set.synced); + assert!(set.status.is_none()); + assert!(set.share_url.is_none()); + let get = session + .rpc() + .visibility() + .get() + .await + .expect("get visibility"); + assert!(!get.synced); + assert!(get.status.is_none()); + assert!(get.share_url.is_none()); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_get_context_attribution_and_heaviest_messages_after_turn() { + with_e2e_context( + "rpc_session_state_extras", + "should_get_context_attribution_and_heaviest_messages_after_turn", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + + let answer = session + .send_and_wait("Say CONTEXT_METADATA_OK exactly.") + .await + .expect("send prompt") + .expect("assistant message"); + assert!(assistant_message_content(&answer).contains("CONTEXT_METADATA_OK")); + + let attribution = session + .rpc() + .metadata() + .get_context_attribution() + .await + .expect("get context attribution"); + assert!(attribution.context_attribution.is_some()); + let heaviest = session + .rpc() + .metadata() + .get_context_heaviest_messages(MetadataContextHeaviestMessagesRequest { + limit: Some(5), + }) + .await + .expect("get heaviest messages"); + assert!(heaviest.total_tokens >= 0); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_update_and_clear_live_subagent_settings() { + with_e2e_context( + "rpc_session_state_extras", + "should_update_and_clear_live_subagent_settings", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + + session + .rpc() + .tools() + .update_subagent_settings(UpdateSubagentSettingsRequest { + subagents: Some(UpdateSubagentSettingsRequestSubagents { + agents: Some(HashMap::from([( + "general-purpose".to_string(), + SubagentSettingsEntry { + context_tier: Some( + SubagentSettingsEntryContextTier::LongContext, + ), + effort_level: Some("low".to_string()), + model: Some("gpt-5-mini".to_string()), + }, + )])), + disabled_subagents: Some(vec!["legacy-agent".to_string()]), + max_concurrency: None, + max_depth: None, + }), + }) + .await + .expect("update subagent settings"); + session + .rpc() + .tools() + .update_subagent_settings(UpdateSubagentSettingsRequest { subagents: None }) + .await + .expect("clear subagent settings"); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + #[tokio::test] async fn should_reload_session_plugins() { with_e2e_context( diff --git a/rust/tests/e2e/rpc_tasks_and_handlers.rs b/rust/tests/e2e/rpc_tasks_and_handlers.rs index 9226addc0c..601cc70bf2 100644 --- a/rust/tests/e2e/rpc_tasks_and_handlers.rs +++ b/rust/tests/e2e/rpc_tasks_and_handlers.rs @@ -1,5 +1,11 @@ +use std::collections::HashMap; + use github_copilot_sdk::rpc::{ - CommandsHandlePendingCommandRequest, HandlePendingToolCallRequest, PermissionDecision, + CommandsHandlePendingCommandRequest, HandlePendingToolCallRequest, + McpHeadersHandlePendingHeadersRefreshRequest, + McpHeadersHandlePendingHeadersRefreshRequestHeaders, + McpHeadersHandlePendingHeadersRefreshRequestHeadersKind, + McpHeadersHandlePendingHeadersRefreshRequestRequest, PermissionDecision, PermissionDecisionApproveForLocation, PermissionDecisionApproveForLocationApproval, PermissionDecisionApproveForLocationApprovalCustomTool, PermissionDecisionApproveForLocationApprovalCustomToolKind, @@ -16,8 +22,9 @@ use github_copilot_sdk::rpc::{ UIElicitationResponse, UIElicitationResponseAction, UIExitPlanModeResponse, UIHandlePendingAutoModeSwitchRequest, UIHandlePendingElicitationRequest, UIHandlePendingExitPlanModeRequest, UIHandlePendingSamplingRequest, - UIHandlePendingUserInputRequest, UIUnregisterDirectAutoModeSwitchHandlerRequest, - UIUserInputResponse, + UIHandlePendingSessionLimitsExhaustedRequest, UIHandlePendingUserInputRequest, + UISessionLimitsExhaustedResponse, UISessionLimitsExhaustedResponseAction, + UIUnregisterDirectAutoModeSwitchHandlerRequest, UIUserInputResponse, }; use super::support::with_e2e_context; @@ -323,6 +330,23 @@ async fn should_return_expected_results_for_missing_pending_handler_requestids() .expect("handle missing exit plan"); assert!(!exit_plan.success); + let session_limits = session + .rpc() + .ui() + .handle_pending_session_limits_exhausted( + UIHandlePendingSessionLimitsExhaustedRequest { + request_id: "missing-session-limits-request".into(), + response: UISessionLimitsExhaustedResponse { + action: UISessionLimitsExhaustedResponseAction::Unset, + additional_ai_credits: None, + max_ai_credits: None, + }, + }, + ) + .await + .expect("handle missing session limits exhausted"); + assert!(!session_limits.success); + for (request_id, result) in [ ( "missing-permission-request", @@ -385,6 +409,28 @@ async fn should_return_expected_results_for_missing_pending_handler_requestids() assert!(!permission.success, "{request_id} should not be handled"); } + let headers_refresh = session + .rpc() + .mcp() + .headers() + .handle_pending_headers_refresh_request( + McpHeadersHandlePendingHeadersRefreshRequestRequest { + request_id: "missing-headers-refresh-request".into(), + result: McpHeadersHandlePendingHeadersRefreshRequest::Headers( + McpHeadersHandlePendingHeadersRefreshRequestHeaders { + headers: HashMap::from([( + "x-refresh".to_string(), + "missing".to_string(), + )]), + kind: McpHeadersHandlePendingHeadersRefreshRequestHeadersKind::Headers, + }, + ), + }, + ) + .await + .expect("handle missing headers refresh"); + assert!(!headers_refresh.success); + session.disconnect().await.expect("disconnect session"); client.stop().await.expect("stop client"); }) diff --git a/rust/tests/e2e/rpc_workspace_checkpoints.rs b/rust/tests/e2e/rpc_workspace_checkpoints.rs index 2c185a535a..0a8bf56152 100644 --- a/rust/tests/e2e/rpc_workspace_checkpoints.rs +++ b/rust/tests/e2e/rpc_workspace_checkpoints.rs @@ -40,6 +40,12 @@ async fn should_list_no_checkpoints_for_fresh_session() { #[tokio::test] async fn should_return_null_or_empty_content_for_unknown_checkpoint() { + // In-process, session.workspaces.readCheckpoint is answered by the native runtime, + // which decodes the checkpoint number as a u32 and rejects the i64::MAX sentinel this + // test uses. Covered by the default (stdio) transport. See issue #1934. + if super::support::skip_inprocess("readCheckpoint decodes the id as u32 in-process") { + return; + } with_e2e_context( "rpc_workspace_checkpoints", "should_return_null_or_empty_content_for_unknown_checkpoint", diff --git a/rust/tests/e2e/session.rs b/rust/tests/e2e/session.rs index ee3a010bfb..744708db76 100644 --- a/rust/tests/e2e/session.rs +++ b/rust/tests/e2e/session.rs @@ -2,7 +2,9 @@ use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; -use github_copilot_sdk::handler::ApproveAllHandler; +use github_copilot_sdk::handler::{ + ApproveAllHandler, McpAuthHandler, McpAuthRequest, McpAuthResult, +}; use github_copilot_sdk::session_events::{ SessionErrorData, SessionEventType, SessionInfoData, SessionModelChangeData, SessionResumeData, SessionStartData, SessionWarningData, UserMessageData, @@ -12,8 +14,8 @@ use github_copilot_sdk::types::LogLevel as SessionLogLevel; use github_copilot_sdk::{ Attachment, AttachmentLineRange, AttachmentSelectionPosition, AttachmentSelectionRange, AzureProviderOptions, DefaultAgentConfig, Error, GitHubReferenceType, LogOptions, - MessageOptions, ProviderConfig, ResumeSessionConfig, SectionOverride, SessionConfig, - SetModelOptions, SystemMessageConfig, Tool, ToolInvocation, ToolResult, + MessageOptions, ProviderConfig, RequestId, ResumeSessionConfig, SectionOverride, SessionConfig, + SessionId, SetModelOptions, SystemMessageConfig, Tool, ToolInvocation, ToolResult, }; use serde_json::json; @@ -597,6 +599,60 @@ async fn should_resume_a_session_using_a_new_client() { .await; } +#[tokio::test] +async fn resumes_a_persisted_session_from_a_new_client_when_an_mcp_oauth_handler_is_configured() { + with_e2e_context( + "session", + "resumes_a_persisted_session_from_a_new_client_when_an_mcp_oauth_handler_is_configured", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session = client + .create_session( + ctx.approve_all_session_config() + .with_mcp_auth_handler(Arc::new(CancelMcpAuthHandler)), + ) + .await + .expect("create session"); + let session_id = session.id().clone(); + + let first = session + .send_and_wait("What is 1+1?") + .await + .expect("send") + .expect("assistant message"); + assert!(assistant_message_content(&first).contains('2')); + + session + .disconnect() + .await + .expect("disconnect first session"); + client.stop().await.expect("stop first client"); + + let new_client = ctx.start_client().await; + let resumed = new_client + .resume_session( + ResumeSessionConfig::new(session_id.clone()) + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_mcp_auth_handler(Arc::new(CancelMcpAuthHandler)) + .with_github_token(super::support::DEFAULT_TEST_TOKEN), + ) + .await + .expect("resume session"); + assert_eq!(resumed.id(), &session_id); + + resumed + .disconnect() + .await + .expect("disconnect resumed session"); + new_client.stop().await.expect("stop new client"); + }) + }, + ) + .await; +} + #[tokio::test] async fn should_receive_session_events() { with_e2e_context("session", "should_receive_session_events", |ctx| { @@ -1528,6 +1584,20 @@ async fn latest_user_message( .expect("user.message") } +struct CancelMcpAuthHandler; + +#[async_trait::async_trait] +impl McpAuthHandler for CancelMcpAuthHandler { + async fn handle( + &self, + _session_id: SessionId, + _request_id: RequestId, + _request: McpAuthRequest, + ) -> McpAuthResult { + McpAuthResult::Cancelled + } +} + struct SecretNumberTool; #[async_trait::async_trait] diff --git a/rust/tests/e2e/session_config.rs b/rust/tests/e2e/session_config.rs index 8b13789179..dd498e3761 100644 --- a/rust/tests/e2e/session_config.rs +++ b/rust/tests/e2e/session_config.rs @@ -1 +1,628 @@ +use std::net::TcpListener; +use std::sync::Arc; +use std::time::Duration; +use async_trait::async_trait; +use base64::Engine; +use bytes::Bytes; +use github_copilot_sdk::handler::ApproveAllHandler; +use github_copilot_sdk::{ + Attachment, Client, CopilotHttpRequest, CopilotHttpResponse, CopilotRequestContext, + CopilotRequestError, CopilotRequestHandler, MessageOptions, ProviderConfig, + ResumeSessionConfig, SessionConfig, SessionLimitsConfig, Transport, +}; +use http::{HeaderMap, HeaderValue}; +use parking_lot::Mutex; +use serde_json::{Value, json}; + +use super::support::{ + DEFAULT_TEST_TOKEN, E2eContext, with_e2e_context, with_e2e_context_no_snapshot, +}; + +const SYNTHETIC_TEXT: &str = "OK from the synthetic stream."; +const CITATION_PROMPT: &str = "Summarize the attached PDF with citations enabled."; + +fn session_limits(max_ai_credits: f64) -> SessionLimitsConfig { + SessionLimitsConfig { + max_ai_credits: Some(max_ai_credits), + } +} + +async fn send_and_get_next_exchange( + ctx: &E2eContext, + session: &github_copilot_sdk::session::Session, + prompt: &str, +) -> Value { + let existing_count = ctx.exchanges().len(); + session + .send_and_wait(MessageOptions::new(prompt).with_wait_timeout(Duration::from_secs(120))) + .await + .expect("send_and_wait"); + let exchanges = ctx.exchanges(); + assert!(exchanges.len() > existing_count); + exchanges[existing_count].clone() +} + +fn assert_session_limits_status(exchange: &Value, expected_remaining: &str) { + let messages = exchange["request"]["messages"] + .as_array() + .expect("request messages"); + for message in messages { + if message["role"] != "user" { + continue; + } + let Some(content) = message["content"].as_str() else { + continue; + }; + if !content.contains("") { + continue; + } + assert!( + content.contains(&format!("Remaining session limits: {expected_remaining}.")), + "expected session limits status to include remaining {expected_remaining:?}, got {content:?}" + ); + assert!( + content.contains("Be frugal; avoid optional exploration and unnecessary tool calls."), + "expected session limits status to include frugality instruction, got {content:?}" + ); + return; + } + panic!("expected session limits status message"); +} + +fn task_agent_types(exchange: &Value) -> Vec { + let tools = exchange["request"]["tools"] + .as_array() + .expect("request tools"); + for tool in tools { + if tool["function"]["name"] != "task" { + continue; + } + return tool["function"]["parameters"]["properties"]["agent_type"]["enum"] + .as_array() + .expect("agent type enum") + .iter() + .map(|value| value.as_str().expect("agent type").to_string()) + .collect(); + } + panic!("expected task tool in request"); +} + +#[tokio::test] +async fn should_apply_session_limits_on_create() { + with_e2e_context( + "session_config", + "should_apply_session_limits_on_create", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session = client + .create_session( + ctx.approve_all_session_config() + .with_session_limits(session_limits(30.0)), + ) + .await + .expect("create session"); + + let exchange = send_and_get_next_exchange( + ctx, + &session, + "Acknowledge the current session limits.", + ) + .await; + assert_session_limits_status(&exchange, "30 AI credits"); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_apply_session_limits_on_resume() { + with_e2e_context( + "session_config", + "should_apply_session_limits_on_resume", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session1 = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + let session2 = client + .resume_session( + ResumeSessionConfig::new(session1.id().clone()) + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_github_token(DEFAULT_TEST_TOKEN) + .with_session_limits(session_limits(30.0)), + ) + .await + .expect("resume session"); + + let exchange = send_and_get_next_exchange( + ctx, + &session2, + "Acknowledge the current session limits.", + ) + .await; + assert_session_limits_status(&exchange, "30 AI credits"); + + session2 + .disconnect() + .await + .expect("disconnect resumed session"); + session1 + .disconnect() + .await + .expect("disconnect original session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_apply_excluded_built_in_agents_on_create() { + with_e2e_context( + "session_config", + "should_apply_excluded_built_in_agents_on_create", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + + let baseline = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create baseline session"); + let baseline_exchange = + send_and_get_next_exchange(ctx, &baseline, "What is 1+1?").await; + let baseline_agents = task_agent_types(&baseline_exchange); + assert!( + baseline_agents.iter().any(|agent| agent == "explore"), + "expected baseline task agents to include explore, got {baseline_agents:?}" + ); + baseline + .disconnect() + .await + .expect("disconnect baseline session"); + + let excluded = client + .create_session( + ctx.approve_all_session_config() + .with_excluded_builtin_agents(["explore"]), + ) + .await + .expect("create excluded-agent session"); + let excluded_exchange = + send_and_get_next_exchange(ctx, &excluded, "What is 1+1?").await; + let excluded_agents = task_agent_types(&excluded_exchange); + assert!(!excluded_agents.is_empty()); + assert!( + !excluded_agents.iter().any(|agent| agent == "explore"), + "expected task agents not to include explore, got {excluded_agents:?}" + ); + + excluded + .disconnect() + .await + .expect("disconnect excluded-agent session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[tokio::test] +async fn should_apply_excluded_built_in_agents_on_resume() { + with_e2e_context( + "session_config", + "should_apply_excluded_built_in_agents_on_resume", + |ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let client = ctx.start_client().await; + let session1 = client + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + let session2 = client + .resume_session( + ResumeSessionConfig::new(session1.id().clone()) + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_github_token(DEFAULT_TEST_TOKEN) + .with_excluded_builtin_agents(["explore"]), + ) + .await + .expect("resume session"); + + let exchange = send_and_get_next_exchange(ctx, &session2, "What is 1+1?").await; + let agent_types = task_agent_types(&exchange); + assert!(!agent_types.is_empty()); + assert!( + !agent_types.iter().any(|agent| agent == "explore"), + "expected task agents not to include explore, got {agent_types:?}" + ); + + session2 + .disconnect() + .await + .expect("disconnect resumed session"); + session1 + .disconnect() + .await + .expect("disconnect original session"); + client.stop().await.expect("stop client"); + }) + }, + ) + .await; +} + +#[derive(Clone, Default)] +struct RecordingHandler { + records: Arc>>, +} + +#[derive(Clone)] +struct RecordedRequest { + url: String, + body: Vec, +} + +impl RecordingHandler { + fn inference_records(&self) -> Vec { + self.records + .lock() + .iter() + .filter(|record| is_inference_url(&record.url)) + .cloned() + .collect() + } +} + +#[async_trait] +impl CopilotRequestHandler for RecordingHandler { + async fn send_request( + &self, + request: CopilotHttpRequest, + _ctx: &CopilotRequestContext, + ) -> Result { + self.records.lock().push(RecordedRequest { + url: request.url.clone(), + body: request.body.clone(), + }); + if is_inference_url(&request.url) { + return Ok(synth_inference_response(&request.url, &request.body)); + } + Ok(synth_non_inference_response(&request.url)) + } +} + +fn is_inference_url(url: &str) -> bool { + let url = url.to_lowercase(); + url.ends_with("/chat/completions") + || url.ends_with("/responses") + || url.ends_with("/v1/messages") + || url.ends_with("/messages") +} + +fn json_headers() -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert("content-type", HeaderValue::from_static("application/json")); + headers +} + +fn http_response(status: u16, headers: HeaderMap, body: Value) -> CopilotHttpResponse { + let bytes = serde_json::to_vec(&body).expect("serialize response"); + let stream = + futures_util::stream::once( + async move { Ok::(Bytes::from(bytes)) }, + ); + CopilotHttpResponse::new(status, None, headers, Box::pin(stream)) +} + +fn sse_response(body: String) -> CopilotHttpResponse { + let mut headers = HeaderMap::new(); + headers.insert( + "content-type", + HeaderValue::from_static("text/event-stream"), + ); + let stream = futures_util::stream::once(async move { + Ok::(Bytes::from(body.into_bytes())) + }); + CopilotHttpResponse::new(200, None, headers, Box::pin(stream)) +} + +fn wants_stream(body: &[u8]) -> bool { + String::from_utf8_lossy(body) + .replace(char::is_whitespace, "") + .contains("\"stream\":true") +} + +fn anthropic_message_stream_body(text: &str) -> String { + let events = [ + ( + "message_start", + json!({ + "type": "message_start", + "message": { + "id": "msg_stub_1", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4.5", + "content": [], + "stop_reason": null, + "stop_sequence": null, + "usage": { "input_tokens": 5, "output_tokens": 1 }, + }, + }), + ), + ( + "content_block_start", + json!({ + "type": "content_block_start", + "index": 0, + "content_block": { "type": "text", "text": "" }, + }), + ), + ( + "content_block_delta", + json!({ + "type": "content_block_delta", + "index": 0, + "delta": { "type": "text_delta", "text": text }, + }), + ), + ( + "content_block_stop", + json!({ "type": "content_block_stop", "index": 0 }), + ), + ( + "message_delta", + json!({ + "type": "message_delta", + "delta": { "stop_reason": "end_turn", "stop_sequence": null }, + "usage": { "output_tokens": 7 }, + }), + ), + ("message_stop", json!({ "type": "message_stop" })), + ]; + events + .iter() + .map(|(name, data)| format!("event: {name}\ndata: {data}\n\n")) + .collect() +} + +fn synth_non_inference_response(url: &str) -> CopilotHttpResponse { + let lower = url.to_lowercase(); + if lower.ends_with("/models") { + return http_response( + 200, + json_headers(), + json!({ + "data": [{ + "id": "claude-sonnet-4.5", + "name": "Claude Sonnet 4.5", + "object": "model", + "vendor": "Anthropic", + "version": "1", + "preview": false, + "model_picker_enabled": true, + "capabilities": { + "type": "chat", + "family": "claude-sonnet-4.5", + "tokenizer": "o200k_base", + "limits": { + "max_context_window_tokens": 200000, + "max_output_tokens": 8192, + }, + "supports": { + "streaming": true, + "tool_calls": true, + "parallel_tool_calls": true, + "vision": true, + }, + }, + }], + }), + ); + } + if lower.contains("/policy") { + return http_response(200, json_headers(), json!({ "state": "enabled" })); + } + http_response(200, json_headers(), json!({})) +} + +fn synth_inference_response(url: &str, body: &[u8]) -> CopilotHttpResponse { + let lower = url.to_lowercase(); + if lower.ends_with("/messages") { + if wants_stream(body) { + return sse_response(anthropic_message_stream_body(SYNTHETIC_TEXT)); + } + return http_response( + 200, + json_headers(), + json!({ + "id": "msg_stub_1", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4.5", + "content": [{ "type": "text", "text": SYNTHETIC_TEXT }], + "stop_reason": "end_turn", + "stop_sequence": null, + "usage": { "input_tokens": 5, "output_tokens": 7 }, + }), + ); + } + http_response( + 200, + json_headers(), + json!({ + "id": "chatcmpl-stub-1", + "object": "chat.completion", + "created": 1, + "model": "claude-sonnet-4.5", + "choices": [{ + "index": 0, + "message": { "role": "assistant", "content": SYNTHETIC_TEXT }, + "finish_reason": "stop", + }], + "usage": { "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12 }, + }), + ) +} + +fn anthropic_provider() -> ProviderConfig { + ProviderConfig::new("https://anthropic-citations.invalid/v1") + .with_provider_type("anthropic") + .with_api_key("test-provider-key") + .with_model_id("claude-sonnet-4.5") + .with_wire_model("claude-sonnet-4.5") +} + +fn pdf_attachment() -> Attachment { + let pdf_text = + "%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n"; + Attachment::Blob { + data: base64::engine::general_purpose::STANDARD.encode(pdf_text), + mime_type: "application/pdf".to_string(), + display_name: Some("citation-source.pdf".to_string()), + } +} + +fn assert_anthropic_document_citations_enabled(request_body: &[u8]) { + let body: Value = serde_json::from_slice(request_body).expect("Anthropic request body"); + let documents: Vec<&Value> = body["messages"] + .as_array() + .expect("messages") + .iter() + .flat_map(|message| message["content"].as_array().expect("message content")) + .filter(|block| block["type"] == "document") + .collect(); + + assert_eq!(documents.len(), 1); + assert_eq!(documents[0]["title"], "citation-source.pdf"); + assert_eq!(documents[0]["citations"]["enabled"], true); +} + +#[tokio::test] +async fn should_enable_citations_for_anthropic_file_attachments_on_create() { + if super::support::skip_inprocess("LLM inference providers are process-global in-process") { + return; + } + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let handler = RecordingHandler::default(); + let client = ctx.start_llm_client(handler.clone(), &[]).await; + let session = client + .create_session( + SessionConfig::default() + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_model("claude-sonnet-4.5") + .with_enable_citations(true) + .with_provider(anthropic_provider()), + ) + .await + .expect("create session"); + + session + .send_and_wait( + MessageOptions::new(CITATION_PROMPT) + .with_wait_timeout(Duration::from_secs(120)) + .with_attachments(vec![pdf_attachment()]), + ) + .await + .expect("send_and_wait"); + + let inference_records = handler.inference_records(); + assert_eq!(inference_records.len(), 1); + assert_anthropic_document_citations_enabled(&inference_records[0].body); + + session.disconnect().await.expect("disconnect session"); + client.stop().await.expect("stop client"); + }) + }) + .await; +} + +#[tokio::test] +async fn should_enable_citations_for_anthropic_file_attachments_on_resume() { + with_e2e_context_no_snapshot(|ctx| { + Box::pin(async move { + ctx.set_default_copilot_user(); + let handler = RecordingHandler::default(); + let port = free_tcp_port(); + let token = "rust-citation-resume-token".to_string(); + let server = Client::start( + ctx.client_options_with_transport(Transport::Tcp { + port, + connection_token: Some(token.clone()), + }) + .with_request_handler(handler.clone()), + ) + .await + .expect("start TCP server client"); + let session1 = server + .create_session(ctx.approve_all_session_config()) + .await + .expect("create session"); + let resume_client = + Client::start(ctx.client_options_with_transport(Transport::External { + host: "127.0.0.1".to_string(), + port, + connection_token: Some(token), + })) + .await + .expect("start external client"); + let session2 = resume_client + .resume_session( + ResumeSessionConfig::new(session1.id().clone()) + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_model("claude-sonnet-4.5") + .with_enable_citations(true) + .with_provider(anthropic_provider()), + ) + .await + .expect("resume session"); + + session2 + .send_and_wait( + MessageOptions::new(CITATION_PROMPT) + .with_wait_timeout(Duration::from_secs(120)) + .with_attachments(vec![pdf_attachment()]), + ) + .await + .expect("send_and_wait"); + + let inference_records = handler.inference_records(); + assert_eq!(inference_records.len(), 1); + assert_anthropic_document_citations_enabled(&inference_records[0].body); + + session2 + .disconnect() + .await + .expect("disconnect resumed session"); + session1 + .disconnect() + .await + .expect("disconnect original session"); + resume_client.stop().await.expect("stop external client"); + server.stop().await.expect("stop TCP server client"); + }) + }) + .await; +} + +fn free_tcp_port() -> u16 { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind free TCP port"); + listener.local_addr().expect("local addr").port() +} diff --git a/rust/tests/e2e/subagent_hooks.rs b/rust/tests/e2e/subagent_hooks.rs index 99529c433b..fe94c36779 100644 --- a/rust/tests/e2e/subagent_hooks.rs +++ b/rust/tests/e2e/subagent_hooks.rs @@ -5,12 +5,19 @@ use github_copilot_sdk::hooks::{ HookContext, PostToolUseInput, PostToolUseOutput, PreToolUseInput, PreToolUseOutput, SessionHooks, }; +use github_copilot_sdk::{ + CopilotHttpRequest, CopilotHttpResponse, CopilotRequestContext, CopilotRequestError, + CopilotRequestHandler, forward_http, +}; use parking_lot::Mutex; use super::support::with_e2e_context; #[tokio::test] async fn should_invoke_pretooluse_and_posttooluse_hooks_for_sub_agent_tool_calls() { + if super::support::skip_inprocess("LLM inference providers are process-global in-process") { + return; + } with_e2e_context( "subagent_hooks", "should_invoke_pretooluse_and_posttooluse_hooks_for_sub_agent_tool_calls", @@ -24,16 +31,14 @@ async fn should_invoke_pretooluse_and_posttooluse_hooks_for_sub_agent_tool_calls .expect("write test file"); let hook_log = Arc::new(Mutex::new(Vec::::new())); + let request_log = Arc::new(RecordingRequestHandler::default()); - let mut opts = ctx.client_options(); - opts.env.push(( - "COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS".into(), - "true".into(), - )); - - let client = github_copilot_sdk::Client::start(opts) - .await - .expect("start client"); + let client = ctx + .start_llm_client( + Arc::clone(&request_log), + &[("COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS", "true")], + ) + .await; let session = client .create_session(ctx.approve_all_session_config().with_hooks(Arc::new( @@ -88,6 +93,7 @@ async fn should_invoke_pretooluse_and_posttooluse_hooks_for_sub_agent_tool_calls task_pre.unwrap().session_id, "Sub-agent tool hooks should have a different sessionId than parent tool hooks" ); + assert_subagent_request_metadata(&request_log.inference_records()); session.disconnect().await.expect("disconnect session"); client.stop().await.expect("stop client"); @@ -104,6 +110,90 @@ struct HookEntry { session_id: String, } +#[derive(Clone, Debug)] +struct RequestEntry { + url: String, + agent_id: Option, + parent_agent_id: Option, + interaction_type: Option, +} + +#[derive(Default)] +struct RecordingRequestHandler { + log: Mutex>, +} + +impl RecordingRequestHandler { + fn inference_records(&self) -> Vec { + self.log + .lock() + .iter() + .filter(|entry| is_inference_url(&entry.url)) + .cloned() + .collect() + } +} + +#[async_trait] +impl CopilotRequestHandler for RecordingRequestHandler { + async fn send_request( + &self, + request: CopilotHttpRequest, + ctx: &CopilotRequestContext, + ) -> Result { + self.log.lock().push(RequestEntry { + url: request.url.clone(), + agent_id: ctx.agent_id.clone(), + parent_agent_id: ctx.parent_agent_id.clone(), + interaction_type: ctx.interaction_type.clone(), + }); + forward_http(request).await + } +} + +fn is_inference_url(url: &str) -> bool { + let url = url.to_lowercase(); + url.ends_with("/chat/completions") + || url.ends_with("/responses") + || url.ends_with("/v1/messages") + || url.ends_with("/messages") +} + +fn assert_subagent_request_metadata(records: &[RequestEntry]) { + assert!( + !records.is_empty(), + "request handler should observe inference requests" + ); + let subagent_request = records + .iter() + .find(|entry| { + entry + .parent_agent_id + .as_deref() + .is_some_and(|id| !id.is_empty()) + }) + .expect("sub-agent inference request should carry a parentAgentId"); + assert!( + subagent_request + .agent_id + .as_deref() + .is_some_and(|id| !id.is_empty()), + "sub-agent inference request should carry an agentId" + ); + assert!( + subagent_request + .interaction_type + .as_deref() + .is_some_and(|kind| !kind.is_empty()), + "sub-agent inference request should carry an interactionType" + ); + assert_ne!( + subagent_request.parent_agent_id.as_deref(), + subagent_request.agent_id.as_deref(), + "sub-agent inference request should have distinct parent and child agent ids" + ); +} + struct RecordingHooks { log: Arc>>, } diff --git a/rust/tests/e2e/support.rs b/rust/tests/e2e/support.rs index 1805eb145b..6ad609f58e 100644 --- a/rust/tests/e2e/support.rs +++ b/rust/tests/e2e/support.rs @@ -1,4 +1,4 @@ -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::future::Future; use std::io::{BufRead, BufReader, Read, Write}; use std::net::TcpStream; @@ -36,6 +36,13 @@ where .await .unwrap_or_else(|err| panic!("create E2E context: {err}")); + // In-process hosting: the runtime loads into this test process and its worker + // inherits the ambient environment (per-client env is not honored in-process, see + // https://github.com/github/copilot-sdk/issues/1934), so mirror this context's env + // onto the process for the duration of the test and restore on drop. Safe because + // E2E_CONCURRENCY is 1 in-process, serializing the whole critical section. + let _env_guard = InProcessEnvGuard::activate(&ctx); + let timed_out = tokio::time::timeout(default_test_timeout(), test(&mut ctx)) .await .is_err(); @@ -65,6 +72,10 @@ where .await .unwrap_or_else(|err| panic!("create E2E context: {err}")); + // See `with_e2e_context` for why the in-process transport mirrors env onto the + // process (restored on drop). + let _env_guard = InProcessEnvGuard::activate(&ctx); + let timed_out = tokio::time::timeout(default_test_timeout(), test(&mut ctx)) .await .is_err(); @@ -104,6 +115,7 @@ impl E2eContext { proxy: Some(proxy), }; ctx.configure(category, snapshot_name)?; + ctx.set_default_copilot_user(); Ok(ctx) } @@ -133,6 +145,7 @@ impl E2eContext { .map_err(|err| { std::io::Error::other(format!("configure proxy without snapshot failed: {err}")) })?; + ctx.set_default_copilot_user(); Ok(ctx) } @@ -157,24 +170,36 @@ impl E2eContext { } pub fn client_options(&self) -> ClientOptions { - ClientOptions::new() - .with_program(CliProgram::Path(PathBuf::from(node_program()))) - .with_prefix_args([self.cli_path.as_os_str().to_owned()]) - .with_cwd(self.work_dir.path()) - .with_env(self.environment()) - .with_use_logged_in_user(false) + client_options_for_cli(&self.cli_path, self.work_dir.path(), self.environment()) } pub fn client_options_with_transport(&self, transport: Transport) -> ClientOptions { self.client_options().with_transport(transport) } + pub fn client_options_with_github_token(&self, token: &str) -> ClientOptions { + self.client_options().with_github_token(token) + } + pub async fn start_client(&self) -> Client { Client::start(self.client_options()) .await .expect("start E2E client") } + /// Start a client that hosts the runtime in-process over FFI + /// ([`Transport::InProcess`]). Unlike the stdio harness, the CLI + /// entrypoint is passed as the program directly (the FFI host builds the + /// `node --embedded-host` argv itself and loads the sibling + /// runtime cdylib), so a `.js` entrypoint is not split into node + + /// prefix_args here. + pub async fn start_inprocess_client(&self) -> Client { + let options = ClientOptions::new().with_transport(Transport::InProcess); + Client::start(options) + .await + .expect("start in-process FFI E2E client") + } + /// Start a client wired to a Copilot request handler, appending `extra_env` /// to the spawned runtime's environment (used to flip the WebSocket ExP /// flag for the WS transport tests). @@ -188,12 +213,7 @@ impl E2eContext { .iter() .map(|(key, value)| (OsString::from(*key), OsString::from(*value))), ); - let options = ClientOptions::new() - .with_program(CliProgram::Path(PathBuf::from(node_program()))) - .with_prefix_args([self.cli_path.as_os_str().to_owned()]) - .with_cwd(self.work_dir.path()) - .with_env(env) - .with_use_logged_in_user(false) + let options = client_options_for_cli(&self.cli_path, self.work_dir.path(), env) .with_request_handler(handler); Client::start(options).await.expect("start E2E LLM client") } @@ -310,11 +330,15 @@ impl E2eContext { .as_os_str() .to_owned(), ), + ("COPILOT_MCP_APPS".into(), "true".into()), + ("MCP_APPS".into(), "true".into()), + ("GH_TOKEN".into(), DEFAULT_TEST_TOKEN.into()), + ("GITHUB_TOKEN".into(), DEFAULT_TEST_TOKEN.into()), + ("GH_ENTERPRISE_TOKEN".into(), "".into()), + ("GITHUB_ENTERPRISE_TOKEN".into(), "".into()), + ("COPILOT_HMAC_KEY".into(), "".into()), + ("CAPI_HMAC_KEY".into(), "".into()), ]); - if std::env::var("GITHUB_ACTIONS").as_deref() == Ok("true") { - env.push(("GH_TOKEN".into(), "fake-token-for-e2e-tests".into())); - env.push(("GITHUB_TOKEN".into(), "fake-token-for-e2e-tests".into())); - } env } @@ -536,6 +560,12 @@ fn default_test_timeout() -> Duration { } fn e2e_concurrency() -> usize { + // The in-process transport mirrors per-test environment onto the shared process + // environment (see `InProcessEnvGuard`), which is only coherent when one test runs + // at a time. Force serial execution in-process; otherwise honor RUST_E2E_CONCURRENCY. + if is_inprocess_default() { + return 1; + } std::env::var("RUST_E2E_CONCURRENCY") .ok() .and_then(|value| value.parse::().ok()) @@ -543,6 +573,104 @@ fn e2e_concurrency() -> usize { .unwrap_or(4) } +/// True when the E2E suite runs over the in-process (FFI) transport, i.e. the SDK +/// resolves `COPILOT_SDK_DEFAULT_CONNECTION=inprocess` to [`Transport::InProcess`]. +pub fn is_inprocess_default() -> bool { + std::env::var("COPILOT_SDK_DEFAULT_CONNECTION") + .map(|value| value.eq_ignore_ascii_case("inprocess")) + .unwrap_or(false) +} + +/// Skip guard for E2E tests exercising features the in-process (FFI) transport does not +/// support (the runtime loads into the shared host process). Returns `true` — and logs — +/// when running in-process so the caller can `return` early; such tests remain covered +/// by the default (stdio) transport. See . +pub fn skip_inprocess(reason: &str) -> bool { + if is_inprocess_default() { + eprintln!("skipping test over the in-process (FFI) transport: {reason}"); + true + } else { + false + } +} + +/// Mirrors an [`E2eContext`]'s environment onto the real process environment for the +/// in-process transport, whose worker inherits this process's ambient environment +/// rather than a per-client env block. Restores the previous values on drop. Only the +/// in-process transport needs this; for stdio/tcp the environment is handed to the +/// spawned child directly. Auth flows via GH_TOKEN/GITHUB_TOKEN and HMAC is disabled so +/// host-side auth resolution picks the token the replay snapshots expect. +struct InProcessEnvGuard { + saved: Vec<(OsString, Option)>, + previous_cwd: PathBuf, +} + +impl InProcessEnvGuard { + /// Returns `Some` guard (having applied the env) when in-process, else `None`. + fn activate(ctx: &E2eContext) -> Option { + if !is_inprocess_default() { + return None; + } + let mut pairs: Vec<(OsString, OsString)> = ctx.environment(); + pairs.retain(|(key, _)| { + key.as_os_str() != OsStr::new("COPILOT_HMAC_KEY") + && key.as_os_str() != OsStr::new("CAPI_HMAC_KEY") + }); + pairs.push(("COPILOT_SDK_AUTH_TOKEN".into(), "".into())); + pairs.push(( + "COPILOT_CLI_PATH".into(), + ctx.cli_path.clone().into_os_string(), + )); + // Some tests opt into gated runtime APIs via per-client `options.env`, which the + // in-process transport does not pass to the shared native runtime (see issue #1934). + // These are process-global runtime gates (not per-client behavior), so applying + // them to the host process for the serial in-process suite is equivalent and + // inert for tests that don't exercise the gated API. + pairs.push(("COPILOT_ALLOW_GET_PROVIDER_ENDPOINT".into(), "true".into())); + pairs.push(( + "COPILOT_EXP_COPILOT_CLI_WEBSOCKET_RESPONSES".into(), + "true".into(), + )); + pairs.push(( + "COPILOT_EXP_COPILOT_CLI_SESSION_BASED_SUBAGENTS".into(), + "true".into(), + )); + + let mut saved: Vec<(OsString, Option)> = Vec::new(); + for (key, value) in &pairs { + saved.push((key.clone(), std::env::var_os(key))); + // SAFETY: the E2E suite runs serially in-process (concurrency 1), so no + // other thread races these process-wide env mutations. + unsafe { std::env::set_var(key, value) }; + } + for key in ["COPILOT_HMAC_KEY", "CAPI_HMAC_KEY"] { + let key = OsString::from(key); + saved.push((key.clone(), std::env::var_os(&key))); + // SAFETY: as above, the in-process suite is serialized. + unsafe { std::env::remove_var(key) }; + } + let previous_cwd = std::env::current_dir().expect("read in-process test cwd"); + std::env::set_current_dir(ctx.work_dir()).expect("set in-process test cwd"); + Some(Self { + saved, + previous_cwd, + }) + } +} + +impl Drop for InProcessEnvGuard { + fn drop(&mut self) { + std::env::set_current_dir(&self.previous_cwd).expect("restore in-process test cwd"); + for (key, previous) in self.saved.iter().rev() { + // SAFETY: as in `activate` — serial execution in-process. + match previous { + Some(value) => unsafe { std::env::set_var(key, value) }, + None => unsafe { std::env::remove_var(key) }, + } + } + } +} + pub fn get_system_message(exchange: &serde_json::Value) -> String { exchange .get("request") @@ -625,6 +753,32 @@ fn cli_path(repo_root: &Path) -> std::io::Result { )) } +#[allow(deprecated)] +fn client_options_for_cli( + cli_path: &Path, + cwd: &Path, + env: Vec<(OsString, OsString)>, +) -> ClientOptions { + if is_inprocess_default() { + return ClientOptions::new(); + } + let options = ClientOptions::new() + .with_cwd(cwd) + .with_env(env) + .with_use_logged_in_user(false); + if cli_path + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| extension.eq_ignore_ascii_case("js")) + { + options + .with_program(CliProgram::Path(PathBuf::from(node_program()))) + .with_prefix_args([cli_path.as_os_str().to_owned()]) + } else { + options.with_program(CliProgram::Path(cli_path.to_path_buf())) + } +} + fn canonical_temp_path(path: &Path) -> PathBuf { std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) } diff --git a/rust/tests/e2e/telemetry.rs b/rust/tests/e2e/telemetry.rs index 38bf4a404a..f6905427ae 100644 --- a/rust/tests/e2e/telemetry.rs +++ b/rust/tests/e2e/telemetry.rs @@ -13,6 +13,11 @@ use super::support::{assistant_message_content, with_e2e_context}; #[tokio::test] async fn should_export_file_telemetry_for_sdk_interactions() { + // Telemetry lowers to environment variables the in-process worker cannot receive + // per-client; covered by the default (stdio) transport. See issue #1934. + if super::support::skip_inprocess("telemetry configuration is not honored in-process") { + return; + } with_e2e_context( "telemetry", "should_export_file_telemetry_for_sdk_interactions", diff --git a/rust/tests/e2e/tool_results.rs b/rust/tests/e2e/tool_results.rs index a6047007ff..e6e62643fa 100644 --- a/rust/tests/e2e/tool_results.rs +++ b/rust/tests/e2e/tool_results.rs @@ -213,14 +213,7 @@ async fn recv_called(receiver: &mut mpsc::UnboundedReceiver<()>, description: &' } fn expanded(text: impl Into, result_type: impl Into) -> ToolResult { - ToolResult::Expanded(ToolResultExpanded { - text_result_for_llm: text.into(), - result_type: result_type.into(), - binary_results_for_llm: None, - session_log: None, - error: None, - tool_telemetry: None, - }) + ToolResult::Expanded(ToolResultExpanded::new(text, result_type)) } fn weather_tool() -> Tool { diff --git a/rust/tests/session_test.rs b/rust/tests/session_test.rs index 98c6248230..122ec475df 100644 --- a/rust/tests/session_test.rs +++ b/rust/tests/session_test.rs @@ -9,19 +9,23 @@ use async_trait::async_trait; use github_copilot_sdk::canvas::{CanvasDeclaration, CanvasHandler, CanvasResult}; use github_copilot_sdk::handler::{ ApproveAllHandler, AutoModeSwitchHandler, AutoModeSwitchResponse, ElicitationHandler, - ExitPlanModeHandler, ExitPlanModeResult, UserInputHandler, UserInputResponse, + ExitPlanModeHandler, ExitPlanModeResult, McpAuthHandler, McpAuthRequest, McpAuthResult, + UserInputHandler, UserInputResponse, }; use github_copilot_sdk::rpc::{ CanvasProviderInvokeActionRequest, CanvasProviderOpenRequest, CanvasProviderOpenResult, OpenCanvasInstance, }; -use github_copilot_sdk::session_events::ReasoningSummary; +use github_copilot_sdk::session_events::{ + McpOauthRequiredData, ReasoningSummary, SessionLimitsConfig, +}; use github_copilot_sdk::types::{ - CommandContext, CommandDefinition, CommandHandler, DeliveryMode, ElicitationRequest, - ElicitationResult, ExitPlanModeData, ExtensionInfo, MessageOptions, RequestId, SessionConfig, - SessionId, SetModelOptions, Tool, ToolInvocation, ToolResult, + CanvasProviderIdentity, CloudSessionOptions, CloudSessionRepository, CommandContext, + CommandDefinition, CommandHandler, DeliveryMode, ElicitationRequest, ElicitationResult, + ExitPlanModeData, ExtensionInfo, MessageOptions, RequestId, SessionConfig, SessionId, + SetModelOptions, Tool, ToolInvocation, ToolResult, }; -use github_copilot_sdk::{Client, ContextTier, tool}; +use github_copilot_sdk::{Client, ContextTier, ErrorKind, ProtocolErrorKind, tool}; use serde_json::Value; use tokio::io::{AsyncWrite, AsyncWriteExt, duplex}; use tokio::time::timeout; @@ -30,6 +34,20 @@ const TIMEOUT: Duration = Duration::from_secs(2); struct TestCanvasHandler; +struct CancelMcpAuthHandler; + +#[async_trait] +impl McpAuthHandler for CancelMcpAuthHandler { + async fn handle( + &self, + _session_id: SessionId, + _request_id: RequestId, + _request: McpAuthRequest, + ) -> McpAuthResult { + McpAuthResult::Cancelled + } +} + #[async_trait] impl CanvasHandler for TestCanvasHandler { async fn on_open( @@ -220,12 +238,295 @@ fn rand_id() -> u64 { COUNTER.fetch_add(1, Ordering::Relaxed) as u64 } +#[test] +fn mcp_oauth_required_data_allows_optional_metadata() { + let with_metadata: McpOauthRequiredData = serde_json::from_value(serde_json::json!({ + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp", + "wwwAuthenticateParams": { + "resourceMetadataUrl": "https://example.com/.well-known/oauth-protected-resource" + }, + "resourceMetadata": "{\"resource\":\"https://example.com/mcp\"}", + "staticClientConfig": { + "clientId": "static-client", + "clientSecret": "static-secret", + "publicClient": false + } + })) + .unwrap(); + assert_eq!( + with_metadata.resource_metadata.as_deref(), + Some("{\"resource\":\"https://example.com/mcp\"}") + ); + assert!(with_metadata.www_authenticate_params.is_some()); + assert_eq!( + with_metadata + .static_client_config + .as_ref() + .and_then(|config| config.client_secret.as_deref()), + Some("static-secret") + ); + + let without_metadata: McpOauthRequiredData = serde_json::from_value(serde_json::json!({ + "requestId": "oauth-request", + "reason": "initial", + "serverName": "oauth-server", + "serverUrl": "https://example.com/mcp" + })) + .unwrap(); + assert!(without_metadata.resource_metadata.is_none()); + assert!(without_metadata.www_authenticate_params.is_none()); +} + fn requested_session_id(request: &Value) -> &str { request["params"]["sessionId"] .as_str() .expect("session request should include sessionId") } +#[tokio::test] +async fn create_session_registers_mcp_auth_interest_only_with_handler() { + let (client, mut server_read, mut server_write) = make_client(); + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session( + SessionConfig::default().with_permission_handler(Arc::new(ApproveAllHandler)), + ) + .await + .unwrap() + } + }); + + let create_req = read_framed(&mut server_read).await; + assert_eq!(create_req["method"], "session.create"); + assert_eq!(create_req["params"]["requestPermission"], true); + let session_id = requested_session_id(&create_req).to_string(); + server_respond_create(&mut server_write, &create_req, &session_id).await; + let session = timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); + + let no_extra_request = timeout(Duration::from_millis(50), read_framed(&mut server_read)).await; + assert!(no_extra_request.is_err()); + drop(session); + + let (client, mut server_read, mut server_write) = make_client(); + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session( + SessionConfig::default() + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_mcp_auth_handler(Arc::new(CancelMcpAuthHandler)), + ) + .await + .unwrap() + } + }); + + let create_req = read_framed(&mut server_read).await; + assert_eq!(create_req["method"], "session.create"); + assert_eq!(create_req["params"]["requestPermission"], true); + let session_id = requested_session_id(&create_req).to_string(); + server_respond_create(&mut server_write, &create_req, &session_id).await; + + let interest_req = read_framed(&mut server_read).await; + assert_eq!(interest_req["method"], "session.eventLog.registerInterest"); + assert_eq!(interest_req["params"]["eventType"], "mcp.oauth_required"); + let id = interest_req["id"].as_u64().unwrap(); + write_framed( + &mut server_write, + &serde_json::to_vec(&serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "id": "interest-1" }, + })) + .unwrap(), + ) + .await; + + let _session = timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn cloud_create_session_registers_mcp_auth_interest_after_create_only_with_handler() { + let cloud = || { + CloudSessionOptions::with_repository( + CloudSessionRepository::new("github", "copilot-sdk").with_branch("main"), + ) + }; + + let (client, mut server_read, mut server_write) = make_client(); + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session( + SessionConfig::default() + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_cloud(cloud()), + ) + .await + .unwrap() + } + }); + + let create_req = read_framed(&mut server_read).await; + assert_eq!(create_req["method"], "session.create"); + assert!(create_req["params"].get("sessionId").is_none()); + assert_eq!(create_req["params"]["requestPermission"], true); + server_respond_create(&mut server_write, &create_req, "server-assigned-session-1").await; + let session = timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); + let no_extra_request = timeout(Duration::from_millis(50), read_framed(&mut server_read)).await; + assert!(no_extra_request.is_err()); + drop(session); + + let (client, mut server_read, mut server_write) = make_client(); + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session( + SessionConfig::default() + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_mcp_auth_handler(Arc::new(CancelMcpAuthHandler)) + .with_cloud(cloud()), + ) + .await + .unwrap() + } + }); + + let create_req = read_framed(&mut server_read).await; + assert_eq!(create_req["method"], "session.create"); + assert!(create_req["params"].get("sessionId").is_none()); + assert_eq!(create_req["params"]["requestPermission"], true); + server_respond_create(&mut server_write, &create_req, "server-assigned-session-2").await; + + let interest_req = read_framed(&mut server_read).await; + assert_eq!(interest_req["method"], "session.eventLog.registerInterest"); + assert_eq!( + interest_req["params"]["sessionId"], + "server-assigned-session-2" + ); + assert_eq!(interest_req["params"]["eventType"], "mcp.oauth_required"); + let id = interest_req["id"].as_u64().unwrap(); + write_framed( + &mut server_write, + &serde_json::to_vec(&serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "id": "interest-1" }, + })) + .unwrap(), + ) + .await; + let _session = timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn resume_session_registers_mcp_auth_interest_only_with_handler() { + use github_copilot_sdk::types::ResumeSessionConfig; + + let (client, mut server_read, mut server_write) = make_client(); + let resume_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .resume_session( + ResumeSessionConfig::new(SessionId::from("session-without-auth")) + .with_permission_handler(Arc::new(ApproveAllHandler)), + ) + .await + .unwrap() + } + }); + + let resume_req = read_framed(&mut server_read).await; + assert_eq!(resume_req["method"], "session.resume"); + assert_eq!(resume_req["params"]["requestPermission"], true); + server_respond_create(&mut server_write, &resume_req, "session-without-auth").await; + respond_to_reload(&mut server_read, &mut server_write).await; + let session = timeout(TIMEOUT, resume_handle).await.unwrap().unwrap(); + let no_extra_request = timeout(Duration::from_millis(50), read_framed(&mut server_read)).await; + assert!(no_extra_request.is_err()); + drop(session); + + let (client, mut server_read, mut server_write) = make_client(); + let resume_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .resume_session( + ResumeSessionConfig::new(SessionId::from("session-with-auth")) + .with_permission_handler(Arc::new(ApproveAllHandler)) + .with_mcp_auth_handler(Arc::new(CancelMcpAuthHandler)), + ) + .await + .unwrap() + } + }); + + let resume_req = read_framed(&mut server_read).await; + assert_eq!(resume_req["method"], "session.resume"); + assert_eq!(resume_req["params"]["requestPermission"], true); + server_respond_create(&mut server_write, &resume_req, "session-with-auth").await; + + let interest_req = read_framed(&mut server_read).await; + assert_eq!(interest_req["method"], "session.eventLog.registerInterest"); + assert_eq!(interest_req["params"]["eventType"], "mcp.oauth_required"); + let id = interest_req["id"].as_u64().unwrap(); + write_framed( + &mut server_write, + &serde_json::to_vec(&serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "id": "interest-1" }, + })) + .unwrap(), + ) + .await; + + respond_to_reload(&mut server_read, &mut server_write).await; + let _session = timeout(TIMEOUT, resume_handle).await.unwrap().unwrap(); +} + +async fn server_respond_create( + writer: &mut (impl AsyncWrite + Unpin), + request: &Value, + session_id: &str, +) { + let id = request["id"].as_u64().unwrap(); + write_framed( + writer, + &serde_json::to_vec(&serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": session_id, "workspacePath": "/tmp/workspace" }, + })) + .unwrap(), + ) + .await; +} + +async fn respond_to_reload( + reader: &mut (impl tokio::io::AsyncRead + Unpin), + writer: &mut (impl AsyncWrite + Unpin), +) { + let reload = read_framed(reader).await; + assert_eq!(reload["method"], "session.skills.reload"); + let id = reload["id"].as_u64().unwrap(); + write_framed( + writer, + &serde_json::to_vec(&serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": {} })) + .unwrap(), + ) + .await; +} + #[tokio::test] async fn session_subscribe_yields_events_observe_only() { let (session, mut server) = create_session_pair().await; @@ -326,6 +627,86 @@ async fn create_session_sends_correct_rpc() { assert_eq!(session.workspace_path(), Some(Path::new("/ws"))); } +#[tokio::test] +async fn create_session_sends_new_session_options() { + let (client, mut server_read, mut server_write) = make_client(); + + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session( + SessionConfig::default() + .with_excluded_builtin_agents(["explore"]) + .with_enable_citations(true) + .with_session_limits(SessionLimitsConfig { + max_ai_credits: Some(30.0), + }), + ) + .await + .unwrap() + } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "session.create"); + assert_eq!( + request["params"]["excludedBuiltinAgents"], + serde_json::json!(["explore"]) + ); + assert_eq!(request["params"]["enableCitations"], true); + assert_eq!(request["params"]["sessionLimits"]["maxAiCredits"], 30.0); + + let id = request["id"].as_u64().unwrap(); + let session_id = requested_session_id(&request).to_string(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": session_id, "workspacePath": "/ws" }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + + timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn resume_session_sends_new_session_options() { + use github_copilot_sdk::types::ResumeSessionConfig; + + let (client, mut server_read, mut server_write) = make_client(); + + let resume_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .resume_session( + ResumeSessionConfig::new(SessionId::from("session-options")) + .with_excluded_builtin_agents(["task"]) + .with_enable_citations(false) + .with_session_limits(SessionLimitsConfig { + max_ai_credits: Some(15.0), + }), + ) + .await + .unwrap() + } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "session.resume"); + assert_eq!(request["params"]["sessionId"], "session-options"); + assert_eq!( + request["params"]["excludedBuiltinAgents"], + serde_json::json!(["task"]) + ); + assert_eq!(request["params"]["enableCitations"], false); + assert_eq!(request["params"]["sessionLimits"]["maxAiCredits"], 15.0); + + server_respond_create(&mut server_write, &request, "session-options").await; + respond_to_reload(&mut server_read, &mut server_write).await; + timeout(TIMEOUT, resume_handle).await.unwrap().unwrap(); +} + #[tokio::test] async fn create_session_sends_canvas_wire_fields() { let (client, mut server_read, mut server_write) = make_client(); @@ -339,7 +720,11 @@ async fn create_session_sends_canvas_wire_fields() { .with_canvases([test_canvas("counter")]) .with_request_canvas_renderer(true) .with_request_extensions(true) - .with_extension_info(ExtensionInfo::new("github-app", "counter-provider")), + .with_extension_info(ExtensionInfo::new("github-app", "counter-provider")) + .with_canvas_provider( + CanvasProviderIdentity::new("app:builtin:window-1") + .with_name("Built-in"), + ), ) .await .unwrap() @@ -360,6 +745,125 @@ async fn create_session_sends_canvas_wire_fields() { request["params"]["extensionInfo"]["name"], "counter-provider" ); + assert_eq!( + request["params"]["canvasProvider"]["id"], + "app:builtin:window-1" + ); + assert_eq!(request["params"]["canvasProvider"]["name"], "Built-in"); + + let id = request["id"].as_u64().unwrap(); + let session_id = requested_session_id(&request).to_string(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": session_id }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + + timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); +} + +fn make_client_with_telemetry( + callback: github_copilot_sdk::github_telemetry::GitHubTelemetryCallback, +) -> (Client, tokio::io::DuplexStream, tokio::io::DuplexStream) { + let (client_write, server_read) = duplex(8192); + let (server_write, client_read) = duplex(8192); + let client = Client::from_streams_with_github_telemetry( + client_read, + client_write, + std::env::temp_dir(), + callback, + ) + .unwrap(); + (client, server_read, server_write) +} + +#[tokio::test] +async fn create_and_resume_send_github_telemetry_forwarding_when_callback_registered() { + use github_copilot_sdk::types::ResumeSessionConfig; + + let callback: github_copilot_sdk::github_telemetry::GitHubTelemetryCallback = + Arc::new(|_notification| {}); + let (client, mut server_read, mut server_write) = make_client_with_telemetry(callback); + + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session(SessionConfig::default()) + .await + .unwrap() + } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "session.create"); + assert_eq!(request["params"]["enableGitHubTelemetryForwarding"], true); + + let id = request["id"].as_u64().unwrap(); + let session_id = requested_session_id(&request).to_string(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": session_id.clone() }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); + + let resume_handle = tokio::spawn({ + let client = client.clone(); + let session_id = session_id.clone(); + async move { + client + .resume_session(ResumeSessionConfig::new(SessionId::from(session_id))) + .await + .unwrap() + } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "session.resume"); + assert_eq!(request["params"]["enableGitHubTelemetryForwarding"], true); + + let id = request["id"].as_u64().unwrap(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": session_id }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + + let reload = read_framed(&mut server_read).await; + assert_eq!(reload["method"], "session.skills.reload"); + let id = reload["id"].as_u64().unwrap(); + let response = serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": {} }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + + timeout(TIMEOUT, resume_handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn create_session_omits_github_telemetry_forwarding_without_callback() { + let (client, mut server_read, mut server_write) = make_client(); + + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session(SessionConfig::default()) + .await + .unwrap() + } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "session.create"); + assert!( + request["params"] + .get("enableGitHubTelemetryForwarding") + .is_none_or(Value::is_null), + "forwarding flag should be omitted when no callback is registered" + ); let id = request["id"].as_u64().unwrap(); let session_id = requested_session_id(&request).to_string(); @@ -369,8 +873,210 @@ async fn create_session_sends_canvas_wire_fields() { "result": { "sessionId": session_id }, }); write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn resume_session_omits_github_telemetry_forwarding_without_callback() { + use github_copilot_sdk::types::ResumeSessionConfig; + + let (client, mut server_read, mut server_write) = make_client(); + + let resume_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .resume_session(ResumeSessionConfig::new(SessionId::from( + "sess-1".to_string(), + ))) + .await + .unwrap() + } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "session.resume"); + assert!( + request["params"] + .get("enableGitHubTelemetryForwarding") + .is_none_or(Value::is_null), + "forwarding flag should be omitted when no callback is registered" + ); + let id = request["id"].as_u64().unwrap(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": "sess-1" }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + + let reload = read_framed(&mut server_read).await; + assert_eq!(reload["method"], "session.skills.reload"); + let id = reload["id"].as_u64().unwrap(); + let response = serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": {} }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + + timeout(TIMEOUT, resume_handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn connect_sends_github_telemetry_forwarding_when_callback_registered() { + let callback: github_copilot_sdk::github_telemetry::GitHubTelemetryCallback = + Arc::new(|_notification| {}); + let (client, mut server_read, mut server_write) = make_client_with_telemetry(callback); + + let handle = tokio::spawn({ + let client = client.clone(); + async move { client.verify_protocol_version().await.unwrap() } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "connect"); + assert_eq!(request["params"]["enableGitHubTelemetryForwarding"], true); + + let id = request["id"].as_u64().unwrap(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "ok": true, "protocolVersion": 3, "version": "test" }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + timeout(TIMEOUT, handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn connect_omits_github_telemetry_forwarding_without_callback() { + let (client, mut server_read, mut server_write) = make_client(); + + let handle = tokio::spawn({ + let client = client.clone(); + async move { client.verify_protocol_version().await.unwrap() } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "connect"); + assert!( + request["params"] + .get("enableGitHubTelemetryForwarding") + .is_none_or(Value::is_null), + "forwarding flag should be omitted when no callback is registered" + ); + + let id = request["id"].as_u64().unwrap(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "ok": true, "protocolVersion": 3, "version": "test" }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + timeout(TIMEOUT, handle).await.unwrap().unwrap(); +} + +#[tokio::test] +async fn connect_rejects_invalid_protocol_version_values() { + for protocol_version in [-1, i64::from(u32::MAX) + 1] { + let (client, mut server_read, mut server_write) = make_client(); + + let handle = tokio::spawn({ + let client = client.clone(); + async move { client.verify_protocol_version().await } + }); + + let request = read_framed(&mut server_read).await; + assert_eq!(request["method"], "connect"); + + let id = request["id"].as_u64().unwrap(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "ok": true, "protocolVersion": protocol_version, "version": "test" }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; + + let err = timeout(TIMEOUT, handle) + .await + .unwrap() + .unwrap() + .unwrap_err(); + match err.kind() { + ErrorKind::Protocol(ProtocolErrorKind::InvalidProtocolVersion { server }) => { + assert_eq!(*server, protocol_version); + } + other => panic!("unexpected error kind: {other:?}"), + } + } +} + +#[tokio::test] +async fn github_telemetry_event_dispatches_to_callback() { + use github_copilot_sdk::github_telemetry::GitHubTelemetryNotification; + + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); + let callback: github_copilot_sdk::github_telemetry::GitHubTelemetryCallback = + Arc::new(move |notification| { + let _ = tx.send(notification); + }); + let (client, mut server_read, mut server_write) = make_client_with_telemetry(callback); + + let create_handle = tokio::spawn({ + let client = client.clone(); + async move { + client + .create_session(SessionConfig::default()) + .await + .unwrap() + } + }); + + let request = read_framed(&mut server_read).await; + let id = request["id"].as_u64().unwrap(); + let session_id = requested_session_id(&request).to_string(); + let response = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": { "sessionId": session_id.clone() }, + }); + write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; timeout(TIMEOUT, create_handle).await.unwrap().unwrap(); + + let notification = serde_json::json!({ + "jsonrpc": "2.0", + "method": "gitHubTelemetry.event", + "params": { + "sessionId": session_id.clone(), + "restricted": false, + "event": { + "kind": "tool_call_executed", + "properties": { "tool": "bash" }, + "metrics": { "duration_ms": 12.0 }, + "session_id": session_id.clone(), + "created_at": "2025-01-01T00:00:00Z" + } + } + }); + write_framed( + &mut server_write, + &serde_json::to_vec(¬ification).unwrap(), + ) + .await; + + let received = timeout(TIMEOUT, rx.recv()).await.unwrap().unwrap(); + assert_eq!(received.session_id.as_deref(), Some(session_id.as_str())); + assert!(!received.restricted); + assert_eq!(received.event.kind, "tool_call_executed"); + assert_eq!( + received.event.properties.get("tool").map(String::as_str), + Some("bash") + ); + assert_eq!( + received.event.metrics.get("duration_ms").copied(), + Some(12.0) + ); + assert_eq!( + received.event.created_at.as_deref(), + Some("2025-01-01T00:00:00Z") + ); } #[tokio::test] @@ -2614,11 +3320,13 @@ async fn resume_session_sends_canvas_fields_and_captures_open_canvases() { .with_request_canvas_renderer(true) .with_request_extensions(true) .with_extension_info(ExtensionInfo::new("github-app", "counter-provider")) + .with_canvas_provider(CanvasProviderIdentity::new("app:builtin:window-1")) .with_open_canvases([OpenCanvasInstance { instance_id: "counter-1".to_string(), extension_id: "github-app:counter-provider".to_string(), extension_name: Some("Counter Provider".to_string()), canvas_id: "counter".to_string(), + icon: None, title: Some("Counter".to_string()), status: Some("ready".to_string()), url: Some("https://example.test/counter".to_string()), @@ -2638,6 +3346,14 @@ async fn resume_session_sends_canvas_fields_and_captures_open_canvases() { request["params"]["extensionInfo"]["name"], "counter-provider" ); + assert_eq!( + request["params"]["canvasProvider"]["id"], + "app:builtin:window-1" + ); + assert!( + request["params"]["canvasProvider"].get("name").is_none(), + "name should be omitted from the wire when None, not serialized as null" + ); assert_eq!( request["params"]["openCanvases"][0]["instanceId"], "counter-1" diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index e1ceea5b11..24ec217f5b 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -27,6 +27,7 @@ import { findSharedSchemaDefinitions, postProcessSchema, propagateInternalVisibility, + filterNodeByVisibility, resolveRef, resolveObjectSchema, resolveSchema, @@ -230,7 +231,8 @@ function stripDurationMillisecondsSuffix(name: string): string { } function toCSharpPropertyName(propName: string, schema: JSONSchema7): string { - return toPascalCase(isDurationProperty(schema) ? stripDurationMillisecondsSuffix(propName) : propName); + const normalizedName = propName.replace(/^_+/, "") || propName; + return toPascalCase(isDurationProperty(schema) ? stripDurationMillisecondsSuffix(normalizedName) : normalizedName); } function isSecondsDurationPropertyName(propName: string | undefined): boolean { @@ -493,7 +495,9 @@ const COPYRIGHT = `/*----------------------------------------------------------- const EXPERIMENTAL_ATTRIBUTE = "[Experimental(Diagnostics.Experimental)]"; const EDITOR_BROWSABLE_NEVER_ATTRIBUTE = "[EditorBrowsable(EditorBrowsableState.Never)]"; -const OBSOLETE_ATTRIBUTE = `[Obsolete("This member is deprecated and will be removed in a future version.")]`; +const OBSOLETE_ATTRIBUTE = `#if NET5_0_OR_GREATER +[Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif`; const STRING_ENUM_RESERVED_MEMBER_NAMES = new Set(["Value", "Equals", "GetHashCode", "ToString", "Converter"]); function experimentalAttribute(indent = ""): string { @@ -507,7 +511,7 @@ function pushExperimentalAttribute(lines: string[], indent = ""): void { function obsoleteAttributes(indent = ""): string[] { return [ `${indent}${EDITOR_BROWSABLE_NEVER_ATTRIBUTE}`, - `${indent}${OBSOLETE_ATTRIBUTE}`, + ...OBSOLETE_ATTRIBUTE.split("\n").map((line) => line.startsWith("#") ? line : `${indent}${line}`), ]; } @@ -1319,7 +1323,7 @@ function emitSessionEventEnvelopeProperty( export function generateSessionEventsCode(schema: JSONSchema7): string { generatedEnums.clear(); sessionDefinitions = collectDefinitionCollections(schema as Record); - const variants = extractEventVariants(schema); + const variants = extractEventVariants(schema).filter((variant) => !isSchemaInternal(variant.dataSchema)); const knownTypes = new Map(); const nestedClasses = new Map(); const enumOutput: string[] = []; @@ -1378,12 +1382,16 @@ namespace GitHub.Copilot; if (variant.eventExperimental) { pushExperimentalAttribute(lines); } - const variantVisibility = isSchemaInternal(variant.dataSchema) ? "internal" : "public"; - lines.push(`${variantVisibility} sealed partial class ${variant.className} : SessionEvent`, `{`); + lines.push(`public sealed partial class ${variant.className} : SessionEvent`, `{`); lines.push(` /// `); lines.push(` [JsonIgnore]`, ` public override string Type => "${variant.typeName}";`, ""); lines.push(` /// The ${escapeXml(variant.typeName)} event payload.`); - lines.push(` [JsonPropertyName("data")]`, ` ${variantVisibility} required ${variant.dataClassName} Data { get; set; }`, `}`, ""); + lines.push( + ` [JsonPropertyName("data")]`, + ` public required ${variant.dataClassName} Data { get; set; }`, + `}`, + "" + ); } // Data classes @@ -1429,6 +1437,7 @@ let nonExperimentalRpcTypes = new Set(); let rpcKnownTypes = new Map(); let rpcEnumOutput: string[] = []; let externalRpcValueTypes = new Set(); +let rpcRootJsonSerializableTypes = new Set(); /** Schema definitions available during RPC generation (for $ref resolution). */ let rpcDefinitions: DefinitionCollections = { definitions: {}, $defs: {} }; @@ -1701,7 +1710,11 @@ function emitRpcResultType(typeName: string, schema: JSONSchema7, visibility: "p return typeName; } - return resolveRpcType(schema, true, typeName, "", classes); + const resultType = resolveRpcType(schema, true, typeName, "", classes); + if (resultType.includes("<") || resultType.endsWith("[]")) { + rpcRootJsonSerializableTypes.add(resultType.replace(/\?$/, "")); + } + return resultType; } /** @@ -2444,6 +2457,7 @@ function generateRpcCode( nonExperimentalRpcTypes.clear(); rpcKnownTypes.clear(); rpcEnumOutput = []; + rpcRootJsonSerializableTypes.clear(); generatedEnums.clear(); // Clear shared enum deduplication map externalRpcValueTypes = new Set([...externalValueTypes].map(typeToClassName)); rpcDefinitions = collectDefinitionCollections(schema as Record); @@ -2477,11 +2491,23 @@ function generateRpcCode( let sessionRpcParts: string[] = []; if (schema.session) sessionRpcParts = emitSessionRpcClasses(schema.session, classes); + // Client handler surfaces (interfaces, handler properties, RPC registration) + // are only generated for public methods. Internal client methods (e.g. + // `hooks.invoke`) are runtime transport plumbing and must not surface any + // generated code — including their request/result DTOs, which would + // otherwise leak as `internal` types referenced by a `public` handler + // interface (CS0050/CS0051 inconsistent accessibility). let clientSessionParts: string[] = []; - if (schema.clientSession) clientSessionParts = emitClientSessionApiRegistration(schema.clientSession, classes); + if (schema.clientSession) { + const publicClientSession = filterNodeByVisibility(schema.clientSession, "public"); + if (publicClientSession) clientSessionParts = emitClientSessionApiRegistration(publicClientSession, classes); + } let clientGlobalParts: string[] = []; - if (schema.clientGlobal) clientGlobalParts = emitClientGlobalApiRegistration(schema.clientGlobal, classes); + if (schema.clientGlobal) { + const publicClientGlobal = filterNodeByVisibility(schema.clientGlobal, "public"); + if (publicClientGlobal) clientGlobalParts = emitClientGlobalApiRegistration(publicClientGlobal, classes); + } const lines: string[] = []; lines.push(`${COPYRIGHT} @@ -2511,7 +2537,9 @@ namespace GitHub.Copilot.Rpc; if (clientGlobalParts.length > 0) lines.push(...clientGlobalParts, ""); // Add JsonSerializerContext for AOT/trimming support - const typeNames = [...emittedRpcClassSchemas.keys(), ...emittedRpcEnumResultTypes].sort(); + const typeNames = [ + ...new Set([...emittedRpcClassSchemas.keys(), ...emittedRpcEnumResultTypes, ...rpcRootJsonSerializableTypes]), + ].sort(); if (typeNames.length > 0) { lines.push(`[JsonSourceGenerationOptions(`); lines.push(` JsonSerializerDefaults.Web,`); diff --git a/scripts/codegen/go.ts b/scripts/codegen/go.ts index 5403fb4444..b1d7474b98 100644 --- a/scripts/codegen/go.ts +++ b/scripts/codegen/go.ts @@ -581,7 +581,8 @@ function extractGoEventVariants(schema: JSONSchema7): GoEventVariant[] { eventExperimental: isSchemaExperimental(variant), dataExperimental: isSchemaExperimental(dataSchema), }; - }); + }) + .filter((variant) => !isSchemaInternal(variant.dataSchema)); } function getGoSharedEventEnvelopeProperties(schema: JSONSchema7, ctx: GoCodegenCtx): GoEventEnvelopeProperty[] { @@ -3784,6 +3785,7 @@ async function generateRpc(schemaPath?: string): Promise { ...collectRpcMethods(schema.server || {}), ...collectRpcMethods(schema.session || {}), ...collectRpcMethods(schema.clientSession || {}), + ...collectRpcMethods(schema.clientGlobal || {}), ].sort((left, right) => left.rpcMethod.localeCompare(right.rpcMethod)); // Build a combined definition map, including shared API definitions plus @@ -4384,6 +4386,11 @@ function emitClientGlobalApiRegistration(lines: string[], clientSchema: Record !isSchemaInternal(variant.dataSchema)); } function getPySharedEventEnvelopeProperties(schema: JSONSchema7, ctx: PyCodegenCtx): PyEventEnvelopeProperty[] { @@ -2673,19 +2674,34 @@ export function generatePythonSessionEventsCode(schema: JSONSchema7): string { out.push(``); out.push(` def __init__(self, **kwargs: Any):`); out.push(` self._values = {key: _compat_from_json_value(value) for key, value in kwargs.items()}`); + out.push(` self._json_keys: dict[str, str] = {}`); + out.push(` self._json_values: dict[str, Any] | None = None`); out.push(` for key, value in self._values.items():`); out.push(` setattr(self, key, value)`); out.push(``); out.push(` @staticmethod`); out.push(` def from_dict(obj: Any) -> "Data":`); out.push(` assert isinstance(obj, dict)`); - out.push( - ` return Data(**{_compat_to_python_key(key): _compat_from_json_value(value) for key, value in obj.items()})` - ); + out.push(` data = Data()`); + out.push(` data._values = {}`); + out.push(` data._json_keys = {}`); + out.push(` data._json_values = {}`); + out.push(` for key, value in obj.items():`); + out.push(` py_key = _compat_to_python_key(key)`); + out.push(` json_value = _compat_from_json_value(value)`); + out.push(` data._values[py_key] = json_value`); + out.push(` data._json_keys[py_key] = key`); + out.push(` data._json_values[key] = json_value`); + out.push(` setattr(data, py_key, data._values[py_key])`); + out.push(` return data`); out.push(``); out.push(` def to_dict(self) -> dict:`); + out.push(` if self._json_values is not None:`); + out.push( + ` return {key: _compat_to_json_value(value) for key, value in self._json_values.items() if value is not None}` + ); out.push( - ` return {_compat_to_json_key(key): _compat_to_json_value(value) for key, value in self._values.items() if value is not None}` + ` return {(self._json_keys.get(key) or _compat_to_json_key(key)): _compat_to_json_value(value) for key, value in self._values.items() if value is not None}` ); out.push(``); out.push(``); @@ -3791,6 +3807,20 @@ function emitClientGlobalRegistrationMethod( const handlerField = toSnakeCase(groupName); const handlerMethod = clientSessionHandlerMethodName(method.rpcMethod); + if (method.notification) { + // Notification methods carry no response and are dispatched via the + // notification path (an `id`-less message never reaches a request + // handler), so register on the method-specific notification registry. + lines.push(` async def ${handlerVariableName}(params: dict) -> None:`); + lines.push(` request = ${paramsType}.from_dict(params)`); + lines.push(` handler = handlers.${handlerField}`); + lines.push(` if handler is None: return None`); + lines.push(` await handler.${handlerMethod}(request)`); + lines.push(` return None`); + lines.push(` client.set_notification_method_handler("${method.rpcMethod}", ${handlerVariableName})`); + return; + } + lines.push(` async def ${handlerVariableName}(params: dict) -> dict | None:`); lines.push(` request = ${paramsType}.from_dict(params)`); lines.push(` handler = handlers.${handlerField}`); diff --git a/scripts/codegen/rust.ts b/scripts/codegen/rust.ts index b8a1c6d6db..a04f5a21c5 100644 --- a/scripts/codegen/rust.ts +++ b/scripts/codegen/rust.ts @@ -1109,7 +1109,11 @@ function extractEventVariants(schema: JSONSchema7): EventVariant[] { dataExperimental: isSchemaExperimental(dataSchema), }; }) - .filter((v) => !EXCLUDED_EVENT_TYPES.has(v.typeName)); + .filter( + (v) => + !EXCLUDED_EVENT_TYPES.has(v.typeName) && + !isSchemaInternal(v.dataSchema), + ); } export function generateSessionEventsCode(schema: JSONSchema7): string { @@ -1229,6 +1233,8 @@ export function generateSessionEventsCode(schema: JSONSchema7): string { "//! Auto-generated from session-events.schema.json — do not edit manually.", ); out.push(""); + out.push("#![allow(deprecated)]"); + out.push(""); out.push("use std::collections::HashMap;"); out.push(""); out.push("use serde::{Deserialize, Serialize};"); @@ -1580,6 +1586,7 @@ function generateApiTypesCode( out.push("//! Auto-generated from api.schema.json — do not edit manually."); out.push(""); out.push("#![allow(clippy::large_enum_variant)]"); + out.push("#![allow(deprecated)]"); out.push("#![allow(dead_code)]"); out.push("#![allow(rustdoc::invalid_html_tags)]"); out.push(""); @@ -2002,6 +2009,7 @@ function generateRpcCode(apiSchema: ApiSchema): string { out.push(""); out.push("#![allow(missing_docs)]"); out.push("#![allow(clippy::too_many_arguments)]"); + out.push("#![allow(deprecated)]"); out.push("#![allow(dead_code)]"); out.push(""); out.push("use super::api_types::{rpc_methods, *};"); diff --git a/scripts/codegen/typescript.ts b/scripts/codegen/typescript.ts index 1303a4979c..f82e67abe6 100644 --- a/scripts/codegen/typescript.ts +++ b/scripts/codegen/typescript.ts @@ -37,6 +37,7 @@ import { isNodeFullyDeprecated, isVoidSchema, isSchemaExperimental, + isSchemaInternal, appendPropertyMarkerTagsToDescriptions, getEnumValueDescriptions, stripOpaqueJsonMarker, @@ -348,7 +349,39 @@ async function generateSessionEvents(schemaPath?: string): Promise { resolveSchema({ $ref: "#/definitions/SessionEvent" }, definitionCollections) ?? resolveSchema({ $ref: "#/$defs/SessionEvent" }, definitionCollections) ?? processed; - const schemaForCompile = withSharedDefinitions(sessionEvent, definitionCollections); + const excludedDefinitionNames = new Set(); + const publicVariants = (sessionEvent.anyOf ?? []).filter((variant) => { + const variantSchema = variant as JSONSchema7; + const resolvedVariant = resolveSchema(variantSchema, definitionCollections) ?? variantSchema; + const dataSchema = resolvedVariant.properties?.data as JSONSchema7 | undefined; + const resolvedData = dataSchema ? resolveSchema(dataSchema, definitionCollections) ?? dataSchema : undefined; + if (!isSchemaInternal(resolvedData)) { + return true; + } + + for (const ref of [variantSchema.$ref, dataSchema?.$ref]) { + const match = ref?.match(/^#\/(?:definitions|\$defs)\/([^/]+)$/); + if (match) excludedDefinitionNames.add(match[1]); + } + return false; + }); + const publicDefinitions = Object.fromEntries( + Object.entries(definitionCollections.definitions).filter(([name]) => !excludedDefinitionNames.has(name)) + ); + const publicDraftDefinitions = Object.fromEntries( + Object.entries(definitionCollections.$defs).filter(([name]) => !excludedDefinitionNames.has(name)) + ); + const publicSessionEvent = { ...sessionEvent, anyOf: publicVariants }; + if ("SessionEvent" in publicDefinitions) { + publicDefinitions.SessionEvent = publicSessionEvent; + } + if ("SessionEvent" in publicDraftDefinitions) { + publicDraftDefinitions.SessionEvent = publicSessionEvent; + } + const schemaForCompile = withSharedDefinitions( + publicSessionEvent, + { definitions: publicDefinitions, $defs: publicDraftDefinitions } + ); appendPropertyMarkerTagsToDescriptions(schemaForCompile); const ts = await compile(normalizeSchemaForTypeScript(schemaForCompile), "SessionEvent", { @@ -1011,7 +1044,24 @@ function emitClientGlobalApiRegistration(clientSchema: Record): const pType = paramsTypeName(method); const hasParams = hasSchemaPayload(getMethodParamsSchema(method)); - if (hasParams) { + if (method.notification) { + // Notification methods carry no response; the server dispatches + // them via `sendNotification`, which only fires `onNotification` + // handlers (an `onRequest` handler would never be invoked). + if (hasParams) { + lines.push(` connection.onNotification("${method.rpcMethod}", async (params: ${pType}) => {`); + lines.push(` const handler = handlers.${groupName};`); + lines.push(` if (!handler) return;`); + lines.push(` await handler.${name}(params);`); + lines.push(` });`); + } else { + lines.push(` connection.onNotification("${method.rpcMethod}", async () => {`); + lines.push(` const handler = handlers.${groupName};`); + lines.push(` if (!handler) return;`); + lines.push(` await handler.${name}();`); + lines.push(` });`); + } + } else if (hasParams) { lines.push(` connection.onRequest("${method.rpcMethod}", async (params: ${pType}) => {`); lines.push(` const handler = handlers.${groupName};`); lines.push(` if (!handler) throw new Error("No ${groupName} client-global handler registered");`); diff --git a/scripts/codegen/utils.ts b/scripts/codegen/utils.ts index c63f9732c4..9ab335b05f 100644 --- a/scripts/codegen/utils.ts +++ b/scripts/codegen/utils.ts @@ -383,6 +383,7 @@ export interface RpcMethod { stability?: string; visibility?: string; deprecated?: boolean; + notification?: boolean; } export function getRpcSchemaTypeName(schema: JSONSchema7 | null | undefined, fallback: string): string { diff --git a/test/harness/anthropicMessagesAdapter.ts b/test/harness/anthropicMessagesAdapter.ts new file mode 100644 index 0000000000..acc74a2bf9 --- /dev/null +++ b/test/harness/anthropicMessagesAdapter.ts @@ -0,0 +1,396 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +import type { ChatCompletion } from "openai/resources/chat/completions"; +import { + CanonicalMessage, + CanonicalToolCall, + formatSseEvent, + functionToolCalls, + isObject, + JsonObject, +} from "./modelProtocolAdapterShared"; + +export const anthropicMessagesEndpoint = "/v1/messages"; + +type CanonicalContentPart = + | { type: "text"; text: string } + | { type: "image_url"; image_url: { url: string } } + | { + type: "file"; + file: { file_data: string; filename?: string }; + }; + +type AnthropicContentBlock = + | { type: "text"; text: string; citations?: null } + | { + type: "image" | "document"; + source?: { type?: string; media_type?: string; data?: string }; + } + | { type: "tool_use"; id: string; name: string; input: unknown } + | { + type: "tool_result"; + tool_use_id?: string; + content?: string | Array<{ type?: string; text?: string }>; + }; + +type AnthropicMessageParam = { + role: "user" | "assistant"; + content: string | AnthropicContentBlock[]; +}; + +type AnthropicRequest = { + model: string; + messages: AnthropicMessageParam[]; + system?: string | Array<{ type?: string; text?: string }>; + max_tokens?: number; + temperature?: number; + top_p?: number; + stream?: boolean; + tools?: Array<{ + name: string; + description?: string; + input_schema?: JsonObject; + }>; + tool_choice?: + | { type: "auto" | "any" | "none" } + | { type: "tool"; name: string }; +}; + +type AnthropicStopReason = + | "end_turn" + | "max_tokens" + | "stop_sequence" + | "tool_use" + | "refusal"; + +export type AnthropicMessage = { + id: string; + type: "message"; + role: "assistant"; + content: Array< + | { type: "text"; text: string; citations: null } + | { type: "tool_use"; id: string; name: string; input: unknown } + >; + model: string; + stop_reason: AnthropicStopReason | null; + stop_sequence: string | null; + usage: { + input_tokens: number; + output_tokens: number; + cache_creation_input_tokens: number | null; + cache_read_input_tokens: number | null; + }; +}; + +const finishReasonToStopReason: Record = { + stop: "end_turn", + length: "max_tokens", + tool_calls: "tool_use", + function_call: "tool_use", + content_filter: "refusal", +}; + +export function anthropicMessagesRequestToChatCompletion( + requestBody: string, +): string { + const request = JSON.parse(requestBody) as AnthropicRequest; + const messages: CanonicalMessage[] = []; + + const system = anthropicSystemToString(request.system); + if (system) messages.push({ role: "system", content: system }); + + for (const message of request.messages) { + messages.push(...convertAnthropicMessage(message)); + } + + return JSON.stringify({ + model: request.model, + messages, + ...(request.max_tokens !== undefined + ? { max_tokens: request.max_tokens } + : {}), + ...(request.temperature !== undefined + ? { temperature: request.temperature } + : {}), + ...(request.top_p !== undefined ? { top_p: request.top_p } : {}), + ...(request.stream !== undefined ? { stream: request.stream } : {}), + ...(request.tools + ? { + tools: request.tools.map((tool) => ({ + type: "function", + function: { + name: tool.name, + ...(tool.description ? { description: tool.description } : {}), + parameters: tool.input_schema ?? { + type: "object", + properties: {}, + }, + }, + })), + } + : {}), + ...(request.tool_choice + ? { tool_choice: convertToolChoice(request.tool_choice) } + : {}), + }); +} + +function anthropicSystemToString( + system: AnthropicRequest["system"], +): string | undefined { + if (typeof system === "string") return system; + if (!Array.isArray(system)) return undefined; + return system + .map((block) => (typeof block.text === "string" ? block.text : "")) + .filter(Boolean) + .join("\n"); +} + +function convertAnthropicMessage( + message: AnthropicMessageParam, +): CanonicalMessage[] { + return message.role === "user" + ? convertAnthropicUserMessage(message) + : convertAnthropicAssistantMessage(message); +} + +function normalizeContent( + content: AnthropicMessageParam["content"], +): AnthropicContentBlock[] { + return typeof content === "string" + ? [{ type: "text", text: content }] + : content; +} + +function convertAnthropicUserMessage( + message: AnthropicMessageParam, +): CanonicalMessage[] { + const result: CanonicalMessage[] = []; + const contentParts: CanonicalContentPart[] = []; + + const flushUserContent = () => { + if (contentParts.length === 0) return; + const onlyText = contentParts.every((part) => part.type === "text"); + result.push({ + role: "user", + content: onlyText + ? contentParts + .map((part) => (part.type === "text" ? part.text : "")) + .join("\n") + : [...contentParts], + }); + contentParts.length = 0; + }; + + for (const block of normalizeContent(message.content)) { + if (block.type === "text") { + contentParts.push({ type: "text", text: block.text }); + } else if ( + (block.type === "image" || block.type === "document") && + block.source?.type === "base64" && + block.source.data + ) { + const dataUrl = `data:${ + block.source.media_type ?? + (block.type === "image" ? "image/png" : "application/pdf") + };base64,${block.source.data}`; + contentParts.push( + block.type === "image" + ? { type: "image_url", image_url: { url: dataUrl } } + : { type: "file", file: { file_data: dataUrl } }, + ); + } else if (block.type === "tool_result") { + flushUserContent(); + result.push({ + role: "tool", + tool_call_id: block.tool_use_id ?? "", + content: anthropicToolResultContent(block.content), + }); + } + } + + flushUserContent(); + return result; +} + +function convertAnthropicAssistantMessage( + message: AnthropicMessageParam, +): CanonicalMessage[] { + const text: string[] = []; + const toolCalls: CanonicalToolCall[] = []; + for (const block of normalizeContent(message.content)) { + if (block.type === "text") { + text.push(block.text); + } else if (block.type === "tool_use") { + toolCalls.push({ + id: block.id, + type: "function", + function: { + name: block.name, + arguments: JSON.stringify(block.input ?? {}), + }, + }); + } + } + + return [ + { + role: "assistant", + content: text.length ? text.join("") : null, + ...(toolCalls.length ? { tool_calls: toolCalls } : {}), + }, + ]; +} + +function anthropicToolResultContent(content: unknown): string { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content + .map((part) => + isObject(part) && typeof part.text === "string" ? part.text : "", + ) + .filter(Boolean) + .join("\n"); +} + +function convertToolChoice( + choice: NonNullable, +): unknown { + switch (choice.type) { + case "auto": + return "auto"; + case "any": + return "required"; + case "none": + return "none"; + case "tool": + return { type: "function", function: { name: choice.name } }; + } +} + +export function chatCompletionResponseToAnthropicMessage( + response: ChatCompletion, +): AnthropicMessage { + const content: AnthropicMessage["content"] = []; + for (const choice of response.choices) { + if (choice.message.content) { + content.push({ + type: "text", + text: choice.message.content, + citations: null, + }); + } + for (const toolCall of functionToolCalls(choice.message)) { + content.push({ + type: "tool_use", + id: toolCall.id, + name: toolCall.function.name, + input: safeParseJson(toolCall.function.arguments), + }); + } + } + + const finishReason = response.choices.at(-1)?.finish_reason; + return { + id: response.id, + type: "message", + role: "assistant", + content, + model: response.model, + stop_reason: finishReason + ? (finishReasonToStopReason[finishReason] ?? null) + : null, + stop_sequence: null, + usage: { + input_tokens: response.usage?.prompt_tokens ?? 0, + output_tokens: response.usage?.completion_tokens ?? 0, + cache_creation_input_tokens: null, + cache_read_input_tokens: null, + }, + }; +} + +export function chatCompletionResponseToAnthropicSseChunks( + response: ChatCompletion, +): string[] { + const message = chatCompletionResponseToAnthropicMessage(response); + const chunks = [ + formatSseEvent("message_start", { + type: "message_start", + message: { + ...message, + content: [], + stop_reason: null, + usage: { ...message.usage, output_tokens: 1 }, + }, + }), + ]; + + for (let index = 0; index < message.content.length; index++) { + const block = message.content[index]; + if (block.type === "text") { + chunks.push( + formatSseEvent("content_block_start", { + type: "content_block_start", + index, + content_block: { type: "text", text: "", citations: null }, + }), + formatSseEvent("content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "text_delta", text: block.text }, + }), + ); + } else { + chunks.push( + formatSseEvent("content_block_start", { + type: "content_block_start", + index, + content_block: { + type: "tool_use", + id: block.id, + name: block.name, + input: {}, + }, + }), + formatSseEvent("content_block_delta", { + type: "content_block_delta", + index, + delta: { + type: "input_json_delta", + partial_json: JSON.stringify(block.input ?? {}), + }, + }), + ); + } + chunks.push( + formatSseEvent("content_block_stop", { + type: "content_block_stop", + index, + }), + ); + } + + chunks.push( + formatSseEvent("message_delta", { + type: "message_delta", + delta: { + stop_reason: message.stop_reason, + stop_sequence: message.stop_sequence, + }, + usage: { output_tokens: message.usage.output_tokens }, + }), + formatSseEvent("message_stop", { type: "message_stop" }), + ); + return chunks; +} + +function safeParseJson(value: string): unknown { + try { + return JSON.parse(value); + } catch { + return {}; + } +} diff --git a/test/harness/modelProtocolAdapterShared.ts b/test/harness/modelProtocolAdapterShared.ts new file mode 100644 index 0000000000..1f879da5d0 --- /dev/null +++ b/test/harness/modelProtocolAdapterShared.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +export type JsonObject = Record; + +export type CanonicalToolCall = { + id: string; + type: "function"; + function: { name: string; arguments: string }; +}; + +export type CanonicalMessage = { + role: "system" | "user" | "assistant" | "tool"; + content?: string | unknown[] | null; + tool_call_id?: string; + tool_calls?: CanonicalToolCall[]; +}; + +export function functionToolCalls(message: unknown): CanonicalToolCall[] { + if (!isObject(message) || !Array.isArray(message.tool_calls)) return []; + return message.tool_calls.filter( + (toolCall): toolCall is CanonicalToolCall => + isObject(toolCall) && + typeof toolCall.id === "string" && + toolCall.type === "function" && + isObject(toolCall.function) && + typeof toolCall.function.name === "string" && + typeof toolCall.function.arguments === "string", + ); +} + +export function formatSseEvent(type: string, data: unknown): string { + return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; +} + +export function isObject(value: unknown): value is JsonObject { + return value !== null && typeof value === "object" && !Array.isArray(value); +} diff --git a/test/harness/modelProtocolAdapters.test.ts b/test/harness/modelProtocolAdapters.test.ts new file mode 100644 index 0000000000..ddb6fe40bf --- /dev/null +++ b/test/harness/modelProtocolAdapters.test.ts @@ -0,0 +1,641 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { ChatCompletion } from "openai/resources/chat/completions"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import yaml from "yaml"; +import { + anthropicMessagesRequestToChatCompletion, + chatCompletionResponseToAnthropicMessage, + chatCompletionResponseToAnthropicSseChunks, +} from "./anthropicMessagesAdapter"; +import { + chatCompletionResponseToResponsesApiMessage, + chatCompletionResponseToResponsesApiSseChunks, + responsesApiRequestToChatCompletion, +} from "./responsesApiAdapter"; +import { + NormalizedData, + ReplayBackend, + ReplayingCapiProxy, +} from "./replayingCapiProxy"; + +type ByokBackend = Exclude; + +const backends: ReplayBackend[] = [ + "capi", + "anthropic-messages", + "openai-responses", + "openai-completions", +]; + +const endpoints: Record = { + capi: "/chat/completions", + "anthropic-messages": "/v1/messages", + "openai-responses": "/responses", + "openai-completions": "/chat/completions", +}; + +const models: Record = { + capi: "gpt-4.1", + "anthropic-messages": "claude-sonnet-4.5", + "openai-responses": "gpt-4.1", + "openai-completions": "gpt-4.1", +}; + +const completionWithTool: ChatCompletion = { + id: "completion-1", + object: "chat.completion", + created: 123, + model: "test-model", + choices: [ + { + index: 0, + message: { + role: "assistant", + content: "Calling a tool", + refusal: null, + tool_calls: [ + { + id: "call-1", + type: "function", + function: { name: "lookup", arguments: '{"value":42}' }, + }, + ], + }, + logprobs: null, + finish_reason: "tool_calls", + }, + ], + usage: { + prompt_tokens: 10, + completion_tokens: 5, + total_tokens: 15, + }, +}; + +function requestFor( + backend: ReplayBackend, + prompt: string, +): Record { + const model = models[backend]; + switch (backend) { + case "anthropic-messages": + return { + model, + system: "Be helpful", + messages: [{ role: "user", content: prompt }], + max_tokens: 128, + }; + case "openai-responses": + return { + model, + instructions: "Be helpful", + input: [ + { + type: "message", + role: "user", + content: [{ type: "input_text", text: prompt }], + }, + ], + }; + case "capi": + case "openai-completions": + return { + model, + messages: [ + { role: "system", content: "Be helpful" }, + { role: "user", content: prompt }, + ], + }; + } +} + +async function postJson( + proxyUrl: string, + endpoint: string, + body: unknown, +): Promise { + return fetch(`${proxyUrl}${endpoint}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); +} + +describe("Anthropic Messages adapter", () => { + test("normalizes messages, binary content, and tools", () => { + const result = JSON.parse( + anthropicMessagesRequestToChatCompletion( + JSON.stringify({ + model: "test-model", + system: [{ type: "text", text: "Be helpful" }], + messages: [ + { + role: "user", + content: [ + { type: "text", text: "Inspect this" }, + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "AQID", + }, + }, + ], + }, + { + role: "assistant", + content: [ + { + type: "tool_use", + id: "call-1", + name: "lookup", + input: { value: 42 }, + }, + ], + }, + { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "call-1", + content: "found", + }, + ], + }, + ], + tools: [ + { + name: "lookup", + description: "Find a value", + input_schema: { type: "object" }, + }, + ], + stream: true, + }), + ), + ) as { + messages: Array>; + tools: Array>; + stream: boolean; + }; + + expect(result.messages.map((message) => message.role)).toEqual([ + "system", + "user", + "assistant", + "tool", + ]); + expect(result.messages[1].content).toEqual([ + { type: "text", text: "Inspect this" }, + { + type: "image_url", + image_url: { url: "data:image/png;base64,AQID" }, + }, + ]); + expect(result.messages[2].tool_calls).toEqual([ + { + id: "call-1", + type: "function", + function: { name: "lookup", arguments: '{"value":42}' }, + }, + ]); + expect(result.messages[3]).toMatchObject({ + tool_call_id: "call-1", + content: "found", + }); + expect(result.tools).toHaveLength(1); + expect(result.stream).toBe(true); + }); + + test("renders JSON and streaming tool responses", () => { + const message = + chatCompletionResponseToAnthropicMessage(completionWithTool); + expect(message.stop_reason).toBe("tool_use"); + expect(message.usage).toMatchObject({ + cache_creation_input_tokens: null, + cache_read_input_tokens: null, + }); + expect(message.content.map((block) => block.type)).toEqual([ + "text", + "tool_use", + ]); + + const stream = + chatCompletionResponseToAnthropicSseChunks(completionWithTool).join(""); + expect(stream).toContain("event: message_start"); + expect(stream).toContain("event: content_block_delta"); + expect(stream).toContain("event: message_stop"); + }); + + test("combines tools from multiple canonical choices", () => { + const secondChoice = structuredClone(completionWithTool.choices[0]); + secondChoice.message.content = null; + secondChoice.message.tool_calls![0] = { + id: "call-2", + type: "function", + function: { name: "inspect", arguments: '{"path":"file.txt"}' }, + }; + + const message = chatCompletionResponseToAnthropicMessage({ + ...completionWithTool, + choices: [completionWithTool.choices[0], secondChoice], + }); + expect( + message.content + .filter((block) => block.type === "tool_use") + .map((block) => block.name), + ).toEqual(["lookup", "inspect"]); + }); +}); + +describe("OpenAI Responses adapter", () => { + test("normalizes messages, binary content, and tools", () => { + const result = JSON.parse( + responsesApiRequestToChatCompletion( + JSON.stringify({ + model: "test-model", + instructions: "Be helpful", + input: [ + { + type: "message", + role: "user", + content: [ + { type: "input_text", text: "Inspect this" }, + { + type: "input_image", + image_url: "data:image/png;base64,AQID", + }, + ], + }, + { + type: "function_call", + call_id: "call-1", + name: "lookup", + arguments: '{"value":42}', + }, + { + type: "function_call_output", + call_id: "call-1", + output: "found", + }, + ], + tools: [ + { + type: "function", + name: "lookup", + parameters: { type: "object" }, + }, + ], + }), + ), + ) as { + messages: Array>; + tools: Array>; + }; + + expect(result.messages.map((message) => message.role)).toEqual([ + "system", + "user", + "assistant", + "tool", + ]); + expect(result.messages[1].content).toEqual([ + { type: "text", text: "Inspect this" }, + { + type: "image_url", + image_url: { url: "data:image/png;base64,AQID" }, + }, + ]); + expect(result.messages[2].tool_calls).toEqual([ + { + id: "call-1", + type: "function", + function: { name: "lookup", arguments: '{"value":42}' }, + }, + ]); + expect(result.messages[3]).toMatchObject({ + tool_call_id: "call-1", + content: "found", + }); + expect(result.tools).toHaveLength(1); + }); + + test("renders JSON and streaming tool responses", () => { + const response = + chatCompletionResponseToResponsesApiMessage(completionWithTool); + const nextResponse = + chatCompletionResponseToResponsesApiMessage(completionWithTool); + expect(response).toMatchObject({ + object: "response", + created_at: completionWithTool.created, + status: "completed", + incomplete_details: null, + error: null, + }); + expect(response.output[0].id).not.toBe(nextResponse.output[0].id); + expect(response.output.map((item) => item.type)).toEqual([ + "message", + "function_call", + ]); + + const chunks = + chatCompletionResponseToResponsesApiSseChunks(completionWithTool); + const events = chunks.map( + (chunk) => + JSON.parse(chunk.split("\ndata: ")[1]) as Record, + ); + const stream = chunks.join(""); + expect(stream).toContain("event: response.created"); + expect(stream).toContain("event: response.in_progress"); + expect(stream).toContain("event: response.output_text.delta"); + expect(stream).toContain('"sequence_number":0'); + expect(stream).toContain("event: response.completed"); + + expect(events[0]).toMatchObject({ + type: "response.created", + response: { status: "in_progress", output: [] }, + }); + expect(events[1]).toMatchObject({ + type: "response.in_progress", + response: { status: "in_progress", output: [] }, + }); + + const addedItems = events.filter( + (event) => event.type === "response.output_item.added", + ); + expect(addedItems).toMatchObject([ + { + item: { + type: "message", + status: "in_progress", + content: [], + }, + }, + { + item: { + type: "function_call", + status: "in_progress", + arguments: "", + }, + }, + ]); + expect( + events.find((event) => event.type === "response.content_part.added"), + ).toMatchObject({ + part: { type: "output_text", text: "" }, + }); + + const completedItems = events.filter( + (event) => event.type === "response.output_item.done", + ); + expect(completedItems).toMatchObject([ + { + item: { + type: "message", + status: "completed", + content: [{ type: "output_text", text: "Calling a tool" }], + }, + }, + { + item: { + type: "function_call", + status: "completed", + arguments: '{"value":42}', + }, + }, + ]); + }); +}); + +describe("protocol-aware replay", () => { + let tempDir: string; + let workDir: string; + let cachePath: string; + + async function writeSnapshot( + messages: NormalizedData["conversations"][number]["messages"], + ): Promise { + await writeFile( + cachePath, + yaml.stringify({ + models: ["captured-capi-model"], + conversations: [{ messages }], + } satisfies NormalizedData), + ); + } + + async function withProxy( + backend: ReplayBackend, + action: (proxyUrl: string) => Promise, + ): Promise { + const proxy = new ReplayingCapiProxy( + "http://localhost:9999", + cachePath, + workDir, + ); + const proxyUrl = await proxy.start(); + await proxy.updateConfig({ filePath: cachePath, workDir, backend }); + try { + await action(proxyUrl); + } finally { + await proxy.stop(true); + } + } + + beforeEach(async () => { + tempDir = await mkdtemp(path.join(os.tmpdir(), "protocol-replay-")); + workDir = path.join(tempDir, "work"); + cachePath = path.join(tempDir, "cache.yaml"); + await writeSnapshot([ + { role: "system", content: "${system}" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + ]); + }); + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + test.each(backends)( + "replays one model-independent snapshot through %s", + async (backend) => { + await withProxy(backend, async (proxyUrl) => { + const response = await postJson( + proxyUrl, + endpoints[backend], + requestFor(backend, "Hello"), + ); + expect(response.status).toBe(200); + const body = (await response.json()) as Record; + expect(body.model).toBe(models[backend]); + + const exchanges = (await ( + await fetch(`${proxyUrl}/exchanges`) + ).json()) as Array<{ + request: { + model: string; + messages: Array<{ role: string; content: unknown }>; + }; + response?: unknown; + }>; + expect(exchanges).toHaveLength(1); + expect(exchanges[0].request.model).toBe(models[backend]); + expect(exchanges[0].request.messages.at(-1)).toEqual({ + role: "user", + content: "Hello", + }); + if ( + backend === "anthropic-messages" || + backend === "openai-responses" + ) { + expect(exchanges[0].response).toBeUndefined(); + } + }); + }, + ); + + test("does not rewrite canonical snapshots after BYOK replay", async () => { + const original = await readFile(cachePath, "utf8"); + const proxy = new ReplayingCapiProxy( + "http://localhost:9999", + cachePath, + workDir, + ); + const proxyUrl = await proxy.start(); + await proxy.updateConfig({ + filePath: cachePath, + workDir, + backend: "openai-responses", + }); + + let stopped = false; + try { + const response = await postJson( + proxyUrl, + endpoints["openai-responses"], + requestFor("openai-responses", "Hello"), + ); + expect(response.status).toBe(200); + await proxy.stop(); + stopped = true; + expect(await readFile(cachePath, "utf8")).toBe(original); + } finally { + if (!stopped) await proxy.stop(true); + } + }); + + test.each(["openai-responses", "openai-completions"] as const)( + "coalesces adjacent user messages from %s", + async (backend) => { + await writeSnapshot([ + { role: "system", content: "${system}" }, + { role: "user", content: "Hook context" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + ]); + const request = requestFor(backend, "Hello"); + const hook = + "Hook context\n\n\n2026-01-01T00:00:00Z\n\n"; + if (backend === "openai-responses") { + (request.input as unknown[]).unshift({ + type: "message", + role: "user", + content: [{ type: "input_text", text: hook }], + }); + } else { + (request.messages as unknown[]).splice(1, 0, { + role: "user", + content: hook, + }); + } + + await withProxy(backend, async (proxyUrl) => { + const response = await postJson( + proxyUrl, + endpoints[backend], + request, + ); + expect(response.status).toBe(200); + }); + }, + ); + + test("normalizes Anthropic spacing between adjacent user turns", async () => { + await writeSnapshot([ + { role: "system", content: "${system}" }, + { role: "user", content: "First prompt" }, + { role: "user", content: "Recovery prompt" }, + { role: "assistant", content: "Recovered" }, + ]); + await withProxy("anthropic-messages", async (proxyUrl) => { + const response = await postJson( + proxyUrl, + endpoints["anthropic-messages"], + requestFor( + "anthropic-messages", + "First prompt\n\n\n\n\nRecovery prompt", + ), + ); + expect(response.status).toBe(200); + }); + }); + + test.each(backends)( + "replays compaction responses through %s", + async (backend) => { + await writeSnapshot([ + { role: "system", content: "${system}" }, + { role: "user", content: "${compaction_prompt}" }, + { + role: "assistant", + content: + "CompactedHistoryCheckpoint", + }, + ]); + await withProxy(backend, async (proxyUrl) => { + const response = await postJson( + proxyUrl, + endpoints[backend], + requestFor(backend, "${compaction_prompt}"), + ); + expect(response.status).toBe(200); + const body = JSON.stringify(await response.json()); + expect(body).toContain(""); + expect(body).toContain(""); + expect(body).toContain(""); + }); + }, + ); + + test("rejects an inference request over the wrong protocol", async () => { + await withProxy("anthropic-messages", async (proxyUrl) => { + const response = await postJson( + proxyUrl, + endpoints["openai-completions"], + requestFor("openai-completions", "Hello"), + ); + expect(response.status).toBe(400); + await expect(response.text()).resolves.toContain("protocol_mismatch"); + }); + }); + + test("keeps foreign model endpoints unavailable in CAPI mode", async () => { + await withProxy("capi", async (proxyUrl) => { + const response = await postJson( + proxyUrl, + endpoints["openai-responses"], + requestFor("openai-responses", "Hello"), + ); + expect(response.status).toBe(404); + }); + }); +}); diff --git a/test/harness/package-lock.json b/test/harness/package-lock.json index 80a2d239f6..1a8462d661 100644 --- a/test/harness/package-lock.json +++ b/test/harness/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "license": "ISC", "devDependencies": { - "@github/copilot": "^1.0.65", + "@github/copilot": "^1.0.71", "@modelcontextprotocol/sdk": "^1.26.0", "@types/node": "^25.3.3", "@types/node-forge": "^1.3.14", @@ -501,9 +501,9 @@ } }, "node_modules/@github/copilot": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.65.tgz", - "integrity": "sha512-J1XvLuOiVpiAi/E1MBICBymszCgdGLnZxokosXzGcmcjEVZd+QSDoW/kPRHq6oEyBT9SDASPcjCEZ9Q0rLJllg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.71.tgz", + "integrity": "sha512-F3axBi+sXSLYDJbxCBW36bM6MYKNC2rlyAf3Ivo/MjiHKKJW7j5AmaR1IRYS9Gt8r9mxOwWFM1cJFA+CuLaR8g==", "dev": true, "license": "SEE LICENSE IN LICENSE.md", "dependencies": { @@ -513,20 +513,20 @@ "copilot": "npm-loader.js" }, "optionalDependencies": { - "@github/copilot-darwin-arm64": "1.0.65", - "@github/copilot-darwin-x64": "1.0.65", - "@github/copilot-linux-arm64": "1.0.65", - "@github/copilot-linux-x64": "1.0.65", - "@github/copilot-linuxmusl-arm64": "1.0.65", - "@github/copilot-linuxmusl-x64": "1.0.65", - "@github/copilot-win32-arm64": "1.0.65", - "@github/copilot-win32-x64": "1.0.65" + "@github/copilot-darwin-arm64": "1.0.71", + "@github/copilot-darwin-x64": "1.0.71", + "@github/copilot-linux-arm64": "1.0.71", + "@github/copilot-linux-x64": "1.0.71", + "@github/copilot-linuxmusl-arm64": "1.0.71", + "@github/copilot-linuxmusl-x64": "1.0.71", + "@github/copilot-win32-arm64": "1.0.71", + "@github/copilot-win32-x64": "1.0.71" } }, "node_modules/@github/copilot-darwin-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.65.tgz", - "integrity": "sha512-NFc4xIstZNiIuAYkurQT5DVtbZjBoZ/z6yt/Ffcom7Y5QGjfpN4BFuekv9k+OADRioxxR99NgmhjbuNPWtQhNQ==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.71.tgz", + "integrity": "sha512-mEWzyqbqRAWgyU7i2uuSRoVPx/TwaFQX0nZmw0bc30aJ0BnO7cy2kYQyCHw8ykmf/tfxT0xauZ6k0BOFmWizzQ==", "cpu": [ "arm64" ], @@ -541,9 +541,9 @@ } }, "node_modules/@github/copilot-darwin-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.65.tgz", - "integrity": "sha512-0wtV22KmTa12VbqWRRkgvJcBz/oIbszfcIpyDWGc4MzbCVksajQ3TWVQ6c7Sdzj5RifCaYdkHAX2zuIYXYlLoQ==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.71.tgz", + "integrity": "sha512-Md9yEg406OBVBx3w4PeEj62TubulVLBcHleqmCoOoUmPgUxPZotUbrqz3rtbzADbXfrrD7JWvVsbd2UiNL194w==", "cpu": [ "x64" ], @@ -558,9 +558,9 @@ } }, "node_modules/@github/copilot-linux-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.65.tgz", - "integrity": "sha512-dOwdy/YbTXQN/+x2v4ZgiDycdRtWElyHxPuA6ail3yJDt0nagwn8OYAA/diBLPMAJuuBXiOZGvvb9fGRuh7Xgg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.71.tgz", + "integrity": "sha512-ykLJYOqBj3jRB5IJCDugLClAqbr7DmtTbUjlNY7+Jdq/n6i+d7xUQGclf1IWL5gnxbGQVAf+zkToD+sRM389Kg==", "cpu": [ "arm64" ], @@ -575,9 +575,9 @@ } }, "node_modules/@github/copilot-linux-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.65.tgz", - "integrity": "sha512-al/1a/l/GrpHtygTxt7PZspmv0eHBPdAZ5B31J7Hv/GRdVZM4STCC9dCIOSUFsOX2fhaKD8yLfz4HureSYs23g==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.71.tgz", + "integrity": "sha512-pC0FNHG+BBwZd6yZlM85kkAGN+uJhM6o+THi76N2GnnSxmw7+remb1mvYxdgRVbdCm+LBUIbCKRWJLuMwrfb6A==", "cpu": [ "x64" ], @@ -592,9 +592,9 @@ } }, "node_modules/@github/copilot-linuxmusl-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.65.tgz", - "integrity": "sha512-xccQeJSR45xyoaL7J5mZjtU++dmte+ZCDQkIlrpTn2yuMl2LWriBvorQ1P2MwVnXmIiW/GHi93B+lNtsybA9yw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.71.tgz", + "integrity": "sha512-hBmDljFTjacxqZTasCEy43H8EIzuXB/hHEBBCMFjhB9J00nIxsO6Dh0woTifKpx7knTYZdpTjjca3D0pAoZlUA==", "cpu": [ "arm64" ], @@ -609,9 +609,9 @@ } }, "node_modules/@github/copilot-linuxmusl-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.65.tgz", - "integrity": "sha512-RHPVUaqjSrhKHQ2EpfGKWErnV+R5elGIZaHXPKO10zpSaQD9b/C9u6nLigZnBuT/8sCaJpVrazPMwOYvYA62aw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.71.tgz", + "integrity": "sha512-CfTXU8pa5dxRz22xQzoi3TiG1PJo9+WR8PRDiPSdkIBSyPJ1NvX87DJmfXjTgeAfR+wkjt/p0keDCaBBVhNmUA==", "cpu": [ "x64" ], @@ -626,9 +626,9 @@ } }, "node_modules/@github/copilot-win32-arm64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.65.tgz", - "integrity": "sha512-/vSE/t9Wm3eFSWpxlKyn/oL8OAVOB0yFO7ECxhgbtiqNrBd1tgpYh1k7IXBIWa/saxlV1+de6DEmPuQfx3Z0bg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.71.tgz", + "integrity": "sha512-+HI1DokixXhHUahj06Fw67ZAigBuXKC58BFma4UJOGrQsDgwOSbqeTQHCw6vuymzjKlg3sactfsCUTaefkjscQ==", "cpu": [ "arm64" ], @@ -643,9 +643,9 @@ } }, "node_modules/@github/copilot-win32-x64": { - "version": "1.0.65", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.65.tgz", - "integrity": "sha512-wjVWXepET+SpFg8z8V43ZiTy6X1OerCb7yu3QZKNNJ3zY9z20goihPXQCDWkiJpGzszNSgfrsiqUzpUsC9qS0A==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.71.tgz", + "integrity": "sha512-02kXOBd9CwBbCaztuf71WYWn+uGapCuiaasomN4tcMH3HBVZ4gi3J0ZUoRcgcS80xh81uQyeBHbnUKzb/RE/9A==", "cpu": [ "x64" ], diff --git a/test/harness/package.json b/test/harness/package.json index d13dbb99a7..18b19e21ac 100644 --- a/test/harness/package.json +++ b/test/harness/package.json @@ -14,7 +14,7 @@ "node": "^20.19.0 || >=22.12.0" }, "devDependencies": { - "@github/copilot": "^1.0.65", + "@github/copilot": "^1.0.71", "@modelcontextprotocol/sdk": "^1.26.0", "@types/node": "^25.3.3", "@types/node-forge": "^1.3.14", diff --git a/test/harness/replayingCapiProxy.test.ts b/test/harness/replayingCapiProxy.test.ts index 8032265485..009a1e40a8 100644 --- a/test/harness/replayingCapiProxy.test.ts +++ b/test/harness/replayingCapiProxy.test.ts @@ -509,6 +509,47 @@ Always include PINEAPPLE_COCONUT_42. expect(toolMessages[1].content).toBe("[beta result]"); }); + test("collapses the available-tools list to a stable placeholder", async () => { + const requestBody = JSON.stringify({ + messages: [ + { role: "user", content: "Help me" }, + { + role: "assistant", + tool_calls: [ + { + id: "tc1", + type: "function", + function: { name: "report_intent", arguments: "{}" }, + }, + ], + }, + { + role: "tool", + tool_call_id: "tc1", + content: + "Tool 'report_intent' does not exist. Available tools that can be called are bash, read_bash, view, read_agent, list_agents, write_agent, grep, glob, task.", + }, + ], + }); + const responseBody = JSON.stringify({ + choices: [{ message: { role: "assistant", content: "Done" } }], + }); + + const outputPath = await createProxy([ + { url: "/chat/completions", requestBody, responseBody }, + ]); + + const result = await readYamlOutput(outputPath); + const toolMessage = result.conversations[0].messages.find( + (m) => m.role === "tool", + ); + // The whole enumeration collapses so snapshots stay stable as the built-in + // tool set evolves (e.g. write_agent being added). + expect(toolMessage?.content).toBe( + "Tool 'report_intent' does not exist. Available tools that can be called are ${available_tools}.", + ); + }); + test("normalizes read_agent timing metadata", async () => { const requestBody = JSON.stringify({ messages: [ @@ -827,6 +868,85 @@ Always include PINEAPPLE_COCONUT_42. } }); + test("matches available-tools results after the built-in tool set changes", async () => { + const cachePath = path.join(tempDir, "cache.yaml"); + // Legacy snapshot recorded before write_agent was a built-in tool: the + // enumeration frozen on disk still contains the older tool list. + const cacheContent = yaml.stringify({ + models: ["test-model"], + conversations: [ + { + messages: [ + { role: "system", content: "${system}" }, + { role: "user", content: "Report intent" }, + { + role: "assistant", + tool_calls: [ + { + id: "toolcall_0", + type: "function", + function: { name: "report_intent", arguments: "{}" }, + }, + ], + }, + { + role: "tool", + tool_call_id: "toolcall_0", + content: + "Tool 'report_intent' does not exist. Available tools that can be called are ${shell}, view, read_agent, list_agents, grep, glob, task.", + }, + { role: "assistant", content: "Done" }, + ], + }, + ], + } satisfies NormalizedData); + await writeFile(cachePath, cacheContent); + + const proxy = new ReplayingCapiProxy( + "http://localhost:9999", + cachePath, + workDir, + ); + const proxyUrl = await proxy.start(); + + try { + const response = await makeRequest(proxyUrl, "/chat/completions", { + body: { + model: "test-model", + messages: [ + { role: "system", content: "System prompt" }, + { role: "user", content: "Report intent" }, + { + role: "assistant", + tool_calls: [ + { + id: "runtime-call-id", + type: "function", + function: { name: "report_intent", arguments: "{}" }, + }, + ], + }, + { + role: "tool", + tool_call_id: "runtime-call-id", + // Newer runtime added write_agent to the built-in tool set. + content: + "Tool 'report_intent' does not exist. Available tools that can be called are bash, read_bash, view, read_agent, list_agents, write_agent, grep, glob, task.", + }, + ], + }, + }); + + expect(response.status).toBe(200); + expect( + (JSON.parse(response.body) as ChatCompletion).choices[0].message + .content, + ).toBe("Done"); + } finally { + await proxy.stop(); + } + }); + test("expands workdir placeholder in cached response", async () => { const cachePath = path.join(tempDir, "cache.yaml"); const cacheContent = yaml.stringify({ diff --git a/test/harness/replayingCapiProxy.ts b/test/harness/replayingCapiProxy.ts index 740f8ab746..1c29fb7559 100644 --- a/test/harness/replayingCapiProxy.ts +++ b/test/harness/replayingCapiProxy.ts @@ -2,7 +2,7 @@ * Copyright (c) Microsoft Corporation. All rights reserved. *--------------------------------------------------------------------------------------------*/ -import { existsSync, appendFileSync } from "fs"; +import { appendFileSync, existsSync } from "fs"; import { mkdir, readFile, writeFile } from "fs/promises"; import type { ChatCompletion, @@ -19,10 +19,80 @@ import { CapturingHttpProxy, PerformRequestOptions, } from "./capturingHttpProxy"; +import { + anthropicMessagesEndpoint, + anthropicMessagesRequestToChatCompletion, + chatCompletionResponseToAnthropicMessage, + chatCompletionResponseToAnthropicSseChunks, +} from "./anthropicMessagesAdapter"; +import { + chatCompletionResponseToResponsesApiMessage, + chatCompletionResponseToResponsesApiSseChunks, + responsesApiRequestToChatCompletion, + responsesEndpoint, +} from "./responsesApiAdapter"; import { iife, ShellConfig, sleep } from "./util"; export const workingDirPlaceholder = "${workdir}"; const chatCompletionEndpoint = "/chat/completions"; +export type ReplayBackend = + | "capi" + | "anthropic-messages" + | "openai-responses" + | "openai-completions"; + +type ReplayProtocol = { + endpoint: string; + normalizeRequest?: (body: string) => string; + responseBody?: (response: ChatCompletion) => unknown; + responseChunks: (response: ChatCompletion) => string[]; + responseEndChunk?: string; + errorBody?: (code: string | undefined, message: string) => unknown; + canonicalResponse?: boolean; +}; + +const chatCompletionsProtocol = { + endpoint: chatCompletionEndpoint, + responseChunks: (response) => + convertToStreamingResponseChunks(response).map( + (chunk) => `data: ${JSON.stringify(chunk)}\n\n`, + ), + responseEndChunk: "data: [DONE]\n\n", + canonicalResponse: true, +} satisfies ReplayProtocol; + +const replayProtocols: Record = { + capi: chatCompletionsProtocol, + "openai-completions": { + ...chatCompletionsProtocol, + normalizeRequest: coalesceAdjacentUserMessages, + }, + "anthropic-messages": { + endpoint: anthropicMessagesEndpoint, + normalizeRequest: (body) => + coalesceAdjacentUserMessages( + anthropicMessagesRequestToChatCompletion(body), + ), + responseBody: chatCompletionResponseToAnthropicMessage, + responseChunks: chatCompletionResponseToAnthropicSseChunks, + errorBody: (code, message) => { + const type = code ?? "rate_limited"; + return { type: "error", error: { type, message } }; + }, + }, + "openai-responses": { + endpoint: responsesEndpoint, + normalizeRequest: (body) => + coalesceAdjacentUserMessages(responsesApiRequestToChatCompletion(body)), + responseBody: chatCompletionResponseToResponsesApiMessage, + responseChunks: chatCompletionResponseToResponsesApiSseChunks, + }, +}; + +const modelEndpoints = new Set( + Object.values(replayProtocols).map((protocol) => protocol.endpoint), +); + const shellConfig = process.platform === "win32" ? ShellConfig.powerShell : ShellConfig.bash; const normalizedToolNames: Record = { @@ -90,6 +160,7 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { filePath, workDir, testInfo, + backend: "capi", toolResultNormalizers: [...this.defaultToolResultNormalizers], }; } @@ -112,7 +183,10 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { // In CI mode (GITHUB_ACTIONS=true) we never write — the snapshots are read-only. // Otherwise tests that exercise only a subset of a multi-conversation snapshot // would silently overwrite the file with that subset, breaking subsequent runs. - if (this.state && process.env.GITHUB_ACTIONS !== "true") { + if ( + this.state?.backend === "capi" && + process.env.GITHUB_ACTIONS !== "true" + ) { await writeCapturesToDisk(this.exchanges, this.state); } @@ -120,6 +194,7 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { filePath: config.filePath, workDir: config.workDir, testInfo: config.testInfo, + backend: parseReplayBackend(config.backend), toolResultNormalizers: [...this.defaultToolResultNormalizers], }; @@ -133,15 +208,21 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { this.state.storedData = yaml.parse(content) as NormalizedData; normalizeToolResultOrder(this.state.storedData.conversations); normalizeStoredUserMessages(this.state.storedData.conversations); + normalizeStoredToolMessages(this.state.storedData.conversations); + normalizeStoredMessagesForBackend( + this.state.storedData.conversations, + this.state.backend, + ); } } async stop(skipWritingCache?: boolean): Promise { await super.stop(); - // In CI mode we never write — the snapshots are read-only. + // CAPI is the authoritative capture path. BYOK modes only verify that the + // same canonical snapshots replay through each provider protocol. if ( - this.state && + this.state?.backend === "capi" && !skipWritingCache && process.env.GITHUB_ACTIONS !== "true" ) { @@ -223,17 +304,21 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { options.requestOptions.path === "/exchanges" && options.requestOptions.method === "GET" ) { - const chatCompletionExchanges = this.exchanges.filter( - (e) => e.request.url === chatCompletionEndpoint, - ); + const protocol = + replayProtocols[this.state?.backend ?? "capi"]; const parsedExchanges = await Promise.all( - chatCompletionExchanges.map((e) => - parseHttpExchange( - e.request.body, - e.response?.body, - e.request.headers, + this.exchanges + .filter((exchange) => exchange.request.url === protocol.endpoint) + .map((exchange) => + parseHttpExchange( + protocol.normalizeRequest?.(exchange.request.body) ?? + exchange.request.body, + protocol.canonicalResponse + ? exchange.response?.body + : undefined, + exchange.request.headers, + ), ), - ), ); options.onResponseStart(200, {}); options.onData(Buffer.from(JSON.stringify(parsedExchanges))); @@ -335,16 +420,42 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { options.onResponseEnd(); return; } - - // Handle /chat/completions endpoint + const requestPath = options.requestOptions.path ?? ""; + const protocol = replayProtocols[state.backend]; if ( - state.storedData && - options.requestOptions.path === chatCompletionEndpoint && - options.body + modelEndpoints.has(requestPath) && + state.backend !== "capi" && + requestPath !== protocol.endpoint ) { + const message = `Expected ${protocol.endpoint} for backend ${state.backend}, received ${requestPath}`; + options.onResponseStart(400, { + "content-type": "application/json", + ...commonResponseHeaders, + }); + options.onData( + Buffer.from( + JSON.stringify({ + error: { type: "protocol_mismatch", message }, + }), + ), + ); + options.onResponseEnd(); + return; + } + + const isModelRequest = requestPath === protocol.endpoint; + // Every protocol enters the existing Chat Completions snapshot matcher. + const normalizedBody = + isModelRequest && options.body + ? (protocol.normalizeRequest?.(options.body) ?? options.body) + : options.body; + if (state.storedData && isModelRequest && normalizedBody) { + const streamingIsRequested = + (JSON.parse(normalizedBody) as { stream?: boolean }).stream === true; + const savedError = await findSavedChatCompletionError( state.storedData, - options.body, + normalizedBody, state.workDir, state.toolResultNormalizers, ); @@ -360,14 +471,12 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { options.onResponseStart(savedError.status, headers); options.onData( Buffer.from( - JSON.stringify({ - error: { - message: - savedError.message ?? "Rate limited by test snapshot", - type: savedError.code ?? "rate_limited", - code: savedError.code ?? "rate_limited", - }, - }), + JSON.stringify( + (protocol.errorBody ?? openAIErrorBody)( + savedError.code, + savedError.message ?? "Rate limited by test snapshot", + ), + ), ), ); options.onResponseEnd(); @@ -376,45 +485,19 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { const savedResponse = await findSavedChatCompletionResponse( state.storedData, - options.body, + normalizedBody, state.workDir, state.toolResultNormalizers, ); if (savedResponse) { - const streamingIsRequested = - options.body && - (JSON.parse(options.body) as { stream?: boolean }).stream === - true; - - if (streamingIsRequested) { - const headers = { - "content-type": "text/event-stream", - ...commonResponseHeaders, - }; - options.onResponseStart(200, headers); - for (const chunk of convertToStreamingResponseChunks( - savedResponse, - )) { - options.onData( - Buffer.from(`data: ${JSON.stringify(chunk)}\n\n`), - ); - if (this.slowStreaming) { - await sleep(100); - } - } - options.onData(Buffer.from("data: [DONE]\n\n")); - options.onResponseEnd(); - } else { - const body = JSON.stringify(savedResponse); - const headers = { - "content-type": "application/json", - ...commonResponseHeaders, - }; - options.onResponseStart(200, headers); - options.onData(Buffer.from(body)); - options.onResponseEnd(); - } + await this.respondWithProtocol( + options, + protocol, + savedResponse, + streamingIsRequested, + commonResponseHeaders, + ); return; } @@ -424,15 +507,11 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { if ( await isRequestOnlySnapshot( state.storedData, - options.body, + normalizedBody, state.workDir, state.toolResultNormalizers, ) ) { - const streamingIsRequested = - options.body && - (JSON.parse(options.body) as { stream?: boolean }).stream === - true; const headers = { "content-type": streamingIsRequested ? "text/event-stream" @@ -449,7 +528,7 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { // Beyond this point, we're only going to be able to supply responses in CI if we have a snapshot, // and we only store snapshots for chat completion. For anything else (e.g., custom-agents fetches), // return 404 so the CLI treats them as unavailable instead of erroring. - if (options.requestOptions.path !== chatCompletionEndpoint) { + if (!isModelRequest) { const headers = { "content-type": "application/json", "x-github-request-id": "proxy-not-found", @@ -465,13 +544,14 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { // Fallback to normal proxying if no cached response found // This implicitly captures the new exchange too const isCI = process.env.GITHUB_ACTIONS === "true"; - if (isCI) { + if (isCI || state.backend !== "capi") { await exitWithNoMatchingRequestError( options, state.testInfo, state.workDir, state.toolResultNormalizers, state.storedData, + normalizedBody, ); return; } @@ -481,6 +561,43 @@ export class ReplayingCapiProxy extends CapturingHttpProxy { } }); } + + private async respondWithProtocol( + options: PerformRequestOptions, + protocol: ReplayProtocol, + response: ChatCompletion, + streaming: boolean, + commonHeaders: Record, + ): Promise { + if (!streaming) { + options.onResponseStart(200, { + "content-type": "application/json", + ...commonHeaders, + }); + options.onData( + Buffer.from( + JSON.stringify(protocol.responseBody?.(response) ?? response), + ), + ); + options.onResponseEnd(); + return; + } + + options.onResponseStart(200, { + "content-type": "text/event-stream", + ...commonHeaders, + }); + for (const chunk of protocol.responseChunks(response)) { + options.onData(Buffer.from(chunk)); + if (this.slowStreaming) { + await sleep(100); + } + } + if (protocol.responseEndChunk) { + options.onData(Buffer.from(protocol.responseEndChunk)); + } + options.onResponseEnd(); + } } async function writeCapturesToDisk( @@ -591,11 +708,12 @@ async function exitWithNoMatchingRequestError( workDir: string, toolResultNormalizers: ToolResultNormalizer[], storedData?: NormalizedData, + requestBody?: string, ) { let diagnostics: string; try { const normalized = await parseAndNormalizeRequest( - options.body, + requestBody ?? options.body, workDir, toolResultNormalizers, ); @@ -604,8 +722,11 @@ async function exitWithNoMatchingRequestError( let rawMessages: unknown[] = []; try { rawMessages = - (JSON.parse(options.body ?? "{}") as { messages?: unknown[] }) - .messages ?? []; + ( + JSON.parse(requestBody ?? options.body ?? "{}") as { + messages?: unknown[]; + } + ).messages ?? []; } catch { /* non-JSON body */ } @@ -774,6 +895,60 @@ async function transformHttpExchanges( return { models: Array.from(dedupedModels), conversations: dedupedExchanges }; } +function parseReplayBackend(value: unknown): ReplayBackend { + if (value === undefined || value === null || value === "") return "capi"; + if (typeof value === "string" && Object.hasOwn(replayProtocols, value)) { + return value as ReplayBackend; + } + throw new Error(`Unsupported replay backend: ${String(value)}`); +} + +function coalesceAdjacentUserMessages(requestBody: string): string { + const request = JSON.parse(requestBody) as { + messages?: Array<{ + role?: string; + content?: unknown; + [key: string]: unknown; + }>; + }; + if (!request.messages) return requestBody; + + const messages: NonNullable = []; + for (const message of request.messages) { + const previous = messages.at(-1); + if ( + previous?.role === "user" && + message.role === "user" && + typeof previous.content === "string" && + typeof message.content === "string" + ) { + previous.content = `${previous.content.trimEnd()}\n\n\n${message.content.trimStart()}`; + } else { + messages.push(message); + } + } + + for (const message of messages) { + if (message.role === "user" && typeof message.content === "string") { + message.content = normalizeUserMessage(message.content).replace( + /\n{5,}/g, + "\n\n\n", + ); + } + } + + request.messages = messages; + return JSON.stringify(request); +} + +function openAIErrorBody( + code: string | undefined, + message: string, +): unknown { + const type = code ?? "rate_limited"; + return { error: { message, type, code: type } }; +} + function normalizeFilenames( conversations: NormalizedConversation[], workDir: string, @@ -1079,6 +1254,67 @@ function normalizeStoredUserMessages(conversations: NormalizedConversation[]) { } } +function normalizeStoredMessagesForBackend( + conversations: NormalizedConversation[], + backend: ReplayBackend, +) { + if (backend === "capi") return; + + for (const conversation of conversations) { + conversation.messages = coalesceMessages( + conversation.messages, + backend !== "openai-completions", + ); + } +} + +function coalesceMessages( + messages: NormalizedMessage[], + coalesceAssistantMessages: boolean, +): NormalizedMessage[] { + const result: NormalizedMessage[] = []; + for (const message of messages) { + const previous = result.at(-1); + const shouldCoalesce = + previous?.role === message.role && + ((coalesceAssistantMessages && message.role === "assistant") || + message.role === "user"); + if (!shouldCoalesce) { + result.push(message); + continue; + } + + const separator = message.role === "user" ? "\n\n\n" : ""; + const previousContent = previous.content ?? ""; + const currentContent = message.content ?? ""; + const content = `${previousContent}${previousContent && currentContent ? separator : ""}${currentContent}`; + if (content) previous.content = content; + + const toolCalls = [ + ...(previous.tool_calls ?? []), + ...(message.tool_calls ?? []), + ]; + if (toolCalls.length) previous.tool_calls = toolCalls; + } + return result; +} + +// Re-normalizes the built-in tool enumeration in stored tool results at load +// time. Snapshots recorded before normalizeAvailableToolNames collapsed the +// whole list (or recorded against an older tool set) still contain the literal +// enumeration on disk; the result normalizers only run against live requests, +// so without this the stored side would keep the stale list and never match a +// request whose tool set has since changed. +function normalizeStoredToolMessages(conversations: NormalizedConversation[]) { + for (const conversation of conversations) { + for (const message of conversation.messages) { + if (message.role === "tool" && typeof message.content === "string") { + message.content = normalizeAvailableToolNames(message.content); + } + } + } +} + function normalizeSkillContextFrontmatter(content: string): string { // Runtime versions may include or omit SKILL.md metadata in the prompt context. return content.replace( @@ -1169,41 +1405,21 @@ function normalizeReadAgentTimings(result: string): string { .replace(/\bduration: \d+(?:\.\d+)?s\b/g, "duration: 0s"); } -// Maps the platform-specific shell tool family names to stable placeholders. -// On Windows the runtime exposes powershell/read_powershell/stop_powershell/..., -// on Linux/macOS it exposes bash/read_bash/stop_bash/.... Ordered so that the -// prefixed names are handled explicitly; \b boundaries keep bare names from -// matching inside the prefixed ones. -const shellToolFamilyReplacements: ReadonlyArray = [ - [/\bread_powershell\b/g, "${read_shell}"], - [/\bstop_powershell\b/g, "${stop_shell}"], - [/\blist_powershell\b/g, "${list_shell}"], - [/\bwrite_powershell\b/g, "${write_shell}"], - [/\bpowershell\b/g, "${shell}"], - [/\bread_bash\b/g, "${read_shell}"], - [/\bstop_bash\b/g, "${stop_shell}"], - [/\blist_bash\b/g, "${list_shell}"], - [/\bwrite_bash\b/g, "${write_shell}"], - [/\bbash\b/g, "${shell}"], -]; - -function normalizeShellToolFamilyNames(text: string): string { - let result = text; - for (const [pattern, replacement] of shellToolFamilyReplacements) { - result = result.replace(pattern, replacement); - } - return result; -} +// Stable placeholder for the built-in tool enumeration the runtime emits when a +// nonexistent tool is called (see normalizeAvailableToolNames). +export const availableToolsPlaceholder = "${available_tools}"; // When a model calls a tool that doesn't exist (e.g., the removed report_intent // tool), the runtime replies with "Available tools that can be called are ." -// The shell tool family names in that list are platform-specific, so normalize -// them to placeholders to keep snapshots matching across Windows/Linux/macOS. +// That enumeration is both platform-specific (shell tool family names differ +// across OSes) and runtime-version-specific (built-in tools such as write_agent +// are added or removed over time), so any test that trips this path would break +// whenever the tool set changes. Collapse the whole list to a stable placeholder +// so snapshots keep matching as the built-in tool set evolves. function normalizeAvailableToolNames(result: string): string { return result.replace( - /(Available tools that can be called are )([^.]*)/g, - (_full, prefix: string, list: string) => - prefix + normalizeShellToolFamilyNames(list), + /(Available tools that can be called are )[^.]*/g, + (_full, prefix: string) => prefix + availableToolsPlaceholder, ); } @@ -1546,6 +1762,7 @@ type ReplayingCapiProxyState = { filePath: string; workDir: string; testInfo?: { file: string; line?: number }; + backend: ReplayBackend; storedData?: NormalizedData | undefined; toolResultNormalizers: ToolResultNormalizer[]; }; diff --git a/test/harness/responsesApiAdapter.ts b/test/harness/responsesApiAdapter.ts new file mode 100644 index 0000000000..16568f6e03 --- /dev/null +++ b/test/harness/responsesApiAdapter.ts @@ -0,0 +1,437 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +import { randomUUID } from "node:crypto"; +import type { ChatCompletion } from "openai/resources/chat/completions"; +import type { Response as OpenAIResponse } from "openai/resources/responses/responses"; +import { + CanonicalMessage, + formatSseEvent, + functionToolCalls, + isObject, + JsonObject, +} from "./modelProtocolAdapterShared"; + +export const responsesEndpoint = "/responses"; + +type ResponsesRequest = { + model: string; + instructions?: string; + input?: string | JsonObject[]; + stream?: boolean; + tools?: JsonObject[]; + tool_choice?: unknown; + temperature?: number | null; + top_p?: number | null; + parallel_tool_calls?: boolean | null; +}; + +export type ResponsesApiResponse = OpenAIResponse; + +export function responsesApiRequestToChatCompletion( + requestBody: string, +): string { + const request = JSON.parse(requestBody) as ResponsesRequest; + const messages: CanonicalMessage[] = []; + if (request.instructions) { + messages.push({ role: "system", content: request.instructions }); + } + + if (typeof request.input === "string") { + messages.push({ role: "user", content: request.input }); + } else { + for (const item of request.input ?? []) { + const converted = responseInputItemToCanonicalMessages(item); + messages.push(...converted); + } + } + + return JSON.stringify({ + model: request.model, + messages: coalesceAssistantMessages(messages), + ...(request.tools ? { tools: convertResponsesTools(request.tools) } : {}), + ...(request.tool_choice !== undefined + ? { tool_choice: convertResponsesToolChoice(request.tool_choice) } + : {}), + ...(request.stream !== undefined ? { stream: request.stream } : {}), + ...(request.temperature !== undefined && request.temperature !== null + ? { temperature: request.temperature } + : {}), + ...(request.top_p !== undefined && request.top_p !== null + ? { top_p: request.top_p } + : {}), + ...(request.parallel_tool_calls !== undefined && + request.parallel_tool_calls !== null + ? { parallel_tool_calls: request.parallel_tool_calls } + : {}), + }); +} + +function responseInputItemToCanonicalMessages( + item: JsonObject, +): CanonicalMessage[] { + if (item.type === "function_call") { + const callId = + typeof item.call_id === "string" + ? item.call_id + : typeof item.id === "string" + ? item.id + : ""; + return [ + { + role: "assistant", + content: null, + tool_calls: [ + { + id: callId, + type: "function", + function: { + name: typeof item.name === "string" ? item.name : "", + arguments: + typeof item.arguments === "string" ? item.arguments : "{}", + }, + }, + ], + }, + ]; + } + + if (item.type === "function_call_output") { + return [ + { + role: "tool", + tool_call_id: typeof item.call_id === "string" ? item.call_id : "", + content: + typeof item.output === "string" + ? item.output + : JSON.stringify(item.output ?? ""), + }, + ]; + } + + if (item.type === "reasoning") return []; + + if ( + item.type !== "message" && + item.role !== "user" && + item.role !== "assistant" && + item.role !== "system" + ) { + return []; + } + + const role = + item.role === "assistant" || item.role === "system" ? item.role : "user"; + if (typeof item.content === "string") { + return [{ role, content: item.content }]; + } + if (!Array.isArray(item.content)) return [{ role, content: "" }]; + + const parts: unknown[] = []; + for (const part of item.content) { + if (!isObject(part)) continue; + if ( + (part.type === "input_text" || part.type === "output_text") && + typeof part.text === "string" + ) { + parts.push({ type: "text", text: part.text }); + } else if ( + part.type === "input_image" && + typeof part.image_url === "string" + ) { + parts.push({ + type: "image_url", + image_url: { + url: part.image_url, + ...(typeof part.detail === "string" ? { detail: part.detail } : {}), + }, + }); + } else if ( + part.type === "input_file" && + typeof part.file_data === "string" + ) { + parts.push({ + type: "file", + file: { + file_data: part.file_data, + ...(typeof part.filename === "string" + ? { filename: part.filename } + : {}), + }, + }); + } + } + + const onlyText = parts.every( + (part) => isObject(part) && part.type === "text", + ); + return [ + { + role, + content: onlyText + ? parts + .map((part) => + isObject(part) && typeof part.text === "string" ? part.text : "", + ) + .join("") + : parts, + }, + ]; +} + +function coalesceAssistantMessages( + messages: CanonicalMessage[], +): CanonicalMessage[] { + const result: CanonicalMessage[] = []; + for (const message of messages) { + const previous = result[result.length - 1]; + if (message.role === "assistant" && previous?.role === "assistant") { + const previousText = + typeof previous.content === "string" ? previous.content : ""; + const currentText = + typeof message.content === "string" ? message.content : ""; + previous.content = `${previousText}${currentText}` || null; + const toolCalls = [ + ...(previous.tool_calls ?? []), + ...(message.tool_calls ?? []), + ]; + if (toolCalls.length) previous.tool_calls = toolCalls; + } else { + result.push(message); + } + } + return result; +} + +function convertResponsesTools(tools: JsonObject[]): JsonObject[] { + return tools + .filter((tool) => tool.type === "function" && typeof tool.name === "string") + .map((tool) => ({ + type: "function", + function: { + name: tool.name, + ...(typeof tool.description === "string" + ? { description: tool.description } + : {}), + ...(isObject(tool.parameters) ? { parameters: tool.parameters } : {}), + ...(typeof tool.strict === "boolean" ? { strict: tool.strict } : {}), + }, + })); +} + +function convertResponsesToolChoice(toolChoice: unknown): unknown { + if ( + toolChoice === "auto" || + toolChoice === "none" || + toolChoice === "required" + ) { + return toolChoice; + } + if ( + isObject(toolChoice) && + toolChoice.type === "function" && + typeof toolChoice.name === "string" + ) { + return { + type: "function", + function: { name: toolChoice.name }, + }; + } + return undefined; +} + +export function chatCompletionResponseToResponsesApiMessage( + response: ChatCompletion, +): ResponsesApiResponse { + const output: ResponsesApiResponse["output"] = []; + const outputText: string[] = []; + + for (const choice of response.choices) { + if (choice.message.content) { + const text = choice.message.content; + outputText.push(text); + output.push({ + type: "message", + id: `msg_${randomUUID()}`, + role: "assistant", + status: "completed", + content: [ + { + type: "output_text", + text, + annotations: [], + }, + ], + }); + } + for (const toolCall of functionToolCalls(choice.message)) { + output.push({ + type: "function_call", + id: `fc_${toolCall.id}`, + call_id: toolCall.id, + name: toolCall.function.name, + arguments: toolCall.function.arguments, + status: "completed", + }); + } + } + + const finishReason = response.choices[0]?.finish_reason; + return { + id: response.id, + object: "response", + created_at: response.created, + model: response.model, + status: "completed", + output, + output_text: outputText.join(""), + incomplete_details: + finishReason === "length" + ? { reason: "max_output_tokens" } + : finishReason === "content_filter" + ? { reason: "content_filter" } + : null, + error: null, + instructions: null, + metadata: null, + parallel_tool_calls: false, + temperature: null, + tool_choice: "auto", + tools: [], + top_p: null, + usage: { + input_tokens: response.usage?.prompt_tokens ?? 0, + output_tokens: response.usage?.completion_tokens ?? 0, + total_tokens: response.usage?.total_tokens ?? 0, + input_tokens_details: { + cached_tokens: + response.usage?.prompt_tokens_details?.cached_tokens ?? 0, + }, + output_tokens_details: { + reasoning_tokens: + response.usage?.completion_tokens_details?.reasoning_tokens ?? 0, + }, + }, + }; +} + +export function chatCompletionResponseToResponsesApiSseChunks( + response: ChatCompletion, +): string[] { + const fullResponse = chatCompletionResponseToResponsesApiMessage(response); + const skeleton = { + ...fullResponse, + status: "in_progress" as const, + output: [], + output_text: "", + usage: undefined, + }; + const chunks: string[] = []; + let sequenceNumber = 0; + const event = (type: string, data: JsonObject) => + formatSseEvent(type, { + type, + sequence_number: sequenceNumber++, + ...data, + }); + + chunks.push( + event("response.created", { response: skeleton }), + event("response.in_progress", { response: skeleton }), + ); + + for ( + let outputIndex = 0; + outputIndex < fullResponse.output.length; + outputIndex++ + ) { + const item = fullResponse.output[outputIndex]; + const addedItem = + item.type === "message" + ? { ...item, status: "in_progress" as const, content: [] } + : item.type === "function_call" + ? { ...item, status: "in_progress" as const, arguments: "" } + : item; + chunks.push( + event("response.output_item.added", { + output_index: outputIndex, + item: addedItem, + }), + ); + + if (item.type === "message" && Array.isArray(item.content)) { + for ( + let contentIndex = 0; + contentIndex < item.content.length; + contentIndex++ + ) { + const part = item.content[contentIndex]; + chunks.push( + event("response.content_part.added", { + item_id: item.id, + output_index: outputIndex, + content_index: contentIndex, + part: + isObject(part) && part.type === "output_text" + ? { ...part, text: "" } + : part, + }), + ); + if ( + isObject(part) && + part.type === "output_text" && + typeof part.text === "string" + ) { + chunks.push( + event("response.output_text.delta", { + item_id: item.id, + output_index: outputIndex, + content_index: contentIndex, + delta: part.text, + logprobs: [], + }), + event("response.output_text.done", { + item_id: item.id, + output_index: outputIndex, + content_index: contentIndex, + text: part.text, + logprobs: [], + }), + ); + } + chunks.push( + event("response.content_part.done", { + item_id: item.id, + output_index: outputIndex, + content_index: contentIndex, + part, + }), + ); + } + } else if (item.type === "function_call") { + chunks.push( + event("response.function_call_arguments.delta", { + item_id: item.id, + output_index: outputIndex, + delta: item.arguments, + }), + event("response.function_call_arguments.done", { + item_id: item.id, + output_index: outputIndex, + arguments: item.arguments, + }), + ); + } + + chunks.push( + event("response.output_item.done", { + output_index: outputIndex, + item, + }), + ); + } + + chunks.push(event("response.completed", { response: fullResponse })); + return chunks; +} diff --git a/test/harness/test-mcp-oauth-server.mjs b/test/harness/test-mcp-oauth-server.mjs new file mode 100644 index 0000000000..eacd35f304 --- /dev/null +++ b/test/harness/test-mcp-oauth-server.mjs @@ -0,0 +1,325 @@ +#!/usr/bin/env node +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +/** + * Minimal OAuth-protected Streamable HTTP MCP server for SDK E2E tests. + * + * The `/mcp` endpoint returns a WWW-Authenticate challenge until requests include + * an accepted test token, then serves enough JSON-RPC MCP methods for the runtime + * to initialize and list/call one tool. Specific tool-call scenarios trigger + * replacement-token challenges so SDK E2E tests can cover refresh, upscope, and + * reauth flows without relying on a real OAuth server. + */ + +import http from "node:http"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const DEFAULT_EXPECTED_TOKEN = "sdk-host-token"; +const PROTOCOL_VERSION = "2025-03-26"; +const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource"; + +export async function startOAuthMcpServer({ + expectedToken = DEFAULT_EXPECTED_TOKEN, + host = "127.0.0.1", + port = 0, +} = {}) { + const requests = []; + const tokens = { + initial: expectedToken, + refresh: `${expectedToken}-refresh`, + upscope: `${expectedToken}-upscope`, + reauth: `${expectedToken}-reauth`, + rejected: `${expectedToken}-rejected`, + }; + const acceptedTokens = new Set([ + tokens.initial, + tokens.refresh, + tokens.upscope, + tokens.reauth, + ]); + + const server = http.createServer(async (req, res) => { + const url = new URL( + req.url ?? "/", + `http://${req.headers.host ?? `${host}:${port}`}`, + ); + const baseUrl = url.origin; + + if (req.method === "GET" && url.pathname === "/__requests") { + respondJson(res, 200, requests); + return; + } + + if ( + req.method === "GET" && + url.pathname === PROTECTED_RESOURCE_PATH + ) { + respondJson(res, 200, { + resource: `${baseUrl}/mcp`, + authorization_servers: [baseUrl], + scopes_supported: ["mcp.read"], + bearer_methods_supported: ["header"], + }); + return; + } + + if ( + req.method === "GET" && + url.pathname === "/.well-known/oauth-authorization-server" + ) { + respondJson(res, 200, { + issuer: baseUrl, + authorization_endpoint: `${baseUrl}/authorize`, + token_endpoint: `${baseUrl}/token`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code"], + }); + return; + } + + if (url.pathname !== "/mcp") { + respondJson(res, 404, { error: "not_found" }); + return; + } + + const body = await readBody(req); + requests.push({ + method: req.method, + path: url.pathname, + authorization: req.headers.authorization ?? null, + body: body || null, + }); + + const token = parseBearerToken(req.headers.authorization); + if (!token || !acceptedTokens.has(token)) { + challengeInitial(res, baseUrl); + return; + } + + if (req.method !== "POST") { + respondJson(res, 405, { error: "method_not_allowed" }); + return; + } + + const parsedBody = parseJsonBody(body); + if (!parsedBody.ok) { + respondJson(res, 400, { error: "invalid_json" }); + return; + } + + const message = parsedBody.value; + const replacementChallenge = getReplacementChallenge( + message, + token, + tokens, + baseUrl, + ); + if (replacementChallenge) { + res.writeHead(replacementChallenge.statusCode, { + "www-authenticate": replacementChallenge.wwwAuthenticate, + "content-type": "application/json", + }); + res.end(JSON.stringify({ error: replacementChallenge.error })); + return; + } + + const response = Array.isArray(message) + ? message + .map((item) => handleJsonRpcMessage(item)) + .filter((item) => item !== undefined) + : handleJsonRpcMessage(message); + + if ( + response === undefined || + (Array.isArray(response) && response.length === 0) + ) { + res.writeHead(202, { "mcp-session-id": "oauth-test-session" }); + res.end(); + return; + } + + res.writeHead(200, { + "content-type": "application/json", + "mcp-session-id": "oauth-test-session", + }); + res.end(JSON.stringify(response)); + }); + + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(port, host, () => { + server.off("error", reject); + resolve(); + }); + }); + + const address = server.address(); + if (!address || typeof address === "string") { + throw new Error("Expected TCP server address"); + } + + return { + url: `http://${host}:${address.port}`, + requests, + close: () => + new Promise((resolve, reject) => + server.close((err) => (err ? reject(err) : resolve())), + ), + }; +} + +function getReplacementChallenge(message, token, tokens, baseUrl) { + const messages = Array.isArray(message) ? message : [message]; + const toolCall = messages.find((item) => item?.method === "tools/call"); + const scenario = toolCall?.params?.arguments?.scenario; + + if (scenario === "refresh" && token !== tokens.refresh) { + return { + statusCode: 401, + wwwAuthenticate: 'Bearer error="invalid_token"', + error: "token_expired", + }; + } + + if (scenario === "upscope" && token !== tokens.upscope) { + return { + statusCode: 403, + wwwAuthenticate: `Bearer resource_metadata="${baseUrl}${PROTECTED_RESOURCE_PATH}", scope="mcp.write", error="insufficient_scope"`, + error: "insufficient_scope", + }; + } + + if (scenario === "reauth" && token !== tokens.reauth) { + return { + statusCode: 401, + wwwAuthenticate: 'Bearer error="invalid_token"', + error: "reauth_required", + }; + } + + if (scenario === "cancel" && token !== tokens.refresh) { + return { + statusCode: 401, + wwwAuthenticate: 'Bearer error="invalid_token"', + error: "token_expired", + }; + } + + return undefined; +} + +function handleJsonRpcMessage(message) { + if (!message || typeof message !== "object" || !("id" in message)) { + return undefined; + } + + switch (message.method) { + case "initialize": + return { + jsonrpc: "2.0", + id: message.id, + result: { + protocolVersion: message.params?.protocolVersion ?? PROTOCOL_VERSION, + capabilities: { tools: {} }, + serverInfo: { name: "oauth-test-server", version: "1.0.0" }, + }, + }; + case "tools/list": + return { + jsonrpc: "2.0", + id: message.id, + result: { + tools: [ + { + name: "whoami", + description: "Returns the authenticated test principal.", + inputSchema: { + type: "object", + properties: { + scenario: { + type: "string", + enum: ["initial", "refresh", "upscope", "reauth", "cancel"], + }, + }, + additionalProperties: false, + }, + _meta: { "ui.visibility": ["model", "app"] }, + }, + ], + }, + }; + case "tools/call": + return { + jsonrpc: "2.0", + id: message.id, + result: { + content: [{ type: "text", text: "oauth-test-user" }], + isError: false, + }, + }; + default: + return { + jsonrpc: "2.0", + id: message.id, + error: { code: -32601, message: `Method not found: ${message.method}` }, + }; + } +} + +function parseBearerToken(authorization) { + const match = /^Bearer (.+)$/.exec(authorization ?? ""); + return match?.[1]; +} + +function challengeInitial(res, baseUrl) { + const resourceMetadataUrl = `${baseUrl}${PROTECTED_RESOURCE_PATH}`; + res.writeHead(401, { + "www-authenticate": `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp.read", error="invalid_token"`, + "content-type": "application/json", + }); + res.end(JSON.stringify({ error: "missing_or_invalid_token" })); +} + +function readBody(req) { + return new Promise((resolve, reject) => { + const chunks = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("error", reject); + req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + }); +} + +function parseJsonBody(body) { + if (!body) { + return { ok: true, value: undefined }; + } + + try { + return { ok: true, value: JSON.parse(body) }; + } catch { + return { ok: false, value: undefined }; + } +} + +function respondJson(res, statusCode, body) { + const data = JSON.stringify(body); + res.writeHead(statusCode, { + "content-type": "application/json", + "content-length": Buffer.byteLength(data), + }); + res.end(data); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const server = await startOAuthMcpServer({ + expectedToken: process.env.EXPECTED_TOKEN ?? DEFAULT_EXPECTED_TOKEN, + }); + console.log(`Listening: ${server.url}`); + process.on("SIGTERM", async () => { + await server.close(); + process.exit(0); + }); +} diff --git a/test/snapshots/abort/should_abort_during_active_streaming.yaml b/test/snapshots/abort/should_abort_during_active_streaming.yaml index ea70c0d536..70981ee597 100644 --- a/test/snapshots/abort/should_abort_during_active_streaming.yaml +++ b/test/snapshots/abort/should_abort_during_active_streaming.yaml @@ -35,3 +35,13 @@ conversations: content: Say 'abort_recovery_ok'. - role: assistant content: abort_recovery_ok + - messages: + - role: system + content: ${system} + - role: user + content: Write a very long essay about the history of computing, covering every decade from the 1940s to the 2020s in + great detail. + - role: user + content: Say 'abort_recovery_ok'. + - role: assistant + content: abort_recovery_ok diff --git a/test/snapshots/mode_handlers/should_invoke_exit_plan_mode_handler_when_model_uses_tool.yaml b/test/snapshots/mode_handlers/should_invoke_exit_plan_mode_handler_when_model_uses_tool.yaml index d3e915f6d4..078ba05483 100644 --- a/test/snapshots/mode_handlers/should_invoke_exit_plan_mode_handler_when_model_uses_tool.yaml +++ b/test/snapshots/mode_handlers/should_invoke_exit_plan_mode_handler_when_model_uses_tool.yaml @@ -13,7 +13,7 @@ conversations: function: name: exit_plan_mode arguments: '{"summary":"Greeting file implementation - plan","actions":["interactive","autopilot","exit_only"],"recommendedAction":"interactive"}' + plan","actions":["autopilot","interactive","exit_only"],"recommendedAction":"interactive"}' - role: tool tool_call_id: toolcall_0 content: >- diff --git a/test/snapshots/resume_mcp_oauth/should_resume_a_persisted_session_with_mcp_auth_handler.yaml b/test/snapshots/resume_mcp_oauth/should_resume_a_persisted_session_with_mcp_auth_handler.yaml new file mode 100644 index 0000000000..250402101b --- /dev/null +++ b/test/snapshots/resume_mcp_oauth/should_resume_a_persisted_session_with_mcp_auth_handler.yaml @@ -0,0 +1,10 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: What is 1+1? + - role: assistant + content: 1 + 1 = 2 diff --git a/test/snapshots/rpc_mcp_lifecycle/should_respond_to_mcp_oauth_request_without_pending_request.yaml b/test/snapshots/rpc_server_misc/should_get_set_and_clear_user_settings.yaml similarity index 100% rename from test/snapshots/rpc_mcp_lifecycle/should_respond_to_mcp_oauth_request_without_pending_request.yaml rename to test/snapshots/rpc_server_misc/should_get_set_and_clear_user_settings.yaml diff --git a/test/snapshots/rpc_server_misc/should_login_list_getcurrentauth_and_logout_account.yaml b/test/snapshots/rpc_server_misc/should_login_list_getcurrentauth_and_logout_account.yaml new file mode 100644 index 0000000000..056351ddb4 --- /dev/null +++ b/test/snapshots/rpc_server_misc/should_login_list_getcurrentauth_and_logout_account.yaml @@ -0,0 +1,3 @@ +models: + - claude-sonnet-4.5 +conversations: [] diff --git a/test/snapshots/rpc_session_state_extras/should_add_byok_provider_and_model_at_runtime.yaml b/test/snapshots/rpc_session_state_extras/should_add_byok_provider_and_model_at_runtime.yaml new file mode 100644 index 0000000000..056351ddb4 --- /dev/null +++ b/test/snapshots/rpc_session_state_extras/should_add_byok_provider_and_model_at_runtime.yaml @@ -0,0 +1,3 @@ +models: + - claude-sonnet-4.5 +conversations: [] diff --git a/test/snapshots/rpc_session_state_extras/should_get_context_attribution_and_heaviest_messages_after_turn.yaml b/test/snapshots/rpc_session_state_extras/should_get_context_attribution_and_heaviest_messages_after_turn.yaml new file mode 100644 index 0000000000..c4798dc83d --- /dev/null +++ b/test/snapshots/rpc_session_state_extras/should_get_context_attribution_and_heaviest_messages_after_turn.yaml @@ -0,0 +1,10 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: Say CONTEXT_METADATA_OK exactly. + - role: assistant + content: CONTEXT_METADATA_OK diff --git a/test/snapshots/rpc_session_state_extras/should_report_visibility_as_unsynced_for_local_session.yaml b/test/snapshots/rpc_session_state_extras/should_report_visibility_as_unsynced_for_local_session.yaml new file mode 100644 index 0000000000..056351ddb4 --- /dev/null +++ b/test/snapshots/rpc_session_state_extras/should_report_visibility_as_unsynced_for_local_session.yaml @@ -0,0 +1,3 @@ +models: + - claude-sonnet-4.5 +conversations: [] diff --git a/test/snapshots/rpc_session_state_extras/should_return_empty_completions_when_host_does_not_provide_them.yaml b/test/snapshots/rpc_session_state_extras/should_return_empty_completions_when_host_does_not_provide_them.yaml new file mode 100644 index 0000000000..056351ddb4 --- /dev/null +++ b/test/snapshots/rpc_session_state_extras/should_return_empty_completions_when_host_does_not_provide_them.yaml @@ -0,0 +1,3 @@ +models: + - claude-sonnet-4.5 +conversations: [] diff --git a/test/snapshots/rpc_session_state_extras/should_update_and_clear_live_subagent_settings.yaml b/test/snapshots/rpc_session_state_extras/should_update_and_clear_live_subagent_settings.yaml new file mode 100644 index 0000000000..056351ddb4 --- /dev/null +++ b/test/snapshots/rpc_session_state_extras/should_update_and_clear_live_subagent_settings.yaml @@ -0,0 +1,3 @@ +models: + - claude-sonnet-4.5 +conversations: [] diff --git a/test/snapshots/session/resumes_a_persisted_session_from_a_new_client_when_an_mcp_oauth_handler_is_configured.yaml b/test/snapshots/session/resumes_a_persisted_session_from_a_new_client_when_an_mcp_oauth_handler_is_configured.yaml new file mode 100644 index 0000000000..250402101b --- /dev/null +++ b/test/snapshots/session/resumes_a_persisted_session_from_a_new_client_when_an_mcp_oauth_handler_is_configured.yaml @@ -0,0 +1,10 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: What is 1+1? + - role: assistant + content: 1 + 1 = 2 diff --git a/test/snapshots/session_config/should_apply_excluded_built_in_agents_on_create.yaml b/test/snapshots/session_config/should_apply_excluded_built_in_agents_on_create.yaml new file mode 100644 index 0000000000..3cbf86e981 --- /dev/null +++ b/test/snapshots/session_config/should_apply_excluded_built_in_agents_on_create.yaml @@ -0,0 +1,17 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: What is 1+1? + - role: assistant + content: 1 + 1 = 2 + - messages: + - role: system + content: ${system} + - role: user + content: What is 1+1? + - role: assistant + content: 1 + 1 = 2 diff --git a/test/snapshots/session_config/should_apply_excluded_built_in_agents_on_resume.yaml b/test/snapshots/session_config/should_apply_excluded_built_in_agents_on_resume.yaml new file mode 100644 index 0000000000..250402101b --- /dev/null +++ b/test/snapshots/session_config/should_apply_excluded_built_in_agents_on_resume.yaml @@ -0,0 +1,10 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: What is 1+1? + - role: assistant + content: 1 + 1 = 2 diff --git a/test/snapshots/session_config/should_apply_session_limits_on_create.yaml b/test/snapshots/session_config/should_apply_session_limits_on_create.yaml new file mode 100644 index 0000000000..904d69c872 --- /dev/null +++ b/test/snapshots/session_config/should_apply_session_limits_on_create.yaml @@ -0,0 +1,18 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: Acknowledge the current session limits. + - role: user + content: >- + + + Remaining session limits: 30 AI credits. Later session_limits_status messages supersede earlier ones. Be + frugal; avoid optional exploration and unnecessary tool calls. + + + - role: assistant + content: Session limits acknowledged. diff --git a/test/snapshots/session_config/should_apply_session_limits_on_resume.yaml b/test/snapshots/session_config/should_apply_session_limits_on_resume.yaml new file mode 100644 index 0000000000..904d69c872 --- /dev/null +++ b/test/snapshots/session_config/should_apply_session_limits_on_resume.yaml @@ -0,0 +1,18 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: Acknowledge the current session limits. + - role: user + content: >- + + + Remaining session limits: 30 AI credits. Later session_limits_status messages supersede earlier ones. Be + frugal; avoid optional exploration and unnecessary tool calls. + + + - role: assistant + content: Session limits acknowledged. diff --git a/test/snapshots/tools/ergonomic_tool_arity0.yaml b/test/snapshots/tools/ergonomic_tool_arity0.yaml new file mode 100644 index 0000000000..a55f486816 --- /dev/null +++ b/test/snapshots/tools/ergonomic_tool_arity0.yaml @@ -0,0 +1,21 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: Call get_status and tell me the result. + - role: assistant + content: I'll call get_status now. + tool_calls: + - id: toolcall_0 + type: function + function: + name: get_status + arguments: '{}' + - role: tool + tool_call_id: toolcall_0 + content: "Status: OK" + - role: assistant + content: "The status is: OK" diff --git a/test/snapshots/tools/ergonomic_tool_arity2.yaml b/test/snapshots/tools/ergonomic_tool_arity2.yaml new file mode 100644 index 0000000000..e34c695bd4 --- /dev/null +++ b/test/snapshots/tools/ergonomic_tool_arity2.yaml @@ -0,0 +1,21 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: Call combine_values with 'alpha' and 'beta', then report the combined result. + - role: assistant + content: I'll call combine_values with those arguments. + tool_calls: + - id: toolcall_0 + type: function + function: + name: combine_values + arguments: '{"value1":"alpha","value2":"beta"}' + - role: tool + tool_call_id: toolcall_0 + content: "combined: alpha + beta" + - role: assistant + content: "The combined result is: alpha + beta" diff --git a/test/snapshots/tools/ergonomic_tool_definition.yaml b/test/snapshots/tools/ergonomic_tool_definition.yaml new file mode 100644 index 0000000000..ebb05ce1b9 --- /dev/null +++ b/test/snapshots/tools/ergonomic_tool_definition.yaml @@ -0,0 +1,33 @@ +models: + - claude-sonnet-4.5 +conversations: + - messages: + - role: system + content: ${system} + - role: user + content: + First, set the current phase to 'analyzing'. Then search for items with keyword 'copilot'. Report the phase and + search results. + - role: assistant + content: I'll set the phase and run the search now. + tool_calls: + - id: toolcall_0 + type: function + function: + name: set_current_phase + arguments: '{"phase":"analyzing"}' + - id: toolcall_1 + type: function + function: + name: search_items + arguments: '{"keyword":"copilot"}' + - role: tool + tool_call_id: toolcall_0 + content: Phase set to analyzing + - role: tool + tool_call_id: toolcall_1 + content: "Found: copilot -> item_alpha, item_beta" + - role: assistant + content: |- + Current phase: analyzing + Search results: item_alpha, item_beta