@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
@@ -0,0 +1,493 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { MAX_REQUEST_TIMEOUT_MS, } from "../../protocol/index.js";
3
+ import { serveLoopback } from "../proxy/loopback.js";
4
+ import { onAbort } from "../utils/deadline.js";
5
+ import { InvalidRequestError, McpUnavailableError } from "../utils/errors.js";
6
+ // @ref LLP 0018#timeouts — a tool may run as long as a question may wait
7
+ /** How long a host tool call may run unless its source says otherwise. */
8
+ export const HOST_TOOL_TIMEOUT_MS = 30 * 60_000;
9
+ /** The MCP versions answered, newest first: the official SDK's list (1.32), as `operator/mcp.ts`. */
10
+ const MCP_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
11
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12
+ const ok = (id, result) => ({ jsonrpc: "2.0", id, result });
13
+ const fail = (id, code, message) => ({
14
+ jsonrpc: "2.0",
15
+ id,
16
+ error: { code, message },
17
+ });
18
+ const failed = (text) => ({
19
+ content: [{ type: "text", text }],
20
+ isError: true,
21
+ });
22
+ /**
23
+ * Answer one MCP message for `source`: the tool methods only. Null for a
24
+ * notification or a response.
25
+ */
26
+ async function answer(source, message, answering) {
27
+ if (!isRecord(message) || message.jsonrpc !== "2.0")
28
+ return fail(null, -32600, "Invalid Request");
29
+ const { id, method } = message;
30
+ const params = isRecord(message.params) ? message.params : {};
31
+ if (typeof method !== "string")
32
+ return null;
33
+ if (typeof id !== "string" && typeof id !== "number") {
34
+ if (method === "notifications/cancelled")
35
+ answering.calls?.get(params.requestId)?.("the agent cancelled the call");
36
+ return null;
37
+ }
38
+ switch (method) {
39
+ case "initialize":
40
+ return ok(id, {
41
+ protocolVersion: MCP_VERSIONS.find((v) => v === params.protocolVersion) ?? MCP_VERSIONS[0],
42
+ capabilities: { tools: {} },
43
+ serverInfo: { name: source.name, version: "1" },
44
+ ...(source.instructions && { instructions: source.instructions }),
45
+ });
46
+ case "ping":
47
+ return ok(id, {});
48
+ case "tools/list":
49
+ return ok(id, { tools: source.tools.map(listed) });
50
+ case "tools/call": {
51
+ const tool = source.tools.find((each) => each.name === params.name);
52
+ if (!tool)
53
+ return ok(id, failed(`No tool ${JSON.stringify(params.name)} on ${source.name}`));
54
+ // A client that already gave up is answered by no call.
55
+ if (answering.signal?.aborted)
56
+ return null;
57
+ // @ref LLP 0018#the-api — a call of a released session does not run
58
+ if (!answering.alive())
59
+ return ok(id, failed(`${source.name} of this session was released`));
60
+ // @ref LLP 0018#the-api — a call names its turn, or does not run
61
+ const who = answering.caller();
62
+ if (!who)
63
+ return ok(id, failed(`${source.name} answers only during a turn of this session, and none is running`));
64
+ const refused = answering.refuse?.(tool, who.caller);
65
+ if (refused)
66
+ return ok(id, failed(refused));
67
+ return ok(id, await run(source, tool, params.arguments, who, id, answering));
68
+ }
69
+ default:
70
+ return fail(id, -32601, `Method not found: ${method}`);
71
+ }
72
+ }
73
+ /** A tool as `tools/list` shows it: only the hints the host gave, so MCP's defaults hold for the rest. */
74
+ function listed({ name, description, inputSchema, annotations }) {
75
+ const hints = {
76
+ ...(annotations?.readOnly !== undefined && { readOnlyHint: annotations.readOnly }),
77
+ ...(annotations?.destructive !== undefined && { destructiveHint: annotations.destructive }),
78
+ };
79
+ return {
80
+ name,
81
+ description,
82
+ inputSchema,
83
+ ...(Object.keys(hints).length && { annotations: hints }),
84
+ };
85
+ }
86
+ // @ref LLP 0018#timeouts — the engine holds the limit: an in-process call has none of its own
87
+ /**
88
+ * One call. It ends at whichever comes first: the tool's answer, its limit,
89
+ * its client closing, the turn's cancel, the session's release. The engine's
90
+ * outcome is settled before the tool's signal aborts, so a tool that answers
91
+ * from its abort handler cannot turn a cut call into a success, and every
92
+ * path clears the timer and the listeners.
93
+ */
94
+ function run(source, tool, args, who, id, { calls, signal, running }) {
95
+ const call = new AbortController();
96
+ const limit = timeoutOf(source);
97
+ return new Promise((resolve) => {
98
+ let settled = false;
99
+ const offs = [];
100
+ const settle = (result) => {
101
+ if (settled)
102
+ return false;
103
+ settled = true;
104
+ clearTimeout(timer);
105
+ for (const off of offs)
106
+ off();
107
+ if (calls?.get(id) === stop)
108
+ calls.delete(id);
109
+ running.delete(stop);
110
+ resolve(result);
111
+ return true;
112
+ };
113
+ const stop = (why) => {
114
+ if (settle(failed(why)))
115
+ call.abort();
116
+ };
117
+ const timer = setTimeout(() => stop(`${tool.name} did not answer within ${limit / 1000} s, its time limit`), limit);
118
+ calls?.set(id, stop);
119
+ running.add(stop);
120
+ offs.push(onAbort(signal, () => stop("the agent gave the call up")));
121
+ offs.push(onAbort(who.signal, () => stop("the turn was cancelled")));
122
+ // A call already ended (its client or turn gone) never reaches the host:
123
+ // checked here, and the host is asked at once, with no tick between.
124
+ if (settled)
125
+ return;
126
+ const given = isRecord(args) ? args : {};
127
+ const fault = (error) => settle(failed(describe(error)));
128
+ let answered;
129
+ try {
130
+ answered = Promise.resolve(source.call(tool.name, given, who.caller, call.signal));
131
+ }
132
+ catch (error) {
133
+ fault(error);
134
+ return;
135
+ }
136
+ answered.then((result) => settle(asResult(tool, result)), fault).catch(fault);
137
+ });
138
+ }
139
+ /** A host's answer as MCP takes it; one not of the declared shape is the tool's failure. */
140
+ function asResult(tool, result) {
141
+ if (!isRecord(result) || !Array.isArray(result.content))
142
+ return failed(`${tool.name} answered with no content (a host tool's result is { content: [...] })`);
143
+ return { content: result.content, ...(result.isError === true && { isError: true }) };
144
+ }
145
+ /** The header that carries a session's secret: never its URL, which Codex logs (LLP 0018). */
146
+ const SECRET_HEADER = "authorization";
147
+ /** The hosts a harness process must reach directly, never through a proxy (`NO_PROXY`). */
148
+ export const LOOPBACK_HOSTS = ["127.0.0.1", "localhost"];
149
+ /**
150
+ * A harness's host tools: each session's source, asked once; for Claude an
151
+ * in-process server, for an agent that reaches it over HTTP the engine's own
152
+ * loopback endpoint, which knows a session by the secret its config carries.
153
+ */
154
+ export class HostToolSessions {
155
+ hostTools;
156
+ harness;
157
+ options;
158
+ entries = new Map();
159
+ bySecret = new Map();
160
+ loopback;
161
+ closed = false;
162
+ constructor(hostTools, harness, options = {}) {
163
+ this.hostTools = hostTools;
164
+ this.harness = harness;
165
+ this.options = options;
166
+ }
167
+ /** The session's source: asked at its first turn, the same one after. */
168
+ source(sessionId, cwd) {
169
+ return this.entry(sessionId, cwd)?.source ?? Promise.resolve(undefined);
170
+ }
171
+ // @ref LLP 0018#the-api — setup carries the exact entry it began with
172
+ /** The session's source and its HTTP server, both bound to the entry asked now. */
173
+ async lease(sessionId, cwd) {
174
+ const entry = this.entry(sessionId, cwd);
175
+ const source = await entry?.source;
176
+ if (!entry || !source || this.entries.get(sessionId) !== entry)
177
+ return undefined;
178
+ return { source, http: () => this.http(sessionId, entry, source) };
179
+ }
180
+ entry(sessionId, cwd) {
181
+ if (this.closed)
182
+ return undefined;
183
+ const existing = this.entries.get(sessionId);
184
+ if (existing)
185
+ return existing;
186
+ const entry = {
187
+ source: Promise.resolve(this.hostTools({ sessionId, cwd, harness: this.harness })),
188
+ running: new Set(),
189
+ };
190
+ this.entries.set(sessionId, entry);
191
+ // @ref LLP 0018#the-api — a late answer belongs to its own entry, never a successor's
192
+ entry.source.then((source) => {
193
+ if (this.entries.get(sessionId) === entry)
194
+ entry.resolved = source;
195
+ },
196
+ // A source that failed is asked again by the next turn.
197
+ () => {
198
+ if (this.entries.get(sessionId) === entry)
199
+ this.entries.delete(sessionId);
200
+ });
201
+ return entry;
202
+ }
203
+ /** Claude's in-process server for the session's source, its caller read from `live` at each call. */
204
+ inProcess(sessionId, source, live) {
205
+ const entry = this.entries.get(sessionId);
206
+ const answering = {
207
+ caller: () => this.caller(sessionId, live),
208
+ alive: () => entry !== undefined && this.entries.get(sessionId) === entry,
209
+ refuse: (tool, caller) => this.refuse(tool, caller),
210
+ calls: new Map(),
211
+ running: entry?.running ?? new Set(),
212
+ };
213
+ const instance = {
214
+ async connect(transport) {
215
+ // The transport closed: its calls stop, and nothing more is sent on it.
216
+ const closed = new AbortController();
217
+ answering.signal = closed.signal;
218
+ transport.onclose = () => closed.abort();
219
+ transport.onmessage = (message) => void answer(source, message, answering)
220
+ .then((reply) => {
221
+ if (reply !== null && !closed.signal.aborted)
222
+ return transport.send(reply);
223
+ })
224
+ .catch(() => { });
225
+ await transport.start();
226
+ },
227
+ };
228
+ return { type: "sdk", name: source.name, timeout: timeoutOf(source), instance };
229
+ }
230
+ async http(sessionId, entry, source) {
231
+ const owner = () => {
232
+ if (this.closed || this.entries.get(sessionId) !== entry || entry.resolved !== source)
233
+ throw new Error(`the host's tools of session ${sessionId} were released`);
234
+ };
235
+ owner();
236
+ this.loopback ??= serveLoopback((request) => this.serve(request));
237
+ const starting = this.loopback;
238
+ let url;
239
+ try {
240
+ ({ url } = await starting);
241
+ }
242
+ catch (error) {
243
+ if (this.loopback === starting)
244
+ this.loopback = undefined;
245
+ const cause = describe(error);
246
+ throw new McpUnavailableError({
247
+ [source.name]: `the engine's loopback did not start: ${cause}`,
248
+ });
249
+ }
250
+ owner();
251
+ if (!entry.secret) {
252
+ entry.secret = randomBytes(32).toString("base64url");
253
+ this.bySecret.set(entry.secret, sessionId);
254
+ }
255
+ return {
256
+ type: "http",
257
+ url: `${url}/host-tools`,
258
+ headers: { [SECRET_HEADER]: `Bearer ${entry.secret}` },
259
+ timeoutMs: timeoutOf(source),
260
+ };
261
+ }
262
+ /** The session's secret, when it has one: no text the engine lets out may hold it. */
263
+ secretOf(sessionId) {
264
+ return this.entries.get(sessionId)?.secret;
265
+ }
266
+ /** Forget the session: its source, its calls, and its secret, which answers no more. */
267
+ release(sessionId) {
268
+ const entry = this.entries.get(sessionId);
269
+ if (!entry)
270
+ return;
271
+ this.entries.delete(sessionId);
272
+ if (entry.secret)
273
+ this.bySecret.delete(entry.secret);
274
+ for (const stop of [...entry.running])
275
+ stop("the session was released");
276
+ }
277
+ async close() {
278
+ this.closed = true;
279
+ for (const sessionId of [...this.entries.keys()])
280
+ this.release(sessionId);
281
+ const loopback = this.loopback;
282
+ this.loopback = undefined;
283
+ await (await loopback?.catch(() => undefined))?.close();
284
+ }
285
+ caller(sessionId, live) {
286
+ const turn = live();
287
+ if (!turn)
288
+ return undefined;
289
+ const { signal, turnId, permissionMode } = turn;
290
+ return { caller: { sessionId, harness: this.harness, turnId, permissionMode }, signal };
291
+ }
292
+ // @ref LLP 0018#permissions — an ACP agent's writes run only with full access
293
+ refuse(tool, caller) {
294
+ if (!this.options.writesNeedFullAccess || tool.annotations?.readOnly)
295
+ return undefined;
296
+ if (caller.permissionMode === "bypass_permissions")
297
+ return undefined;
298
+ return `${tool.name} changes something, and this agent cannot ask the person first: it runs only when the session has full access (bypass_permissions)`;
299
+ }
300
+ /** The session a request's bearer names, and its entry, when both still stand. */
301
+ bearer(request) {
302
+ const given = /^Bearer (.+)$/i.exec(request.headers.get(SECRET_HEADER) ?? "")?.[1];
303
+ const sessionId = given === undefined ? undefined : this.bySecret.get(given);
304
+ const entry = sessionId === undefined ? undefined : this.entries.get(sessionId);
305
+ return sessionId !== undefined && entry?.resolved && entry.secret === given
306
+ ? { sessionId, entry }
307
+ : undefined;
308
+ }
309
+ /** One MCP POST: a secret of no session's, or none, is refused; never a 401, which starts OAuth. */
310
+ async serve(request) {
311
+ const before = this.bearer(request);
312
+ if (!before)
313
+ return new Response("Forbidden", { status: 403 });
314
+ if (new URL(request.url).pathname !== "/host-tools" || request.method !== "POST")
315
+ return new Response(null, { status: 405, headers: { Allow: "POST" } });
316
+ let message;
317
+ try {
318
+ message = await request.json();
319
+ }
320
+ catch {
321
+ return Response.json(fail(null, -32700, "Parse error"), { status: 400 });
322
+ }
323
+ // @ref LLP 0018#codex — the bearer still names the same session and source once the body is read
324
+ const now = this.bearer(request);
325
+ if (now?.entry !== before.entry)
326
+ return new Response("Forbidden", { status: 403 });
327
+ const { sessionId, entry } = now;
328
+ const source = entry.resolved;
329
+ const reply = await answer(source, message, {
330
+ caller: () => this.caller(sessionId, () => this.options.live?.(sessionId)),
331
+ alive: () => this.entries.get(sessionId) === entry,
332
+ refuse: (tool, caller) => this.refuse(tool, caller),
333
+ signal: request.signal,
334
+ running: entry.running,
335
+ });
336
+ return reply === null ? new Response(null, { status: 202 }) : Response.json(reply);
337
+ }
338
+ }
339
+ /** A harness's host tools, when the operator gives any. */
340
+ export function hostToolSessions(hostTools, harness, options) {
341
+ return hostTools && new HostToolSessions(hostTools, harness, options);
342
+ }
343
+ // @ref LLP 0018#timeouts — the wire's own cap: a larger delay is a 1 ms timer on Node
344
+ /** A source's limit when the wire would take it (a positive whole number of ms, at most a timer's limit), else the default. */
345
+ function timeoutOf(source) {
346
+ const limit = source.timeoutMs;
347
+ const valid = limit !== undefined && Number.isInteger(limit) && limit > 0 && limit <= MAX_REQUEST_TIMEOUT_MS;
348
+ return valid ? limit : HOST_TOOL_TIMEOUT_MS;
349
+ }
350
+ /** A turn's own server may not take the host tools' name: neither harness would say whose it is. */
351
+ export function refuseHostName(servers, name) {
352
+ if (servers?.[name] !== undefined)
353
+ throw new InvalidRequestError([
354
+ { path: `mcpServers.${name}`, message: "the host's own tools have this name" },
355
+ ]);
356
+ }
357
+ /** The variables that name a proxy, in both spellings. */
358
+ const PROXY_VARIABLES = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"].flatMap((name) => [
359
+ name,
360
+ name.toLowerCase(),
361
+ ]);
362
+ // @ref LLP 0018#codex — the loopback reached directly, and a bare `*` left exactly as it is
363
+ /**
364
+ * The environment `env` changes to for the loopback to be reached directly,
365
+ * each value `""` for a variable to leave out:
366
+ * - each of `NO_PROXY` and `no_proxy` that is set gets the loopback hosts
367
+ * added to its own list (a tool may read either, and the two may differ);
368
+ * with neither set, both name the loopback;
369
+ * - one whose value is exactly `*` (no proxy for anything) is left as it is,
370
+ * since a client may honour `*` only as the whole value (Codex 0.169.1 sent
371
+ * its model's traffic through the proxy once it read `*,127.0.0.1`); when
372
+ * the value a client reads (`NO_PROXY`, else `no_proxy`) is exactly `*`, the
373
+ * proxy variables are left out instead: Codex's MCP client (hyper-util
374
+ * 0.1.20) checks an IP address only against IP entries, so `*` alone left
375
+ * 127.0.0.1 to the proxy, and with `*` the person asked for no proxy at all.
376
+ * A `*` inside a longer list is extended like any other list.
377
+ */
378
+ export function loopbackDirect(env) {
379
+ const names = ["NO_PROXY", "no_proxy"].filter((name) => env[name] !== undefined);
380
+ if (!names.length)
381
+ return { NO_PROXY: LOOPBACK_HOSTS.join(","), no_proxy: LOOPBACK_HOSTS.join(",") };
382
+ const lists = names.map((name) => {
383
+ const list = env[name]
384
+ .split(",")
385
+ .map((host) => host.trim())
386
+ .filter(Boolean);
387
+ return [name, list];
388
+ });
389
+ // The value a client reads: `NO_PROXY`, else `no_proxy` (hyper-util's order).
390
+ const effective = (env.NO_PROXY ?? env.no_proxy ?? "").trim();
391
+ const bare = ([, list]) => list.length === 1 && list[0] === "*";
392
+ return Object.fromEntries([
393
+ ...(effective === "*"
394
+ ? PROXY_VARIABLES.filter((name) => env[name] !== undefined).map((name) => [name, ""])
395
+ : []),
396
+ ...lists
397
+ .filter((entry) => !bare(entry))
398
+ .map(([name, list]) => [
399
+ name,
400
+ [...list, ...LOOPBACK_HOSTS.filter((host) => !list.includes(host))].join(","),
401
+ ]),
402
+ ]);
403
+ }
404
+ /** An error's words, for a call's failure: never a throw of its own. */
405
+ function describe(error) {
406
+ try {
407
+ return error instanceof Error ? String(error.message) : String(error);
408
+ }
409
+ catch {
410
+ return "the tool failed, and its error could not be read";
411
+ }
412
+ }
413
+ /** `env` with the loopback reached directly: a variable left out is gone, not empty. */
414
+ export function withLoopbackDirect(env) {
415
+ const changes = loopbackDirect(env);
416
+ const out = { ...env, ...changes };
417
+ for (const [name, value] of Object.entries(changes))
418
+ if (value === "")
419
+ delete out[name];
420
+ return out;
421
+ }
422
+ // @ref LLP 0018#who-can-read-the-secret — no serialising; a copy only of an event that holds it
423
+ /**
424
+ * `value` with `secret` replaced by `[redacted]` in every string, key and
425
+ * value alike, at any depth. A first pass looks for it without copying, so
426
+ * an event that does not hold it is returned as it is. One that does is
427
+ * copied whole (arrays and plain objects; strings are shared), each object
428
+ * once, so two fields sharing an object share its copy and a cycle stays a
429
+ * cycle in the copy. An error is changed in place: its message, stack,
430
+ * cause and every own field (`data`). Other objects are left as they are.
431
+ */
432
+ export function withoutSecret(value, secret) {
433
+ if (!secret)
434
+ return value;
435
+ const plain = (each) => Array.isArray(each) ||
436
+ Object.getPrototypeOf(each) === Object.prototype ||
437
+ Object.getPrototypeOf(each) === null;
438
+ const fieldsOf = (error) => ["message", "stack", "cause", ...Object.keys(error)];
439
+ const seen = new Set();
440
+ const holds = (each) => {
441
+ if (typeof each === "string")
442
+ return each.includes(secret);
443
+ if (typeof each !== "object" || each === null || seen.has(each))
444
+ return false;
445
+ seen.add(each);
446
+ const fields = each;
447
+ if (each instanceof Error)
448
+ return fieldsOf(each).some((key) => holds(fields[key]));
449
+ if (!plain(each))
450
+ return false;
451
+ return Object.entries(fields).some(([key, field]) => key.includes(secret) || holds(field));
452
+ };
453
+ if (!holds(value))
454
+ return value;
455
+ const copies = new Map();
456
+ const copy = (each) => {
457
+ if (typeof each === "string")
458
+ return each.replaceAll(secret, "[redacted]");
459
+ if (typeof each !== "object" || each === null)
460
+ return each;
461
+ if (copies.has(each))
462
+ return copies.get(each);
463
+ if (each instanceof Error) {
464
+ copies.set(each, each);
465
+ const fields = each;
466
+ for (const key of fieldsOf(each))
467
+ if (fields[key] !== undefined)
468
+ fields[key] = copy(fields[key]);
469
+ return each;
470
+ }
471
+ if (!plain(each))
472
+ return each;
473
+ if (Array.isArray(each)) {
474
+ const out = [];
475
+ copies.set(each, out);
476
+ for (const item of each)
477
+ out.push(copy(item));
478
+ return out;
479
+ }
480
+ const out = Object.create(Object.getPrototypeOf(each));
481
+ copies.set(each, out);
482
+ // Own data properties: a JSON `__proto__` key assigned would set the copy's prototype.
483
+ for (const [key, field] of Object.entries(each))
484
+ Object.defineProperty(out, copy(key), {
485
+ value: copy(field),
486
+ enumerable: true,
487
+ writable: true,
488
+ configurable: true,
489
+ });
490
+ return out;
491
+ };
492
+ return copy(value);
493
+ }
@@ -8,9 +8,13 @@ export function snapshotMcpServers(servers) {
8
8
  function mcpServerRequired(server) {
9
9
  return server?.required !== false;
10
10
  }
11
- /** The server as its harness takes it: whether a turn needs it is the engine's rule. */
11
+ /**
12
+ * The server as a harness takes it: whether a turn needs it is the engine's
13
+ * rule, and how long a tool call may run each harness says in its own way
14
+ * (Claude's `timeout`, Codex's `tool_timeout_sec`), if at all.
15
+ */
12
16
  export function nativeMcpServer(server) {
13
- const { required: _required, ...native } = server;
17
+ const { required: _required, timeoutMs: _timeoutMs, ...native } = server;
14
18
  return native;
15
19
  }
16
20
  export function mcpConnectionErrors(names, statuses) {
@@ -121,8 +121,10 @@ export class ScriptedAgent extends SessionAgent {
121
121
  }
122
122
  async *executeTurn(input, options, controller) {
123
123
  const { signal } = controller;
124
- if (signal.aborted)
125
- throw stopped();
124
+ // A turn cancelled before it began is still a turn of its script: it
125
+ // opens it and stops at its first step (or at its end, when it has no
126
+ // step), so a queue skips the turn's steps through its `end` and the
127
+ // next turn plays its own.
126
128
  // A script runs nothing of its own: the abort stops it, so a cancel is confirmed at once.
127
129
  this.cancelWith(options, async () => true);
128
130
  const { sessionId, turnId } = options;
@@ -141,8 +143,12 @@ export class ScriptedAgent extends SessionAgent {
141
143
  for (let n = 1;; n++) {
142
144
  // What the step before did is the value of its `yield` in a generator.
143
145
  const next = await untilAborted(Promise.resolve(iterator.next(outcome)), signal);
144
- if (next.done)
146
+ if (next.done) {
147
+ // No step left to stop at: the cancel was confirmed, so the turn ends cancelled.
148
+ if (signal.aborted)
149
+ throw stopped();
145
150
  return;
151
+ }
146
152
  const step = readStep(next.value, `Step ${n} of turn ${turnId}`);
147
153
  const played = yield* this.play(step, turn);
148
154
  if ("stop" in played || "end" in step)
@@ -59,7 +59,11 @@ export const ScriptStepSchema = z.union([
59
59
  z.strictObject({ echo: z.enum(["input", "config"]) }),
60
60
  /** A pause of this many ms. */
61
61
  z.strictObject({ wait: Ms }),
62
- /** Runs until the turn is cancelled, then `stopTakes` ms more before it stops, also when the cancel came first. */
62
+ /**
63
+ * Runs until the turn is cancelled, then `stopTakes` ms more before it
64
+ * stops, also when the cancel came first; not in an async generator's
65
+ * script, whose next step a cancel does not wait for.
66
+ */
63
67
  z.strictObject({ hang: z.literal(true), stopTakes: Ms.optional() }),
64
68
  /**
65
69
  * Ends the turn in an error with this message: of `category` when given,
@@ -2,6 +2,7 @@ import { withTimeout } from "../utils/deadline.js";
2
2
  import { SessionResumeError, TurnActiveError } from "../utils/errors.js";
3
3
  import { BaseAgent, CANCEL_CONFIRM_MS, } from "./base.js";
4
4
  import { configFingerprint } from "./config-fingerprint.js";
5
+ import { withoutSecret } from "./host-tools.js";
5
6
  /**
6
7
  * The execution lifecycle the engine's own harnesses extend: one turn owns a
7
8
  * logical session from preparation through native cleanup, with steering,
@@ -9,6 +10,43 @@ import { configFingerprint } from "./config-fingerprint.js";
9
10
  * exported while its design is a Draft (LLP 0016); a product's own harness
10
11
  * extends `BaseAgent`, the public base.
11
12
  */
13
+ // @ref LLP 0018#who-can-read-the-secret — the broker publishes a request's options too
14
+ /**
15
+ * A permission request as the broker publishes it: its tool call and its
16
+ * options (a harness's own labels and ids) without the secret, and the
17
+ * option picked mapped back to the harness's own id.
18
+ */
19
+ async function permission(ask, scrub, call, rest) {
20
+ const [opts] = rest;
21
+ if (!opts)
22
+ return ask(scrub(call), ...rest);
23
+ const scrubbed = scrub(opts);
24
+ // A choice whose id held the secret gets an opaque id of its own, unique, so
25
+ // two redacted the same can never be taken for each other.
26
+ const used = new Set((scrubbed.options ?? []).flatMap((option, index) => opts.options?.[index]?.optionId === option.optionId ? [option.optionId] : []));
27
+ const opaque = (index) => {
28
+ let id = `redacted-option-${index}`;
29
+ while (used.has(id))
30
+ id += "-";
31
+ used.add(id);
32
+ return id;
33
+ };
34
+ const choices = (scrubbed.options ?? []).map((option, index) => {
35
+ const own = opts.options?.[index]?.optionId ?? option.optionId;
36
+ return {
37
+ option: own === option.optionId ? option : { ...option, optionId: opaque(index) },
38
+ own,
39
+ };
40
+ });
41
+ const native = new Map(choices.map(({ option, own }) => [option.optionId, own]));
42
+ const shown = scrubbed.options
43
+ ? { ...scrubbed, options: choices.map(({ option }) => option) }
44
+ : scrubbed;
45
+ const decision = await ask(scrub(call), shown);
46
+ if (decision.decision === "cancel" || decision.optionId === undefined)
47
+ return decision;
48
+ return { ...decision, optionId: native.get(decision.optionId) ?? decision.optionId };
49
+ }
12
50
  export class SessionAgent extends BaseAgent {
13
51
  terminated = false;
14
52
  /**
@@ -53,8 +91,33 @@ export class SessionAgent extends BaseAgent {
53
91
  try {
54
92
  // The adapter still produces its native cancellation result for an
55
93
  // already-aborted turn. It must not select a conversation or do setup.
56
- const prepared = controller.signal.aborted ? options : this.prepareSessionOptions(options);
57
- yield* this.executeTurn(input, prepared, controller);
94
+ const ready = controller.signal.aborted ? options : this.prepareSessionOptions(options);
95
+ // @ref LLP 0018#who-can-read-the-secret — the session's own secret leaves in no text
96
+ // Kept for the turn once seen: its output may still drain after the session's release.
97
+ let secret;
98
+ const scrub = (value) => {
99
+ secret ??= this.hostSecret(sessionId);
100
+ return withoutSecret(value, secret);
101
+ };
102
+ const { onWarning, onPermissionRequest, onElicitationRequest } = ready;
103
+ const prepared = {
104
+ ...ready,
105
+ ...(onWarning && { onWarning: (warning) => onWarning(scrub(warning)) }),
106
+ // What the broker puts on the stream (a request's input, its title) is the agent's text too.
107
+ ...(onPermissionRequest && {
108
+ onPermissionRequest: (call, ...rest) => permission(onPermissionRequest, scrub, call, rest),
109
+ }),
110
+ ...(onElicitationRequest && {
111
+ onElicitationRequest: (request, ...rest) => onElicitationRequest(scrub(request), ...rest),
112
+ }),
113
+ };
114
+ try {
115
+ for await (const event of this.executeTurn(input, prepared, controller))
116
+ yield scrub(event);
117
+ }
118
+ catch (error) {
119
+ throw scrub(error);
120
+ }
58
121
  }
59
122
  finally {
60
123
  this.executed.set(sessionId, options.turnId);
@@ -167,6 +230,11 @@ export class SessionAgent extends BaseAgent {
167
230
  if (turn?.turnId === options.turnId)
168
231
  turn.deliver = undefined;
169
232
  }
233
+ /** Native protocol execution; options are prepared and the session is exclusively owned. */
234
+ /** The session's host-tools secret, which no event, warning or error it lets out may hold. */
235
+ hostSecret(_sessionId) {
236
+ return undefined;
237
+ }
170
238
  prepareSessionOptions(options) {
171
239
  const boundary = configFingerprint({
172
240
  cwd: options.cwd,
@@ -1,9 +1,12 @@
1
- import { THINKING_LEVELS, isThinkingLevel } from "../../protocol/index.js";
2
- /** The values that are thinking levels, once each, lowest first. */
3
- export function knownThinkingLevels(values) {
1
+ /**
2
+ * The levels a harness lists: each non-blank string once, in the order given.
3
+ * The order is the harness's own (both CLIs list lowest first), and a name
4
+ * this build does not know is kept.
5
+ */
6
+ export function listedThinkingLevels(values) {
4
7
  const levels = new Set();
5
8
  for (const value of values)
6
- if (typeof value === "string" && isThinkingLevel(value))
9
+ if (typeof value === "string" && /\S/.test(value))
7
10
  levels.add(value);
8
- return THINKING_LEVELS.filter((level) => levels.has(level));
11
+ return [...levels];
9
12
  }
@@ -6,6 +6,7 @@ export { EventSinkError, callbackSink, CollectingSink, serialSink, teeSink, } fr
6
6
  export { BaseAgent, } from "./agents/base.js";
7
7
  export { AgentRegistry } from "./agents/registry.js";
8
8
  export { credentialsFromUrl } from "./agents/credentials.js";
9
+ export { HOST_TOOL_TIMEOUT_MS, } from "./agents/host-tools.js";
9
10
  export { INHERIT_CONFIGS, isInheritConfig, } from "./agents/inherit-config.js";
10
11
  // Native processes: each CLI in a group of its own, held by the lifeline, recorded, swept at restart.
11
12
  export { DEFAULT_GRACE_MS, NativeProcess, NativeProcesses, } from "./processes/native-processes.js";