Skip to content

agent host: eagerly create sessions when a folder is picked - #313841

Merged
Connor Peet (connor4312) merged 3 commits into
mainfrom
connor4312/eager-create-session
May 2, 2026
Merged

Connor Peet (connor4312) merged 3 commits into
mainfrom
connor4312/eager-create-session

Conversation

@connor4312

Copy link
Copy Markdown
Member

Previously the agent-host backend session was only created when the user sent their first message. Move creation up to folder-pick time so the new-chat view interacts with a real session URI throughout: model selections, session-config picks, etc. all dispatch against a known session, and the chat handler avoids a duplicate createSession round-trip on the user's first send.

This is particularly in advance of support for completions, which necessarily are derived in the context of a workspace, agent customizations, etc. While the work for these new 'provisional sessions' is trending towards gnarly internally, the protocol is kept pretty clean with the only change being semantic guidance that sessions with no messages should be garbage collected.

To make eager creation cheap, sessions are ephemeral in the agent until the first message lands — no SDK session, no worktree, no on-disk metadata. Materialization happens inside sendMessage and fires onDidMaterializeSession, at which point the agent service emits the deferred notify/sessionAdded and transitions lifecycle to Ready.

Switching workspaces or closing the new-chat view disposes the provisional record (disposeSession over the wire); a 30s server-side empty-session GC backstops crashes and dropped disconnects.

The new-session bookkeeping in the sessions provider previously lived across 11 loose _currentNewSession* fields and 4 keyed-by-sessionId maps. Bundle them into a single NewSession class held as a MutableDisposable — assigning a new value automatically tears down the previous one (subscription release + disposeSession RPC).

Subtle wire-ordering note: NewSession.eagerCreate awaits createSession before opening the state subscription. Reversing the order races the wire — the server sees subscribe for an unknown session, returns AHP_SESSION_NOT_FOUND, and the client subscription enters an unrecoverable error state. New unit tests pin the ordering and the bail-out behaviour for workspace-switch-mid-flight.


Architecture (provisional → real session):

sequenceDiagram
    participant U as User
    participant SP as SessionsProvider
    participant H as ChatHandler
    participant A as Agent (CopilotAgent)
    participant S as StateManager

    U->>SP: pick folder
    SP->>A: createSession(uri)
    A->>S: createSession(emitNotification=false)
    Note over A: provisional record<br/>(no SDK, no worktree, no DB)
    SP-->>U: session.resource

    U->>SP: pick model / config (optional)
    SP->>A: SessionModelChanged / SessionConfigChanged
    Note over A: updates provisional record

    U->>H: send first message
    H->>A: sendMessage()
    A->>A: _materializeProvisional<br/>(create worktree,<br/> SDK session, persist DB)
    A->>S: onDidMaterializeSession
    S-->>U: notify/sessionAdded
    S->>S: SessionReady

    U-)SP: switch workspace
    SP->>A: disposeSession (old uri)
    Note over A: drops provisional record<br/>cancels worktree creation
Loading

Previously the agent-host backend session was only created when the user
sent their first message. Move creation up to folder-pick time so the
new-chat view interacts with a real session URI throughout: model
selections, session-config picks, etc. all dispatch against a known
session, and the chat handler avoids a duplicate createSession round-trip
on the user's first send.

This is particularly in advance of support for completions, which necessarily
are derived in the context of a workspace, agent customizations, etc. While
the work for these new 'provisional sessions' is trending towards gnarly
internally, the protocol is kept pretty clean with the only change being
semantic guidance that sessions with no messages should be garbage collected.

To make eager creation cheap, sessions are ephemeral in the agent
until the first message lands — no SDK session, no worktree, no on-disk
metadata. Materialization happens inside `sendMessage` and fires
`onDidMaterializeSession`, at which point the agent service emits the
deferred `notify/sessionAdded` and transitions lifecycle to `Ready`.

