@zvada/agent-server 0.3.23 → 0.3.24

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 (246) hide show
  1. package/CHANGELOG.md +34 -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 +686 -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 +330 -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 +91 -0
  91. package/dist/core/processes/lifeline.js +210 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +163 -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 +28 -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 +434 -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 +329 -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 +141 -0
  141. package/dist/protocol/errors.js +181 -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 +291 -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/core/agents/claude-code/approvals.d.ts.map +1 -1
  207. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  208. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/options.d.ts +24 -11
  210. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  212. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  213. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  214. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  216. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  218. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  219. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  220. package/dist/types/core/agents/process-pool.d.ts +8 -0
  221. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  222. package/dist/types/core/presets.d.ts +2 -2
  223. package/dist/types/core/presets.d.ts.map +1 -1
  224. package/dist/types/server/bin.d.ts +3 -0
  225. package/dist/types/server/bin.d.ts.map +1 -0
  226. package/dist/types/server/transports.d.ts +2 -1
  227. package/dist/types/server/transports.d.ts.map +1 -1
  228. package/dist/types/sync/node-sqlite.d.ts +4 -1
  229. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  230. package/docs/consuming.md +30 -4
  231. package/docs/deploy.md +28 -0
  232. package/docs/harnesses.md +13 -1
  233. package/package.json +43 -18
  234. package/src/core/agents/claude-code/approvals.ts +5 -1
  235. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  236. package/src/core/agents/claude-code/options.ts +24 -11
  237. package/src/core/agents/claude-code/session.ts +13 -0
  238. package/src/core/agents/codex-app-server/homes.ts +11 -2
  239. package/src/core/agents/codex-app-server/login.ts +30 -0
  240. package/src/core/agents/codex-app-server/requests.ts +7 -6
  241. package/src/core/agents/codex-app-server/session.ts +11 -2
  242. package/src/core/agents/process-pool.ts +30 -4
  243. package/src/core/presets.ts +3 -2
  244. package/src/server/bin.ts +25 -10
  245. package/src/server/transports.ts +6 -1
  246. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,401 @@
