@zvada/agent-server 0.3.24 → 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 (190) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +3 -0
  3. package/dist/client/client.js +93 -34
  4. package/dist/core/agents/acp/acp-agent.js +91 -14
  5. package/dist/core/agents/acp/mappings.js +5 -1
  6. package/dist/core/agents/claude-code/approvals.js +2 -1
  7. package/dist/core/agents/claude-code/claude-agent.js +12 -2
  8. package/dist/core/agents/claude-code/mcp.js +9 -1
  9. package/dist/core/agents/claude-code/models.js +16 -10
  10. package/dist/core/agents/claude-code/options.js +23 -2
  11. package/dist/core/agents/claude-code/session.js +21 -1
  12. package/dist/core/agents/claude-code/tools.js +9 -4
  13. package/dist/core/agents/claude-code/turn.js +2 -0
  14. package/dist/core/agents/codex-app-server/adapter.js +2 -0
  15. package/dist/core/agents/codex-app-server/client.js +8 -5
  16. package/dist/core/agents/codex-app-server/codex-agent.js +35 -2
  17. package/dist/core/agents/codex-app-server/effort.js +13 -6
  18. package/dist/core/agents/codex-app-server/mcp.js +35 -18
  19. package/dist/core/agents/codex-app-server/models.js +10 -10
  20. package/dist/core/agents/codex-app-server/options.js +11 -2
  21. package/dist/core/agents/codex-app-server/session.js +11 -4
  22. package/dist/core/agents/codex-app-server/thread-settings.js +30 -11
  23. package/dist/core/agents/host-tools.js +493 -0
  24. package/dist/core/agents/mcp-config.js +6 -2
  25. package/dist/core/agents/scripted/scripted-agent.js +11 -4
  26. package/dist/core/agents/scripted/steps.js +5 -1
  27. package/dist/core/agents/session-agent.js +70 -2
  28. package/dist/core/agents/thinking-levels.js +8 -5
  29. package/dist/core/index.js +1 -0
  30. package/dist/core/presets.js +12 -2
  31. package/dist/core/processes/identity.js +1 -0
  32. package/dist/core/processes/lifeline.js +13 -1
  33. package/dist/core/processes/process-table.js +1 -0
  34. package/dist/core/provision/extract.js +1 -0
  35. package/dist/core/provision/pins.js +7 -16
  36. package/dist/core/provision/releases.js +25 -25
  37. package/dist/core/proxy/loopback.js +22 -4
  38. package/dist/core/runtime/agent-runtime.js +6 -3
  39. package/dist/core/runtime/turn.js +20 -10
  40. package/dist/protocol/config.js +21 -1
  41. package/dist/protocol/credentials.js +2 -1
  42. package/dist/protocol/errors.js +12 -3
  43. package/dist/protocol/model-catalog.js +58 -18
  44. package/dist/protocol/models.js +6 -27
  45. package/dist/protocol/thinking.js +22 -9
  46. package/dist/protocol/wire-api.js +2 -2
  47. package/dist/server/bin.js +6 -4
  48. package/dist/server/routes.js +3 -2
  49. package/dist/types/client/client.d.ts +6 -1
  50. package/dist/types/client/client.d.ts.map +1 -1
  51. package/dist/types/core/agents/acp/acp-agent.d.ts +15 -0
  52. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  53. package/dist/types/core/agents/acp/mappings.d.ts +5 -1
  54. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  55. package/dist/types/core/agents/acp/requests.d.ts +2 -0
  56. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  57. package/dist/types/core/agents/claude-code/approvals.d.ts +2 -1
  58. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  59. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -0
  60. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  61. package/dist/types/core/agents/claude-code/mcp.d.ts +8 -1
  62. package/dist/types/core/agents/claude-code/mcp.d.ts.map +1 -1
  63. package/dist/types/core/agents/claude-code/models.d.ts +9 -5
  64. package/dist/types/core/agents/claude-code/models.d.ts.map +1 -1
  65. package/dist/types/core/agents/claude-code/options.d.ts +14 -1
  66. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  67. package/dist/types/core/agents/claude-code/session.d.ts +2 -0
  68. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  69. package/dist/types/core/agents/claude-code/tools.d.ts.map +1 -1
  70. package/dist/types/core/agents/claude-code/turn.d.ts +3 -0
  71. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  72. package/dist/types/core/agents/codex-app-server/adapter.d.ts.map +1 -1
  73. package/dist/types/core/agents/codex-app-server/client.d.ts +2 -0
  74. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  75. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +11 -0
  76. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  77. package/dist/types/core/agents/codex-app-server/effort.d.ts +7 -7
  78. package/dist/types/core/agents/codex-app-server/effort.d.ts.map +1 -1
  79. package/dist/types/core/agents/codex-app-server/mcp.d.ts +11 -3
  80. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  81. package/dist/types/core/agents/codex-app-server/models.d.ts +4 -1
  82. package/dist/types/core/agents/codex-app-server/models.d.ts.map +1 -1
  83. package/dist/types/core/agents/codex-app-server/options.d.ts +9 -2
  84. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  85. package/dist/types/core/agents/codex-app-server/requests.d.ts +2 -0
  86. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  87. package/dist/types/core/agents/codex-app-server/session.d.ts +6 -3
  88. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  89. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts.map +1 -1
  90. package/dist/types/core/agents/host-tools.d.ts +162 -0
  91. package/dist/types/core/agents/host-tools.d.ts.map +1 -0
  92. package/dist/types/core/agents/mcp-config.d.ts +11 -2
  93. package/dist/types/core/agents/mcp-config.d.ts.map +1 -1
  94. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  95. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  96. package/dist/types/core/agents/scripted/steps.d.ts.map +1 -1
  97. package/dist/types/core/agents/session-agent.d.ts +2 -7
  98. package/dist/types/core/agents/session-agent.d.ts.map +1 -1
  99. package/dist/types/core/agents/thinking-levels.d.ts +7 -3
  100. package/dist/types/core/agents/thinking-levels.d.ts.map +1 -1
  101. package/dist/types/core/index.d.ts +1 -0
  102. package/dist/types/core/index.d.ts.map +1 -1
  103. package/dist/types/core/presets.d.ts +11 -1
  104. package/dist/types/core/presets.d.ts.map +1 -1
  105. package/dist/types/core/processes/identity.d.ts.map +1 -1
  106. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  107. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  108. package/dist/types/core/provision/extract.d.ts.map +1 -1
  109. package/dist/types/core/provision/pins.d.ts +5 -4
  110. package/dist/types/core/provision/pins.d.ts.map +1 -1
  111. package/dist/types/core/proxy/loopback.d.ts.map +1 -1
  112. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  113. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  114. package/dist/types/core/runtime/turn.d.ts +12 -7
  115. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  116. package/dist/types/protocol/clis.d.ts +3 -3
  117. package/dist/types/protocol/config.d.ts +12 -19
  118. package/dist/types/protocol/config.d.ts.map +1 -1
  119. package/dist/types/protocol/conversation.d.ts +10 -42
  120. package/dist/types/protocol/conversation.d.ts.map +1 -1
  121. package/dist/types/protocol/credentials.d.ts +13 -1
  122. package/dist/types/protocol/credentials.d.ts.map +1 -1
  123. package/dist/types/protocol/errors.d.ts +6 -4
  124. package/dist/types/protocol/errors.d.ts.map +1 -1
  125. package/dist/types/protocol/execution.d.ts +2 -18
  126. package/dist/types/protocol/execution.d.ts.map +1 -1
  127. package/dist/types/protocol/lifecycle.d.ts +12 -76
  128. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  129. package/dist/types/protocol/model-catalog.d.ts.map +1 -1
  130. package/dist/types/protocol/models.d.ts +4 -42
  131. package/dist/types/protocol/models.d.ts.map +1 -1
  132. package/dist/types/protocol/thinking.d.ts +19 -19
  133. package/dist/types/protocol/thinking.d.ts.map +1 -1
  134. package/dist/types/protocol/wire-api.d.ts +32 -117
  135. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  136. package/dist/types/protocol/wire.d.ts +24 -125
  137. package/dist/types/protocol/wire.d.ts.map +1 -1
  138. package/dist/types/server/routes.d.ts.map +1 -1
  139. package/docs/consuming.md +92 -12
  140. package/docs/deploy.md +8 -0
  141. package/docs/harnesses.md +88 -27
  142. package/package.json +4 -4
  143. package/src/client/client.ts +114 -44
  144. package/src/core/agents/acp/acp-agent.ts +123 -17
  145. package/src/core/agents/acp/mappings.ts +5 -1
  146. package/src/core/agents/acp/requests.ts +2 -0
  147. package/src/core/agents/claude-code/approvals.ts +2 -1
  148. package/src/core/agents/claude-code/claude-agent.ts +14 -2
  149. package/src/core/agents/claude-code/mcp.ts +11 -1
  150. package/src/core/agents/claude-code/models.ts +15 -10
  151. package/src/core/agents/claude-code/options.ts +37 -3
  152. package/src/core/agents/claude-code/session.ts +26 -1
  153. package/src/core/agents/claude-code/tools.ts +10 -4
  154. package/src/core/agents/claude-code/turn.ts +4 -0
  155. package/src/core/agents/codex-app-server/adapter.ts +2 -0
  156. package/src/core/agents/codex-app-server/client.ts +11 -5
  157. package/src/core/agents/codex-app-server/codex-agent.ts +45 -1
  158. package/src/core/agents/codex-app-server/effort.ts +15 -20
  159. package/src/core/agents/codex-app-server/mcp.ts +46 -23
  160. package/src/core/agents/codex-app-server/models.ts +10 -10
  161. package/src/core/agents/codex-app-server/options.ts +16 -2
  162. package/src/core/agents/codex-app-server/requests.ts +2 -0
  163. package/src/core/agents/codex-app-server/session.ts +19 -4
  164. package/src/core/agents/codex-app-server/thread-settings.ts +31 -11
  165. package/src/core/agents/host-tools.ts +649 -0
  166. package/src/core/agents/mcp-config.ts +15 -3
  167. package/src/core/agents/scripted/scripted-agent.ts +11 -3
  168. package/src/core/agents/scripted/steps.ts +5 -1
  169. package/src/core/agents/session-agent.ts +78 -2
  170. package/src/core/agents/thinking-levels.ts +9 -6
  171. package/src/core/index.ts +9 -0
  172. package/src/core/presets.ts +24 -3
  173. package/src/core/processes/identity.ts +1 -0
  174. package/src/core/processes/lifeline.ts +14 -1
  175. package/src/core/processes/process-table.ts +1 -0
  176. package/src/core/provision/extract.ts +1 -0
  177. package/src/core/provision/pins.ts +7 -16
  178. package/src/core/provision/releases.ts +25 -25
  179. package/src/core/proxy/loopback.ts +25 -4
  180. package/src/core/runtime/agent-runtime.ts +6 -3
  181. package/src/core/runtime/turn.ts +21 -9
  182. package/src/protocol/config.ts +22 -1
  183. package/src/protocol/credentials.ts +19 -5
  184. package/src/protocol/errors.ts +12 -3
  185. package/src/protocol/model-catalog.ts +58 -18
  186. package/src/protocol/models.ts +6 -26
  187. package/src/protocol/thinking.ts +27 -14
  188. package/src/protocol/wire-api.ts +2 -2
  189. package/src/server/bin.ts +6 -4
  190. package/src/server/routes.ts +3 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,116 @@ 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
