@zvada/agent-server 0.3.27 → 0.3.30

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 (190) hide show
  1. package/CHANGELOG.md +61 -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 +249 -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/claude-agent.js +2 -12
  14. package/dist/core/agents/claude-code/login.js +4 -1
  15. package/dist/core/agents/claude-code/session.js +50 -18
  16. package/dist/core/agents/claude-code/spawn.js +0 -26
  17. package/dist/core/agents/claude-code/turn.js +6 -2
  18. package/dist/core/agents/codex-app-server/client.js +12 -13
  19. package/dist/core/agents/codex-app-server/login.js +4 -1
  20. package/dist/core/agents/gemini/failures.js +133 -0
  21. package/dist/core/agents/gemini/login.js +173 -0
  22. package/dist/core/agents/gemini/profile.js +138 -0
  23. package/dist/core/agents/gemini/tools.js +91 -0
  24. package/dist/core/agents/login.js +8 -6
  25. package/dist/core/agents/stderr-tail.js +5 -2
  26. package/dist/core/presets.js +13 -0
  27. package/dist/core/processes/native-processes.js +23 -1
  28. package/dist/core/provision/install-build.js +70 -26
  29. package/dist/core/provision/pins.js +5 -0
  30. package/dist/core/provision/provisioner.js +39 -16
  31. package/dist/core/provision/releases.js +39 -1
  32. package/dist/core/provision/tools.js +87 -28
  33. package/dist/operator/errors.js +2 -2
  34. package/dist/operator/operator.js +201 -90
  35. package/dist/operator/render.js +34 -28
  36. package/dist/operator/session-tools.js +2 -1
  37. package/dist/protocol/account.js +5 -1
  38. package/dist/protocol/auth.js +5 -1
  39. package/dist/protocol/config.js +4 -2
  40. package/dist/protocol/credentials.js +9 -1
  41. package/dist/protocol/harness.js +9 -1
  42. package/dist/protocol/part-input.js +2 -6
  43. package/dist/protocol/text-parts.js +10 -0
  44. package/dist/server/bin.js +22 -7
  45. package/dist/server/install.js +6 -4
  46. package/dist/types/core/agents/acp/account.d.ts +55 -0
  47. package/dist/types/core/agents/acp/account.d.ts.map +1 -0
  48. package/dist/types/core/agents/acp/acp-agent.d.ts +65 -36
  49. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  50. package/dist/types/core/agents/acp/adapter.d.ts +28 -3
  51. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  52. package/dist/types/core/agents/acp/client.d.ts +66 -4
  53. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  54. package/dist/types/core/agents/acp/known-agents.d.ts +4 -2
  55. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -1
  56. package/dist/types/core/agents/acp/mappings.d.ts +53 -7
  57. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  58. package/dist/types/core/agents/acp/models.d.ts +22 -0
  59. package/dist/types/core/agents/acp/models.d.ts.map +1 -0
  60. package/dist/types/core/agents/acp/profile.d.ts +97 -0
  61. package/dist/types/core/agents/acp/profile.d.ts.map +1 -0
  62. package/dist/types/core/agents/acp/prompts.d.ts +108 -0
  63. package/dist/types/core/agents/acp/prompts.d.ts.map +1 -0
  64. package/dist/types/core/agents/acp/requests.d.ts +7 -1
  65. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  66. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -2
  67. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  68. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  69. package/dist/types/core/agents/claude-code/options.d.ts +1 -1
  70. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  71. package/dist/types/core/agents/claude-code/session.d.ts +7 -6
  72. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  73. package/dist/types/core/agents/claude-code/spawn.d.ts +0 -8
  74. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -1
  75. package/dist/types/core/agents/claude-code/turn.d.ts +3 -2
  76. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  77. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  78. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  79. package/dist/types/core/agents/gemini/failures.d.ts +25 -0
  80. package/dist/types/core/agents/gemini/failures.d.ts.map +1 -0
  81. package/dist/types/core/agents/gemini/login.d.ts +28 -0
  82. package/dist/types/core/agents/gemini/login.d.ts.map +1 -0
  83. package/dist/types/core/agents/gemini/profile.d.ts +30 -0
  84. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -0
  85. package/dist/types/core/agents/gemini/tools.d.ts +18 -0
  86. package/dist/types/core/agents/gemini/tools.d.ts.map +1 -0
  87. package/dist/types/core/agents/login.d.ts +15 -5
  88. package/dist/types/core/agents/login.d.ts.map +1 -1
  89. package/dist/types/core/agents/stderr-tail.d.ts +1 -1
  90. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -1
  91. package/dist/types/core/presets.d.ts +2 -2
  92. package/dist/types/core/presets.d.ts.map +1 -1
  93. package/dist/types/core/processes/native-processes.d.ts +6 -0
  94. package/dist/types/core/processes/native-processes.d.ts.map +1 -1
  95. package/dist/types/core/provision/checksums.d.ts +7 -1
  96. package/dist/types/core/provision/checksums.d.ts.map +1 -1
  97. package/dist/types/core/provision/install-build.d.ts +32 -6
  98. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  99. package/dist/types/core/provision/pins.d.ts +4 -0
  100. package/dist/types/core/provision/pins.d.ts.map +1 -1
  101. package/dist/types/core/provision/provisioner.d.ts +18 -7
  102. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  103. package/dist/types/core/provision/releases.d.ts +2 -1
  104. package/dist/types/core/provision/releases.d.ts.map +1 -1
  105. package/dist/types/core/provision/tools.d.ts +36 -7
  106. package/dist/types/core/provision/tools.d.ts.map +1 -1
  107. package/dist/types/operator/errors.d.ts +5 -1
  108. package/dist/types/operator/errors.d.ts.map +1 -1
  109. package/dist/types/operator/operator.d.ts.map +1 -1
  110. package/dist/types/operator/render.d.ts +11 -6
  111. package/dist/types/operator/render.d.ts.map +1 -1
  112. package/dist/types/operator/session-tools.d.ts.map +1 -1
  113. package/dist/types/operator/types.d.ts +5 -4
  114. package/dist/types/operator/types.d.ts.map +1 -1
  115. package/dist/types/protocol/account.d.ts +4 -2
  116. package/dist/types/protocol/account.d.ts.map +1 -1
  117. package/dist/types/protocol/auth.d.ts +10 -7
  118. package/dist/types/protocol/auth.d.ts.map +1 -1
  119. package/dist/types/protocol/clis.d.ts +4 -3
  120. package/dist/types/protocol/clis.d.ts.map +1 -1
  121. package/dist/types/protocol/config.d.ts +6 -2
  122. package/dist/types/protocol/config.d.ts.map +1 -1
  123. package/dist/types/protocol/conversation.d.ts +3 -3
  124. package/dist/types/protocol/credentials.d.ts +8 -0
  125. package/dist/types/protocol/credentials.d.ts.map +1 -1
  126. package/dist/types/protocol/execution.d.ts +1 -1
  127. package/dist/types/protocol/harness.d.ts +5 -2
  128. package/dist/types/protocol/harness.d.ts.map +1 -1
  129. package/dist/types/protocol/lifecycle.d.ts +8 -8
  130. package/dist/types/protocol/models.d.ts +3 -0
  131. package/dist/types/protocol/models.d.ts.map +1 -1
  132. package/dist/types/protocol/part-input.d.ts.map +1 -1
  133. package/dist/types/protocol/text-parts.d.ts +10 -0
  134. package/dist/types/protocol/text-parts.d.ts.map +1 -0
  135. package/dist/types/protocol/wire-api.d.ts +39 -29
  136. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  137. package/dist/types/protocol/wire.d.ts +13 -10
  138. package/dist/types/protocol/wire.d.ts.map +1 -1
  139. package/dist/types/server/install.d.ts +2 -1
  140. package/dist/types/server/install.d.ts.map +1 -1
  141. package/docs/consuming.md +8 -1
  142. package/docs/deploy.md +17 -8
  143. package/docs/harnesses.md +173 -44
  144. package/package.json +1 -1
  145. package/src/core/agents/acp/account.ts +158 -0
  146. package/src/core/agents/acp/acp-agent.ts +290 -178
  147. package/src/core/agents/acp/adapter.ts +126 -35
  148. package/src/core/agents/acp/client.ts +196 -49
  149. package/src/core/agents/acp/known-agents.ts +14 -5
  150. package/src/core/agents/acp/mappings.ts +112 -21
  151. package/src/core/agents/acp/models.ts +72 -0
  152. package/src/core/agents/acp/profile.ts +133 -0
  153. package/src/core/agents/acp/prompts.ts +287 -0
  154. package/src/core/agents/acp/requests.ts +16 -9
  155. package/src/core/agents/claude-code/claude-agent.ts +2 -13
  156. package/src/core/agents/claude-code/login.ts +4 -1
  157. package/src/core/agents/claude-code/options.ts +1 -1
  158. package/src/core/agents/claude-code/session.ts +50 -16
  159. package/src/core/agents/claude-code/spawn.ts +0 -26
  160. package/src/core/agents/claude-code/turn.ts +7 -2
  161. package/src/core/agents/codex-app-server/client.ts +11 -18
  162. package/src/core/agents/codex-app-server/login.ts +4 -5
  163. package/src/core/agents/gemini/failures.ts +148 -0
  164. package/src/core/agents/gemini/login.ts +188 -0
  165. package/src/core/agents/gemini/profile.ts +163 -0
  166. package/src/core/agents/gemini/tools.ts +99 -0
  167. package/src/core/agents/login.ts +14 -8
  168. package/src/core/agents/stderr-tail.ts +5 -2
  169. package/src/core/presets.ts +15 -2
  170. package/src/core/processes/native-processes.ts +32 -1
  171. package/src/core/provision/checksums.ts +12 -2
  172. package/src/core/provision/install-build.ts +122 -55
  173. package/src/core/provision/pins.ts +5 -0
  174. package/src/core/provision/provisioner.ts +62 -27
  175. package/src/core/provision/releases.ts +47 -1
  176. package/src/core/provision/tools.ts +124 -31
  177. package/src/operator/errors.ts +5 -2
  178. package/src/operator/operator.ts +208 -91
  179. package/src/operator/render.ts +61 -33
  180. package/src/operator/session-tools.ts +2 -1
  181. package/src/operator/types.ts +5 -4
  182. package/src/protocol/account.ts +5 -2
  183. package/src/protocol/auth.ts +5 -1
  184. package/src/protocol/config.ts +4 -2
  185. package/src/protocol/credentials.ts +11 -2
  186. package/src/protocol/harness.ts +9 -1
  187. package/src/protocol/part-input.ts +2 -5
  188. package/src/protocol/text-parts.ts +10 -0
  189. package/src/server/bin.ts +20 -6
  190. package/src/server/install.ts +6 -3
