AGENTS.md
extensions/copilot/src/extension/chatSessions/copilotcli/AGENTS.mdAGENTS.md
Quality
85/100
Scores the file, not the repository.Length
2,161 words
35 headings · 3 code blocksRepository
188k
— · pushed 0 days agoLast changed
3 days ago
First indexed 3 days ago.1# Copilot CLI Integration23This folder contains the Copilot CLI integration for VS Code Chat. It enables users to open a new Chat window and interact with a Copilot CLI agent instance directly within VS Code. **VS Code provides the UI, Copilot CLI SDK provides the smarts.**45> **Important:** The Copilot CLI agent functionality is powered by the `@github/copilot/sdk` package. See the SDK package for full type definitions.67## Architecture89```10┌─────────────────────────────────────────────────────────────────┐11│ VS Code Chat UI │12└─────────────────────────┬───────────────────────────────────────┘13 │14 ▼15┌─────────────────────────────────────────────────────────────────┐16│ CopilotCLISessionService │17│ (node/copilotcliSessionService.ts) │18│ - Manages SDK LocalSessionManager lifecycle │19│ - Creates, retrieves, and caches CopilotCLISession instances │20│ - Handles session persistence, discovery, and forking │21│ - Monitors session files on disk for external changes │22│ - Installs OTel bridge span processor for debug panel │23└─────────────────────────┬───────────────────────────────────────┘24 │25 ▼26┌─────────────────────────────────────────────────────────────────┐27│ CopilotCLISession │28│ (node/copilotcliSession.ts) │29│ - Wraps a single SDK Session for one conversation │30│ - Processes SDK events (messages, tools, permissions, errors) │31│ - Handles tool confirmation and permission requests │32│ - Supports steering (injecting messages into running sessions) │33│ - Manages model switching and reasoning effort │34│ - Tracks OTel spans for observability │35└─────────────────────────┬───────────────────────────────────────┘36 │37 ▼38┌─────────────────────────────────────────────────────────────────┐39│ Copilot CLI SDK (@github/copilot/sdk) │40│ - Manages the agentic conversation loop │41│ - Executes tools and reports results via events │42│ - Handles permissions (read, write, shell, MCP) │43│ - Provides session persistence as events.jsonl files │44│ - Supports fleet mode and plan mode │45└─────────────────────────────────────────────────────────────────┘46 │47 ▼48┌─────────────────────────────────────────────────────────────────┐49│ MCP Server (In-Process) │50│ (vscode-node/contribution.ts, vscode-node/inProcHttpServer.ts) │51│ - Provides VS Code-specific tools to the SDK via MCP protocol │52│ - Runs as an in-process HTTP server (InProcHttpServer) │53│ - Exposes diff, diagnostics, selection, and session tools │54│ - Discoverable by CLI via lock files in ~/.copilot/ide/ │55└─────────────────────────────────────────────────────────────────┘56```5758## Folder Structure5960The integration follows VS Code's platform layering pattern with three layers:6162```63copilotcli/64├── common/ # Platform-agnostic (NO Node.js or VS Code API imports)65│ ├── copilotCLITools.ts # Tool type definitions and processing helpers66│ ├── copilotCLIPrompt.ts # Prompt reference extraction and parsing67│ ├── customSessionTitleService.ts68│ ├── delegationSummaryService.ts69│ ├── utils.ts # SessionIdForCLI namespace (URI scheme: 'copilotcli')70│ └── test/71│72├── node/ # Node.js-specific (SDK integration, filesystem, permissions)73│ ├── copilotCli.ts # ICopilotCLISDK, CopilotCLIModels, CopilotCLIAgents74│ ├── copilotcliSession.ts # CopilotCLISession — main session wrapper75│ ├── copilotcliSessionService.ts # Session lifecycle management76│ ├── permissionHelpers.ts # Permission request handlers77│ ├── copilotcliPromptResolver.ts # Resolves prompts with variables and attachments78│ ├── copilotCLISkills.ts # Skills location resolution79│ ├── copilotCLIImageSupport.ts # Image attachment handling80│ ├── mcpHandler.ts # MCP server configuration for SDK sessions81│ ├── nodePtyShim.ts # Runtime node-pty copy for separate extension installs82│ ├── userInputHelpers.ts # User question/input handling interface83│ ├── exitPlanModeHandler.ts # Plan mode exit flow with user choice84│ ├── ripgrepShim.ts # Copies VS Code's ripgrep for SDK use85│ └── test/86│87└── vscode-node/ # VS Code API-dependent (commands, MCP tools, UI)88 ├── copilotCLIFolderMru.ts # Folder MRU (most-recently-used) service89 └── test/90```9192## Layering Rules9394Strict import dependency rules — violations will cause build failures:9596| Layer | Can import from | Cannot import from |97|-------|----------------|--------------------|98| `common/` | `src/util/common/`, `src/platform/`, sibling `../common/` | `node/`, `vscode-node/`, `vscode` module |99| `node/` | `common/`, `src/util/`, `src/platform/`, Node.js builtins | `vscode-node/`, `vscode` module |100| `vscode-node/` | `common/`, `node/`, `src/util/`, `src/platform/`, `vscode` module | (top layer — no restrictions) |101102103## Key Components104### `node/copilotCli.ts`105106**ICopilotCLISDK / CopilotCLISDK**107- Service interface wrapping the dynamic `import('@github/copilot/sdk')` for dependency injection and testability108109**ICopilotCLIModels / CopilotCLIModels**110- Fetches and caches available AI models from the SDK via `getAvailableModels()`111- Registers a `LanguageModelChatProvider` with `targetChatSessionType: 'copilotcli'` so VS Code's model picker shows CLI models112- Exposes model capabilities: vision support, reasoning effort levels, token limits, billing multiplier113- Rebuilds model list on authentication changes114- Builds configuration schema for reasoning effort per model (low/medium/high/xhigh)115116**ICopilotCLIAgents / CopilotCLIAgents**117- Discovers custom agents118119### `node/copilotcliSession.ts`120121**CopilotCLISession**122- Wraps a single `Session` object from the `@github/copilot/sdk`123- Entry point for every chat request via `handleRequest()`124- Listens to SDK events and translates them to VS Code chat UI parts125- Manages permission flow126- Tracks external edits via `ExternalEditTracker` for proper diff display127- Supports CLI commands: `compact`, `plan`, `fleet`128- Built-in slash commands: `/commit`, `/sync`, `/merge`, `/create-pr`, `/create-draft-pr`, `/update-pr`129- Captures pull request URLs from `create_pull_request` tool results130131### `node/copilotcliSessionService.ts`132133**ICopilotCLISessionService / CopilotCLISessionService**134- Central service managing the lifecycle of all Copilot CLI sessions135136### `common/copilotCLITools.ts`137138Defines all tool type interfaces used by the Copilot CLI agent:139140* File Operations141* Shell Operations142* Search Operations143* Agent & Task Operations144* User Interaction145* Code Review & Git146* Data, Memory & MCP147* Security148149150### `common/copilotCLIPrompt.ts`151152Parses raw user prompts and extracts structured chat prompt references (files, locations, diagnostics)153154### `node/copilotcliPromptResolver.ts`155156**CopilotCLIPromptResolver**157- Resolves chat request prompts by processing variable references and building attachments158- Extracts prompt variables from `ChatVariablesCollection` (files, locations, diagnostics, custom instructions)159- Converts image attachments160- Generates the final user prompt161- Handles workspace folder path translation for multi-folder isolation162163### `node/permissionHelpers.ts`164165Handles permission requests from the SDK. Each permission kind has a dedicated handler:166167* handleReadPermission168* handleWritePermission169* handleShellPermission170* handleMcpPermission171* showInteractivePermissionPrompt172173### `node/mcpHandler.ts`174175**ICopilotCLIMCPHandler / CopilotCLIMCPHandler**176- Loads MCP server configuration for SDK sessions177- Proxies all VS Code-configured MCP servers through a gateway URL with `type: 'http'` config per server178179### `node/copilotCLIImageSupport.ts`180181**ICopilotCLIImageSupport / CopilotCLIImageSupport**182- Stores image data as files in extension global storage (`copilot-cli-images/`)183- Tracks trusted image URIs to auto-approve read permissions184- Supports PNG, JPEG, GIF, WebP, and BMP formats via `isImageMimeType()`185186### `node/exitPlanModeHandler.ts`187188**`handleExitPlanMode()`**189- Presents exit options when the SDK finishes plan generation: Autopilot, Interactive, Exit Only, Autopilot Fleet190- Syncs saved plan changes back to the SDK session191192### `node/cliHelpers.ts`193194Path helpers for Copilot CLI directories.195196## Message Flow1971981. **User sends message** in VS Code Chat1992. **CopilotCLISessionService** creates or retrieves an existing session wrapper2003. **CopilotCLISession.handleRequest()** is called:201 - If session is idle → normal request via `send()`202 - If session is busy → steering request via `send({ mode: 'immediate' })`2034. **SDK Session** processes the request and emits events:204 - `assistant.message_delta` → streamed markdown to chat UI205 - `tool.execution_start` / `tool.execution_complete` → tool invocation UI parts206 - `permission.requested` → routed to permission handler (auto-approve or interactive)207 - `user_input.requested` → question carousel shown to user208 - `exit_plan_mode.requested` → plan mode exit choices209 - `session.title_changed` → session title updated210 - `subagent.started/completed/failed` → subagent metadata enriches tool invocations211 - `hook.start/end` → forwarded to OTel bridge for debug panel2125. **Session completes** — status set to `Completed`, usage reported213214## Permission System215216The SDK emits `permission.requested` events with a `kind` field.217218When `autopilot` / `autoApprove` permission level is set, all permissions are auto-approved without user interaction.219220Tool invocation messages are intentionally held in a queue (`toolCallWaitingForPermissions`) until the permission resolves, preventing a flash of "Running..." immediately followed by "Permission requested...".221222## Session Persistence223224Copilot CLI sessions are persisted to `~/.copilot/session-state/<sessionId>/` directories containing:225- `events.jsonl` — Ordered event stream (messages, tool calls, results)226- `workspace.yaml` — Workspace configuration227228### `IWorkspaceInfo` (`../common/workspaceInfo.ts`)229230Central type representing all workspace/repository/worktree state for a session:231232### `IChatSessionMetadataStore` (`../common/chatSessionMetadataStore.ts`)233234Persists VS Code-specific metadata that sits alongside the SDK's own session data. This metadata is **not part of the SDK's `events.jsonl`** — it tracks VS Code concepts like worktree properties, request-to-tool mappings, mode instructions, and checkpoint refs.235236**Key Types:**237238**`ChatSessionMetadataFile`** — The full metadata shape per session:239240**`RequestDetails`** — Per-request metadata:241242**`RepositoryProperties`** — Git repository metadata:243244### `IChatSessionWorktreeService` (`../common/chatSessionWorktreeService.ts`)245246Manages Git worktree lifecycle for session isolation. When isolation is enabled, each session gets its own Git worktree so the agent can make changes without affecting the user's working copy.247248### `IChatSessionWorktreeCheckpointService` (`../common/chatSessionWorktreeCheckpointService.ts`)249250Creates Git checkpoints (lightweight commits or refs) at the start and end of each request turn. These checkpoints enable the **undo/revert** feature — users can roll back to any previous turn's state.251252### `IChatSessionWorkspaceFolderService` (`../common/chatSessionWorkspaceFolderService.ts`)253254Handles workspace folder tracking for sessions **without** Git worktree isolation — i.e., when the agent works directly in the user's workspace. Used in multi-root workspaces where some folders may not have Git repositories.255256### `IFolderRepositoryManager` (`../common/folderRepositoryManager.ts`)257258Orchestrates the full folder/repository initialization flow for a session. This is the high-level coordinator that brings together worktree creation, trust verification, uncommitted change handling, and folder tracking.259260### `ISessionRequestLifecycle` (`../vscode-node/sessionRequestLifecycle.ts`)261262Orchestrates the start and end of each chat request turn, coordinating worktree commits, checkpoint creation, PR detection, and metadata updates. Handles the complexity of **steering** — where multiple requests can be in-flight for the same session simultaneously.263264## Architecture Diagram: Shared Services265266```267┌──────────────────────────────────────────────────────────────────────┐268│ SessionRequestLifecycle │269│ Orchestrates start/end of each request turn │270│ Handles steering (multiple concurrent requests per session) │271└──────┬──────────┬──────────────┬─────────────┬──────────────────────┘272 │ │ │ │273 ▼ ▼ ▼ ▼274┌────────────┐ ┌───────────┐ ┌─────────────┐ ┌──────────────────────┐275│ Worktree │ │ Workspace │ │ Checkpoint │ │ MetadataStore │276│ Service │ │ Folder │ │ Service │ │ │277│ │ │ Service │ │ │ │ - Request details │278│ - Create │ │ │ │ - Baseline │ │ - Worktree props │279│ - Commit │ │ - Track │ │ checkpts │ │ - Workspace folder │280│ - Cleanup │ │ - Stage │ │ - Post-turn │ │ - Repo properties │281│ - Archive │ │ - Changes │ │ checkpts │ │ - Mode instructions │282│ - Unarchive│ │ - Clear │ │ - Multi-root│ │ - Checkpoint refs │283└────────────┘ └───────────┘ └─────────────┘ └──────────────────────┘284 │ │ │ │285 └──────────┴──────────────┴─────────────┘286 │287 ▼288 ┌──────────────────────┐289 │ FolderRepositoryMgr │290 │ │291 │ - Init flow │292 │ - Trust verification │293 │ - Multi-root batch │294 │ - MRU tracking │295 │ - Isolation mode │296 └──────────────────────┘297```298299300## How to Add New Features301302### Adding a new permission handler3033041. Add `handle<Kind>Permission()` in `node/permissionHelpers.ts` following the existing pattern3052. Add a `case '<kind>':` in the permission switch in `node/copilotcliSession.ts` (~line 468)3063. Handler should return a `PermissionRequestResult` with `kind: 'approved' | 'denied-interactively-by-user' | ...`307308### Handling a new SDK event3093101. Add a listener in `node/copilotcliSession.ts` using `this._sdkSession.on(eventName, handler)`3112. Wrap with `toDisposable()` and add to the `DisposableStore` for proper cleanup3123. Use `this._stream?.markdown()` / `this._stream?.push()` to output to the chat UI313314## Critical Pitfalls315316- **Shims before SDK import**: For separate Marketplace/VSIX extension installs, `CopilotCLISDK.ensureShims()` in `node/copilotCli.ts` MUST run before any `import('@github/copilot/sdk')`. That runtime path calls both `ensureRipgrepShim()` and `ensureNodePtyShim()` to copy VS Code's native binaries from `envService.appRoot` into the installed extension's SDK layout.317318- **Bundled/core shim path is different**: When Copilot Chat is bundled together with core VS Code, build-time packaging materializes only the ripgrep shim and writes `node_modules/@github/copilot/shims.txt`. That marker intentionally makes runtime `ensureShims()` return early, so node-pty is not copied in the bundled path; it is resolved from VS Code's own app tree instead.319320- **Delayed permission UI**: Tool invocation messages are held in `toolCallWaitingForPermissions` until permission resolves. `flushPendingInvocationMessageForToolCallId()` flushes only the specific approved tool, not all pending tools. This is intentional — don't bypass it.321322- **Steering mode**: When a session is already busy (`InProgress` or `NeedsInput`), use `send({ mode: 'immediate' })` to inject messages into the running conversation instead of starting a new request.323324## Commands & Slash Commands325326**Copilot CLI commands** (user-facing, sent programmatically):327- `compact` — compress conversation history to reduce tokens328- `plan` — enter plan mode (SDK generates plan before executing)329- `fleet` — start fleet mode for multi-agent parallel execution330331**Built-in custom slash commands** (user-facing):332`/commit`, `/sync`, `/merge`, `/create-pr`, `/create-draft-pr`, `/update-pr`333334**VS Code Session commands** (registered via `registerCLIChatCommands` in `vscode-node/copilotCLIChatSessions.ts`):335336## Configuration337338The integration respects these VS Code settings (all under `github.copilot.chat.cli.*`):339340| Setting | Default | Description |341|---------|---------|-------------|342| `mcp.enabled` | `true` | Enable MCP server proxying for CLI sessions |343| `branchSupport.enabled` | `false` | Enable Git branch support features |344| `showExternalSessions` | `false` | Show sessions created outside VS Code (e.g., terminal CLI) |345| `planExitMode.enabled` | `true` | Show plan exit mode choices (Autopilot/Interactive/Exit) |346| `planCommand.enabled` | `true` | Enable the `/plan` command |347| `aiGenerateBranchNames.enabled` | `true` | AI-generated branch names for worktrees |348| `forkSessions.enabled` | `true` | Allow forking sessions into new conversations |349| `isolationOption.enabled` | `true` | Show worktree isolation option in session UI |350| `autoCommit.enabled` | `true` | Auto-commit worktree changes at end of each turn |351| `sessionController.enabled` | `false` | Use session controller API (V2) |352| `thinkingEffort.enabled` | `true` | Show thinking effort control per model |353| `sessionControllerForSessionsApp.enabled` | `false` | Use session controller for Sessions window |354| `terminalLinks.enabled` | `true` | Enable terminal link detection |355356## Dependencies357358- `@github/copilot/sdk`: Official Copilot CLI SDK (session management, tools, permissions, events)359360## Deprecated Code361362V1 registration in `../vscode-node/copilotCLIChatSessionsContribution.ts` and `registerCopilotCLIServicesV1` are deprecated. All new development should use `CopilotCLISessionService` and the controller-based V2 API.363
Also in microsoft/vscode
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| microsoft/vscode.github/instructions/accessibility.instructions.md · 188k | Copilot instructions | styledo-not | 61/100 | 3 days ago | |
| microsoft/vscode.github/instructions/chat.instructions.md · 188k | Copilot instructions | no sections | 39/100 | 3 days ago | |
| microsoft/vscodeextensions/copilot/src/platform/authentication/common/AGENTS.md · 188k | AGENTS.md | archsecurityagent-behaviour | 58/100 | 3 days ago | |
| microsoft/vscode.github/copilot-instructions.md · 188k | Copilot instructions | stylearchtypesui+2 | 74/100 | 2 days ago | |
| microsoft/vscode.github/instructions/agentHostTesting.instructions.md · 188k | Copilot instructions | teststyletesting-strategyagent-behaviour | 55/100 | 3 days ago | |
| microsoft/vscode.github/instructions/ai-customization.instructions.md · 188k | Copilot instructions | archtypesui | 58/100 | 3 days ago | |
| microsoft/vscode.github/instructions/best-practices.instructions.md · 188k | Copilot instructions | styleui | 60/100 | 3 days ago | |
| microsoft/vscode.github/instructions/buildNext.instructions.md · 188k | Copilot instructions | setupbuildtestarch+1 | 66/100 | 3 days ago | |
| microsoft/vscode.github/instructions/coding-guidelines.instructions.md · 188k | Copilot instructions | styletypesuidocs | 60/100 | 3 days ago | |
| microsoft/vscode.github/instructions/committing.instructions.md · 188k | Copilot instructions | do-not | 23/100 | 3 days ago | |
| microsoft/vscode.github/instructions/css-best-practices.instructions.md · 188k | Copilot instructions | styleui | 29/100 | 3 days ago | |
| microsoft/vscode.github/instructions/design-philosophy.instructions.md · 188k | Copilot instructions | style | 34/100 | 3 days ago | |
| microsoft/vscode.github/instructions/design-tokens.instructions.md · 188k | Copilot instructions | styledo-not | 65/100 | 3 days ago | |
| microsoft/vscode.github/instructions/disposable.instructions.md · 188k | Copilot instructions | no sections | 16/100 | 3 days ago | |
| microsoft/vscode.github/instructions/interactive.instructions.md · 188k | Copilot instructions | ui | 43/100 | 3 days ago | |
| microsoft/vscode.github/instructions/kusto.instructions.md · 188k | Copilot instructions | agent-behaviour | 16/100 | 3 days ago | |
| microsoft/vscode.github/instructions/learnings.instructions.md · 188k | Copilot instructions | style | 40/100 | 3 days ago | |
| microsoft/vscode.github/instructions/notebook.instructions.md · 188k | Copilot instructions | no sections | 48/100 | 3 days ago | |
| microsoft/vscode.github/instructions/observables.instructions.md · 188k | Copilot instructions | no sections | 40/100 | 3 days ago | |
| microsoft/vscode.github/instructions/oss-third-party-notices.instructions.md · 188k | Copilot instructions | buildgitdependenciesdeployment+1 | 65/100 | 3 days ago |
Diff against .github/instructions/accessibility.instructions.md Diff against .github/instructions/chat.instructions.md Diff against extensions/copilot/src/platform/authentication/common/AGENTS.md Diff against .github/copilot-instructions.md Diff against .github/instructions/agentHostTesting.instructions.md Diff against .github/instructions/ai-customization.instructions.md Diff against .github/instructions/best-practices.instructions.md Diff against .github/instructions/buildNext.instructions.md Diff against .github/instructions/coding-guidelines.instructions.md Diff against .github/instructions/committing.instructions.md Diff against .github/instructions/css-best-practices.instructions.md Diff against .github/instructions/design-philosophy.instructions.md Diff against .github/instructions/design-tokens.instructions.md Diff against .github/instructions/disposable.instructions.md Diff against .github/instructions/interactive.instructions.md Diff against .github/instructions/kusto.instructions.md Diff against .github/instructions/learnings.instructions.md Diff against .github/instructions/notebook.instructions.md Diff against .github/instructions/observables.instructions.md Diff against .github/instructions/oss-third-party-notices.instructions.md
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| n8n-io/n8npackages/@n8n/agents/AGENTS.md · 199k | AGENTS.md | buildteststylearch+3 | 100/100 | 3 days ago | |
| aaif-goose/gooseAGENTS.md · 52k | AGENTS.md | setupbuildtestlint-format+6 | 100/100 | 3 days ago | |
| wpscanteam/wpscanAGENTS.md · 9.7k | AGENTS.md | setupbuildteststyle+6 | 100/100 | 2 days ago | |
| mui/material-uiAGENTS.md · 99k | AGENTS.md | setupbuildtestlint-format+9 | 100/100 | 3 days ago | |
| SkeneTechnologies/skene-cookbookAGENTS.md · 51 | AGENTS.md | setupbuildtestlint-format+7 | 100/100 | 2 days ago | |
| duckduckgo/content-scope-scriptsspecial-pages/AGENTS.md · 70 | AGENTS.md | buildteststylearch+3 | 100/100 | 3 days ago | |
| trick77/agents-md-syncAGENTS.md · 2 | AGENTS.md | setupbuildteststyle+5 | 100/100 | 3 days ago | |
| TryGhost/Ghoste2e/AGENTS.md · 55k | AGENTS.md | setupteststylearch+2 | 100/100 | 3 days ago |
