@zvada/agent-server 0.3.23 → 0.3.25

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 (280) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +14 -5
  3. package/dist/accounts/chatgpt.js +144 -0
  4. package/dist/accounts/check.js +71 -0
  5. package/dist/accounts/claude.js +80 -0
  6. package/dist/accounts/endpoint.js +104 -0
  7. package/dist/accounts/http.js +58 -0
  8. package/dist/accounts/index.js +9 -0
  9. package/dist/client/client.js +745 -0
  10. package/dist/client/connection.js +338 -0
  11. package/dist/client/history.js +49 -0
  12. package/dist/client/index.js +6 -0
  13. package/dist/client/listeners.js +19 -0
  14. package/dist/client/logins.js +92 -0
  15. package/dist/client/rpc.js +105 -0
  16. package/dist/client/streams.js +432 -0
  17. package/dist/client/transports.js +118 -0
  18. package/dist/client/turns.js +122 -0
  19. package/dist/core/agents/acp/acp-agent.js +425 -0
  20. package/dist/core/agents/acp/adapter.js +231 -0
  21. package/dist/core/agents/acp/client.js +222 -0
  22. package/dist/core/agents/acp/known-agents.js +57 -0
  23. package/dist/core/agents/acp/mappings.js +164 -0
  24. package/dist/core/agents/acp/requests.js +79 -0
  25. package/dist/core/agents/attachments.js +14 -0
  26. package/dist/core/agents/base.js +64 -0
  27. package/dist/core/agents/claude-code/adapter.js +474 -0
  28. package/dist/core/agents/claude-code/approvals.js +245 -0
  29. package/dist/core/agents/claude-code/claude-agent.js +319 -0
  30. package/dist/core/agents/claude-code/credentials.js +142 -0
  31. package/dist/core/agents/claude-code/events.js +11 -0
  32. package/dist/core/agents/claude-code/login.js +217 -0
  33. package/dist/core/agents/claude-code/mcp.js +181 -0
  34. package/dist/core/agents/claude-code/models.js +74 -0
  35. package/dist/core/agents/claude-code/options.js +240 -0
  36. package/dist/core/agents/claude-code/outcome.js +204 -0
  37. package/dist/core/agents/claude-code/results.js +58 -0
  38. package/dist/core/agents/claude-code/sdk-pair.js +59 -0
  39. package/dist/core/agents/claude-code/session.js +593 -0
  40. package/dist/core/agents/claude-code/spawn.js +125 -0
  41. package/dist/core/agents/claude-code/spend.js +118 -0
  42. package/dist/core/agents/claude-code/tools.js +131 -0
  43. package/dist/core/agents/claude-code/turn-usage.js +121 -0
  44. package/dist/core/agents/claude-code/turn.js +199 -0
  45. package/dist/core/agents/codex-app-server/adapter.js +463 -0
  46. package/dist/core/agents/codex-app-server/client.js +338 -0
  47. package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
  48. package/dist/core/agents/codex-app-server/commands.js +184 -0
  49. package/dist/core/agents/codex-app-server/credentials.js +92 -0
  50. package/dist/core/agents/codex-app-server/effort.js +13 -0
  51. package/dist/core/agents/codex-app-server/events.js +18 -0
  52. package/dist/core/agents/codex-app-server/homes.js +118 -0
  53. package/dist/core/agents/codex-app-server/input.js +52 -0
  54. package/dist/core/agents/codex-app-server/items.js +307 -0
  55. package/dist/core/agents/codex-app-server/login.js +183 -0
  56. package/dist/core/agents/codex-app-server/mcp.js +323 -0
  57. package/dist/core/agents/codex-app-server/models.js +160 -0
  58. package/dist/core/agents/codex-app-server/options.js +155 -0
  59. package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
  60. package/dist/core/agents/codex-app-server/protocol.js +38 -0
  61. package/dist/core/agents/codex-app-server/requests.js +250 -0
  62. package/dist/core/agents/codex-app-server/session.js +278 -0
  63. package/dist/core/agents/codex-app-server/subagents.js +260 -0
  64. package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
  65. package/dist/core/agents/codex-app-server/turn-items.js +69 -0
  66. package/dist/core/agents/codex-app-server/turn.js +448 -0
  67. package/dist/core/agents/codex-app-server/user-login.js +78 -0
  68. package/dist/core/agents/config-fingerprint.js +10 -0
  69. package/dist/core/agents/credentials.js +71 -0
  70. package/dist/core/agents/diffs.js +27 -0
  71. package/dist/core/agents/elicitation.js +42 -0
  72. package/dist/core/agents/inherit-config.js +5 -0
  73. package/dist/core/agents/login.js +56 -0
  74. package/dist/core/agents/mcp-config.js +109 -0
  75. package/dist/core/agents/plan.js +6 -0
  76. package/dist/core/agents/process-pool.js +307 -0
  77. package/dist/core/agents/registry.js +49 -0
  78. package/dist/core/agents/scripted/adapter.js +86 -0
  79. package/dist/core/agents/scripted/mcp-call.js +74 -0
  80. package/dist/core/agents/scripted/scripted-agent.js +331 -0
  81. package/dist/core/agents/scripted/scripts.js +154 -0
  82. package/dist/core/agents/scripted/steps.js +87 -0
  83. package/dist/core/agents/session-agent.js +209 -0
  84. package/dist/core/agents/stderr-tail.js +71 -0
  85. package/dist/core/agents/thinking-levels.js +9 -0
  86. package/dist/core/agents/types.js +1 -0
  87. package/dist/core/diagnostics.js +23 -0
  88. package/dist/core/index.js +31 -0
  89. package/dist/core/presets.js +114 -0
  90. package/dist/core/processes/identity.js +92 -0
  91. package/dist/core/processes/lifeline.js +218 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +164 -0
  94. package/dist/core/provision/cache-trust.js +121 -0
  95. package/dist/core/provision/cache-usage.js +61 -0
  96. package/dist/core/provision/checksums.js +22 -0
  97. package/dist/core/provision/extract.js +29 -0
  98. package/dist/core/provision/index.js +4 -0
  99. package/dist/core/provision/install-build.js +99 -0
  100. package/dist/core/provision/npm.js +316 -0
  101. package/dist/core/provision/pins.js +35 -0
  102. package/dist/core/provision/platform.js +65 -0
  103. package/dist/core/provision/provisioner.js +372 -0
  104. package/dist/core/provision/releases.js +68 -0
  105. package/dist/core/provision/tools.js +279 -0
  106. package/dist/core/proxy/anthropic-proxy.js +163 -0
  107. package/dist/core/proxy/api-key-store.js +30 -0
  108. package/dist/core/proxy/index.js +3 -0
  109. package/dist/core/proxy/loopback.js +86 -0
  110. package/dist/core/runtime/agent-runtime.js +437 -0
  111. package/dist/core/runtime/event-processor.js +379 -0
  112. package/dist/core/runtime/event-sink.js +65 -0
  113. package/dist/core/runtime/harness-clis.js +83 -0
  114. package/dist/core/runtime/harness-logins.js +313 -0
  115. package/dist/core/runtime/login-reads.js +71 -0
  116. package/dist/core/runtime/model-lists.js +160 -0
  117. package/dist/core/runtime/permission-policy.js +84 -0
  118. package/dist/core/runtime/request-broker.js +139 -0
  119. package/dist/core/runtime/steering.js +79 -0
  120. package/dist/core/runtime/turn-outcome.js +16 -0
  121. package/dist/core/runtime/turn.js +339 -0
  122. package/dist/core/utils/bounded.js +13 -0
  123. package/dist/core/utils/deadline.js +57 -0
  124. package/dist/core/utils/errors.js +176 -0
  125. package/dist/core/utils/is-record.js +4 -0
  126. package/dist/core/utils/loopback.js +11 -0
  127. package/dist/index.js +4 -0
  128. package/dist/operator/index.js +10 -0
  129. package/dist/operator/mcp.js +139 -0
  130. package/dist/operator/operator.js +499 -0
  131. package/dist/operator/render.js +408 -0
  132. package/dist/operator/view.js +35 -0
  133. package/dist/protocol/account.js +96 -0
  134. package/dist/protocol/async-queue.js +65 -0
  135. package/dist/protocol/auth.js +169 -0
  136. package/dist/protocol/canonical.js +18 -0
  137. package/dist/protocol/clis.js +63 -0
  138. package/dist/protocol/config.js +137 -0
  139. package/dist/protocol/conversation.js +231 -0
  140. package/dist/protocol/credentials.js +142 -0
  141. package/dist/protocol/errors.js +190 -0
  142. package/dist/protocol/execution.js +28 -0
  143. package/dist/protocol/factories.js +231 -0
  144. package/dist/protocol/guards.js +71 -0
  145. package/dist/protocol/harness.js +93 -0
  146. package/dist/protocol/history.js +201 -0
  147. package/dist/protocol/ids.js +37 -0
  148. package/dist/protocol/index.js +36 -0
  149. package/dist/protocol/lifecycle.js +562 -0
  150. package/dist/protocol/meta-keys.js +17 -0
  151. package/dist/protocol/meta.js +13 -0
  152. package/dist/protocol/model-catalog.js +223 -0
  153. package/dist/protocol/models.js +84 -0
  154. package/dist/protocol/part-input.js +94 -0
  155. package/dist/protocol/parts.js +166 -0
  156. package/dist/protocol/plan.js +31 -0
  157. package/dist/protocol/reduce.js +484 -0
  158. package/dist/protocol/selectors.js +136 -0
  159. package/dist/protocol/seq-cursor.js +37 -0
  160. package/dist/protocol/stop-reasons.js +41 -0
  161. package/dist/protocol/thinking.js +31 -0
  162. package/dist/protocol/time.js +21 -0
  163. package/dist/protocol/tokens.js +57 -0
  164. package/dist/protocol/tool-closure.js +70 -0
  165. package/dist/protocol/tool-state.js +153 -0
  166. package/dist/protocol/verify.js +467 -0
  167. package/dist/protocol/vocabulary.js +27 -0
  168. package/dist/protocol/wire-api.js +94 -0
  169. package/dist/protocol/wire.js +669 -0
  170. package/dist/server/acp/binding.js +251 -0
  171. package/dist/server/acp/session-records.js +53 -0
  172. package/dist/server/acp/translate.js +401 -0
  173. package/dist/server/agent-server.js +338 -0
  174. package/dist/server/bin.js +492 -0
  175. package/dist/server/feedback.js +216 -0
  176. package/dist/server/history.js +123 -0
  177. package/dist/server/index.js +8 -0
  178. package/dist/server/install.js +171 -0
  179. package/dist/server/open-parts.js +87 -0
  180. package/dist/server/routes.js +292 -0
  181. package/dist/server/secrets.js +19 -0
  182. package/dist/server/session-gate.js +54 -0
  183. package/dist/server/session-log.js +66 -0
  184. package/dist/server/session-store.js +243 -0
  185. package/dist/server/subscriptions.js +189 -0
  186. package/dist/server/transports.js +214 -0
  187. package/dist/server/wire-error.js +26 -0
  188. package/dist/sync/event-log.js +89 -0
  189. package/dist/sync/fit.js +202 -0
  190. package/dist/sync/history-reader.js +33 -0
  191. package/dist/sync/history-sqlite.js +281 -0
  192. package/dist/sync/history.js +163 -0
  193. package/dist/sync/index.js +5 -0
  194. package/dist/sync/journal-sqlite.js +316 -0
  195. package/dist/sync/journal.js +10 -0
  196. package/dist/sync/live-tails.js +85 -0
  197. package/dist/sync/node-sqlite.js +27 -0
  198. package/dist/sync/projection.js +32 -0
  199. package/dist/sync/recovery.js +117 -0
  200. package/dist/sync/retry.js +45 -0
  201. package/dist/sync/schema.js +73 -0
  202. package/dist/sync/sql.js +94 -0
  203. package/dist/sync/sqlite-file.js +31 -0
  204. package/dist/sync/sqlite.js +18 -0
  205. package/dist/sync/worker.js +212 -0
  206. package/dist/types/client/client.d.ts +6 -1
  207. package/dist/types/client/client.d.ts.map +1 -1
  208. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  210. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/options.d.ts +28 -11
  212. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  213. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  214. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  216. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  218. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  219. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  220. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  221. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  222. package/dist/types/core/agents/process-pool.d.ts +8 -0
  223. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  224. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  225. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  226. package/dist/types/core/presets.d.ts +2 -2
  227. package/dist/types/core/presets.d.ts.map +1 -1
  228. package/dist/types/core/processes/identity.d.ts.map +1 -1
  229. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  230. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  231. package/dist/types/core/provision/extract.d.ts.map +1 -1
  232. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  233. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  234. package/dist/types/core/runtime/turn.d.ts +12 -7
  235. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  236. package/dist/types/protocol/clis.d.ts +3 -3
  237. package/dist/types/protocol/conversation.d.ts +6 -6
  238. package/dist/types/protocol/credentials.d.ts +13 -1
  239. package/dist/types/protocol/credentials.d.ts.map +1 -1
  240. package/dist/types/protocol/errors.d.ts +6 -4
  241. package/dist/types/protocol/errors.d.ts.map +1 -1
  242. package/dist/types/protocol/lifecycle.d.ts +4 -4
  243. package/dist/types/protocol/wire-api.d.ts +12 -12
  244. package/dist/types/protocol/wire.d.ts +8 -8
  245. package/dist/types/server/bin.d.ts +3 -0
  246. package/dist/types/server/bin.d.ts.map +1 -0
  247. package/dist/types/server/routes.d.ts.map +1 -1
  248. package/dist/types/server/transports.d.ts +2 -1
  249. package/dist/types/server/transports.d.ts.map +1 -1
  250. package/dist/types/sync/node-sqlite.d.ts +4 -1
  251. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  252. package/docs/consuming.md +56 -7
  253. package/docs/deploy.md +35 -0
  254. package/docs/harnesses.md +30 -5
  255. package/package.json +43 -18
  256. package/src/client/client.ts +114 -44
  257. package/src/core/agents/claude-code/approvals.ts +5 -1
  258. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  259. package/src/core/agents/claude-code/options.ts +28 -11
  260. package/src/core/agents/claude-code/session.ts +13 -0
  261. package/src/core/agents/codex-app-server/homes.ts +11 -2
  262. package/src/core/agents/codex-app-server/login.ts +30 -0
  263. package/src/core/agents/codex-app-server/requests.ts +7 -6
  264. package/src/core/agents/codex-app-server/session.ts +11 -2
  265. package/src/core/agents/process-pool.ts +30 -4
  266. package/src/core/agents/scripted/scripted-agent.ts +2 -1
  267. package/src/core/agents/scripted/steps.ts +1 -1
  268. package/src/core/presets.ts +3 -2
  269. package/src/core/processes/identity.ts +1 -0
  270. package/src/core/processes/lifeline.ts +10 -1
  271. package/src/core/processes/process-table.ts +1 -0
  272. package/src/core/provision/extract.ts +1 -0
  273. package/src/core/runtime/agent-runtime.ts +6 -3
  274. package/src/core/runtime/turn.ts +21 -9
  275. package/src/protocol/credentials.ts +19 -5
  276. package/src/protocol/errors.ts +12 -3
  277. package/src/server/bin.ts +25 -10
  278. package/src/server/routes.ts +3 -2
  279. package/src/server/transports.ts +6 -1
  280. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,56 @@
