@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
@@ -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
@@ -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
 
@@ -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,7 +39,6 @@ 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
 
@@ -112,6 +111,8 @@ export class ClaudeSession implements PooledProcess, PooledClient {
112
111
  private readonly planWindows = new Map<string, SDKRateLimitEvent>();
113
112
  /** The `claude` process the engine started for it; none under an operator's spawner. */
114
113
  private native?: NativeProcess;
114
+ /** The CLI was still running when the session asked it to stop. */
115
+ private stoppedCli = false;
115
116
  /** Its end, once it began: settles when its process is stopped. */
116
117
  private ending?: Promise<void>;
117
118
  private readonly closeHandlers = new Set<() => void>();
@@ -490,6 +491,8 @@ export class ClaudeSession implements PooledProcess, PooledClient {
490
491
  this.promptQueue.end();
491
492
  this.turn?.end();
492
493
  this.turn = null;
494
+ const child = this.native?.child;
495
+ this.stoppedCli = child?.exitCode === null && child.signalCode === null;
493
496
  try {
494
497
  // The SDK documents close() as the forceful subprocess/MCP cleanup path.
495
498
  query?.close();
@@ -511,22 +514,48 @@ export class ClaudeSession implements PooledProcess, PooledClient {
511
514
 
512
515
  private async consumeEvents(): Promise<void> {
513
516
  if (!this.query) return;
517
+ let initializing = true;
518
+ // The SDK already sent initialize. Its receipt is independent of the first turn event.
519
+ void this.query.initializationResult?.().then(
520
+ () => {
521
+ initializing = false;
522
+ },
523
+ () => {},
524
+ );
514
525
  try {
515
526
  for await (const event of this.query) {
516
527
  this.cliStarted = true;
517
528
  this.observe(event);
518
529
  this.route(event);
530
+ if (this.startupError) return;
519
531
  }
532
+ // @ref LLP 0016.000#when-a-process-exits-before-answering — only the session knows who ended this query
533
+ if (!this.closed && (this.turn || !this.cliStarted || this.state === "starting"))
534
+ throw new AgentExitedError("Claude ended the turn without a result");
520
535
  } 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;
536
+ const pending = initializing ? ["initialize"] : this.turn ? ["the turn"] : [];
537
+ await this.failStream(thrown, pending);
525
538
  } finally {
526
539
  await this.terminate();
527
540
  }
528
541
  }
529
542
 
543
+ private async failStream(cause: unknown, pending: string[]): Promise<void> {
544
+ const native = this.native;
545
+ const exit = await native?.exitAfterDisconnect();
546
+ if (this.stoppedCli || this.turn?.cancelled) return;
547
+ let error = cause;
548
+ if (native && exit && (exit.code !== null || exit.signal !== null)) {
549
+ const resume = this.config.resumeSessionId;
550
+ error =
551
+ resume && !this.queryBegun && classifyError(native.stderrTail) === "resume_failed"
552
+ ? new SessionResumeError(resume, native.stderrTail.trim())
553
+ : native.exitError("Claude Code", exit, pending);
554
+ }
555
+ if (this.turn) this.turn.fail(error);
556
+ else this.startupError = error;
557
+ }
558
+
530
559
  /** What an event says of the session: its native id, its mode, plan windows, spend, steers read. */
531
560
  private observe(event: SDKMessage): void {
532
561
  if (event.type === "system" && event.subtype === "init") {
@@ -595,11 +624,12 @@ export class ClaudeSession implements PooledProcess, PooledClient {
595
624
  private settleUnshown(result: SDKResultMessage): void {
596
625
  if (result.subtype !== "success" && result.origin === undefined) {
597
626
  const reason = result.errors.join("; ") || "Claude failed during startup";
598
- throw this.config.resumeSessionId
627
+ this.startupError = this.config.resumeSessionId
599
628
  ? new SessionResumeError(this.config.resumeSessionId, reason, {
600
629
  cause: new Error(reason),
601
630
  })
602
631
  : new Error(reason);
632
+ return;
603
633
  }
604
634
  this.spend.charge(result);
605
635
  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
- }
@@ -1,6 +1,5 @@
1
1
  import { StringDecoder } from "node:string_decoder";
2
2
  import type { NativeProcess, NativeProcesses } from "../../processes/native-processes.ts";
3
- import { AgentExitedError } from "../../utils/errors.ts";
4
3
  import type { CodexNotification } from "./protocol.ts";
5
4
 
6
5
  /** What the pinned native server logs of a cleanup that failed; it still exits 0. */
@@ -224,14 +223,16 @@ export class CodexAppServerClient implements CodexConnection {
224
223
  }
225
224
 
226
225
  request(method: string, params: unknown, timeoutMs?: number): Promise<unknown> {
227
- if (!this.native || this.exited)
226
+ const native = this.native;
227
+ if (!native || this.exited)
228
228
  return Promise.reject(this.lastExit ?? new Error("codex app-server not running"));
229
229
  const id = this.nextId++;
230
230
  return new Promise<unknown>((resolve, reject) => {
231
231
  const deadline = timeoutMs ?? this.opts.requestTimeoutMs ?? 30_000;
232
232
  const timer = setTimeout(() => {
233
233
  this.pending.delete(id);
234
- reject(new Error(`codex app-server '${method}' timed out after ${deadline}ms`));
234
+ const stderr = method === "initialize" ? `. ${native.stderrSummary}` : "";
235
+ reject(new Error(`codex app-server '${method}' timed out after ${deadline}ms${stderr}`));
235
236
  }, deadline);
236
237
  this.pending.set(id, { method, resolve, reject, timer });
237
238
  try {
@@ -346,10 +347,9 @@ export class CodexAppServerClient implements CodexConnection {
346
347
  proc.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
347
348
  // A broken pipe usually means the process died: its exit, which says
348
349
  // how and carries its stderr, is the error to keep when it follows.
349
- const onPipeError = (err: Error) =>
350
- setTimeout(() => {
351
- if (this.native === native) this.onExit(err);
352
- }, 1_000).unref?.();
350
+ const onPipeError = async (err: Error) => {
351
+ if (!(await native.exitAfterDisconnect()) && this.native === native) this.onExit(err);
352
+ };
353
353
  proc.stdin?.on("error", onPipeError);
354
354
  proc.stdout?.on("error", onPipeError);
355
355
  // The pinned native server logs its cleanup failures but still exits 0.
@@ -360,17 +360,10 @@ export class CodexAppServerClient implements CodexConnection {
360
360
  recent = recent.slice(-SNIFF_MAX);
361
361
  });
362
362
  proc.on("error", (err) => this.onExit(err));
363
- // Its exit once stdout and stderr closed: a response it wrote just before
364
- // is read first, and stderr's last flush, usually the line that says WHY
365
- // (a missing or expired login prints there and exits 1), is in the tail.
366
- void native.exited.then(({ code, signal }) => {
367
- const tail = native.stderrTail.trim().replace(/\s+/g, " ");
368
- // The process exiting is the failure (`process_exit`), whatever its stderr says.
369
- this.onExit(
370
- new AgentExitedError(
371
- `codex app-server exited (code=${code} signal=${signal})${tail ? `: ${tail}` : ""}`,
372
- ),
373
- );
363
+ void native.exited.then((exit) => {
364
+ if (this.native !== native || this.exited) return;
365
+ const pending = Array.from(this.pending.values(), (request) => request.method);
366
+ this.onExit(native.exitError("codex app-server", exit, pending));
374
367
  });
375
368
  }
376
369
 
@@ -144,11 +144,10 @@ export class CodexCliLogin implements CliLogin {
144
144
  async methods(options: LoginOptions): Promise<AuthMethod[]> {
145
145
  return [
146
146
  ...LOGINS.map(({ type: _type, ...method }) => method),
147
- terminalMethod(
148
- [await this.options.cliPath(), "login"],
149
- { ...process.env, ...options.env },
150
- STORE_VARIABLE,
151
- ),
147
+ terminalMethod([await this.options.cliPath(), "login"], {
148
+ variable: STORE_VARIABLE,
149
+ env: { ...process.env, ...options.env },
150
+ }),
152
151
  ];
153
152
  }
154
153