@zvada/agent-server 0.3.13 → 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 +41 -0
- package/docs/deploy.md +4 -0
- package/docs/harnesses.md +37 -2
- package/package.json +4 -4
- package/src/core/agents/acp/acp-agent.ts +113 -18
- package/src/core/agents/acp/adapter.ts +23 -4
- package/src/core/agents/claude-code/options.ts +7 -1
- package/src/core/agents/codex-app-server/adapter.ts +3 -1
- package/src/core/agents/codex-sdk/adapter.ts +4 -1
- package/src/core/agents/codex-sdk/codex-sdk-agent.ts +28 -18
- package/src/core/provision/pins.ts +11 -9
- package/src/core/runtime/agent-runtime.ts +6 -2
- package/src/protocol/config.ts +2 -2
- package/src/protocol/errors.ts +30 -1
- package/src/protocol/models.ts +23 -9
- package/src/protocol/thinking.ts +15 -3
- package/src/server/acp/binding.ts +79 -4
- package/src/server/bin.ts +16 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,46 @@
|
|
|
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
|
+
|
|
3
44
|
## 0.3.13
|
|
4
45
|
|
|
5
46
|
- Add opt-in `subagentMode: "turn"` for Claude Code and Codex app-server.
|
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.
|
|
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
|
|
@@ -130,6 +160,11 @@ provide the cache breakdown without an additional native usage report.
|
|
|
130
160
|
- **MCP servers** are supported by Claude and Codex app-server. Codex SDK
|
|
131
161
|
passthrough remains unsupported. See [MCP configuration](consuming.md#configure-mcp-between-turns)
|
|
132
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.
|
|
133
168
|
- The **BYOK proxy** (`/core/proxy`) is a building block, not yet auto-wired
|
|
134
169
|
into the harnesses (they use ambient/explicit keys today).
|
|
135
170
|
- **Hook bridge** (PreToolUse/Stop decisions) is exposed for the claude
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zvada/agent-server",
|
|
3
|
-
"version": "0.3.
|
|
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.
|
|
103
|
-
"@anthropic-ai/claude-agent-sdk": "0.3.
|
|
104
|
-
"@openai/codex-sdk": "0.
|
|
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
|
|
29
|
-
//
|
|
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
|
-
{
|
|
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
|
|
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
|
-
|
|
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
|
|
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:
|
|
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:
|
|
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
|
-
|
|
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(
|
|
@@ -90,9 +90,14 @@ function toSdkPermissionMode(mode: PermissionMode | undefined): CCOptions["permi
|
|
|
90
90
|
* entirely when `env` is set, so we must spread `process.env` to preserve PATH/
|
|
91
91
|
* HOME (and thus keychain/subscription auth). We only inject ANTHROPIC_API_KEY
|
|
92
92
|
* when an explicit key is supplied — otherwise the CLI's own auth is used.
|
|
93
|
+
*
|
|
94
|
+
* A subscription login also brings that account's claude.ai connectors (Drive,
|
|
95
|
+
* Gmail, …) into every session. A turn gets the MCP servers its config names,
|
|
96
|
+
* so they stay off unless the operator's or the turn's env turns them on.
|
|
93
97
|
*/
|
|
94
98
|
function buildEnv(config: ClaudeSessionConfig): Record<string, string | undefined> {
|
|
95
99
|
return {
|
|
100
|
+
ENABLE_CLAUDEAI_MCP_SERVERS: "false",
|
|
96
101
|
...process.env,
|
|
97
102
|
...(config.apiKey ? { ANTHROPIC_API_KEY: config.apiKey } : {}),
|
|
98
103
|
...config.env,
|
|
@@ -131,7 +136,8 @@ export function buildClaudeOptions(
|
|
|
131
136
|
options.thinking = { type: "disabled" };
|
|
132
137
|
} else {
|
|
133
138
|
options.thinking = { type: "adaptive" };
|
|
134
|
-
|
|
139
|
+
// Claude's ceiling is `max`.
|
|
140
|
+
options.effort = config.thinkingLevel === "ultra" ? "max" : config.thinkingLevel;
|
|
135
141
|
}
|
|
136
142
|
}
|
|
137
143
|
if (config.resumeSessionId) {
|
|
@@ -213,7 +213,9 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
|
|
|
213
213
|
? createTextPart(this.ctx, "", true)
|
|
214
214
|
: createReasoningPart(this.ctx, "", true);
|
|
215
215
|
this.partByItem.set(itemId, part);
|
|
216
|
-
|
|
216
|
+
// The processor snapshots at emit time, after the append below. Open
|
|
217
|
+
// with a copy so this delta arrives once.
|
|
218
|
+
events.push({ kind: "part-open", part: structuredClone(part) });
|
|
217
219
|
}
|
|
218
220
|
part.text += delta;
|
|
219
221
|
events.push(
|
|
@@ -152,7 +152,10 @@ export class CodexSdkTransformer implements EventTransformer<unknown> {
|
|
|
152
152
|
// single finalized snapshot below: pushing both part-open and part-update
|
|
153
153
|
// for the same in-place-mutated object doubles the text, since the processor
|
|
154
154
|
// clones each at emit time and by then both read as "done".
|
|
155
|
-
|
|
155
|
+
// A copy: the processor snapshots at emit time, after the text set below,
|
|
156
|
+
// and a first sight that already carries text sends it as the delta.
|
|
157
|
+
if (isNew && phase !== "completed")
|
|
158
|
+
events.push({ kind: "part-open", part: structuredClone(part) });
|
|
156
159
|
|
|
157
160
|
const text = item.text ?? "";
|
|
158
161
|
const prevLen = this.textLenByItem.get(item.id) ?? 0;
|
|
@@ -216,26 +216,36 @@ export class CodexSdkAgent extends SessionAgent {
|
|
|
216
216
|
const { events } = await live.thread.runStreamed(toCodexInput(input), {
|
|
217
217
|
signal: controller.signal,
|
|
218
218
|
});
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
219
|
+
// `codex exec` reports a fatal turn on its stream, then exits non-zero; the
|
|
220
|
+
// SDK throws for that exit with only stderr. Keep the reported cause.
|
|
221
|
+
let failure: string | undefined;
|
|
222
|
+
try {
|
|
223
|
+
for await (const event of events as AsyncGenerator<ThreadEvent>) {
|
|
224
|
+
if (event.type === "turn.failed") failure = event.error.message;
|
|
225
|
+
if (event.type === "thread.started") {
|
|
226
|
+
if (options.resumeSessionId && event.thread_id !== options.resumeSessionId) {
|
|
227
|
+
// The SDK mutates Thread.id before yielding this event. Discard
|
|
228
|
+
// that wrapper; the retained resume target remains unchanged.
|
|
229
|
+
if (this.threads.get(options.sessionId) === live)
|
|
230
|
+
this.threads.delete(options.sessionId);
|
|
231
|
+
controller.abort();
|
|
232
|
+
throw new SessionResumeError(
|
|
233
|
+
options.resumeSessionId,
|
|
234
|
+
`Codex returned a different thread: ${event.thread_id}`,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
if (!reported) {
|
|
238
|
+
reported = true;
|
|
239
|
+
options.onNativeSession?.(event.thread_id, {
|
|
240
|
+
resumed: Boolean(options.resumeSessionId),
|
|
241
|
+
});
|
|
242
|
+
}
|
|
236
243
|
}
|
|
244
|
+
yield event as RawAgentEvent;
|
|
237
245
|
}
|
|
238
|
-
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (failure === undefined || controller.signal.aborted) throw error;
|
|
248
|
+
throw new Error(failure, { cause: error });
|
|
239
249
|
}
|
|
240
250
|
}
|
|
241
251
|
|
|
@@ -27,15 +27,17 @@ export type CliTool = (typeof CLI_TOOLS)[number];
|
|
|
27
27
|
* set `provision.pins.codex` to their SDK's vendored version.
|
|
28
28
|
*/
|
|
29
29
|
export const DEFAULT_PINS: Record<CliTool, string> = {
|
|
30
|
-
//
|
|
31
|
-
// summarized`, so reasoning parts carry text
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
claude: "0.3.
|
|
35
|
-
// 0.
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
|
|
30
|
+
// 0.3.288 verified 2026-10-03: the paired CLI honors `--thinking-display
|
|
31
|
+
// summarized`, so reasoning parts carry text (2.1.233 ignored the flag and
|
|
32
|
+
// streamed token-estimate placeholders). Re-check thinking summaries on
|
|
33
|
+
// every bump (see options.ts extraArgs).
|
|
34
|
+
claude: "0.3.288",
|
|
35
|
+
// 0.160.0 re-verified 2026-10-03 against generate-ts: thread/turn/item
|
|
36
|
+
// methods, token usage, approvals, and host-managed ChatGPT auth changed
|
|
37
|
+
// only additively since 0.153.4. The GPT-6 family needs 0.159 or newer.
|
|
38
|
+
// Since 0.160 a thread has one writer: resuming it from a second process
|
|
39
|
+
// fails until the first releases it.
|
|
40
|
+
codex: "0.160.0",
|
|
39
41
|
};
|
|
40
42
|
|
|
41
43
|
/**
|
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
classifyError,
|
|
4
4
|
isCancellation,
|
|
5
5
|
isRecoverable,
|
|
6
|
+
readableErrorMessage,
|
|
6
7
|
} from "../../protocol/errors.ts";
|
|
7
8
|
import type {
|
|
8
9
|
AgentCapabilities,
|
|
@@ -443,7 +444,7 @@ export class AgentRuntime {
|
|
|
443
444
|
cancelled = isCancellation(err);
|
|
444
445
|
if (!cancelled) {
|
|
445
446
|
const category = classifyError(err);
|
|
446
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
447
|
+
const message = readableErrorMessage(err instanceof Error ? err.message : String(err));
|
|
447
448
|
errored = { category, message };
|
|
448
449
|
await emit({
|
|
449
450
|
type: "error",
|
|
@@ -463,7 +464,10 @@ export class AgentRuntime {
|
|
|
463
464
|
const result = transformer.finish();
|
|
464
465
|
cancelled = cancelled || Boolean(result.cancelled);
|
|
465
466
|
if (result.error && !errored && !cancelled) {
|
|
466
|
-
errored = {
|
|
467
|
+
errored = {
|
|
468
|
+
category: classifyError(new Error(result.error)),
|
|
469
|
+
message: readableErrorMessage(result.error),
|
|
470
|
+
};
|
|
467
471
|
}
|
|
468
472
|
const stopReason: StopReason = cancelled
|
|
469
473
|
? "cancelled"
|
package/src/protocol/config.ts
CHANGED
|
@@ -51,8 +51,8 @@ export const RunConfigSchema = z.object({
|
|
|
51
51
|
cwd: z.string(),
|
|
52
52
|
/**
|
|
53
53
|
* Extra directories the agent may access beyond `cwd`. Mapped by the
|
|
54
|
-
* claude-code and codex-sdk harnesses
|
|
55
|
-
* native equivalent
|
|
54
|
+
* claude-code and codex-sdk harnesses, and by acp for agents that advertise
|
|
55
|
+
* the capability; codex-app-server has no native equivalent and ignores it.
|
|
56
56
|
*/
|
|
57
57
|
additionalDirectories: z.array(z.string()).optional(),
|
|
58
58
|
systemPromptAppend: z.string().optional(),
|
package/src/protocol/errors.ts
CHANGED
|
@@ -72,7 +72,15 @@ const RULES: ReadonlyArray<[ErrorCategory, readonly string[]]> = [
|
|
|
72
72
|
],
|
|
73
73
|
[
|
|
74
74
|
"invalid_request",
|
|
75
|
-
[
|
|
75
|
+
[
|
|
76
|
+
"invalid request",
|
|
77
|
+
"invalid_request_error",
|
|
78
|
+
"status 400",
|
|
79
|
+
"http 400",
|
|
80
|
+
"bad request",
|
|
81
|
+
// Claude Code's wording for an unknown or inaccessible model.
|
|
82
|
+
"issue with the selected model",
|
|
83
|
+
],
|
|
76
84
|
],
|
|
77
85
|
["process_exit", ["exited with code", "process exited", "spawn", "enoent", "killed"]],
|
|
78
86
|
];
|
|
@@ -94,6 +102,27 @@ export function classifyError(error: unknown): ErrorCategory {
|
|
|
94
102
|
return "internal";
|
|
95
103
|
}
|
|
96
104
|
|
|
105
|
+
/**
|
|
106
|
+
* The message to show for a failure. Providers often answer with a JSON
|
|
107
|
+
* envelope (`{"error":{"message":…}}`), sometimes behind a transport prefix;
|
|
108
|
+
* its message is the readable part. Classify the raw text first: the envelope
|
|
109
|
+
* carries the status and error type the rules match on.
|
|
110
|
+
*/
|
|
111
|
+
export function readableErrorMessage(message: string): string {
|
|
112
|
+
const start = message.indexOf("{");
|
|
113
|
+
if (start < 0) return message;
|
|
114
|
+
try {
|
|
115
|
+
const body = JSON.parse(message.slice(start)) as {
|
|
116
|
+
error?: { message?: unknown };
|
|
117
|
+
message?: unknown;
|
|
118
|
+
};
|
|
119
|
+
const inner = body.error?.message ?? body.message;
|
|
120
|
+
return typeof inner === "string" && inner ? inner : message;
|
|
121
|
+
} catch {
|
|
122
|
+
return message;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
97
126
|
/** Whether a turn can plausibly be retried after this error. */
|
|
98
127
|
export function isRecoverable(category: ErrorCategory): boolean {
|
|
99
128
|
return category === "rate_limit" || category === "network";
|
package/src/protocol/models.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentHarness } from "./harness.ts";
|
|
2
|
-
import type
|
|
2
|
+
import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Advisory catalog of known-good models per harness. `model` on a RunConfig is
|
|
@@ -13,7 +13,16 @@ export interface ModelInfo {
|
|
|
13
13
|
readonly thinking: readonly ThinkingLevel[];
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
const ALL: readonly ThinkingLevel[] =
|
|
16
|
+
const ALL: readonly ThinkingLevel[] = THINKING_LEVELS;
|
|
17
|
+
|
|
18
|
+
// As listed by Codex CLI 0.160.0. The GPT-6 family needs CLI 0.159 or newer.
|
|
19
|
+
const CODEX_MODELS: ReadonlyArray<readonly [id: string, label: string]> = [
|
|
20
|
+
["gpt-6.1-sol", "GPT-6.1 Sol"],
|
|
21
|
+
["gpt-6-astra", "GPT-6 Astra"],
|
|
22
|
+
["gpt-6-sol", "GPT-6 Sol"],
|
|
23
|
+
["gpt-6-luna", "GPT-6 Luna"],
|
|
24
|
+
["gpt-5.5", "GPT-5.5"],
|
|
25
|
+
];
|
|
17
26
|
|
|
18
27
|
export const MODEL_CATALOG: readonly ModelInfo[] = [
|
|
19
28
|
// Claude (the claude CLI also accepts the bare aliases "sonnet"/"opus"/"haiku").
|
|
@@ -21,18 +30,23 @@ export const MODEL_CATALOG: readonly ModelInfo[] = [
|
|
|
21
30
|
{ id: "opus", harness: "claude-code", label: "Claude Opus (latest)", thinking: ALL },
|
|
22
31
|
{ id: "haiku", harness: "claude-code", label: "Claude Haiku (latest)", thinking: ALL },
|
|
23
32
|
// Codex (shared between codex-sdk and codex-app-server).
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
33
|
+
...CODEX_MODELS.flatMap(([id, label]) =>
|
|
34
|
+
(["codex-sdk", "codex-app-server"] as const).map((harness) => ({
|
|
35
|
+
id,
|
|
36
|
+
harness,
|
|
37
|
+
label,
|
|
38
|
+
thinking: ALL,
|
|
39
|
+
})),
|
|
40
|
+
),
|
|
28
41
|
];
|
|
29
42
|
|
|
30
43
|
/**
|
|
31
|
-
*
|
|
32
|
-
*
|
|
44
|
+
* The model a turn runs on when its config names none. `undefined` means the
|
|
45
|
+
* harness's CLI picks: Claude Code its own default for the account, Codex the
|
|
46
|
+
* one in `~/.codex/config.toml`. The engine never substitutes a model.
|
|
33
47
|
*/
|
|
34
48
|
export const DEFAULT_MODELS: Record<AgentHarness, string | undefined> = {
|
|
35
|
-
"claude-code":
|
|
49
|
+
"claude-code": undefined,
|
|
36
50
|
"codex-sdk": undefined,
|
|
37
51
|
"codex-app-server": undefined,
|
|
38
52
|
// ACP v1 has no portable model parameter (selection is agent-defined via
|
package/src/protocol/thinking.ts
CHANGED
|
@@ -3,9 +3,10 @@ import { z } from "zod";
|
|
|
3
3
|
/**
|
|
4
4
|
* A single, harness-agnostic reasoning dial. Each harness maps it to its own
|
|
5
5
|
* native control: Claude -> adaptive `thinking` + `effort`; Codex ->
|
|
6
|
-
* `ReasoningEffort`.
|
|
6
|
+
* `ReasoningEffort`. The top levels depend on the model: Claude's ceiling is
|
|
7
|
+
* `max` (it runs `ultra` as `max`), and not every Codex model offers `ultra`.
|
|
7
8
|
*/
|
|
8
|
-
export const THINKING_LEVELS = ["off", "low", "medium", "high", "xhigh"] as const;
|
|
9
|
+
export const THINKING_LEVELS = ["off", "low", "medium", "high", "xhigh", "max", "ultra"] as const;
|
|
9
10
|
export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
|
|
10
11
|
export const ThinkingLevelSchema = z.enum(THINKING_LEVELS);
|
|
11
12
|
export const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
|
|
@@ -15,7 +16,14 @@ export function isThinkingLevel(v: string): v is ThinkingLevel {
|
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
/** Codex reasoning-effort string for a level (matches the `ReasoningEffort` enum). */
|
|
18
|
-
export type CodexReasoningEffort =
|
|
19
|
+
export type CodexReasoningEffort =
|
|
20
|
+
| "minimal"
|
|
21
|
+
| "low"
|
|
22
|
+
| "medium"
|
|
23
|
+
| "high"
|
|
24
|
+
| "xhigh"
|
|
25
|
+
| "max"
|
|
26
|
+
| "ultra";
|
|
19
27
|
export function codexReasoningEffort(level: ThinkingLevel): CodexReasoningEffort {
|
|
20
28
|
switch (level) {
|
|
21
29
|
case "off":
|
|
@@ -28,5 +36,9 @@ export function codexReasoningEffort(level: ThinkingLevel): CodexReasoningEffort
|
|
|
28
36
|
return "high";
|
|
29
37
|
case "xhigh":
|
|
30
38
|
return "xhigh";
|
|
39
|
+
case "max":
|
|
40
|
+
return "max";
|
|
41
|
+
case "ultra":
|
|
42
|
+
return "ultra";
|
|
31
43
|
}
|
|
32
44
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
1
3
|
import { Readable, Writable } from "node:stream";
|
|
2
4
|
import type {
|
|
3
5
|
AgentApp,
|
|
@@ -12,6 +14,7 @@ import type {
|
|
|
12
14
|
LifecycleEvent,
|
|
13
15
|
PermissionMode,
|
|
14
16
|
PermissionOutcome,
|
|
17
|
+
TokenUsage,
|
|
15
18
|
} from "../../protocol/index.ts";
|
|
16
19
|
import { AcpUpdateTranslator, fromAcpMcpServers, fromPromptBlocks } from "./translate.ts";
|
|
17
20
|
|
|
@@ -27,11 +30,35 @@ export interface AcpBindingOptions {
|
|
|
27
30
|
permissionMode?: PermissionMode;
|
|
28
31
|
name?: string;
|
|
29
32
|
version?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Where to record each session's native id so `session/resume` works after
|
|
35
|
+
* this process restarts. Absent: sessions resume only within the process.
|
|
36
|
+
*/
|
|
37
|
+
sessionDir?: string;
|
|
30
38
|
}
|
|
31
39
|
|
|
32
40
|
interface BoundSession {
|
|
33
41
|
cwd: string;
|
|
34
42
|
mcpServers?: ReturnType<typeof fromAcpMcpServers>;
|
|
43
|
+
/** Native conversation to continue on the next prompt (restored sessions). */
|
|
44
|
+
resumeSessionId?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Session ids become file names; accept only what this binding mints. */
|
|
48
|
+
const SESSION_ID = /^[\w-]{1,128}$/;
|
|
49
|
+
|
|
50
|
+
/** The engine's disjoint token buckets as ACP's (still unstable) turn usage. */
|
|
51
|
+
function toAcpUsage(usage: TokenUsage): NonNullable<PromptResponse["usage"]> {
|
|
52
|
+
const read = usage.cache?.read ?? 0;
|
|
53
|
+
const write = usage.cache?.write ?? 0;
|
|
54
|
+
return {
|
|
55
|
+
totalTokens: usage.input + usage.output + read + write,
|
|
56
|
+
inputTokens: usage.input,
|
|
57
|
+
outputTokens: usage.output,
|
|
58
|
+
...(usage.reasoning !== undefined && { thoughtTokens: usage.reasoning }),
|
|
59
|
+
cachedReadTokens: read,
|
|
60
|
+
cachedWriteTokens: write,
|
|
61
|
+
};
|
|
35
62
|
}
|
|
36
63
|
|
|
37
64
|
/**
|
|
@@ -41,8 +68,9 @@ interface BoundSession {
|
|
|
41
68
|
* integration. `session/prompt` runs one engine turn; LifecycleEvents stream
|
|
42
69
|
* out as `session/update`; engine-brokered permissions become
|
|
43
70
|
* `session/request_permission` round-trips (identical option vocabulary).
|
|
44
|
-
*
|
|
45
|
-
*
|
|
71
|
+
* An ACP sessionId stays valid for the binding's lifetime; with `sessionDir`
|
|
72
|
+
* its native conversation is recorded, so `session/resume` also works after a
|
|
73
|
+
* restart.
|
|
46
74
|
*/
|
|
47
75
|
export async function createAcpAgentApp(options: AcpBindingOptions): Promise<AgentApp> {
|
|
48
76
|
const acp = await import("@agentclientprotocol/sdk");
|
|
@@ -59,6 +87,37 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
|
|
|
59
87
|
}
|
|
60
88
|
};
|
|
61
89
|
|
|
90
|
+
const recordPath = (sessionId: string): string | undefined =>
|
|
91
|
+
options.sessionDir && SESSION_ID.test(sessionId)
|
|
92
|
+
? join(options.sessionDir, `${sessionId}.json`)
|
|
93
|
+
: undefined;
|
|
94
|
+
const remember = async (sessionId: string, nativeSessionId: string): Promise<void> => {
|
|
95
|
+
const path = recordPath(sessionId);
|
|
96
|
+
if (!path || !options.sessionDir) return;
|
|
97
|
+
// Write then rename: a crash mid-write must not leave a torn record.
|
|
98
|
+
const draft = `${path}.${process.pid}.tmp`;
|
|
99
|
+
try {
|
|
100
|
+
await mkdir(options.sessionDir, { recursive: true, mode: 0o700 });
|
|
101
|
+
await writeFile(draft, JSON.stringify({ harness, nativeSessionId }), { mode: 0o600 });
|
|
102
|
+
await rename(draft, path);
|
|
103
|
+
} catch {
|
|
104
|
+
// Best effort: without the record the session resumes only in-process.
|
|
105
|
+
await rm(draft, { force: true }).catch(() => {});
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const recall = async (sessionId: string): Promise<string | undefined> => {
|
|
109
|
+
const path = recordPath(sessionId);
|
|
110
|
+
if (!path) return undefined;
|
|
111
|
+
try {
|
|
112
|
+
const record = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
|
|
113
|
+
return record.harness === harness && typeof record.nativeSessionId === "string"
|
|
114
|
+
? record.nativeSessionId
|
|
115
|
+
: undefined;
|
|
116
|
+
} catch {
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
62
121
|
const requireSession = (sessionId: string): BoundSession => {
|
|
63
122
|
const session = sessions.get(sessionId);
|
|
64
123
|
if (!session) throw acp.RequestError.resourceNotFound(sessionId);
|
|
@@ -72,6 +131,8 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
|
|
|
72
131
|
agentInfo: { name: options.name ?? "agent-server", version: options.version ?? "0.0.0" },
|
|
73
132
|
agentCapabilities: {
|
|
74
133
|
promptCapabilities: { image: true },
|
|
134
|
+
// Clients send HTTP/SSE servers only to agents that advertise them.
|
|
135
|
+
...(harness === "claude-code" && { mcpCapabilities: { http: true, sse: true } }),
|
|
75
136
|
sessionCapabilities: { resume: {}, close: {} },
|
|
76
137
|
},
|
|
77
138
|
authMethods: [],
|
|
@@ -85,9 +146,15 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
|
|
|
85
146
|
});
|
|
86
147
|
return { sessionId };
|
|
87
148
|
})
|
|
88
|
-
.onRequest("session/resume", (ctx) => {
|
|
89
|
-
const session = requireSession(ctx.params.sessionId);
|
|
149
|
+
.onRequest("session/resume", async (ctx) => {
|
|
90
150
|
checkMcpSupport(ctx.params.mcpServers);
|
|
151
|
+
let session = sessions.get(ctx.params.sessionId);
|
|
152
|
+
if (!session) {
|
|
153
|
+
const resumeSessionId = await recall(ctx.params.sessionId);
|
|
154
|
+
if (!resumeSessionId) throw acp.RequestError.resourceNotFound(ctx.params.sessionId);
|
|
155
|
+
session = { cwd: ctx.params.cwd, resumeSessionId };
|
|
156
|
+
sessions.set(ctx.params.sessionId, session);
|
|
157
|
+
}
|
|
91
158
|
session.cwd = ctx.params.cwd;
|
|
92
159
|
if (ctx.params.mcpServers) session.mcpServers = fromAcpMcpServers(ctx.params.mcpServers);
|
|
93
160
|
return {};
|
|
@@ -152,10 +219,16 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
|
|
|
152
219
|
model: options.model,
|
|
153
220
|
permissionMode: options.permissionMode ?? "default",
|
|
154
221
|
mcpServers: session.mcpServers,
|
|
222
|
+
resumeSessionId: session.resumeSessionId,
|
|
155
223
|
},
|
|
156
224
|
},
|
|
157
225
|
sink,
|
|
158
226
|
);
|
|
227
|
+
if (summary.nativeSessionId) {
|
|
228
|
+
session.resumeSessionId = undefined;
|
|
229
|
+
await remember(ctx.params.sessionId, summary.nativeSessionId);
|
|
230
|
+
}
|
|
231
|
+
const usage = toAcpUsage(summary.usage);
|
|
159
232
|
// ACP v1's StopReason set is closed and has no `error` member. Map our
|
|
160
233
|
// open stopReason onto it: `error` reports as an ended turn with the
|
|
161
234
|
// failure in `_meta` (an ACP client must see a stop, not a JSON-RPC
|
|
@@ -170,6 +243,7 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
|
|
|
170
243
|
if (summary.stopReason === "error") {
|
|
171
244
|
return {
|
|
172
245
|
stopReason: "end_turn",
|
|
246
|
+
usage,
|
|
173
247
|
_meta: {
|
|
174
248
|
"zvada.dev/error": summary.error ?? { category: "internal", message: "turn failed" },
|
|
175
249
|
},
|
|
@@ -179,6 +253,7 @@ export async function createAcpAgentApp(options: AcpBindingOptions): Promise<Age
|
|
|
179
253
|
stopReason: (acpStopReasons.has(summary.stopReason)
|
|
180
254
|
? summary.stopReason
|
|
181
255
|
: "end_turn") as PromptResponse["stopReason"],
|
|
256
|
+
usage,
|
|
182
257
|
};
|
|
183
258
|
});
|
|
184
259
|
}
|
package/src/server/bin.ts
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
// agent-server install # prefetch the pinned agent CLIs
|
|
12
12
|
//
|
|
13
13
|
// All logs go to stderr; stdout is reserved for the wire in stdio mode.
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
14
16
|
import pkg from "../../package.json" with { type: "json" };
|
|
15
17
|
import {
|
|
16
18
|
KNOWN_ACP_AGENTS,
|
|
@@ -61,7 +63,8 @@ function usage(exitCode: number): never {
|
|
|
61
63
|
" --version, --help",
|
|
62
64
|
"",
|
|
63
65
|
"env: CLAUDE_CLI_PATH / CODEX_CLI_PATH (explicit binaries),",
|
|
64
|
-
" AGENT_SERVER_PROVISION, AGENT_SERVER_CACHE_DIR, AGENT_SERVER_NPM_REGISTRY",
|
|
66
|
+
" AGENT_SERVER_PROVISION, AGENT_SERVER_CACHE_DIR, AGENT_SERVER_NPM_REGISTRY,",
|
|
67
|
+
" AGENT_SERVER_ACP_SESSION_DIR (--acp: where resumable session ids are kept)",
|
|
65
68
|
].join("\n"),
|
|
66
69
|
);
|
|
67
70
|
process.exit(exitCode);
|
|
@@ -176,7 +179,18 @@ if (args.mode === "acp") {
|
|
|
176
179
|
// Speak ACP v1 on stdio: this process IS the agent (Zed-spawnable).
|
|
177
180
|
const { serveAcpStdio } = await import("./acp/binding.ts");
|
|
178
181
|
const frontedHarness = harnesses?.[0] ?? "claude-code";
|
|
179
|
-
const connection = await serveAcpStdio({
|
|
182
|
+
const connection = await serveAcpStdio({
|
|
183
|
+
runtime,
|
|
184
|
+
harness: frontedHarness,
|
|
185
|
+
version: VERSION,
|
|
186
|
+
sessionDir:
|
|
187
|
+
process.env.AGENT_SERVER_ACP_SESSION_DIR ??
|
|
188
|
+
join(
|
|
189
|
+
process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"),
|
|
190
|
+
"agent-server",
|
|
191
|
+
"acp-sessions",
|
|
192
|
+
),
|
|
193
|
+
});
|
|
180
194
|
console.error(`agent-server ${VERSION} speaking ACP v1 on stdio (harness: ${frontedHarness})`);
|
|
181
195
|
shutdown = () => void runtime.shutdown().then(() => process.exit(0));
|
|
182
196
|
// Client hung up — shut down cleanly (mirrors the stdio wire transport).
|