Switching workspaces or closing the new-chat view disposes the
provisional record (`disposeSession` over the wire); a 30s server-side
empty-session GC backstops crashes and dropped disconnects.

The new-session bookkeeping in the sessions provider previously lived
across 11 loose `_currentNewSession*` fields and 4 keyed-by-sessionId
maps. Bundle them into a single `NewSession` class held as a
`MutableDisposable` — assigning a new value automatically tears down
the previous one (subscription release + disposeSession RPC).

Subtle wire-ordering note: `NewSession.eagerCreate` awaits
`createSession` *before* opening the state subscription. Reversing the
order races the wire — the server sees `subscribe` for an unknown
session, returns `AHP_SESSION_NOT_FOUND`, and the client subscription
enters an unrecoverable error state. New unit tests pin the ordering
and the bail-out behaviour for workspace-switch-mid-flight.

---

Architecture (provisional → real session):

```mermaid
sequenceDiagram
    participant U as User
    participant SP as SessionsProvider
    participant H as ChatHandler
    participant A as Agent (CopilotAgent)
    participant S as StateManager

    U->>SP: pick folder
    SP->>A: createSession(uri)
    A->>S: createSession(emitNotification=false)
    Note over A: provisional record<br/>(no SDK, no worktree, no DB)
    SP-->>U: session.resource

    U->>SP: pick model / config (optional)
    SP->>A: SessionModelChanged / SessionConfigChanged
    Note over A: updates provisional record

    U->>H: send first message
    H->>A: sendMessage()
    A->>A: _materializeProvisional<br/>(create worktree,<br/> SDK session, persist DB)
    A->>S: onDidMaterializeSession
    S-->>U: notify/sessionAdded
    S->>S: SessionReady

    U-)SP: switch workspace
    SP->>A: disposeSession (old uri)
    Note over A: drops provisional record<br/>cancels worktree creation
```
Copilot AI review requested due to automatic review settings May 2, 2026 02:21
@github-actions

github-actions Bot commented May 2, 2026 •

Copy link
Copy Markdown
Contributor

blocks-ci screenshots changed

Replace the contents of test/componentFixtures/blocks-ci-screenshots.md with:

Updated blocks-ci-screenshots.md
<!-- auto-generated by CI — do not edit manually -->

