@zvada/agent-server 0.3.26 → 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 (262) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +7 -5
  3. package/dist/client/client.js +27 -11
  4. package/dist/client/connection.js +35 -3
  5. package/dist/core/agents/acp/account.js +111 -0
  6. package/dist/core/agents/acp/acp-agent.js +247 -158
  7. package/dist/core/agents/acp/adapter.js +103 -34
  8. package/dist/core/agents/acp/client.js +169 -42
  9. package/dist/core/agents/acp/known-agents.js +12 -5
  10. package/dist/core/agents/acp/mappings.js +84 -20
  11. package/dist/core/agents/acp/models.js +59 -0
  12. package/dist/core/agents/acp/profile.js +36 -0
  13. package/dist/core/agents/acp/prompts.js +248 -0
  14. package/dist/core/agents/acp/requests.js +4 -4
  15. package/dist/core/agents/claude-code/approvals.js +1 -1
  16. package/dist/core/agents/claude-code/login.js +4 -1
  17. package/dist/core/agents/claude-code/session.js +38 -10
  18. package/dist/core/agents/claude-code/spawn.js +0 -26
  19. package/dist/core/agents/codex-app-server/client.js +12 -13
  20. package/dist/core/agents/codex-app-server/login.js +4 -1
  21. package/dist/core/agents/codex-app-server/plan-approval.js +1 -1
  22. package/dist/core/agents/gemini/failures.js +133 -0
  23. package/dist/core/agents/gemini/login.js +173 -0
  24. package/dist/core/agents/gemini/profile.js +137 -0
  25. package/dist/core/agents/gemini/tools.js +91 -0
  26. package/dist/core/agents/login.js +8 -6
  27. package/dist/core/agents/scripted/scripted-agent.js +30 -3
  28. package/dist/core/agents/stderr-tail.js +5 -2
  29. package/dist/core/presets.js +17 -1
  30. package/dist/core/processes/native-processes.js +23 -1
  31. package/dist/core/provision/install-build.js +70 -26
  32. package/dist/core/provision/pins.js +5 -0
  33. package/dist/core/provision/provisioner.js +39 -16
  34. package/dist/core/provision/releases.js +39 -1
  35. package/dist/core/provision/tools.js +87 -28
  36. package/dist/core/runtime/agent-runtime.js +15 -5
  37. package/dist/core/runtime/event-processor.js +13 -8
  38. package/dist/core/runtime/origin-line.js +42 -0
  39. package/dist/core/runtime/request-broker.js +2 -1
  40. package/dist/core/runtime/steering.js +4 -3
  41. package/dist/core/runtime/turn.js +6 -4
  42. package/dist/operator/errors.js +97 -0
  43. package/dist/operator/index.js +10 -5
  44. package/dist/operator/mcp.js +7 -12
  45. package/dist/operator/operator.js +1431 -378
  46. package/dist/operator/refs.js +59 -0
  47. package/dist/operator/render.js +199 -94
  48. package/dist/operator/session-tools.js +88 -0
  49. package/dist/operator/types.js +30 -0
  50. package/dist/operator/view.js +82 -27
  51. package/dist/protocol/account.js +5 -1
  52. package/dist/protocol/auth.js +5 -1
  53. package/dist/protocol/config.js +12 -5
  54. package/dist/protocol/conversation.js +3 -0
  55. package/dist/protocol/credentials.js +9 -1
  56. package/dist/protocol/harness.js +9 -1
  57. package/dist/protocol/history.js +2 -1
  58. package/dist/protocol/index.js +1 -0
  59. package/dist/protocol/lifecycle.js +19 -0
  60. package/dist/protocol/origin.js +39 -0
  61. package/dist/protocol/reduce.js +2 -0
  62. package/dist/protocol/wire.js +17 -0
  63. package/dist/server/bin.js +22 -7
  64. package/dist/server/install.js +6 -4
  65. package/dist/server/routes.js +15 -5
  66. package/dist/types/client/client.d.ts.map +1 -1
  67. package/dist/types/client/connection.d.ts +14 -2
  68. package/dist/types/client/connection.d.ts.map +1 -1
  69. package/dist/types/client/turns.d.ts +2 -2
  70. package/dist/types/client/turns.d.ts.map +1 -1
  71. package/dist/types/core/agents/acp/account.d.ts +55 -0
  72. package/dist/types/core/agents/acp/account.d.ts.map +1 -0
  73. package/dist/types/core/agents/acp/acp-agent.d.ts +65 -36
  74. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  75. package/dist/types/core/agents/acp/adapter.d.ts +28 -3
  76. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  77. package/dist/types/core/agents/acp/client.d.ts +66 -4
  78. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  79. package/dist/types/core/agents/acp/known-agents.d.ts +4 -2
  80. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -1
  81. package/dist/types/core/agents/acp/mappings.d.ts +53 -7
  82. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  83. package/dist/types/core/agents/acp/models.d.ts +22 -0
  84. package/dist/types/core/agents/acp/models.d.ts.map +1 -0
  85. package/dist/types/core/agents/acp/profile.d.ts +92 -0
  86. package/dist/types/core/agents/acp/profile.d.ts.map +1 -0
  87. package/dist/types/core/agents/acp/prompts.d.ts +108 -0
  88. package/dist/types/core/agents/acp/prompts.d.ts.map +1 -0
  89. package/dist/types/core/agents/acp/requests.d.ts +7 -1
  90. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  91. package/dist/types/core/agents/base.d.ts +2 -0
  92. package/dist/types/core/agents/base.d.ts.map +1 -1
  93. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  94. package/dist/types/core/agents/claude-code/session.d.ts +3 -0
  95. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  96. package/dist/types/core/agents/claude-code/spawn.d.ts +0 -8
  97. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -1
  98. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  99. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  100. package/dist/types/core/agents/gemini/failures.d.ts +25 -0
  101. package/dist/types/core/agents/gemini/failures.d.ts.map +1 -0
  102. package/dist/types/core/agents/gemini/login.d.ts +28 -0
  103. package/dist/types/core/agents/gemini/login.d.ts.map +1 -0
  104. package/dist/types/core/agents/gemini/profile.d.ts +30 -0
  105. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -0
  106. package/dist/types/core/agents/gemini/tools.d.ts +18 -0
  107. package/dist/types/core/agents/gemini/tools.d.ts.map +1 -0
  108. package/dist/types/core/agents/login.d.ts +15 -5
  109. package/dist/types/core/agents/login.d.ts.map +1 -1
  110. package/dist/types/core/agents/scripted/scripted-agent.d.ts +14 -1
  111. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  112. package/dist/types/core/agents/stderr-tail.d.ts +1 -1
  113. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -1
  114. package/dist/types/core/presets.d.ts +2 -2
  115. package/dist/types/core/presets.d.ts.map +1 -1
  116. package/dist/types/core/processes/native-processes.d.ts +6 -0
  117. package/dist/types/core/processes/native-processes.d.ts.map +1 -1
  118. package/dist/types/core/provision/checksums.d.ts +7 -1
  119. package/dist/types/core/provision/checksums.d.ts.map +1 -1
  120. package/dist/types/core/provision/install-build.d.ts +32 -6
  121. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  122. package/dist/types/core/provision/pins.d.ts +4 -0
  123. package/dist/types/core/provision/pins.d.ts.map +1 -1
  124. package/dist/types/core/provision/provisioner.d.ts +18 -7
  125. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  126. package/dist/types/core/provision/releases.d.ts +2 -1
  127. package/dist/types/core/provision/releases.d.ts.map +1 -1
  128. package/dist/types/core/provision/tools.d.ts +36 -7
  129. package/dist/types/core/provision/tools.d.ts.map +1 -1
  130. package/dist/types/core/runtime/agent-runtime.d.ts +4 -2
  131. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  132. package/dist/types/core/runtime/event-processor.d.ts +2 -2
  133. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  134. package/dist/types/core/runtime/origin-line.d.ts +15 -0
  135. package/dist/types/core/runtime/origin-line.d.ts.map +1 -0
  136. package/dist/types/core/runtime/request-broker.d.ts +1 -1
  137. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  138. package/dist/types/core/runtime/steering.d.ts +7 -4
  139. package/dist/types/core/runtime/steering.d.ts.map +1 -1
  140. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  141. package/dist/types/operator/errors.d.ts +87 -0
  142. package/dist/types/operator/errors.d.ts.map +1 -0
  143. package/dist/types/operator/index.d.ts +10 -5
  144. package/dist/types/operator/index.d.ts.map +1 -1
  145. package/dist/types/operator/mcp.d.ts +1 -1
  146. package/dist/types/operator/mcp.d.ts.map +1 -1
  147. package/dist/types/operator/operator.d.ts +15 -197
  148. package/dist/types/operator/operator.d.ts.map +1 -1
  149. package/dist/types/operator/refs.d.ts +25 -0
  150. package/dist/types/operator/refs.d.ts.map +1 -0
  151. package/dist/types/operator/render.d.ts +67 -22
  152. package/dist/types/operator/render.d.ts.map +1 -1
  153. package/dist/types/operator/session-tools.d.ts +61 -0
  154. package/dist/types/operator/session-tools.d.ts.map +1 -0
  155. package/dist/types/operator/types.d.ts +442 -0
  156. package/dist/types/operator/types.d.ts.map +1 -0
  157. package/dist/types/operator/view.d.ts +19 -29
  158. package/dist/types/operator/view.d.ts.map +1 -1
  159. package/dist/types/protocol/account.d.ts +4 -2
  160. package/dist/types/protocol/account.d.ts.map +1 -1
  161. package/dist/types/protocol/auth.d.ts +10 -7
  162. package/dist/types/protocol/auth.d.ts.map +1 -1
  163. package/dist/types/protocol/clis.d.ts +4 -3
  164. package/dist/types/protocol/clis.d.ts.map +1 -1
  165. package/dist/types/protocol/config.d.ts +22 -5
  166. package/dist/types/protocol/config.d.ts.map +1 -1
  167. package/dist/types/protocol/conversation.d.ts +47 -6
  168. package/dist/types/protocol/conversation.d.ts.map +1 -1
  169. package/dist/types/protocol/credentials.d.ts +8 -0
  170. package/dist/types/protocol/credentials.d.ts.map +1 -1
  171. package/dist/types/protocol/execution.d.ts +1 -1
  172. package/dist/types/protocol/harness.d.ts +5 -2
  173. package/dist/types/protocol/harness.d.ts.map +1 -1
  174. package/dist/types/protocol/history.d.ts +1 -1
  175. package/dist/types/protocol/history.d.ts.map +1 -1
  176. package/dist/types/protocol/index.d.ts +1 -0
  177. package/dist/types/protocol/index.d.ts.map +1 -1
  178. package/dist/types/protocol/lifecycle.d.ts +48 -10
  179. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  180. package/dist/types/protocol/models.d.ts +3 -0
  181. package/dist/types/protocol/models.d.ts.map +1 -1
  182. package/dist/types/protocol/origin.d.ts +49 -0
  183. package/dist/types/protocol/origin.d.ts.map +1 -0
  184. package/dist/types/protocol/reduce.d.ts.map +1 -1
  185. package/dist/types/protocol/wire-api.d.ts +78 -30
  186. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  187. package/dist/types/protocol/wire.d.ts +78 -12
  188. package/dist/types/protocol/wire.d.ts.map +1 -1
  189. package/dist/types/server/install.d.ts +2 -1
  190. package/dist/types/server/install.d.ts.map +1 -1
  191. package/dist/types/server/routes.d.ts.map +1 -1
  192. package/docs/consuming.md +62 -121
  193. package/docs/deploy.md +17 -8
  194. package/docs/harnesses.md +166 -44
  195. package/docs/sync-history.md +2 -1
  196. package/package.json +1 -1
  197. package/src/client/client.ts +36 -9
  198. package/src/client/connection.ts +31 -1
  199. package/src/client/turns.ts +2 -1
  200. package/src/core/agents/acp/account.ts +158 -0
  201. package/src/core/agents/acp/acp-agent.ts +288 -178
  202. package/src/core/agents/acp/adapter.ts +126 -35
  203. package/src/core/agents/acp/client.ts +196 -49
  204. package/src/core/agents/acp/known-agents.ts +14 -5
  205. package/src/core/agents/acp/mappings.ts +112 -21
  206. package/src/core/agents/acp/models.ts +72 -0
  207. package/src/core/agents/acp/profile.ts +127 -0
  208. package/src/core/agents/acp/prompts.ts +287 -0
  209. package/src/core/agents/acp/requests.ts +16 -9
  210. package/src/core/agents/base.ts +2 -0
  211. package/src/core/agents/claude-code/approvals.ts +2 -2
  212. package/src/core/agents/claude-code/login.ts +4 -1
  213. package/src/core/agents/claude-code/session.ts +38 -8
  214. package/src/core/agents/claude-code/spawn.ts +0 -26
  215. package/src/core/agents/codex-app-server/client.ts +11 -18
  216. package/src/core/agents/codex-app-server/login.ts +4 -5
  217. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  218. package/src/core/agents/gemini/failures.ts +148 -0
  219. package/src/core/agents/gemini/login.ts +188 -0
  220. package/src/core/agents/gemini/profile.ts +162 -0
  221. package/src/core/agents/gemini/tools.ts +99 -0
  222. package/src/core/agents/login.ts +14 -8
  223. package/src/core/agents/scripted/scripted-agent.ts +42 -3
  224. package/src/core/agents/stderr-tail.ts +5 -2
  225. package/src/core/presets.ts +19 -3
  226. package/src/core/processes/native-processes.ts +32 -1
  227. package/src/core/provision/checksums.ts +12 -2
  228. package/src/core/provision/install-build.ts +122 -55
  229. package/src/core/provision/pins.ts +5 -0
  230. package/src/core/provision/provisioner.ts +62 -27
  231. package/src/core/provision/releases.ts +47 -1
  232. package/src/core/provision/tools.ts +124 -31
  233. package/src/core/runtime/agent-runtime.ts +31 -7
  234. package/src/core/runtime/event-processor.ts +13 -6
  235. package/src/core/runtime/origin-line.ts +43 -0
  236. package/src/core/runtime/request-broker.ts +2 -0
  237. package/src/core/runtime/steering.ts +8 -4
  238. package/src/core/runtime/turn.ts +11 -4
  239. package/src/operator/errors.ts +221 -0
  240. package/src/operator/index.ts +18 -23
  241. package/src/operator/mcp.ts +7 -16
  242. package/src/operator/operator.ts +1684 -610
  243. package/src/operator/refs.ts +75 -0
  244. package/src/operator/render.ts +260 -118
  245. package/src/operator/session-tools.ts +127 -0
  246. package/src/operator/types.ts +506 -0
  247. package/src/operator/view.ts +93 -42
  248. package/src/protocol/account.ts +5 -2
  249. package/src/protocol/auth.ts +5 -1
  250. package/src/protocol/config.ts +14 -6
  251. package/src/protocol/conversation.ts +3 -0
  252. package/src/protocol/credentials.ts +11 -2
  253. package/src/protocol/harness.ts +9 -1
  254. package/src/protocol/history.ts +2 -1
  255. package/src/protocol/index.ts +1 -0
  256. package/src/protocol/lifecycle.ts +21 -0
  257. package/src/protocol/origin.ts +47 -0
  258. package/src/protocol/reduce.ts +4 -0
  259. package/src/protocol/wire.ts +18 -0
  260. package/src/server/bin.ts +20 -6
  261. package/src/server/install.ts +6 -3
  262. package/src/server/routes.ts +16 -5
