@zvada/agent-server 0.3.27 → 0.3.28

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 (170) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +6 -4
  3. package/dist/core/agents/acp/account.js +111 -0
  4. package/dist/core/agents/acp/acp-agent.js +247 -158
  5. package/dist/core/agents/acp/adapter.js +103 -34
  6. package/dist/core/agents/acp/client.js +169 -42
  7. package/dist/core/agents/acp/known-agents.js +12 -5
  8. package/dist/core/agents/acp/mappings.js +84 -20
  9. package/dist/core/agents/acp/models.js +59 -0
  10. package/dist/core/agents/acp/profile.js +36 -0
  11. package/dist/core/agents/acp/prompts.js +248 -0
  12. package/dist/core/agents/acp/requests.js +4 -4
  13. package/dist/core/agents/claude-code/login.js +4 -1
  14. package/dist/core/agents/claude-code/session.js +38 -10
  15. package/dist/core/agents/claude-code/spawn.js +0 -26
  16. package/dist/core/agents/codex-app-server/client.js +12 -13
  17. package/dist/core/agents/codex-app-server/login.js +4 -1
  18. package/dist/core/agents/gemini/failures.js +133 -0
  19. package/dist/core/agents/gemini/login.js +173 -0
  20. package/dist/core/agents/gemini/profile.js +137 -0
  21. package/dist/core/agents/gemini/tools.js +91 -0
  22. package/dist/core/agents/login.js +8 -6
  23. package/dist/core/agents/stderr-tail.js +5 -2
  24. package/dist/core/presets.js +13 -0
  25. package/dist/core/processes/native-processes.js +23 -1
  26. package/dist/core/provision/install-build.js +70 -26
  27. package/dist/core/provision/pins.js +5 -0
  28. package/dist/core/provision/provisioner.js +39 -16
  29. package/dist/core/provision/releases.js +39 -1
  30. package/dist/core/provision/tools.js +87 -28
  31. package/dist/operator/errors.js +2 -2
  32. package/dist/operator/operator.js +171 -74
  33. package/dist/operator/render.js +33 -25
  34. package/dist/operator/session-tools.js +2 -1
  35. package/dist/protocol/account.js +5 -1
  36. package/dist/protocol/auth.js +5 -1
  37. package/dist/protocol/credentials.js +9 -1
  38. package/dist/protocol/harness.js +9 -1
  39. package/dist/server/bin.js +22 -7
  40. package/dist/server/install.js +6 -4
  41. package/dist/types/core/agents/acp/account.d.ts +55 -0
  42. package/dist/types/core/agents/acp/account.d.ts.map +1 -0
  43. package/dist/types/core/agents/acp/acp-agent.d.ts +65 -36
  44. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  45. package/dist/types/core/agents/acp/adapter.d.ts +28 -3
  46. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  47. package/dist/types/core/agents/acp/client.d.ts +66 -4
  48. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  49. package/dist/types/core/agents/acp/known-agents.d.ts +4 -2
  50. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -1
  51. package/dist/types/core/agents/acp/mappings.d.ts +53 -7
  52. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  53. package/dist/types/core/agents/acp/models.d.ts +22 -0
  54. package/dist/types/core/agents/acp/models.d.ts.map +1 -0
  55. package/dist/types/core/agents/acp/profile.d.ts +92 -0
  56. package/dist/types/core/agents/acp/profile.d.ts.map +1 -0
  57. package/dist/types/core/agents/acp/prompts.d.ts +108 -0
  58. package/dist/types/core/agents/acp/prompts.d.ts.map +1 -0
  59. package/dist/types/core/agents/acp/requests.d.ts +7 -1
  60. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  61. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  62. package/dist/types/core/agents/claude-code/session.d.ts +3 -0
  63. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  64. package/dist/types/core/agents/claude-code/spawn.d.ts +0 -8
  65. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -1
  66. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  67. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  68. package/dist/types/core/agents/gemini/failures.d.ts +25 -0
  69. package/dist/types/core/agents/gemini/failures.d.ts.map +1 -0
  70. package/dist/types/core/agents/gemini/login.d.ts +28 -0
  71. package/dist/types/core/agents/gemini/login.d.ts.map +1 -0
  72. package/dist/types/core/agents/gemini/profile.d.ts +30 -0
  73. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -0
  74. package/dist/types/core/agents/gemini/tools.d.ts +18 -0
  75. package/dist/types/core/agents/gemini/tools.d.ts.map +1 -0
  76. package/dist/types/core/agents/login.d.ts +15 -5
  77. package/dist/types/core/agents/login.d.ts.map +1 -1
  78. package/dist/types/core/agents/stderr-tail.d.ts +1 -1
  79. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -1
  80. package/dist/types/core/presets.d.ts +2 -2
  81. package/dist/types/core/presets.d.ts.map +1 -1
  82. package/dist/types/core/processes/native-processes.d.ts +6 -0
  83. package/dist/types/core/processes/native-processes.d.ts.map +1 -1
  84. package/dist/types/core/provision/checksums.d.ts +7 -1
  85. package/dist/types/core/provision/checksums.d.ts.map +1 -1
  86. package/dist/types/core/provision/install-build.d.ts +32 -6
  87. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  88. package/dist/types/core/provision/pins.d.ts +4 -0
  89. package/dist/types/core/provision/pins.d.ts.map +1 -1
  90. package/dist/types/core/provision/provisioner.d.ts +18 -7
  91. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  92. package/dist/types/core/provision/releases.d.ts +2 -1
  93. package/dist/types/core/provision/releases.d.ts.map +1 -1
  94. package/dist/types/core/provision/tools.d.ts +36 -7
  95. package/dist/types/core/provision/tools.d.ts.map +1 -1
  96. package/dist/types/operator/errors.d.ts +5 -1
  97. package/dist/types/operator/errors.d.ts.map +1 -1
  98. package/dist/types/operator/operator.d.ts.map +1 -1
  99. package/dist/types/operator/render.d.ts +11 -6
  100. package/dist/types/operator/render.d.ts.map +1 -1
  101. package/dist/types/operator/session-tools.d.ts.map +1 -1
  102. package/dist/types/operator/types.d.ts +1 -0
  103. package/dist/types/operator/types.d.ts.map +1 -1
  104. package/dist/types/protocol/account.d.ts +4 -2
  105. package/dist/types/protocol/account.d.ts.map +1 -1
  106. package/dist/types/protocol/auth.d.ts +10 -7
  107. package/dist/types/protocol/auth.d.ts.map +1 -1
  108. package/dist/types/protocol/clis.d.ts +4 -3
  109. package/dist/types/protocol/clis.d.ts.map +1 -1
  110. package/dist/types/protocol/config.d.ts +2 -0
  111. package/dist/types/protocol/config.d.ts.map +1 -1
  112. package/dist/types/protocol/conversation.d.ts +3 -3
  113. package/dist/types/protocol/credentials.d.ts +8 -0
  114. package/dist/types/protocol/credentials.d.ts.map +1 -1
  115. package/dist/types/protocol/execution.d.ts +1 -1
  116. package/dist/types/protocol/harness.d.ts +5 -2
  117. package/dist/types/protocol/harness.d.ts.map +1 -1
  118. package/dist/types/protocol/lifecycle.d.ts +8 -8
  119. package/dist/types/protocol/models.d.ts +3 -0
  120. package/dist/types/protocol/models.d.ts.map +1 -1
  121. package/dist/types/protocol/wire-api.d.ts +39 -29
  122. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  123. package/dist/types/protocol/wire.d.ts +13 -10
  124. package/dist/types/protocol/wire.d.ts.map +1 -1
  125. package/dist/types/server/install.d.ts +2 -1
  126. package/dist/types/server/install.d.ts.map +1 -1
  127. package/docs/consuming.md +6 -0
  128. package/docs/deploy.md +17 -8
  129. package/docs/harnesses.md +166 -44
  130. package/package.json +1 -1
  131. package/src/core/agents/acp/account.ts +158 -0
  132. package/src/core/agents/acp/acp-agent.ts +288 -178
  133. package/src/core/agents/acp/adapter.ts +126 -35
  134. package/src/core/agents/acp/client.ts +196 -49
  135. package/src/core/agents/acp/known-agents.ts +14 -5
  136. package/src/core/agents/acp/mappings.ts +112 -21
  137. package/src/core/agents/acp/models.ts +72 -0
  138. package/src/core/agents/acp/profile.ts +127 -0
  139. package/src/core/agents/acp/prompts.ts +287 -0
  140. package/src/core/agents/acp/requests.ts +16 -9
  141. package/src/core/agents/claude-code/login.ts +4 -1
  142. package/src/core/agents/claude-code/session.ts +38 -8
  143. package/src/core/agents/claude-code/spawn.ts +0 -26
  144. package/src/core/agents/codex-app-server/client.ts +11 -18
  145. package/src/core/agents/codex-app-server/login.ts +4 -5
  146. package/src/core/agents/gemini/failures.ts +148 -0
  147. package/src/core/agents/gemini/login.ts +188 -0
  148. package/src/core/agents/gemini/profile.ts +162 -0
  149. package/src/core/agents/gemini/tools.ts +99 -0
  150. package/src/core/agents/login.ts +14 -8
  151. package/src/core/agents/stderr-tail.ts +5 -2
  152. package/src/core/presets.ts +15 -2
  153. package/src/core/processes/native-processes.ts +32 -1
  154. package/src/core/provision/checksums.ts +12 -2
  155. package/src/core/provision/install-build.ts +122 -55
  156. package/src/core/provision/pins.ts +5 -0
  157. package/src/core/provision/provisioner.ts +62 -27
  158. package/src/core/provision/releases.ts +47 -1
  159. package/src/core/provision/tools.ts +124 -31
  160. package/src/operator/errors.ts +5 -2
  161. package/src/operator/operator.ts +181 -77
  162. package/src/operator/render.ts +60 -28
  163. package/src/operator/session-tools.ts +2 -1
  164. package/src/operator/types.ts +1 -0
  165. package/src/protocol/account.ts +5 -2
  166. package/src/protocol/auth.ts +5 -1
  167. package/src/protocol/credentials.ts +11 -2
  168. package/src/protocol/harness.ts +9 -1
  169. package/src/server/bin.ts +20 -6
  170. package/src/server/install.ts +6 -3