@@ -0,0 +1,287 @@
1
+ import type { ContentBlock, PromptResponse, SessionUpdate, Usage } from "@agentclientprotocol/sdk";
2
+ import type { AgentRequests } from "./client.ts";
3
+
4
+ const sum = (a: number | null | undefined, b: number | null | undefined) => (a ?? 0) + (b ?? 0);
5
+
6
+ /** Two responses' usage, summed: each counts its own model steps. */
7
+ function addUsage(a: Usage | undefined, b: Usage | null | undefined): Usage | undefined {
8
+ if (!b) return a;
9
+ if (!a) return b;
10
+ return {
11
+ totalTokens: a.totalTokens + b.totalTokens,
12
+ inputTokens: a.inputTokens + b.inputTokens,
13
+ outputTokens: a.outputTokens + b.outputTokens,
14
+ thoughtTokens: sum(a.thoughtTokens, b.thoughtTokens),
15
+ cachedReadTokens: sum(a.cachedReadTokens, b.cachedReadTokens),
16
+ cachedWriteTokens: sum(a.cachedWriteTokens, b.cachedWriteTokens),
17
+ };
18
+ }
19
+
20
+ /** A steer, sent as a prompt of its own. */
21
+ interface Steer {
22
+ steerId: string;
23
+ prompt: ContentBlock[];
24
+ /** While its prompt is in flight unsettled: the agent's requests counted when it was sent. */
25
+ mark?: number;
26
+ /** Once taken: the usage reports still to pass before the model call that reads it can start. */
27
+ reports?: number;
28
+ }
29
+
30
+ /** A prompt in flight, in the order sent: the turn's own, or a steer's. */
31
+ interface Prompt {
32
+ order: number;
33
+ steer?: Steer;
34
+ }
35
+
36
+ /** How a turn's prompts end, and the steers the agent read on the way. */
37
+ export interface PromptEnds {
38
+ /** The agent read a steer: its echo goes before what the agent says next. */
39
+ read(steerId: string): void;
40
+ /** No prompt is in flight: the newest prompt's stop reason, the usage summed over every answer. */
41
+ ended(result: Pick<PromptResponse, "stopReason" | "usage">): void;
42
+ /** The turn's own prompt failed, and no prompt is in flight. */
43
+ failed(error: unknown): void;
44
+ }
45
+
46
+ export interface TurnPromptsOptions {
47
+ /** Send a prompt on the turn's session. */
48
+ send(prompt: ContentBlock[]): Promise<PromptResponse>;
49
+ /** What the agent asks, for a turn that takes steers (`AcpClient.asking`). */
50
+ asking?: AgentRequests;
51
+ /** The turn's: once aborted no steer is sent, and those left are undelivered. */
52
+ signal: AbortSignal;
53
+ ends: PromptEnds;
54
+ }
55
+
56
+ // @ref LLP 0016.000#an-acp-agent-steered-by-prompt — the turn's prompts and its steers, as one state machine
57
+ /**
58
+ * The prompts a turn has in flight: its own, then each steer, sent as a
59
+ * prompt of its own to an agent that takes a prompt while one runs as input
60
+ * to the running turn (Antigravity). Such an agent answers the prompt before
61
+ * at once (`end_turn`, the usage of the steps it finished) and goes on; it
62
+ * refuses a prompt while it asks the person.
63
+ *
64
+ * - Order: steers wait in order, and the head stays the head until it is
65
+ * settled. It is sent once the agent asks nothing (`asking`); it is taken
66
+ * when the prompt before it answers, and refused when its own prompt
67
+ * fails. A refused head goes again, in place, only when a request of the
68
+ * agent's arrived after it was sent (the two crossed); refused with none
69
+ * between, it is undelivered, and the next steer is the head.
70
+ * - Read: a taken steer is read by the first model call that starts after
71
+ * it was taken; the call running then goes on without it. A call ends with
72
+ * a usage report (`usage_update`, after every call; its tool calls are
73
+ * announced after it), and its output is its message and thought chunks.
74
+ * Taken while a call streams (from its first chunk to its usage report),
75
+ * it waits for that report, whatever tool calls are open (a command left
76
+ * running in the background). Otherwise, while a tool call of the turn is
77
+ * open, or after a call's usage report or the end of its last open tool
78
+ * call with no chunk since, no call is known to run: it is read at the
79
+ * next chunk, or the next usage report for a call that made none. After a tool ends the wire cannot
80
+ * tell whether Antigravity's next call carries it (one run of three did):
81
+ * the echo is then one message early at worst, never after its reply. Otherwise one usage report must pass first, then the same. A steer's
82
+ * own answer reads nothing (a later steer supersedes it at once); one still
83
+ * unread when the turn ends with its prompts answered, cancelled included,
84
+ * is read then, and none when the turn fails. The echo goes out just before
85
+ * what it is read at (`update`). One whose own prompt fails was never read,
86
+ * and is undelivered.
87
+ * - Result: the turn ends when no prompt is in flight, with the stop reason
88
+ * of the newest prompt sent that answered and the usage of every answer.
89
+ */
90
+ export class TurnPrompts {
91
+ private readonly flying: Prompt[] = [];
92
+ /** Steers not yet taken, the head first. */
93
+ private readonly waiting: Steer[] = [];
94
+ /** Steers taken and not yet read, in order. */
95
+ private readonly taken: Steer[] = [];
96
+ /** The turn's tool calls not yet `completed` or `failed`: while one is, no model call runs. */
97
+ private readonly tools = new Set<string>();
98
+ /** The turn has made a chunk or a tool update. */
99
+ private produced = false;
100
+ /** No call's output since a call (its usage report, after output) or the last open tool call ended. */
101
+ private betweenCalls = false;
102
+ /** A model call is streaming, for certain: from a chunk to the next usage report. */
103
+ private streaming = false;
104
+ private sent = 0;
105
+ private newest?: { order: number; stopReason: PromptResponse["stopReason"] };
106
+ private usage?: Usage;
107
+ private failure?: { error: unknown };
108
+ private done = false;
109
+ private pumping = false;
110
+ private settle = () => {};
111
+ /** Settles once no prompt is in flight, or the agent is gone. */
112
+ readonly settled = new Promise<void>((resolve) => {
113
+ this.settle = resolve;
114
+ });
115
+
116
+ constructor(private readonly options: TurnPromptsOptions) {}
117
+
118
+ /** Whether the turn still takes a prompt. */
119
+ get open(): boolean {
120
+ return !this.done;
121
+ }
122
+
123
+ /** The turn's own prompt. */
124
+ start(prompt: ContentBlock[]): void {
125
+ this.send(prompt);
126
+ }
127
+
128
+ /** A steer: it waits behind the steers before it. */
129
+ steer(steerId: string, prompt: ContentBlock[]): void {
130
+ this.waiting.push({ steerId, prompt });
131
+ void this.pump();
132
+ }
133
+
134
+ /**
135
+ * An update of the turn's session, before it goes out: a chunk reads the
136
+ * steers taken whose call has started, a usage report ends a call.
137
+ */
138
+ update(update: SessionUpdate): void {
139
+ switch (update.sessionUpdate) {
140
+ case "tool_call":
141
+ case "tool_call_update":
142
+ this.produced = true;
143
+ // An update carries only what changed: one with no status moves nothing.
144
+ if (update.status === "completed" || update.status === "failed") {
145
+ // The turn's last open tool call ended: no call's output has come since.
146
+ // One a streaming call leaves behind ends nothing: that call goes on.
147
+ if (this.tools.delete(update.toolCallId) && this.tools.size === 0 && !this.streaming)
148
+ this.betweenCalls = true;
149
+ } else if (update.status || update.sessionUpdate === "tool_call") {
150
+ this.tools.add(update.toolCallId);
151
+ this.betweenCalls = false;
152
+ }
153
+ return;
154
+ case "agent_message_chunk":
155
+ case "agent_thought_chunk":
156
+ [this.produced, this.betweenCalls, this.streaming] = [true, false, true];
157
+ this.read(this.ready());
158
+ return;
159
+ case "usage_update":
160
+ // The report before any output (a session's first prompt) ends no call.
161
+ this.betweenCalls ||= this.produced;
162
+ this.streaming = false;
163
+ // A call that made no chunk read them at its end.
164
+ this.read(this.ready());
165
+ for (const steer of this.taken) steer.reports = Math.max(0, (steer.reports ?? 0) - 1);
166
+ return;
167
+ }
168
+ }
169
+
170
+ /** How many steers taken, in order, are past every usage report they waited for. */
171
+ private ready(): number {
172
+ const waiting = this.taken.findIndex((steer) => (steer.reports ?? 0) > 0);
173
+ return waiting === -1 ? this.taken.length : waiting;
174
+ }
175
+
176
+ /** The agent is gone: nothing more is told. */
177
+ close(): void {
178
+ this.done = true;
179
+ this.settle();
180
+ }
181
+
182
+ private send(prompt: ContentBlock[], steer?: Steer): void {
183
+ const sent: Prompt = { order: ++this.sent, ...(steer && { steer }) };
184
+ this.flying.push(sent);
185
+ this.options.send(prompt).then(
186
+ (response) => this.answered(sent, response),
187
+ (error: unknown) => this.refused(sent, error),
188
+ );
189
+ }
190
+
191
+ private answered(prompt: Prompt, response: PromptResponse): void {
192
+ if (this.done) return;
193
+ this.usage = addUsage(this.usage, response.usage);
194
+ if (!this.newest || prompt.order > this.newest.order)
195
+ this.newest = { order: prompt.order, stopReason: response.stopReason };
196
+ const next = this.flying[this.flying.indexOf(prompt) + 1];
197
+ this.remove(prompt);
198
+ const { steer } = prompt;
199
+ // Answered before the prompt before it: taken all the same. Its answer
200
+ // reads nothing: a later steer supersedes it as one supersedes the turn's own.
201
+ if (steer && this.waiting[0] === steer) this.take();
202
+ // Superseded: the agent took the steer after it.
203
+ if (next?.steer && this.waiting[0] === next.steer) this.take();
204
+ this.endIfIdle();
205
+ }
206
+
207
+ private refused(prompt: Prompt, error: unknown): void {
208
+ if (this.done) return;
209
+ this.remove(prompt);
210
+ const { steer } = prompt;
211
+ if (!steer) this.failure = { error };
212
+ else if (this.waiting[0] === steer) {
213
+ const crossed = this.options.asking?.arrivedSince(steer.mark ?? 0) ?? false;
214
+ steer.mark = undefined;
215
+ // Refused for a reason of its own: undelivered.
216
+ if (!crossed) this.waiting.shift();
217
+ } else if (this.taken.includes(steer)) this.taken.splice(this.taken.indexOf(steer), 1);
218
+ this.endIfIdle();
219
+ void this.pump();
220
+ }
221
+
222
+ /** The head is taken: the next steer is the head. */
223
+ private take(): void {
224
+ const steer = this.waiting.shift();
225
+ if (!steer) return;
226
+ steer.mark = undefined;
227
+ // With a tool call open, or a call ended and nothing since, no model call runs;
228
+ // otherwise the running one began without it.
229
+ // A call streaming waits for its report, whatever tool calls are open.
230
+ steer.reports = !this.streaming && (this.tools.size > 0 || this.betweenCalls) ? 0 : 1;
231
+ // It starts the next call: a steer taken after it waits for that call's report.
232
+ this.betweenCalls = false;
233
+ this.taken.push(steer);
234
+ void this.pump();
235
+ }
236
+
237
+ /** Read the first `count` steers taken. */
238
+ private read(count: number): void {
239
+ for (const steer of this.taken.splice(0, count)) this.options.ends.read(steer.steerId);
240
+ }
241
+
242
+ /** Send the head once the agent asks nothing, unless it is in flight already. */
243
+ private async pump(): Promise<void> {
244
+ if (this.pumping) return;
245
+ this.pumping = true;
246
+ try {
247
+ for (;;) {
248
+ const head = this.waiting[0];
249
+ if (!head || head.mark !== undefined || !this.sending) return;
250
+ const { asking } = this.options;
251
+ if (asking?.pending) {
252
+ // The turn's end releases a steer still waiting: it is undelivered.
253
+ await Promise.race([asking.idle(), this.settled]);
254
+ continue;
255
+ }
256
+ head.mark = asking?.arrived ?? 0;
257
+ this.send(head.prompt, head);
258
+ }
259
+ } finally {
260
+ this.pumping = false;
261
+ }
262
+ }
263
+
264
+ /** Whether a steer may still go: the turn runs, and its own prompt has not failed. */
265
+ private get sending(): boolean {
266
+ return !this.done && !this.failure && !this.options.signal.aborted;
267
+ }
268
+
269
+ private remove(prompt: Prompt): void {
270
+ this.flying.splice(this.flying.indexOf(prompt), 1);
271
+ }
272
+
273
+ private endIfIdle(): void {
274
+ if (this.flying.length > 0) return;
275
+ this.close();
276
+ if (this.failure) {
277
+ this.options.ends.failed(this.failure.error);
278
+ return;
279
+ }
280
+ // The turn is over with its prompts answered, cancelled included: what the agent took, it has.
281
+ this.read(this.taken.length);
282
+ this.options.ends.ended({
283
+ stopReason: this.newest?.stopReason ?? "end_turn",
284
+ ...(this.usage && { usage: this.usage }),
285
+ });
286
+ }
287
+ }
@@ -4,16 +4,18 @@ import type {
4
4
  RequestPermissionRequest,
5
5
  RequestPermissionResponse,
6
6
  } from "@agentclientprotocol/sdk";