@@ -1,6 +1,6 @@
1
1
  import { DEFAULT_TOKEN_USAGE, STOP_REASONS, completeToolPart, createReasoningPart, createTextPart, createToolPart, setToolMeta, startToolPart, } from "../../../protocol/index.js";
2
2
  import { isRecord } from "../../utils/is-record.js";
3
- import { permissionModeOf, toToolLocations, toToolResultContent, toolKindOf } from "./mappings.js";
3
+ import { modeNames, toToolLocations, toToolResultContent, toolKindOf } from "./mappings.js";
4
4
  /** How a turn the agent did not get to answer ends: cancelled. */
5
5
  export const CANCELLED_PROMPT_RESULT = {
6
6
  method: "session/prompt_result",
@@ -25,30 +25,47 @@ function tokenUsageOf(usage) {
25
25
  cache: { read: usage.cachedReadTokens ?? 0, write: usage.cachedWriteTokens ?? 0 },
26
26
  };
27
27
  }
28
- /** Flatten a tool call's content blocks (plus rawOutput) into one output string. */
28
+ /**
29
+ * Flatten a tool call's content blocks (plus rawOutput) into one output
30
+ * string. An empty record says nothing: no output, not `{}`.
31
+ */
29
32
  function toolOutput(content, rawOutput) {
30
33
  const texts = (content ?? [])
31
34
  .map((item) => item.type === "content" && item.content.type === "text" ? item.content.text : "")
32
35
  .filter(Boolean);
33
36
  if (texts.length)
34
37
  return texts.join("\n");
35
- return rawOutput !== undefined && rawOutput !== null ? JSON.stringify(rawOutput) : "";
38
+ if (rawOutput === undefined || rawOutput === null)
39
+ return "";
40
+ if (isRecord(rawOutput) && Object.keys(rawOutput).length === 0)
41
+ return "";
42
+ return JSON.stringify(rawOutput);
36
43
  }
