@zvada/agent-server 0.3.13 → 0.3.15
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 +60 -0
- package/docs/deploy.md +4 -0
- package/docs/harnesses.md +42 -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-app-server/codex-app-server-agent.ts +93 -4
- package/src/core/agents/codex-sdk/adapter.ts +4 -1
- package/src/core/agents/codex-sdk/codex-sdk-agent.ts +37 -21
- package/src/core/provision/pins.ts +12 -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 +55 -13
- package/src/protocol/thinking.ts +51 -16
- package/src/server/acp/binding.ts +79 -4
- package/src/server/bin.ts +16 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,65 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.15
|
|
4
|
+
|
|
5
|
+
- Codex runs the nearest thinking level its model accepts. `off` sent effort
|
|
6
|
+
`minimal`, which every current Codex model rejects, so the turn failed
|
|
7
|
+
("Unsupported value: 'minimal' is not supported with the 'gpt-6-astra'
|
|
8
|
+
model"); it now sends the model's lowest effort. A level above the model's
|
|
9
|
+
top becomes that top. `codex-app-server` asks the CLI (`model/list`) what the
|
|
10
|
+
thread's model accepts, including a model `~/.codex/config.toml` selected;
|
|
11
|
+
`codex-sdk` uses the catalog.
|
|
12
|
+
- `MODEL_CATALOG` lists each model's real levels instead of all seven for
|
|
13
|
+
every model, and adds `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna` and
|
|
14
|
+
Claude's `fable` alias. Codex models offer no `off`; Claude models offer no
|
|
15
|
+
`ultra` (it runs as `max`); Haiku lists none. `gpt-5.5` is labeled API-key
|
|
16
|
+
only: Codex refuses it for a ChatGPT login.
|
|
17
|
+
- Add `clampThinkingLevel(level, supported)` and `modelThinkingLevels(harness,
|
|
18
|
+
model)` for pickers that switch models.
|
|
19
|
+
- Development only: lift `vite` (through vitest) to 8.3 past a newly
|
|
20
|
+
published advisory so the audit passes.
|
|
21
|
+
|
|
22
|
+
## 0.3.14
|
|
23
|
+
|
|
24
|
+
- Update the managed CLIs and development SDKs: Codex 0.160.0 and Claude Agent
|
|
25
|
+
SDK 0.3.288. Codex 0.153.4 rejected the GPT-6.1 models a current
|
|
26
|
+
`~/.codex/config.toml` selects, so every default Codex turn failed on a
|
|
27
|
+
machine with a newer Codex installed. Claude thinking summaries flow again
|
|
28
|
+
on the newer CLI, which was the reason its pin was held.
|
|
29
|
+
- Report the failure Codex streamed when a `codex-sdk` turn fails. The turn
|
|
30
|
+
ended as `process_exit` with the CLI's stderr ("Reading prompt from
|
|
31
|
+
stdin..."); it now carries the provider's message and category, as
|
|
32
|
+
`codex-app-server` already did.
|
|
33
|
+
- Classify a model Claude Code rejects as `invalid_request` instead of
|
|
34
|
+
`internal`.
|
|
35
|
+
- Stream a part's first text once in the `acp`, `codex-app-server` and
|
|
36
|
+
`codex-sdk` harnesses. When a part arrived with text already in hand, its
|
|
37
|
+
opening snapshot and its first delta both carried that text, so clients
|
|
38
|
+
showed it twice until the final snapshot, and kept it if none came.
|
|
39
|
+
- Keep the logged-in account's claude.ai connectors (Drive, Gmail, …) out of
|
|
40
|
+
Claude sessions. They loaded into every turn. Set
|
|
41
|
+
`ENABLE_CLAUDEAI_MCP_SERVERS=true` in the env to load them.
|
|
42
|
+
- Add the `max` and `ultra` thinking levels. Claude runs `ultra` as `max`.
|
|
43
|
+
- Show a provider's message for a failed turn instead of its JSON envelope.
|
|
44
|
+
- `DEFAULT_MODELS["claude-code"]` is now `undefined`: the engine never applied
|
|
45
|
+
the `sonnet` it listed, and turns ran on the CLI's own default.
|
|
46
|
+
- Refresh the advisory Codex model catalog: add the GPT-6 family and drop
|
|
47
|
+
`gpt-5.5-codex`, which the provider rejects.
|
|
48
|
+
- ACP harness (SDK 1.7.0): fall back to `session/load` for agents without
|
|
49
|
+
`session/resume`; select `model` and `thinkingLevel` through the agent's
|
|
50
|
+
config options; send `additionalDirectories` to agents that take them;
|
|
51
|
+
identify the client in `initialize`; read per-turn usage when the agent
|
|
52
|
+
reports it; report a cancelled prompt as a cancelled turn; include the
|
|
53
|
+
JSON-RPC error detail when a prompt fails.
|
|
54
|
+
- ACP server binding: `session/resume` works after a restart (native ids are
|
|
55
|
+
recorded under `AGENT_SERVER_ACP_SESSION_DIR`); the prompt response carries
|
|
56
|
+
the turn's usage; HTTP/SSE MCP is advertised when fronting `claude-code`.
|
|
57
|
+
- Codex 0.160 allows one writer per thread. Resuming a thread from a second
|
|
58
|
+
process fails with `resume_failed` until the first session is closed.
|
|
59
|
+
- Lift `@modelcontextprotocol/sdk` to 1.32, `proxy-addr` to 2.0.8 and
|
|
60
|
+
`source-map-js` to 1.2.2, past published advisories, and align the CLI app
|
|
61
|
+
on the package's Claude Agent SDK.
|
|
62
|
+
|
|
3
63
|
## 0.3.13
|
|
4
64
|
|
|
5
65
|
- 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,26 @@ 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`), and Claude Code silently lowers a level its model lacks.
|
|
72
|
+
Codex runs the nearest level the model accepts: `off` becomes the model's
|
|
73
|
+
lowest (current models reject `minimal`), and a level above its top becomes
|
|
74
|
+
that top. `codex-app-server` reads what each model accepts from `model/list`;
|
|
75
|
+
`codex-sdk` uses `MODEL_CATALOG`. `MODEL_CATALOG` lists each model's own
|
|
76
|
+
levels, and `clampThinkingLevel` picks the nearest one when a picker switches
|
|
77
|
+
models.
|
|
78
|
+
|
|
44
79
|
Consult `runtime.capabilities(harness)` before relying on a capability.
|
|
45
80
|
|
|
46
81
|
## Host-managed Codex authentication
|
|
@@ -70,7 +105,7 @@ fresh access credentials, the callback must return the same ChatGPT account;
|
|
|
70
105
|
the engine rejects mismatched identities and refreshes that outlive their turn.
|
|
71
106
|
An absent previous-account hint resolves to the turn's selected account. No
|
|
72
107
|
credentials or callbacks are added to `RunConfig` or the engine's public wire.
|
|
73
|
-
The protocol was checked against Codex CLI 0.
|
|
108
|
+
The protocol was checked against Codex CLI 0.160.0 and the
|
|
74
109
|
[official app-server authentication documentation](https://learn.chatgpt.com/docs/app-server#3c-log-in-with-externally-managed-chatgpt-tokens-chatgptauthtokens).
|
|
75
110
|
|
|
76
111
|
## Payload notes
|
|
@@ -130,6 +165,11 @@ provide the cache breakdown without an additional native usage report.
|
|
|
130
165
|
- **MCP servers** are supported by Claude and Codex app-server. Codex SDK
|
|
131
166
|
passthrough remains unsupported. See [MCP configuration](consuming.md#configure-mcp-between-turns)
|
|
132
167
|
for Codex home ownership, supported transports, and live-update behavior.
|
|
168
|
+
- **Codex app-server threads have one writer** (CLI 0.160 and newer). A
|
|
169
|
+
thread still loaded by a live session cannot be resumed from another
|
|
170
|
+
process; the turn fails with `resume_failed` ("already has an active
|
|
171
|
+
writer"). Close the first session (`session/close`) or let its process end
|
|
172
|
+
before resuming elsewhere.
|
|
133
173
|
- The **BYOK proxy** (`/core/proxy`) is a building block, not yet auto-wired
|
|
134
174
|
into the harnesses (they use ambient/explicit keys today).
|
|
135
175
|
- **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.15",
|
|
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(
|
|
@@ -6,8 +6,14 @@ import type {
|
|
|
6
6
|
AgentInput,
|
|
7
7
|
PermissionMode,
|
|
8
8
|
PermissionToolCall,
|
|
9
|
+
ThinkingLevel,
|
|
10
|
+
} from "../../../protocol/index.ts";
|
|
11
|
+
import {
|
|
12
|
+
AsyncQueue,
|
|
13
|
+
codexReasoningEffort,
|
|
14
|
+
isThinkingLevel,
|
|
15
|
+
modelThinkingLevels,
|
|
9
16
|
} from "../../../protocol/index.ts";
|
|
10
|
-
import { AsyncQueue, codexReasoningEffort } from "../../../protocol/index.ts";
|
|
11
17
|
import { SessionResumeError } from "../../utils/errors.ts";
|
|
12
18
|
import type {
|
|
13
19
|
AgentExecuteOptions,
|
|
@@ -60,6 +66,16 @@ export interface AppServerSession {
|
|
|
60
66
|
/** Credentials and permission broker belong only to the current execute. */
|
|
61
67
|
turn?: AppServerTurn;
|
|
62
68
|
idleTimer?: ReturnType<typeof setTimeout>;
|
|
69
|
+
/** The thread's model, as Codex resolved it (config.toml included). */
|
|
70
|
+
model?: string;
|
|
71
|
+
/** What each model accepts, from this process's `model/list`; read once. */
|
|
72
|
+
modelEfforts?: Promise<ReadonlyMap<string, CodexModelThinking> | undefined>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A model's thinking levels, and the native effort that `off` means for it. */
|
|
76
|
+
export interface CodexModelThinking {
|
|
77
|
+
levels: readonly ThinkingLevel[];
|
|
78
|
+
off?: "none" | "minimal";
|
|
63
79
|
}
|
|
64
80
|
|
|
65
81
|
interface AppServerTurn {
|
|
@@ -225,6 +241,58 @@ export function appServerNotificationEndsTurn(notification: CodexNotification):
|
|
|
225
241
|
);
|
|
226
242
|
}
|
|
227
243
|
|
|
244
|
+
const MODEL_LIST_TIMEOUT_MS = 5_000;
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The thinking levels each model the logged-in account can run accepts, from
|
|
248
|
+
* `model/list`. Codex's `none` or `minimal` is `off`, and is remembered so
|
|
249
|
+
* `off` sends the value the model advertised (`none` when it offers both).
|
|
250
|
+
* `undefined` when the CLI cannot answer; callers fall back to `MODEL_CATALOG`.
|
|
251
|
+
*/
|
|
252
|
+
export async function listModelThinking(
|
|
253
|
+
client: Pick<CodexAppServerClient, "request">,
|
|
254
|
+
): Promise<ReadonlyMap<string, CodexModelThinking> | undefined> {
|
|
255
|
+
const models = new Map<string, CodexModelThinking>();
|
|
256
|
+
let cursor: string | undefined;
|
|
257
|
+
try {
|
|
258
|
+
for (let page = 0; page < 10; page++) {
|
|
259
|
+
const result = (await client.request(
|
|
260
|
+
"model/list",
|
|
261
|
+
{ includeHidden: true, ...(cursor && { cursor }) },
|
|
262
|
+
MODEL_LIST_TIMEOUT_MS,
|
|
263
|
+
)) as { data?: unknown; nextCursor?: unknown } | undefined;
|
|
264
|
+
if (!Array.isArray(result?.data)) break;
|
|
265
|
+
for (const entry of result.data as Array<Record<string, unknown>>) {
|
|
266
|
+
const efforts = Array.isArray(entry.supportedReasoningEfforts)
|
|
267
|
+
? (entry.supportedReasoningEfforts as Array<{ reasoningEffort?: unknown }>).map(
|
|
268
|
+
({ reasoningEffort }) => reasoningEffort,
|
|
269
|
+
)
|
|
270
|
+
: [];
|
|
271
|
+
const off = efforts.includes("none")
|
|
272
|
+
? "none"
|
|
273
|
+
: efforts.includes("minimal")
|
|
274
|
+
? "minimal"
|
|
275
|
+
: undefined;
|
|
276
|
+
const levels: ThinkingLevel[] = [
|
|
277
|
+
...(off ? (["off"] as const) : []),
|
|
278
|
+
...efforts.filter(
|
|
279
|
+
(effort): effort is ThinkingLevel =>
|
|
280
|
+
typeof effort === "string" && effort !== "off" && isThinkingLevel(effort),
|
|
281
|
+
),
|
|
282
|
+
];
|
|
283
|
+
for (const name of [entry.model, entry.id])
|
|
284
|
+
if (typeof name === "string" && levels.length)
|
|
285
|
+
models.set(name, { levels, ...(off && { off }) });
|
|
286
|
+
}
|
|
287
|
+
cursor = typeof result.nextCursor === "string" ? result.nextCursor : undefined;
|
|
288
|
+
if (!cursor) break;
|
|
289
|
+
}
|
|
290
|
+
} catch {
|
|
291
|
+
// An older CLI, a slow answer or a closed process: the catalog decides.
|
|
292
|
+
}
|
|
293
|
+
return models.size ? models : undefined;
|
|
294
|
+
}
|
|
295
|
+
|
|
228
296
|
/**
|
|
229
297
|
* Codex harness backed by a long-lived `codex app-server` subprocess speaking
|
|
230
298
|
* JSON-RPC. Unlike the SDK harness this streams token-level deltas. A client +
|
|
@@ -359,7 +427,7 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
359
427
|
cause instanceof Error ? cause.message : String(cause),
|
|
360
428
|
{ cause },
|
|
361
429
|
);
|
|
362
|
-
})) as { thread?: { id?: string } };
|
|
430
|
+
})) as { thread?: { id?: string }; model?: unknown };
|
|
363
431
|
const threadId = result?.thread?.id;
|
|
364
432
|
if (resumeThreadId && threadId !== resumeThreadId) {
|
|
365
433
|
throw new SessionResumeError(
|
|
@@ -370,6 +438,7 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
370
438
|
if (!threadId) throw new Error("codex app-server thread/start returned no thread id");
|
|
371
439
|
signal.throwIfAborted();
|
|
372
440
|
session.threadId = threadId;
|
|
441
|
+
session.model = typeof result.model === "string" ? result.model : options.model;
|
|
373
442
|
this.sessions.set(options.sessionId, session);
|
|
374
443
|
return session;
|
|
375
444
|
} catch (error) {
|
|
@@ -422,6 +491,16 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
422
491
|
session.mcpFingerprint = fingerprint;
|
|
423
492
|
}
|
|
424
493
|
|
|
494
|
+
/** What the thread's model accepts: live from this process, else the catalog. */
|
|
495
|
+
private async modelThinking(session: AppServerSession): Promise<CodexModelThinking | undefined> {
|
|
496
|
+
if (!session.model) return undefined;
|
|
497
|
+
session.modelEfforts ??= listModelThinking(session.client);
|
|
498
|
+
const live = (await session.modelEfforts)?.get(session.model);
|
|
499
|
+
if (live) return live;
|
|
500
|
+
const levels = modelThinkingLevels("codex-app-server", session.model);
|
|
501
|
+
return levels && { levels };
|
|
502
|
+
}
|
|
503
|
+
|
|
425
504
|
private async authenticate(session: AppServerSession): Promise<void> {
|
|
426
505
|
session.turn?.signal.throwIfAborted();
|
|
427
506
|
const auth = session.turn?.auth;
|
|
@@ -714,8 +793,18 @@ export class CodexAppServerAgent extends SessionAgent {
|
|
|
714
793
|
threadId,
|
|
715
794
|
input: toUserInput(input),
|
|
716
795
|
};
|
|
717
|
-
if (options.model)
|
|
718
|
-
|
|
796
|
+
if (options.model) {
|
|
797
|
+
turnParams.model = options.model;
|
|
798
|
+
session.model = options.model;
|
|
799
|
+
}
|
|
800
|
+
if (options.thinkingLevel) {
|
|
801
|
+
const accepts = await this.modelThinking(session);
|
|
802
|
+
turnParams.effort = codexReasoningEffort(
|
|
803
|
+
options.thinkingLevel,
|
|
804
|
+
accepts?.levels,
|
|
805
|
+
accepts?.off,
|
|
806
|
+
);
|
|
807
|
+
}
|
|
719
808
|
|
|
720
809
|
if (controller.signal.aborted) throw new Error("turn aborted");
|
|
721
810
|
if (this.invalidatedClients.has(client)) {
|
|
@@ -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;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Codex, Thread, ThreadEvent, ThreadOptions } from "@openai/codex-sdk";
|
|
2
2
|
import type { AgentCapabilities, AgentInput, PermissionMode } from "../../../protocol/index.ts";
|
|
3
|
-
import { codexReasoningEffort } from "../../../protocol/index.ts";
|
|
3
|
+
import { codexReasoningEffort, modelThinkingLevels } from "../../../protocol/index.ts";
|
|
4
4
|
import { SessionResumeError } from "../../utils/errors.ts";
|
|
5
5
|
import type { AgentExecuteOptions, RawAgentEvent } from "../base.ts";
|
|
6
6
|
import { configFingerprint } from "../config-fingerprint.ts";
|
|
@@ -101,7 +101,8 @@ function toCodexInput(input: AgentInput): string {
|
|
|
101
101
|
.join("\n\n");
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
/** `codex exec` options for a turn. Exported for tests. */
|
|
105
|
+
export function threadOptions(options: AgentExecuteOptions): ThreadOptions {
|
|
105
106
|
const opts: ThreadOptions = {
|
|
106
107
|
workingDirectory: options.cwd,
|
|
107
108
|
skipGitRepoCheck: true,
|
|
@@ -112,8 +113,13 @@ function threadOptions(options: AgentExecuteOptions): ThreadOptions {
|
|
|
112
113
|
: {}),
|
|
113
114
|
};
|
|
114
115
|
if (options.model) opts.model = options.model;
|
|
116
|
+
// `codex exec` cannot list models, so the catalog says what a model accepts.
|
|
115
117
|
if (options.thinkingLevel)
|
|
116
|
-
opts.modelReasoningEffort = codexReasoningEffort(
|
|
118
|
+
opts.modelReasoningEffort = codexReasoningEffort(
|
|
119
|
+
options.thinkingLevel,
|
|
120
|
+
options.model ? modelThinkingLevels("codex-sdk", options.model) : undefined,
|
|
121
|
+
"minimal",
|
|
122
|
+
);
|
|
117
123
|
return opts;
|
|
118
124
|
}
|
|
119
125
|
|
|
@@ -216,26 +222,36 @@ export class CodexSdkAgent extends SessionAgent {
|
|
|
216
222
|
const { events } = await live.thread.runStreamed(toCodexInput(input), {
|
|
217
223
|
signal: controller.signal,
|
|
218
224
|
});
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
225
|
+
// `codex exec` reports a fatal turn on its stream, then exits non-zero; the
|
|
226
|
+
// SDK throws for that exit with only stderr. Keep the reported cause.
|
|
227
|
+
let failure: string | undefined;
|
|
228
|
+
try {
|
|
229
|
+
for await (const event of events as AsyncGenerator<ThreadEvent>) {
|
|
230
|
+
if (event.type === "turn.failed") failure = event.error.message;
|
|
231
|
+
if (event.type === "thread.started") {
|
|
232
|
+
if (options.resumeSessionId && event.thread_id !== options.resumeSessionId) {
|
|
233
|
+
// The SDK mutates Thread.id before yielding this event. Discard
|
|
234
|
+
// that wrapper; the retained resume target remains unchanged.
|
|
235
|
+
if (this.threads.get(options.sessionId) === live)
|
|
236
|
+
this.threads.delete(options.sessionId);
|
|
237
|
+
controller.abort();
|
|
238
|
+
throw new SessionResumeError(
|
|
239
|
+
options.resumeSessionId,
|
|
240
|
+
`Codex returned a different thread: ${event.thread_id}`,
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
if (!reported) {
|
|
244
|
+
reported = true;
|
|
245
|
+
options.onNativeSession?.(event.thread_id, {
|
|
246
|
+
resumed: Boolean(options.resumeSessionId),
|
|
247
|
+
});
|
|
248
|
+
}
|
|
236
249
|
}
|
|
250
|
+
yield event as RawAgentEvent;
|
|
237
251
|
}
|
|
238
|
-
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (failure === undefined || controller.signal.aborted) throw error;
|
|
254
|
+
throw new Error(failure, { cause: error });
|
|
239
255
|
}
|
|
240
256
|
}
|
|
241
257
|
|
|
@@ -27,15 +27,18 @@ 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. On every bump, re-read `model/list`
|
|
40
|
+
// and update MODEL_CATALOG's Codex models and thinking levels.
|
|
41
|
+
codex: "0.160.0",
|
|
39
42
|
};
|
|
40
43
|
|
|
41
44
|
/**
|
|
@@ -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
|
@@ -10,29 +10,63 @@ export interface ModelInfo {
|
|
|
10
10
|
readonly id: string;
|
|
11
11
|
readonly harness: AgentHarness;
|
|
12
12
|
readonly label: string;
|
|
13
|
+
/** The levels the model runs as distinct settings, lowest first. Empty: no control. */
|
|
13
14
|
readonly thinking: readonly ThinkingLevel[];
|
|
14
15
|
}
|
|
15
16
|
|
|
16
|
-
const
|
|
17
|
+
const UP_TO_XHIGH: readonly ThinkingLevel[] = ["low", "medium", "high", "xhigh"];
|
|
18
|
+
const UP_TO_MAX: readonly ThinkingLevel[] = [...UP_TO_XHIGH, "max"];
|
|
19
|
+
const UP_TO_ULTRA: readonly ThinkingLevel[] = [...UP_TO_MAX, "ultra"];
|
|
20
|
+
|
|
21
|
+
// Claude Code 2.1.288 aliases. The 5.5 models reject disabled thinking and
|
|
22
|
+
// Claude runs `ultra` as `max`, so neither `off` nor `ultra` is a setting of
|
|
23
|
+
// its own. Haiku 4.5 has no effort control.
|
|
24
|
+
const CLAUDE_MODELS: ReadonlyArray<readonly [string, string, readonly ThinkingLevel[]]> = [
|
|
25
|
+
["sonnet", "Claude Sonnet (latest)", UP_TO_MAX],
|
|
26
|
+
["opus", "Claude Opus (latest)", UP_TO_MAX],
|
|
27
|
+
["fable", "Claude Fable (latest)", UP_TO_MAX],
|
|
28
|
+
["haiku", "Claude Haiku (latest)", []],
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
// As Codex CLI 0.160.0 `model/list` reports them. No model accepts `minimal`,
|
|
32
|
+
// so none offers `off`. The GPT-6 family needs CLI 0.159 or newer.
|
|
33
|
+
const CODEX_MODELS: ReadonlyArray<readonly [string, string, readonly ThinkingLevel[]]> = [
|
|
34
|
+
["gpt-6.1-sol", "GPT-6.1 Sol", UP_TO_ULTRA],
|
|
35
|
+
["gpt-6-astra", "GPT-6 Astra", UP_TO_ULTRA],
|
|
36
|
+
["gpt-6-sol", "GPT-6 Sol", UP_TO_ULTRA],
|
|
37
|
+
["gpt-6-luna", "GPT-6 Luna", UP_TO_MAX],
|
|
38
|
+
["gpt-5.6-sol", "GPT-5.6 Sol", UP_TO_ULTRA],
|
|
39
|
+
["gpt-5.6-terra", "GPT-5.6 Terra", UP_TO_ULTRA],
|
|
40
|
+
["gpt-5.6-luna", "GPT-5.6 Luna", UP_TO_MAX],
|
|
41
|
+
// Codex refuses it for a ChatGPT login.
|
|
42
|
+
["gpt-5.5", "GPT-5.5 (API key)", UP_TO_XHIGH],
|
|
43
|
+
];
|
|
17
44
|
|
|
18
45
|
export const MODEL_CATALOG: readonly ModelInfo[] = [
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
46
|
+
...CLAUDE_MODELS.map(([id, label, thinking]) => ({
|
|
47
|
+
id,
|
|
48
|
+
harness: "claude-code" as const,
|
|
49
|
+
label,
|
|
50
|
+
thinking,
|
|
51
|
+
})),
|
|
52
|
+
// Shared between codex-sdk and codex-app-server.
|
|
53
|
+
...CODEX_MODELS.flatMap(([id, label, thinking]) =>
|
|
54
|
+
(["codex-sdk", "codex-app-server"] as const).map((harness) => ({
|
|
55
|
+
id,
|
|
56
|
+
harness,
|
|
57
|
+
label,
|
|
58
|
+
thinking,
|
|
59
|
+
})),
|
|
60
|
+
),
|
|
28
61
|
];
|
|
29
62
|
|
|
30
63
|
/**
|
|
31
|
-
*
|
|
32
|
-
*
|
|
64
|
+
* The model a turn runs on when its config names none. `undefined` means the
|
|
65
|
+
* harness's CLI picks: Claude Code its own default for the account, Codex the
|
|
66
|
+
* one in `~/.codex/config.toml`. The engine never substitutes a model.
|
|
33
67
|
*/
|
|
34
68
|
export const DEFAULT_MODELS: Record<AgentHarness, string | undefined> = {
|
|
35
|
-
"claude-code":
|
|
69
|
+
"claude-code": undefined,
|
|
36
70
|
"codex-sdk": undefined,
|
|
37
71
|
"codex-app-server": undefined,
|
|
38
72
|
// ACP v1 has no portable model parameter (selection is agent-defined via
|
|
@@ -43,3 +77,11 @@ export const DEFAULT_MODELS: Record<AgentHarness, string | undefined> = {
|
|
|
43
77
|
export function modelsForHarness(harness: AgentHarness): readonly ModelInfo[] {
|
|
44
78
|
return MODEL_CATALOG.filter((m) => m.harness === harness);
|
|
45
79
|
}
|
|
80
|
+
|
|
81
|
+
/** The catalog's thinking levels for a model; `undefined` when it isn't listed. */
|
|
82
|
+
export function modelThinkingLevels(
|
|
83
|
+
harness: AgentHarness,
|
|
84
|
+
model: string,
|
|
85
|
+
): readonly ThinkingLevel[] | undefined {
|
|
86
|
+
return MODEL_CATALOG.find((m) => m.harness === harness && m.id === model)?.thinking;
|
|
87
|
+
}
|
package/src/protocol/thinking.ts
CHANGED
|
@@ -3,9 +3,11 @@ 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`. What runs depends on the model: Claude's ceiling is `max`
|
|
7
|
+
* (it runs `ultra` as `max`), and Codex runs the nearest level the model
|
|
8
|
+
* accepts (see `codexReasoningEffort`).
|
|
7
9
|
*/
|
|
8
|
-
export const THINKING_LEVELS = ["off", "low", "medium", "high", "xhigh"] as const;
|
|
10
|
+
export const THINKING_LEVELS = ["off", "low", "medium", "high", "xhigh", "max", "ultra"] as const;
|
|
9
11
|
export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
|
|
10
12
|
export const ThinkingLevelSchema = z.enum(THINKING_LEVELS);
|
|
11
13
|
export const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
|
|
@@ -14,19 +16,52 @@ export function isThinkingLevel(v: string): v is ThinkingLevel {
|
|
|
14
16
|
return (THINKING_LEVELS as readonly string[]).includes(v);
|
|
15
17
|
}
|
|
16
18
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
19
|
+
const rank = (level: ThinkingLevel) => THINKING_LEVELS.indexOf(level);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The level a model runs when it offers only `supported`: the highest one at
|
|
23
|
+
* or below `level`, else its lowest. Use it when switching models, so `ultra`
|
|
24
|
+
* on a model topping out at `max` becomes `max`, not a fixed fallback.
|
|
25
|
+
* `undefined` when the model offers none.
|
|
26
|
+
*/
|
|
27
|
+
export function clampThinkingLevel(
|
|
28
|
+
level: ThinkingLevel,
|
|
29
|
+
supported: readonly ThinkingLevel[],
|
|
30
|
+
): ThinkingLevel | undefined {
|
|
31
|
+
let below: ThinkingLevel | undefined;
|
|
32
|
+
let lowest: ThinkingLevel | undefined;
|
|
33
|
+
for (const candidate of supported) {
|
|
34
|
+
if (lowest === undefined || rank(candidate) < rank(lowest)) lowest = candidate;
|
|
35
|
+
if (rank(candidate) <= rank(level) && (below === undefined || rank(candidate) > rank(below)))
|
|
36
|
+
below = candidate;
|
|
31
37
|
}
|
|
38
|
+
return below ?? lowest;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Codex reasoning-effort string for a level (matches the `ReasoningEffort` enum). */
|
|
42
|
+
export type CodexReasoningEffort =
|
|
43
|
+
| "none"
|
|
44
|
+
| "minimal"
|
|
45
|
+
| "low"
|
|
46
|
+
| "medium"
|
|
47
|
+
| "high"
|
|
48
|
+
| "xhigh"
|
|
49
|
+
| "max"
|
|
50
|
+
| "ultra";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The effort Codex runs for `level`. `supported` is what the model accepts, in
|
|
54
|
+
* this vocabulary, where `off` stands for its least effort: `offEffort`, the
|
|
55
|
+
* native `none` or `minimal` the model advertises. A level it lacks becomes the
|
|
56
|
+
* nearest one it has. Without `supported`, `off` becomes `low`: no model the
|
|
57
|
+
* pinned CLI lists accepts `none` or `minimal`, and every one accepts `low`.
|
|
58
|
+
*/
|
|
59
|
+
export function codexReasoningEffort<Off extends "none" | "minimal" = "minimal">(
|
|
60
|
+
level: ThinkingLevel,
|
|
61
|
+
supported?: readonly ThinkingLevel[],
|
|
62
|
+
offEffort?: Off,
|
|
63
|
+
): Exclude<CodexReasoningEffort, "none" | "minimal"> | Off {
|
|
64
|
+
const clamped = supported?.length ? clampThinkingLevel(level, supported) : undefined;
|
|
65
|
+
const effective = clamped ?? (level === "off" ? "low" : level);
|
|
66
|
+
return effective === "off" ? (offEffort ?? ("minimal" as Off)) : effective;
|
|
32
67
|
}
|
|
@@ -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).
|