+
90
+ ## 0.3.25
91
+
92
+ ### Changed
93
+
94
+ - A Codex resume refused because another app-server still holds the thread ("already
95
+ has an active writer") fails with the new error category `resume_busy`, not
96
+ `resume_failed`: the same resume succeeds once that one lets go. A product that
97
+ matched `resume_failed` retries later on `resume_busy` instead of starting fresh (LLP 0002).
98
+
99
+ ### Fixed
100
+
101
+ - Under Bun, the lifeline shell and the `ps` and `sysctl` the engine runs get its
102
+ `process.env` as it is now, not as Bun was launched: a secret your product, or the
103
+ bin's own `AGENT_SERVER_*_TOKEN`, deleted from `process.env` no longer lives on in
104
+ the lifeline for as long as the engine runs (LLP 0007, The environment a process is given).
105
+ - A cancel that lands after a turn is admitted and before its harness begins it ends
106
+ the turn `cancelled`, where the turn ran to its own end; its answer is still
107
+ `hadTurn: false` (on the wire `unconfirmed`). A scripted `hang` takes `stopTakes`
108
+ also when the cancel came first, so a test can cancel without a sleep (LLP 0001, D9).
109
+ - `AgentServerClient.cancelTurn` for a turn the same client is starting (`runTurn`,
110
+ `startTurn`) is sent after that start's first send: a cancel in the same tick as the
111
+ start ends the turn `cancelled`, where it got `no_active_turn` and the turn ran on
112
+ (LLP 0001, D9).
113
+ - The error classifier no longer reads a status code out of an identifier: a thread
114
+ id holding `-b401-` or `-a429-` no longer makes a failure `auth` or `rate_limit`
115
+ (LLP 0002, Open vocabularies).
116
+ - `credentialRunsOn` takes any `AgentHarness` and answers `{ ok: false, error }` for
117
+ ACP and scripted, which run on no credential a product holds, where it threw a
118
+ `TypeError`; a caller naming Claude or Codex keeps the narrow type (LLP 0012).
119
+
10
120
  ## 0.3.24
11
121
 
12
122
  ### Added
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)
@@ -21,6 +21,40 @@ function stopOn(handle, signal) {
21
21
  const off = () => signal.removeEventListener("abort", stop);
22
22
  void handle.result.then(off, off);
23
23
  }