@@ -8,6 +8,7 @@ import type {
8
8
  } from "@agentclientprotocol/sdk";
9
9
  import {
10
10
  DEFAULT_TOKEN_USAGE,
11
+ type ErrorCategory,
11
12
  type ReasoningPart,
12
13
  STOP_REASONS,
13
14
  type StopReason,
@@ -25,13 +26,16 @@ import {
25
26
  } from "../../../protocol/index.ts";
26
27
  import { isRecord } from "../../utils/is-record.ts";
27
28
  import type { AdapterEvent, EventTransformer, TransformResult } from "../types.ts";
28
- import { permissionModeOf, toToolLocations, toToolResultContent, toolKindOf } from "./mappings.ts";
29
+ import { modeNames, toToolLocations, toToolResultContent, toolKindOf } from "./mappings.ts";
30
+ import type { AcpProfile, AcpToolCall } from "./profile.ts";
29
31
 
30
32
  /**
31
33
  * Parses ACP v1 raw events into AdapterEvents. The mapping is nearly identity:
32
34
  * our part vocabulary (ToolKind, tool status, locations) was aligned to ACP up
33
35
  * front, so chunks append to text/reasoning parts and
34
- * `tool_call`/`tool_call_update` upsert tool parts by `toolCallId`. Everything
36
+ * `tool_call`/`tool_call_update` upsert tool parts by `toolCallId`. Parts keep
37
+ * the order they came in: a message has one streaming part open at a time,
38
+ * which a new tool call or a chunk of the other kind finishes. Everything
35
39
  * arrives through the SDK connection, which zod-validates inbound payloads —
36
40
  * so the SDK's own types ARE the raw shapes (no defensive re-modelling).
37
41
  *
@@ -40,7 +44,13 @@ import { permissionModeOf, toToolLocations, toToolResultContent, toolKindOf } fr
40
44
  * - `{method: "session/prompt_result", params: PromptResponse}` (synthetic —
41
45
  * ACP returns the turn's stopReason as the prompt *response*, not as a
42
46
  * notification, so the agent re-injects it into the event stream)
43
- * - `{method: "error", params: {message}}` (synthetic, prompt failure)
47
+ * - `{method: "error", params: {message, category?, usage?}}` (synthetic, a
48
+ * prompt that failed: its category when the reader knows it, and the usage
49
+ * of an answer a harness reads as a failure)
50
+ * - `{method: "agentServer/mcpServers", params: {names}}` (synthetic, the
51
+ * session's MCP servers, for a harness's tool rules)
52
+ * - `{method: "agentServer/steerRead", params: {steerId}}` (synthetic, the
53
+ * agent took a steer sent as a prompt)
44
54
  *
45
55
  * v1 `messageId` on chunks is optional: when present, a change opens a new
46
56
  * wire message; when absent the whole turn is one message (the processor
@@ -49,7 +59,12 @@ import { permissionModeOf, toToolLocations, toToolResultContent, toolKindOf } fr
49
59
  export type AcpRawEvent =
50
60
  | { method: "session/update"; params: SessionNotification }
51
61
  | { method: "session/prompt_result"; params: Partial<PromptResponse> }
52
- | { method: "error"; params: { message?: string } };
62
+ | {
63
+ method: "error";
64
+ params: { message?: string; category?: ErrorCategory; usage?: PromptResponse["usage"] };
65
+ }
66
+ | { method: "agentServer/mcpServers"; params: { names: string[] } }
67
+ | { method: "agentServer/steerRead"; params: { steerId: string } };
53
68
 
54
69
  /** How a turn the agent did not get to answer ends: cancelled. */
55
70
  export const CANCELLED_PROMPT_RESULT: AcpRawEvent = {
@@ -77,7 +92,10 @@ function tokenUsageOf(usage: PromptResponse["usage"]): TokenUsage {
77
92
  };
78
93
  }
79
94
 
80
- /** Flatten a tool call's content blocks (plus rawOutput) into one output string. */
95
+ /**
96
+ * Flatten a tool call's content blocks (plus rawOutput) into one output
97
+ * string. An empty record says nothing: no output, not `{}`.
98
+ */
81
99
  function toolOutput(content: ToolCallContent[] | null | undefined, rawOutput: unknown): string {
82
100
  const texts = (content ?? [])
83
101
  .map((item) =>
@@ -85,28 +103,46 @@ function toolOutput(content: ToolCallContent[] | null | undefined, rawOutput: un
85
103
  )
86
104
  .filter(Boolean);
87
105
  if (texts.length) return texts.join("\n");
88
- return rawOutput !== undefined && rawOutput !== null ? JSON.stringify(rawOutput) : "";
106
+ if (rawOutput === undefined || rawOutput === null) return "";
107
+ if (isRecord(rawOutput) && Object.keys(rawOutput).length === 0) return "";
108
+ return JSON.stringify(rawOutput);
89
109
  }
90
110
 
91
111
  type StreamSlot = "text" | "reasoning";
92
112
 
113
+ /** What of its harness's profile an ACP turn's adapter reads: its tool rules and its mode ids. */
114
+ export type AcpReading = Pick<AcpProfile, "tools" | "modeIds">;
115
+
93
116
  class AcpTransformer implements EventTransformer<AcpRawEvent> {
94
117
  private readonly ctx: StreamContext;
95
118
  private readonly toolParts = new Map<string, ToolPart>();
119
+ /** Each tool call as its updates assembled it: an update carries only what changed. */
120
+ private readonly toolCalls = new Map<string, AcpToolCall>();
96
121
  /** A tool's latest display content: ACP replaces it with each update that carries some. */
97
122
  private readonly toolContent = new Map<string, ToolResultContent[]>();
98
- private readonly streamParts = new Map<StreamSlot, TextPart | ReasoningPart>();
123
+ /** The text or reasoning part chunks of its kind append to, until something else comes. */
124
+ private streaming?: TextPart | ReasoningPart;
99
125
  /** messageId of the currently open wire message (undefined = implicit single message). */
100
126
  private currentMessageId?: string;
101
127
  private messageOpen = false;
102
128
 
129
+ /** The session's MCP servers, by name: what the tool rules tell a call's server from its tool by. */
130
+ private servers: readonly string[] = [];
131
+
103
132
  private usage: TokenUsage = { ...DEFAULT_TOKEN_USAGE };
104
133
  private stopReason?: StopReason;
105
134
  private finishReason?: string;
106
135
  private error?: string;
136
+ private errorCategory?: ErrorCategory;
137
+
138
+ private readonly modes: ReturnType<typeof modeNames>;
107
139
 
108
- constructor(ctx: { sessionId: string }) {
140
+ constructor(
141
+ ctx: { sessionId: string },
142
+ private readonly reading: AcpReading = {},
143
+ ) {
109
144
  this.ctx = { sessionId: ctx.sessionId, messageId: "" };
145
+ this.modes = modeNames(reading.modeIds);
110
146
  }
111
147
 
112
148
  process(event: AcpRawEvent): AdapterEvent[] {
@@ -117,12 +153,19 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
117
153
  this.usage = tokenUsageOf(event.params.usage);
118
154
  this.stopReason = stopReasonOf(event.params.stopReason);
119
155
  this.finishReason = event.params.stopReason;
120
- return this.finalizeStreamingParts();
156
+ return this.finishStreaming();
121
157
  case "error":
122
158
  this.error = event.params.message ?? "acp agent error";
123
159
  this.finishReason = "error";
160
+ if (event.params.category) this.errorCategory = event.params.category;
161
+ if (event.params.usage) this.usage = tokenUsageOf(event.params.usage);
124
162
  // A failed prompt still closes any parts left streaming.
125
- return this.finalizeStreamingParts();
163
+ return this.finishStreaming();
164
+ case "agentServer/mcpServers":
165
+ this.servers = event.params.names;
166
+ return [];
167
+ case "agentServer/steerRead":
168
+ return this.steerRead(event.params.steerId);
126
169
  default:
127
170
  return [];
128
171
  }
@@ -136,6 +179,7 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
136
179
  stopReason: this.stopReason,
137
180
  finishReason: this.finishReason,
138
181
  error: this.error,
182
+ ...(this.errorCategory && { errorCategory: this.errorCategory }),
139
183
  };
140
184
  }
141
185
 
@@ -164,8 +208,8 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
164
208
  }
165
209
  case "current_mode_update": {
166
210
  // Only a mode the engine has a name for (claude-agent-acp's are
167
- // Claude's own); another agent's mode stays raw.
168
- const permissionMode = permissionModeOf(update.currentModeId);
211
+ // Claude's own, a profile's by its ids); another agent's mode stays raw.
212
+ const permissionMode = this.modes.modeOf(update.currentModeId);
169
213
  return permissionMode ? [{ kind: "mode", permissionMode }] : [];
170
214
  }
171
215
  default:
@@ -182,13 +226,14 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
182
226
  ): AdapterEvent[] {
183
227
  if (content.type !== "text" || !content.text) return [];
184
228
  const events: AdapterEvent[] = [...this.rolloverMessage(messageId ?? undefined)];
185
- let part = this.streamParts.get(slot);
186
- if (!part) {
229
+ let part = this.streaming;
230
+ if (part?.type !== slot) {
231
+ events.push(...this.finishStreaming());
187
232
  part =
188
233
  slot === "text"
189
234
  ? createTextPart(this.ctx, "", true)
190
235
  : createReasoningPart(this.ctx, "", true);
191
- this.streamParts.set(slot, part);
236
+ this.streaming = part;
192
237
  // The processor snapshots at emit time, after the append below. Open
193
238
  // with a copy so this chunk arrives once, as the delta.
194
239
  events.push({ kind: "part-open", part: structuredClone(part) });
@@ -204,28 +249,69 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
204
249
 
205
250
  private toolCall(update: ToolCallUpdate): AdapterEvent[] {
206
251
  if (this.toolParts.has(update.toolCallId)) return this.toolCallUpdate(update); // duplicate open
252
+ const events = this.finishStreaming();
207
253
  const part = this.openTool(update);
208
- const events: AdapterEvent[] = [{ kind: "part-open", part }];
254
+ events.push({ kind: "part-open", part });
209
255
  if (this.applyToolUpdate(part, update)) events.push({ kind: "part-update", part });
210
256
  return events;
211
257
  }
212
258
 
213
259
  private toolCallUpdate(update: ToolCallUpdate): AdapterEvent[] {
260
+ const known = this.toolParts.get(update.toolCallId);
214
261
  // Update before (or without) its tool_call — open a part so nothing is lost.
215
- const part = this.toolParts.get(update.toolCallId) ?? this.openTool(update);
262
+ const events: AdapterEvent[] = known ? [] : this.finishStreaming();
263
+ const part = known ?? this.openTool(update);
216
264
  this.applyToolUpdate(part, update);
217
- return [{ kind: "part-update", part }];
265
+ events.push({ kind: "part-update", part });
266
+ return events;
267
+ }
268
+
269
+ /**
270
+ * The agent took a steer: what streamed before it is done, and its message
271
+ * ends; the agent's next output opens a message after the steer's echo.
272
+ */
273
+ private steerRead(steerId: string): AdapterEvent[] {
274
+ // What came before the steer stays before it.
275
+ const events = this.finishStreaming();
276
+ if (this.messageOpen) events.push({ kind: "message-end" });
277
+ this.messageOpen = false;
278
+ this.currentMessageId = undefined;
279
+ events.push({ kind: "steer-inserted", steerId });
280
+ return events;
281
+ }
282
+
283
+ /**
284
+ * The call an update makes of its tool call, its fields over those before
285
+ * them: what the tool rules read, since an ACP agent names its tools by no
286
+ * rule of its own.
287
+ */
288
+ private assemble(update: ToolCallUpdate): AcpToolCall {
289
+ const before = this.toolCalls.get(update.toolCallId) ?? {};
290
+ const call: AcpToolCall = {
291
+ ...before,
292
+ ...(update.name != null && { name: update.name }),
293
+ ...(update.rawInput !== undefined && { rawInput: update.rawInput }),
294
+ ...(update.rawOutput !== undefined && { rawOutput: update.rawOutput }),
295
+ };
296
+ this.toolCalls.set(update.toolCallId, call);
297
+ return call;
298
+ }
299
+
300
+ /** What the tool rules read of a call, as its updates assembled it. */
301
+ private described(call: AcpToolCall) {
302
+ return this.reading.tools?.describe(call, this.servers) ?? {};
218
303
  }
219
304
 
220
305
  private openTool(update: ToolCallUpdate): ToolPart {
306
+ const call = this.assemble(update);
221
307
  const part = createToolPart(
222
308
  this.ctx,
223
309
  update.toolCallId,
224
310
  update.name ?? update.title ?? "tool",
225
311
  isRecord(update.rawInput) ? update.rawInput : {},
226
- // No `mcp`: an ACP agent names its tools by no rule, so no server or tool can be read from it.
227
312
  {
228
313
  kind: toolKindOf(update.kind),
314
+ ...this.described(call),
229
315
  title: update.title ?? undefined,
230
316
  locations: toToolLocations(update.locations),
231
317
  },
@@ -240,8 +326,10 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
240
326
 
241
327
  /** Fold an update's meta/input/status into the part; true when it just completed. */
242
328
  private applyToolUpdate(part: ToolPart, update: ToolCallUpdate): boolean {
329
+ const call = this.assemble(update);
243
330
  setToolMeta(part, {
244
331
  kind: toolKindOf(update.kind),
332
+ ...this.described(call),
245
333
  title: update.title ?? undefined,
246
334
  locations: toToolLocations(update.locations),
247
335
  });
@@ -254,10 +342,13 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
254
342
  if (update.content)
255
343
  this.toolContent.set(update.toolCallId, toToolResultContent(update.content));
256
344
  if (update.status !== "completed" && update.status !== "failed") return false;
345
+ const read = this.reading.tools?.output?.(call);
346
+ // @ref LLP 0002#tool-output-has-three-audiences — a command's exit code is metadata; non-zero fails it
257
347
  completeToolPart(part, {
258
- output: toolOutput(update.content, update.rawOutput),
259
- isError: update.status === "failed",
348
+ output: read?.text ?? toolOutput(update.content, update.rawOutput),
349
+ isError: update.status === "failed" || (read?.exitCode ?? 0) !== 0 || read?.failed === true,
260
350
  content: this.toolContent.get(update.toolCallId),
351
+ ...(read?.exitCode !== undefined && { metadata: { exitCode: read.exitCode } }),
261
352
  });
262
353
  this.toolContent.delete(update.toolCallId);
263
354
  return true;
@@ -275,28 +366,28 @@ class AcpTransformer implements EventTransformer<AcpRawEvent> {
275
366
  if (messageId === this.currentMessageId) return [];
276
367
  const events: AdapterEvent[] = [];
277
368
  if (this.messageOpen) {
278
- events.push(...this.finalizeStreamingParts(), { kind: "message-end" });
369
+ events.push(...this.finishStreaming(), { kind: "message-end" });
279
370
  }
280
371
  this.currentMessageId = messageId;
281
372
  this.messageOpen = true;
282
- this.streamParts.clear();
283
373
  events.push({ kind: "message-start", role: "assistant" });
284
374
  return events;
285
375
  }
286
376
 
287
- /** Mark still-streaming text/reasoning parts done (turn or message boundary). */
288
- private finalizeStreamingParts(): AdapterEvent[] {
289
- const events: AdapterEvent[] = [];
290
- for (const part of this.streamParts.values()) {
291
- if (part.state === "streaming") {
292
- part.state = "done";
293
- events.push({ kind: "part-update", part });
294
- }
295
- }
296
- return events;
377
+ /** Mark the streaming text or reasoning part done: something else came, or the message or turn ended. */
378
+ private finishStreaming(): AdapterEvent[] {
379
+ const part = this.streaming;
380
+ this.streaming = undefined;
381
+ if (!part) return [];
382
+ part.state = "done";
383
+ return [{ kind: "part-update", part }];
297
384
  }
298
385
  }
299
386
 
300
- export function createAcpTransformer(ctx: { sessionId: string }): EventTransformer {
301
- return new AcpTransformer(ctx);
387
+ /** An ACP turn's adapter; `reading` is what of its harness's profile it reads beyond ACP. */
388
+ export function createAcpTransformer(
389
+ ctx: { sessionId: string },
390
+ reading?: AcpReading,
391
+ ): EventTransformer<AcpRawEvent> {
392
+ return new AcpTransformer(ctx, reading);
302
393
  }
@@ -1,3 +1,4 @@
1
+ import { basename } from "node:path";
1
2
  import { Readable, Writable } from "node:stream";
2
3
  import type {
3
4
  AgentNotificationMethod,
@@ -5,20 +6,19 @@ import type {
5
6
  AgentRequestMethod,
6
7
  AgentRequestParamsByMethod,
7
8
  AgentRequestResponsesByMethod,
9
+ AnyMessage,
8
10
  ClientConnection,
9
11
  CreateElicitationRequest,
10
12
  CreateElicitationResponse,
11
13
  RequestPermissionRequest,
12
14
  RequestPermissionResponse,
13
15
  SessionNotification,
16
+ Stream,
14
17
  } from "@agentclientprotocol/sdk";
15
- import type {
16
- NativeExit,
17
- NativeProcess,
18
- NativeProcesses,
19
- } from "../../processes/native-processes.ts";
18
+ import type { AgentHarness } from "../../../protocol/index.ts";
19
+ import type { NativeProcess, NativeProcesses } from "../../processes/native-processes.ts";
20
20
  import { withTimeout } from "../../utils/deadline.ts";
21
- import { AgentExitedError } from "../../utils/errors.ts";
21
+ import { isRecord } from "../../utils/is-record.ts";
22
22
 
23
23
  /**
24
24
  * How to start one ACP agent subprocess. Operator-level only — the wire never
@@ -30,18 +30,165 @@ export interface AcpLaunch {
30
30
  args?: string[];
31
31
  /** Extra env layered onto the subprocess (over process.env). */
32
32
  env?: Record<string, string>;
33
+ /**
34
+ * Env set over every other, the turn's included, which comes from the
35
+ * wire: what the engine keeps for its own reasons (a pinned CLI's
36
+ * self-update off), for a turn, a read with no turn and a sign-in alike.
37
+ */
38
+ fixedEnv?: Record<string, string>;
33
39
  }
34
40
 
35
- /** How much of the agent's stderr tail an exit error carries: its last lines say why. */
36
- const REASON_LINES = 2;
37
- const REASON_MAX = 400;
38
41
  /** How long an agent gets to stop on SIGTERM before it is killed. */
39
42
  const KILL_GRACE_MS = 3_000;
40
- /** How long a closed connection waits for the process's own exit, which says why. */
41
- const EXIT_REASON_WAIT_MS = 500;
42
43
 
43
44
  type SessionUpdateHandler = (notification: SessionNotification) => void;
44
45
 
46
+ // @ref LLP 0016.000#an-acp-agent-steered-by-prompt — the agent asks until it has acted on our answer
47
+ /**
48
+ * What the agent is asking on one connection, read from the messages
49
+ * themselves, for an agent steered by prompt, which refuses a prompt while it
50
+ * asks. A request (a `method` and an `id`) is open from its arrival, through
51
+ * our answer to it (that `id`, no `method`) being handed to the writer, until
52
+ * the agent shows it acted on that answer: its next `session/update` for the
53
+ * same session about the tool call the request names
54
+ * (`params.toolCall.toolCallId`, a permission's; `params.toolCallId`,
55
+ * Antigravity's question). An agent may apply an answer after it was written
56
+ * (Antigravity does), and nothing else says it has. A request that names no
57
+ * tool call cannot be seen acted on: it stays open until nothing is asked any
58
+ * more (`askNothing`). A prompt goes down the same writable as the answers,
59
+ * so one sent once `idle()` settles reaches an agent that has acted on every
60
+ * answer it waited for.
61
+ */
62
+ export class AgentRequests {
63
+ /** Each open request, by its id: what it is about, and whether our answer is given. */
64
+ private readonly open = new Map<
65
+ string | number,
66
+ { sessionId?: unknown; toolCallId?: string; answered: boolean }
67
+ >();
68
+ private arrivals = 0;
69
+ private waiters: Array<() => void> = [];
70
+
71
+ /** The connection's messages, counted as they pass: what `AcpClient` hands the SDK. */
72
+ watch(stream: Stream): Stream {
73
+ const out = stream.writable.getWriter();
74
+ return {
75
+ readable: stream.readable.pipeThrough(
76
+ new TransformStream<AnyMessage, AnyMessage>({
77
+ transform: (message, controller) => {
78
+ this.received(message);
79
+ controller.enqueue(message);
80
+ },
81
+ }),
82
+ ),
83
+ writable: new WritableStream<AnyMessage>({
84
+ // Given once handed over: the agent may read it, and act, before the write settles.
85
+ write: (message) => {
86
+ this.written(message);
87
+ return out.write(message);
88
+ },
89
+ close: () => out.close(),
90
+ abort: (reason) => out.abort(reason),
91
+ }),
92
+ };
93
+ }
94
+
95
+ /**
96
+ * A message from the agent: an update acts on the answers given before it
97
+ * that wait for it, and a request opens what it asks.
98
+ */
99
+ received(message: AnyMessage | readonly AnyMessage[]): void {
100
+ for (const one of batch(message)) {
101
+ const about = updateOf(one);
102
+ if (about)
103
+ for (const [id, request] of this.open)
104
+ if (
105
+ request.answered &&
106
+ request.toolCallId === about.toolCallId &&
107
+ request.sessionId === about.sessionId
108
+ )
109
+ this.open.delete(id);
110
+ if ("method" in one && "id" in one && one.id !== null) {
111
+ const params = isRecord(one.params) ? one.params : {};
112
+ const toolCallId = toolCallOf(params);
113
+ this.open.set(one.id, {
114
+ sessionId: params.sessionId,
115
+ ...(toolCallId !== undefined && { toolCallId }),
116
+ answered: false,
117
+ });
118
+ this.arrivals++;
119
+ }
120
+ }
121
+ if (this.open.size === 0) this.wake();
122
+ }
123
+
124
+ /** A message on its way to the agent: an answer is given, and the agent is yet to act on it. */
125
+ written(message: AnyMessage | readonly AnyMessage[]): void {
126
+ for (const one of batch(message)) {
127
+ if ("method" in one || !("id" in one) || one.id === null) continue;
128
+ const request = this.open.get(one.id);
129
+ if (request) request.answered = true;
130
+ }
131
+ }
132
+
133
+ /** Whether the agent is waiting for an answer. */
134
+ get pending(): boolean {
135
+ return this.open.size > 0;
136
+ }
137
+
138
+ /**
139
+ * How many requests have arrived so far: a mark a later request passes
140
+ * (`arrivedSince`).
141
+ */
142
+ get arrived(): number {
143
+ return this.arrivals;
144
+ }
145
+
146
+ /** Whether a request arrived after `mark` (`arrived`, read earlier). */
147
+ arrivedSince(mark: number): boolean {
148
+ return this.arrivals > mark;
149
+ }
150
+
151
+ /** Settles once the agent asks nothing, or nothing is asked any more (`askNothing`). */
152
+ idle(): Promise<void> {
153
+ if (!this.pending) return Promise.resolve();
154
+ return new Promise((resolve) => {
155
+ this.waiters.push(resolve);
156
+ });
157
+ }
158
+
159
+ /**
160
+ * Nothing is asked any more: the connection is gone, or the turn that
161
+ * asked has ended, so a request the agent never acted on is forgotten.
162
+ */
163
+ askNothing(): void {
164
+ this.open.clear();
165
+ this.wake();
166
+ }
167
+
168
+ private wake(): void {
169
+ for (const wake of this.waiters.splice(0)) wake();
170
+ }
171
+ }
172
+
173
+ /** The tool call a request names: a permission's `toolCall.toolCallId`, else its own `toolCallId`. */
174
+ function toolCallOf(params: Record<string, unknown>): string | undefined {
175
+ const id = isRecord(params.toolCall) ? params.toolCall.toolCallId : params.toolCallId;
176
+ return typeof id === "string" ? id : undefined;
177
+ }
178
+
179
+ /** The session and tool call a `session/update` is about, when it is about one. */
180
+ function updateOf(message: AnyMessage): { sessionId: unknown; toolCallId: string } | undefined {
181
+ if (!("method" in message) || message.method !== "session/update") return undefined;
182
+ const params = isRecord(message.params) ? message.params : {};
183
+ const toolCallId = isRecord(params.update) ? params.update.toolCallId : undefined;
184
+ return typeof toolCallId === "string" ? { sessionId: params.sessionId, toolCallId } : undefined;
185
+ }
186
+
187
+ /** The messages of one JSON-RPC message or batch. */
188
+ function batch(message: AnyMessage | readonly AnyMessage[]): readonly AnyMessage[] {
189
+ return Array.isArray(message) ? message : [message as AnyMessage];
190
+ }
191
+
45
192
  /** Answers agent→client `session/request_permission`. Absent handler → cancelled. */
46
193
  type AcpPermissionHandler = (
47
194
  request: RequestPermissionRequest,
@@ -63,8 +210,15 @@ export interface AcpClientOptions {
63
210
  * recorded for `sessionId` (`createAgentRegistry` passes the runtime's).
64
211
  */
65
212
  processes: NativeProcesses;
213
+ /** The harness it runs under, which its record names. */
214
+ harness: AgentHarness;
66
215
  /** The logical session it serves, which its record names. */
67
216
  sessionId?: string;
217
+ /**
218
+ * Count what the agent asks on the connection (`asking`), for an agent
219
+ * steered by prompt; otherwise the SDK gets the stream as it is.
220
+ */
221
+ watchRequests?: boolean;
68
222
  }
69
223
 
70
224
  /**
@@ -83,14 +237,19 @@ export class AcpClient {
83
237
  private readonly closeHandlers = new Set<(error?: Error) => void>();
84
238
  private permissionHandler?: AcpPermissionHandler;
85
239
  private elicitationHandler?: AcpElicitationHandler;
240
+ /** What the agent is asking, until it acted on each answer: present when `watchRequests` says so. */
241
+ readonly asking?: AgentRequests;
86
242
  private exited = false;
87
243
  /** The stop of its process, once one began: what `gone` waits for. */
88
244
  private leaving?: Promise<void>;
89
245
  /** Why the agent stopped, once it has: its exit code and stderr tail. */
90
246
  private exitError?: Error;
91
- private connectionEnded = false;
247
+ private readonly pending = new Set<{ method: AgentRequestMethod }>();
248
+ private connectionEnd?: Promise<void>;
92
249
 
93
- private constructor(private readonly opts: AcpClientOptions) {}
250
+ private constructor(private readonly opts: AcpClientOptions) {
251
+ if (opts.watchRequests) this.asking = new AgentRequests();
252
+ }
94
253
 
95
254
  /** Spawn the agent and connect. Fails if `@agentclientprotocol/sdk` is absent. */
96
255
  static async create(opts: AcpClientOptions): Promise<AcpClient> {
@@ -121,7 +280,7 @@ export class AcpClient {
121
280
  }
122
281
 
123
282
  get closed(): boolean {
124
- return this.exited || this.connectionEnded;
283
+ return this.exited || this.connectionEnd !== undefined;
125
284
  }
126
285
 
127
286
  /**
@@ -137,24 +296,21 @@ export class AcpClient {
137
296
  params: AgentRequestParamsByMethod[M],
138
297
  timeoutMs?: number,
139
298
  ): Promise<AgentRequestResponsesByMethod[M]> {
299
+ if (this.connectionEnd) await this.connectionEnd;
140
300
  if (!this.connection || this.exited) throw this.exitError ?? new Error("acp agent not running");
301
+ const request = { method };
302
+ this.pending.add(request);
141
303
  try {
142
304
  return await this.send(method, params, timeoutMs);
143
305
  } catch (error) {
144
- // Cut short by the agent's exit: say why it exited, not just that the
145
- // connection closed. (The SDK marks the connection closed before it
146
- // fails the requests it held.)
147
- if (this.exited || this.connectionEnded) throw (await this.whyExited()) ?? error;
148
- throw error;
306
+ // The SDK closes the connection before it rejects its pending requests.
307
+ if (this.connectionEnd) await this.connectionEnd;
308
+ throw this.exitError ?? error;
309
+ } finally {
310
+ this.pending.delete(request);
149
311
  }
150
312
  }
151
313
 
152
- /** Why the agent exited, waiting briefly for its exit when the connection went first. */
153
- private async whyExited(): Promise<Error | undefined> {
154
- if (!this.exitError && this.native) await withTimeout(this.native.exited, EXIT_REASON_WAIT_MS);
155
- return this.exitError;
156
- }
157
-
158
314
  private async send<M extends AgentRequestMethod>(
159
315
  method: M,
160
316
  params: AgentRequestParamsByMethod[M],
@@ -219,8 +375,8 @@ export class AcpClient {
219
375
  command: launch.command,
220
376
  args: launch.args ?? [],
221
377
  cwd: this.opts.cwd,
222
- env: { ...process.env, ...launch.env, ...this.opts.env },
223
- harness: "acp",
378
+ env: { ...process.env, ...launch.env, ...this.opts.env, ...launch.fixedEnv },
379
+ harness: this.opts.harness,
224
380
  ...(this.opts.sessionId !== undefined && { sessionId: this.opts.sessionId }),
225
381
  });
226
382
  this.native = native;
@@ -230,9 +386,12 @@ export class AcpClient {
230
386
  throw new Error("acp agent subprocess has no stdio");
231
387
  }
232
388
  proc.on("error", (err) => this.onExit(err));
233
- // Once its output closed, or a moment after its exit when a child it left
234
- // running holds the pipes: its stderr's last lines usually say why.
235
- void native.exited.then((exit) => this.onExit(exitedWith(exit, native.stderrTail)));
389
+ void native.exited.then((exit) => {
390
+ if (this.exited) return;
391
+ const name = this.opts.harness === "acp" ? basename(launch.command) : this.opts.harness;
392
+ const pending = Array.from(this.pending, (request) => request.method);
393
+ this.onExit(native.exitError(`ACP agent (${name})`, exit, pending));
394
+ });
236
395
 
237
396
  const stream = acp.ndJsonStream(
238
397
  Writable.toWeb(proc.stdin),
@@ -255,13 +414,14 @@ export class AcpClient {
255
414
  .onNotification("session/update", (ctx) => {
256
415
  for (const handler of this.updateHandlers) handler(ctx.params);
257
416
  })
258
- .connect(stream);
417
+ .connect(this.asking ? this.asking.watch(stream) : stream);
259
418
  // A closed connection without a process exit (stream error) still ends the
260
419
  // client; a rejected `closed` must not become an unhandled rejection. The
261
420
  // process's own exit usually follows at once and says why: let it.
262
- const ended = async (error: Error) => {
263
- this.connectionEnded = true;
264
- if (!(await withTimeout(native.exited, EXIT_REASON_WAIT_MS))) this.onExit(error);
421
+ const ended = (error: Error) => {
422
+ this.connectionEnd = native.exitAfterDisconnect().then((exit) => {
423
+ if (!exit) this.onExit(error);
424
+ });
265
425
  };
266
426
  this.connection.closed.then(
267
427
  () => ended(new Error("acp connection closed")),
@@ -271,8 +431,8 @@ export class AcpClient {
271
431
  }
272
432
 
273
433
  private onExit(error: Error): void {
274
- this.exitError ??= error;
275
434
  if (this.exited) return;
435
+ this.exitError = error;
276
436
  this.exited = true;
277
437
  // The connection can end while the process lives on: stop it.
278
438
  if (this.native) this.stop(this.native);
@@ -282,21 +442,8 @@ export class AcpClient {
282
442
  }
283
443
 
284
444
  private notifyClosed(error?: Error): void {
445
+ this.asking?.askNothing();
285
446
  for (const handler of this.closeHandlers) handler(error);
286
447
  this.closeHandlers.clear();
287
448
  }
288
449
  }
289
-
290
- /** Why the agent exited: its code, and the last lines of its stderr. */
291
- function exitedWith({ code, signal }: NativeExit, stderr: string): AgentExitedError {
292
- const reason = stderr
293
- .split("\n")
294
- .map((line) => line.trim())
295
- .filter(Boolean)
296
- .slice(-REASON_LINES)
297
- .join(" | ")
298
- .slice(-REASON_MAX);
299
- return new AgentExitedError(
300
- `acp agent exited (code=${code} signal=${signal})${reason ? `: ${reason}` : ""}`,
301
- );
302
- }