@firespoon/pi-antigravity-bridge 0.0.0-stage → 1.10.7

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 (54) hide show
  1. package/CHANGELOG.md +902 -0
  2. package/LICENSE +21 -0
  3. package/README.md +235 -3
  4. package/extensions/index.ts +1993 -0
  5. package/package.json +71 -6
  6. package/src/acp/connection.ts +623 -0
  7. package/src/acp/driver.ts +953 -0
  8. package/src/acp/events.ts +331 -0
  9. package/src/acp/home.ts +238 -0
  10. package/src/acp/jsonrpc.ts +232 -0
  11. package/src/acp/setup.ts +107 -0
  12. package/src/acp/usage-estimate.ts +61 -0
  13. package/src/agents.ts +64 -0
  14. package/src/agy-install.ts +85 -0
  15. package/src/agy-paths.ts +30 -0
  16. package/src/agy-setup.ts +72 -0
  17. package/src/agy-version.ts +283 -0
  18. package/src/approval-detect.ts +146 -0
  19. package/src/approval-gate.ts +208 -0
  20. package/src/approval-hook.ts +270 -0
  21. package/src/artifacts-ui.ts +88 -0
  22. package/src/artifacts.ts +144 -0
  23. package/src/ask-tool.ts +1222 -0
  24. package/src/background-watch.ts +225 -0
  25. package/src/bridge-catalog.ts +27 -0
  26. package/src/config.ts +485 -0
  27. package/src/daily-log.ts +196 -0
  28. package/src/dialog-lock.ts +48 -0
  29. package/src/diff-render.ts +205 -0
  30. package/src/driver-types.ts +172 -0
  31. package/src/driver.ts +907 -0
  32. package/src/engine-picker.ts +160 -0
  33. package/src/frame-guard.ts +38 -0
  34. package/src/mcp-registration.ts +382 -0
  35. package/src/mcp-server.ts +620 -0
  36. package/src/models.ts +407 -0
  37. package/src/native-tools.ts +104 -0
  38. package/src/parked-turn.ts +125 -0
  39. package/src/patch-cleanup.ts +519 -0
  40. package/src/poll-fold.ts +55 -0
  41. package/src/prompt-images.ts +92 -0
  42. package/src/provider.ts +2066 -0
  43. package/src/queued-messages.ts +152 -0
  44. package/src/redact.ts +27 -0
  45. package/src/sessions.ts +185 -0
  46. package/src/skills.ts +192 -0
  47. package/src/stream-events.ts +122 -0
  48. package/src/stream-sanitizer.ts +180 -0
  49. package/src/subagent-roster.ts +245 -0
  50. package/src/sysprompt-agent.ts +163 -0
  51. package/src/tasks-ui.ts +90 -0
  52. package/src/tasks.ts +174 -0
  53. package/src/usage.ts +174 -0
  54. package/src/web-tools.ts +320 -0