24
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — a cancel sent right behind its start reaches the turn
25
+ /**
26
+ * The `turn/start`s this client has not sent yet, each from before its
27
+ * first `await` until its first send or its end. The server takes a
28
+ * connection's requests in order and admits a turn in its start's handler,
29
+ * so a cancel for one of their turns goes out after that first send. Once
30
+ * sent, a start delays no cancel: after a redial a cancel can overtake its
31
+ * re-send, and is answered `no_active_turn`. Before its first send a start
32
+ * waits only on the handshake, a request the client's close fails, so no
33
+ * cancel waits past the close.
34
+ */
35
+ class Starts {
36
+ unsent = new Set();
37
+ /** Record a start; the function returned lets it go (its first send, or its end), and may be called again. */
38
+ begin(sessionId, turnId) {
39
+ let settle = () => { };
40
+ const gone = new Promise((resolve) => {
41
+ settle = resolve;
42
+ });
43
+ const start = { sessionId, turnId, gone };
44
+ this.unsent.add(start);
45
+ return () => {
46
+ this.unsent.delete(start);
47
+ settle();
48
+ };
49
+ }
50
+ /** `send`, once no start of `turnId` (without one, of the session) is unsent; in the call when none is. */
51
+ after(sessionId, turnId, send) {
52
+ const waiting = [...this.unsent].filter((start) => start.sessionId === sessionId && (turnId === undefined || start.turnId === turnId));
53
+ if (waiting.length === 0)
54
+ return send();
55
+ return Promise.all(waiting.map((start) => start.gone)).then(send);
56
+ }
57
+ }
24
58
  /** How often `prepareClis` asks again while an install runs, besides when one ends. */