#### editor/codeEditor/CodeEditor/Dark
![screenshot](https://hediet-screenshots.azurewebsites.net/images/cb32a3e854b5734fe5aaca2318f2e0a42ee821b05ea97883ea42c5ba95edb3c3)

#### editor/codeEditor/CodeEditor/Light
![screenshot](https://hediet-screenshots.azurewebsites.net/images/42624fbba5e0db7f32c224b5eb9c5dd3b08245697ae2e7d2a88be0d7c287129b)

#### editor/inlineChatZoneWidget/InlineChatZoneWidget/Dark
![screenshot](https://hediet-screenshots.azurewebsites.net/images/28af1b719f3877d2f048fef10bb4534d5f638c1987bb0536331f4ab50ea0ea7a)

#### editor/inlineChatZoneWidget/InlineChatZoneWidget/Light
![screenshot](https://hediet-screenshots.azurewebsites.net/images/c6c77ca2785665ae66c817cda21a8e5f5ea7d51e798c5b4e5aedcda9fd7323bd)

#### editor/inlineChatZoneWidget/InlineChatZoneWidgetTerminated/Dark
![screenshot](https://hediet-screenshots.azurewebsites.net/images/2fbc12507b59ff950d9612d2df92e6b39d8bf0bf500478e42eca2ead4d1ae206)

#### editor/inlineChatZoneWidget/InlineChatZoneWidgetTerminated/Light
![screenshot](https://hediet-screenshots.azurewebsites.net/images/4632ab04d1fdd7db9ab0e00cce10aefb7a6344eb8869dfce740309a8801cab73)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR moves agent-host session creation earlier (folder-pick time) by introducing “provisional sessions” that exist in protocol state immediately, but only materialize SDK/worktree/on-disk metadata on first sendMessage. This lets the new-chat UI operate against a stable session URI for model/config selections and avoids a first-message createSession round-trip.

Changes:

  • Add eager backend createSession on new-session creation and refactor new-session bookkeeping into a single NewSession (MutableDisposable) in the sessions providers.
  • Introduce provisional sessions in the agent host: defer SDK/worktree/DB work until first message, and add empty-session GC (30s) for unsubscribed empty sessions.
  • Extend reconnect replay results to include missing subscriptions and add tests covering ordering/races around eager session creation.
Show a summary per file
File Description
src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts Uses existing eagerly-created session state to avoid redundant create+subscribe on first message and pushes initial config/active-client state.
src/vs/sessions/contrib/remoteAgentHost/test/browser/remoteAgentHostSessionsProvider.test.ts Updates mocks to track eager createSession calls for remote provider tests.
src/vs/sessions/contrib/remoteAgentHost/browser/remoteAgentHostSessionsProvider.ts Plumbs ILogService into base provider and simplifies new-session teardown via MutableDisposable.
src/vs/sessions/contrib/agentHost/test/browser/localAgentHostSessionsProvider.test.ts Adds tests for eager create ordering, failure paths, and workspace-switch races; stubs ILogService.
src/vs/sessions/contrib/agentHost/browser/localAgentHostSessionsProvider.ts Plumbs ILogService into base provider.
src/vs/sessions/contrib/agentHost/browser/baseAgentHostSessionsProvider.ts Introduces NewSession class, eager backend session creation, and consolidates prior scattered new-session fields/maps.
src/vs/platform/agentHost/test/node/copilotAgent.test.ts Updates expectations for provisional createSession behavior and adds provisional-session unit tests.
src/vs/platform/agentHost/test/node/agentService.test.ts Updates eviction expectations and adds empty-session GC test coverage using fake timers.
src/vs/platform/agentHost/node/protocolServerHandler.ts Adds reconnect replay missing list for subscriptions that cannot be restored.
src/vs/platform/agentHost/node/copilot/copilotAgent.ts Implements provisional sessions + materialization on first message; adds onDidMaterializeSession event.
src/vs/platform/agentHost/node/agentService.ts Defers sessionAdded for provisional sessions, adds empty-session GC scheduling, and handles materialization events.
src/vs/platform/agentHost/node/agentHostStateManager.ts Supports deferring SessionAdded notifications until persistence and suppresses SessionRemoved for never-announced sessions.
src/vs/platform/agentHost/node/agentConfigurationService.ts Adds getSessionConfigValues to read live reducer-managed config during materialization.
src/vs/platform/agentHost/common/state/protocol/state.ts Small doc wording update (“server-provided”).
src/vs/platform/agentHost/common/state/protocol/commands.ts Adds ReconnectReplayResult.missing field.
src/vs/platform/agentHost/common/state/protocol/.ahp-version Bumps synced protocol version hash.
src/vs/platform/agentHost/common/agentService.ts Adds provisional flag to createSession result and defines IAgentMaterializeSessionEvent + optional agent event.

Copilot's findings

Comments suppressed due to low confidence (2)

src/vs/platform/agentHost/node/agentService.ts:317

  • The comment says provisional sessions defer the SessionReady lifecycle transition until materialization, but createSession dispatches ActionType.SessionReady unconditionally a few lines later. Either gate the initial SessionReady dispatch for created.provisional sessions, or adjust the comment to match the actual behavior (and consider removing the redundant SessionReady dispatch in _onDidMaterializeSession if it remains unconditional).
		// When forking, populate the new session's protocol state with
		// the source session's turns so the client sees the forked history.
		if (config?.fork) {
			const sourceState = this._stateManager.getSessionState(config.fork.session.toString());
			let sourceTurns: Turn[] = [];
			if (sourceState && config.fork.turnIdMapping) {
				sourceTurns = sourceState.turns.slice(0, config.fork.turnIndex + 1)

src/vs/platform/agentHost/node/copilot/copilotAgent.ts:708

  • In the idempotency branch (if (this._sessions.has(sessionId))), the method returns workingDirectory: config.workingDirectory and computes project from that directory. For already-materialized sessions (e.g. worktree isolation), this may not match the session’s actual resolved working directory / project metadata, which can make retries report inconsistent data to the agent service. Consider returning the working directory/project from the existing in-memory session (or persisted session metadata) instead of the incoming createSession request.
				}

				// Resume the forked session so the SDK loads the forked history
				const agentSession = await this._resumeSession(newSessionId);

				// Remap turn IDs to match the new protocol turn IDs
				if (config.fork!.turnIdMapping) {
					await agentSession.remapTurnIds(config.fork!.turnIdMapping);
				}

				const session = agentSession.sessionUri;
  • Files reviewed: 17/17 changed files
  • Comments generated: 3

@connor4312
Connor Peet (connor4312) merged commit 8309b22 into main May 2, 2026
25 of 26 checks passed
@connor4312
Connor Peet (connor4312) deleted the connor4312/eager-create-session branch May 2, 2026 03:29
@vs-code-engineering vs-code-engineering Bot added this to the 1.119.0 milestone May 2, 2026
TylerLeonhardt added a commit that referenced this pull request May 2, 2026
Handoff plan for Phase 5 (replace 7 throwing stubs in claudeAgent.ts).
Locked against post-PR-#313841 reality (provisional sessions,
onDidMaterializeSession, 30s empty-session GC) and the IAgent contract
on origin/main.

Decisions captured:
- Non-fork createSession is synchronous and in-memory; fork deferred
  to Phase 6 (throws TODO).
- IClaudeAgentSdkService surface mirrors IAgent (no dir parameter on
  listSessions); SDK loader caches resolved module, retries on
  failure, logs once.
- listSessions joins SDK enumeration with workbench session DB
  metadata via ISessionDataService; per-entry try/catch resilience.
- shutdown() routes per-session teardown through the same
  SequencerByKey<string> used by disposeSession() so concurrent
  shutdown/disposeSession cannot double-dispose a wrapper in Phase 6.
- 14 unit tests defined (12 lifecycle + 2 resolved-config), including
  log-once contract and shutdown/disposeSession race guard.
TylerLeonhardt added a commit that referenced this pull request May 5, 2026
* agentHost/claude: post-Phase-4 cleanup

- roadmap.md: mark Phase 4 as DONE, link merged PR #313780.
- phase4-plan.md: record live-system smoke completion in §7.8;
  disabled-gate run skipped (covered by unit tests + env-var guard).
- claudeAgent.test.ts: drop gratuitous 'as unknown as' cast in the
  CCAModel fixture (literal already matches CCAModelBilling exactly;
  plan §7.4 forbids unsafe casts in tests).

* agentHost/claude: lock Phase 5 implementation plan

Handoff plan for Phase 5 (replace 7 throwing stubs in claudeAgent.ts).
Locked against post-PR-#313841 reality (provisional sessions,
onDidMaterializeSession, 30s empty-session GC) and the IAgent contract
on origin/main.

Decisions captured:
- Non-fork createSession is synchronous and in-memory; fork deferred
  to Phase 6 (throws TODO).
- IClaudeAgentSdkService surface mirrors IAgent (no dir parameter on
  listSessions); SDK loader caches resolved module, retries on
  failure, logs once.
- listSessions joins SDK enumeration with workbench session DB
  metadata via ISessionDataService; per-entry try/catch resilience.
- shutdown() routes per-session teardown through the same
  SequencerByKey<string> used by disposeSession() so concurrent
  shutdown/disposeSession cannot double-dispose a wrapper in Phase 6.
- 14 unit tests defined (12 lifecycle + 2 resolved-config), including
  log-once contract and shutdown/disposeSession race guard.

* agentHost/claude: Phase 5 — IAgent provider skeleton

Lands the ClaudeAgent IAgent provider behind the
'chat.agentHost.claudeAgent.enabled' setting (env gate
VSCODE_AGENT_HOST_ENABLE_CLAUDE=1). Pins
@anthropic-ai/[email protected] in workspace + remote/.

Implemented in this phase:
* createSession - non-fork, in-memory wrapper only. Honors
  config.session for restore. The fork path and SDK session
  creation are deferred to Phase 6.
* listSessions - SDK is source of truth; per-session DB read
  is a best-effort overlay (failure never excludes an entry).
* disposeSession / shutdown - routed through a per-session
  SequencerByKey to serialize teardown.
* getDescriptor, getProtectedResources, models,
  onDidSessionProgress, setClientCustomizations,
  setClientTools, onClientToolCallComplete,
  setCustomizationEnabled, authenticate, respondTo*Request -
  minimal Phase-5 wiring.

Stubbed for Phase 6 (throw async 'TODO: Phase 6'):
sendMessage, abortSession, changeModel, getSessionMessages,
plus the createSession fork path.

Tests: 29 unit tests in claudeAgent.test.ts cover the
createSession restore-id path, listSessions overlay resilience,
dispose serialization, and stub surfaces.

Note: provisional / onDidMaterializeSession is intentionally
omitted in Phase 5 (see plan section 3.3.1) - the workbench needs
an immediate sessionAdded until the agent has real materialization
work, which arrives in Phase 6 alongside SDK query() startup.

* agentHost/claude: Phase 6 — sendMessage, single-turn, no tools

Implements the Phase 6 plan: provisional sessions materialize on first sendMessage, route a single-turn prompt through the Anthropic Claude Agent SDK's WarmQuery, and stream SDKMessages back as protocol AgentSignals via a pure mapSDKMessageToAgentSignals reducer.

Tools remain denied (canUseTool: 'deny'); fork moves to Phase 6.5; Plan Mode UI moves to Phase 7.

Highlights:

- ClaudeAgent.sendMessage routes through _sessionSequencer to collapse concurrent first sends into one materialize + N ordered sends.

- _materializeProvisional has two abort gates (post-startup + post-customizationDirectory write) so disposeSession landing mid-materialize cannot leak a WarmQuery subprocess.

- ClaudeAgentSession owns the prompt iterator + per-turn deferreds; mapSDKMessageToAgentSignals is a pure reducer with state owned by the session.

- IClaudeAgentSdkService gains startup() alongside listSessions().

Tests: 43 unit + 2 proxy-backed integration. Council-review fixes (C1 dispose race, C2 missing integration test, S1 cwd-less ratification) included.

* agentHost/claude: address PR review (listSessions resilience, dispose abort)

Two Copilot-reviewer comments on #314216:

1. listSessions: wrap _sdkService.listSessions() in try/catch. AgentService.listSessions fans out across providers via Promise.all; an SDK dynamic-import failure would otherwise nuke every other provider's session list. Now logs and returns [].

2. dispose: abort _provisionalSessions AbortControllers before super.dispose(). Previously a racing first sendMessage parked inside _writeCustomizationDirectory could pass the materialize abort gates and call _sessions.set on a disposed DisposableMap, orphaning the WarmQuery. Aborting first triggers the existing post-customization-write abort gate, which asyncDisposes the WarmQuery.

Tests: 2 new regressions (listSessions empty on SDK throw; agent.dispose() during racing materialize disposes the WarmQuery). 45/45 unit + 2/2 integration pass.
TylerLeonhardt added a commit that referenced this pull request May 5, 2026
Handoff plan for Phase 5 (replace 7 throwing stubs in claudeAgent.ts).
Locked against post-PR-#313841 reality (provisional sessions,
onDidMaterializeSession, 30s empty-session GC) and the IAgent contract
on origin/main.

Decisions captured:
- Non-fork createSession is synchronous and in-memory; fork deferred
  to Phase 6 (throws TODO).
- IClaudeAgentSdkService surface mirrors IAgent (no dir parameter on
  listSessions); SDK loader caches resolved module, retries on
  failure, logs once.
- listSessions joins SDK enumeration with workbench session DB
  metadata via ISessionDataService; per-entry try/catch resilience.
- shutdown() routes per-session teardown through the same
  SequencerByKey<string> used by disposeSession() so concurrent
  shutdown/disposeSession cannot double-dispose a wrapper in Phase 6.
- 14 unit tests defined (12 lifecycle + 2 resolved-config), including
  log-once contract and shutdown/disposeSession race guard.
TylerLeonhardt added a commit that referenced this pull request May 6, 2026
…e-land) (#314533)

* agentHost/claude: post-Phase-4 cleanup

- roadmap.md: mark Phase 4 as DONE, link merged PR #313780.
- phase4-plan.md: record live-system smoke completion in §7.8;
  disabled-gate run skipped (covered by unit tests + env-var guard).
- claudeAgent.test.ts: drop gratuitous 'as unknown as' cast in the
  CCAModel fixture (literal already matches CCAModelBilling exactly;
  plan §7.4 forbids unsafe casts in tests).

* agentHost/claude: lock Phase 5 implementation plan

Handoff plan for Phase 5 (replace 7 throwing stubs in claudeAgent.ts).
Locked against post-PR-#313841 reality (provisional sessions,
onDidMaterializeSession, 30s empty-session GC) and the IAgent contract
on origin/main.

Decisions captured:
- Non-fork createSession is synchronous and in-memory; fork deferred
  to Phase 6 (throws TODO).
- IClaudeAgentSdkService surface mirrors IAgent (no dir parameter on
  listSessions); SDK loader caches resolved module, retries on
  failure, logs once.
- listSessions joins SDK enumeration with workbench session DB
  metadata via ISessionDataService; per-entry try/catch resilience.
- shutdown() routes per-session teardown through the same
  SequencerByKey<string> used by disposeSession() so concurrent
  shutdown/disposeSession cannot double-dispose a wrapper in Phase 6.
- 14 unit tests defined (12 lifecycle + 2 resolved-config), including
  log-once contract and shutdown/disposeSession race guard.

* agentHost/claude: Phase 5 — IAgent provider skeleton

Lands the ClaudeAgent IAgent provider behind the
'chat.agentHost.claudeAgent.enabled' setting (env gate
VSCODE_AGENT_HOST_ENABLE_CLAUDE=1). Pins
@anthropic-ai/[email protected] in workspace + remote/.

Implemented in this phase:
* createSession - non-fork, in-memory wrapper only. Honors
  config.session for restore. The fork path and SDK session
  creation are deferred to Phase 6.
* listSessions - SDK is source of truth; per-session DB read
  is a best-effort overlay (failure never excludes an entry).
* disposeSession / shutdown - routed through a per-session
  SequencerByKey to serialize teardown.
* getDescriptor, getProtectedResources, models,
  onDidSessionProgress, setClientCustomizations,
  setClientTools, onClientToolCallComplete,
  setCustomizationEnabled, authenticate, respondTo*Request -
  minimal Phase-5 wiring.

Stubbed for Phase 6 (throw async 'TODO: Phase 6'):
sendMessage, abortSession, changeModel, getSessionMessages,
plus the createSession fork path.

Tests: 29 unit tests in claudeAgent.test.ts cover the
createSession restore-id path, listSessions overlay resilience,
dispose serialization, and stub surfaces.

Note: provisional / onDidMaterializeSession is intentionally
omitted in Phase 5 (see plan section 3.3.1) - the workbench needs
an immediate sessionAdded until the agent has real materialization
work, which arrives in Phase 6 alongside SDK query() startup.

* agentHost/claude: Phase 6 — sendMessage, single-turn, no tools

Implements the Phase 6 plan: provisional sessions materialize on first sendMessage, route a single-turn prompt through the Anthropic Claude Agent SDK's WarmQuery, and stream SDKMessages back as protocol AgentSignals via a pure mapSDKMessageToAgentSignals reducer.

Tools remain denied (canUseTool: 'deny'); fork moves to Phase 6.5; Plan Mode UI moves to Phase 7.

Highlights:

- ClaudeAgent.sendMessage routes through _sessionSequencer to collapse concurrent first sends into one materialize + N ordered sends.

- _materializeProvisional has two abort gates (post-startup + post-customizationDirectory write) so disposeSession landing mid-materialize cannot leak a WarmQuery subprocess.

- ClaudeAgentSession owns the prompt iterator + per-turn deferreds; mapSDKMessageToAgentSignals is a pure reducer with state owned by the session.

- IClaudeAgentSdkService gains startup() alongside listSessions().

Tests: 43 unit + 2 proxy-backed integration. Council-review fixes (C1 dispose race, C2 missing integration test, S1 cwd-less ratification) included.

* agentHost/claude: address PR review (listSessions resilience, dispose abort)

Two Copilot-reviewer comments on #314216:

1. listSessions: wrap _sdkService.listSessions() in try/catch. AgentService.listSessions fans out across providers via Promise.all; an SDK dynamic-import failure would otherwise nuke every other provider's session list. Now logs and returns [].

2. dispose: abort _provisionalSessions AbortControllers before super.dispose(). Previously a racing first sendMessage parked inside _writeCustomizationDirectory could pass the materialize abort gates and call _sessions.set on a disposed DisposableMap, orphaning the WarmQuery. Aborting first triggers the existing post-customization-write abort gate, which asyncDisposes the WarmQuery.

Tests: 2 new regressions (listSessions empty on SDK throw; agent.dispose() during racing materialize disposes the WarmQuery). 45/45 unit + 2/2 integration pass.

* Drop stale @anthropic-ai/sandbox-runtime dep from merge resolution

* Bump @anthropic-ai/claude-agent-sdk 0.2.112 → 0.2.128

The new SDK no longer vendors native binaries inside the main package.
It now ships a ~200MB `claude` executable per platform via 8 optional
platform-specific packages, mirroring the @github/copilot pattern:

  @anthropic-ai/claude-agent-sdk-{darwin,win32}-{x64,arm64}
  @anthropic-ai/claude-agent-sdk-linux-{x64,arm64}{,-musl}

The SDK loader picks the right package at runtime via process.platform
/process.arch (and tries -musl first on linux).

To strip off-target packages from the build output:
- build/lib/claudeAgentSdk.ts mirrors build/lib/copilot.ts
- gulpfile.vscode.ts and gulpfile.reh.ts apply the filter alongside
  the existing copilot one
- gulpfile.vscode.ts asar-unpacks @anthropic-ai/claude-agent-sdk-* so
  the executable stays on disk (asar would break exec permissions)
- alpine-{arch} maps to linux-{arch}-musl (claude is statically linked
  against libc and must match the host)

cglicenses.json gets 8 new entries mirroring the parent SDK's
"© Anthropic PBC. All rights reserved." text.

The new SDK Query interface adds a `readFile` method; FakeQuery and
RoundTripQuery test doubles get matching stubs.

Co-authored-by: Copilot <[email protected]>

* build: cross-copy @anthropic-ai/claude-agent-sdk darwin packages for universal app

Mirror the existing @github/copilot pattern in create-universal-app.ts.
Each darwin arch build only contains its own platform package (npm only
installs the optionalDependency matching the host CPU), so the universal
merger fails with files unique to one side.

Cross-copy node_modules/@anthropic-ai/claude-agent-sdk-{darwin-x64,darwin-arm64}/
between the two builds, skip them from the equality comparison, and tag
the per-arch `claude` executable as arch-specific so the merger keeps both.

Also extend verify-macho's skip list to ignore the single-arch `claude`
binaries inside the universal app.

* agentHost/claude: address PR review

- claudeAgent: rewrite `rgPath` from node_modules.asar →
  node_modules.asar.unpacked before putting it on the Claude subprocess
  PATH. Mirrors copilotAgent.ts and the workbench search engine helpers;
  without this, packaged builds advertise a path that doesn't exist on
  disk.
- cglicenses.json: add "// Reason: …" justification comments to the
  parent @anthropic-ai/claude-agent-sdk entry and each of the 8 new
  platform sub-packages, matching the file's convention.

* build: bump DMG volume size from 1g to 2g

The universal macOS app now carries platform-specific binaries for both
x64 and arm64 — @github/copilot-darwin-* (~128MB each) and the new
@anthropic-ai/claude-agent-sdk-darwin-* (~207MB each) — so the source
filesystem the DMG is built from has crossed 1GB. dmgbuild fails with
`No space left on device` when ditto can't fit the app inside the
volume.

Output DMG is LZMA-compressed (format = 'ULMO') so this only changes
the build-time staging size, not the shipped artifact size.

* agentHost/claude: don't bundle claude-agent-sdk; load it from a user-specified path

Move `@anthropic-ai/claude-agent-sdk` from `dependencies` to
`devDependencies` so the ~200MB-per-arch platform binaries are no longer
shipped with VS Code. The SDK becomes opt-in and externally-installed.

User-facing surface:
  - Replace boolean setting `chat.agentHost.claudeAgent.enabled` with
    string setting `chat.agentHost.claudeAgent.path`. When the setting
    is non-empty, the Claude provider registers; when empty (the default),
    it does not.
  - The setting value is forwarded to the agent host via the
    `VSCODE_AGENT_HOST_CLAUDE_SDK_PATH` env var (replacing the previous
    `VSCODE_AGENT_HOST_ENABLE_CLAUDE` flag).
  - `agentHostServerMain` exposes a `--claude-sdk-path <path>` CLI flag
    in place of the previous `--enable-claude-agent` flag.

Runtime loader:
  - `ClaudeAgentSdkService._loadSdk()` now reads the env var and
    dynamic-imports from there. If the path is a directory, the package's
    main entry is resolved from `package.json` (`exports['.']` /
    `main`) before the import — Node ESM does not support directory
    imports of `file://` URLs.

Build/packaging cleanup (no longer needed once the SDK is gone from
production deps):
  - Drop `build/lib/claudeAgentSdk.ts` and its callers in
    `gulpfile.{vscode,reh}.ts`.
  - Drop the `@anthropic-ai/claude-agent-sdk-*` glob from the
    asar-unpack list in `gulpfile.vscode.ts`.
  - Revert universal-app cross-copy + filesToSkip + x64ArchFiles entries
    in `build/darwin/create-universal-app.ts` and the corresponding
    skip patterns in `build/darwin/verify-macho.ts`.
  - Revert DMG volume size from 2g back to 1g in
    `build/darwin/dmg-settings.py.template` (was bumped earlier in
    this branch to fit the bundled SDK; no longer needed).
  - Remove the 9 `@anthropic-ai/claude-agent-sdk*` entries from
    `cglicenses.json` (no longer shipped, no manifest to license).

Type imports of `@anthropic-ai/claude-agent-sdk` continue to work via
the devDependency, so source code that does `import type` from the
package still typechecks.

* revert cglicenses change

---------

Co-authored-by: Copilot <[email protected]>
@vs-code-engineering vs-code-engineering Bot locked and limited conversation to collaborators Jun 16, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants