@zvada/agent-server 0.3.12 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.14
4
+
5
+ - Update the managed CLIs and development SDKs: Codex 0.160.0 and Claude Agent
6
+ SDK 0.3.288. Codex 0.153.4 rejected the GPT-6.1 models a current
7
+ `~/.codex/config.toml` selects, so every default Codex turn failed on a
8
+ machine with a newer Codex installed. Claude thinking summaries flow again
9
+ on the newer CLI, which was the reason its pin was held.
10
+ - Report the failure Codex streamed when a `codex-sdk` turn fails. The turn
11
+ ended as `process_exit` with the CLI's stderr ("Reading prompt from
12
+ stdin..."); it now carries the provider's message and category, as
13
+ `codex-app-server` already did.
14
+ - Classify a model Claude Code rejects as `invalid_request` instead of
15
+ `internal`.
16
+ - Stream a part's first text once in the `acp`, `codex-app-server` and
17
+ `codex-sdk` harnesses. When a part arrived with text already in hand, its
18
+ opening snapshot and its first delta both carried that text, so clients
19
+ showed it twice until the final snapshot, and kept it if none came.
20
+ - Keep the logged-in account's claude.ai connectors (Drive, Gmail, …) out of
21
+ Claude sessions. They loaded into every turn. Set
22
+ `ENABLE_CLAUDEAI_MCP_SERVERS=true` in the env to load them.
23
+ - Add the `max` and `ultra` thinking levels. Claude runs `ultra` as `max`.
24
+ - Show a provider's message for a failed turn instead of its JSON envelope.
25
+ - `DEFAULT_MODELS["claude-code"]` is now `undefined`: the engine never applied
26
+ the `sonnet` it listed, and turns ran on the CLI's own default.
27
+ - Refresh the advisory Codex model catalog: add the GPT-6 family and drop
28
+ `gpt-5.5-codex`, which the provider rejects.
29
+ - ACP harness (SDK 1.7.0): fall back to `session/load` for agents without
30
+ `session/resume`; select `model` and `thinkingLevel` through the agent's
31
+ config options; send `additionalDirectories` to agents that take them;
32
+ identify the client in `initialize`; read per-turn usage when the agent
33
+ reports it; report a cancelled prompt as a cancelled turn; include the
34
+ JSON-RPC error detail when a prompt fails.
35
+ - ACP server binding: `session/resume` works after a restart (native ids are
36
+ recorded under `AGENT_SERVER_ACP_SESSION_DIR`); the prompt response carries
37
+ the turn's usage; HTTP/SSE MCP is advertised when fronting `claude-code`.
38
+ - Codex 0.160 allows one writer per thread. Resuming a thread from a second
39
+ process fails with `resume_failed` until the first session is closed.
40
+ - Lift `@modelcontextprotocol/sdk` to 1.32, `proxy-addr` to 2.0.8 and
41
+ `source-map-js` to 1.2.2, past published advisories, and align the CLI app
42
+ on the package's Claude Agent SDK.
43
+
44
+ ## 0.3.13
45
+
46
+ - Add opt-in `subagentMode: "turn"` for Claude Code and Codex app-server.
47
+ Native workers stay within the managed execution's lifetime and existing
48
+ permission broker. Unsupported harnesses reject this mode.
49
+ - Preserve modern Claude Agent metadata and nested text, normalize Codex V1
50
+ task tools, and expose V2 native activity as a typed `SubagentPart`.
51
+ - Require native cleanup before a managed Codex execution releases ownership,
52
+ including cancellation and failed startup. Unconfirmed cleanup prevents
53
+ session reuse. Managed Codex successors resume in a fresh native process.
54
+ Default interactive harness behavior remains unchanged.
55
+
3
56
  ## 0.3.12
4
57
 
5
58
  - Report a Claude turn whose API call failed as an error. Claude Code ends it
package/docs/deploy.md CHANGED
@@ -41,6 +41,10 @@ bun build --compile packages/agent-server/src/server/bin.ts --outfile dist/agent
41
41
  # | bun-linux-x64-musl (Alpine) | bun-linux-arm64-musl
42
42
  ```
43
43
 
44
+ On macOS 27, binaries compiled by Bun 1.3.x carry an invalid signature and
45
+ are killed at launch (exit 137, no output). Compile with Bun 1.4.2 or newer,
46
+ or re-sign: `codesign --force --sign - dist/agent-server`.
47
+
44
48
  Inside a compiled binary the Claude SDK can't reach its platform package, so
45
49
  provisioning is what makes the binary *work*: first turn on a bare machine
46
50
  downloads the pinned CLIs (~7 s on datacenter bandwidth, parallel), every
package/docs/harnesses.md CHANGED
@@ -9,7 +9,7 @@ support differ only where the backends genuinely do.
9
9
  | `claude-code` | `@anthropic-ai/claude-agent-sdk` (claude CLI) | token-level | yes (`resume`) | in-session (`setModel`) |
10
10
  | `codex-sdk` | `@openai/codex-sdk` (codex CLI exec) | item-level (deltas synthesized) | yes (`resumeThread`) | restart-session |
11
11
  | `codex-app-server` | `codex app-server` (JSON-RPC subprocess) | token-level | yes (`thread/resume`) | in-session (per-turn) |
12
- | `acp` | any ACP v1 agent via `@agentclientprotocol/sdk` | per-agent | yes (`session/resume`) | per-agent |
12
+ | `acp` | any ACP v1 agent via `@agentclientprotocol/sdk` | per-agent | yes (`session/resume`, else `session/load`) | per-agent (`model` config option) |
13
13
 
14
14
  The `acp` harness is opt-in (an operator-supplied launch command, never
15
15
  wire-sourced): well-known agents run by name (`--harness=pi`,
@@ -17,6 +17,21 @@ wire-sourced): well-known agents run by name (`--harness=pi`,
17
17
  `$AGENT_SERVER_ACP_AGENT`, or `CreateRegistryOptions.acp.resolveLaunch` when
18
18
  embedding.
19
19
 
20
+ What the `acp` harness asks of an agent, and what it does when the agent
21
+ offers it (checked against SDK 1.7.0 with `claude-agent-acp` and `codex-acp`):
22
+
23
+ - **Resume:** `session/resume` when advertised, otherwise `session/load`
24
+ (the replayed history is discarded). An agent with neither fails the turn
25
+ as `resume_failed`.
26
+ - **Model and thinking level:** selected through the agent's `model` and
27
+ `thought_level` config options (`session/set_config_option`). An agent
28
+ without the option keeps its default. A model the agent does not list fails
29
+ the turn as `invalid_request`; an unlisted thinking level is left alone.
30
+ - **Extra directories:** `additionalDirectories` is sent to agents that
31
+ advertise the capability and ignored otherwise.
32
+ - **Token usage:** read from the prompt response when the agent sends it. The
33
+ field is still unstable in ACP v1, so many agents report none.
34
+
20
35
  All harnesses share: one stable logical `sessionId` you assign, a
21
36
  harness-native id surfaced via `session.created` (persist it to resume later),
22
37
  warm multi-turn reuse, a unified `ThinkingLevel`, and normalized token usage.
@@ -41,6 +56,21 @@ Codex per-turn MCP is supported through the engine/JSON-RPC API, AGNT, and the
41
56
  repository CLI with an explicit `--codex-home`. The ACP server binding cannot
42
57
  provide isolated homes and rejects this combination at session admission.
43
58
 
59
+ The ACP server binding (`agent-server --acp`) records each session's native
60
+ id under `$AGENT_SERVER_ACP_SESSION_DIR` (default
61
+ `~/.local/state/agent-server/acp-sessions`), so a client's `session/resume`
62
+ works after the agent process restarts. It reports per-turn usage on the prompt
63
+ response and advertises HTTP/SSE MCP when fronting `claude-code`.
64
+
65
+ A Claude session loads the operator's filesystem settings, as the CLI does,
66
+ but not the logged-in account's claude.ai connectors: a turn gets the MCP
67
+ servers its config names. Set `ENABLE_CLAUDEAI_MCP_SERVERS=true` in the
68
+ server's or the turn's env to load them.
69
+
70
+ `thinkingLevel` runs from `off` to `ultra`. Claude's ceiling is `max` (it runs
71
+ `ultra` as `max`); Codex passes the level through, and not every model offers
72
+ `ultra`.
73
+
44
74
  Consult `runtime.capabilities(harness)` before relying on a capability.
45
75
 
46
76
  ## Host-managed Codex authentication
@@ -70,7 +100,7 @@ fresh access credentials, the callback must return the same ChatGPT account;
70
100
  the engine rejects mismatched identities and refreshes that outlive their turn.
71
101
  An absent previous-account hint resolves to the turn's selected account. No
72
102
  credentials or callbacks are added to `RunConfig` or the engine's public wire.
73
- The protocol was checked against Codex CLI 0.153.4 and the
103
+ The protocol was checked against Codex CLI 0.160.0 and the
74
104
  [official app-server authentication documentation](https://learn.chatgpt.com/docs/app-server#3c-log-in-with-externally-managed-chatgpt-tokens-chatgptauthtokens).
75
105
 
76
106
  ## Payload notes
@@ -120,9 +150,21 @@ provide the cache breakdown without an additional native usage report.
120
150
 
121
151
  ## Known limitations (roadmap)
122
152
 
153
+ - **Native subagents:** opt into `RunConfig.subagentMode: "turn"` for Claude
154
+ Code or Codex app-server. The parent collects results; native workers settle
155
+ before the engine releases the turn. Claude forwards nested worker text.
156
+ Codex emits task tools and typed `subagent` activity; it does not forward full
157
+ child transcripts. Managed Codex turns close the native process after cleanup
158
+ and resume saved context on the next turn. Default behavior is unchanged.
159
+ See [RFD 0002](rfds/0002-native-subagents.md) for the rehearsal and qualification.
123
160
  - **MCP servers** are supported by Claude and Codex app-server. Codex SDK
124
161
  passthrough remains unsupported. See [MCP configuration](consuming.md#configure-mcp-between-turns)
125
162
  for Codex home ownership, supported transports, and live-update behavior.
163
+ - **Codex app-server threads have one writer** (CLI 0.160 and newer). A
164
+ thread still loaded by a live session cannot be resumed from another
165
+ process; the turn fails with `resume_failed` ("already has an active
166
+ writer"). Close the first session (`session/close`) or let its process end
167
+ before resuming elsewhere.
126
168
  - The **BYOK proxy** (`/core/proxy`) is a building block, not yet auto-wired
127
169
  into the harnesses (they use ambient/explicit keys today).
128
170
  - **Hook bridge** (PreToolUse/Stop decisions) is exposed for the claude
@@ -0,0 +1,197 @@
1
+ # RFD 0002 — Native delegation within a managed turn
2
+
3
+ **Status:** implemented; native Claude and Codex qualification passed on 2026-09-29.
4
+ **Date:** 2026-09-29
5
+ **Scope:** Claude Code and Codex app-server in agent-server and AGNT.
6
+ **Baseline:** agent-server `7248c43`; AGNT `39df4fa9`.
7
+
8
+ ## Recommendation
9
+
10
+ Support native delegation inside the existing logical engine turn. The parent
11
+ assigns work, collects results and produces the final answer. The engine retains
12
+ ownership until its native work finishes or is stopped. AGNT keeps using its
13
+ existing turn-scoped credentials, permission bridge, persistence and cancellation.
14
+
15
+ This is a smaller extension of [DESIGN D10](../../../../DESIGN.md#d10--built-in-turns-own-their-logical-session-through-cleanup).
16
+ It does not require a second scheduler, child credential leases, a worker
17
+ database, or a stream that remains active between managed turns. Independently
18
+ running workers across later turns are outside this first contract.
19
+
20
+ ## What already works — observed
21
+
22
+ Deus Machine already configures this engine with `forwardSubagentText: true`
23
+ and renders nested subagent output. At `origin/main` `4e957a26c`, see
24
+ `apps/agent-server/agents/core/engine.ts`,
25
+ `apps/web/src/features/session/ui/blocks/SubagentGroupBlock.tsx` and
26
+ `apps/backend/test/unit/services/event-persistence-integration.test.ts`.
27
+ The last file tests nesting a worker message under its spawning tool. This is
28
+ source evidence, not a new live execution.
29
+
30
+ The engine already carries `ToolPart.subagent` and `parentToolCallId`; its
31
+ `test/server/flows.test.ts` covers nested output. AGNT already round-trips these
32
+ fields. Its two focused message suites passed **37 tests** during this rehearsal.
33
+
34
+ [SessionAgent](../../src/core/agents/session-agent.ts) already reserves a session
35
+ through `executeTurn` cleanup. AGNT's controller waits for its predecessor to
36
+ drain before preparing a new credential and releases credentials in its existing
37
+ `finally`. These are the owners to reuse.
38
+
39
+ AGNT does not globally disable native delegation. Its explicit `toolAllowlist`
40
+ rejects `Agent` and `Task`; QApp also omits them. AGNT's Claude SDK options omit
41
+ Deus Machine's forwarding flag. Saying that the whole stack lacked subagents
42
+ was too broad.
43
+
44
+ ## Pass 1 — the smallest apparent patch
45
+
46
+ 1. Enable Claude child-text forwarding in AGNT. Recognize modern `Agent` as
47
+ well as legacy `Task` in the Claude adapter.
48
+ 2. Normalize Codex's existing native delegation output.
49
+ 3. Permit delegation under AGNT's scoped tool policy.
50
+
51
+ Steps 1–3 alone are insufficient. The following counterexamples determine the
52
+ additional work; they do not justify a general background-worker platform.
53
+
54
+ ## Pass 2 — counterexamples and smallest corrections
55
+
56
+ | Trigger and current path | Wrong result | Smallest correction and proof |
57
+ | --- | --- | --- |
58
+ | Claude returns its parent `result` while background work remains; `ClaudeGeneratorSession` closes the tap. | Late child output is lost or reaches the next tap after the host changes policy. | In the managed mode, enforce native foreground execution and qualify cleanup on the pinned SDK. Test cancellation plus a successor with changed policy. |
59
+ | Codex emits root `turn/completed`; `executeTurn` ends its queue and removes listeners. | Child activity disappears; credentials can be released too early. | Track native descendants for this execution, separate parent completion from execution settlement, and retain the existing session reservation through cleanup. |
60
+ | Merely delay Codex's queue end, leaving `turnEnded = true`. | `forceCancel` returns early, so cancellation can hang or falsely settle. | Make cancellation depend on execution settlement, target active owned native turns, and observe completion. Test cancel after the parent response. |
61
+ | A Codex child requests approval. `bindRequests` currently declines every foreign thread id. | Owned children cannot use the existing permission broker. | Admit only descendants proven by native ownership; route them through the current turn's handler. Test an owned child and an unrelated thread. |
62
+ | Treat `client.close()` or a stop request as proof of teardown. | Current `close()` marks itself closed before the OS process exits. | Await actual native completion or bounded subprocess teardown; qualify descendant tools too. Never report a clean stop from the local boolean alone. |
63
+ | Set foreground behavior globally for all engine consumers. | Existing interactive Deus Machine behavior changes unintentionally. | Use one explicit managed-turn option, include it in native session configuration, and preserve the default for existing consumers. |
64
+ | Wait for workers after the parent has already submitted its answer. | The final answer may never have used their results. | Require the parent to collect results. If it returns with outstanding work, stop that work and report incomplete execution; do not silently run another model turn. |
65
+
66
+ The earlier synthetic probes reproduced omitted adapter events and late-tap
67
+ routing, not a live permission escape. Artifacts remain under
68
+ `.context/subagents-research/` and QApp's `.context/delegation-audit/`.
69
+
70
+ ## Pass 3 — revised implementation
71
+
72
+ ### Engine option and lifetime
73
+
74
+ The opt-in `RunConfig.subagentMode: "turn"` preserves existing native behavior
75
+ when omitted. Unsupported
76
+ harnesses reject the request. Thread it through
77
+ `src/protocol/config.ts`, `src/core/agents/base.ts`,
78
+ `src/core/runtime/agent-runtime.ts` and native session configuration.
79
+ A warm process must not silently retain an incompatible mode.
80
+
81
+ The normal path remains one run: native workers execute, the parent receives
82
+ their results, and the engine finishes after native cleanup. Multiple native
83
+ workers may run concurrently where the pinned harness supports it; qualify that
84
+ behavior rather than promising it from an SDK option.
85
+
86
+ The adapter needs an execution-local record of owned native work, not a durable
87
+ child-session service. Track starts, terminal outcomes and active native turn
88
+ identifiers, including descendants. A spawn acknowledgement is not completion.
89
+ On early parent exit or cancellation, stop remaining owned work before releasing
90
+ ownership. Failure to establish cleanup must remain a failed/unconfirmed
91
+ execution and prevent unsafe session reuse. Do not add automatic retries or
92
+ background parent wake-ups.
93
+
94
+ ### Claude
95
+
96
+ Use the native foreground control in managed mode and forward child text.
97
+ The current [Claude documentation](https://code.claude.com/docs/en/sub-agents#run-subagents-in-foreground-or-background)
98
+ documents `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1`; verify the behavior against
99
+ the pinned SDK **0.3.220**, including explicit background requests and
100
+ cancellation. Reuse the existing message nesting.
101
+
102
+ Changes belong in `claude-code/options.ts`, `claude-agent.ts`,
103
+ `generator-session.ts` as required by that qualification, and the
104
+ `subagentFromInput` branch in `claude-code/adapter.ts`. Do not build a separate
105
+ Claude scheduler. If the native foreground control does not contain the pinned
106
+ runtime, keep the managed capability disabled until that specific gap is fixed.
107
+
108
+ ### Codex
109
+
110
+ The pinned CLI **0.153.4** emits V1 `collabAgentToolCall` and V2
111
+ `subAgentActivity`. Both currently disappear in the adapters. V2 activity may
112
+ arrive after its originating parent response. The
113
+ [pinned app-server contract](https://github.com/openai/codex/blob/3d2ee51ca2d5db578f328aa75e20aa22c0197c9a/codex-rs/app-server/README.md)
114
+ supports `turn/interrupt` for parent-owned V2 children too: use each child's
115
+ active native turn, then observe its terminal outcome. Interrupting an already
116
+ completed root is insufficient. Native background terminals have a separate
117
+ cleanup operation; include child-owned terminals in cancellation qualification.
118
+
119
+ Implement ownership, notification selection and drain behavior in
120
+ `codex-app-server/codex-app-server-agent.ts`; add awaited process-exit fallback
121
+ in `client.ts`. Use native parent links/read APIs to settle notification-order
122
+ races, never permissive thread matching. Child approval handling stays on the
123
+ existing broker.
124
+
125
+ Normalize V1 calls in `codex-app-server/adapter.ts` and `codex-items.ts`.
126
+ Preserve real native ids, results and task metadata. V2 is an activity, not a
127
+ public tool invocation: add the small typed activity representation it needs to
128
+ the existing Part/adapter/reducer path rather than inventing a tool call.
129
+ Carry its native activity id, child thread id and observed kind. This is a
130
+ persisted message part, not a new independently managed session. Full child
131
+ transcript parity is not a prerequisite; unavailable transcripts stay explicit.
132
+
133
+ ### AGNT and review consumers
134
+
135
+ AGNT enables the qualified managed mode in `AgentEngine.prepareTurn` and adds
136
+ `forwardSubagentText`. Its existing controller and credential cleanup remain
137
+ the owners. Extend existing part persistence only for the activity shape the
138
+ engine actually emits; no new worker table is needed.
139
+
140
+ Relax `Agent`/`Task` rejection only when child tools demonstrably obey the same
141
+ Claude allowlist, including bypass mode. Gate this admission on an updated
142
+ sidecar version. Codex's existing lack of custom `toolAllowlist` enforcement
143
+ remains a separate limitation; this work must not claim to solve it.
144
+
145
+ The parent decides what to test through skills, gives each worker the necessary
146
+ context, waits for results and submits one report. Device workers share no
147
+ simulator concurrently unless separate devices exist. QApp's evidence still
148
+ comes through its trusted capture path. No review roles belong in the engine.
149
+
150
+ ## Checks that establish the feature
151
+
152
+ - Adapter fixtures cover modern Claude `Agent`, legacy `Task`, Codex V1 and
153
+ V2, interleaved workers, native ids and honest outcomes.
154
+ - Runtime tests cover early parent completion, child failure, cancellation while
155
+ waiting, owned/unrelated approvals, actual teardown, and a successor with
156
+ different credentials/MCP/policy. No old child reaches that successor.
157
+ - Existing reducer, replay and AGNT JSON-part round trips retain nesting and
158
+ activity without a separate lifecycle database.
159
+ - Live pinned Claude and Codex runs each delegate two tasks and incorporate both
160
+ results. Repeat through AGNT's real proxy/MCP path, including a denied child
161
+ tool for Claude. Prove stop behavior and absence of continued child execution.
162
+ - Existing consumers without the managed option keep their native behavior.
163
+ A QApp review demonstrates worker evidence reaching the final report and
164
+ visible partial coverage on failure.
165
+
166
+ ## Implementation qualification
167
+
168
+ The deterministic engine suite passes (907 tests). The opt-in live suite
169
+ `test/core/live/subagents.live.test.ts` passes four real-model cases: Claude and
170
+ Codex each delegate to two workers and incorporate both unique file values;
171
+ each cancels a worker running a real shell command, confirms that PID stopped,
172
+ and successfully runs a successor. Proof is retained in `.context/proof/subagents`.
173
+ No simulator was used in these engine tests.
174
+
175
+ Live testing found that Claude can return `error_during_execution` with
176
+ `stop_reason: tool_use` on an acknowledged cancellation. The adapter now uses
177
+ the confirmed interrupt marker to distinguish that from an execution failure.
178
+
179
+ Codex can register a background terminal AFTER its thread becomes idle. An
180
+ interrupt response and empty terminal list therefore cannot prove cleanup.
181
+ Managed Codex turns close the app-server through stdin EOF after reconciliation,
182
+ which invokes native thread/tool shutdown. Root SIGTERM alone left a real child
183
+ command running on macOS. Forced exits or native cleanup warnings are unconfirmed
184
+ and quarantine the logical session. A managed successor resumes persisted context
185
+ in a fresh process; the default interactive mode retains its warm process.
186
+
187
+ This contract covers native managed work. It does not turn arbitrary shell
188
+ commands into an OS containment boundary; sandbox custody remains with the host.
189
+ AGNT and QApp integration qualification is recorded in their own design documents.
190
+
191
+ Repeated cancellation also consults persistent unconfirmed native cleanup after the wrapper turn has ended. The idle response of another harness must not erase that result in the host. AGNT cloud qualification additionally verified real child PID cleanup and a successful successor for both harnesses.
192
+
193
+ Releasing a quarantined Codex session also refuses unconfirmed cleanup. A host
194
+ must propagate that release failure before resetting the session or switching
195
+ harnesses; otherwise a successor could bypass the same-harness admission guard.
196
+ Deterministic regressions cover failure after normal parent completion, repeated
197
+ release attempts, and successful release after confirmed cleanup.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvada/agent-server",
3
- "version": "0.3.12",
3
+ "version": "0.3.14",
4
4
  "description": "Harness-agnostic agent execution engine: run Claude Code, Codex (SDK/CLI + app-server), and any ACP agent behind one interface with a normalized event stream, multi-turn sessions, and resume. Root export is the wire contract; /core, /server, /client are the seats.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -99,9 +99,9 @@
99
99
  }
100
100
  },
101
101
  "devDependencies": {
102
- "@agentclientprotocol/sdk": "^1.2.1",
103
- "@anthropic-ai/claude-agent-sdk": "0.3.220",
104
- "@openai/codex-sdk": "0.153.4",
102
+ "@agentclientprotocol/sdk": "^1.7.0",
103
+ "@anthropic-ai/claude-agent-sdk": "0.3.288",
104
+ "@openai/codex-sdk": "0.160.0",
105
105
  "@types/bun": "^1.2.0"
106
106
  }
107
107
  }
@@ -3,6 +3,7 @@ import type {
3
3
  PromptRequest,
4
4
  RequestPermissionRequest,
5
5
  RequestPermissionResponse,
6
+ SessionConfigOption,
6
7
  } from "@agentclientprotocol/sdk";
7
8
  import type { AgentCapabilities, AgentInput, PermissionMode } from "../../../protocol/index.ts";
8
9
  import { AsyncQueue } from "../../../protocol/index.ts";
@@ -25,8 +26,9 @@ const CAPABILITIES: AgentCapabilities = {
25
26
  multiTurn: true,
26
27
  // A requested resume fails if the target agent cannot load saved sessions.
27
28
  sessionResume: true,
28
- // v1 exposes model selection only through agent-defined config options;
29
- // there is no portable model parameter to pass through yet.
29
+ // v1 has no portable model parameter. A requested model or thinking level
30
+ // is applied only when the agent offers a `model` / `thought_level` config
31
+ // option, so neither is promised here.
30
32
  modelSwitch: "unsupported",
31
33
  thinkingLevels: false,
32
34
  images: true,
@@ -57,6 +59,8 @@ export interface AcpAgentOptions {
57
59
  resolveLaunch: () => Promise<AcpLaunch | undefined> | AcpLaunch | undefined;
58
60
  /** `clientInfo.name` advertised to agents. */
59
61
  clientName?: string;
62
+ /** `clientInfo.version` advertised to agents. */
63
+ clientVersion?: string;
60
64
  idleTimeoutMs?: number;
61
65
  /** Grace period for a `session/cancel` to resolve the in-flight prompt. */
62
66
  cancelGraceMs?: number;
@@ -79,7 +83,11 @@ interface AcpSession {
79
83
  cwd: string;
80
84
  envFingerprint: string;
81
85
  mcpFingerprint: string;
86
+ /** Absent when the agent takes no extra directories, so a change is moot. */
87
+ directoriesFingerprint?: string;
82
88
  launchFingerprint: string;
89
+ /** The agent's selectable settings, kept current by `config_option_update`. */
90
+ configOptions: SessionConfigOption[];
83
91
  /** From `initialize`: whether the agent accepts image content blocks. */
84
92
  imagesSupported: boolean;
85
93
  turn?: TurnPermissions;
@@ -97,11 +105,35 @@ export function acpSessionCompatible(
97
105
  existing.cwd === options.cwd &&
98
106
  existing.envFingerprint === configFingerprint(options.env) &&
99
107
  existing.mcpFingerprint === configFingerprint(options.mcpServers) &&
108
+ (existing.directoriesFingerprint === undefined ||
109
+ existing.directoriesFingerprint === directoriesFingerprint(options)) &&
100
110
  existing.launchFingerprint === launchFingerprint &&
101
111
  (!options.resumeSessionId || options.resumeSessionId === existing.acpSessionId),
102
112
  );
103
113
  }
104
114
 
115
+ /** A JSON-RPC error's `data` usually holds the cause its message only names. */
116
+ function failureMessage(error: unknown): string {
117
+ if (!(error instanceof Error)) return String(error);
118
+ const data = (error as { data?: unknown }).data;
119
+ if (data === undefined || data === null) return String(error);
120
+ const nested = (data as { message?: unknown }).message;
121
+ const detail =
122
+ typeof data === "string" ? data : typeof nested === "string" ? nested : JSON.stringify(data);
123
+ return `${error}: ${detail}`;
124
+ }
125
+
126
+ function directoriesFingerprint(options: AgentExecuteOptions): string {
127
+ return (options.additionalDirectories ?? []).join("\n");
128
+ }
129
+
130
+ /** Every value a select option offers, whether listed flat or in groups. */
131
+ function selectableValues(option: SessionConfigOption & { type: "select" }): string[] {
132
+ return option.options.flatMap((entry) =>
133
+ "options" in entry ? entry.options.map((nested) => nested.value) : [entry.value],
134
+ );
135
+ }
136
+
105
137
  /** Answer an agent permission request against the session's current turn. */
106
138
  export async function answerPermission(
107
139
  session: AcpSession,
@@ -196,24 +228,45 @@ export class AcpAgent extends SessionAgent {
196
228
  if (signal.aborted) throw new Error("turn aborted");
197
229
  init = await client.request(
198
230
  "initialize",
199
- { protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} },
231
+ {
232
+ protocolVersion: PROTOCOL_VERSION,
233
+ clientCapabilities: {},
234
+ clientInfo: {
235
+ name: this.agentOptions.clientName ?? "agent-server",
236
+ version: this.agentOptions.clientVersion ?? "0.0.0",
237
+ },
238
+ },
200
239
  INITIALIZE_TIMEOUT_MS,
201
240
  );
202
241
  if (signal.aborted) throw new Error("turn aborted");
203
- const mcpServers = toAcpMcpServers(options.mcpServers);
242
+ const capabilities = init.agentCapabilities;
243
+ const target = {
244
+ cwd: options.cwd,
245
+ mcpServers: toAcpMcpServers(options.mcpServers),
246
+ // Sent only to agents that advertise it; others keep `cwd` alone.
247
+ ...(capabilities?.sessionCapabilities?.additionalDirectories &&
248
+ options.additionalDirectories?.length && {
249
+ additionalDirectories: options.additionalDirectories,
250
+ }),
251
+ };
252
+ let configOptions: SessionConfigOption[] | null | undefined;
204
253
  if (resumeTarget) {
205
- if (!init.agentCapabilities?.sessionCapabilities?.resume) {
254
+ // `session/load` restores the same conversation and replays its
255
+ // history as updates; no turn is listening yet, so the replay is
256
+ // dropped and both paths leave the session ready for a prompt.
257
+ const method = capabilities?.sessionCapabilities?.resume
258
+ ? "session/resume"
259
+ : capabilities?.loadSession
260
+ ? "session/load"
261
+ : undefined;
262
+ if (!method) {
206
263
  throw new SessionResumeError(
207
264
  resumeTarget,
208
- "the ACP agent does not support session/resume",
265
+ "the ACP agent supports neither session/resume nor session/load",
209
266
  );
210
267
  }
211
- await client
212
- .request(
213
- "session/resume",
214
- { sessionId: resumeTarget, cwd: options.cwd, mcpServers },
215
- SESSION_REQUEST_TIMEOUT_MS,
216
- )
268
+ const resumed = await client
269
+ .request(method, { sessionId: resumeTarget, ...target }, SESSION_REQUEST_TIMEOUT_MS)
217
270
  .catch((cause: unknown) => {
218
271
  throw new SessionResumeError(
219
272
  resumeTarget,
@@ -222,13 +275,11 @@ export class AcpAgent extends SessionAgent {
222
275
  );
223
276
  });
224
277
  acpSessionId = resumeTarget;
278
+ configOptions = resumed?.configOptions;
225
279
  } else {
226
- const created = await client.request(
227
- "session/new",
228
- { cwd: options.cwd, mcpServers },
229
- SESSION_REQUEST_TIMEOUT_MS,
230
- );
280
+ const created = await client.request("session/new", target, SESSION_REQUEST_TIMEOUT_MS);
231
281
  acpSessionId = created.sessionId;
282
+ configOptions = created.configOptions;
232
283
  }
233
284
  signal.throwIfAborted();
234
285
  if (!acpSessionId) throw new Error("acp agent returned no session id");
@@ -239,10 +290,18 @@ export class AcpAgent extends SessionAgent {
239
290
  cwd: options.cwd,
240
291
  envFingerprint: configFingerprint(options.env),
241
292
  mcpFingerprint: configFingerprint(options.mcpServers),
293
+ ...(capabilities?.sessionCapabilities?.additionalDirectories && {
294
+ directoriesFingerprint: directoriesFingerprint(options),
295
+ }),
242
296
  launchFingerprint,
297
+ configOptions: configOptions ?? [],
243
298
  imagesSupported: Boolean(init.agentCapabilities?.promptCapabilities?.image),
244
299
  };
245
300
  client.setPermissionHandler((request) => answerPermission(session, request));
301
+ client.onSessionUpdate(({ sessionId, update }) => {
302
+ if (sessionId === session.acpSessionId && update.sessionUpdate === "config_option_update")
303
+ session.configOptions = update.configOptions;
304
+ });
246
305
  this.sessions.set(options.sessionId, session);
247
306
  return session;
248
307
  } catch (error) {
@@ -254,6 +313,40 @@ export class AcpAgent extends SessionAgent {
254
313
  }
255
314
  }
256
315
 
316
+ /**
317
+ * Select the requested model and thinking level through the agent's config
318
+ * options. An agent without the option keeps its own default. A model the
319
+ * agent does not offer fails the turn; thinking levels are a normalized
320
+ * vocabulary an agent may not share, so an unmatched level is left alone.
321
+ */
322
+ private async applyConfig(session: AcpSession, options: AgentExecuteOptions): Promise<void> {
323
+ const requested = [
324
+ ["model", options.model],
325
+ ["thought_level", options.thinkingLevel],
326
+ ] as const;
327
+ for (const [category, value] of requested) {
328
+ if (!value) continue;
329
+ const option = session.configOptions.find(
330
+ (candidate): candidate is SessionConfigOption & { type: "select" } =>
331
+ candidate.category === category && candidate.type === "select",
332
+ );
333
+ if (!option || option.currentValue === value) continue;
334
+ const offered = selectableValues(option);
335
+ if (!offered.includes(value)) {
336
+ if (category === "thought_level") continue;
337
+ throw new Error(
338
+ `invalid request: the ACP agent does not offer model '${value}' (available: ${offered.join(", ")})`,
339
+ );
340
+ }
341
+ const updated = await session.client.request(
342
+ "session/set_config_option",
343
+ { sessionId: session.acpSessionId, configId: option.id, value },
344
+ SESSION_REQUEST_TIMEOUT_MS,
345
+ );
346
+ session.configOptions = updated.configOptions;
347
+ }
348
+ }
349
+
257
350
  protected override async *executeTurn(
258
351
  input: AgentInput,
259
352
  options: AgentExecuteOptions,
@@ -266,6 +359,8 @@ export class AcpAgent extends SessionAgent {
266
359
  try {
267
360
  controller.signal.throwIfAborted();
268
361
  session = await this.resolveSession(options, controller.signal);
362
+ await this.applyConfig(session, options);
363
+ controller.signal.throwIfAborted();
269
364
  session.turn = {
270
365
  broker: options.onPermissionRequest,
271
366
  mode: options.permissionMode,
@@ -326,7 +421,7 @@ export class AcpAgent extends SessionAgent {
326
421
  finishCancelled();
327
422
  return;
328
423
  }
329
- queue.push({ method: "error", params: { message: String(error) } });
424
+ queue.push({ method: "error", params: { message: failureMessage(error) } });
330
425
  queue.end();
331
426
  },
332
427
  );
@@ -13,6 +13,7 @@ import {
13
13
  type StopReason,
14
14
  type StreamContext,
15
15
  type TextPart,
16
+ type TokenUsage,
16
17
  type ToolPart,
17
18
  completeToolPart,
18
19
  createReasoningPart,
@@ -54,6 +55,20 @@ function stopReasonOf(value: string | undefined): StopReason | undefined {
54
55
  : undefined;
55
56
  }
56
57
 
58
+ /**
59
+ * Per-turn usage rides the prompt response. The field is still unstable in
60
+ * v1, so most agents omit it; `usage_update` is a context gauge, not a bill.
61
+ */
62
+ function tokenUsageOf(usage: PromptResponse["usage"]): TokenUsage {
63
+ if (!usage) return { ...DEFAULT_TOKEN_USAGE };
64
+ return {
65
+ input: usage.inputTokens,
66
+ output: usage.outputTokens,
67
+ reasoning: usage.thoughtTokens ?? 0,
68
+ cache: { read: usage.cachedReadTokens ?? 0, write: usage.cachedWriteTokens ?? 0 },
69
+ };
70
+ }
71
+
57
72
  /** Flatten a tool call's content blocks (plus rawOutput) into one output string. */
58
73
  function toolOutput(content: ToolCallContent[] | null | undefined, rawOutput: unknown): string {
59
74
  const texts = (content ?? [])
@@ -75,6 +90,7 @@ export class AcpTransformer implements EventTransformer<unknown> {
75
90
  private currentMessageId?: string;
76
91
  private messageOpen = false;
77
92
 
93
+ private usage: TokenUsage = { ...DEFAULT_TOKEN_USAGE };
78
94
  private stopReason?: StopReason;
79
95
  private finishReason?: string;
80
96
  private error?: string;
@@ -89,6 +105,7 @@ export class AcpTransformer implements EventTransformer<unknown> {
89
105
  case "session/update":
90
106
  return this.onUpdate(event.params.update);
91
107
  case "session/prompt_result":
108
+ this.usage = tokenUsageOf(event.params.usage);
92
109
  this.stopReason = stopReasonOf(event.params.stopReason);
93
110
  this.finishReason = event.params.stopReason;
94
111
  return this.finalizeStreamingParts();
@@ -103,10 +120,10 @@ export class AcpTransformer implements EventTransformer<unknown> {
103
120
  }
104
121
 
105
122
  finish(): TransformResult {
106
- // ACP v1 has no per-turn token usage (the end-turn-token-usage RFD is
107
- // still draft); `usage_update` is a context-window gauge, not a bill.
108
123
  return {
109
- usage: { ...DEFAULT_TOKEN_USAGE },
124
+ usage: this.usage,
125
+ // A cancelled prompt resolves normally; nothing throws for the engine.
126
+ cancelled: this.stopReason === "cancelled",
110
127
  stopReason: this.stopReason,
111
128
  finishReason: this.finishReason,
112
129
  error: this.error,
@@ -158,7 +175,9 @@ export class AcpTransformer implements EventTransformer<unknown> {
158
175
  ? createTextPart(this.ctx, "", true)
159
176
  : createReasoningPart(this.ctx, "", true);
160
177
  this.streamParts.set(slot, part);
161
- events.push({ kind: "part-open", part });
178
+ // The processor snapshots at emit time, after the append below. Open
179
+ // with a copy so this chunk arrives once, as the delta.
180
+ events.push({ kind: "part-open", part: structuredClone(part) });
162
181
  }
163
182
  part.text += content.text;
164
183
  events.push(