25
59
  const PREPARE_POLL_MS = 2_000;
26
60
  /**
@@ -36,6 +70,7 @@ export class AgentServerClient {
36
70
  options;
37
71
  connection;
38
72
  turns = new Turns();
73
+ starts = new Starts();
39
74
  progress = new Listeners();
40
75
  authUpdates = new Listeners();
41
76
  streams;
@@ -123,37 +158,47 @@ export class AgentServerClient {
123
158
  * it), and `onEvent` hears it to its end.
124
159
  */
125
160
  async runTurn(params, options = {}) {
126
- await this.initialize();
127
161
  const sessionId = params.sessionId ?? generateUUIDv7();
128
162
  const turnId = params.turnId ?? generateUUIDv7();
129
- if (this.turns.running(sessionId))
130
- throw new Error(`session ${sessionId} already has an active turn`);
131
- const handle = this.turns.open(sessionId, turnId, true);
132
- stopOn(handle, options.signal);
163
+ // Before the first `await`: a cancel sent right behind this call goes out after the start.
164
+ const release = this.starts.begin(sessionId, turnId);
133
165
  try {
134
- const accepted = await this.connection.resend(WIRE_METHODS.turnStart, { ...params, sessionId, turnId, subscribe: true },
135
- // A turn that already ended streams nothing: its end is in the ack.
136
- (ack) => {
137
- if (!ack.terminal)
138
- this.joinAt(handle, ack.headSeq, { turnId });
139
- });
140
- const { terminal } = accepted;
141
- if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
142
- throw new Error("Turn receipt belongs to a different request");
143
- // A retried start of a turn that already ended: its end, without its events
144
- // (`replay` or `history` serve its transcript).
145
- if (terminal)
146
- handle.push(terminal);
147
- else
148
- await this.catchUp(handle, accepted.deduplicated
149
- ? (accepted.startedSeq ?? accepted.headSeq + 1)
150
- : accepted.headSeq + 1, accepted.headSeq);
166
+ await this.initialize();
167
+ if (this.turns.running(sessionId))
168
+ throw new Error(`session ${sessionId} already has an active turn`);
169
+ const handle = this.turns.open(sessionId, turnId, true);
170
+ try {
171
+ stopOn(handle, options.signal);
172
+ // `resend` sends (or fails for no connection) before its first `await`, in this call.
173
+ const sending = this.connection.resend(WIRE_METHODS.turnStart, { ...params, sessionId, turnId, subscribe: true },
174
+ // A turn that already ended streams nothing: its end is in the ack.
175
+ (ack) => {
176
+ if (!ack.terminal)
177
+ this.joinAt(handle, ack.headSeq, { turnId });
178
+ });
179
+ release();
180
+ const accepted = await sending;
181
+ const { terminal } = accepted;
182
+ if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
183
+ throw new Error("Turn receipt belongs to a different request");
184
+ // A retried start of a turn that already ended: its end, without its events
185
+ // (`replay` or `history` serve its transcript).
186
+ if (terminal)
187
+ handle.push(terminal);
188
+ else
189
+ await this.catchUp(handle, accepted.deduplicated
190
+ ? (accepted.startedSeq ?? accepted.headSeq + 1)
191
+ : accepted.headSeq + 1, accepted.headSeq);
192
+ }
193
+ catch (error) {
194
+ handle.fail(error);
195
+ throw error;
196
+ }
197
+ return this.handleOf(handle);
151
198
  }
152
- catch (error) {
153
- handle.fail(error);
154
- throw error;
199
+ finally {
200
+ release();
155
201
  }
156
- return this.handleOf(handle);
157
202
  }
158
203
  /**
159
204
  * Quick-ack only: the turn's events reach `onEvent` through its
@@ -161,13 +206,23 @@ export class AgentServerClient {
161
206
  * before.
162
207
  */
163
208
  async startTurn(params) {
164
- await this.initialize();
165
209
  const sessionId = params.sessionId ?? generateUUIDv7();
166
210
  const turnId = params.turnId ?? generateUUIDv7();
167
- return this.connection.request(WIRE_METHODS.turnStart, { ...params, sessionId, turnId }, (ack) => {
168
- if (params.subscribe !== false && !ack.terminal)
169
- this.streams.joined(sessionId, ack.headSeq, { turnId });
170
- });
211
+ // As in `runTurn`: a cancel sent right behind this call goes out after the start.
212
+ const release = this.starts.begin(sessionId, turnId);
213
+ try {
214
+ await this.initialize();
215
+ // `request` sends (or fails for no connection) in this call.
216
+ const answer = this.connection.request(WIRE_METHODS.turnStart, { ...params, sessionId, turnId }, (ack) => {
217
+ if (params.subscribe !== false && !ack.terminal)
218
+ this.streams.joined(sessionId, ack.headSeq, { turnId });
219
+ });
220
+ release();
221
+ return await answer;
222
+ }
223
+ finally {
224
+ release();
225
+ }
171
226
  }
172
227
  /**
173
228
  * Join the turn running in `sessionId`. Yields, each once and in seq
@@ -228,13 +283,17 @@ export class AgentServerClient {
228
283
  * finished turn then returns `{outcome: "no_active_turn", activeTurnId}`
229
284
  * instead of killing the turn that replaced it. `{outcome: "unconfirmed"}`
230
285
  * means the harness did not acknowledge the interrupt — the agent may still
231
- * be running; `turn.ended` remains the source of truth.
286
+ * be running; `turn.ended` remains the source of truth. A cancel for a
287
+ * turn this client is starting (`runTurn`, `startTurn`) goes out after
288
+ * that start's first send, so one sent right behind the start reaches the
289
+ * turn. After a reconnect a cancel can reach the server before a re-sent
290
+ * start, and is then answered `no_active_turn`.
232
291
  */
233
292
  cancelTurn(sessionId, turnId) {
234
- return this.connection.request(WIRE_METHODS.turnCancel, {
293
+ return this.starts.after(sessionId, turnId, () => this.connection.request(WIRE_METHODS.turnCancel, {
235
294
  sessionId,
236
295
  ...(turnId !== undefined ? { turnId } : {}),
237
- });
296
+ }));
238
297
  }
239
298
  /** Answer a `permission.requested` event. */
240
299
  async respondPermission(sessionId, requestId, outcome) {
@@ -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();