@zvada/agent-server 0.3.25 → 0.3.26

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.
Files changed (156) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +3 -0
  3. package/dist/core/agents/acp/acp-agent.js +91 -14
  4. package/dist/core/agents/acp/mappings.js +5 -1
  5. package/dist/core/agents/claude-code/approvals.js +2 -1
  6. package/dist/core/agents/claude-code/claude-agent.js +12 -2
  7. package/dist/core/agents/claude-code/mcp.js +9 -1
  8. package/dist/core/agents/claude-code/models.js +16 -10
  9. package/dist/core/agents/claude-code/options.js +23 -2
  10. package/dist/core/agents/claude-code/session.js +21 -1
  11. package/dist/core/agents/claude-code/tools.js +9 -4
  12. package/dist/core/agents/claude-code/turn.js +2 -0
  13. package/dist/core/agents/codex-app-server/adapter.js +2 -0
  14. package/dist/core/agents/codex-app-server/client.js +8 -5
  15. package/dist/core/agents/codex-app-server/codex-agent.js +35 -2
  16. package/dist/core/agents/codex-app-server/effort.js +13 -6
  17. package/dist/core/agents/codex-app-server/mcp.js +35 -18
  18. package/dist/core/agents/codex-app-server/models.js +10 -10
  19. package/dist/core/agents/codex-app-server/options.js +11 -2
  20. package/dist/core/agents/codex-app-server/session.js +11 -4
  21. package/dist/core/agents/codex-app-server/thread-settings.js +30 -11
  22. package/dist/core/agents/host-tools.js +493 -0
  23. package/dist/core/agents/mcp-config.js +6 -2
  24. package/dist/core/agents/scripted/scripted-agent.js +9 -3
  25. package/dist/core/agents/scripted/steps.js +5 -1
  26. package/dist/core/agents/session-agent.js +70 -2
  27. package/dist/core/agents/thinking-levels.js +8 -5
  28. package/dist/core/index.js +1 -0
  29. package/dist/core/presets.js +12 -2
  30. package/dist/core/processes/lifeline.js +9 -5
  31. package/dist/core/provision/pins.js +7 -16
  32. package/dist/core/provision/releases.js +25 -25
  33. package/dist/core/proxy/loopback.js +22 -4
  34. package/dist/protocol/config.js +21 -1
  35. package/dist/protocol/model-catalog.js +58 -18
  36. package/dist/protocol/models.js +6 -27
  37. package/dist/protocol/thinking.js +22 -9
  38. package/dist/protocol/wire-api.js +2 -2
  39. package/dist/server/bin.js +6 -4
  40. package/dist/types/core/agents/acp/acp-agent.d.ts +15 -0
  41. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  42. package/dist/types/core/agents/acp/mappings.d.ts +5 -1
  43. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  44. package/dist/types/core/agents/acp/requests.d.ts +2 -0
  45. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  46. package/dist/types/core/agents/claude-code/approvals.d.ts +2 -1
  47. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  48. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -0
  49. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  50. package/dist/types/core/agents/claude-code/mcp.d.ts +8 -1
  51. package/dist/types/core/agents/claude-code/mcp.d.ts.map +1 -1
  52. package/dist/types/core/agents/claude-code/models.d.ts +9 -5
  53. package/dist/types/core/agents/claude-code/models.d.ts.map +1 -1
  54. package/dist/types/core/agents/claude-code/options.d.ts +10 -1
  55. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  56. package/dist/types/core/agents/claude-code/session.d.ts +2 -0
  57. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  58. package/dist/types/core/agents/claude-code/tools.d.ts.map +1 -1
  59. package/dist/types/core/agents/claude-code/turn.d.ts +3 -0
  60. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  61. package/dist/types/core/agents/codex-app-server/adapter.d.ts.map +1 -1
  62. package/dist/types/core/agents/codex-app-server/client.d.ts +2 -0
  63. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  64. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +11 -0
  65. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  66. package/dist/types/core/agents/codex-app-server/effort.d.ts +7 -7
  67. package/dist/types/core/agents/codex-app-server/effort.d.ts.map +1 -1
  68. package/dist/types/core/agents/codex-app-server/mcp.d.ts +11 -3
  69. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  70. package/dist/types/core/agents/codex-app-server/models.d.ts +4 -1
  71. package/dist/types/core/agents/codex-app-server/models.d.ts.map +1 -1
  72. package/dist/types/core/agents/codex-app-server/options.d.ts +9 -2
  73. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  74. package/dist/types/core/agents/codex-app-server/requests.d.ts +2 -0
  75. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  76. package/dist/types/core/agents/codex-app-server/session.d.ts +6 -3
  77. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  78. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts.map +1 -1
  79. package/dist/types/core/agents/host-tools.d.ts +162 -0
  80. package/dist/types/core/agents/host-tools.d.ts.map +1 -0
  81. package/dist/types/core/agents/mcp-config.d.ts +11 -2
  82. package/dist/types/core/agents/mcp-config.d.ts.map +1 -1
  83. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  84. package/dist/types/core/agents/scripted/steps.d.ts.map +1 -1
  85. package/dist/types/core/agents/session-agent.d.ts +2 -7
  86. package/dist/types/core/agents/session-agent.d.ts.map +1 -1
  87. package/dist/types/core/agents/thinking-levels.d.ts +7 -3
  88. package/dist/types/core/agents/thinking-levels.d.ts.map +1 -1
  89. package/dist/types/core/index.d.ts +1 -0
  90. package/dist/types/core/index.d.ts.map +1 -1
  91. package/dist/types/core/presets.d.ts +11 -1
  92. package/dist/types/core/presets.d.ts.map +1 -1
  93. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  94. package/dist/types/core/provision/pins.d.ts +5 -4
  95. package/dist/types/core/provision/pins.d.ts.map +1 -1
  96. package/dist/types/core/proxy/loopback.d.ts.map +1 -1
  97. package/dist/types/protocol/config.d.ts +12 -19
  98. package/dist/types/protocol/config.d.ts.map +1 -1
  99. package/dist/types/protocol/conversation.d.ts +4 -36
  100. package/dist/types/protocol/conversation.d.ts.map +1 -1
  101. package/dist/types/protocol/execution.d.ts +2 -18
  102. package/dist/types/protocol/execution.d.ts.map +1 -1
  103. package/dist/types/protocol/lifecycle.d.ts +8 -72
  104. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  105. package/dist/types/protocol/model-catalog.d.ts.map +1 -1
  106. package/dist/types/protocol/models.d.ts +4 -42
  107. package/dist/types/protocol/models.d.ts.map +1 -1
  108. package/dist/types/protocol/thinking.d.ts +19 -19
  109. package/dist/types/protocol/thinking.d.ts.map +1 -1
  110. package/dist/types/protocol/wire-api.d.ts +20 -105
  111. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  112. package/dist/types/protocol/wire.d.ts +16 -117
  113. package/dist/types/protocol/wire.d.ts.map +1 -1
  114. package/docs/consuming.md +68 -11
  115. package/docs/deploy.md +6 -5
  116. package/docs/harnesses.md +79 -31
  117. package/package.json +4 -4
  118. package/src/core/agents/acp/acp-agent.ts +123 -17
  119. package/src/core/agents/acp/mappings.ts +5 -1
  120. package/src/core/agents/acp/requests.ts +2 -0
  121. package/src/core/agents/claude-code/approvals.ts +2 -1
  122. package/src/core/agents/claude-code/claude-agent.ts +14 -2
  123. package/src/core/agents/claude-code/mcp.ts +11 -1
  124. package/src/core/agents/claude-code/models.ts +15 -10
  125. package/src/core/agents/claude-code/options.ts +33 -3
  126. package/src/core/agents/claude-code/session.ts +26 -1
  127. package/src/core/agents/claude-code/tools.ts +10 -4
  128. package/src/core/agents/claude-code/turn.ts +4 -0
  129. package/src/core/agents/codex-app-server/adapter.ts +2 -0
  130. package/src/core/agents/codex-app-server/client.ts +11 -5
  131. package/src/core/agents/codex-app-server/codex-agent.ts +45 -1
  132. package/src/core/agents/codex-app-server/effort.ts +15 -20
  133. package/src/core/agents/codex-app-server/mcp.ts +46 -23
  134. package/src/core/agents/codex-app-server/models.ts +10 -10
  135. package/src/core/agents/codex-app-server/options.ts +16 -2
  136. package/src/core/agents/codex-app-server/requests.ts +2 -0
  137. package/src/core/agents/codex-app-server/session.ts +19 -4
  138. package/src/core/agents/codex-app-server/thread-settings.ts +31 -11
  139. package/src/core/agents/host-tools.ts +649 -0
  140. package/src/core/agents/mcp-config.ts +15 -3
  141. package/src/core/agents/scripted/scripted-agent.ts +9 -2
  142. package/src/core/agents/scripted/steps.ts +5 -1
  143. package/src/core/agents/session-agent.ts +78 -2
  144. package/src/core/agents/thinking-levels.ts +9 -6
  145. package/src/core/index.ts +9 -0
  146. package/src/core/presets.ts +24 -3
  147. package/src/core/processes/lifeline.ts +9 -5
  148. package/src/core/provision/pins.ts +7 -16
  149. package/src/core/provision/releases.ts +25 -25
  150. package/src/core/proxy/loopback.ts +25 -4
  151. package/src/protocol/config.ts +22 -1
  152. package/src/protocol/model-catalog.ts +58 -18
  153. package/src/protocol/models.ts +6 -26
  154. package/src/protocol/thinking.ts +27 -14
  155. package/src/protocol/wire-api.ts +2 -2
  156. package/src/server/bin.ts +6 -4
