@herbertgao/pi-extensions 2026.11.18 → 2026.11.19

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