7
- import type { PermissionMode } from "../../../protocol/index.ts";
7
+ import type { McpTool, PermissionMode } from "../../../protocol/index.ts";
8
8
  import type { ElicitationRequestHandler, PermissionRequestHandler } from "../base.ts";
9
9
  import { inputReply, inputRequest } from "../elicitation.ts";
10
10
  import {
11
11
  CANCELLED_OUTCOME,
12
+ asksInMode,
12
13
  autoDecide,
13
14
  chooseOutcome,
14
15
  permissionModeOf,
15
16
  permissionToolCall,
16
17
  } from "./mappings.ts";
18
+ import type { AcpToolCall } from "./profile.ts";
17
19
 
18
20
  /**
19
21
  * What the turn running on a session answers the agent's requests with: set
@@ -35,6 +37,8 @@ export interface TurnScope {
35
37
  export interface RequestScope {
36
38
  readonly acpSessionId: string;
37
39
  turn?: TurnScope;
40
+ /** What the harness's tool rules read of a call (`AcpProfile.stream`). */
41
+ describe?(call: AcpToolCall): { mcp?: McpTool; command?: string };
38
42
  }
39
43
 
40
44
  /** Answer an agent permission request against the session's current turn. */
@@ -48,20 +52,23 @@ export async function answerPermission(
48
52
  // Leaving a mode (claude-agent-acp's plan approval) is the user's choice,
49
53
  // from the agent's own options, in any mode that asks: they say how it
50
54
  // goes on. A turn that never asks (`dont_ask`, `bypass_permissions`)
51
- // decides it as before; other requests ask only in `default`.
55
+ // decides it as before; other requests ask as the mode says (`asksInMode`).
52
56
  const plan =
53
57
  request.toolCall.kind === "switch_mode" &&
54
58
  turn?.mode !== "dont_ask" &&
55
59
  turn?.mode !== "bypass_permissions";
56
- if (!turn?.broker || !(plan || (turn.mode ?? "default") === "default")) {
60
+ if (!turn?.broker || !(plan || asksInMode(request, turn.mode ?? "default"))) {
57
61
  return autoDecide(request, turn?.mode);
58
62
  }
59
- const decision = await turn.broker(permissionToolCall(request), {
60
- signal: turn.signal,
61
- ...(plan && {
62
- options: request.options.map(({ optionId, name, kind }) => ({ optionId, name, kind })),
63
- }),
64
- });
63
+ const decision = await turn.broker(
64
+ permissionToolCall(request, scope.describe?.(request.toolCall)),
65
+ {
66
+ signal: turn.signal,
67
+ ...(plan && {
68
+ options: request.options.map(({ optionId, name, kind }) => ({ optionId, name, kind })),
69
+ }),
70
+ },
71
+ );
65
72
  if (decision.decision === "cancel") return CANCELLED_OUTCOME;
66
73
  // `decision.updatedInput` is unrepresentable here: ACP v1's outcome carries
67
74
  // an optionId and nothing else, so an edited input cannot be honoured — and
@@ -33,12 +33,6 @@ import type { ClaudeTurn } from "./turn.ts";
33
33
 
34
34
  type ClaudeContent = SDKUserMessage["message"]["content"];
35
35
 
36
- /**
37
- * How long after a cancel a turn Claude has not ended has its process ended,
38
- * unless `cancelGraceMs` says otherwise (LLP 0001, D9).
39
- */
40
- const CANCEL_GRACE_MS = 10_000;
41
-
42
36
  const CAPABILITIES: AgentCapabilities = {
43
37
  multiTurn: true,
44
38
  sessionResume: true,
@@ -125,12 +119,10 @@ export class ClaudeCodeAgent extends SessionAgent {
125
119
  readonly login: ClaudeCliLogin;
126
120
  private readonly pool: ClaudeSessionPool;
127
121
  private readonly credentials?: ClaudeCredentials;
128
- private readonly cancelGraceMs: number;
129
122
  private readonly host?: HostToolSessions;
130
123
 
131
124
  constructor(private readonly agentOptions: ClaudeCodeAgentOptions = {}) {
132
125
  super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
133
- this.cancelGraceMs = agentOptions.cancelGraceMs ?? CANCEL_GRACE_MS;
134
126
  this.processes = agentOptions.processes ?? sharedNativeProcesses();
135
127
  this.host = hostToolSessions(agentOptions.hostTools, this.harness);
136
128
  this.pool = claudeSessionPool({ ...agentOptions, processes: this.processes, host: this.host });
@@ -241,10 +233,7 @@ export class ClaudeCodeAgent extends SessionAgent {
241
233
  ? "steered"
242
234
  : "no_active_turn",
243
235
  );
244
- removeInterrupt = onAbort(controller.signal, () => {
245
- void session.interruptTurn();
246
- void session.endUnstopped(turn, this.cancelGraceMs);
247
- });
236
+ removeInterrupt = onAbort(controller.signal, () => void session.cancelTurn(turn));
248
237
  const mcpServers = session.mcp.names;
249
238
  if (mcpServers.length) yield { type: "agentServer/mcpServers", names: mcpServers };
250
239
  let sawOutput = false;
@@ -352,7 +341,7 @@ export class ClaudeCodeAgent extends SessionAgent {
352
341
  * before the SDK interrupt lands (the abort-order race that could surface
353
342
  * a clean user cancel as `error`/`end_turn`). The SDK interrupt's
354
343
  * round-trip confirms the cancel, and so does the turn's end, whoever ended
355
- * it: Claude, or the grace that ended its process (`endUnstopped`). An
344
+ * it: Claude, or the grace that ended its process (`cancelTurn`). An
356
345
  * interrupt that fails while the turn runs is unconfirmed at once.
357
346
  */
358
347
  private async interrupt(
@@ -146,7 +146,10 @@ export class ClaudeCliLogin implements CliLogin {
146
146
  const cliPath = await this.commandPath();
147
147
  return [
148
148
  ...LOGINS,
149
- terminalMethod([cliPath, "auth", "login"], this.env(options), STORE_VARIABLE),
149
+ terminalMethod([cliPath, "auth", "login"], {
150
+ variable: STORE_VARIABLE,
151
+ env: this.env(options),
152
+ }),
150
153
  ];
151
154
  }
152
155
 
@@ -204,7 +204,7 @@ export type ClaudeSessionExtras = Pick<
204
204
 
205
205
  /** What every session of an agent runs with: fixed when the agent is made. */
206
206
  export type ClaudeSessionSettings = ClaudeSessionExtras &
207
- Pick<ClaudeCodeAgentOptions, "idleTimeoutMs" | "cancelConfirmMs"> & {
207
+ Pick<ClaudeCodeAgentOptions, "idleTimeoutMs" | "cancelConfirmMs" | "cancelGraceMs"> & {
208
208
  /** The agent's: where its sessions' `claude` processes start. */
209
209
  processes: NativeProcesses;
210
210
  /** The agent's: its sessions' host tools. */
@@ -8,11 +8,11 @@ import type {
8
8
  SDKResultMessage,
9
9
  SDKUserMessage,
10
10
  } from "@anthropic-ai/claude-agent-sdk";
11
- import { AsyncQueue, generateUUIDv7 } from "../../../protocol/index.ts";
11
+ import { AsyncQueue, classifyError, generateUUIDv7 } from "../../../protocol/index.ts";
12
12
  import type { McpServerConfig, PermissionMode } from "../../../protocol/index.ts";
13
13
  import type { NativeProcess } from "../../processes/native-processes.ts";
14
14
  import { onAbort, untilAborted, withTimeout } from "../../utils/deadline.ts";
15
- import { SessionResumeError } from "../../utils/errors.ts";
15
+ import { AgentExitedError, SessionResumeError } from "../../utils/errors.ts";
16
16
  import { CANCEL_CONFIRM_MS } from "../base.ts";
17
17
  import type { LiveTurn } from "../host-tools.ts";
18
18
  import {
@@ -39,10 +39,12 @@ import {
39
39
  } from "./options.ts";
40
40
  import { planUsedUp } from "./outcome.ts";
41
41
  import { notePairedReleases } from "./sdk-pair.ts";
42
- import { withStderr } from "./spawn.ts";
43
42
  import { ClaudeSpend } from "./spend.ts";
44
43
  import { ClaudeTurn, type ClaudeTurnStart } from "./turn.ts";
45
44
 
45
+ /** How long a cancelled turn has to end before its process is replaced (LLP 0001, D9). */
46
+ const CANCEL_GRACE_MS = 10_000;
47
+
46
48
  type SessionState = "starting" | "idle" | "busy" | "terminated";
47
49
  type ClaudeContent = SDKUserMessage["message"]["content"];
48
50
 
@@ -112,6 +114,8 @@ export class ClaudeSession implements PooledProcess, PooledClient {
112
114
  private readonly planWindows = new Map<string, SDKRateLimitEvent>();
113
115
  /** The `claude` process the engine started for it; none under an operator's spawner. */
114
116
  private native?: NativeProcess;
117
+ /** The CLI was still running when the session asked it to stop. */
118
+ private stoppedCli = false;
115
119
  /** Its end, once it began: settles when its process is stopped. */
116
120
  private ending?: Promise<void>;
117
121
  private readonly closeHandlers = new Set<() => void>();
@@ -324,7 +328,7 @@ export class ClaudeSession implements PooledProcess, PooledClient {
324
328
  }
325
329
  this.state = "busy";
326
330
  const prompt = this.userMessage(content);
327
- const turn = new ClaudeTurn(start, prompt.uuid);
331
+ const turn = new ClaudeTurn(start, prompt.uuid, () => void this.cancelTurn(turn));
328
332
  this.turn = turn;
329
333
  for (const report of this.rejectedWindowReports()) turn.events.push(report);
330
334
  this.promptQueue.push(prompt);
@@ -339,7 +343,7 @@ export class ClaudeSession implements PooledProcess, PooledClient {
339
343
  * False when no turn takes input.
340
344
  */
341
345
  steer(content: ClaudeContent, steerId: string): boolean {
342
- if (this.state !== "busy" || !this.turn) return false;
346
+ if (this.state !== "busy" || !this.turn || this.turn.cancelled) return false;
343
347
  const message = this.userMessage(content);
344
348
  this.turn.sendSteer(message.uuid, steerId);
345
349
  this.promptQueue.push(message);
@@ -405,13 +409,14 @@ export class ClaudeSession implements PooledProcess, PooledClient {
405
409
 
406
410
  // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — cancelGraceMs: an agent that has not stopped is ended
407
411
  /**
408
- * End the process of a cancelled `turn` that has not ended within
409
- * `graceMs`: Claude did not stop it (a frozen or hung CLI), and nothing
410
- * else would. The turn's events end, so it ends cancelled, and the pool
411
- * hears `replaced` (`onSessionEnd`); the next turn resumes on a new
412
- * process. A turn that ended, and any turn after it, is left alone.
412
+ * Interrupt this turn. If Claude still hasn't stopped it at `cancelGraceMs`,
413
+ * end the process. The turn's events end and the next turn resumes on a
414
+ * new process. A request answered after its turn ended stops nothing.
413
415
  */
414
- async endUnstopped(turn: ClaudeTurn, graceMs: number): Promise<void> {
416
+ async cancelTurn(turn: ClaudeTurn): Promise<void> {
417
+ if (this.turn !== turn) return;
418
+ void this.interruptTurn();
419
+ const graceMs = this.settings.cancelGraceMs ?? CANCEL_GRACE_MS;
415
420
  if ((await withTimeout(turn.ended, graceMs)) === undefined && this.turn === turn)
416
421
  await this.terminate("replaced");
417
422
  }
@@ -490,6 +495,8 @@ export class ClaudeSession implements PooledProcess, PooledClient {
490
495
  this.promptQueue.end();
491
496
  this.turn?.end();
492
497
  this.turn = null;
498
+ const child = this.native?.child;
499
+ this.stoppedCli = child?.exitCode === null && child.signalCode === null;
493
500
  try {
494
501
  // The SDK documents close() as the forceful subprocess/MCP cleanup path.
495
502
  query?.close();
@@ -511,22 +518,48 @@ export class ClaudeSession implements PooledProcess, PooledClient {
511
518
 
512
519
  private async consumeEvents(): Promise<void> {
513
520
  if (!this.query) return;
521
+ let initializing = true;
522
+ // The SDK already sent initialize. Its receipt is independent of the first turn event.
523
+ void this.query.initializationResult?.().then(
524
+ () => {
525
+ initializing = false;
526
+ },
527
+ () => {},
528
+ );
514
529
  try {
515
530
  for await (const event of this.query) {
516
531
  this.cliStarted = true;
517
532
  this.observe(event);
518
533
  this.route(event);
534
+ if (this.startupError) return;
519
535
  }
536
+ // @ref LLP 0016.000#when-a-process-exits-before-answering — only the session knows who ended this query
537
+ if (!this.closed && (this.turn || !this.cliStarted || this.state === "starting"))
538
+ throw new AgentExitedError("Claude ended the turn without a result");
520
539
  } catch (thrown) {
521
- // The SDK words an exit from its own spawner with the CLI's stderr; ours keeps that tail.
522
- const err = withStderr(thrown, this.native?.stderrTail ?? "");
523
- if (this.turn) this.turn.fail(err);
524
- else this.startupError = err;
540
+ const pending = initializing ? ["initialize"] : this.turn ? ["the turn"] : [];
541
+ await this.failStream(thrown, pending);
525
542
  } finally {
526
543
  await this.terminate();
527
544
  }
528
545
  }
529
546
 
547
+ private async failStream(cause: unknown, pending: string[]): Promise<void> {
548
+ const native = this.native;
549
+ const exit = await native?.exitAfterDisconnect();
550
+ if (this.stoppedCli || this.turn?.cancelled) return;
551
+ let error = cause;
552
+ if (native && exit && (exit.code !== null || exit.signal !== null)) {
553
+ const resume = this.config.resumeSessionId;
554
+ error =
555
+ resume && !this.queryBegun && classifyError(native.stderrTail) === "resume_failed"
556
+ ? new SessionResumeError(resume, native.stderrTail.trim())
557
+ : native.exitError("Claude Code", exit, pending);
558
+ }
559
+ if (this.turn) this.turn.fail(error);
560
+ else this.startupError = error;
561
+ }
562
+
530
563
  /** What an event says of the session: its native id, its mode, plan windows, spend, steers read. */
531
564
  private observe(event: SDKMessage): void {
532
565
  if (event.type === "system" && event.subtype === "init") {
@@ -595,11 +628,12 @@ export class ClaudeSession implements PooledProcess, PooledClient {
595
628
  private settleUnshown(result: SDKResultMessage): void {
596
629
  if (result.subtype !== "success" && result.origin === undefined) {
597
630
  const reason = result.errors.join("; ") || "Claude failed during startup";
598
- throw this.config.resumeSessionId
631
+ this.startupError = this.config.resumeSessionId
599
632
  ? new SessionResumeError(this.config.resumeSessionId, reason, {
600
633
  cause: new Error(reason),
601
634
  })
602
635
  : new Error(reason);
636
+ return;
603
637
  }
604
638
  this.spend.charge(result);
605
639
  if (this.state === "idle") this.pooling?.betweenTurns();
@@ -3,7 +3,6 @@ import type { Readable, Writable } from "node:stream";
3
3
  import { StringDecoder } from "node:string_decoder";
4
4
  import type { Options, SpawnOptions, SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
5
5
  import type { NativeProcess, NativeProcesses } from "../../processes/native-processes.ts";
6
- import { redactSecrets } from "../stderr-tail.ts";
7
6
 
8
7
  type ExitListener = (code: number | null, signal: NodeJS.Signals | null) => void;
9
8
  type ErrorListener = (error: Error) => void;
@@ -18,9 +17,6 @@ export interface ClaudeSpawn {
18
17
  onSpawned?: (native: NativeProcess) => void;
19
18
  }
20
19
 
21
- /** The longest stderr tail an SDK exit error carries. */
22
- const SDK_TAIL_MAX = 2048;
23
-
24
20
  /**
25
21
  * The CLI as the SDK sees it: the child's pipes, and its `exit` once stderr
26
22
  * has closed too (at most 200 ms after it), as the SDK's own spawner delivers
@@ -120,25 +116,3 @@ export function claudeSpawner(
120
116
  return new SpawnedClaude(native, stdin, stdout);
121
117
  };
122
118
  }
123
-
124
- /** The SDK's bare exit error: what its own spawner would have followed with `. stderr: <tail>`. */
125
- const BARE_EXIT = /^Claude Code process (?:exited with code \S+|terminated by signal \S+)$/;
126
-
127
- /**
128
- * Put the CLI's own words back into the SDK's exit error, as the SDK's own
129
- * spawner words it ("Claude Code process exited with code 1. stderr: …"):
130
- * the last 2 KB, trimmed, with its secrets redacted (the SDK redacts its own;
131
- * this marks each `[REDACTED]`). The SDK builds that tail only from its own
132
- * spawner. Its message alone changes, so the error keeps its class and fields.
133
- */
134
- export function withStderr(error: unknown, tail: string): unknown {
135
- if (!(error instanceof Error) || !BARE_EXIT.test(error.message)) return error;
136
- let kept = tail.length > SDK_TAIL_MAX ? tail.slice(-SDK_TAIL_MAX) : tail;
137
- // A cut that splits a surrogate pair drops its half, as the SDK's does.
138
- const first = kept.charCodeAt(0);
139
- if (first >= 0xdc00 && first <= 0xdfff) kept = kept.slice(1);
140
- // As the SDK redacts its own tail, before it quotes it.
141
- kept = redactSecrets(kept).trim();
142
- if (kept) error.message = `${error.message}. stderr: ${kept}`;
143
- return error;
144
- }
@@ -72,7 +72,11 @@ export class ClaudeTurn {
72
72
  /** Set while Claude is between queries, about to run the unread steers. */
73
73
  private watchdog?: ReturnType<typeof setTimeout>;
74
74
 
75
- constructor(start: ClaudeTurnStart, prompt: string) {
75
+ constructor(
76
+ start: ClaudeTurnStart,
77
+ prompt: string,
78
+ private readonly dropUnread: () => void,
79
+ ) {
76
80
  this.id = start.turnId;
77
81
  this.signal = start.signal;
78
82
  this.permissions = start.permissions;
@@ -85,9 +89,10 @@ export class ClaudeTurn {
85
89
  });
86
90
  }
87
91
 
88
- /** A request of the turn was answered `cancelled`: Claude stops the turn, which ends cancelled. */
92
+ /** Drop unread steers before the SDK's denial lets Claude start their query. */
89
93
  cancelByRequest(): void {
90
94
  this.stoppedByRequest = true;
95
+ if (this.unread.size) this.dropUnread();
91
96
  }
92
97
 
93
98
  /** Whether a cancelled request stopped the turn (Claude interrupts on it). */