1
+ import { basename } from "node:path";
2
+ import { withTimeout } from "../utils/deadline.js";
3
+ import { InvalidRequestError } from "../utils/errors.js";
4
+ /** The method a login names, refused unless the harness offers it as a login. */
5
+ export function loginMethod(methods, id) {
6
+ const method = methods.find((candidate) => candidate.id === id && candidate.kind !== "terminal");
7
+ if (method)
8
+ return method;
9
+ const offered = methods.filter((candidate) => candidate.kind !== "terminal").map((m) => m.id);
10
+ throw new InvalidRequestError([
11
+ { path: "method", message: `not a login this harness offers (${offered.join(", ")})` },
12
+ ]);
13
+ }
14
+ /**
15
+ * Signing in from a terminal with the CLI's own command. Of the environment a
16
+ * turn would run with, it takes only the variable that picks the CLI's store
17
+ * (`storeVariable`), so the login lands where turns look.
18
+ */
19
+ export function terminalMethod(command, env, storeVariable) {
20
+ const store = env[storeVariable];
21
+ return {
22
+ id: "terminal",
23
+ kind: "terminal",
24
+ label: [basename(command[0] ?? ""), ...command.slice(1)].join(" "),
25
+ command,
26
+ ...(store && { env: { [storeVariable]: store } }),
27
+ };
28
+ }
29
+ /** How long a CLI's own auth command may take. */
30
+ const COMMAND_TIMEOUT_MS = 30_000;
31
+ /**
32
+ * Run one of a CLI's auth commands to its end, held by the lifeline and not
33
+ * recorded (no session waits on it): its exit code and what it wrote.
34
+ */
35
+ export async function runAuthCommand(processes, spec) {
36
+ const native = processes.spawn(spec);
37
+ let failed;
38
+ native.child.once("error", (error) => {
39
+ failed = error;
40
+ });
41
+ native.child.stdin?.end();
42
+ let stdout = "";
43
+ native.child.stdout?.setEncoding("utf8").on("data", (chunk) => {
44
+ stdout += chunk;
45
+ });
46
+ const exit = await withTimeout(native.exited, COMMAND_TIMEOUT_MS);
47
+ if (!exit) {
48
+ void native.stop();
49
+ throw new Error(`${spec.command} ${spec.args.join(" ")} did not finish`);
50
+ }
51
+ // It never started: no such CLI, or not one this user may run.
52
+ if (failed)
53
+ throw new Error(`cannot run ${spec.command}: ${failed.message}`);
54
+ // The tail is redacted already.
55
+ return { code: exit.value.code, stdout, stderr: native.stderrTail.trim() };
56
+ }
@@ -0,0 +1,109 @@
1
+ import { McpUnavailableError } from "../utils/errors.js";
2
+ /** A turn owns its wire configuration even when the caller reuses its objects. */
3
+ export function snapshotMcpServers(servers) {
4
+ return structuredClone(servers ?? {});
5
+ }
6
+ // @ref LLP 0001#d15--a-turns-mcp-servers-are-required-unless-it-says-otherwise — the caller's check stays
7
+ /** Whether a turn needs the server: each does unless it says `required: false`. */
8
+ function mcpServerRequired(server) {
9
+ return server?.required !== false;
10
+ }
11
+ /** The server as its harness takes it: whether a turn needs it is the engine's rule. */
12
+ export function nativeMcpServer(server) {
13
+ const { required: _required, ...native } = server;
14
+ return native;
15
+ }
16
+ export function mcpConnectionErrors(names, statuses) {
17
+ return Object.fromEntries(names.flatMap((name) => {
18
+ const status = statuses.find((entry) => entry.name === name);
19
+ return status?.status === "connected"
20
+ ? []
21
+ : [[name, status?.error ?? `server is ${status?.status ?? "missing"}`]];
22
+ }));
23
+ }
24
+ /**
25
+ * Settle a turn's MCP connection failures: a required server's fails the
26
+ * turn; the others are returned, for the turn to say and go on without.
27
+ * A server missing from `servers` (an operator's in-process one) is required.
28
+ */
29
+ export function settleMcpFailures(errors, servers) {
30
+ const causes = Object.entries(errors).map(([name, cause]) => [name, mcpCause(cause)]);
31
+ const required = causes.filter(([name]) => mcpServerRequired(servers[name]));
32
+ if (required.length)
33
+ throw new McpUnavailableError(Object.fromEntries(required));
34
+ return Object.fromEntries(causes);
35
+ }
36
+ /**
37
+ * A connection failure as the stream may carry it: a URL in it names only its
38
+ * origin, since a per-session MCP URL can carry a capability in its path or
39
+ * query, and the stream is journaled, replayed and synced.
40
+ */
41
+ export function mcpCause(cause) {
42
+ // A URL a JSON string escaped (`https:\/\/…`) is a URL too.
43
+ return cause
44
+ .replace(/:\\\/\\\//g, "://")
45
+ .replace(/\b(?:https?|wss?):\/\/[^\s)"'<>]+/gi, (url) => {
46
+ // Punctuation after it is the sentence's.
47
+ const trailing = /[.,;:!?]+$/.exec(url)?.[0] ?? "";
48
+ try {
49
+ return new URL(url.slice(0, url.length - trailing.length)).origin + trailing;
50
+ }
51
+ catch {
52
+ return `<url>${trailing}`;
53
+ }
54
+ });
55
+ }
56
+ // @ref LLP 0001#d15--a-turns-mcp-servers-are-required-unless-it-says-otherwise — a recoverable error
57
+ /** What a turn says of a server it goes on without. */
58
+ function mcpUnavailableWarning(name, cause) {
59
+ return {
60
+ category: "mcp_unavailable",
61
+ message: `MCP server ${name} could not connect (${cause}); the turn goes on without its tools`,
62
+ };
63
+ }
64
+ /**
65
+ * How long a turn goes on without a server that could not connect before a
66
+ * turn tries it again: a server that never answers would otherwise hold up
67
+ * every turn by its connection timeout. A changed configuration is tried at
68
+ * once.
69
+ */
70
+ export const MCP_RETRY_MS = 30_000;
71
+ // @ref LLP 0001#d15--a-turns-mcp-servers-are-required-unless-it-says-otherwise — tried again after 30 s, or at once when required
72
+ /**
73
+ * The MCP servers a session's turns go on without: why each could not
74
+ * connect, and when it was last tried. A later turn tries one again once
75
+ * `MCP_RETRY_MS` has passed since that try, and at once when it requires it.
76
+ */
77
+ export class UnavailableMcpServers {
78
+ servers = new Map();
79
+ /** Why each server could not connect. */
80
+ get causes() {
81
+ return Object.fromEntries([...this.servers].map(([name, { cause }]) => [name, cause]));
82
+ }
83
+ /**
84
+ * The servers to try again now: due, or required by the turn's `servers`.
85
+ * One the turn no longer names is returned too: the turn's configuration
86
+ * changed, which reloads the servers anyway.
87
+ */
88
+ retryNow(servers) {
89
+ const now = Date.now();
90
+ return [...this.servers].flatMap(([name, { triedAt }]) => now - triedAt >= MCP_RETRY_MS || mcpServerRequired(servers[name]) ? [name] : []);
91
+ }
92
+ /**
93
+ * What an attempt to connect went on without, and why. One it tried
94
+ * (`tried`) was last tried now; one it left alone keeps its last try.
95
+ */
96
+ record(unavailable, tried) {
97
+ const now = Date.now();
98
+ const before = this.servers;
99
+ this.servers = new Map(Object.entries(unavailable).map(([name, cause]) => {
100
+ const at = before.get(name)?.triedAt;
101
+ return [name, { cause, triedAt: at === undefined || tried(name) ? now : at }];
102
+ }));
103
+ }
104
+ /** Say each server the turn goes on without (`AgentExecuteOptions.onWarning`). */
105
+ async announce(onWarning) {
106
+ for (const [name, { cause }] of this.servers)
107
+ await onWarning?.(mcpUnavailableWarning(name, cause));
108
+ }
109
+ }
@@ -0,0 +1,6 @@
1
+ // The plan's options live in the protocol, so a client that asks or answers a plan uses the same ones.
2
+ export { PLAN_OPTIONS, PLAN_TITLE } from "../../protocol/plan.js";
3
+ /** The mode an approved plan is implemented in. */
4
+ export function approvedPlanMode(optionId) {
5
+ return optionId === "accept_edits" ? "accept_edits" : "default";
6
+ }
@@ -0,0 +1,307 @@
1
+ import { onAbort } from "../utils/deadline.js";
2
+ /**
3
+ * Idle time before an unused session's process is ended, unless
4
+ * `idleTimeoutMs` says otherwise.
5
+ */
6
+ export const IDLE_TIMEOUT_MS = 5 * 60_000;
7
+ /**
8
+ * Each logical session's native process: reused while it still fits the
9
+ * turn, replaced otherwise, ended when idle, and never succeeded before it
10
+ * has exited. Claude, Codex and ACP run on it; a harness keeps only what is
11
+ * its own.
12
+ */
13
+ export class ProcessPool {
14
+ harness;
15
+ options;
16
+ held = new Map();
17
+ /** Clients still being started, per session: a release or a shutdown closes them too. */
18
+ starting = new Map();
19
+ /** Every exit still under way, per session: a successor and a release wait for all of them. */
20
+ exiting = new Map();
21
+ /** Per client, from the moment it is owned: a process still starting can ask too. */
22
+ started = new WeakMap();
23
+ /** Login changes per store, and those that named none (every store). */
24
+ logins = new Map();
25
+ loginsEverywhere = 0;
26
+ /** Host resumes so far (`invalidate`). */
27
+ resumes = 0;
28
+ closed = false;
29
+ constructor(harness, options) {
30
+ this.harness = harness;
31
+ this.options = options;
32
+ }
33
+ /** The session's process, ready, between or during its turns. */
34
+ get(sessionId) {
35
+ return this.held.get(sessionId)?.process;
36
+ }
37
+ /**
38
+ * The session's client: its process's, or the one still starting, the
39
+ * latest when the start owns several. An explicit change a harness queues
40
+ * on its client (Claude's MCP swap) reaches a session that is starting.
41
+ */
42
+ client(sessionId) {
43
+ const held = this.held.get(sessionId);
44
+ if (held)
45
+ return held.process.client;
46
+ return [...(this.starting.get(sessionId) ?? [])].at(-1);
47
+ }
48
+ /**
49
+ * The session's process for the turn, which has it until `leave`: the
50
+ * warm one when it can take the turn, else a new one, started once every
51
+ * process of the session that was ended has exited. A session runs one
52
+ * turn at a time (`SessionAgent`), so a warm process is never under a
53
+ * running turn here.
54
+ */
55
+ async acquire(sessionId, turn, signal) {
56
+ signal.throwIfAborted();
57
+ const warm = this.held.get(sessionId);
58
+ let replacing;
59
+ if (warm) {
60
+ this.clearIdle(warm);
61
+ let reason;
62
+ try {
63
+ reason = await this.replaceReason(warm.process, turn, signal);
64
+ signal.throwIfAborted();
65
+ }
66
+ catch (error) {
67
+ this.leave(sessionId, warm.process);
68
+ throw error;
69
+ }
70
+ if (!reason)
71
+ return warm.process;
72
+ this.end(sessionId, warm, `replaced:${reason}`);
73
+ replacing = warm.process;
74
+ }
75
+ await this.exited(sessionId, signal);
76
+ return this.start(sessionId, turn, signal, replacing);
77
+ }
78
+ /**
79
+ * The one rule: why the warm process cannot take the turn, or nothing
80
+ * when it can. The facts first, the harness's checks next, and the live
81
+ * change last, since it acts on the process.
82
+ */
83
+ async replaceReason(process, turn, signal) {
84
+ const { harness } = this;
85
+ if (process.client.closed)
86
+ return "exited";
87
+ const started = this.started.get(process.client);
88
+ if (started && started.resumes !== this.resumes && !harness.holdsOnlyCopy?.(process))
89
+ return "hostResumed";
90
+ // @ref LLP 0011#a-login-change-starts-the-next-turn-on-a-new-cli — a generation, never a close under a turn
91
+ if (started && started.generation !== this.generation(started.store))
92
+ return "loginChanged";
93
+ const resume = harness.resumeOf(turn);
94
+ if (resume !== undefined && !harness.conversationsOf(process).includes(resume))
95
+ return "otherConversation";
96
+ if (!harness.fits(process, turn))
97
+ return "doesNotFit";
98
+ // @ref LLP 0011#a-login-change-starts-the-next-turn-on-a-new-cli — a login changed outside the engine, by its mark
99
+ // After `fits`: only a process that would take the turn is compared,
100
+ // and the mark it started under is of the store the turn runs on.
101
+ if (started?.loginMark !== undefined) {
102
+ const now = harness.loginMark?.(turn);
103
+ if (now !== undefined && now !== started.loginMark)
104
+ return "loginChanged";
105
+ }
106
+ if (harness.applyLiveChange && !(await harness.applyLiveChange(process, turn, signal)))
107
+ return "cannotChange";
108
+ return undefined;
109
+ }
110
+ /**
111
+ * Activity on a warm process between turns (Claude answering a query it
112
+ * began itself): its idle wait starts again. Nothing while a turn has it.
113
+ */
114
+ touch(sessionId, process) {
115
+ if (this.held.get(sessionId)?.idleTimer)
116
+ this.leave(sessionId, process);
117
+ }
118
+ /** The turn is done with the process: a warm one waits for the next turn, at most `idleMs`. */
119
+ leave(sessionId, process) {
120
+ const held = this.held.get(sessionId);
121
+ if (held?.process !== process || process.client.closed)
122
+ return;
123
+ this.clearIdle(held);
124
+ const { idleMs } = this.options;
125
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — 0 never ends it; nor one that holds its conversation
126
+ if (idleMs <= 0 || this.harness.holdsOnlyCopy?.(process))
127
+ return;
128
+ held.idleTimer = setTimeout(() => this.end(sessionId, held, "idle"), idleMs);
129
+ held.idleTimer.unref?.();
130
+ }
131
+ /**
132
+ * A login changed in `store` (in every store when none is named): each
133
+ * session's next turn on it starts a new process, which resumes its
134
+ * conversation. A turn already starting or running finishes on its own.
135
+ */
136
+ loginChanged(store) {
137
+ if (store === undefined)
138
+ this.loginsEverywhere++;
139
+ else
140
+ this.logins.set(store, (this.logins.get(store) ?? 0) + 1);
141
+ }
142
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — a host resume marks, the next turn replaces
143
+ /**
144
+ * The host resumed from suspension, which left every process's remote
145
+ * connections dead: each session's next turn starts a new process. Ends
146
+ * nothing now, since ending at once has killed a turn still setting up.
147
+ */
148
+ invalidate() {
149
+ this.resumes++;
150
+ }
151
+ /**
152
+ * Whether a host resume came since the process began to start (a harness
153
+ * may refuse to prompt it); asked while it starts, too.
154
+ */
155
+ startedBeforeResume(process) {
156
+ const started = this.started.get(process.client);
157
+ return started !== undefined && started.resumes !== this.resumes;
158
+ }
159
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — released once its processes exited
160
+ /**
161
+ * End the session's process for good, and any still starting, and settle
162
+ * once every process of the session has exited, those ended earlier
163
+ * (idle, replaced) included: a host removes the session's folders on this
164
+ * answer, and a process still exiting can write to them. Each wait is
165
+ * bounded by its client's stop (LLP 0007).
166
+ */
167
+ async release(sessionId) {
168
+ this.remove(sessionId, "released");
169
+ await this.exits(sessionId);
170
+ }
171
+ /**
172
+ * End every process and refuse new ones; settles once every process of
173
+ * every session has exited, bounded as a release is.
174
+ */
175
+ async closeAll() {
176
+ this.closed = true;
177
+ for (const id of new Set([...this.held.keys(), ...this.starting.keys()]))
178
+ this.remove(id, "shutdown");
179
+ await Promise.all([...this.exiting.keys()].map((id) => this.exits(id)));
180
+ }
181
+ generation(store) {
182
+ return (this.logins.get(store) ?? 0) + this.loginsEverywhere;
183
+ }
184
+ /** Every exit under way for the session, as one wait. */
185
+ exits(sessionId) {
186
+ return Promise.all(this.exiting.get(sessionId) ?? []);
187
+ }
188
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — one process on a conversation at a time
189
+ /** Wait for every ended process of the session to exit; a cancelled turn does not sit it out. */
190
+ async exited(sessionId, signal) {
191
+ if (!this.exiting.get(sessionId)?.size)
192
+ return;
193
+ let offCancel = () => { };
194
+ const cancelled = new Promise((resolve) => {
195
+ offCancel = onAbort(signal, resolve);
196
+ });
197
+ await Promise.race([this.exits(sessionId), cancelled]);
198
+ offCancel();
199
+ signal.throwIfAborted();
200
+ }
201
+ async start(sessionId, turn, signal, replacing) {
202
+ if (this.closed)
203
+ throw new Error("the process pool is closed");
204
+ // Taken as the start begins, before the process reads its login: a login
205
+ // change or a host resume while it initializes replaces it at its next
206
+ // turn.
207
+ const store = this.harness.store?.(turn) ?? "";
208
+ const loginMark = this.harness.loginMark?.(turn);
209
+ const started = {
210
+ store,
211
+ generation: this.generation(store),
212
+ ...(loginMark !== undefined && { loginMark }),
213
+ resumes: this.resumes,
214
+ };
215
+ const owned = [];
216
+ try {
217
+ const process = await this.harness.spawn(turn, (client) => {
218
+ this.own(sessionId, client);
219
+ this.started.set(client, started);
220
+ owned.push(client);
221
+ }, signal, replacing);
222
+ if (this.closed || process.client.closed) {
223
+ process.client.close("shutdown");
224
+ throw new Error(this.closed ? "the process pool is closed" : "the process ended as it started");
225
+ }
226
+ this.started.set(process.client, started);
227
+ this.held.set(sessionId, { process });
228
+ return process;
229
+ }
230
+ finally {
231
+ for (const client of owned)
232
+ this.disown(sessionId, client);
233
+ }
234
+ }
235
+ /** Own a client from its first moment: a release closes it, and its exit is waited for. */
236
+ own(sessionId, client) {
237
+ if (this.closed) {
238
+ client.close("shutdown");
239
+ throw new Error("the process pool is closed");
240
+ }
241
+ let clients = this.starting.get(sessionId);
242
+ if (!clients) {
243
+ clients = new Set();
244
+ this.starting.set(sessionId, clients);
245
+ }
246
+ clients.add(client);
247
+ const ended = () => {
248
+ const held = this.held.get(sessionId);
249
+ if (held?.process.client === client) {
250
+ this.clearIdle(held);
251
+ this.held.delete(sessionId);
252
+ }
253
+ this.exitUnderWay(sessionId, client);
254
+ };
255
+ if (client.closed)
256
+ ended();
257
+ else
258
+ client.onClose(ended);
259
+ }
260
+ /** Keep the client's exit until it is done: `gone()` is set by now (`PooledClient`). */
261
+ exitUnderWay(sessionId, client) {
262
+ const gone = client.gone?.();
263
+ if (!gone)
264
+ return;
265
+ const exits = this.exiting.get(sessionId) ?? new Set();
266
+ this.exiting.set(sessionId, exits);
267
+ const exit = gone.then(() => { }, () => { });
268
+ exits.add(exit);
269
+ void exit.then(() => {
270
+ exits.delete(exit);
271
+ if (!exits.size && this.exiting.get(sessionId) === exits)
272
+ this.exiting.delete(sessionId);
273
+ });
274
+ }
275
+ disown(sessionId, client) {
276
+ const clients = this.starting.get(sessionId);
277
+ if (!clients)
278
+ return;
279
+ clients.delete(client);
280
+ if (!clients.size)
281
+ this.starting.delete(sessionId);
282
+ }
283
+ /** End the session's process and those still starting. */
284
+ remove(sessionId, reason) {
285
+ const starting = this.starting.get(sessionId);
286
+ this.starting.delete(sessionId);
287
+ const held = this.held.get(sessionId);
288
+ if (held)
289
+ this.end(sessionId, held, reason);
290
+ for (const client of starting ?? [])
291
+ client.close(reason);
292
+ }
293
+ /** End a held process, when it is still the session's; its exit is then waited for. */
294
+ end(sessionId, held, reason) {
295
+ if (this.held.get(sessionId) !== held)
296
+ return;
297
+ this.clearIdle(held);
298
+ this.held.delete(sessionId);
299
+ held.process.client.close(reason);
300
+ }
301
+ clearIdle(held) {
302
+ if (held.idleTimer) {
303
+ clearTimeout(held.idleTimer);
304
+ held.idleTimer = undefined;
305
+ }
306
+ }
307
+ }
@@ -0,0 +1,49 @@
1
+ import { NativeProcesses } from "../processes/native-processes.js";
2
+ import { HarnessNotAvailableError } from "../utils/errors.js";
3
+ /**
4
+ * Pairs each harness with its agent implementation and event adapter, and
5
+ * holds the native processes its agents start, which the runtime stops at
6
+ * shutdown and a restart sweeps, and the provisioner that installs their
7
+ * CLIs, which the runtime asks for status and installs ahead of a turn.
8
+ */
9
+ export class AgentRegistry {
10
+ processes;
11
+ provisioner;
12
+ agents = new Map();
13
+ adapters = new Map();
14
+ /**
15
+ * Agents made for this registry start their CLIs through `processes` and
16
+ * resolve them through `provisioner` (`createAgentRegistry` does both);
17
+ * without one, the runtime reports its harnesses' CLIs `unmanaged`.
18
+ */
19
+ constructor(processes = new NativeProcesses(), provisioner) {
20
+ this.processes = processes;
21
+ this.provisioner = provisioner;
22
+ }
23
+ register(agent, adapter) {
24
+ this.agents.set(agent.harness, agent);
25
+ this.adapters.set(agent.harness, adapter);
26
+ return this;
27
+ }
28
+ getAgent(harness) {
29
+ const agent = this.agents.get(harness);
30
+ if (!agent)
31
+ throw new HarnessNotAvailableError(harness);
32
+ return agent;
33
+ }
34
+ getAdapter(harness) {
35
+ const adapter = this.adapters.get(harness);
36
+ if (!adapter)
37
+ throw new HarnessNotAvailableError(harness);
38
+ return adapter;
39
+ }
40
+ has(harness) {
41
+ return this.agents.has(harness);
42
+ }
43
+ list() {
44
+ return [...this.agents.keys()];
45
+ }
46
+ async terminateAll() {
47
+ await Promise.all([...this.agents.values()].map((a) => a.terminateAll()));
48
+ }
49
+ }
@@ -0,0 +1,86 @@
1
+ import { DEFAULT_TOKEN_USAGE, completeToolPart, createTextPart, createToolPart, } from "../../../protocol/index.js";
2
+ /**
3
+ * The scripted harness's adapter: its events to the engine's `AdapterEvent`s.
4
+ * Every part goes into the turn's one assistant message, which the engine
5
+ * opens; ids, indices and clones are the engine's (`EventProcessor`).
6
+ */
7
+ export class ScriptedTransformer {
8
+ sessionId;
9
+ streaming;
10
+ tools = new Map();
11
+ ended;
12
+ cancelled = false;
13
+ constructor(sessionId) {
14
+ this.sessionId = sessionId;
15
+ }
16
+ process(event) {
17
+ const ctx = { sessionId: this.sessionId, messageId: "" };
18
+ switch (event.type) {
19
+ case "text":
20
+ return [{ kind: "part-open", part: createTextPart(ctx, event.text, false) }];
21
+ case "stream": {
22
+ const open = [];
23
+ if (!this.streaming) {
24
+ this.streaming = createTextPart(ctx, "", true);
25
+ // The processor snapshots at emit time, after the append below. Open
26
+ // with a copy so this word arrives once, as the delta.
27
+ open.push({ kind: "part-open", part: structuredClone(this.streaming) });
28
+ }
29
+ this.streaming.text += event.text;
30
+ return [...open, { kind: "text-delta", partId: this.streaming.id, text: event.text }];
31
+ }
32
+ case "streamed": {
33
+ const part = this.streaming;
34
+ this.streaming = undefined;
35
+ return part ? [{ kind: "part-update", part: { ...part, state: "done" } }] : [];
36
+ }
37
+ case "tool": {
38
+ const part = createToolPart(ctx, event.toolCallId, event.toolName, event.input, {
39
+ ...(event.kind && { kind: event.kind }),
40
+ ...(event.mcp && { mcp: event.mcp }),
41
+ ...(event.command !== undefined && { command: event.command }),
42
+ ...(event.url !== undefined && { url: event.url }),
43
+ ...(event.locations && { locations: event.locations }),
44
+ });
45
+ this.tools.set(event.toolCallId, part);
46
+ return [{ kind: "part-open", part }];
47
+ }
48
+ case "tool-result": {
49
+ const part = this.tools.get(event.toolCallId);
50
+ if (!part)
51
+ return [];
52
+ if (event.input && part.state.status === "in_progress")
53
+ part.state.input = event.input;
54
+ completeToolPart(part, event.error !== undefined
55
+ ? {
56
+ output: event.error,
57
+ isError: true,
58
+ ...(event.metadata && { metadata: event.metadata }),
59
+ }
60
+ : {
61
+ output: event.output ?? "",
62
+ ...(event.content && { content: event.content }),
63
+ ...(event.metadata && { metadata: event.metadata }),
64
+ });
65
+ return [{ kind: "part-update", part }];
66
+ }
67
+ case "end":
68
+ this.ended = event;
69
+ return [];
70
+ case "cancelled":
71
+ this.cancelled = true;
72
+ return [];
73
+ }
74
+ }
75
+ finish() {
76
+ return {
77
+ usage: this.ended?.usage ?? { ...DEFAULT_TOKEN_USAGE },
78
+ stopReason: this.ended?.stopReason ?? "end_turn",
79
+ ...(this.ended?.cost !== undefined && { cost: this.ended.cost }),
80
+ ...(this.cancelled && { cancelled: true }),
81
+ };
82
+ }
83
+ }
84
+ export function createScriptedTransformer(ctx) {
85
+ return new ScriptedTransformer(ctx.sessionId);
86
+ }