@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
@@ -39,13 +39,24 @@ async function modelThinking(session, model, known) {
39
39
  const levels = known ?? modelThinkingLevels("codex-app-server", model);
40
40
  return levels && { levels };
41
41
  }
42
- /** An effort fitted to what `model` accepts, so Codex is not asked for one it lacks. */
42
+ /**
43
+ * An effort fitted to what `model` accepts, so Codex is not asked for one it
44
+ * lacks. When the model's levels are known, the answer is always an effort it
45
+ * lists: the fit; else the model's own default effort; else the first level
46
+ * it lists, as Codex names it (its `none` or `minimal` for `off`). The effort
47
+ * as it was only when the model's levels are unknown or it lists none.
48
+ */
43
49
  async function fitEffort(session, model, effort, known) {
44
- const level = codexThinkingLevel(effort);
45
50
  const accepts = await modelThinking(session, model, known);
46
- return level && accepts?.levels.length
47
- ? codexReasoningEffort(level, accepts.levels, accepts.off)
48
- : effort;
51
+ const first = accepts?.levels[0];
52
+ if (!accepts || first === undefined)
53
+ return effort;
54
+ const level = codexThinkingLevel(effort);
55
+ return ((level && codexReasoningEffort(level, accepts.levels, accepts.off)) ??
56
+ accepts.defaultEffort ??
57
+ // A level the model lists always fits; `off` becomes its native effort.
58
+ codexReasoningEffort(first, accepts.levels, accepts.off) ??
59
+ first);
49
60
  }
50
61
  /** One logical session's thread settings, which outlive its processes. */
51
62
  export class CodexThread {
@@ -106,17 +117,24 @@ export class CodexThread {
106
117
  // A model known to have no reasoning control is sent no effort, and the
107
118
  // turn reports no level: the thread's effort does not apply to it.
108
119
  let noThinking = false;
120
+ // A level with no fit among the levels the model lists is not sent: the
121
+ // turn runs as one that names no level.
122
+ let unlisted = false;
109
123
  if (options.thinkingLevel) {
110
124
  const accepts = await modelThinking(session, next.model, known);
111
125
  if (accepts && !accepts.levels.length)
112
126
  noThinking = true;
113
127
  else {
114
128
  const effort = codexReasoningEffort(options.thinkingLevel, accepts?.levels, accepts?.off);
115
- params.effort = effort;
116
- next = { ...next, effort, effortSet: true };
129
+ if (effort === undefined)
130
+ unlisted = true;
131
+ else {
132
+ params.effort = effort;
133
+ next = { ...next, effort, effortSet: true };
134
+ }
117
135
  }
118
136
  }
119
- else {
137
+ if (!options.thinkingLevel || unlisted) {
120
138
  // Once a turn set the thread's effort, the default is worked out for
121
139
  // this turn's model. Otherwise, and when Codex cannot say what the
122
140
  // default is, the thread keeps its own effort, fitted to a model the
@@ -137,12 +155,13 @@ export class CodexThread {
137
155
  const collaboration = inCollaborationMode(next, mode);
138
156
  return {
139
157
  params: { ...params, ...collaboration.params },
140
- ...((level || next.reportedModel || noThinking) && {
158
+ ...((level || next.reportedModel || noThinking || unlisted) && {
141
159
  applied: {
142
160
  ...(level && { thinkingLevel: level }),
143
161
  ...(next.reportedModel && { model: next.reportedModel }),
144
- // The turn's level was not sent: its model has no reasoning control.
145
- ...(noThinking && { notApplied: ["thinkingLevel"] }),
162
+ // The turn's level was not sent: its model has no reasoning
163
+ // control, or does not list that level.
164
+ ...((noThinking || unlisted) && { notApplied: ["thinkingLevel"] }),
146
165
  },
147
166
  }),
148
167
  next: collaboration.next,
@@ -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)
@@ -157,7 +163,8 @@ export class ScriptedAgent extends SessionAgent {
157
163
  }
158
164
  async *play(step, turn) {
159
165
  const { options, signal } = turn;
160
- if (signal.aborted)
166
+ // A hang takes its `stopTakes` whenever the cancel came: a product's test cancels without a sleep.
167
+ if (signal.aborted && !("hang" in step))
161
168
  throw stopped();
162
169
  if ("say" in step)
163
170
  yield { type: "text", text: step.say };
@@ -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. */
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,