1
+ import { META_KEYS, } from "../../protocol/index.js";
2
+ /** ACP v1's ToolKind set: ours without `task` and the extensions. */
3
+ const ACP_TOOL_KINDS = new Set([
4
+ "read",
5
+ "edit",
6
+ "delete",
7
+ "move",
8
+ "search",
9
+ "execute",
10
+ "think",
11
+ "fetch",
12
+ "switch_mode",
13
+ "other",
14
+ ]);
15
+ function isAcpToolKind(kind) {
16
+ return ACP_TOOL_KINDS.has(kind);
17
+ }
18
+ /** Our open ToolKind narrowed to ACP's: `task` and extensions fall back to `other`. */
19
+ const toAcpToolKind = (kind) => (isAcpToolKind(kind) ? kind : "other");
20
+ /** ACP v1's StopReason set: closed, and with no `error` member. */
21
+ const ACP_STOP_REASONS = new Set([
22
+ "end_turn",
23
+ "max_tokens",
24
+ "max_turn_requests",
25
+ "refusal",
26
+ "cancelled",
27
+ ]);
28
+ function isAcpStopReason(reason) {
29
+ return ACP_STOP_REASONS.has(reason);
30
+ }
31
+ /** ACP v1's permission option kinds: the four the engine's options use. */
32
+ const ACP_OPTION_KINDS = new Set([
33
+ "allow_once",
34
+ "allow_always",
35
+ "reject_once",
36
+ "reject_always",
37
+ ]);
38
+ function isAcpOption(option) {
39
+ return ACP_OPTION_KINDS.has(option.kind);
40
+ }
41
+ /** The engine's disjoint token buckets as ACP's (still unstable) turn usage. */
42
+ function toAcpUsage(usage) {
43
+ const read = usage.cache?.read ?? 0;
44
+ const write = usage.cache?.write ?? 0;
45
+ return {
46
+ totalTokens: usage.input + usage.output + read + write,
47
+ inputTokens: usage.input,
48
+ outputTokens: usage.output,
49
+ ...(usage.reasoning !== undefined && { thoughtTokens: usage.reasoning }),
50
+ cachedReadTokens: read,
51
+ cachedWriteTokens: write,
52
+ };
53
+ }
54
+ /**
55
+ * A turn's end as ACP's prompt response, our open stop reasons mapped onto
56
+ * ACP's closed set: `error` reports as an ended turn with the failure in
57
+ * `_meta` (an ACP client must see a stop, not a JSON-RPC failure), and
58
+ * extension and unknown values fall back to `end_turn`.
59
+ */
60
+ export function toAcpPromptResponse(summary) {
61
+ const usage = toAcpUsage(summary.usage);
62
+ if (summary.stopReason === "error")
63
+ return {
64
+ stopReason: "end_turn",
65
+ usage,
66
+ _meta: {
67
+ [META_KEYS.error]: summary.error ?? { category: "internal", message: "turn failed" },
68
+ },
69
+ };
70
+ return {
71
+ stopReason: isAcpStopReason(summary.stopReason) ? summary.stopReason : "end_turn",
72
+ usage,
73
+ };
74
+ }
75
+ /**
76
+ * A brokered permission request as ACP's `session/request_permission`: the
77
+ * option vocabulary is ACP's, so the options pass through (one of a kind ACP
78
+ * cannot carry is not offered, never read as an approval). The call's name
79
+ * and locations ride ACP's own fields; its command, address, reason and MCP
80
+ * identity have none.
81
+ */
82
+ export function toAcpPermissionRequest(sessionId, event) {
83
+ const call = event.toolCall;
84
+ return {
85
+ sessionId,
86
+ toolCall: {
87
+ toolCallId: call?.toolCallId ?? event.requestId,
88
+ title: event.title,
89
+ ...(call && { name: call.toolName }),
90
+ status: "pending",
91
+ ...(call?.kind && { kind: toAcpToolKind(call.kind) }),
92
+ ...(call?.locations?.length && { locations: call.locations }),
93
+ ...(call?.rawInput && { rawInput: call.rawInput }),
94
+ },
95
+ options: event.options.filter(isAcpOption),
96
+ };
97
+ }
98
+ // @ref LLP 0001#d12--what-the-agent-asks-the-user-is-first-class-protocol-opted-into-per-turn — a question reaches an ACP client as a form
99
+ /**
100
+ * A request for the person's input as ACP's `elicitation/create`, or
101
+ * `undefined` when the client cannot take it. ACP v1 has a form and a URL
102
+ * mode and no question mode, so the agent's own questions are a form, one
103
+ * required field per question: its choices a single or multiple select, a
104
+ * free answer (or one beside the choices) a string. ACP has no masked
105
+ * field, so a `secret` question is an ordinary one.
106
+ */
107
+ export function toAcpElicitation(sessionId, event, client) {
108
+ const scope = {
109
+ sessionId,
110
+ ...(event.toolCallId && { toolCallId: event.toolCallId }),
111
+ message: event.message,
112
+ };
113
+ if (event.mode === "question" && client?.form && event.questions?.length)
114
+ return {
115
+ ...scope,
116
+ mode: "form",
117
+ requestedSchema: {
118
+ type: "object",
119
+ properties: Object.fromEntries(event.questions.map((q) => [q.id, questionField(q)])),
120
+ required: event.questions.map((q) => q.id),
121
+ },
122
+ };
123
+ if (event.mode === "form" && client?.form && event.requestedSchema)
124
+ return {
125
+ ...scope,
126
+ mode: "form",
127
+ // An MCP server's schema, which ACP's form mode takes as MCP defines it.
128
+ requestedSchema: event.requestedSchema,
129
+ };
130
+ if (event.mode === "url" && client?.url && event.url && event.elicitationId)
131
+ return { ...scope, mode: "url", url: event.url, elicitationId: event.elicitationId };
132
+ return undefined;
133
+ }
134
+ /** One question as a form field. */
135
+ function questionField(question) {
136
+ const label = {
137
+ title: question.header ?? question.question,
138
+ ...(question.header && { description: question.question }),
139
+ };
140
+ const choices = question.options?.map((option) => ({
141
+ const: option.label,
142
+ title: option.label,
143
+ ...(option.description && { description: option.description }),
144
+ }));
145
+ // Words of the person's own beside the choices: a string, the choices named.
146
+ if (!choices?.length || question.allowOther)
147
+ return {
148
+ type: "string",
149
+ ...label,
150
+ ...(choices?.length && {
151
+ description: `${question.question} (${choices.map((c) => c.const).join(", ")}, or your own words)`,
152
+ }),
153
+ };
154
+ if (question.multiSelect)
155
+ return { type: "array", ...label, items: { anyOf: choices } };
156
+ return { type: "string", ...label, oneOf: choices };
157
+ }
158
+ /**
159
+ * The client's answer as the engine's outcome: a question's answers are each
160
+ * an array (a form's single value becomes one), a form's content passes as
161
+ * it is, and an action ACP may add later is a cancel.
162
+ */
163
+ export function fromAcpElicitation(event, response) {
164
+ if (response.action === "decline")
165
+ return { action: "decline" };
166
+ if (response.action !== "accept")
167
+ return { action: "cancel" };
168
+ const content = response.content;
169
+ if (!content)
170
+ return { action: "accept" };
171
+ if (event.mode !== "question")
172
+ return { action: "accept", content };
173
+ return {
174
+ action: "accept",
175
+ content: Object.fromEntries(Object.entries(content).map(([id, value]) => [
176
+ id,
177
+ Array.isArray(value) ? value.map(String) : [String(value)],
178
+ ])),
179
+ };
180
+ }
181
+ /**
182
+ * Per-prompt translator from the engine's LifecycleEvents to ACP v1
183
+ * `session/update` payloads — the exact inverse of the acp harness adapter
184
+ * (the vocabularies were aligned for this: ToolKind, tool status, and
185
+ * permission shapes pass through unchanged).
186
+ *
187
+ * Deliberate v1 gaps: sub-agent parts (`parentToolCallId`) have no ACP slot
188
+ * and are dropped (the parent tool's result carries the outcome); the
189
+ * `session.compaction` entity has no v1 equivalent; `usage_update` requires
190
+ * `size`, so gauges without a window size are skipped. The user echo is
191
+ * skipped too — the ACP client authored the prompt and re-chunking it back
192
+ * would duplicate it.
193
+ */
194
+ export class AcpUpdateTranslator {
195
+ /** toolCallIds already announced via `tool_call`. */
196
+ openedTools = new Set();
197
+ /** Text/reasoning characters already emitted per part (dedupe snapshots vs deltas). */
198
+ sentByPart = new Map();
199
+ /** Message ids of the user echo (role "user") — skipped entirely. */
200
+ userMessageIds = new Set();
201
+ /** Part ids that belong to a sub-agent (parented) — their deltas are skipped. */
202
+ parentedParts = new Set();
203
+ translate(event) {
204
+ switch (event.type) {
205
+ case "message.started": {
206
+ if (event.role === "user")
207
+ this.userMessageIds.add(event.messageId);
208
+ return [];
209
+ }
210
+ case "message.part.delta": {
211
+ if (this.parentedParts.has(event.partId))
212
+ return [];
213
+ if (this.userMessageIds.has(event.messageId))
214
+ return [];
215
+ const { delta } = event;
216
+ if (delta.type === "tool_input")
217
+ return []; // covered by part snapshots
218
+ this.sentByPart.set(event.partId, (this.sentByPart.get(event.partId) ?? 0) + delta.text.length);
219
+ return [
220
+ chunk(delta.type === "text" ? "agent_message_chunk" : "agent_thought_chunk", delta.text, event.messageId),
221
+ ];
222
+ }
223
+ case "message.part": {
224
+ const part = event.part;
225
+ if (part.parentToolCallId) {
226
+ this.parentedParts.add(part.id);
227
+ return [];
228
+ }
229
+ if (this.userMessageIds.has(event.messageId))
230
+ return [];
231
+ if (part.type === "tool")
232
+ return this.toolUpdate(part);
233
+ // Image/file parts have no v1 chunk slot (agent-side); dropped.
234
+ if (part.type !== "text" && part.type !== "reasoning")
235
+ return [];
236
+ // While a part is still streaming, its snapshots mirror the deltas
237
+ // (adapters mutate in place, so an early snapshot can already carry
238
+ // delta text — emitting both doubles it). Only the final `done`
239
+ // snapshot may contribute an unseen suffix, which is also how fully
240
+ // non-streamed parts (no deltas at all) get emitted exactly once.
241
+ if (part.state !== "done")
242
+ return [];
243
+ const sent = this.sentByPart.get(part.id) ?? 0;
244
+ if (part.text.length <= sent)
245
+ return [];
246
+ this.sentByPart.set(part.id, part.text.length);
247
+ return [
248
+ chunk(part.type === "text" ? "agent_message_chunk" : "agent_thought_chunk", part.text.slice(sent), event.messageId),
249
+ ];
250
+ }
251
+ case "session.usage":
252
+ if (event.size === undefined)
253
+ return [];
254
+ return [
255
+ {
256
+ sessionUpdate: "usage_update",
257
+ used: event.used,
258
+ size: event.size,
259
+ ...(event.cost !== undefined && {
260
+ cost: { amount: event.cost, currency: "USD" },
261
+ }),
262
+ },
263
+ ];
264
+ default:
265
+ return [];
266
+ }
267
+ }
268
+ toolUpdate(part) {
269
+ // Statuses and ToolKind are the SDK's own vocabulary, with
270
+ // two edge maps: `cancelled` (ACP v2 / schema 1.6+) predates our pinned
271
+ // SDK's ToolCallStatus and maps to `failed`; our open kind narrows to
272
+ // ACP's (`toAcpToolKind`).
273
+ const status = (part.state.status === "cancelled" ? "failed" : part.state.status);
274
+ const kind = part.kind ? toAcpToolKind(part.kind) : undefined;
275
+ const updates = [];
276
+ if (!this.openedTools.has(part.toolCallId)) {
277
+ this.openedTools.add(part.toolCallId);
278
+ // A terminal-first snapshot — a tool already `completed`/`failed` on
279
+ // its first (and maybe only) `message.part` (e.g. a conforming ACP
280
+ // agent that reports a tool solely via a bare terminal
281
+ // `tool_call_update`, which the `acp` harness preserves as a single
282
+ // terminal part) — must still deliver its result body. Emit the
283
+ // spec-canonical pair: announce with a NON-terminal `in_progress`
284
+ // status, then a `tool_call_update` carrying the real terminal
285
+ // status and the output/error `content` (the only update a result
286
+ // can ride on). `cancelled` has no body to drop and stays on the
287
+ // single-event announce path with its mapped `failed` status.
288
+ const terminalFirst = part.state.status === "completed" || part.state.status === "failed";
289
+ updates.push({
290
+ sessionUpdate: "tool_call",
291
+ toolCallId: part.toolCallId,
292
+ title: part.title ?? part.toolName,
293
+ name: part.toolName,
294
+ ...(kind && { kind }),
295
+ status: terminalFirst ? "in_progress" : status,
296
+ ...(part.locations?.length && { locations: part.locations }),
297
+ ...("input" in part.state && { rawInput: part.state.input }),
298
+ });
299
+ if (!terminalFirst)
300
+ return updates;
301
+ }
302
+ const output = part.state.status === "failed"
303
+ ? part.state.error
304
+ : part.state.status === "completed"
305
+ ? part.state.output
306
+ : undefined;
307
+ const content = [
308
+ ...(output
309
+ ? [{ type: "content", content: { type: "text", text: output } }]
310
+ : []),
311
+ ...toAcpDiffs(part.state.status === "completed" ? part.state.content : undefined),
312
+ ];
313
+ updates.push({
314
+ sessionUpdate: "tool_call_update",
315
+ toolCallId: part.toolCallId,
316
+ status,
317
+ ...(content.length && { content }),
318
+ });
319
+ return updates;
320
+ }
321
+ }
322
+ // @ref LLP 0002#tool-output-has-three-audiences — a part's diffs reach an ACP client as ACP diffs
323
+ /**
324
+ * A part's `diff` entries as ACP's, which a client draws. A `terminal`
325
+ * names a terminal of the agent's, which no client of ours can show, so it
326
+ * is not sent; text is the part's output.
327
+ */
328
+ function toAcpDiffs(content) {
329
+ return (content ?? []).flatMap((item) => item.type === "diff"
330
+ ? [
331
+ {
332
+ type: "diff",
333
+ path: item.path,
334
+ ...(item.oldText !== undefined && { oldText: item.oldText }),
335
+ newText: item.newText,
336
+ },
337
+ ]
338
+ : []);
339
+ }
340
+ function chunk(kind, text, messageId) {
341
+ return { sessionUpdate: kind, content: { type: "text", text }, messageId };
342
+ }
343
+ /**
344
+ * ACP prompt content → engine input: text, base64 images, and a resource
345
+ * link as a Markdown link in the text, which ACP v1 has every agent take (a
346
+ * client's @-mention of a file) and any harness's agent can follow. Audio
347
+ * and embedded resources, which the binding does not advertise, are dropped.
348
+ */
349
+ export function fromPromptBlocks(prompt) {
350
+ const parts = [];
351
+ for (const block of prompt) {
352
+ if (block.type === "text" && block.text)
353
+ parts.push({ type: "text", text: block.text });
354
+ else if (block.type === "resource_link")
355
+ parts.push({
356
+ type: "text",
357
+ text: block.name && block.name !== block.uri ? `[${block.name}](${block.uri})` : block.uri,
358
+ });
359
+ else if (block.type === "image" && block.data) {
360
+ parts.push({ type: "image", data: block.data, mimeType: block.mimeType });
361
+ }
362
+ }
363
+ if (parts.length === 1 && parts[0]?.type === "text")
364
+ return parts[0].text;
365
+ return parts.length ? parts : "";
366
+ }
367
+ /**
368
+ * ACP `McpServer[]` → engine MCP config map (inverse of the harness-side
369
+ * mapping). A server of another transport throws, naming it: ACP v1 lets a
370
+ * client send one only to an agent that advertised it, says nothing of what
371
+ * an agent does with one it did not, and a session without a server it
372
+ * asked for must not run as if it had it.
373
+ */
374
+ export function fromAcpMcpServers(servers) {
375
+ if (!servers?.length)
376
+ return undefined;
377
+ const out = {};
378
+ for (const server of servers) {
379
+ if ("command" in server) {
380
+ out[server.name] = {
381
+ type: "stdio",
382
+ command: server.command,
383
+ args: server.args,
384
+ env: Object.fromEntries((server.env ?? []).map((e) => [e.name, e.value])),
385
+ };
386
+ }
387
+ else if ("url" in server && (server.type === "http" || server.type === "sse")) {
388
+ out[server.name] = {
389
+ type: server.type,
390
+ url: server.url,
391
+ headers: Object.fromEntries((server.headers ?? []).map((h) => [h.name, h.value])),
392
+ };
393
+ }
394
+ else {
395
+ // The SDK's `acp` transport (MCP over the ACP channel, unstable) or one newer still.
396
+ const transport = server.type;
397
+ throw new Error(`MCP server "${server.name}" uses the ${String(transport)} transport, which agent-server cannot attach (it takes stdio, http and sse)`);
398
+ }
399
+ }
400
+ return Object.keys(out).length ? out : undefined;
401
+ }