37
44
  class AcpTransformer {
45
+ reading;
38
46
  ctx;
39
47
  toolParts = new Map();
48
+ /** Each tool call as its updates assembled it: an update carries only what changed. */
49
+ toolCalls = new Map();
40
50
  /** A tool's latest display content: ACP replaces it with each update that carries some. */
41
51
  toolContent = new Map();
42
- streamParts = new Map();
52
+ /** The text or reasoning part chunks of its kind append to, until something else comes. */
53
+ streaming;
43
54
  /** messageId of the currently open wire message (undefined = implicit single message). */
44
55
  currentMessageId;
45
56
  messageOpen = false;
57
+ /** The session's MCP servers, by name: what the tool rules tell a call's server from its tool by. */
58
+ servers = [];
46
59
  usage = { ...DEFAULT_TOKEN_USAGE };
47
60
  stopReason;
48
61
  finishReason;
49
62
  error;
50
- constructor(ctx) {
63
+ errorCategory;
64
+ modes;
65
+ constructor(ctx, reading = {}) {
66
+ this.reading = reading;
51
67
  this.ctx = { sessionId: ctx.sessionId, messageId: "" };
68
+ this.modes = modeNames(reading.modeIds);
52
69
  }
53
70
  process(event) {
54
71
  switch (event.method) {
@@ -58,12 +75,21 @@ class AcpTransformer {
58
75
  this.usage = tokenUsageOf(event.params.usage);
59
76
  this.stopReason = stopReasonOf(event.params.stopReason);
60
77
  this.finishReason = event.params.stopReason;
61
- return this.finalizeStreamingParts();
78
+ return this.finishStreaming();
62
79
  case "error":
63
80
  this.error = event.params.message ?? "acp agent error";
64
81
  this.finishReason = "error";
82
+ if (event.params.category)
83
+ this.errorCategory = event.params.category;
84
+ if (event.params.usage)
85
+ this.usage = tokenUsageOf(event.params.usage);
65
86
  // A failed prompt still closes any parts left streaming.
66
- return this.finalizeStreamingParts();
87
+ return this.finishStreaming();
88
+ case "agentServer/mcpServers":
89
+ this.servers = event.params.names;
90
+ return [];
91
+ case "agentServer/steerRead":
92
+ return this.steerRead(event.params.steerId);
67
93
  default:
68
94
  return [];
69
95
  }
@@ -76,6 +102,7 @@ class AcpTransformer {
76
102
  stopReason: this.stopReason,
77
103
  finishReason: this.finishReason,
78
104
  error: this.error,
105
+ ...(this.errorCategory && { errorCategory: this.errorCategory }),
79
106
  };
80
107
  }
81
108
  onUpdate(update) {
@@ -103,8 +130,8 @@ class AcpTransformer {
103
130
  }
104
131
  case "current_mode_update": {
105
132
  // 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);
133
+ // Claude's own, a profile's by its ids); another agent's mode stays raw.
134
+ const permissionMode = this.modes.modeOf(update.currentModeId);
108
135
  return permissionMode ? [{ kind: "mode", permissionMode }] : [];
109
136
  }
110
137
  default:
@@ -117,13 +144,14 @@ class AcpTransformer {
117
144
  if (content.type !== "text" || !content.text)
118
145
  return [];
119
146
  const events = [...this.rolloverMessage(messageId ?? undefined)];
120
- let part = this.streamParts.get(slot);
121
- if (!part) {
147
+ let part = this.streaming;
148
+ if (part?.type !== slot) {
149
+ events.push(...this.finishStreaming());
122
150
  part =
123
151
  slot === "text"
124
152
  ? createTextPart(this.ctx, "", true)
125
153
  : createReasoningPart(this.ctx, "", true);
126
- this.streamParts.set(slot, part);
154
+ this.streaming = part;
127
155
  // The processor snapshots at emit time, after the append below. Open
128
156
  // with a copy so this chunk arrives once, as the delta.
129
157
  events.push({ kind: "part-open", part: structuredClone(part) });
@@ -137,23 +165,61 @@ class AcpTransformer {
137
165
  toolCall(update) {
138
166
  if (this.toolParts.has(update.toolCallId))
139
167
  return this.toolCallUpdate(update); // duplicate open
168
+ const events = this.finishStreaming();
140
169
  const part = this.openTool(update);
141
- const events = [{ kind: "part-open", part }];
170
+ events.push({ kind: "part-open", part });
142
171
  if (this.applyToolUpdate(part, update))
143
172
  events.push({ kind: "part-update", part });
144
173
  return events;
145
174
  }
146
175
  toolCallUpdate(update) {
176
+ const known = this.toolParts.get(update.toolCallId);
147
177
  // 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);
178
+ const events = known ? [] : this.finishStreaming();
179
+ const part = known ?? this.openTool(update);
149
180
  this.applyToolUpdate(part, update);
150
- return [{ kind: "part-update", part }];
181
+ events.push({ kind: "part-update", part });
182
+ return events;
183
+ }
184
+ /**
185
+ * The agent took a steer: what streamed before it is done, and its message
186
+ * ends; the agent's next output opens a message after the steer's echo.
187
+ */
188
+ steerRead(steerId) {
189
+ // What came before the steer stays before it.
190
+ const events = this.finishStreaming();
191
+ if (this.messageOpen)
192
+ events.push({ kind: "message-end" });
193
+ this.messageOpen = false;
194
+ this.currentMessageId = undefined;
195
+ events.push({ kind: "steer-inserted", steerId });
196
+ return events;
197
+ }
198
+ /**
199
+ * The call an update makes of its tool call, its fields over those before
200
+ * them: what the tool rules read, since an ACP agent names its tools by no
201
+ * rule of its own.
202
+ */
203
+ assemble(update) {
204
+ const before = this.toolCalls.get(update.toolCallId) ?? {};
205
+ const call = {
206
+ ...before,
207
+ ...(update.name != null && { name: update.name }),
208
+ ...(update.rawInput !== undefined && { rawInput: update.rawInput }),
209
+ ...(update.rawOutput !== undefined && { rawOutput: update.rawOutput }),
210
+ };
211
+ this.toolCalls.set(update.toolCallId, call);
212
+ return call;
213
+ }
214
+ /** What the tool rules read of a call, as its updates assembled it. */
215
+ described(call) {
216
+ return this.reading.tools?.describe(call, this.servers) ?? {};
151
217
  }
152
218
  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
- {
219
+ const call = this.assemble(update);
220
+ const part = createToolPart(this.ctx, update.toolCallId, update.name ?? update.title ?? "tool", isRecord(update.rawInput) ? update.rawInput : {}, {
156
221
  kind: toolKindOf(update.kind),
222
+ ...this.described(call),
157
223
  title: update.title ?? undefined,
158
224
  locations: toToolLocations(update.locations),
159
225
  });
@@ -166,8 +232,10 @@ class AcpTransformer {
166
232
  }
167
233
  /** Fold an update's meta/input/status into the part; true when it just completed. */
168
234
  applyToolUpdate(part, update) {
235
+ const call = this.assemble(update);
169
236
  setToolMeta(part, {
170
237
  kind: toolKindOf(update.kind),
238
+ ...this.described(call),
171
239
  title: update.title ?? undefined,
172
240
  locations: toToolLocations(update.locations),
173
241
  });
@@ -184,10 +252,13 @@ class AcpTransformer {
184
252
  this.toolContent.set(update.toolCallId, toToolResultContent(update.content));
185
253
  if (update.status !== "completed" && update.status !== "failed")
186
254
  return false;
255
+ const read = this.reading.tools?.output?.(call);
256
+ // @ref LLP 0002#tool-output-has-three-audiences — a command's exit code is metadata; non-zero fails it
187
257
  completeToolPart(part, {
188
- output: toolOutput(update.content, update.rawOutput),
189
- isError: update.status === "failed",
258
+ output: read?.text ?? toolOutput(update.content, update.rawOutput),
259
+ isError: update.status === "failed" || (read?.exitCode ?? 0) !== 0 || read?.failed === true,
190
260
  content: this.toolContent.get(update.toolCallId),
261
+ ...(read?.exitCode !== undefined && { metadata: { exitCode: read.exitCode } }),
191
262
  });
192
263
  this.toolContent.delete(update.toolCallId);
193
264
  return true;
@@ -206,26 +277,24 @@ class AcpTransformer {
206
277
  return [];
207
278
  const events = [];
208
279
  if (this.messageOpen) {
209
- events.push(...this.finalizeStreamingParts(), { kind: "message-end" });
280
+ events.push(...this.finishStreaming(), { kind: "message-end" });
210
281
  }
211
282
  this.currentMessageId = messageId;
212
283
  this.messageOpen = true;
213
- this.streamParts.clear();
214
284
  events.push({ kind: "message-start", role: "assistant" });
215
285
  return events;
216
286
  }
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;
287
+ /** Mark the streaming text or reasoning part done: something else came, or the message or turn ended. */
288
+ finishStreaming() {
289
+ const part = this.streaming;
290
+ this.streaming = undefined;
291
+ if (!part)
292
+ return [];
293
+ part.state = "done";
294
+ return [{ kind: "part-update", part }];
227
295
  }
228
296
  }
229
- export function createAcpTransformer(ctx) {
230
- return new AcpTransformer(ctx);
297
+ /** An ACP turn's adapter; `reading` is what of its harness's profile it reads beyond ACP. */
298
+ export function createAcpTransformer(ctx, reading) {
299
+ return new AcpTransformer(ctx, reading);
231
300
  }
@@ -1,13 +1,141 @@
1
+ import { basename } from "node:path";
1
2
  import { Readable, Writable } from "node:stream";
2
3
  import { withTimeout } from "../../utils/deadline.js";
3
- import { AgentExitedError } from "../../utils/errors.js";
4
- /** How much of the agent's stderr tail an exit error carries: its last lines say why. */
5
- const REASON_LINES = 2;
6
- const REASON_MAX = 400;
4
+ import { isRecord } from "../../utils/is-record.js";
7
5
  /** How long an agent gets to stop on SIGTERM before it is killed. */
8
6
  const KILL_GRACE_MS = 3_000;
9
- /** How long a closed connection waits for the process's own exit, which says why. */
10
- const EXIT_REASON_WAIT_MS = 500;
7
+ // @ref LLP 0016.000#an-acp-agent-steered-by-prompt — the agent asks until it has acted on our answer
8
+ /**
9
+ * What the agent is asking on one connection, read from the messages
10
+ * themselves, for an agent steered by prompt, which refuses a prompt while it
11
+ * asks. A request (a `method` and an `id`) is open from its arrival, through
12
+ * our answer to it (that `id`, no `method`) being handed to the writer, until
13
+ * the agent shows it acted on that answer: its next `session/update` for the
14
+ * same session about the tool call the request names
15
+ * (`params.toolCall.toolCallId`, a permission's; `params.toolCallId`,
16
+ * Antigravity's question). An agent may apply an answer after it was written
17
+ * (Antigravity does), and nothing else says it has. A request that names no
18
+ * tool call cannot be seen acted on: it stays open until nothing is asked any
19
+ * more (`askNothing`). A prompt goes down the same writable as the answers,
20
+ * so one sent once `idle()` settles reaches an agent that has acted on every
21
+ * answer it waited for.
22
+ */
23
+ export class AgentRequests {
24
+ /** Each open request, by its id: what it is about, and whether our answer is given. */
25
+ open = new Map();
26
+ arrivals = 0;
27
+ waiters = [];
28
+ /** The connection's messages, counted as they pass: what `AcpClient` hands the SDK. */
29
+ watch(stream) {
30
+ const out = stream.writable.getWriter();
31
+ return {
32
+ readable: stream.readable.pipeThrough(new TransformStream({
33
+ transform: (message, controller) => {
34
+ this.received(message);
35
+ controller.enqueue(message);
36
+ },
37
+ })),
38
+ writable: new WritableStream({
39
+ // Given once handed over: the agent may read it, and act, before the write settles.
40
+ write: (message) => {
41
+ this.written(message);
42
+ return out.write(message);
43
+ },
44
+ close: () => out.close(),
45
+ abort: (reason) => out.abort(reason),
46
+ }),
47
+ };
48
+ }
49
+ /**
50
+ * A message from the agent: an update acts on the answers given before it
51
+ * that wait for it, and a request opens what it asks.
52
+ */
53
+ received(message) {
54
+ for (const one of batch(message)) {
55
+ const about = updateOf(one);
56
+ if (about)
57
+ for (const [id, request] of this.open)
58
+ if (request.answered &&
59
+ request.toolCallId === about.toolCallId &&
60
+ request.sessionId === about.sessionId)
61
+ this.open.delete(id);
62
+ if ("method" in one && "id" in one && one.id !== null) {
63
+ const params = isRecord(one.params) ? one.params : {};
64
+ const toolCallId = toolCallOf(params);
65
+ this.open.set(one.id, {
66
+ sessionId: params.sessionId,
67
+ ...(toolCallId !== undefined && { toolCallId }),
68
+ answered: false,
69
+ });
70
+ this.arrivals++;
71
+ }
72
+ }
73
+ if (this.open.size === 0)
74
+ this.wake();
75
+ }
76
+ /** A message on its way to the agent: an answer is given, and the agent is yet to act on it. */
77
+ written(message) {
78
+ for (const one of batch(message)) {
79
+ if ("method" in one || !("id" in one) || one.id === null)
80
+ continue;
81
+ const request = this.open.get(one.id);
82
+ if (request)
83
+ request.answered = true;
84
+ }
85
+ }
86
+ /** Whether the agent is waiting for an answer. */
87
+ get pending() {
88
+ return this.open.size > 0;
89
+ }
90
+ /**
91
+ * How many requests have arrived so far: a mark a later request passes
92
+ * (`arrivedSince`).
93
+ */
94
+ get arrived() {
95
+ return this.arrivals;
96
+ }
97
+ /** Whether a request arrived after `mark` (`arrived`, read earlier). */
98
+ arrivedSince(mark) {
99
+ return this.arrivals > mark;
100
+ }
101
+ /** Settles once the agent asks nothing, or nothing is asked any more (`askNothing`). */
102
+ idle() {
103
+ if (!this.pending)
104
+ return Promise.resolve();
105
+ return new Promise((resolve) => {
106
+ this.waiters.push(resolve);
107
+ });
108
+ }
109
+ /**
110
+ * Nothing is asked any more: the connection is gone, or the turn that
111
+ * asked has ended, so a request the agent never acted on is forgotten.
112
+ */
113
+ askNothing() {
114
+ this.open.clear();
115
+ this.wake();
116
+ }
117
+ wake() {
118
+ for (const wake of this.waiters.splice(0))
119
+ wake();
120
+ }
121
+ }
122
+ /** The tool call a request names: a permission's `toolCall.toolCallId`, else its own `toolCallId`. */
123
+ function toolCallOf(params) {
124
+ const id = isRecord(params.toolCall) ? params.toolCall.toolCallId : params.toolCallId;
125
+ return typeof id === "string" ? id : undefined;
126
+ }
127
+ /** The session and tool call a `session/update` is about, when it is about one. */
128
+ function updateOf(message) {
129
+ if (!("method" in message) || message.method !== "session/update")
130
+ return undefined;
131
+ const params = isRecord(message.params) ? message.params : {};
132
+ const toolCallId = isRecord(params.update) ? params.update.toolCallId : undefined;
133
+ return typeof toolCallId === "string" ? { sessionId: params.sessionId, toolCallId } : undefined;
134
+ }
135
+ /** The messages of one JSON-RPC message or batch. */
136
+ function batch(message) {
137
+ return Array.isArray(message) ? message : [message];
138
+ }
11
139
  /**
12
140
  * One ACP agent subprocess + its SDK connection. The engine talks to any
13
141
  * ACP v1 agent through this: JSON-RPC framing, routing, and schema types come
@@ -25,14 +153,19 @@ export class AcpClient {
25
153
  closeHandlers = new Set();
26
154
  permissionHandler;
27
155
  elicitationHandler;
156
+ /** What the agent is asking, until it acted on each answer: present when `watchRequests` says so. */
157
+ asking;
28
158
  exited = false;
29
159
  /** The stop of its process, once one began: what `gone` waits for. */
30
160
  leaving;
31
161
  /** Why the agent stopped, once it has: its exit code and stderr tail. */
32
162
  exitError;
33
- connectionEnded = false;
163
+ pending = new Set();
164
+ connectionEnd;
34
165
  constructor(opts) {
35
166
  this.opts = opts;
167
+ if (opts.watchRequests)
168
+ this.asking = new AgentRequests();
36
169
  }
37
170
  /** Spawn the agent and connect. Fails if `@agentclientprotocol/sdk` is absent. */
38
171
  static async create(opts) {
@@ -58,7 +191,7 @@ export class AcpClient {
58
191
  return () => this.closeHandlers.delete(handler);
59
192
  }
60
193
  get closed() {
61
- return this.exited || this.connectionEnded;
194
+ return this.exited || this.connectionEnd !== undefined;
62
195
  }
63
196
  /**
64
197
  * Send a request to the agent (`initialize`, `session/new`, `session/prompt`, …).
@@ -69,25 +202,24 @@ export class AcpClient {
69
202
  * pass no timeout.
70
203
  */
71
204
  async request(method, params, timeoutMs) {
205
+ if (this.connectionEnd)
206
+ await this.connectionEnd;
72
207
  if (!this.connection || this.exited)
73
208
  throw this.exitError ?? new Error("acp agent not running");
209
+ const request = { method };
210
+ this.pending.add(request);
74
211
  try {
75
212
  return await this.send(method, params, timeoutMs);
76
213
  }
77
214
  catch (error) {
78
- // Cut short by the agent's exit: say why it exited, not just that the
79
- // connection closed. (The SDK marks the connection closed before it
80
- // fails the requests it held.)
81
- if (this.exited || this.connectionEnded)
82
- throw (await this.whyExited()) ?? error;
83
- throw error;
215
+ // The SDK closes the connection before it rejects its pending requests.
216
+ if (this.connectionEnd)
217
+ await this.connectionEnd;
218
+ throw this.exitError ?? error;
219
+ }
220
+ finally {
221
+ this.pending.delete(request);
84
222
  }
85
- }
86
- /** Why the agent exited, waiting briefly for its exit when the connection went first. */
87
- async whyExited() {
88
- if (!this.exitError && this.native)
89
- await withTimeout(this.native.exited, EXIT_REASON_WAIT_MS);
90
- return this.exitError;
91
223
  }
92
224
  async send(method, params, timeoutMs) {
93
225
  if (!this.connection)
@@ -144,8 +276,8 @@ export class AcpClient {
144
276
  command: launch.command,
145
277
  args: launch.args ?? [],
146
278
  cwd: this.opts.cwd,
147
- env: { ...process.env, ...launch.env, ...this.opts.env },
148
- harness: "acp",
279
+ env: { ...process.env, ...launch.env, ...this.opts.env, ...launch.fixedEnv },
280
+ harness: this.opts.harness,
149
281
  ...(this.opts.sessionId !== undefined && { sessionId: this.opts.sessionId }),
150
282
  });
151
283
  this.native = native;
@@ -155,9 +287,13 @@ export class AcpClient {
155
287
  throw new Error("acp agent subprocess has no stdio");
156
288
  }
157
289
  proc.on("error", (err) => this.onExit(err));
158
- // Once its output closed, or a moment after its exit when a child it left
159
- // running holds the pipes: its stderr's last lines usually say why.
160
- void native.exited.then((exit) => this.onExit(exitedWith(exit, native.stderrTail)));
290
+ void native.exited.then((exit) => {
291
+ if (this.exited)
292
+ return;
293
+ const name = this.opts.harness === "acp" ? basename(launch.command) : this.opts.harness;
294
+ const pending = Array.from(this.pending, (request) => request.method);
295
+ this.onExit(native.exitError(`ACP agent (${name})`, exit, pending));
296
+ });
161
297
  const stream = acp.ndJsonStream(Writable.toWeb(proc.stdin),
162
298
  // Kept cast: some lib.dom versions type Readable.toWeb as
163
299
  // ReadableStream<any>.
@@ -180,21 +316,22 @@ export class AcpClient {
180
316
  for (const handler of this.updateHandlers)
181
317
  handler(ctx.params);
182
318
  })
183
- .connect(stream);
319
+ .connect(this.asking ? this.asking.watch(stream) : stream);
184
320
  // A closed connection without a process exit (stream error) still ends the
185
321
  // client; a rejected `closed` must not become an unhandled rejection. The
186
322
  // process's own exit usually follows at once and says why: let it.
187
- const ended = async (error) => {
188
- this.connectionEnded = true;
189
- if (!(await withTimeout(native.exited, EXIT_REASON_WAIT_MS)))
190
- this.onExit(error);
323
+ const ended = (error) => {
324
+ this.connectionEnd = native.exitAfterDisconnect().then((exit) => {
325
+ if (!exit)
326
+ this.onExit(error);
327
+ });
191
328
  };
192
329
  this.connection.closed.then(() => ended(new Error("acp connection closed")), (err) => ended(err instanceof Error ? err : new Error(`acp connection failed: ${err}`)));
193
330
  }
194
331
  onExit(error) {
195
- this.exitError ??= error;
196
332
  if (this.exited)
197
333
  return;
334
+ this.exitError = error;
198
335
  this.exited = true;
199
336
  // The connection can end while the process lives on: stop it.
200
337
  if (this.native)
@@ -204,19 +341,9 @@ export class AcpClient {
204
341
  this.notifyClosed(error);
205
342
  }
206
343
  notifyClosed(error) {
344
+ this.asking?.askNothing();
207
345
  for (const handler of this.closeHandlers)
208
346
  handler(error);
209
347
  this.closeHandlers.clear();
210
348
  }
211
349
  }
212
- /** Why the agent exited: its code, and the last lines of its stderr. */
213
- function exitedWith({ code, signal }, stderr) {
214
- const reason = stderr
215
- .split("\n")
216
- .map((line) => line.trim())
217
- .filter(Boolean)
218
- .slice(-REASON_LINES)
219
- .join(" | ")
220
- .slice(-REASON_MAX);
221
- return new AgentExitedError(`acp agent exited (code=${code} signal=${signal})${reason ? `: ${reason}` : ""}`);
222
- }
@@ -2,7 +2,7 @@ import { isAgentHarness } from "../../../protocol/index.js";
2
2
  /**
3
3
  * Advisory catalog of well-known ACP agents — UX sugar, not wire vocabulary
4
4
  * (like the model catalog). On the wire the harness is always `acp`; these names
5
- * let entry points offer "pi" or "gemini" as first-class choices and expand
5
+ * let entry points offer "pi" or "gemini-cli" as first-class choices and expand
6
6
  * them to launch commands at the operator edge. Anything not listed here runs
7
7
  * via an explicit launch command — any ACP-compatible agent works.
8
8
  */
@@ -13,8 +13,9 @@ export const KNOWN_ACP_AGENTS = {
13
13
  // Bump after checking the new release.
14
14
  launch: { command: "npx", args: ["-y", "pi-acp@0.0.34"] },
15
15
  },
16
- gemini: {
17
- label: "Gemini CLI (native ACP mode)",
16
+ // `gemini` is the harness (Google's Antigravity CLI): this is the other CLI.
17
+ "gemini-cli": {
18
+ label: "Gemini CLI (native ACP mode; the enterprise CLI, without Gemini 4)",
18
19
  launch: { command: "gemini", args: ["--acp"] },
19
20
  },
20
21
  };
@@ -48,10 +49,16 @@ export function resolveHarnessName(name) {
48
49
  /**
49
50
  * Resolve an operator spec that is either a known agent name (`"pi"`) or a
50
51
  * raw launch command (`"npx -y pi-acp"`). The canonical resolver behind
51
- * `--acp-agent` and `$AGENT_SERVER_ACP_AGENT`.
52
+ * `--acp-agent` and `$AGENT_SERVER_ACP_AGENT`. A harness's own name is no
53
+ * ACP agent and no command to launch: it is refused, naming the harness and
54
+ * the known agents, so an old setting (`gemini`) says what to write instead.
52
55
  */
53
56
  export function resolveAcpLaunch(spec) {
54
57
  if (!spec)
55
58
  return undefined;
56
- return knownAgent(spec.trim())?.launch ?? parseAcpLaunch(spec);
59
+ const name = spec.trim();
60
+ if (isAgentHarness(name)) {
61
+ throw new Error(`'${name}' is a harness, not an ACP agent: run it with --harness=${name}, or give an ACP agent's name (${Object.keys(KNOWN_ACP_AGENTS).join(", ")}) or launch command`);
62
+ }
63
+ return knownAgent(name)?.launch ?? parseAcpLaunch(spec);
57
64
  }