package/CHANGELOG.md CHANGED
@@ -7,6 +7,86 @@ and the measurements. Evidence lives in the LLP, not here. A release groups
7
7
  its bullets under Breaking, Added, Changed and Fixed, breaking first. The
8
8
  released sections below that predate this convention are kept as written.
9
9
 
10
+ ## 0.3.26
11
+
12
+ ### Breaking
13
+
14
+ - `ThinkingLevel` is an open vocabulary: the type widens, so an exhaustive `switch` over
15
+ it no longer type-checks (`KnownThinkingLevel` is the seven), and `decodeModelList` is
16
+ removed. A model's `thinking.levels` holds every level its harness lists; a level it
17
+ does not list is fitted to the nearest, or not applied, and the turn says so (LLP 0002).
18
+ - Claude SDK 0.3.327 checks the options the engine passes on from yours: a hook
19
+ event's value and a matcher's `hooks` must be arrays, an option it cannot send to
20
+ Claude Code (a circular or BigInt field) is refused, and it needs Node 18.14 or
21
+ newer (LLP 0004, A pin bump).
22
+ - `sdkOptions.sandbox` no longer approves sandboxed Bash commands by itself (Claude
23
+ SDK 0.3.325): set `autoAllowBashIfSandboxed: true` in it to keep that (LLP 0004,
24
+ A pin bump).
25
+
26
+ ### Added
27
+
28
+ - An MCP server's entry takes an optional `timeoutMs`, how long one call to its tools may
29
+ run: it becomes Claude's per-server `timeout` and Codex's `tool_timeout_sec`. Without it
30
+ Claude cuts a call to an HTTP or SSE server at 60 s (or at `MCP_TOOL_TIMEOUT`) and Codex
31
+ a call at 300 s; an ACP agent is not given it and keeps its own (LLP 0001, D15; LLP 0015.001).
32
+ - `hostTools` (registry option, types `HostTools`, `HostToolSource`, `HostToolCaller`):
33
+ a product's own tools reach every harness under one server name, Claude in process,
34
+ Codex and HTTP-capable ACP agents at the engine's loopback by a per-session secret;
35
+ each call names its session, turn and current mode (LLP 0018). A call is held to the
36
+ source's limit, over ACP a tool that writes runs only with full access, the harness
37
+ process reaches the loopback past any proxy (`NO_PROXY`), and the session's secret is
38
+ redacted from every event, warning and error the turn lets out (LLP 0018).
39
+
40
+ ### Changed
41
+
42
+ - A turn's own MCP server named like the host's tools is refused, `invalid_request`
43
+ (LLP 0018, The API).
44
+
45
+ - The pinned Codex is 0.169.1 (it was 0.160.0). Its models add `gpt-6.2-sol`, the default
46
+ in place of `gpt-6.1-sol`, and `gpt-6.2-astra`; neither has an `off` effort, so a turn
47
+ at `thinkingLevel: "off"` runs them at `low` and says so (`appliedThinkingLevel`)
48
+ (LLP 0004, A pin bump).
49
+ - With `codexAppServer.builtInTools.local: false` Codex (since 0.164) still lists
50
+ `apply_patch` to the model and refuses each call, writing nothing; the engine now also
51
+ switches `view_image` off. A refused call is not on the stream: say in your agent's
52
+ instructions that it has no files (LLP 0017, Each turn names its environments).
53
+ - A cancel that lands as an approved Codex command starts (within 110 ms, measured on
54
+ Linux) answers `confirmed: false` with the default deadlines, and Codex's process is
55
+ ended: since 0.169.1 Codex ends such a command itself and says nothing of it. The
56
+ command is stopped either way (LLP 0002, Tools a turn leaves open).
57
+ - Claude runs on Claude SDK 0.3.327 and Claude Code 2.1.327 (from 0.3.288 and
58
+ 2.1.288). `fable` runs Fable 5.2, and `haiku` Haiku 5.5, which has thinking
59
+ levels; the models they ran stay as `claude-fable-5-1` and
60
+ `claude-haiku-4-5-20251001` (LLP 0004, A pin bump).
61
+ - `Monitor` is kept off while background tasks are off, beside your own
62
+ `disallowedTools`: Claude Code 2.1.327 offers it, and its watch outlives the turn
63
+ with requests no turn shows. An env that turns background tasks on leaves it (LLP
64
+ 0001, D14).
65
+ - `ToolSearch` parts appear on the stream (kind `other`): Claude Code 2.1.327 holds
66
+ some tools back, `ExitPlanMode`, `WebFetch` and MCP tools among them, and loads
67
+ them through it before their call (LLP 0002, A tool call says what it acts on).
68
+ - The lifeline shell, the one process that lives as long as the engine, is given `PATH`
69
+ alone, so it holds no secret of the host's (LLP 0007, The environment a process is
70
+ given).
71
+
72
+ ### Fixed
73
+
74
+ - Under Bun, the engine's loopback (the host's tools, the Anthropic proxy) answers in a
75
+ process whose global `Response` a framework replaced (Hono's Node server): `Bun.serve`
76
+ refused every answer before (LLP 0018, Codex).
77
+
78
+ - A Codex turn on `gpt-6.2-sol` or `gpt-6.2-astra` runs, and so does a turn that names no
79
+ model on an account whose own default is one of them: Codex 0.160.0 refused both
80
+ models (LLP 0004, A pin bump).
81
+ - `plan` asks before a read outside the folder, a shell write or an MCP tool on every
82
+ model: the engine sets `useAutoModeDuringPlan: false` beneath your
83
+ `sdkOptions.settings` (your keys win; a settings path is left as it is). On Sonnet
84
+ 5.5, which `haiku` plans on, those ran unasked (LLP 0001, D4).
85
+ - A scripted turn cancelled before the harness has it takes its own steps, so a queue or
86
+ file script's next turn plays its own, not the cancelled one's (and no longer hangs on its
87
+ `hang`, which takes `stopTakes`, except in an async generator's script). A script given as
88
+ a function is now called for such a turn too (LLP 0016.000, The scripted harness; LLP 0001, D23).
89
+
10
90
  ## 0.3.25
11
91
 
12
92
  ### Changed
package/README.md CHANGED
@@ -47,6 +47,9 @@ SDK present. Codex needs none: its harness drives the `codex` CLI directly.
47
47
 
48
48
  ## Run the wire server
49
49
 
50
+ The `agent-server` command runs its TypeScript source and needs Bun: run it
51
+ with `bunx @zvada/agent-server`.
52
+
50
53
  ```sh
51
54
  bunx @zvada/agent-server --listen 4747 # WebSocket wire on 127.0.0.1
52
55
  bunx @zvada/agent-server --stdio # stdio wire (for spawners)
@@ -1,9 +1,9 @@
1
1
  import { AsyncQueue } from "../../../protocol/index.js";
2
2
  import { sharedNativeProcesses } from "../../processes/native-processes.js";
3
3
  import { onAbort, untilAborted } from "../../utils/deadline.js";
4
- import { SessionResumeError } from "../../utils/errors.js";
4
+ import { McpUnavailableError, SessionResumeError } from "../../utils/errors.js";
5
5
  import { configFingerprint } from "../config-fingerprint.js";
6
- import { nativeMcpServer } from "../mcp-config.js";
6
+ import { hostToolSessions, loopbackDirect, refuseHostName, } from "../host-tools.js";
7
7
  import { IDLE_TIMEOUT_MS, ProcessPool } from "../process-pool.js";
8
8
  import { SessionAgent } from "../session-agent.js";
9
9
  import { CANCELLED_PROMPT_RESULT } from "./adapter.js";
@@ -13,18 +13,32 @@ import { answerElicitation, answerPermission } from "./requests.js";
13
13
  /**
14
14
  * What a session's agent process was started with, as one key: a change to
15
15
  * any of it starts another, which resumes the conversation where the agent
16
- * can. MCP servers go without `required`, which is the engine's; extra
17
- * directories count, in any order, only for an agent that takes them.
16
+ * can. MCP servers count as the agent is given them (no `required`, which is
17
+ * the engine's, no `timeoutMs`, which ACP cannot carry); the host's tools by
18
+ * their name, their address and secret being the session's for its life;
19
+ * extra directories, in any order, only for an agent that takes them.
18
20
  * Hashed: the env and MCP headers carry credentials.
19
21
  */
20
- function spawnKey(options, launch, takesDirectories) {
21
- const servers = options.mcpServers;
22
+ /** What the agent is given, in an order of its own: a server's, header's or variable's place means nothing. */
23
+ function canonicalServers(servers) {
24
+ // A total order by code unit: `localeCompare` calls distinct names equal.
25
+ const byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
26
+ return toAcpMcpServers(servers)
27
+ .map((server) => "headers" in server
28
+ ? { ...server, headers: [...server.headers].sort(byName) }
29
+ : "env" in server
30
+ ? { ...server, env: [...server.env].sort(byName) }
31
+ : server)
32
+ .sort(byName);
33
+ }
34
+ function spawnKey(options, launch, takesDirectories, host) {
22
35
  return configFingerprint({
23
36
  launch: { command: launch.command, args: launch.args ?? [], env: launch.env ?? {} },
24
37
  cwd: options.cwd,
25
38
  env: options.env,
26
- mcpServers: servers &&
27
- Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, nativeMcpServer(server)])),
39
+ // @ref LLP 0018#acp — only what the agent is given
40
+ mcpServers: options.mcpServers && canonicalServers(options.mcpServers),
41
+ host,
28
42
  directories: takesDirectories
29
43
  ? [...new Set(options.additionalDirectories ?? [])].sort()
30
44
  : undefined,
@@ -105,14 +119,30 @@ export class AcpAgent extends SessionAgent {
105
119
  /** Its CLIs start here: the runtime's, or this OS process's own when it was made without one. */
106
120
  processes;
107
121
  sessions;
122
+ host;
108
123
  constructor(agentOptions) {
109
124
  super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
110
125
  this.agentOptions = agentOptions;
111
126
  this.processes = agentOptions.processes ?? sharedNativeProcesses();
127
+ this.host = hostToolSessions(agentOptions.hostTools, this.harness, {
128
+ // @ref LLP 0018#acp — the engine's mode: the turn's, moved only by a plan the broker approved
129
+ // The agent's own `current_mode_update` never raises it.
130
+ live: (sessionId) => {
131
+ const turn = this.sessions.get(sessionId)?.turn;
132
+ return turn?.turnId
133
+ ? { turnId: turn.turnId, permissionMode: turn.mode ?? "default", signal: turn.signal }
134
+ : undefined;
135
+ },
136
+ writesNeedFullAccess: true,
137
+ });
112
138
  this.sessions = new ProcessPool({
113
139
  resumeOf: ({ options }) => options.resumeSessionId,
114
140
  conversationsOf: (session) => [session.acpSessionId],
115
- fits: (session, { options, launch }) => session.spawnKey === spawnKey(options, launch, session.takesDirectories),
141
+ fits: (session, { options, launch, host }) => session.spawnKey ===
142
+ spawnKey(options, launch, session.takesDirectories, host?.source.name) &&
143
+ // @ref LLP 0018#acp — an agent started without the host's tools while the loopback was down
144
+ // One that can resume is started again, to get them; one that cannot keeps its conversation.
145
+ !(session.hostFailed && session.resumable),
116
146
  // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — not ended for idleness when it cannot be resumed
117
147
  // An agent that can neither resume nor load holds the only copy of
118
148
  // its conversation: neither idleness nor a host resume ends it.
@@ -128,7 +158,42 @@ export class AcpAgent extends SessionAgent {
128
158
  if (!launch) {
129
159
  throw new Error("acp harness is not configured: resolveLaunch returned no agent launch command");
130
160
  }
131
- return this.sessions.acquire(options.sessionId, { options, launch }, signal);
161
+ const host = await untilAborted(Promise.resolve(this.host?.lease(options.sessionId, options.cwd)), signal);
162
+ if (host)
163
+ refuseHostName(options.mcpServers, host.source.name);
164
+ return this.sessions.acquire(options.sessionId, { options, launch, host }, signal);
165
+ }
166
+ hostSecret(sessionId) {
167
+ return this.host?.secretOf(sessionId);
168
+ }
169
+ // @ref LLP 0018#acp — an agent that takes no HTTP server goes without the host's tools, and says so
170
+ /**
171
+ * The servers the agent is given: the turn's, and the host's when the agent
172
+ * takes HTTP servers, the loopback started only then. Without it, or with a
173
+ * loopback that cannot start, the turn says so and goes on without them.
174
+ */
175
+ async serversFor(options, host, http) {
176
+ if (!host)
177
+ return { servers: options.mcpServers };
178
+ const { name } = host.source;
179
+ let cause = "the agent takes no HTTP MCP server";
180
+ let hostFailed;
181
+ if (http) {
182
+ try {
183
+ return { servers: { ...options.mcpServers, [name]: await host.http() } };
184
+ }
185
+ catch (error) {
186
+ if (!(error instanceof McpUnavailableError))
187
+ throw error;
188
+ cause = error.servers[name] ?? error.message;
189
+ hostFailed = true;
190
+ }
191
+ }
192
+ await options.onWarning?.({
193
+ category: "mcp_unavailable",
194
+ message: `MCP server ${name} could not connect (${cause}); the turn goes on without the host's tools`,
195
+ });
196
+ return { servers: options.mcpServers, ...(hostFailed && { hostFailed }) };
132
197
  }
133
198
  /**
134
199
  * Start the session's agent and open its conversation: the one the turn
@@ -136,12 +201,19 @@ export class AcpAgent extends SessionAgent {
136
201
  * starts it once every agent of the session before it has exited, so a
137
202
  * successor never loads a conversation another agent still has.
138
203
  */
139
- async spawn({ options, launch }, own, signal) {
204
+ async spawn({ options, launch, host }, own, signal) {
140
205
  const resumeTarget = options.resumeSessionId;
141
206
  const clientOptions = {
142
207
  launch,
143
208
  cwd: options.cwd,
144
- env: options.env,
209
+ // @ref LLP 0018#acp — the bearer never travels through a proxy
210
+ // In the client's own order: the engine's environment, the launch's, the turn's.
211
+ env: this.host
212
+ ? {
213
+ ...options.env,
214
+ ...loopbackDirect({ ...process.env, ...launch.env, ...options.env }),
215
+ }
216
+ : options.env,
145
217
  clientName: this.agentOptions.clientName,
146
218
  sessionId: options.sessionId,
147
219
  processes: this.processes,
@@ -174,9 +246,10 @@ export class AcpAgent extends SessionAgent {
174
246
  : capabilities?.loadSession
175
247
  ? "session/load"
176
248
  : undefined;
249
+ const given = await this.serversFor(options, host, Boolean(capabilities?.mcpCapabilities?.http));
177
250
  const target = {
178
251
  cwd: options.cwd,
179
- mcpServers: toAcpMcpServers(options.mcpServers),
252
+ mcpServers: toAcpMcpServers(given.servers),
180
253
  // Sent only to agents that advertise it; others keep `cwd` alone.
181
254
  ...(takesDirectories &&
182
255
  options.additionalDirectories?.length && {
@@ -213,7 +286,8 @@ export class AcpAgent extends SessionAgent {
213
286
  const session = {
214
287
  client,
215
288
  acpSessionId,
216
- spawnKey: spawnKey(options, launch, takesDirectories),
289
+ spawnKey: spawnKey(options, launch, takesDirectories, host?.source.name),
290
+ ...(given.hostFailed && { hostFailed: true }),
217
291
  takesDirectories,
218
292
  resumable: resumeMethod !== undefined,
219
293
  configOptions: configOptions ?? [],
@@ -324,6 +398,7 @@ export class AcpAgent extends SessionAgent {
324
398
  elicitation: options.onElicitationRequest,
325
399
  mode: options.permissionMode,
326
400
  signal: controller.signal,
401
+ turnId: options.turnId,
327
402
  };
328
403
  options.onNativeSession?.(session.acpSessionId, {
329
404
  resumed: session.acpSessionId === options.resumeSessionId,
@@ -413,6 +488,7 @@ export class AcpAgent extends SessionAgent {
413
488
  // confirm window, not after it, and its exit is what confirms it.
414
489
  // An agent an eviction or a replacement ended earlier is waited for too.
415
490
  await Promise.all([super.release(sessionId), this.sessions.release(sessionId)]);
491
+ this.host?.release(sessionId);
416
492
  }
417
493
  /** After a host resume, each session's next turn starts its agent again, on its conversation. */
418
494
  invalidateMcpConnections() {
@@ -421,5 +497,6 @@ export class AcpAgent extends SessionAgent {
421
497
  async terminateAll() {
422
498
  await super.terminateAll();
423
499
  await this.sessions.closeAll();
500
+ await this.host?.close();
424
501
  }
425
502
  }
@@ -41,7 +41,11 @@ export function toToolResultContent(content) {
41
41
  return [];
42
42
  });
43
43
  }
44
- /** Engine MCP config map → ACP `McpServer[]` (names come from the record keys). */
44
+ /**
45
+ * Engine MCP config map → ACP `McpServer[]` (names come from the record keys).
46
+ * ACP's fields only: a strict agent may refuse one it does not know, and ACP
47
+ * v1 has none for `required` or a tool-call limit (`timeoutMs`).
48
+ */
45
49
  export function toAcpMcpServers(mcpServers) {
46
50
  if (!mcpServers)
47
51
  return [];
@@ -32,7 +32,8 @@ export function startQuery(permissionMode, start) {
32
32
  /**
33
33
  * The SDK approval callback, fixed at spawn: it asks the turn running when it
34
34
  * is called, which Claude does for a call its mode and rules do not approve
35
- * by themselves (under `bypass_permissions`, only questions and plans). The
35
+ * by themselves (under `bypass_permissions`, questions, plans and, since
36
+ * Claude Code 2.1.326, the few calls it holds back as dangerous). The
36
37
  * host `toolPolicy` sees each such call first (full native PermissionResult
37
38
  * power), questions and plans included; a call it leaves
38
39
  * (`undefined`) goes to the turn: a question to its elicitation, a plan or a
@@ -3,6 +3,7 @@ import { sharedNativeProcesses } from "../../processes/native-processes.js";
3
3
  import { onAbort, untilAborted } from "../../utils/deadline.js";
4
4
  import { SessionResumeError } from "../../utils/errors.js";
5
5
  import { UnsupportedAttachmentError, attachedText, isTextMedia } from "../attachments.js";
6
+ import { hostToolSessions, refuseHostName } from "../host-tools.js";
6
7
  import { SessionAgent } from "../session-agent.js";
7
8
  import { ClaudeCredentials, ON_PLACEHOLDER } from "./credentials.js";
8
9
  import { ClaudeCliLogin } from "./login.js";
@@ -95,12 +96,14 @@ export class ClaudeCodeAgent extends SessionAgent {
95
96
  pool;
96
97
  credentials;
97
98
  cancelGraceMs;
99
+ host;
98
100
  constructor(agentOptions = {}) {
99
101
  super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
100
102
  this.agentOptions = agentOptions;
101
103
  this.cancelGraceMs = agentOptions.cancelGraceMs ?? CANCEL_GRACE_MS;
102
104
  this.processes = agentOptions.processes ?? sharedNativeProcesses();
103
- this.pool = claudeSessionPool({ ...agentOptions, processes: this.processes });
105
+ this.host = hostToolSessions(agentOptions.hostTools, this.harness);
106
+ this.pool = claudeSessionPool({ ...agentOptions, processes: this.processes, host: this.host });
104
107
  this.login = new ClaudeCliLogin({
105
108
  resolveCliPath: agentOptions.resolveCliPath,
106
109
  processes: this.processes,
@@ -134,6 +137,9 @@ export class ClaudeCodeAgent extends SessionAgent {
134
137
  const cliPath = resolveCliPath && (await untilAborted(resolveCliPath(), controller.signal));
135
138
  const content = toClaudeContent(input);
136
139
  controller.signal.throwIfAborted();
140
+ const source = await untilAborted(Promise.resolve(this.host?.source(options.sessionId, options.cwd)), controller.signal);
141
+ if (source)
142
+ refuseHostName(options.mcpServers, source.name);
137
143
  const thinking = fitClaudeThinking(options.thinkingLevel, options.modelThinking);
138
144
  const turnOptions = this.withDelivery(options, await this.credentials?.forTurn(options.sessionId, options.turnId, controller.signal));
139
145
  controller.signal.throwIfAborted();
@@ -147,7 +153,8 @@ export class ClaudeCodeAgent extends SessionAgent {
147
153
  if (thinking.applied && !session.operatorThinking)
148
154
  options.onExecution?.({ thinkingLevel: thinking.applied });
149
155
  const notApplied = [];
150
- // A model known to have no effort levels is sent no level (`fitClaudeThinking`).
156
+ // A model known to have no effort levels, or whose levels hold no fit for
157
+ // the turn's, is sent no level (`fitClaudeThinking`).
151
158
  if (options.thinkingLevel !== undefined && thinking.send === undefined)
152
159
  notApplied.push("thinkingLevel");
153
160
  // A message to resume at goes only with a resume (`buildClaudeOptions`).
@@ -177,6 +184,7 @@ export class ClaudeCodeAgent extends SessionAgent {
177
184
  report(session.currentSessionId);
178
185
  const turn = session.sendMessage(content, {
179
186
  turnId: options.turnId,
187
+ signal: controller.signal,
180
188
  permissions: options.onPermissionRequest,
181
189
  elicitation: options.onElicitationRequest,
182
190
  });
@@ -308,6 +316,7 @@ export class ClaudeCodeAgent extends SessionAgent {
308
316
  await super.release(sessionId);
309
317
  await this.pool.release(sessionId);
310
318
  this.credentials?.release(sessionId);
319
+ this.host?.release(sessionId);
311
320
  }
312
321
  async terminateAll() {
313
322
  // Before the turns are aborted: a start under way ends for shutdown, not as a cancel.
@@ -315,5 +324,6 @@ export class ClaudeCodeAgent extends SessionAgent {
315
324
  await super.terminateAll();
316
325
  await closed;
317
326
  await this.credentials?.close();
327
+ await this.host?.close();
318
328
  }
319
329
  }
@@ -1,5 +1,13 @@
1
1
  import { configFingerprint } from "../config-fingerprint.js";
2
2
  import { UnavailableMcpServers, mcpConnectionErrors, nativeMcpServer, settleMcpFailures, snapshotMcpServers, } from "../mcp-config.js";
3
+ /**
4
+ * A turn's server as Claude takes it: its tool-call limit is the SDK's
5
+ * per-server `timeout`, in milliseconds as on the wire.
6
+ */
7
+ export function claudeMcpServer(server) {
8
+ const native = nativeMcpServer(server);
9
+ return server.timeoutMs === undefined ? native : { ...native, timeout: server.timeoutMs };
10
+ }
3
11
  function remoteMcpServer(server) {
4
12
  return server.type === "http" || server.type === "sse";
5
13
  }
@@ -106,7 +114,7 @@ export class ClaudeMcpConnections {
106
114
  // for an identical configuration, and its old failure must not decide.
107
115
  const retry = new Set(this.unavailable.retryNow(servers));
108
116
  const resetNames = Object.keys(servers).filter((name) => failed.has(name) || retry.has(name));
109
- const native = Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, nativeMcpServer(server)]));
117
+ const native = Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, claudeMcpServer(server)]));
110
118
  const desired = { ...native, ...this.host };
111
119
  const added = new Set();
112
120
  const removed = new Set();
@@ -1,6 +1,6 @@
1
1
  import { AsyncQueue, clampThinkingLevel, } from "../../../protocol/index.js";
2
2
  import { onAbort } from "../../utils/deadline.js";
3
- import { knownThinkingLevels } from "../thinking-levels.js";
3
+ import { listedThinkingLevels } from "../thinking-levels.js";
4
4
  import { buildClaudeOptions } from "./options.js";
5
5
  /**
6
6
  * Claude Code's model rows in the shared shape. `default` (the account's
@@ -18,7 +18,7 @@ export function claudeModelDescriptors(models) {
18
18
  ...(model.resolvedModel &&
19
19
  model.resolvedModel !== model.value && { resolvedId: model.resolvedModel }),
20
20
  ...(model.value === "default" && { isDefault: true }),
21
- thinking: { levels: knownThinkingLevels(model.supportedEffortLevels ?? []) },
21
+ thinking: { levels: listedThinkingLevels(model.supportedEffortLevels ?? []) },
22
22
  }));
23
23
  }
24
24
  /**
@@ -26,20 +26,26 @@ export function claudeModelDescriptors(models) {
26
26
  * lowers a level its model lacks on its own and does not say so (`max` and
27
27
  * `xhigh` become `high`), so the level is fitted here, where the model's levels
28
28
  * are known. `off` is sent as it is: some models do not let thinking be
29
- * disabled, and Claude Code then thinks at its default effort; Haiku, which
30
- * Claude Code otherwise starts thinking, does not think with it. A model known
31
- * to have no effort levels (`levels: []`, Haiku) is sent no other level, so it
32
- * is not started on adaptive thinking at an effort it has no control for; a
33
- * model whose levels are unknown (`undefined`) is sent the level as asked.
29
+ * disabled (Haiku 5.5 at `off` still spends thinking tokens, with an empty
30
+ * reasoning part, on Claude Code 2.1.327); Haiku 4.5, which Claude Code
31
+ * otherwise starts thinking, does not think with it. A model known to have no
32
+ * effort levels (`levels: []`, Haiku 4.5) is sent no other level, so it is not
33
+ * started on adaptive thinking at an effort it has no control for: it thinks
34
+ * at its own default, as Claude Code starts it. Neither is a model sent a
35
+ * level that has no fit among the levels it lists. A model whose levels are
36
+ * unknown (`undefined`) is sent the level as asked, but `ultra` as `max`,
37
+ * Claude's ceiling; a model that lists `ultra` is sent it.
34
38
  */
35
39
  export function fitClaudeThinking(level, levels) {
36
40
  if (level === undefined)
37
41
  return {};
38
- if (level === "off" || levels === undefined)
42
+ if (level === "off")
39
43
  return { send: level };
40
- if (!levels.length)
44
+ if (levels === undefined)
45
+ return { send: level === "ultra" ? "max" : level };
46
+ const fitted = clampThinkingLevel(level, levels);
47
+ if (fitted === undefined)
41
48
  return {};
42
- const fitted = clampThinkingLevel(level, levels) ?? level;
43
49
  return { send: fitted, applied: fitted };
44
50
  }
45
51
  /**
@@ -149,6 +149,10 @@ function buildEnv(config, level) {
149
149
  }),
150
150
  };
151
151
  }
152
+ /** Whether Claude Code reads a flag as on: `1`, `true`, `yes` or `on`, in any case (2.1.327). */
153
+ function envFlagOn(value) {
154
+ return ["1", "true", "yes", "on"].includes((value ?? "").trim().toLowerCase());
155
+ }
152
156
  /** The environment Claude Code runs a turn with this `env` in, which decides whose login it runs on. */
153
157
  export function claudeEnv(config) {
154
158
  return buildEnv(config, inherited(config));
@@ -191,8 +195,10 @@ export function buildClaudeOptions(config, sdkMcpServers, overrides, spawn) {
191
195
  }
192
196
  else {
193
197
  options.thinking = { type: "adaptive" };
194
- // Claude's ceiling is `max`.
195
- options.effort = config.thinkingLevel === "ultra" ? "max" : config.thinkingLevel;
198
+ // The level as `fitClaudeThinking` gave it. The SDK types `effort` as
199
+ // the levels it knows; one beyond them (a level the model lists, or
200
+ // any when its levels are unknown) goes to the CLI as it is named.
201
+ options.effort = config.thinkingLevel;
196
202
  }
197
203
  }
198
204
  if (config.resumeSessionId) {
@@ -217,8 +223,23 @@ export function buildClaudeOptions(config, sdkMcpServers, overrides, spawn) {
217
223
  // ClaudeSdkOptionOverrides type excludes them anyway).
218
224
  if (overrides)
219
225
  Object.assign(options, overrides);
226
+ // @ref LLP 0001#d4--permission-requests-are-first-class-protocol — plan mode asks through the broker
227
+ // On a model with auto mode, plan mode takes auto mode's semantics: calls run that the broker
228
+ // never sees. Off beneath the operator's own settings object; a path, or `extraArgs.settings`, stays theirs.
229
+ if (typeof options.settings !== "string" && options.extraArgs?.settings === undefined)
230
+ options.settings = { useAutoModeDuringPlan: false, ...options.settings };
220
231
  if (config.subagentMode === "turn")
221
232
  options.forwardSubagentText = true;
233
+ // @ref LLP 0001#d14--nothing-the-agent-does-is-off-the-stream — a watch outlives its turn
234
+ // Claude Code 2.1.327 offers `Monitor` with background tasks off: its watch
235
+ // runs past the turn and Claude answers each line with a query of its own,
236
+ // which no turn shows. With background tasks off it is off too, beside the
237
+ // operator's own denials; an env that turns them on leaves it alone.
238
+ if (envFlagOn(options.env?.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS)) {
239
+ const denied = options.disallowedTools ?? [];
240
+ if (!denied.includes("Monitor"))
241
+ options.disallowedTools = [...denied, "Monitor"];
242
+ }
222
243
  // Engine wiring over the operator's: their spawner still runs, as theirs.
223
244
  if (spawn)
224
245
  options.spawnClaudeCodeProcess = claudeSpawner(spawn, overrides?.spawnClaudeCodeProcess, overrides?.stderr);
@@ -170,12 +170,25 @@ export class ClaudeSession {
170
170
  }
171
171
  return true;
172
172
  }
173
+ /** The turn running now and the mode the process runs in, for a host tool's caller. */
174
+ liveTurn() {
175
+ return this.turn
176
+ ? {
177
+ turnId: this.turn.id,
178
+ permissionMode: this.config.permissionMode ?? "default",
179
+ signal: this.turn.signal,
180
+ }
181
+ : undefined;
182
+ }
173
183
  async start() {
174
184
  if (this.state !== "starting")
175
185
  throw new Error(`Cannot start in state: ${this.state}`);
176
186
  const sdk = await import("@anthropic-ai/claude-agent-sdk");
177
187
  const spawn = { sessionId: this.id, cwd: this.config.cwd };
178
- const hostServers = await this.settings.sdkMcpServers?.(spawn);
188
+ const source = await this.settings.host?.source(this.id, this.config.cwd);
189
+ const hostServers = { ...(await this.settings.sdkMcpServers?.(spawn)) };
190
+ if (source && this.settings.host)
191
+ hostServers[source.name] = this.settings.host.inProcess(this.id, source, () => this.liveTurn());
179
192
  this.mcp.useHostServers(hostServers);
180
193
  const overrides = await this.settings.sdkOptions?.(spawn);
181
194
  this.thinkingOverridden = Boolean(overrides && ("effort" in overrides || "thinking" in overrides));
@@ -186,6 +199,13 @@ export class ClaudeSession {
186
199
  this.native = native;
187
200
  },
188
201
  });
202
+ // @ref LLP 0018#permissions — a read-only host tool runs unasked, as on Codex; any other asks
203
+ const readOnly = (source?.tools ?? []).filter((tool) => tool.annotations?.readOnly);
204
+ if (source && readOnly.length)
205
+ options.allowedTools = [
206
+ ...(options.allowedTools ?? []),
207
+ ...readOnly.map((tool) => `mcp__${source.name}__${tool.name}`),
208
+ ];
189
209
  if (this.settings.hooks) {
190
210
  options.hooks = this.settings.hooks({
191
211
  sessionId: this.id,
@@ -11,12 +11,14 @@
11
11
  * CLI offers that is not here, so a pin bump decides it.
12
12
  */
13
13
  export const CLAUDE_TOOL_KINDS = new Map([
14
- // What the pinned CLI (2.1.288) offers, with the engine's options or a product's.
14
+ // What the pinned CLI offers, with the engine's options or a product's.
15
15
  ["Read", "read"],
16
16
  ["Edit", "edit"],
17
17
  ["Write", "edit"],
18
18
  ["NotebookEdit", "edit"],
19
19
  ["Bash", "execute"],
20
+ // Runs a shell command and reports its output as it comes.
21
+ ["Monitor", "execute"],
20
22
  // Stops a background shell or sub-agent the agent started.
21
23
  ["TaskStop", "execute"],
22
24
  // Runs a script the agent wrote, which starts sub-agents of its own.
@@ -25,6 +27,8 @@ export const CLAUDE_TOOL_KINDS = new Map([
25
27
  ["WebSearch", "fetch"],
26
28
  // Loads a skill's instructions into the conversation.
27
29
  ["Skill", "read"],
30
+ // Loads the definition of a tool the CLI held back: nothing of the person's.
31
+ ["ToolSearch", "other"],
28
32
  // The sub-agent tool: `init` names it `Task`, the model `Agent`. A spawn is `task` by its subagent.
29
33
  ["Task", "think"],
30
34
  ["Agent", "think"],
@@ -71,8 +75,8 @@ function toolLocationsFromInput(input) {
71
75
  }
72
76
  const MCP_PREFIX = "mcp__";
73
77
  /**
74
- * A server's name as Claude Code spells it in a tool name (the pinned CLI
75
- * 2.1.288, SDK 0.3.288, and 2.1.325 alike):
78
+ * A server's name as Claude Code spells it in a tool name (the pinned CLI;
79
+ * 2.1.288 and 2.1.325 spell it alike, observed 2026-11-16):
76
80
  * other than letters, digits, `_` and `-` become `_`, and a claude.ai
77
81
  * connector's runs of `_` collapse.
78
82
  */
@@ -119,7 +123,8 @@ function textOf(input, key) {
119
123
  */
120
124
  export function claudeToolMeta(toolName, input, servers) {
121
125
  const mcp = claudeMcpTool(toolName, servers);
122
- const command = toolName === "Bash" ? textOf(input, "command") : undefined;
126
+ // A `Monitor` on a WebSocket has no command.
127
+ const command = toolName === "Bash" || toolName === "Monitor" ? textOf(input, "command") : undefined;
123
128
  const url = toolName === "WebFetch" ? textOf(input, "url") : undefined;
124
129
  return {
125
130
  kind: CLAUDE_TOOL_KINDS.get(toolName) ?? "other",
@@ -13,6 +13,7 @@ const STEER_QUERY_TIMEOUT_MS = 60_000;
13
13
  */
14
14
  export class ClaudeTurn {
15
15
  id;
16
+ signal;
16
17
  permissions;
17
18
  elicitation;
18
19
  /** What the turn yields, until its result or its failure. */
@@ -48,6 +49,7 @@ export class ClaudeTurn {
48
49
  watchdog;
49
50
  constructor(start, prompt) {
50
51
  this.id = start.turnId;
52
+ this.signal = start.signal;
51
53
  this.permissions = start.permissions;
52
54
  this.elicitation = start.elicitation;
53
55
  this.prompt = prompt;
@@ -442,6 +442,8 @@ export function codexErrorCategory(info) {
442
442
  case "unauthorized":
443
443
  return "auth";
444
444
  case "badRequest":
445
+ // A model the provider does not have, or the account cannot run.
446
+ case "modelNotFound":
445
447
  return "invalid_request";
446
448
  case "internalServerError":
447
449
  return "internal";
@@ -44,6 +44,13 @@ export class CodexRpcError extends Error {
44
44
  this.name = "CodexRpcError";
45
45
  }
46
46
  }
47
+ /** The `-c key=value` overrides the app-server starts with, for these options. */
48
+ export function configArgs(opts) {
49
+ return [
50
+ ...(opts.ephemeralCredentials ? ["-c", 'cli_auth_credentials_store="ephemeral"'] : []),
51
+ ...(opts.pluginsOff ? ["-c", "features.plugins=false"] : []),
52
+ ];
53
+ }
47
54
  /**
48
55
  * Newline-delimited (JSONL) JSON-RPC client over a `codex app-server` subprocess.
49
56
  * Requests get monotonic ids resolved against a pending map; notifications fan
@@ -203,11 +210,7 @@ export class CodexAppServerClient {
203
210
  this.nativeShutdownFailed = false;
204
211
  const native = this.opts.processes.spawn({
205
212
  command: this.opts.codexPath ?? "codex",
206
- args: [
207
- "app-server",
208
- ...(this.opts.ephemeralCredentials ? ["-c", 'cli_auth_credentials_store="ephemeral"'] : []),
209
- ...(this.opts.pluginsOff ? ["-c", "features.plugins=false"] : []),
210
- ],
213
+ args: ["app-server", ...configArgs(this.opts)],
211
214
  cwd: this.opts.cwd,
212
215
  env: this.opts.env ?? process.env,
213
216
  harness: "codex-app-server",