@@ -0,0 +1,953 @@
1
+ // AcpDriver: the ACP turn engine. Implements the same TurnDriver surface as
2
+ // the stream-json driver (see src/driver-types.ts) so provider.ts and
3
+ // the G9 round-trip store work unchanged.
4
+ //
5
+ // Engine differences vs stream-json, all verified live (docs/ACP-PROTOCOL-REFERENCE.md):
6
+ // - no process recycle on model/mode/effort/cwd drift: one server process,
7
+ // sessions selected per turn via session/new / session/load; only a
8
+ // changed request.agent recycles the process (before creating the next turn)
9
+ // - model and thought_level are separate session/set_config_option calls
10
+ // - config does NOT persist across server restarts: re-applied every turn
11
+ // - session/load replays history as full-text notification pairs BEFORE its
12
+ // response; the connection suppresses updates while loading
13
+ // - session/cancel is a notification; teardown remains the safety net
14
+ // - overall-timer pause uses remaining-budget semantics on G9 parks (never a
15
+ // fresh cap); every park carries its own timeout (BRIDGE_TIMEOUT_MS)
16
+ // - request_permission: skipPermissions turns answer the first allow option
17
+ // synchronously; otherwise an optional human handler (extension dialog)
18
+ // PARKS the request with the turn budget paused; no handler = deny
19
+ // fail-closed. Approvals-mode parity: a permissionPolicy override maps
20
+ // approvals.mode allow to the same synchronous auto path
21
+
22
+ import { randomUUID } from "node:crypto";
23
+ import type { UsageEstimate } from "../config.js";
24
+ import { AcpConnection, type AcpMcpServer, type AcpPermissionRequest } from "./connection.js";
25
+ import type { AcpPermissionHandler } from "./connection.js";
26
+ import { mapStopReason, mapUpdate, TextAccumulator, type AcpEditDiff } from "./events.js";
27
+ import { estimateTokens, synthesizeUsage } from "./usage-estimate.js";
28
+ import type {
29
+ AgyUsage,
30
+ DriverActivity,
31
+ DriverSnapshot,
32
+ DriverState,
33
+ DriverTurnRequest,
34
+ TurnDriver,
35
+ TurnHandle,
36
+ TurnOutcome,
37
+ } from "../driver-types.js";
38
+
39
+ const LIFECYCLE_LIMIT = 24;
40
+
41
+ export interface AcpDriverOptions {
42
+ /** agy CLI binary. Tests may substitute node with a fake-server script. */
43
+ bin: string | (() => string);
44
+ /** Extra argv (production: ["acp"]; tests: fake-server script). */
45
+ binArgs?: string[] | (() => string[]);
46
+ /** Native agy only: isolate inherited global MCP from other pi sessions. */
47
+ isolateHome?: boolean;
48
+ /** Explicit agent discovery root for isolated home staging (tests). */
49
+ agentsRoot?: string;
50
+ extraEnv?: Record<string, string>;
51
+ /** Bridge registration for session/new AND session/load. */
52
+ mcpServers?: () => AcpMcpServer[];
53
+ /** Gate B stopgap: how ACP turns synthesize usage while the server sends
54
+ * none. A function is resolved per turn (follows live config, like bin).
55
+ * Default "estimate". */
56
+ usageEstimate?: UsageEstimate | (() => UsageEstimate);
57
+ /** Human gate for ACP request_permission on non-skip turns. Forwarded to
58
+ * the connection; the driver parks the turn budget around each call
59
+ * (dialog time does not eat the deadline). */
60
+ onPermissionRequest?: AcpPermissionHandler;
61
+ /** Park budget for one permission dialog (tests shrink it). */
62
+ permissionParkMs?: number;
63
+ /** Standing policy consulted when the turn is not skipPermissions:
64
+ * "auto" answers the first allow option synchronously, "deny" consults
65
+ * the human handler or fail-closes. Default deny. */
66
+ permissionPolicy?: () => "auto" | "deny";
67
+ log?: (msg: string, data?: unknown) => void;
68
+ }
69
+
70
+ interface ActiveTurn {
71
+ id: string;
72
+ request: DriverTurnRequest;
73
+ sessionId: string;
74
+ buffer: DriverActivity[];
75
+ wake: (() => void)[];
76
+ closed: boolean;
77
+ resolve: (o: TurnOutcome) => void;
78
+ outcome: Promise<TurnOutcome>;
79
+ response: TextAccumulator;
80
+ /** Usage-synthesis counters: per-delta token sums (estimate mode) and
81
+ * delta counts (direct mode). Sums are taken per delta, never over the
82
+ * joined text, so a word split across chunks stays two words. */
83
+ textTokens: number;
84
+ thoughtTokens: number;
85
+ textDeltas: number;
86
+ thoughtDeltas: number;
87
+ /** Estimated once, not re-tokenized for every streaming delta. */
88
+ estimatedInputTokens: number;
89
+ /** Native tool_call batches seen this turn: parallel calls in one
90
+ * inference collapse to one batch. A batch opens on the first tool_call
91
+ * after model output (text/thought) and stays open until the next output
92
+ * frame, so interleaved completions cannot split it. Proxies how many
93
+ * times the model inferred; feeds the PromptResponse.usage context
94
+ * correction (issue #12). */
95
+ toolBatches: number;
96
+ /** True between the first tool_call of an inference and the next model
97
+ * output frame. tool-only inferences keep it open and merge into the
98
+ * previous batch: the divisor shrinks, the total over-reads (safe). */
99
+ toolBatchOpen: boolean;
100
+ /** Last usage_update occupancy this turn. Authoritative over every
101
+ * derived total; native agy 1.5.4 never sends it (probe 2026-11-10). */
102
+ contextUsed: number | undefined;
103
+ sawResult: boolean;
104
+ /** True once the prompt RPC was issued. Abort before this point has
105
+ * nothing to cancel: probing would risk a success-as-noop answer from a
106
+ * future cancel-capable server stranding the turn in the safety-net
107
+ * wait, so the driver tears down instead. */
108
+ promptStarted: boolean;
109
+ aborted: boolean;
110
+ abortedBy: "signal" | "timer" | null;
111
+ parks: number;
112
+ /** Wall-clock deadline of the overall timer; null while paused. */
113
+ overallDeadline: number | null;
114
+ overallRemainingMs: number | null;
115
+ overallTimer?: ReturnType<typeof setTimeout>;
116
+ idleTimer?: ReturnType<typeof setTimeout>;
117
+ /** toolCallId → tool name + args + optional native diff (diff rides on
118
+ * the pending tool_call frame; updates don't repeat it). */
119
+ toolCalls: Map<string, { name: string; args: Record<string, unknown>; diff?: AcpEditDiff; mcpServer?: string }>;
120
+ }
121
+
122
+ /** Map our config knobs onto ACP session modes. skipPermissions=false also
123
+ * fail-closes the in-connection permission handler (reject options), so the
124
+ * modes keep their server-side meaning. Provider plan turns are refused
125
+ * because agy does not enforce review-only writes. */
126
+ export function acpMode(mode: string, skipPermissions: boolean): string {
127
+ if (skipPermissions) return "accept-edits";
128
+ return mode === "plan" ? "plan" : mode === "accept-edits" ? "accept-edits" : "default";
129
+ }
130
+
131
+ export class AcpDriver implements TurnDriver {
132
+ #opts: AcpDriverOptions;
133
+ #state: DriverState = "idle";
134
+ #conn: AcpConnection | undefined;
135
+ #connAgent: string | undefined;
136
+ #generation = 0;
137
+ #active: ActiveTurn | undefined;
138
+ #queueTail: Promise<void> = Promise.resolve();
139
+ #lifecycle: string[] = [];
140
+ #onTurnEnd: ((outcome: TurnOutcome) => void) | undefined;
141
+ #stats = {
142
+ spawns: 0,
143
+ turns: 0,
144
+ sessionsCreated: 0,
145
+ sessionsLoaded: 0,
146
+ kills: 0,
147
+ };
148
+ #serverVersion: string | undefined;
149
+ #lastSessionId: string | undefined;
150
+ #agentInfo: { name?: string; title?: string } | undefined;
151
+
152
+ constructor(opts: AcpDriverOptions) {
153
+ this.#opts = opts;
154
+ this.#log("driver-created", { bin: typeof opts.bin === "function" ? "(resolved per turn)" : opts.bin });
155
+ }
156
+
157
+ get state(): DriverState {
158
+ return this.#state;
159
+ }
160
+
161
+ get activeHandle(): TurnHandle | null {
162
+ const t = this.#active;
163
+ return t && !t.closed ? this.#makeHandle(t) : null;
164
+ }
165
+
166
+ set onTurnEnd(fn: ((outcome: TurnOutcome) => void) | undefined) {
167
+ this.#onTurnEnd = fn;
168
+ }
169
+
170
+ /** Inject a synthetic activity into the live turn (bridge inbox). Parks the
171
+ * turn: suspends the idle timer and pauses the overall deadline. */
172
+ pushExternal(activity: DriverActivity): void {
173
+ const t = this.#active;
174
+ if (!t || t.closed) return;
175
+ if (activity.type === "bridge_call") {
176
+ t.parks += 1;
177
+ this.#clearIdle(t);
178
+ this.#pauseOverall(t);
179
+ }
180
+ this.#emit(t, activity);
181
+ }
182
+
183
+ /** Run the human permission dialog with the turn parked: same budget
184
+ * semantics as bridge parks (dialog time does not consume the deadline).
185
+ * The finally unparks the CAPTURED turn, never whatever is active at
186
+ * exit: the turn can close mid-dialog (abort, server death) and a new
187
+ * turn must not inherit this park's accounting. */
188
+ async #parkForPermission(req: AcpPermissionRequest): Promise<string | null | undefined> {
189
+ const t = this.#active;
190
+ const parked = t !== undefined && !t.closed;
191
+ if (parked) {
192
+ t.parks += 1;
193
+ this.#clearIdle(t);
194
+ this.#pauseOverall(t);
195
+ }
196
+ try {
197
+ return await this.#opts.onPermissionRequest!(req);
198
+ } finally {
199
+ if (parked && !t.closed && t.parks > 0) {
200
+ t.parks -= 1;
201
+ if (t.parks === 0) {
202
+ this.#armIdle(t);
203
+ this.#resumeOverall(t);
204
+ this.#log("unparked");
205
+ }
206
+ }
207
+ }
208
+ }
209
+
210
+ kickIdle(): void {
211
+ const t = this.#active;
212
+ if (!t || t.closed) return;
213
+ if (t.parks > 0) t.parks -= 1;
214
+ if (t.parks === 0) {
215
+ this.#armIdle(t);
216
+ this.#resumeOverall(t);
217
+ this.#log("unparked");
218
+ }
219
+ }
220
+
221
+ /** Turns are serialized; a parked turn stays open and the continuation
222
+ * path uses reentry() (same contract as the stream-json driver). */
223
+ run(request: DriverTurnRequest): Promise<TurnHandle> {
224
+ let release!: () => void;
225
+ const prev = this.#queueTail;
226
+ this.#queueTail = new Promise<void>((r) => (release = r));
227
+ return prev
228
+ .then(() => this.#runExclusive(request))
229
+ .then((handle) => {
230
+ void handle.outcome.catch(() => {}).then(() => release());
231
+ return handle;
232
+ })
233
+ .catch((err) => {
234
+ release();
235
+ throw err;
236
+ });
237
+ }
238
+
239
+ reentry(): TurnHandle | null {
240
+ return this.activeHandle;
241
+ }
242
+
243
+ #runExclusive(request: DriverTurnRequest): Promise<TurnHandle> {
244
+ // No shutdown latch here: pi fires session_shutdown on /new, /resume and
245
+ // /fork (not only process exit), so a closed driver must respawn on the
246
+ // next turn instead of rejecting forever. Regression 2026-09-07:
247
+ // /compact after a model switch failed with "ACP driver is shut down."
248
+ if (request.signal?.aborted) return Promise.reject(new Error("aborted before start"));
249
+
250
+ // Recycle BEFORE creating the new active turn and clear #conn first so
251
+ // the replaced connection's exit lands in #onConnectionExit as stale and
252
+ // never settles the replacement turn.
253
+ if (this.#conn && this.#connAgent !== request.agent) {
254
+ const prev = this.#conn;
255
+ const from = this.#connAgent ?? null;
256
+ this.#conn = undefined;
257
+ this.#connAgent = undefined;
258
+ this.#state = "dead";
259
+ this.#log("recycle-agent", { from, to: request.agent ?? null });
260
+ prev.abortAll("agent changed");
261
+ prev.kill();
262
+ }
263
+
264
+ const turn = this.#createTurn(request);
265
+ this.#active = turn;
266
+ this.#state = "running";
267
+ this.#stats.turns += 1;
268
+ this.#log("turn-start", {
269
+ model: request.model,
270
+ effort: request.effort,
271
+ mode: request.mode,
272
+ ...(request.agent ? { agent: request.agent } : {}),
273
+ conversation: request.conversationId ?? null,
274
+ images: request.images?.length ?? 0,
275
+ contextBlock: request.contextBlock ? true : undefined,
276
+ });
277
+
278
+ // Abort wiring first: a kill during session setup must still settle the
279
+ // turn (Gate D teardown applies from the first request).
280
+ if (request.signal) {
281
+ const onAbort = () => void this.#abortTurn(turn);
282
+ if (request.signal.aborted) {
283
+ onAbort();
284
+ } else {
285
+ request.signal.addEventListener("abort", onAbort, { once: true });
286
+ }
287
+ }
288
+
289
+ // Execute asynchronously: the handle returns as soon as the prompt is
290
+ // dispatched, and activities stream through next() (stream-json contract).
291
+ void this.#executeTurn(turn).catch((err: unknown) => {
292
+ this.#failTurn(turn, `ACP turn failed: ${describe(err)}`);
293
+ });
294
+ return Promise.resolve(this.#makeHandle(turn));
295
+ }
296
+
297
+ async #executeTurn(turn: ActiveTurn): Promise<void> {
298
+ const request = turn.request;
299
+ const conn = await this.#ensureConnection(request);
300
+
301
+ // Session: load (resume) or create. Load failures fall back to a fresh
302
+ // session — a missing conversation must not fail the turn (9.4).
303
+ try {
304
+ if (request.conversationId) {
305
+ this.#log("session-load", { sessionId: request.conversationId });
306
+ this.#stats.sessionsLoaded += 1;
307
+ await conn.loadSession(request.conversationId, request.cwd);
308
+ turn.sessionId = request.conversationId;
309
+ } else {
310
+ const created = await conn.newSession(request.cwd);
311
+ turn.sessionId = created.sessionId;
312
+ this.#stats.sessionsCreated += 1;
313
+ this.#log("session-new", { sessionId: created.sessionId });
314
+ }
315
+ } catch (err) {
316
+ if (turn.aborted) {
317
+ this.#settle(turn, {
318
+ conversationId: turn.sessionId,
319
+ status: "OK",
320
+ response: turn.response.text,
321
+ finished: true,
322
+ aborted: true,
323
+ });
324
+ return;
325
+ }
326
+ if (request.conversationId) {
327
+ this.#log("session-load-failed-creating-fresh", {
328
+ sessionId: request.conversationId,
329
+ message: err instanceof Error ? err.message : String(err),
330
+ });
331
+ try {
332
+ const created = await conn.newSession(request.cwd);
333
+ turn.sessionId = created.sessionId;
334
+ this.#stats.sessionsCreated += 1;
335
+ } catch (err2) {
336
+ this.#failTurn(turn, `ACP session failed: ${describe(err2)}`);
337
+ return;
338
+ }
339
+ } else {
340
+ this.#failTurn(turn, `ACP session failed: ${describe(err)}`);
341
+ return;
342
+ }
343
+ }
344
+ if (turn.closed) return;
345
+
346
+ // Config: model + mode. Model failure fails the turn (wrong-model turns
347
+ // are a parity break); mode failure is best-effort (auto policy makes
348
+ // the modes converge anyway).
349
+ try {
350
+ await conn.setConfigOption(turn.sessionId, "model", request.model);
351
+ if (request.effort) await conn.setConfigOption(turn.sessionId, "thought_level", request.effort);
352
+ } catch (err) {
353
+ this.#failTurn(turn, `ACP model selection failed: ${describe(err)}`);
354
+ return;
355
+ }
356
+ try {
357
+ await conn.setConfigOption(turn.sessionId, "mode", acpMode(request.mode, request.skipPermissions));
358
+ } catch (err) {
359
+ this.#log("mode-apply-failed", { message: describe(err) });
360
+ }
361
+ if (turn.closed) return;
362
+
363
+ // Timers: overall (turn deadline, pause-aware) + idle (inactivity).
364
+ this.#armOverall(turn);
365
+ this.#armIdle(turn);
366
+ // Estimates cover servers without exact PromptResponse.usage. Native
367
+ // agy replaces them with exact counts when the prompt completes.
368
+ this.#emitLiveEstimate(turn);
369
+
370
+ // Prompt. Updates stream through the connection's onUpdate callback.
371
+ try {
372
+ // Nothing to cancel before the prompt RPC exists; see promptStarted.
373
+ turn.promptStarted = true;
374
+ const result = await conn.prompt(turn.sessionId, request.prompt, request.images, request.contextBlock);
375
+ if (turn.closed) return;
376
+ turn.sawResult = true;
377
+ // Exact PromptResponse.usage supersedes every partial estimate, but
378
+ // its total is a billing sum over all inferences, not context (see
379
+ // #derivedContextTokens): correct it before it reaches pi's gauge.
380
+ let settleUsage: AgyUsage | undefined;
381
+ if (result.usage) {
382
+ settleUsage = this.#contextCorrectedUsage(turn, result.usage);
383
+ this.#emit(turn, { type: "usage", usage: settleUsage });
384
+ }
385
+ const mapped = mapStopReason(result.stopReason);
386
+ this.#settle(turn, {
387
+ conversationId: turn.sessionId,
388
+ status: mapped.status,
389
+ response: turn.response.text,
390
+ usage: settleUsage,
391
+ error: mapped.error,
392
+ finished: true,
393
+ aborted: mapped.aborted,
394
+ });
395
+ } catch (err) {
396
+ if (turn.closed) return;
397
+ const aborted = turn.aborted;
398
+ this.#settle(turn, {
399
+ conversationId: turn.sessionId,
400
+ status: aborted ? "OK" : "ERROR",
401
+ response: turn.response.text,
402
+ error: aborted ? undefined : `ACP prompt failed: ${describe(err)}`,
403
+ finished: true,
404
+ aborted,
405
+ });
406
+ }
407
+ }
408
+
409
+ #makeHandle(turn: ActiveTurn): TurnHandle {
410
+ return {
411
+ id: turn.id,
412
+ outcome: turn.outcome,
413
+ next: () => this.#nextActivity(turn),
414
+ pushExternal: (activity) => this.pushExternal(activity),
415
+ };
416
+ }
417
+
418
+ async #nextActivity(turn: ActiveTurn): Promise<DriverActivity | null> {
419
+ for (;;) {
420
+ if (turn.buffer.length > 0) return turn.buffer.shift() ?? null;
421
+ if (turn.closed) return null;
422
+ await new Promise<void>((r) => turn.wake.push(r));
423
+ }
424
+ }
425
+
426
+ #emit(turn: ActiveTurn, activity: DriverActivity): void {
427
+ if (turn.closed) return;
428
+ if (turn.wake.length > 0) turn.wake.shift()!();
429
+ turn.buffer.push(activity);
430
+ }
431
+
432
+ #onConnectionUpdate(sessionId: string | null, update: unknown): void {
433
+ const turn = this.#active;
434
+ if (!turn || turn.closed) return;
435
+ if (sessionId !== null && sessionId !== turn.sessionId) return;
436
+ if (turn.idleTimer) turn.idleTimer.refresh();
437
+ const mapped = mapUpdate(update);
438
+ if (!mapped) return;
439
+ switch (mapped.kind) {
440
+ case "text": {
441
+ const emit = turn.response.append(mapped.delta);
442
+ if (emit) {
443
+ turn.textDeltas += 1;
444
+ turn.textTokens += estimateTokens(emit);
445
+ turn.toolBatchOpen = false;
446
+ this.#emitLiveEstimate(turn);
447
+ this.#emit(turn, { type: "text", delta: emit });
448
+ }
449
+ return;
450
+ }
451
+ case "thought": {
452
+ if (!mapped.delta) return;
453
+ turn.thoughtDeltas += 1;
454
+ turn.thoughtTokens += estimateTokens(mapped.delta);
455
+ turn.toolBatchOpen = false;
456
+ this.#emitLiveEstimate(turn);
457
+ this.#emit(turn, { type: "thought", delta: mapped.delta });
458
+ return;
459
+ }
460
+ case "usage": {
461
+ // Occupancy frames are real server data, not the Gate B synthetic:
462
+ // surface them live so pi's gauge tracks the turn (toPiUsage only
463
+ // overwrites the fields the activity carries).
464
+ turn.contextUsed = mapped.used;
465
+ this.#emit(turn, { type: "usage", usage: { total_tokens: mapped.used } });
466
+ return;
467
+ }
468
+ case "tool_start": {
469
+ // One inference can issue several calls in parallel (and complete
470
+ // them out of order); the divisor must count inference batches, not
471
+ // frames. A batch opens on the first tool_call after model output
472
+ // and only model output closes it, so interleaved completions and
473
+ // duplicate tool_call frames never split or re-open one.
474
+ if (!turn.toolBatchOpen) {
475
+ turn.toolBatches += 1;
476
+ turn.toolBatchOpen = true;
477
+ }
478
+ const entry = { name: mapped.name, args: mapped.args, diff: mapped.diff, mcpServer: mapped.mcpServer };
479
+ turn.toolCalls.set(mapped.toolCallId, entry);
480
+ this.#emit(turn, { type: "tool_start", name: mapped.name, args: mapped.args, mcpServer: mapped.mcpServer, toolCallId: mapped.toolCallId });
481
+ return;
482
+ }
483
+ case "tool_done": {
484
+ let entry = turn.toolCalls.get(mapped.toolCallId);
485
+ if (!entry && turn.toolCalls.size === 1) {
486
+ // The server can finish an approved tool under a different id.
487
+ // Adopt only when exactly one call is pending: with concurrent
488
+ // tools, guessing would attach an edit diff to the wrong file.
489
+ // Residual: an unrelated done with an unknown id still pairs
490
+ // with the pending entry; strictly better than guessing ANY id.
491
+ entry = turn.toolCalls.values().next().value;
492
+ turn.toolCalls.clear();
493
+ }
494
+ turn.toolCalls.delete(mapped.toolCallId);
495
+ const name = entry?.name ?? "tool";
496
+ const args = entry?.args ?? {};
497
+ // Native diff from the stored tool_call frame; the update's own
498
+ // diff (future builds) wins when present.
499
+ this.#emit(turn, { type: "tool_done", name, args, output: mapped.output, diff: mapped.diff ?? entry?.diff, mcpServer: mapped.mcpServer ?? entry?.mcpServer, toolCallId: mapped.toolCallId });
500
+ return;
501
+ }
502
+ case "tool_error": {
503
+ const entry = turn.toolCalls.get(mapped.toolCallId);
504
+ turn.toolCalls.delete(mapped.toolCallId);
505
+ const name = entry?.name ?? "tool";
506
+ this.#emit(turn, { type: "tool_error", name, message: mapped.message, mcpServer: mapped.mcpServer ?? entry?.mcpServer, toolCallId: mapped.toolCallId });
507
+ return;
508
+ }
509
+ case "replay_user":
510
+ return; // load replay: history, never live text
511
+ }
512
+ }
513
+
514
+ #onConnectionExit(conn: AcpConnection, info: { code: number | null; signal: string | null; stderrTail: string }): void {
515
+ if (this.#conn !== conn) {
516
+ // A replaced connection can report its death after the replacement
517
+ // spawns: its turn is long gone and the new connection owns the
518
+ // driver state. Clobbering #conn here would orphan the live one.
519
+ this.#log("stale-connection-exited", { tail: info.stderrTail.slice(-200) });
520
+ return;
521
+ }
522
+ const turn = this.#active;
523
+ this.#conn = undefined;
524
+ this.#connAgent = undefined;
525
+ this.#state = "dead";
526
+ // Teardown exits (abort kill, shutdown, idle recycle) are deliberate:
527
+ // their stderr tail must never reach the UI. Only a live turn dying
528
+ // mid-flight is user-reportable, and it surfaces as a normal turn
529
+ // error, not as raw console noise.
530
+ const turnActive = Boolean(turn && !turn.closed && !turn.aborted && !turn.sawResult);
531
+ this.#log("connection-exited", {
532
+ expected: !turnActive,
533
+ code: info.code,
534
+ signal: info.signal,
535
+ tail: info.stderrTail.slice(-200),
536
+ });
537
+ if (!turn || turn.closed) return;
538
+ if (turn.aborted || turn.sawResult) {
539
+ this.#settle(turn, {
540
+ conversationId: turn.sessionId,
541
+ status: turn.response.text.length > 0 || turn.sawResult ? "OK" : "UNKNOWN",
542
+ response: turn.response.text,
543
+ finished: true,
544
+ aborted: turn.aborted,
545
+ });
546
+ return;
547
+ }
548
+ // A silent death (no stderr) leaves only the exit code/signal as a
549
+ // clue; surface it so the failure is not a bare "exited unexpectedly".
550
+ const where = info.signal ? ` (signal ${info.signal})` : info.code !== null ? ` (code ${info.code})` : "";
551
+ this.#failTurn(turn, `Antigravity session exited unexpectedly${where}; it restarts on the next turn`);
552
+ }
553
+
554
+ #ensureConnection(request: DriverTurnRequest): Promise<AcpConnection> {
555
+ if (this.#conn?.alive) return Promise.resolve(this.#conn);
556
+ this.#generation += 1;
557
+ this.#state = "starting";
558
+ this.#stats.spawns += 1;
559
+ const restricted = Boolean(request.agent);
560
+ this.#connAgent = request.agent;
561
+ const conn = new AcpConnection({
562
+ bin: typeof this.#opts.bin === "function" ? this.#opts.bin() : this.#opts.bin,
563
+ binArgs: typeof this.#opts.binArgs === "function" ? this.#opts.binArgs() : this.#opts.binArgs,
564
+ isolateHome: this.#opts.isolateHome,
565
+ agent: request.agent,
566
+ includeDefaultCustomizations: restricted ? false : undefined,
567
+ agentsRoot: this.#opts.agentsRoot,
568
+ extraEnv: this.#opts.extraEnv,
569
+ cwd: request.cwd,
570
+ mcpServers: this.#opts.mcpServers,
571
+ log: (msg, data) => this.#log(msg, data),
572
+ // Fail-closed permissions: skipPermissions answers allow; a standing
573
+ // policy override (approvals.mode allow) may widen that; everything
574
+ // else goes to the human handler or denies.
575
+ permissions: () =>
576
+ this.#active?.request.skipPermissions
577
+ ? "auto"
578
+ : (this.#opts.permissionPolicy?.() ?? "deny"),
579
+ onPermissionRequest: this.#opts.onPermissionRequest
580
+ ? (req) => this.#parkForPermission(req)
581
+ : undefined,
582
+ permissionParkMs: this.#opts.permissionParkMs,
583
+ onUpdate: (sessionId, update) => this.#onConnectionUpdate(sessionId, update),
584
+ onExit: (info) => this.#onConnectionExit(conn, info),
585
+ });
586
+ this.#conn = conn;
587
+ this.#log("spawn", { bin: typeof this.#opts.bin === "function" ? this.#opts.bin() : this.#opts.bin });
588
+ return conn
589
+ .start()
590
+ .then(() => {
591
+ this.#serverVersion = conn.serverVersion();
592
+ const info = conn.agentInfo as { name?: unknown; title?: unknown } | undefined;
593
+ this.#agentInfo = {
594
+ name: typeof info?.name === "string" ? info.name : undefined,
595
+ title: typeof info?.title === "string" ? info.title : undefined,
596
+ };
597
+ this.#state = "ready";
598
+ return conn;
599
+ })
600
+ .catch((err) => {
601
+ // A server that spawned but failed the handshake (init timeout,
602
+ // auth hang) must not leak: it is detached, so it outlives pi.
603
+ this.#state = "dead";
604
+ this.#conn = undefined;
605
+ this.#connAgent = undefined;
606
+ conn.kill();
607
+ this.#log("start-failed", { message: describe(err) });
608
+ throw err;
609
+ });
610
+ }
611
+
612
+ /** Send native cancellation, then wait for the prompt or tear down. */
613
+ async #abortTurn(turn: ActiveTurn): Promise<void> {
614
+ if (turn.closed) return;
615
+ turn.aborted = true;
616
+ turn.abortedBy = "signal";
617
+ const conn = this.#conn;
618
+ // No session yet (killed during setup), no live connection, or a server
619
+ // already known not to implement cancel: teardown directly.
620
+ if (!conn?.alive || turn.sessionId === "" || !turn.promptStarted) {
621
+ this.#teardownAbort(turn);
622
+ return;
623
+ }
624
+ try {
625
+ conn.cancel(turn.sessionId);
626
+ // Cancel accepted: the prompt result (stopReason cancelled) settles
627
+ // the turn through the normal path. Safety net below in case the
628
+ // server never answers.
629
+ const started = this.#nowMs();
630
+ const check = setInterval(() => {
631
+ if (turn.closed) {
632
+ clearInterval(check);
633
+ return;
634
+ }
635
+ if (this.#nowMs() - started > 10_000) {
636
+ clearInterval(check);
637
+ this.#teardownAbort(turn);
638
+ }
639
+ }, 250);
640
+ } catch (err) {
641
+ this.#log("cancel-failed", { message: describe(err) });
642
+ this.#teardownAbort(turn);
643
+ }
644
+ }
645
+
646
+ /** Gate D teardown: reject everything pending, kill the process. The turn
647
+ * settles through the connection-exit path as aborted. */
648
+ #teardownAbort(turn: ActiveTurn): void {
649
+ this.#stats.kills += 1;
650
+ this.#log("teardown-abort", { sessionId: turn.sessionId });
651
+ turn.aborted = true;
652
+ this.#conn?.abortAll("abort: connection torn down");
653
+ this.#conn?.kill();
654
+ }
655
+
656
+ #createTurn(request: DriverTurnRequest): ActiveTurn {
657
+ let resolve!: (o: TurnOutcome) => void;
658
+ const outcome = new Promise<TurnOutcome>((r) => (resolve = r));
659
+ const turn: ActiveTurn = {
660
+ id: randomUUID().slice(0, 8),
661
+ request,
662
+ sessionId: "",
663
+ buffer: [],
664
+ wake: [],
665
+ closed: false,
666
+ resolve,
667
+ outcome,
668
+ response: new TextAccumulator(),
669
+ textTokens: 0,
670
+ thoughtTokens: 0,
671
+ textDeltas: 0,
672
+ thoughtDeltas: 0,
673
+ estimatedInputTokens: estimateTokens(request.contextBlock?.text ? `${request.prompt}\n${request.contextBlock.text}` : request.prompt),
674
+ toolBatches: 0,
675
+ toolBatchOpen: false,
676
+ contextUsed: undefined,
677
+ sawResult: false,
678
+ promptStarted: false,
679
+ aborted: false,
680
+ abortedBy: null,
681
+ parks: 0,
682
+ overallDeadline: null,
683
+ overallRemainingMs: null,
684
+ toolCalls: new Map(),
685
+ };
686
+ return turn;
687
+ }
688
+
689
+ // --- timers ----------------------------------------------------------------
690
+
691
+ #overallBudgetMs(turn: ActiveTurn): number {
692
+ return (turn.request.timeoutMin ?? 10) * 60_000;
693
+ }
694
+
695
+ #idleBudgetMs(turn: ActiveTurn): number {
696
+ return (turn.request.inactivityMin ?? 5) * 60_000;
697
+ }
698
+
699
+ #nowMs(): number {
700
+ return Date.now();
701
+ }
702
+
703
+ #armOverall(turn: ActiveTurn): void {
704
+ const budget = this.#overallBudgetMs(turn);
705
+ if (turn.overallTimer) clearTimeout(turn.overallTimer);
706
+ // Parked before timers armed (setup-time park): the turn is PAUSED from
707
+ // birth. Keep the pause invariant (deadline === null) and store the full
708
+ // budget; kickIdle() resumes the timer on unpark. A stale non-null
709
+ // deadline here would make the next #pauseOverall recompute the
710
+ // remaining budget against a wall-clock instant that never ran.
711
+ if (turn.parks > 0) {
712
+ turn.overallDeadline = null;
713
+ turn.overallRemainingMs = budget;
714
+ return;
715
+ }
716
+ turn.overallRemainingMs = null;
717
+ this.#startOverallTimer(turn, budget);
718
+ }
719
+
720
+ #startOverallTimer(turn: ActiveTurn, ms: number): void {
721
+ // 0 disables the deadline (config turnTimeoutMin: 0). setTimeout(fn, 0)
722
+ // would fire instantly and kill every turn, guard or not.
723
+ if (ms <= 0) return;
724
+ // The deadline lives HERE, not just in the callers: the running branch
725
+ // of #armOverall never assigns it, and #pauseOverall keys off
726
+ // `deadline !== null` to do anything at all. Without this line every
727
+ // post-arm park is a silent no-op and the timer ticks through the park.
728
+ turn.overallDeadline = this.#nowMs() + ms;
729
+ turn.overallTimer = setTimeout(() => {
730
+ if (turn.closed) return;
731
+ turn.abortedBy = "timer";
732
+ this.#log("timeout", { sessionId: turn.sessionId });
733
+ this.#conn?.abortAll("turn deadline");
734
+ this.#conn?.kill();
735
+ this.#failTurn(turn, `ACP turn exceeded the ${(this.#overallBudgetMs(turn) / 60_000) | 0}m deadline`);
736
+ }, ms);
737
+ }
738
+
739
+ /** Pause WITHOUT resetting the deadline (remaining-budget semantics: the
740
+ * overall timer is a turn deadline, not an inactivity guard). */
741
+ #pauseOverall(turn: ActiveTurn): void {
742
+ if (turn.overallDeadline === null) return;
743
+ if (turn.overallTimer) clearTimeout(turn.overallTimer);
744
+ turn.overallTimer = undefined;
745
+ turn.overallRemainingMs = Math.max(0, turn.overallDeadline - this.#nowMs());
746
+ // Null the deadline: a nested park (parks > 1) must not recompute the
747
+ // remaining budget against a stale wall-clock instant — parked time does
748
+ // not consume budget.
749
+ turn.overallDeadline = null;
750
+ }
751
+
752
+ #resumeOverall(turn: ActiveTurn): void {
753
+ if (turn.overallRemainingMs === null) return;
754
+ const remaining = turn.overallRemainingMs;
755
+ turn.overallRemainingMs = null;
756
+ this.#startOverallTimer(turn, remaining);
757
+ }
758
+
759
+ #armIdle(turn: ActiveTurn): void {
760
+ if (turn.idleTimer) clearTimeout(turn.idleTimer);
761
+ if (turn.parks > 0) return; // parked: idle timer resumes on unpark
762
+ const idleMs = this.#idleBudgetMs(turn);
763
+ // 0 disables the stall guard (config inactivityTimeoutMin: 0).
764
+ if (idleMs <= 0) return;
765
+ turn.idleTimer = setTimeout(() => {
766
+ if (turn.closed) return;
767
+ this.#log("stall", { sessionId: turn.sessionId });
768
+ this.#conn?.abortAll("idle stall");
769
+ this.#conn?.kill();
770
+ this.#failTurn(turn, `ACP stalled for ${(idleMs / 60_000) | 0}m with no output`);
771
+ }, idleMs);
772
+ }
773
+
774
+ #clearIdle(turn: ActiveTurn): void {
775
+ if (turn.idleTimer) clearTimeout(turn.idleTimer);
776
+ turn.idleTimer = undefined;
777
+ }
778
+
779
+ // --- settling ----------------------------------------------------------------
780
+
781
+ #settle(turn: ActiveTurn, outcome: TurnOutcome): void {
782
+ if (turn.closed) return;
783
+ const flushed = turn.response.flush();
784
+ if (flushed) {
785
+ turn.textDeltas += 1;
786
+ turn.textTokens += estimateTokens(flushed);
787
+ this.#emit(turn, { type: "text", delta: flushed });
788
+ }
789
+ outcome.response = turn.response.text;
790
+ // Gate B stopgap: synthesize usage on clean turns while the server sends
791
+ // none. Runs BEFORE close so the usage activity drains through the
792
+ // normal #nextActivity loop (provider maps it onto partial.usage).
793
+ if (outcome.status === "OK" && !outcome.aborted && outcome.usage === undefined) {
794
+ const usage = this.#syntheticUsage(turn);
795
+ if (usage) {
796
+ outcome.usage = usage;
797
+ this.#emit(turn, { type: "usage", usage });
798
+ }
799
+ }
800
+ turn.closed = true;
801
+ if (turn.overallTimer) clearTimeout(turn.overallTimer);
802
+ if (turn.idleTimer) clearTimeout(turn.idleTimer);
803
+ this.#active = undefined;
804
+ this.#state = this.#conn?.alive ? "ready" : "dead";
805
+ if (outcome.conversationId) this.#lastSessionId = outcome.conversationId;
806
+ for (const wake of turn.wake) wake();
807
+ turn.wake = [];
808
+ if (outcome.aborted && turn.abortedBy === null) turn.abortedBy = "signal";
809
+ turn.resolve(outcome);
810
+ try {
811
+ this.#onTurnEnd?.(outcome);
812
+ } catch {
813
+ /* listener errors must not break settling */
814
+ }
815
+ }
816
+
817
+ #failTurn(turn: ActiveTurn, message: string): void {
818
+ this.#settle(turn, {
819
+ conversationId: turn.sessionId,
820
+ status: "ERROR",
821
+ response: turn.response.text,
822
+ error: message,
823
+ finished: true,
824
+ aborted: turn.aborted,
825
+ });
826
+ }
827
+
828
+ /** Usage synthesis mode, resolved per turn (follows live config). */
829
+ #usageMode(): UsageEstimate {
830
+ const opt = this.#opts.usageEstimate;
831
+ return (typeof opt === "function" ? opt() : opt) ?? "estimate";
832
+ }
833
+
834
+ /** Update Pi's partial usage before the next visible text/thought delta.
835
+ * This is not provider-reported billing or an exact context-window count. */
836
+ #emitLiveEstimate(turn: ActiveTurn): void {
837
+ const usage = this.#syntheticUsage(turn);
838
+ if (usage) this.#emit(turn, { type: "usage", usage });
839
+ }
840
+
841
+ #syntheticUsage(turn: ActiveTurn): AgyUsage | undefined {
842
+ const mode = this.#usageMode();
843
+ if (mode === "off") return undefined;
844
+ // Superseded only by EXACT PromptResponse.usage. Diagnostic usage-shaped
845
+ // frames (context windows, occupancy) must not silence the estimates:
846
+ // the connection outlives turns and no exact data ever replaces them
847
+ // on servers without PromptResponse.usage.
848
+ if (this.#conn?.exactUsageSeen) return undefined;
849
+ const usage = synthesizeUsage({
850
+ mode,
851
+ prompt: turn.request.prompt,
852
+ contextText: turn.request.contextBlock?.text,
853
+ inputTokens: turn.estimatedInputTokens,
854
+ textTokens: turn.textTokens,
855
+ thoughtTokens: turn.thoughtTokens,
856
+ textDeltas: turn.textDeltas,
857
+ thoughtDeltas: turn.thoughtDeltas,
858
+ });
859
+ // Observed occupancy outranks the synthetic gauge guess; the estimate's
860
+ // in/out still feed the status line on servers without PromptResponse.usage.
861
+ if (usage && turn.contextUsed !== undefined) return { ...usage, total_tokens: turn.contextUsed };
862
+ return usage;
863
+ }
864
+
865
+ /** Keep PromptResponse.usage billing fields, replace only the context
866
+ * total. Occupancy frames win; otherwise derive (issue #12, derivation
867
+ * in AGENTS.md). */
868
+ #contextCorrectedUsage(turn: ActiveTurn, usage: AgyUsage): AgyUsage {
869
+ return { ...usage, total_tokens: turn.contextUsed ?? this.#derivedContextTokens(turn, usage) };
870
+ }
871
+
872
+ /** PromptResponse.usage sums input+cacheRead+output over EVERY inference
873
+ * of the prompt, but pi reads Usage.totalTokens as the live context
874
+ * length. Each inference's cacheRead is at least the warm prefix C0, so
875
+ * the batch average lower-bounds C0 and added content reaches the total
876
+ * through the Σinput term; exact at one batch (the raw aggregate). Full
877
+ * derivation in AGENTS.md. */
878
+ #derivedContextTokens(turn: ActiveTurn, usage: AgyUsage): number {
879
+ const input = usage.input_tokens ?? 0;
880
+ const output = usage.output_tokens ?? 0;
881
+ const cacheRead = usage.cache_read_tokens ?? 0;
882
+ return input + output + Math.ceil(cacheRead / (turn.toolBatches + 1));
883
+ }
884
+
885
+ #log(msg: string, data?: unknown): void {
886
+ const line = `${new Date().toISOString().slice(11, 19)} ${msg}${data !== undefined ? ` ${JSON.stringify(data)}` : ""}`;
887
+ this.#lifecycle.push(line);
888
+ if (this.#lifecycle.length > LIFECYCLE_LIMIT) this.#lifecycle.shift();
889
+ this.#opts.log?.(msg, data);
890
+ }
891
+
892
+ // --- TurnDriver surface ----------------------------------------------------
893
+
894
+ async close(reason: "recycle" | "shutdown", cause?: string): Promise<void> {
895
+ this.#log(`close:${reason}${cause ? `:${cause}` : ""}`);
896
+ const turn = this.#active;
897
+ if (turn && !turn.closed) {
898
+ this.#settle(turn, {
899
+ conversationId: turn.sessionId,
900
+ status: "ERROR",
901
+ response: turn.response.text,
902
+ error: `ACP driver ${reason === "recycle" ? "recycled" : "shut down"} mid-turn${cause ? ` (${cause})` : ""}`,
903
+ finished: true,
904
+ aborted: false,
905
+ });
906
+ }
907
+ this.#conn?.abortAll(`driver ${reason}`);
908
+ this.#conn?.kill();
909
+ this.#conn = undefined;
910
+ this.#connAgent = undefined;
911
+ this.#state = "dead";
912
+ }
913
+
914
+ snapshot(): DriverSnapshot {
915
+ return {
916
+ state: this.#state,
917
+ pid: this.#conn?.pid,
918
+ conversationId: this.#active?.sessionId ?? this.#lastSessionId,
919
+ stats: {
920
+ spawns: this.#stats.spawns,
921
+ turns: this.#stats.turns,
922
+ reused: 0,
923
+ recycles: this.#stats.kills,
924
+ lastRecycleReason: undefined,
925
+ recycleReasons: {},
926
+ },
927
+ lifecycle: [...this.#lifecycle],
928
+ engine: "acp",
929
+ acp: {
930
+ sessionId: this.#active?.sessionId ?? this.#lastSessionId,
931
+ prompts: this.#stats.turns,
932
+ sessionsCreated: this.#stats.sessionsCreated,
933
+ sessionsLoaded: this.#stats.sessionsLoaded,
934
+ kills: this.#stats.kills,
935
+ serverVersion: this.#serverVersion,
936
+ // Connections beyond the first are server restarts (Gate D kills,
937
+ // stale-exit replacements) = reconnects.
938
+ reconnects: Math.max(0, this.#stats.spawns - 1),
939
+ agentName: this.#agentInfo?.name,
940
+ agentTitle: this.#agentInfo?.title,
941
+ usageSeen: this.#conn?.usageSeen ?? false,
942
+ },
943
+ };
944
+ }
945
+ }
946
+
947
+ function describe(err: unknown): string {
948
+ if (err instanceof Error) return err.message;
949
+ return String(err);
950
+ }
951
+
952
+ // re-exported for the extension's doctor (server version display)
953
+ export type { AcpMcpServer } from "./connection.js";