@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,425 @@
1
+ import { AsyncQueue } from "../../../protocol/index.js";
2
+ import { sharedNativeProcesses } from "../../processes/native-processes.js";
3
+ import { onAbort, untilAborted } from "../../utils/deadline.js";
4
+ import { SessionResumeError } from "../../utils/errors.js";
5
+ import { configFingerprint } from "../config-fingerprint.js";
6
+ import { nativeMcpServer } from "../mcp-config.js";
7
+ import { IDLE_TIMEOUT_MS, ProcessPool } from "../process-pool.js";
8
+ import { SessionAgent } from "../session-agent.js";
9
+ import { CANCELLED_PROMPT_RESULT } from "./adapter.js";
10
+ import { AcpClient } from "./client.js";
11
+ import { permissionModeOf, toAcpMcpServers, toPromptBlocks, } from "./mappings.js";
12
+ import { answerElicitation, answerPermission } from "./requests.js";
13
+ /**
14
+ * What a session's agent process was started with, as one key: a change to
15
+ * any of it starts another, which resumes the conversation where the agent
16
+ * can. MCP servers go without `required`, which is the engine's; extra
17
+ * directories count, in any order, only for an agent that takes them.
18
+ * Hashed: the env and MCP headers carry credentials.
19
+ */
20
+ function spawnKey(options, launch, takesDirectories) {
21
+ const servers = options.mcpServers;
22
+ return configFingerprint({
23
+ launch: { command: launch.command, args: launch.args ?? [], env: launch.env ?? {} },
24
+ cwd: options.cwd,
25
+ env: options.env,
26
+ mcpServers: servers &&
27
+ Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, nativeMcpServer(server)])),
28
+ directories: takesDirectories
29
+ ? [...new Set(options.additionalDirectories ?? [])].sort()
30
+ : undefined,
31
+ });
32
+ }
33
+ const CAPABILITIES = {
34
+ multiTurn: true,
35
+ // A requested resume fails if the target agent cannot load saved sessions.
36
+ sessionResume: true,
37
+ // v1 has no portable model parameter. A requested model or thinking level
38
+ // is applied only when the agent offers a `model` / `thought_level` config
39
+ // option, so neither is promised here.
40
+ modelSwitch: "unsupported",
41
+ thinkingLevels: false,
42
+ // The most an agent can take: its `initialize` decides, image data with its
43
+ // `image` prompt capability and files beyond text with `embeddedContext`.
44
+ images: true,
45
+ files: ["text", "pdf", "binary"],
46
+ mcpServers: true,
47
+ permissionRequests: true,
48
+ // The answer is an option id.
49
+ rejectionMessages: false,
50
+ ignoredSettings: [
51
+ // ACP v1 has no system prompt: session/new takes the folder, the MCP
52
+ // servers and the extra directories only (`resolveSession`).
53
+ "systemPromptAppend",
54
+ // A prompt runs until the agent ends it: ACP v1 has no turn limit.
55
+ "maxTurns",
56
+ // session/resume and session/load name a session, not a message in it.
57
+ "resumeSessionAt",
58
+ // The agent's credentials are its launch command's: the client gets the
59
+ // launch, the folder and the env only (`AcpClientOptions`).
60
+ "apiKey",
61
+ // ACP v1 cannot ask an agent to run without its tools.
62
+ "disableTools",
63
+ ],
64
+ };
65
+ /** ACP protocol major version this harness speaks. */
66
+ const PROTOCOL_VERSION = 1;
67
+ /**
68
+ * How long a cancelled prompt may take to end before the agent is ended,
69
+ * unless `cancelGraceMs` says otherwise: an agent that can neither resume nor
70
+ * load loses its conversation with it.
71
+ */
72
+ const CANCEL_GRACE_MS = 10_000;
73
+ /** Deadline for `initialize` on a freshly spawned agent (mirrors codex startup). */
74
+ const INITIALIZE_TIMEOUT_MS = 15_000;
75
+ /** Deadline for session lifecycle requests (`session/new`, `session/resume`). */
76
+ const SESSION_REQUEST_TIMEOUT_MS = 30_000;
77
+ /** A JSON-RPC error's `data` usually holds the cause its message only names. */
78
+ function failureMessage(error) {
79
+ if (!(error instanceof Error))
80
+ return String(error);
81
+ const data = error.data;
82
+ if (data === undefined || data === null)
83
+ return String(error);
84
+ const nested = data.message;
85
+ const detail = typeof data === "string" ? data : typeof nested === "string" ? nested : JSON.stringify(data);
86
+ return `${error}: ${detail}`;
87
+ }
88
+ /** Every value a select option offers, whether listed flat or in groups. */
89
+ function selectableValues(option) {
90
+ return option.options.flatMap((entry) => "options" in entry ? entry.options.map((nested) => nested.value) : [entry.value]);
91
+ }
92
+ /**
93
+ * ACP harness: drives any Agent Client Protocol v1 agent as a long-lived
94
+ * subprocess (one per logical session, reused across turns). The launch
95
+ * command comes from the operator's `resolveLaunch`; `initialize` negotiates
96
+ * the protocol version and gates optional features (resume, images) on the
97
+ * agent's advertised capabilities. The turn's stopReason arrives as the
98
+ * `session/prompt` *response*, so `execute` re-injects it into the raw stream
99
+ * as a synthetic `session/prompt_result` event for the adapter.
100
+ */
101
+ export class AcpAgent extends SessionAgent {
102
+ agentOptions;
103
+ harness = "acp";
104
+ capabilities = CAPABILITIES;
105
+ /** Its CLIs start here: the runtime's, or this OS process's own when it was made without one. */
106
+ processes;
107
+ sessions;
108
+ constructor(agentOptions) {
109
+ super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
110
+ this.agentOptions = agentOptions;
111
+ this.processes = agentOptions.processes ?? sharedNativeProcesses();
112
+ this.sessions = new ProcessPool({
113
+ resumeOf: ({ options }) => options.resumeSessionId,
114
+ conversationsOf: (session) => [session.acpSessionId],
115
+ fits: (session, { options, launch }) => session.spawnKey === spawnKey(options, launch, session.takesDirectories),
116
+ // @ref LLP 0001#d10--built-in-turns-own-their-logical-session-through-cleanup — not ended for idleness when it cannot be resumed
117
+ // An agent that can neither resume nor load holds the only copy of
118
+ // its conversation: neither idleness nor a host resume ends it.
119
+ holdsOnlyCopy: (session) => !session.resumable,
120
+ spawn: (turn, own, signal) => this.spawn(turn, own, signal),
121
+ }, { idleMs: agentOptions.idleTimeoutMs ?? IDLE_TIMEOUT_MS });
122
+ }
123
+ async resolveSession(options, signal) {
124
+ signal.throwIfAborted();
125
+ // A cancel ends the wait: the operator's resolution goes on for the next turn.
126
+ const launch = await untilAborted(Promise.resolve(this.agentOptions.resolveLaunch()), signal);
127
+ signal.throwIfAborted();
128
+ if (!launch) {
129
+ throw new Error("acp harness is not configured: resolveLaunch returned no agent launch command");
130
+ }
131
+ return this.sessions.acquire(options.sessionId, { options, launch }, signal);
132
+ }
133
+ /**
134
+ * Start the session's agent and open its conversation: the one the turn
135
+ * names by `session/resume` or `session/load`, else a new one. The pool
136
+ * starts it once every agent of the session before it has exited, so a
137
+ * successor never loads a conversation another agent still has.
138
+ */
139
+ async spawn({ options, launch }, own, signal) {
140
+ const resumeTarget = options.resumeSessionId;
141
+ const clientOptions = {
142
+ launch,
143
+ cwd: options.cwd,
144
+ env: options.env,
145
+ clientName: this.agentOptions.clientName,
146
+ sessionId: options.sessionId,
147
+ processes: this.processes,
148
+ };
149
+ const client = this.agentOptions.createClient
150
+ ? await this.agentOptions.createClient(clientOptions)
151
+ : await AcpClient.create(clientOptions);
152
+ own(client);
153
+ // Closed at once when the turn was cancelled meanwhile.
154
+ const offAbort = onAbort(signal, () => client.close());
155
+ let init;
156
+ let acpSessionId;
157
+ try {
158
+ signal.throwIfAborted();
159
+ init = await client.request("initialize", {
160
+ protocolVersion: PROTOCOL_VERSION,
161
+ // The engine brokers the agent's requests for input, form or URL;
162
+ // a turn whose client cannot answer declines them.
163
+ clientCapabilities: { elicitation: { form: {}, url: {} } },
164
+ clientInfo: {
165
+ name: this.agentOptions.clientName ?? "agent-server",
166
+ version: this.agentOptions.clientVersion ?? "0.0.0",
167
+ },
168
+ }, INITIALIZE_TIMEOUT_MS);
169
+ signal.throwIfAborted();
170
+ const capabilities = init.agentCapabilities;
171
+ const takesDirectories = Boolean(capabilities?.sessionCapabilities?.additionalDirectories);
172
+ const resumeMethod = capabilities?.sessionCapabilities?.resume
173
+ ? "session/resume"
174
+ : capabilities?.loadSession
175
+ ? "session/load"
176
+ : undefined;
177
+ const target = {
178
+ cwd: options.cwd,
179
+ mcpServers: toAcpMcpServers(options.mcpServers),
180
+ // Sent only to agents that advertise it; others keep `cwd` alone.
181
+ ...(takesDirectories &&
182
+ options.additionalDirectories?.length && {
183
+ additionalDirectories: options.additionalDirectories,
184
+ }),
185
+ };
186
+ let configOptions;
187
+ let modes;
188
+ if (resumeTarget) {
189
+ // `session/load` restores the same conversation and replays its
190
+ // history as updates; no turn is listening yet, so the replay is
191
+ // dropped and both paths leave the session ready for a prompt.
192
+ if (!resumeMethod) {
193
+ throw new SessionResumeError(resumeTarget, "the ACP agent supports neither session/resume nor session/load");
194
+ }
195
+ const resumed = await client
196
+ .request(resumeMethod, { sessionId: resumeTarget, ...target }, SESSION_REQUEST_TIMEOUT_MS)
197
+ .catch((cause) => {
198
+ throw new SessionResumeError(resumeTarget, cause instanceof Error ? cause.message : String(cause), { cause });
199
+ });
200
+ acpSessionId = resumeTarget;
201
+ configOptions = resumed?.configOptions;
202
+ modes = resumed?.modes;
203
+ }
204
+ else {
205
+ const created = await client.request("session/new", target, SESSION_REQUEST_TIMEOUT_MS);
206
+ acpSessionId = created.sessionId;
207
+ configOptions = created.configOptions;
208
+ modes = created.modes;
209
+ }
210
+ signal.throwIfAborted();
211
+ if (!acpSessionId)
212
+ throw new Error("acp agent returned no session id");
213
+ const session = {
214
+ client,
215
+ acpSessionId,
216
+ spawnKey: spawnKey(options, launch, takesDirectories),
217
+ takesDirectories,
218
+ resumable: resumeMethod !== undefined,
219
+ configOptions: configOptions ?? [],
220
+ ...(modes?.availableModes.length && { modes }),
221
+ prompt: {
222
+ image: Boolean(init.agentCapabilities?.promptCapabilities?.image),
223
+ embeddedContext: Boolean(init.agentCapabilities?.promptCapabilities?.embeddedContext),
224
+ },
225
+ };
226
+ client.setPermissionHandler((request) => answerPermission(session, request));
227
+ client.setElicitationHandler((request) => answerElicitation(session, request));
228
+ client.onSessionUpdate(({ sessionId, update }) => {
229
+ if (sessionId !== session.acpSessionId)
230
+ return;
231
+ if (update.sessionUpdate === "config_option_update")
232
+ session.configOptions = update.configOptions;
233
+ if (update.sessionUpdate === "current_mode_update" && session.modes)
234
+ session.modes = { ...session.modes, currentModeId: update.currentModeId };
235
+ });
236
+ return session;
237
+ }
238
+ catch (error) {
239
+ client.close();
240
+ signal.throwIfAborted();
241
+ throw error;
242
+ }
243
+ finally {
244
+ offAbort();
245
+ }
246
+ }
247
+ /**
248
+ * Select the requested model and thinking level through the agent's config
249
+ * options. An agent without the option keeps its own default. A model the
250
+ * agent does not offer fails the turn; thinking levels are a normalized
251
+ * vocabulary an agent may not share, so an unmatched level is left alone.
252
+ * Returns the settings it left alone.
253
+ */
254
+ async applyConfig(session, options) {
255
+ const requested = [
256
+ ["model", options.model, "model"],
257
+ ["thought_level", options.thinkingLevel, "thinkingLevel"],
258
+ ];
259
+ const left = [];
260
+ for (const [category, value, field] of requested) {
261
+ if (!value)
262
+ continue;
263
+ const option = session.configOptions.find((candidate) => candidate.category === category && candidate.type === "select");
264
+ if (!option) {
265
+ left.push(field);
266
+ continue;
267
+ }
268
+ if (option.currentValue === value)
269
+ continue;
270
+ const offered = selectableValues(option);
271
+ if (!offered.includes(value)) {
272
+ if (category === "thought_level") {
273
+ left.push(field);
274
+ continue;
275
+ }
276
+ throw new Error(`invalid request: the ACP agent does not offer model '${value}' (available: ${offered.join(", ")})`);
277
+ }
278
+ const updated = await session.client.request("session/set_config_option", { sessionId: session.acpSessionId, configId: option.id, value }, SESSION_REQUEST_TIMEOUT_MS);
279
+ session.configOptions = updated.configOptions;
280
+ }
281
+ return left;
282
+ }
283
+ // @ref LLP 0016.000#an-acp-agents-permission-mode — a permission mode reaches the agent, or is said not applied
284
+ /**
285
+ * Put the agent in the turn's permission mode (`default` when it names
286
+ * none) through `session/set_mode`, by the agent's own id for it. Returns
287
+ * whether the mode holds: false for one the agent offers none of, which
288
+ * leaves the agent in its own. An agent that offers no modes runs as it
289
+ * does, the engine answering what it asks by the mode (`autoDecide`); it
290
+ * has no plan of its own to make, so `plan` does not hold there.
291
+ */
292
+ async applyMode(session, requested) {
293
+ const modes = session.modes;
294
+ if (!modes)
295
+ return requested !== "plan";
296
+ const target = modes.availableModes.find((mode) => permissionModeOf(mode.id) === requested);
297
+ if (!target)
298
+ return false;
299
+ if (target.id !== modes.currentModeId) {
300
+ await session.client.request("session/set_mode", { sessionId: session.acpSessionId, modeId: target.id }, SESSION_REQUEST_TIMEOUT_MS);
301
+ session.modes = { ...modes, currentModeId: target.id };
302
+ }
303
+ return true;
304
+ }
305
+ async *executeTurn(input, options, controller) {
306
+ const queue = new AsyncQueue();
307
+ const unsubscribe = [];
308
+ let cancelTimer;
309
+ let session;
310
+ try {
311
+ controller.signal.throwIfAborted();
312
+ session = await this.resolveSession(options, controller.signal);
313
+ const notApplied = await this.applyConfig(session, options);
314
+ // Sent only to an agent that takes them (`resolveSession`).
315
+ if (options.additionalDirectories?.length && !session.takesDirectories)
316
+ notApplied.push("additionalDirectories");
317
+ if (!(await this.applyMode(session, options.permissionMode ?? "default")))
318
+ notApplied.push("permissionMode");
319
+ if (notApplied.length)
320
+ options.onExecution?.({ notApplied });
321
+ controller.signal.throwIfAborted();
322
+ session.turn = {
323
+ broker: options.onPermissionRequest,
324
+ elicitation: options.onElicitationRequest,
325
+ mode: options.permissionMode,
326
+ signal: controller.signal,
327
+ };
328
+ options.onNativeSession?.(session.acpSessionId, {
329
+ resumed: session.acpSessionId === options.resumeSessionId,
330
+ });
331
+ const { client, acpSessionId } = session;
332
+ unsubscribe.push(client.onSessionUpdate((notification) => {
333
+ if (notification.sessionId !== acpSessionId)
334
+ return;
335
+ queue.push({ method: "session/update", params: notification });
336
+ }));
337
+ const finishCancelled = () => {
338
+ queue.push(CANCELLED_PROMPT_RESULT);
339
+ queue.end();
340
+ };
341
+ // Settles once the agent is no longer prompting: its prompt answered, or it exited.
342
+ let promptEnded = () => { };
343
+ const prompted = new Promise((resolve) => {
344
+ promptEnded = () => resolve(true);
345
+ });
346
+ unsubscribe.push(client.onClose((error) => {
347
+ promptEnded();
348
+ if (controller.signal.aborted)
349
+ finishCancelled();
350
+ else
351
+ queue.fail(error ?? new Error("acp agent exited mid-turn"));
352
+ }));
353
+ const cancelPrompt = () => {
354
+ // ACP semantics: session/cancel makes the in-flight prompt resolve
355
+ // with stopReason=cancelled. Bound the wait for misbehaving agents.
356
+ void client.notify("session/cancel", { sessionId: acpSessionId }).catch(() => { });
357
+ cancelTimer = setTimeout(() => {
358
+ // A peer that has not drained cannot safely serve the next turn.
359
+ client.close();
360
+ finishCancelled();
361
+ }, this.agentOptions.cancelGraceMs ?? CANCEL_GRACE_MS);
362
+ cancelTimer.unref?.();
363
+ };
364
+ if (controller.signal.aborted) {
365
+ // Aborted while the session was being set up: there is no prompt to
366
+ // cancel, and none is started.
367
+ finishCancelled();
368
+ }
369
+ else {
370
+ unsubscribe.push(onAbort(controller.signal, cancelPrompt));
371
+ const prompt = {
372
+ sessionId: acpSessionId,
373
+ prompt: toPromptBlocks(input, session.prompt),
374
+ };
375
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — confirmed only when the prompt ended
376
+ this.cancelWith(options, () => prompted);
377
+ client.request("session/prompt", prompt).then((response) => {
378
+ promptEnded();
379
+ queue.push({ method: "session/prompt_result", params: response });
380
+ queue.end();
381
+ }, (error) => {
382
+ promptEnded();
383
+ if (controller.signal.aborted) {
384
+ finishCancelled();
385
+ return;
386
+ }
387
+ queue.push({ method: "error", params: { message: failureMessage(error) } });
388
+ queue.end();
389
+ });
390
+ }
391
+ for await (const event of queue) {
392
+ yield event;
393
+ }
394
+ }
395
+ catch (error) {
396
+ if (!controller.signal.aborted)
397
+ throw error;
398
+ yield CANCELLED_PROMPT_RESULT;
399
+ }
400
+ finally {
401
+ if (cancelTimer)
402
+ clearTimeout(cancelTimer);
403
+ for (const off of unsubscribe)
404
+ off();
405
+ if (session) {
406
+ session.turn = undefined;
407
+ this.sessions.leave(options.sessionId, session);
408
+ }
409
+ }
410
+ }
411
+ async release(sessionId) {
412
+ // The cancel aborts its turn at once; the agent is ended beside its
413
+ // confirm window, not after it, and its exit is what confirms it.
414
+ // An agent an eviction or a replacement ended earlier is waited for too.
415
+ await Promise.all([super.release(sessionId), this.sessions.release(sessionId)]);
416
+ }
417
+ /** After a host resume, each session's next turn starts its agent again, on its conversation. */
418
+ invalidateMcpConnections() {
419
+ this.sessions.invalidate();
420
+ }
421
+ async terminateAll() {
422
+ await super.terminateAll();
423
+ await this.sessions.closeAll();
424
+ }
425
+ }
@@ -0,0 +1,231 @@
1
+ import { DEFAULT_TOKEN_USAGE, STOP_REASONS, completeToolPart, createReasoningPart, createTextPart, createToolPart, setToolMeta, startToolPart, } from "../../../protocol/index.js";
2
+ import { isRecord } from "../../utils/is-record.js";
3
+ import { permissionModeOf, toToolLocations, toToolResultContent, toolKindOf } from "./mappings.js";
4
+ /** How a turn the agent did not get to answer ends: cancelled. */
5
+ export const CANCELLED_PROMPT_RESULT = {
6
+ method: "session/prompt_result",
7
+ params: { stopReason: "cancelled" },
8
+ };
9
+ function stopReasonOf(value) {
10
+ return value && STOP_REASONS.includes(value)
11
+ ? value
12
+ : undefined;
13
+ }
14
+ /**
15
+ * Per-turn usage rides the prompt response. The field is still unstable in
16
+ * v1, so most agents omit it; `usage_update` is a context gauge, not a bill.
17
+ */
18
+ function tokenUsageOf(usage) {
19
+ if (!usage)
20
+ return { ...DEFAULT_TOKEN_USAGE };
21
+ return {
22
+ input: usage.inputTokens,
23
+ output: usage.outputTokens,
24
+ reasoning: usage.thoughtTokens ?? 0,
25
+ cache: { read: usage.cachedReadTokens ?? 0, write: usage.cachedWriteTokens ?? 0 },
26
+ };
27
+ }
28
+ /** Flatten a tool call's content blocks (plus rawOutput) into one output string. */
29
+ function toolOutput(content, rawOutput) {
30
+ const texts = (content ?? [])
31
+ .map((item) => item.type === "content" && item.content.type === "text" ? item.content.text : "")
32
+ .filter(Boolean);
33
+ if (texts.length)
34
+ return texts.join("\n");
35
+ return rawOutput !== undefined && rawOutput !== null ? JSON.stringify(rawOutput) : "";
36
+ }
37
+ class AcpTransformer {
38
+ ctx;
39
+ toolParts = new Map();
40
+ /** A tool's latest display content: ACP replaces it with each update that carries some. */
41
+ toolContent = new Map();
42
+ streamParts = new Map();
43
+ /** messageId of the currently open wire message (undefined = implicit single message). */
44
+ currentMessageId;
45
+ messageOpen = false;
46
+ usage = { ...DEFAULT_TOKEN_USAGE };
47
+ stopReason;
48
+ finishReason;
49
+ error;
50
+ constructor(ctx) {
51
+ this.ctx = { sessionId: ctx.sessionId, messageId: "" };
52
+ }
53
+ process(event) {
54
+ switch (event.method) {
55
+ case "session/update":
56
+ return this.onUpdate(event.params.update);
57
+ case "session/prompt_result":
58
+ this.usage = tokenUsageOf(event.params.usage);
59
+ this.stopReason = stopReasonOf(event.params.stopReason);
60
+ this.finishReason = event.params.stopReason;
61
+ return this.finalizeStreamingParts();
62
+ case "error":
63
+ this.error = event.params.message ?? "acp agent error";
64
+ this.finishReason = "error";
65
+ // A failed prompt still closes any parts left streaming.
66
+ return this.finalizeStreamingParts();
67
+ default:
68
+ return [];
69
+ }
70
+ }
71
+ finish() {
72
+ return {
73
+ usage: this.usage,
74
+ // A cancelled prompt resolves normally; nothing throws for the engine.
75
+ cancelled: this.stopReason === "cancelled",
76
+ stopReason: this.stopReason,
77
+ finishReason: this.finishReason,
78
+ error: this.error,
79
+ };
80
+ }
81
+ onUpdate(update) {
82
+ switch (update.sessionUpdate) {
83
+ case "agent_message_chunk":
84
+ return this.chunk("text", update.content, update.messageId);
85
+ case "agent_thought_chunk":
86
+ return this.chunk("reasoning", update.content, update.messageId);
87
+ case "tool_call":
88
+ return this.toolCall(update);
89
+ case "tool_call_update":
90
+ return this.toolCallUpdate(update);
91
+ case "usage_update": {
92
+ // ACP's stable context gauge maps 1:1 onto session.usage. ACP cost is
93
+ // {amount, currency}; ours is a bare USD number — map USD only.
94
+ const usd = update.cost?.currency === "USD" ? update.cost.amount : undefined;
95
+ return [
96
+ {
97
+ kind: "usage",
98
+ used: update.used,
99
+ size: update.size,
100
+ ...(usd !== undefined && { cost: usd }),
101
+ },
102
+ ];
103
+ }
104
+ case "current_mode_update": {
105
+ // Only a mode the engine has a name for (claude-agent-acp's are
106
+ // Claude's own); another agent's mode stays raw.
107
+ const permissionMode = permissionModeOf(update.currentModeId);
108
+ return permissionMode ? [{ kind: "mode", permissionMode }] : [];
109
+ }
110
+ default:
111
+ // plan / available_commands / config_option / session_info updates
112
+ // have no part representation yet; `includeRaw` consumers still see them.
113
+ return [];
114
+ }
115
+ }
116
+ chunk(slot, content, messageId) {
117
+ if (content.type !== "text" || !content.text)
118
+ return [];
119
+ const events = [...this.rolloverMessage(messageId ?? undefined)];
120
+ let part = this.streamParts.get(slot);
121
+ if (!part) {
122
+ part =
123
+ slot === "text"
124
+ ? createTextPart(this.ctx, "", true)
125
+ : createReasoningPart(this.ctx, "", true);
126
+ this.streamParts.set(slot, part);
127
+ // The processor snapshots at emit time, after the append below. Open
128
+ // with a copy so this chunk arrives once, as the delta.
129
+ events.push({ kind: "part-open", part: structuredClone(part) });
130
+ }
131
+ part.text += content.text;
132
+ events.push(slot === "text"
133
+ ? { kind: "text-delta", partId: part.id, text: content.text }
134
+ : { kind: "reasoning-delta", partId: part.id, text: content.text });
135
+ return events;
136
+ }
137
+ toolCall(update) {
138
+ if (this.toolParts.has(update.toolCallId))
139
+ return this.toolCallUpdate(update); // duplicate open
140
+ const part = this.openTool(update);
141
+ const events = [{ kind: "part-open", part }];
142
+ if (this.applyToolUpdate(part, update))
143
+ events.push({ kind: "part-update", part });
144
+ return events;
145
+ }
146
+ toolCallUpdate(update) {
147
+ // Update before (or without) its tool_call — open a part so nothing is lost.
148
+ const part = this.toolParts.get(update.toolCallId) ?? this.openTool(update);
149
+ this.applyToolUpdate(part, update);
150
+ return [{ kind: "part-update", part }];
151
+ }
152
+ openTool(update) {
153
+ const part = createToolPart(this.ctx, update.toolCallId, update.name ?? update.title ?? "tool", isRecord(update.rawInput) ? update.rawInput : {},
154
+ // No `mcp`: an ACP agent names its tools by no rule, so no server or tool can be read from it.
155
+ {
156
+ kind: toolKindOf(update.kind),
157
+ title: update.title ?? undefined,
158
+ locations: toToolLocations(update.locations),
159
+ });
160
+ this.toolParts.set(update.toolCallId, part);
161
+ // A tool opens (lazily) the wire message it lands in: when later chunks
162
+ // omit messageId, rolloverMessage must not emit a second message-start
163
+ // and split a tool-first turn into two messages.
164
+ this.messageOpen = true;
165
+ return part;
166
+ }
167
+ /** Fold an update's meta/input/status into the part; true when it just completed. */
168
+ applyToolUpdate(part, update) {
169
+ setToolMeta(part, {
170
+ kind: toolKindOf(update.kind),
171
+ title: update.title ?? undefined,
172
+ locations: toToolLocations(update.locations),
173
+ });
174
+ const terminal = part.state.status === "completed" || part.state.status === "failed";
175
+ if (terminal)
176
+ return false;
177
+ if (isRecord(update.rawInput)) {
178
+ if (part.state.status === "pending")
179
+ startToolPart(part, update.rawInput);
180
+ else
181
+ part.state.input = update.rawInput;
182
+ }
183
+ if (update.content)
184
+ this.toolContent.set(update.toolCallId, toToolResultContent(update.content));
185
+ if (update.status !== "completed" && update.status !== "failed")
186
+ return false;
187
+ completeToolPart(part, {
188
+ output: toolOutput(update.content, update.rawOutput),
189
+ isError: update.status === "failed",
190
+ content: this.toolContent.get(update.toolCallId),
191
+ });
192
+ this.toolContent.delete(update.toolCallId);
193
+ return true;
194
+ }
195
+ /** A new v1 `messageId` closes the current wire message and opens the next. */
196
+ rolloverMessage(messageId) {
197
+ if (!messageId) {
198
+ // No id: everything belongs to one implicit message; open it lazily so
199
+ // the assistant role is explicit (parts still work without it).
200
+ if (this.messageOpen)
201
+ return [];
202
+ this.messageOpen = true;
203
+ return [{ kind: "message-start", role: "assistant" }];
204
+ }
205
+ if (messageId === this.currentMessageId)
206
+ return [];
207
+ const events = [];
208
+ if (this.messageOpen) {
209
+ events.push(...this.finalizeStreamingParts(), { kind: "message-end" });
210
+ }
211
+ this.currentMessageId = messageId;
212
+ this.messageOpen = true;
213
+ this.streamParts.clear();
214
+ events.push({ kind: "message-start", role: "assistant" });
215
+ return events;
216
+ }
217
+ /** Mark still-streaming text/reasoning parts done (turn or message boundary). */
218
+ finalizeStreamingParts() {
219
+ const events = [];
220
+ for (const part of this.streamParts.values()) {
221
+ if (part.state === "streaming") {
222
+ part.state = "done";
223
+ events.push({ kind: "part-update", part });
224
+ }
225
+ }
226
+ return events;
227
+ }
228
+ }
229
+ export function createAcpTransformer(ctx) {
230
+ return new AcpTransformer(ctx);
231
+ }