@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,2214 @@
1
+ // The pi provider: streamSimple(model, context, options) -> AssistantMessageEventStream.
2
+ //
3
+ // For each turn pi calls streamSimple. We:
4
+ // 1. extract the latest user message (agy keeps its own history, so we send
5
+ // only the new prompt, not pi's full transcript)
6
+ // 2. resolve the pi model id to the exact agy model string
7
+ // 3. look up the stored agy conversation id + last streamed step for this
8
+ // pi session (resume) or start fresh
9
+ // 4. spawn agy via runAgyTurn, mapping decoded AgyEvents to pi stream events
10
+ // 5. persist the conversation id + final step idx for the next turn
11
+ //
12
+ // Event mapping (close-on-switch: at most one content block open at a time,
13
+ // matching pi-claude-bridge's lifecycle):
14
+ // agy text -> pi text block (text_start / text_delta / text_end)
15
+ // agy thinking -> pi thinking block
16
+ // agy tool -> pi thinking block, labelled "[agy tool: <name>]"
17
+ // We do NOT emit toolCall blocks: agy runs its OWN closed tool loop, so there
18
+ // is no toolUse stopReason and no tool-result delivery path back to pi.
19
+
20
+ import {
21
+ createAssistantMessageEventStream,
22
+ getCurrentSystemPrompt,
23
+ getCurrentTools,
24
+ type AssistantMessage,
25
+ type AssistantMessageEventStream,
26
+ type JsonValue,
27
+ type Message,
28
+ type Model,
29
+ type SimpleStreamOptions,
30
+ type ThinkingLevel,
31
+ type TranscriptContext,
32
+ type Usage,
33
+ } from "@earendil-works/pi-ai";
34
+ import fs from "node:fs";
35
+ import type { Api } from "@earendil-works/pi-ai";
36
+ import type { DriverActivity, TurnDriver, TurnHandle } from "./driver-types.js";
37
+ import { looksBackgroundNativeCall } from "./background-watch.js";
38
+ import { SubagentRoster } from "./subagent-roster.js";
39
+ import { clampOverflowUsage, toPiUsage } from "./stream-events.js";
40
+ import { mapAgyToolToNative } from "./native-tools.js";
41
+ import { toAgyEffort, type AgyModelEntry } from "./models.js";
42
+ import { SessionStore } from "./sessions.js";
43
+ import { detectQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
44
+ import { loadConfig } from "./config.js";
45
+ import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-gate.js";
46
+ import type { ApprovalDecision, ApprovalPayload, ApprovalParkApi } from "./mcp-server.js";
47
+ import path from "node:path";
48
+ import { TurnDiffContext, createExecGitOps, formatInlineDiff, parseEditToolInput } from "./diff-render.js";
49
+ import { stageSyspromptAgent } from "./sysprompt-agent.js";
50
+ import { buildImageNote, stagePromptImages } from "./prompt-images.js";
51
+
52
+ const DEFAULT_TIMEOUT_MIN = 10;
53
+
54
+ /** Warned once per process: config.agent set while the system prompt needs
55
+ * the staged carrier agent (issue #2 inline-block fallback). */
56
+ let warnedUserAgentConflict = false;
57
+
58
+ /** Set of caller-scoped tool names declared by pi-observational-memory background workers.
59
+ * Antigravity models run a closed tool loop on the backend CLI/ACP process and do not
60
+ * support caller-scoped local tools. */
61
+ export const OM_WORKER_TOOL_NAMES = new Set([
62
+ "record_observations",
63
+ "record_reflections",
64
+ "drop_observations",
65
+ ]);
66
+
67
+ /** Detect if a turn belongs to a pi-observational-memory background worker. */
68
+ export function isObservationalMemoryContext(context: TranscriptContext): boolean {
69
+ const currentTools = getCurrentTools(context.messages);
70
+ return currentTools.some((t) => OM_WORKER_TOOL_NAMES.has(t.name));
71
+ }
72
+
73
+ /** Track whether we have warned about observational-memory tool mismatch in this process. */
74
+ let warnedObservationalMemoryMismatch = false;
75
+
76
+ /** Reset latch for unit testing. */
77
+ export function _resetObservationalMemoryWarnedForTesting(): void {
78
+ warnedObservationalMemoryMismatch = false;
79
+ }
80
+
81
+ /** conversationId -> staged carrier agent name. Gate-closed turns look the
82
+ * name up here so a conversation's agent field never flips: a change would
83
+ * recycle the agy process mid-conversation (profile drift), and a respawn
84
+ * must reload THAT conversation's own staged instructions. Content-addressed
85
+ * staging (one dir per body) keeps sibling conversations from overwriting
86
+ * each other's files. */
87
+ const stagedAgentByConversation = new Map<string, string>();
88
+
89
+ /** Zero-usage helper. agy doesn't expose token counts; pi's cost math gets
90
+ * zeros (we're not billing through this provider). */
91
+ function zeroUsage(): Usage {
92
+ return {
93
+ input: 0,
94
+ output: 0,
95
+ cacheRead: 0,
96
+ cacheWrite: 0,
97
+ totalTokens: 0,
98
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
99
+ };
100
+ }
101
+
102
+ /** Extract the latest user message as a flat prompt string. agy maintains its
103
+ * own conversation history via --conversation, so we collapse pi's structured
104
+ * message to text. Returns null if the last message isn't a user message. */
105
+ function extractUserPrompt(context: TranscriptContext): string | null {
106
+ const last = context.messages[context.messages.length - 1];
107
+ if (!last || last.role !== "user") return null;
108
+ const content = last.content;
109
+ if (typeof content === "string") return content;
110
+ // Flatten text blocks; images ride separately via extractImages (native
111
+ // blocks on ACP, staged files on stream-json via prompt-images.ts).
112
+ return content
113
+ .filter((b): b is { type: "text"; text: string } => b.type === "text")
114
+ .map((b) => b.text)
115
+ .join("\n")
116
+ .trim() || null;
117
+ }
118
+
119
+ /** Image blocks of the latest user message (pi-ai ImageContent: base64 data
120
+ * + mimeType). On the ACP engine they ride session/prompt as native
121
+ * content blocks; on stream-json they are staged to temp files and the
122
+ * prompt names the paths (see prompt-images.ts). */
123
+ function extractImages(context: TranscriptContext): Array<{ data: string; mimeType: string }> {
124
+ const last = context.messages[context.messages.length - 1];
125
+ if (!last || last.role !== "user" || typeof last.content === "string") return [];
126
+ return last.content
127
+ .filter((b): b is { type: "image"; data: string; mimeType: string } => b.type === "image")
128
+ .map((b) => ({ data: b.data, mimeType: b.mimeType }));
129
+ }
130
+
131
+ // --- G1: pi-side context digest --------------------------------------------------
132
+ //
133
+ // agy keeps its OWN conversation history (resumed via --conversation), so it
134
+ // already holds every turn it produced. What it lacks is pi-side context it was
135
+ // never spawned for: pi's compaction summaries and turns handled by OTHER
136
+ // providers (or pi's own tools). pi materializes all of that into
137
+ // context.messages every turn (verified: session-manager.js -> convertToLlm),
138
+ // so we build a DELTA digest from those messages and prepend it to the prompt.
139
+ // No pi patch, no new MCP tool. See docs/PI-BRIDGE-GAPS.md (G1).
140
+
141
+ const COMPACTION_MARKER = "compacted into the following summary";
142
+
143
+ /** Synthetic prompt for a resume turn (issue #8): pi's retry dropped the
144
+ * failed attempt from the projected context (_omitRecoveryAttempt), leaving
145
+ * a toolResult or assistant tail with no live agy turn. The bound
146
+ * conversation already holds the task history, so re-open it with this
147
+ * instead of the unretryable "no user message" hard error (which stalled
148
+ * an unattended session for ~6 hours). The wording must stress not
149
+ * repeating actions: the discarded attempt may have half-run with side
150
+ * effects agy saw but pi never recorded. */
151
+ export const RESUME_PROMPT =
152
+ "[The previous attempt of this turn failed and was discarded. Check your conversation history for the last step you completed, then continue the task from there. Do not repeat completed actions.]";
153
+
154
+ /** Synthetic prompt for resuming into a fresh agy conversation right after pi
155
+ * compacts mid-tool-loop (transcript ends in a toolResult or assistant
156
+ * message after the bound conversation was rotated on session_compact). */
157
+ export const COMPACTION_RESUME_PROMPT =
158
+ "[The conversation was compacted into a summary and moved to a fresh Antigravity session. Continue the task from the compaction summary and any recent context above without repeating completed actions.]";
159
+
160
+ export const DIGEST_PREAMBLE =
161
+ "[The following is context from the broader pi session that this Antigravity turn was not directly spawned for: compaction summaries and turns handled by other providers or pi's own tools. Your own prior turns are already in your conversation history. Use this for continuity only.]";
162
+
163
+ // --- pi system prompt (G10) ----------------------------------------------------
164
+ //
165
+ // pi normalizes the system prompt into the transcript every turn (read via
166
+ // getCurrentSystemPrompt): its own operating instructions
167
+ // plus every AGENTS.md/CLAUDE.md it loaded (global agent dir first, then
168
+ // ancestors). The provider used to drop it, so agy models never saw the user's
169
+ // machine-level or project-level instructions. agy has no system-prompt flag
170
+ // (verified against `agy --help`), so the only delivery path is the prompt
171
+ // text. We prepend it as a delimited block on the FIRST prompt of a fresh
172
+ // conversation only: agy keeps its own history, the block stays byte-identical
173
+ // afterwards, and agy's server-side prompt cache keeps hitting.
174
+
175
+ export const SYSTEM_PROMPT_PREAMBLE =
176
+ "[The following is the system prompt of the pi session that spawned this conversation: operating instructions plus project context (AGENTS.md files). Apply it for this whole conversation.]";
177
+
178
+ export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
179
+
180
+ /** Brief tool-priority note appended inside every system prompt block: agy
181
+ * runs embedded in pi, so its native interactive tools never reach the
182
+ * user. Equivalent Pi Bridge tools must win. Concrete clashes observed
183
+ * live: agy picked its native ask_question over the bridge's
184
+ * ask_user_question and the question never displayed; on ACP its native
185
+ * view_file rejects real filesystem paths (artifact sandbox), so reads of
186
+ * the user's machine must go through the bridge. Rides the systemPrompt
187
+ * gate: the note ships only when the system prompt ships. */
188
+ export const TOOL_PRIORITY_NOTE =
189
+ "[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, execute). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. Extension Pi tools not declared directly are listed in bridge_tool_info; call bridge_tool_info to inspect their description and schema, then call bridge_call_tool to run them. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands. Your turn ends when your reply ends, and pi never waits for agy's own wake-ups: never let a native run_command go to the background (keep WaitMsBeforeAsync at 0 for foreground runs and native commands under two minutes, since longer foreground waits hit pi's idle cap and kill the turn; wrap long commands in timeout and run anything longer through the Pi Bridge bash tool, which keeps it inside your turn, and poll bridge_poll_result if it answers STILL RUNNING) and never use the native schedule tool or timers. A task left running when you reply outlives your turn: its wake-up cannot call Pi Bridge tools, and a delegated subagent session is already gone when it fires.]";
190
+
191
+ /** Assemble the full agy prompt: system prompt block, pi-side digest, user
192
+ * prompt. Empty parts are dropped. Pure; exported for unit testing.
193
+ * Pass systemPrompt only on a fresh conversation (see runTurnDriver). */
194
+ export function buildFullPrompt(
195
+ systemPrompt: string | undefined,
196
+ digest: string,
197
+ prompt: string,
198
+ ): string {
199
+ const parts: string[] = [];
200
+ if (systemPrompt) {
201
+ parts.push(`${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${TOOL_PRIORITY_NOTE}\n\n${SYSTEM_PROMPT_END}`);
202
+ }
203
+ if (digest) {
204
+ parts.push(`${DIGEST_PREAMBLE}\n\n${digest}`);
205
+ }
206
+ if (prompt) {
207
+ parts.push(prompt);
208
+ }
209
+ return parts.join("\n\n---\n\n");
210
+ }
211
+
212
+ /** Flatten any message content shape (string or content-block array) to text.
213
+ * Drops images, thinking, and tool-call blocks. */
214
+ function blocksToText(content: unknown): string {
215
+ if (typeof content === "string") return content;
216
+ if (!Array.isArray(content)) return "";
217
+ return content
218
+ .filter(
219
+ (b): b is { type: "text"; text: string } =>
220
+ typeof b === "object" && b !== null && (b as { type?: string }).type === "text",
221
+ )
222
+ .map((b) => b.text)
223
+ .join("\n");
224
+ }
225
+
226
+ /** A compaction summary arrives wrapped in pi's boilerplate prefix/suffix.
227
+ * Return just the summary body. */
228
+ function stripCompactionWrapping(t: string): string {
229
+ const open = t.indexOf("<summary>");
230
+ const close = t.lastIndexOf("</summary>");
231
+ if (open >= 0 && close > open) return t.slice(open + "<summary>".length, close).trim();
232
+ return t.trim();
233
+ }
234
+
235
+ export interface DigestOptions {
236
+ /** Provider id whose assistant turns are already in agy's own DB and so
237
+ * must be skipped to avoid double-counting. Default "antigravity". */
238
+ ownProvider?: string;
239
+ /** Soft cap on the digest body (0 = unbounded). Default 8000. */
240
+ maxChars?: number;
241
+ /** Conversation binding state. bound=true (default): own-provider turns
242
+ * are already in agy's resumed DB and are skipped. bound=false: the agy
243
+ * conversation holds NOTHING (fresh conversation from a mid-session
244
+ * model switch, an engine switch, or recreation recovery), so
245
+ * own-provider turns and their tool results ship too. */
246
+ bound?: boolean;
247
+ /** Compaction summary identity already delivered in a previous digest
248
+ * (compactionFingerprint of the stripped summary text). Index identity
249
+ * is wrong: pi rebuilds post-compaction transcripts with the summary at
250
+ * the front, so every compaction lands at the same index; content
251
+ * identity ships a NEW summary exactly once. */
252
+ seenSummaryId?: string;
253
+ /** Include the trailing message in the delta window instead of reserving
254
+ * it as the current user prompt. Used when resuming into a fresh
255
+ * post-compaction conversation whose transcript ends in a toolResult or
256
+ * assistant message. Default false. */
257
+ includeLast?: boolean;
258
+ }
259
+
260
+ /** Soft cap on the digest body when no tighter budget applies. */
261
+ const DIGEST_MAX_CHARS = 8000;
262
+
263
+ /** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
264
+ * the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
265
+ * and the dropped turn leaves the conversation permanently unresponsive. */
266
+ const STREAM_JSON_PROMPT_CAP = 25_000;
267
+ /** Headroom under the cap for the staged-image note and prompt framing. */
268
+ const STREAM_JSON_PROMPT_MARGIN = 4_096;
269
+
270
+ /** Per-engine digest cap. ACP ships the digest as an embeddedContext
271
+ resource block: no prompt cap applies, so the default cap stands. On
272
+ stream-json the digest rides inline in the prompt, so it must fit under
273
+ the silent-drop budget alongside the user's own prompt bytes. Returns
274
+ null when the budget is already exhausted (ship nothing rather than a
275
+ digest that would push the turn over the drop cap). */
276
+ export function digestMaxCharsForEngine(engine: string, promptLength: number): number | null {
277
+ if (engine === "acp") return DIGEST_MAX_CHARS;
278
+ const budget = STREAM_JSON_PROMPT_CAP - promptLength - STREAM_JSON_PROMPT_MARGIN;
279
+ return budget > 0 ? Math.min(DIGEST_MAX_CHARS, budget) : null;
280
+ }
281
+
282
+ /** role:timestamp fingerprint of the message a watermark points at (the
283
+ digest boundary). A transcript mutated under the stored count (/tree,
284
+ /fork, per-call context-hook rewrites) changes the boundary message, so a
285
+ stored fingerprint that no longer match es invalidates the delta window
286
+ and the digest falls back to the full delta (the Codex WebSocket
287
+ continuation baseline-check pattern: verify before you trust a counter). */
288
+ export function boundaryFingerprint(m: Message | undefined): string | undefined {
289
+ return m ? `${m.role}:${m.timestamp}` : undefined;
290
+ }
291
+
292
+ /** Index of the most recent compaction summary in the transcript, -1 if none. */
293
+ export function findLastCompactionIdx(messages: Message[]): number {
294
+ for (let i = messages.length - 1; i >= 0; i--) {
295
+ const m = messages[i];
296
+ if (m.role !== "user") continue;
297
+ if (blocksToText(m.content).includes(COMPACTION_MARKER)) return i;
298
+ }
299
+ return -1;
300
+ }
301
+
302
+ /** Content identity of a compaction summary message (length + FNV-1a of the
303
+ stripped text). pi puts every post-compaction summary at the transcript
304
+ front, so index identity would swallow the second compaction; this id
305
+ ships a new summary exactly once. */
306
+ export function compactionFingerprint(m: Message): string {
307
+ const text = stripCompactionWrapping(blocksToText(m.content));
308
+ let hash = 0x811c9dc5;
309
+ for (let i = 0; i < text.length; i++) {
310
+ hash ^= text.charCodeAt(i);
311
+ hash = Math.imul(hash, 0x01000193);
312
+ }
313
+ return `${text.length}:${(hash >>> 0).toString(16)}`;
314
+ }
315
+
316
+ /** Build a delta digest of pi-side context agy was not spawned for: the most
317
+ * recent undelivered compaction summary plus turns since the watermark that
318
+ * were not produced by this provider (in bound mode). Pure: no I/O.
319
+ * Exported for unit testing.
320
+ *
321
+ * Delta, not replay: in bound mode skip our own assistant turns
322
+ * (provider === ownProvider) - they are already in agy's resumed DB. In
323
+ * fresh mode (bound: false) the conversation holds nothing, so own turns
324
+ * ship too.
325
+ *
326
+ * Compaction-aware reset: a compaction can shrink the transcript below the
327
+ * stored watermark, which would empty the delta window and silently drop
328
+ * every post-compaction turn. The window instead restarts after the
329
+ * compaction, and the summary itself ships exactly once (tracked by
330
+ * seenSummaryId, content-keyed) to keep steady-state prompts byte-stable.
331
+ *
332
+ * Fidelity note: other-provider assistant turns contribute only their text
333
+ * blocks; tool-call and thinking blocks are dropped. The intent (which tool)
334
+ * is lost, but their results still surface separately as toolResult messages. */
335
+ export function buildContextDigest(
336
+ messages: Message[],
337
+ watermark: number,
338
+ opts: DigestOptions = {},
339
+ ): string {
340
+ const own = opts.ownProvider ?? "antigravity";
341
+ const maxChars = opts.maxChars ?? DIGEST_MAX_CHARS;
342
+ if (messages.length === 0) return "";
343
+
344
+ const deltaParts: string[] = [];
345
+
346
+ // 1. Compaction summary (never in agy's DB, so always high-value), but
347
+ // only when THIS summary has not shipped in a previous digest.
348
+ const compactionIdx = findLastCompactionIdx(messages);
349
+ let summaryPart: string | null = null;
350
+ if (compactionIdx >= 0) {
351
+ const summaryMessage = messages[compactionIdx];
352
+ if (compactionFingerprint(summaryMessage) !== opts.seenSummaryId) {
353
+ summaryPart = `[pi compaction summary]\n${stripCompactionWrapping(blocksToText(summaryMessage.content))}`;
354
+ }
355
+ }
356
+
357
+ // 2. Delta window. Two stale-watermark shapes both clamp to after the
358
+ // compaction: a watermark below it (pre-compaction history is dropped
359
+ // or summarized) and a watermark above the transcript (the compaction
360
+ // shrank the list under the stored count; without the clamp the window
361
+ // would be empty and every post-compaction turn silently dropped).
362
+ // Without a compaction, a watermark above the transcript (branch/prune
363
+ // without a marker) falls back to the full delta.
364
+ let start = Math.max(0, Math.floor(watermark));
365
+ if (compactionIdx >= 0) {
366
+ if (start < compactionIdx + 1 || watermark > messages.length) start = compactionIdx + 1;
367
+ } else if (watermark > messages.length) {
368
+ start = 0;
369
+ }
370
+ const end = opts.includeLast ? messages.length : Math.max(0, messages.length - 1);
371
+ for (let i = start; i < end; i++) {
372
+ const m = messages[i];
373
+ if (m.role === "assistant") {
374
+ if (opts.bound !== false && m.provider === own) continue; // our own turn: already in agy's DB
375
+ const t = blocksToText(m.content).trim();
376
+ if (!t) continue;
377
+ deltaParts.push(`[assistant turn from ${m.provider}]\n${t}`);
378
+ } else if (m.role === "user") {
379
+ const t = blocksToText(m.content);
380
+ if (t.includes(COMPACTION_MARKER)) continue; // delivered as the summary part
381
+ if (!t.trim()) continue;
382
+ deltaParts.push(`[earlier user message]\n${t}`);
383
+ } else if (m.role === "toolResult") {
384
+ const t = blocksToText(m.content).trim();
385
+ deltaParts.push(
386
+ `[tool result: ${m.toolName}${m.isError ? " (error)" : ""}]\n${t || "(no text output)"}`,
387
+ );
388
+ }
389
+ }
390
+
391
+ // Assemble. The compaction summary is clamped to the budget (head kept:
392
+ // a summary reads top-down, and an oversized one must not push a
393
+ // stream-json turn over the silent-drop cap). The DELTA is truncated from
394
+ // the newest end backward when over budget: recent context matters more
395
+ // for continuity than older detail, so drop the oldest delta first. If
396
+ // even the newest single item exceeds the budget, keep its tail slice.
397
+ const SEP = "\n\n";
398
+ const MARKER = "[truncated]";
399
+ if (summaryPart && maxChars > 0 && summaryPart.length > maxChars) {
400
+ const room = Math.max(0, maxChars - MARKER.length - 1);
401
+ summaryPart = `${summaryPart.slice(0, room)}\n${MARKER}`;
402
+ }
403
+ let delta = deltaParts.join(SEP);
404
+ if (maxChars > 0) {
405
+ const budget = Math.max(0, maxChars - (summaryPart ? summaryPart.length + SEP.length : 0));
406
+ if (delta.length > budget) {
407
+ const kept: string[] = [];
408
+ let used = 0;
409
+ for (let i = deltaParts.length - 1; i >= 0; i--) {
410
+ const cost = deltaParts[i].length + (kept.length > 0 ? SEP.length : 0);
411
+ if (used + cost > budget) break;
412
+ kept.unshift(deltaParts[i]);
413
+ used += cost;
414
+ }
415
+ if (kept.length > 0) {
416
+ delta = `${MARKER}\n${kept.join(SEP)}`;
417
+ } else {
418
+ const room = Math.max(0, budget - MARKER.length - 1);
419
+ delta = room > 0 ? `${MARKER}\n${deltaParts[deltaParts.length - 1].slice(-room)}` : "";
420
+ }
421
+ }
422
+ }
423
+
424
+ return [summaryPart, delta]
425
+ .filter((s): s is string => typeof s === "string" && s.length > 0)
426
+ .join(SEP);
427
+ }
428
+
429
+ /** Build a fresh AssistantMessage shell for this turn. Mutated as blocks
430
+ * stream; passed as `partial` with every event. */
431
+ function newAssistant(model: Model<Api>): AssistantMessage {
432
+ return {
433
+ role: "assistant",
434
+ content: [],
435
+ api: model.api,
436
+ provider: model.provider,
437
+ model: model.id,
438
+ usage: zeroUsage(),
439
+ stopReason: "stop",
440
+ timestamp: Date.now(),
441
+ };
442
+ }
443
+
444
+ /** Session key: prefer pi's sessionId (stable per conversation), fall back to
445
+ * cwd so a single pi process still resumes correctly when sessionId is absent. */
446
+ export function sessionKey(
447
+ options: SimpleStreamOptions | undefined,
448
+ cwd: string,
449
+ engine: "stream-json" | "acp",
450
+ ): string {
451
+ const sid = (options as { sessionId?: string } | undefined)?.sessionId;
452
+ const base = sid && sid.length > 0 ? `sid:${sid}` : `cwd:${cwd}`;
453
+ // Engine-scoped keys (plan 9.4): one ACP turn must never touch the stream
454
+ // binding and vice versa. Un-suffixed keys = stream-json, byte-compatible with
455
+ // every store that predates the ACP engine.
456
+ return base + (engine === "acp" ? "@acp" : "");
457
+ }
458
+
459
+ /** Rotate the bound agy conversation after pi compacts the session.
460
+ * Deleting the binding forces the next turn onto a fresh agy conversation so
461
+ * server-side context is freed alongside pi's transcript; recording the key
462
+ * in `pendingCompactionHandoff` guarantees a one-shot compaction handoff even
463
+ * when `config.digest` is disabled. Returns the rotated conversation id, or
464
+ * null when the session had no binding. */
465
+ export function rotateSessionOnCompaction(
466
+ store: SessionStore,
467
+ key: string,
468
+ pendingCompactionHandoff?: Set<string>,
469
+ ): string | null {
470
+ const existing = store.get(key);
471
+ if (!existing) return null;
472
+ store.delete(key);
473
+ stagedAgentByConversation.delete(existing.conversationId);
474
+ pendingCompactionHandoff?.add(key);
475
+ return existing.conversationId;
476
+ }
477
+
478
+ /** Track which content block is currently open so we close-on-switch.
479
+ * At most one of textIdx / thinkingIdx is non-null at a time. */
480
+ export interface BlockState {
481
+ partial: AssistantMessage;
482
+ textIdx: number | null;
483
+ thinkingIdx: number | null;
484
+ started: boolean;
485
+ }
486
+
487
+ export interface NativeDisplayEvent {
488
+ name: string;
489
+ mcpServer?: string;
490
+ status: "started" | "completed" | "failed";
491
+ /** Bridge callId from the tool args (poll calls carry one); lets the
492
+ * extension resolve the polled pi tool via the escalation registry. */
493
+ callId?: string;
494
+ path?: string;
495
+ command?: string;
496
+ output?: string;
497
+ diff?: string;
498
+ }
499
+
500
+ export interface StreamSimpleDeps {
501
+ entries: AgyModelEntry[];
502
+ store: SessionStore;
503
+ /** Stream-json driver (the tested default engine). Turns run on the
504
+ * driver and bridge calls park as toolUse round-trips. Required with
505
+ * roundTrips. */
506
+ driver?: TurnDriver;
507
+ /** Official-server ACP engine (the default engine). Selected via
508
+ * config.engine = "acp"; when absent the config switch falls back to
509
+ * the stream driver. */
510
+ acpDriver?: TurnDriver;
511
+ roundTrips?: ToolRoundTrips;
512
+ /** Replay store for the display-only antigravity wrapper tool. Required
513
+ * for native re-exec and wrapper cards; without it tool steps render as
514
+ * thinking labels only. */
515
+ replay?: WrapperReplay;
516
+ /** Whether a pi tool is active in the session; native re-exec toolCalls
517
+ * are only emitted for active builtins (else the wrapper). */
518
+ nativeActive?: (name: string) => boolean;
519
+ /** Engine latched at extension load. When omitted, the per-call config
520
+ * read decides (tests); production wiring always passes it so a
521
+ * mid-session config flip cannot move one side of a parked turn. */
522
+ engine?: "stream-json" | "acp";
523
+ /** Output-only ACP tool events; persisted as TUI entries, never sent to
524
+ * Antigravity or dispatched through Pi's executable tools. */
525
+ onNativeEvent?: (event: NativeDisplayEvent) => void;
526
+ /** agy backgrounded native work this turn (see DriverDeps). */
527
+ onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
528
+ /** Subagent roster (both engines); folded from every activity. */
529
+ roster?: SubagentRoster;
530
+ /** Session keys rotated on `session_compact` awaiting a one-shot
531
+ * compaction handoff into a fresh agy conversation. */
532
+ pendingCompactionHandoff?: Set<string>;
533
+ /** Daily file log sink (src/daily-log.ts). Records pre-dispatch turn
534
+ * errors that never create a driver turn (and so never reach onTurnEnd). */
535
+ log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
536
+ }
537
+
538
+ // --- G9: no-patch pi-tool round-trips -----------------------------------------
539
+ //
540
+ // The MCP bridge's onToolCall parks the call here instead of executing it:
541
+ // the pending call is injected into the live driver turn as a bridge_call
542
+ // activity, the provider ends the pi assistant message with stopReason
543
+ // "toolUse" for the REAL pi tool, and pi's own loop executes it (native
544
+ // cards, permissions, hooks). The toolResult arrives in the NEXT stream
545
+ // call's context; resolve() then completes the parked MCP HTTP response and
546
+ // agy continues its still-running turn. No pi patch, no privileged API.
547
+
548
+ const BRIDGE_TIMEOUT_MS = 480_000;
549
+ /** Bounded memory of failed bridge parks (late-delivery tombstones). */
550
+ const MAX_PARK_TOMBSTONES = 64;
551
+
552
+ /** One MCP tool-result content block: text always; image blocks carry base64
553
+ * pixels and ride to the model on BOTH engines (ACP probe 2026-09-05;
554
+ * stream-json probe 2026-09-07: the CLI's MCP client delivers tool-result
555
+ * image content to the model). */
556
+ export interface BridgeContentBlock {
557
+ type: string;
558
+ text?: string;
559
+ data?: string;
560
+ mimeType?: string;
561
+ }
562
+
563
+ export interface BridgeCallResultShape {
564
+ content: BridgeContentBlock[];
565
+ isError: boolean;
566
+ }
567
+
568
+ /** Early-ack sentinel: onToolCall settles with this when the pi tool is still
569
+ * running after escalateAfterMs (~20s). agy's MCP client abandons a
570
+ * tools/call HTTP request at ~180s (observed; see ACP-PROTOCOL-REFERENCE), so
571
+ * slow calls must not hold the request. The bridge answers with
572
+ * formatEscalatedAck and the real result arrives via bridge_poll_result (or,
573
+ * if agy never polls, the late-delivery path). */
574
+ export interface BridgeEscalation {
575
+ escalated: true;
576
+ callId: string;
577
+ name: string;
578
+ }
579
+
580
+ export const POLL_TOOL_NAME = "bridge_poll_result";
581
+
582
+ /** Default quiet period before a park escalates to a poll handle. Well under
583
+ * agy's ~180s request deadline; fast tools never see it. */
584
+ export const ESCALATE_AFTER_MS = 20_000;
585
+
586
+ /** Synchronous window for delegation-shaped tools. pi subagents commonly run
587
+ * 30-120s (issue #6) and orchestrators expect a plain tool result; past this
588
+ * they escalate to the poll path. The ceiling stays under agy's ~180s
589
+ * tools/call abandonment, which would kill the request with no result and no
590
+ * poll handle. */
591
+ export const DELEGATION_ESCALATE_MS = 120_000;
592
+
593
+ /** Names that get the long synchronous window: pi's agent_spawn/agent_wait
594
+ * family, subagent_run-style tools, *delegate*, and the Claude Code-style
595
+ * exact name "Agent" (start-anchored stem so incidental agent_ substrings
596
+ * elsewhere in a name keep the fast ack). Human-gated tools
597
+ * (ask_user_question) deliberately stay on the fast ack: their poll path is
598
+ * load-bearing for permission flows. */
599
+ const DELEGATION_NAME_RE = /subagent|delegate|^agent(_|$)/i;
600
+
601
+ /** Per-call escalation threshold. Config can add extra long-running names
602
+ * (escalateLongTools). */
603
+ export function defaultEscalateAfterMs(name: string, extraLongNames: readonly string[] = []): number {
604
+ return DELEGATION_NAME_RE.test(name) || extraLongNames.includes(name) ? DELEGATION_ESCALATE_MS : ESCALATE_AFTER_MS;
605
+ }
606
+ /** Escalated parks carry a longer TTL: human-gated tools (commit previews,
607
+ * permission dialogs) legitimately block for many minutes. */
608
+ export const ESCALATED_TIMEOUT_MS = 1_800_000;
609
+ /** Human-decision budget for one parked approval (docs/TODO.md 2.5). Same
610
+ * envelope as the G9 park; the staged hook timeout exceeds it with margin
611
+ * (approval-hook.stagedTimeoutSeconds). Exported: the extension needs the
612
+ * same number for hooks.json staging and the hook script deadline. */
613
+ export const APPROVAL_PARK_MS = BRIDGE_TIMEOUT_MS;
614
+
615
+ export interface PollView {
616
+ state: "running" | "done" | "failed";
617
+ name: string;
618
+ text?: string;
619
+ isError?: boolean;
620
+ reason?: string;
621
+ images?: Array<{ data: string; mimeType: string }>;
622
+ /** A terminal result the model already received via a poll. Set only by
623
+ * markDelivered (the real poll path); poll() stays pure so internal
624
+ * peeks (escalatedNames) never mark. */
625
+ delivered?: boolean;
626
+ /** The agy conversation this call belongs to. Stamped at turn end so an
627
+ * unpolled result can be re-delivered to the right conversation
628
+ * (first-turn parks never reach the provider's store.set). */
629
+ conversationId?: string;
630
+ }
631
+
632
+ /** Escalated bridge calls. Bounded: past the cap, oldest settled entries
633
+ * evict first (a running call is never evicted while a newer one is). */
634
+ export class EscalationRegistry {
635
+ #calls = new Map<string, PollView>();
636
+ #trim(): void {
637
+ // Soft cap: only settled entries evict. Evicting a RUNNING call would
638
+ // strand its result (settle becomes a no-op, poll reports unknown), so
639
+ // saturating the cap with in-flight calls grows the map instead.
640
+ // Delivered entries evict first: an undelivered result still has a
641
+ // recovery path (redelivery), a delivered one only serves late polls.
642
+ while (this.#calls.size > MAX_PARK_TOMBSTONES) {
643
+ const settled = [...this.#calls.entries()].filter(([, e]) => e.state !== "running");
644
+ const victim = (settled.find(([, e]) => e.delivered) ?? settled[0])?.[0];
645
+ if (victim === undefined) break;
646
+ this.#calls.delete(victim);
647
+ }
648
+ }
649
+ escalate(callId: string, name: string): void {
650
+ this.#calls.set(callId, { name, state: "running" });
651
+ this.#trim();
652
+ }
653
+ settleDone(callId: string, text: string, isError: boolean, images: Array<{ data: string; mimeType: string }> = []): void {
654
+ const e = this.#calls.get(callId);
655
+ if (!e) return;
656
+ e.state = "done";
657
+ e.text = text;
658
+ e.isError = isError;
659
+ if (images.length > 0) e.images = images;
660
+ this.#trim();
661
+ }
662
+ settleFailed(callId: string, reason: string): void {
663
+ const e = this.#calls.get(callId);
664
+ if (!e) return;
665
+ e.state = "failed";
666
+ e.reason = reason;
667
+ this.#trim();
668
+ }
669
+ poll(callId: string): PollView | undefined {
670
+ const e = this.#calls.get(callId);
671
+ return e ? { ...e } : undefined;
672
+ }
673
+
674
+ /** Record that the model received this terminal result (the real poll
675
+ * path calls this when the view is not running). Running entries and
676
+ * unknown ids are a no-op. */
677
+ markDelivered(callId: string): boolean {
678
+ const e = this.#calls.get(callId);
679
+ if (!e || e.state === "running") return false;
680
+ e.delivered = true;
681
+ return true;
682
+ }
683
+
684
+ /** Single-use claim of a done-but-undelivered result: returns the view
685
+ * and marks it delivered in one step, so a later pass can never deliver
686
+ * it twice. The entry stays pollable for a late model poll. Failed
687
+ * escalations are excluded: their pending entry is gone, so the
688
+ * tombstone path is their single delivery channel. */
689
+ claimUndelivered(callId: string): (PollView & { callId: string }) | undefined {
690
+ const e = this.#calls.get(callId);
691
+ if (!e || e.state !== "done" || e.delivered) return undefined;
692
+ e.delivered = true;
693
+ return { ...e, callId };
694
+ }
695
+
696
+ /** Registry-wide sweep: claim every done-but-undelivered result. A
697
+ * toolResult is consumed by its own pass (resolve deletes the pending
698
+ * entry), so a strand that survives its first pass can only be found
699
+ * here, not in a later pass's results. Failed escalations stay with the
700
+ * tombstone path. */
701
+ claimAllUndelivered(): Array<PollView & { callId: string }> {
702
+ const out: Array<PollView & { callId: string }> = [];
703
+ for (const [callId, e] of this.#calls) {
704
+ const claimed = e.state === "done" && !e.delivered ? { ...e, callId } : undefined;
705
+ if (claimed) {
706
+ e.delivered = true;
707
+ out.push(claimed);
708
+ }
709
+ }
710
+ return out;
711
+ }
712
+
713
+ /** Release a claim whose delivery failed to start (driver.run threw): the
714
+ * result returns to the undelivered pool for the next recovery pass. */
715
+ unclaim(callId: string): void {
716
+ const e = this.#calls.get(callId);
717
+ if (e && e.state === "done") e.delivered = false;
718
+ }
719
+
720
+ /** Stamp every running escalation with the ended turn's conversation id
721
+ * (extensions fire this from onTurnEnd). First stamp wins: the ended
722
+ * turn is the conversation the call was made in; a later turn-end (the
723
+ * call can outlive several turns while a human answers) must not
724
+ * re-route the delivery. Entries that escalate later stay unstamped. */
725
+ stampConversation(conversationId: string): void {
726
+ for (const e of this.#calls.values()) {
727
+ if (e.state === "running") e.conversationId ??= conversationId;
728
+ }
729
+ }
730
+ }
731
+
732
+ export function formatEscalatedAck(e: BridgeEscalation): BridgeCallResultShape {
733
+ return {
734
+ content: [
735
+ {
736
+ type: "text",
737
+ text: [
738
+ `STILL RUNNING: the pi tool "${e.name}" has not finished yet.`,
739
+ `Call ${POLL_TOOL_NAME} with callId "${e.callId}" to get the result. Poll again if it still reports running; you may do other work between polls.`,
740
+ "Do NOT end your turn while this call is unresolved: keep polling until it reports done or failed. Ending the turn strands the result.",
741
+ ].join("\n"),
742
+ },
743
+ ],
744
+ isError: false,
745
+ };
746
+ }
747
+
748
+ export function formatPollAnswer(callId: string, view: PollView | undefined): BridgeCallResultShape {
749
+ if (!view) {
750
+ return {
751
+ content: [
752
+ {
753
+ type: "text",
754
+ text: `Error: no escalated bridge call "${callId}". It either finished within the first seconds (its result is in your original tool result) or the callId is wrong.`,
755
+ },
756
+ ],
757
+ isError: true,
758
+ };
759
+ }
760
+ if (view.state === "running") {
761
+ return {
762
+ content: [{ type: "text", text: `STILL RUNNING: "${view.name}" (callId ${callId}) has not finished. Poll again later.` }],
763
+ isError: false,
764
+ };
765
+ }
766
+ if (view.state === "failed") {
767
+ return {
768
+ content: [{ type: "text", text: `Error: bridge call "${view.name}" (callId ${callId}) failed: ${view.reason}` }],
769
+ isError: true,
770
+ };
771
+ }
772
+ return {
773
+ content: [
774
+ ...(view.images ?? []).map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType })),
775
+ { type: "text", text: view.text || "(no output)" },
776
+ ],
777
+ isError: view.isError ?? false,
778
+ };
779
+ }
780
+
781
+ interface PendingRoundTrip {
782
+ /** "bridge": parked MCP HTTP call; resolve() completes it.
783
+ * "rt": native re-exec / wrapper round-trip; pi already executed, the
784
+ * toolResult only confirms continuation, nothing remote to settle.
785
+ * "approval": parked approval gate decision; resolve() maps the shadow
786
+ * tool result to allow/deny and completes the /approval ticket. */
787
+ kind: "bridge" | "rt" | "approval";
788
+ name: string;
789
+ /** Approval entries only: the agy native tool this decision is for. */
790
+ nativeName?: string;
791
+ /** Approval entries only: park start, for the latency audit field. */
792
+ started?: number;
793
+ resolve?: (r: BridgeCallResultShape | BridgeEscalation) => void;
794
+ reject?: (e: Error) => void;
795
+ timer?: NodeJS.Timeout;
796
+ /** Set when the early-ack fired: the HTTP request was answered with a poll
797
+ * handle, so the settling value must go to the registry, not the socket. */
798
+ escalated?: boolean;
799
+ escalateTimer?: NodeJS.Timeout;
800
+ onAbort?: () => void;
801
+ signal?: AbortSignal;
802
+ }
803
+
804
+ /** Replay store for the display-only `antigravity` wrapper tool. The
805
+ * provider records each mutating agy step's output before emitting the
806
+ * toolUse; the wrapper tool's execute() returns it, so pi renders a real
807
+ * toolCall/toolResult pair without re-running anything. */
808
+ export class WrapperReplay {
809
+ #map = new Map<string, string>();
810
+ set(key: string, output: string): void {
811
+ this.#map.set(key, output);
812
+ }
813
+ get(key: string): string | undefined {
814
+ return this.#map.get(key);
815
+ }
816
+ /** Single-use consume: wrapper execute() takes the entry so stale outputs
817
+ * cannot be enumerated by later callers and the map cannot grow unbounded. */
818
+ take(key: string): string | undefined {
819
+ const v = this.#map.get(key);
820
+ this.#map.delete(key);
821
+ return v;
822
+ }
823
+ get size(): number {
824
+ return this.#map.size;
825
+ }
826
+ }
827
+
828
+ export class ToolRoundTrips {
829
+ #pending = new Map<string, PendingRoundTrip>();
830
+ /** Failed bridge parks: the pi tool keeps running and its toolResult will
831
+ * arrive with the park already gone. Bounded; consumed by the
832
+ * late-delivery path (see buildLateResultPrompt). */
833
+ #dead = new Map<string, { name: string; reason: string }>();
834
+ #escalations = new EscalationRegistry();
835
+ #escalateAfterMs: number | ((name: string) => number);
836
+ #getDriver: () => TurnDriver;
837
+ #log: (s: string, d?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
838
+ /** Approval park controls (mcp-server handle). Assigned by the extension
839
+ * only after at least one shadow tool is registered, so an approval
840
+ * toolUse can never dispatch to the REAL builtin and execute locally. */
841
+ #approvalPark?: ApprovalParkApi;
842
+
843
+ /** Accepts a driver or a getter: with two engines wired, the ACTIVE driver
844
+ * is resolved at call time from config (plan §9.5). */
845
+ constructor(
846
+ driver: TurnDriver | (() => TurnDriver),
847
+ log?: (s: string, d?: unknown, level?: "debug" | "info" | "warn" | "error") => void,
848
+ opts: { escalateAfterMs?: number | ((name: string) => number) } = {},
849
+ ) {
850
+ this.#getDriver = typeof driver === "function" ? driver : () => driver;
851
+ this.#log = log ?? (() => {});
852
+ this.#escalateAfterMs = opts.escalateAfterMs ?? defaultEscalateAfterMs;
853
+ }
854
+
855
+ get pendingIds(): string[] {
856
+ return [...this.#pending.keys()];
857
+ }
858
+
859
+ /** Call ids whose park already failed (tombstones). */
860
+ get deadIds(): string[] {
861
+ return [...this.#dead.keys()];
862
+ }
863
+
864
+ /** Take and clear the tombstone for a failed park, if any. */
865
+ consumeDead(toolCallId: string): { name: string; reason: string } | undefined {
866
+ const dead = this.#dead.get(toolCallId);
867
+ if (!dead) return undefined;
868
+ this.#dead.delete(toolCallId);
869
+ return dead;
870
+ }
871
+
872
+ /** Poll view for an escalated call (undefined when the id never escalated:
873
+ * fast calls settle synchronously and need no handle). */
874
+ poll(callId: string): PollView | undefined {
875
+ return this.#escalations.poll(callId);
876
+ }
877
+
878
+ /** Mark a terminal escalated result as received by the model. Only the
879
+ * real poll path (extensions) calls this; poll() stays pure. */
880
+ markDelivered(callId: string): boolean {
881
+ return this.#escalations.markDelivered(callId);
882
+ }
883
+
884
+ /** Single-use claim of a settled-but-undelivered escalated result (the
885
+ * model ended its turn instead of polling). */
886
+ claimUndelivered(callId: string): (PollView & { callId: string }) | undefined {
887
+ return this.#escalations.claimUndelivered(callId);
888
+ }
889
+
890
+ /** Registry-wide sweep for done-but-undelivered results: a toolResult is
891
+ * consumed by its own pass, so multi-pass strands are only findable
892
+ * here. */
893
+ claimAllUndelivered(): Array<PollView & { callId: string }> {
894
+ return this.#escalations.claimAllUndelivered();
895
+ }
896
+
897
+ /** Release a claim whose delivery failed to start. */
898
+ unclaim(callId: string): void {
899
+ this.#escalations.unclaim(callId);
900
+ }
901
+
902
+ /** Stamp running escalations with the ended turn's conversation id so an
903
+ * unpolled result can be re-delivered to the right conversation. */
904
+ stampConversation(conversationId: string): void {
905
+ this.#escalations.stampConversation(conversationId);
906
+ }
907
+
908
+ /** Wire the approval park (mcp-server handle.approvals). The extension
909
+ * assigns this AFTER the shadow tools are registered; see onApproval. */
910
+ set approvalPark(api: ApprovalParkApi | undefined) {
911
+ this.#approvalPark = api;
912
+ }
913
+
914
+ /** Approval gate (docs/TODO.md 2.5): a PreToolUse hook parked a native agy
915
+ * tool call. Interrupt the pi-side view of the still-running agy turn
916
+ * with a toolUse for the SHADOW tool (same bridge_call mechanism as G9,
917
+ * so both drivers pause their turn timers); pi's permission extensions
918
+ * gate it, the shadow execute() consults the fallback policy, and the
919
+ * arriving toolResult maps to the terminal decision (resolve()).
920
+ * Every failure path denies fail-closed: an approval must never be
921
+ * granted by accident. */
922
+ onApproval(ticket: string, payload: ApprovalPayload): void {
923
+ const deny = (reason: string): void => {
924
+ this.#log("approval-denied-pre-park", { ticket, reason });
925
+ this.#approvalPark?.resolve(ticket, { allow: false, reason });
926
+ };
927
+ if (!this.#approvalPark) return deny("shadow tools are not registered");
928
+ const native = payload?.toolCall?.name;
929
+ if (typeof native !== "string" || native.length === 0) return deny("approval payload has no tool name");
930
+ const handle = this.#getDriver().activeHandle;
931
+ if (!handle) return deny("no active antigravity turn");
932
+ const args = (payload.toolCall.args && typeof payload.toolCall.args === "object"
933
+ ? payload.toolCall.args
934
+ : {}) as Record<string, unknown>;
935
+ const mapped = mapNativeToShadow(native, args);
936
+ if (!mapped) return deny(`tool ${native} did not map to a shadow call (ungated or unresolved target path)`);
937
+ const entry: PendingRoundTrip = {
938
+ kind: "approval",
939
+ name: mapped.shadow,
940
+ nativeName: native,
941
+ started: Date.now(),
942
+ timer: setTimeout(() => {
943
+ this.#failApproval(
944
+ ticket,
945
+ `approval gate timed out after ${Math.round(APPROVAL_PARK_MS / 1000)}s`,
946
+ "timeout",
947
+ );
948
+ }, APPROVAL_PARK_MS),
949
+ };
950
+ this.#pending.set(ticket, entry);
951
+ handle.pushExternal({
952
+ type: "bridge_call",
953
+ callId: ticket,
954
+ name: mapped.shadow,
955
+ args: {
956
+ ...mapped.input,
957
+ [GATE_MARKER]: true,
958
+ __agyTicket: ticket,
959
+ __agyTool: native,
960
+ },
961
+ });
962
+ this.#log("approval-parked", { ticket, native, shadow: mapped.shadow });
963
+ }
964
+
965
+ /** Settle a parked approval with a deny. Used by the park timeout and
966
+ * failAll; the ticket is answered (fail closed) and the pending entry
967
+ * dropped, so the late shadow tool result logs as approval-late. */
968
+ #failApproval(ticket: string, reason: string, cause: "timeout" | "shutdown"): void {
969
+ const entry = this.#pending.get(ticket);
970
+ this.#pending.delete(ticket);
971
+ if (entry?.timer) clearTimeout(entry.timer);
972
+ const resolved = this.#approvalPark?.resolve(ticket, { allow: false, reason }) ?? false;
973
+ this.#log(
974
+ resolved ? `approval-${cause}` : "approval-late",
975
+ { ticket, native: entry?.nativeName, shadow: entry?.name, reason },
976
+ resolved && cause === "timeout" ? "warn" : "debug",
977
+ );
978
+ this.#getDriver().kickIdle();
979
+ }
980
+
981
+ /** Fail all pending calls (driver recycle/shutdown path). Escalated bridge
982
+ * calls are skipped: their HTTP request was already answered with a poll
983
+ * handle, and the agy turn ending does NOT make the still-running pi tool
984
+ * a failure. They settle through resolve(), their own 30m timer, or an
985
+ * abort signal on the pi tool call. */
986
+ failAll(reason: string): void {
987
+ for (const id of [...this.#pending.keys()]) {
988
+ const entry = this.#pending.get(id);
989
+ if (entry?.kind === "approval") {
990
+ this.#failApproval(id, reason, "shutdown");
991
+ continue;
992
+ }
993
+ if (entry?.kind === "bridge" && entry.escalated) continue;
994
+ this.#fail(id, reason);
995
+ }
996
+ }
997
+
998
+ #fail(callId: string, reason: string): void {
999
+ const entry = this.#pending.get(callId);
1000
+ if (!entry) return;
1001
+ if (entry.kind === "rt") {
1002
+ // Nothing to reject, but the entry must not leak past turn death.
1003
+ this.#pending.delete(callId);
1004
+ return;
1005
+ }
1006
+ this.#pending.delete(callId);
1007
+ clearTimeout(entry.timer);
1008
+ if (entry.escalateTimer) clearTimeout(entry.escalateTimer);
1009
+ if (entry.onAbort && entry.signal) entry.signal.removeEventListener("abort", entry.onAbort);
1010
+ this.#dead.set(callId, { name: entry.name, reason });
1011
+ while (this.#dead.size > MAX_PARK_TOMBSTONES) {
1012
+ const oldest = this.#dead.keys().next().value;
1013
+ if (oldest === undefined) break;
1014
+ this.#dead.delete(oldest);
1015
+ }
1016
+ if (entry.escalated) this.#escalations.settleFailed(callId, reason);
1017
+ entry.reject!(new Error(reason));
1018
+ this.#getDriver().kickIdle();
1019
+ this.#log("round-trip-fail", { callId, name: entry.name, reason });
1020
+ }
1021
+
1022
+ /** Park the MCP call: inject into the live agy turn. Fast calls settle
1023
+ * with the real BridgeCallResultShape. Calls still running after
1024
+ * escalateAfterMs settle with a BridgeEscalation sentinel instead: the
1025
+ * bridge answers the HTTP request with a poll handle while pi keeps
1026
+ * executing, so agy's ~180s request deadline is never hit. The real
1027
+ * result reaches agy via bridge_poll_result, or via the late-delivery
1028
+ * path if agy never polls. Fail-closed: timeout/abort still reject. */
1029
+ onToolCall = (
1030
+ callId: string,
1031
+ name: string,
1032
+ args: Record<string, unknown>,
1033
+ signal: AbortSignal,
1034
+ ): Promise<BridgeCallResultShape | BridgeEscalation> => {
1035
+ const handle = this.#getDriver().activeHandle;
1036
+ if (!handle) {
1037
+ return Promise.reject(
1038
+ new Error(
1039
+ "no active antigravity turn; the pi tool bridge only works while an antigravity model is streaming",
1040
+ ),
1041
+ );
1042
+ }
1043
+ return new Promise<BridgeCallResultShape | BridgeEscalation>((resolve, reject) => {
1044
+ const timer = setTimeout(() => {
1045
+ this.#fail(callId, `pi tool round-trip timed out after ${BRIDGE_TIMEOUT_MS / 1000}s`);
1046
+ }, BRIDGE_TIMEOUT_MS);
1047
+ const onAbort = () => this.#fail(callId, "agy disconnected before the tool result arrived");
1048
+ signal.addEventListener("abort", onAbort, { once: true });
1049
+ const entry: PendingRoundTrip = { kind: "bridge", name, resolve, reject, timer, onAbort, signal };
1050
+ const escalateAfterMs = typeof this.#escalateAfterMs === "function" ? this.#escalateAfterMs(name) : this.#escalateAfterMs;
1051
+ if (escalateAfterMs > 0) {
1052
+ entry.escalateTimer = setTimeout(() => {
1053
+ const e = this.#pending.get(callId);
1054
+ // Resolved (or failed) between arm and fire: nothing to escalate.
1055
+ if (!e || e.kind !== "bridge") return;
1056
+ e.escalated = true;
1057
+ // Human-gated calls (commit previews, permission dialogs) can
1058
+ // block far longer than the standard park TTL; re-arm generously.
1059
+ if (e.timer) {
1060
+ clearTimeout(e.timer);
1061
+ e.timer = setTimeout(() => {
1062
+ this.#fail(callId, `escalated bridge call timed out after ${ESCALATED_TIMEOUT_MS / 60_000} minutes`);
1063
+ }, ESCALATED_TIMEOUT_MS);
1064
+ }
1065
+ this.#escalations.escalate(callId, e.name);
1066
+ resolve({ escalated: true, callId, name: e.name });
1067
+ }, escalateAfterMs);
1068
+ }
1069
+ this.#pending.set(callId, entry);
1070
+ // Strip the internal marker fields from model-supplied args (peer
1071
+ // review 2026-09-07): a real bridge call must never arrive at the
1072
+ // shadow's gate branch with a forged __agyGate/__agyTicket.
1073
+ handle.pushExternal({ type: "bridge_call", callId, name, args: stripMarkerFields(args) });
1074
+ });
1075
+ };
1076
+
1077
+ /** Track a native re-exec or wrapper round-trip: pi executes the tool in
1078
+ * its own loop; the arriving toolResult only confirms continuation. */
1079
+ track(id: string, name: string): void {
1080
+ this.#pending.set(id, { kind: "rt", name });
1081
+ }
1082
+
1083
+ /** Complete a parked call from a pi toolResult message. Returns false when
1084
+ * the id matches nothing pending. Image blocks ride the result on both
1085
+ * engines (probe-verified on each); the late-delivery prompt stays
1086
+ * text-only and its images re-attach through driver.run (native blocks on
1087
+ * ACP, staged files on stream-json). */
1088
+ resolve(
1089
+ toolCallId: string,
1090
+ text: string,
1091
+ isError: boolean,
1092
+ images: Array<{ data: string; mimeType: string }> = [],
1093
+ ): boolean {
1094
+ const entry = this.#pending.get(toolCallId);
1095
+ if (!entry) return false;
1096
+ this.#pending.delete(toolCallId);
1097
+ clearTimeout(entry.timer);
1098
+ if (entry.escalateTimer) clearTimeout(entry.escalateTimer);
1099
+ if (entry.onAbort && entry.signal) entry.signal.removeEventListener("abort", entry.onAbort);
1100
+ if (entry.kind === "rt") {
1101
+ this.#log("round-trip-rt-done", { callId: toolCallId, name: entry.name, isError });
1102
+ return true;
1103
+ }
1104
+ if (entry.kind === "approval") {
1105
+ clearTimeout(entry.timer);
1106
+ this.#pending.delete(toolCallId);
1107
+ // Decision mapping (docs/TODO.md 2.5): block/error -> deny with the
1108
+ // text (pi turns a tool_call block into an error tool result, so both
1109
+ // paths land here); synthetic success -> allow.
1110
+ const decision: ApprovalDecision = isError
1111
+ ? { allow: false, reason: text || `blocked by approval gate (${entry.nativeName})` }
1112
+ : { allow: true };
1113
+ const delivered = this.#approvalPark?.resolve(toolCallId, decision) ?? false;
1114
+ // Audit trail (docs/TODO.md 2.7): decision, source, latency.
1115
+ this.#log(
1116
+ delivered ? "approval-decision" : "approval-late",
1117
+ {
1118
+ ticket: toolCallId,
1119
+ native: entry.nativeName,
1120
+ shadow: entry.name,
1121
+ decision: decision.allow ? "allow" : "deny",
1122
+ source: isError ? "extension-block" : "policy",
1123
+ reason: decision.allow ? undefined : decision.reason,
1124
+ latencyMs: Date.now() - (entry.started ?? 0),
1125
+ },
1126
+ delivered ? "info" : "debug",
1127
+ );
1128
+ this.#getDriver().kickIdle();
1129
+ return true;
1130
+ }
1131
+ // Escalated call: the HTTP response already carried the poll handle, so
1132
+ // the result lands in the registry for the next bridge_poll_result. The
1133
+ // original promise settled with the sentinel; re-resolving is a silent
1134
+ // no-op, so gate it to keep that explicit.
1135
+ if (entry.escalated) {
1136
+ this.#escalations.settleDone(toolCallId, text, isError, images);
1137
+ } else {
1138
+ entry.resolve!({
1139
+ content: [
1140
+ ...images.map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType })),
1141
+ { type: "text", text },
1142
+ ],
1143
+ isError,
1144
+ });
1145
+ }
1146
+ this.#getDriver().kickIdle();
1147
+ this.#log("round-trip-resolved", { callId: toolCallId, name: entry.name, isError });
1148
+ return true;
1149
+ }
1150
+ }
1151
+
1152
+ /** Image blocks of a tool result (pi's read on an image file, screenshots).
1153
+ * Forwarded to agy as MCP image content (see BridgeContentBlock) on both
1154
+ * engines. Size relies on pi's own inline-image resize cap upstream; no
1155
+ * second cap here. */
1156
+ function extractResultImages(content: unknown): Array<{ data: string; mimeType: string }> {
1157
+ if (!Array.isArray(content)) return [];
1158
+ return content
1159
+ .filter(
1160
+ (b): b is { type: "image"; data: string; mimeType: string } =>
1161
+ typeof b === "object" && b !== null && (b as { type?: string }).type === "image",
1162
+ )
1163
+ .map((b) => ({ data: b.data, mimeType: b.mimeType }))
1164
+ .filter((i) => typeof i.mimeType === "string" && typeof i.data === "string" && i.data.length > 0);
1165
+ }
1166
+
1167
+ /** Extract toolResult messages whose toolCallId is still parked, as text plus
1168
+ * any image blocks (forwarded as MCP image content on both engines). */
1169
+ export function collectToolResults(
1170
+ messages: Message[],
1171
+ pendingIds: readonly string[],
1172
+ ): Array<{ toolCallId: string; text: string; isError: boolean; images: Array<{ data: string; mimeType: string }> }> {
1173
+ if (pendingIds.length === 0) return [];
1174
+ const pending = new Set(pendingIds);
1175
+ const out: Array<{ toolCallId: string; text: string; isError: boolean; images: Array<{ data: string; mimeType: string }> }> = [];
1176
+ for (const m of messages) {
1177
+ if (m.role !== "toolResult") continue;
1178
+ const id = (m as { toolCallId?: string }).toolCallId;
1179
+ if (!id || !pending.has(id)) continue;
1180
+ out.push({
1181
+ toolCallId: id,
1182
+ text: blocksToText(m.content).trim(),
1183
+ isError: m.isError === true,
1184
+ images: extractResultImages(m.content),
1185
+ });
1186
+ }
1187
+ return out;
1188
+ }
1189
+
1190
+ export interface LateToolResult {
1191
+ /** Escalated results only: the registry callId, so a failed delivery can
1192
+ * unclaim it. Tombstone-borne results have none (already consumed). */
1193
+ callId?: string;
1194
+ name: string;
1195
+ reason: string;
1196
+ text: string;
1197
+ isError: boolean;
1198
+ /** Image blocks of the stranded result (read on an image file). The
1199
+ * redelivery prompt is text-only, so they ride driver.run images. */
1200
+ images?: Array<{ data: string; mimeType: string }>;
1201
+ }
1202
+
1203
+ /** Frame late tool results so agy treats them as the results its bridge calls
1204
+ * never received: a park whose round-trip died while the pi tool ran, or an
1205
+ * escalated result the model never polled. The reason carries the framing. */
1206
+ export function buildLateResultPrompt(late: LateToolResult[], userPrompt?: string): string {
1207
+ const blocks = late.map((r) =>
1208
+ [
1209
+ `pi tool "${r.name}": ${r.reason}.`,
1210
+ r.isError ? "The tool reported an error:" : "Result:",
1211
+ r.text.trim() || "(no output)",
1212
+ ].join("\n"),
1213
+ );
1214
+ const header = "Late tool delivery: treat the following as the results of your earlier tool calls.";
1215
+ const body = [header, ...blocks].join("\n\n");
1216
+ return userPrompt ? `${body}\n\n${userPrompt}` : body;
1217
+ }
1218
+
1219
+ // --- stream-json engine -------------------------------------------------------
1220
+
1221
+ export interface DriverDeps {
1222
+ driver: TurnDriver;
1223
+ roundTrips: ToolRoundTrips;
1224
+ replay?: WrapperReplay;
1225
+ nativeActive?: (name: string) => boolean;
1226
+ onNativeEvent?: (event: NativeDisplayEvent) => void;
1227
+ /** agy backgrounded native work this turn (WaitMsBeforeAsync arg seen).
1228
+ * Fired once at the settled OK end of the turn so the extension can arm
1229
+ * its task watcher (src/background-watch.ts); never on abort or error. */
1230
+ onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
1231
+ /** Subagent roster fold target (both engines; best-effort telemetry). */
1232
+ roster?: SubagentRoster;
1233
+ /** Session keys rotated on `session_compact` awaiting a one-shot
1234
+ * compaction handoff into a fresh agy conversation. */
1235
+ pendingCompactionHandoff?: Set<string>;
1236
+ /** Active engine (config), for engine-scoped session keys. */
1237
+ engine: "stream-json" | "acp";
1238
+ /** Daily file log sink for pre-dispatch errors (see StreamSimpleDeps). */
1239
+ log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
1240
+ }
1241
+
1242
+ /** Map one DriverActivity onto the open pi stream. Returns "parked" when the
1243
+ * activity ended the pi call with a toolUse round-trip. */
1244
+ export interface ActivityFeatures {
1245
+ replay?: WrapperReplay;
1246
+ nativeActive?: (name: string) => boolean;
1247
+ roundTrips?: ToolRoundTrips;
1248
+ engine?: "stream-json" | "acp";
1249
+ onNativeEvent?: (event: NativeDisplayEvent) => void;
1250
+ /** Set by runTurnDriver: latches the background arg shape for the arm
1251
+ * decision at turn end. */
1252
+ onBackgroundArg?: (args: Record<string, unknown>) => void;
1253
+ roster?: SubagentRoster;
1254
+ log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
1255
+ }
1256
+
1257
+ /** Process-wide counter: round-trip ids must never repeat across turns in
1258
+ * one session transcript. */
1259
+ let RT_SEQ = 0;
1260
+ function nextRtId(kind: "nat" | "wrap"): string {
1261
+ return `${kind}-${++RT_SEQ}`;
1262
+ }
1263
+
1264
+ /** Emit a complete toolCall block and end the pi call with toolUse.
1265
+ * pi 0.86 restricts ToolCall.arguments to JSON-compatible values. */
1266
+ function emitToolUse(
1267
+ stream: AssistantMessageEventStream,
1268
+ blocks: BlockState,
1269
+ id: string,
1270
+ name: string,
1271
+ args: Record<string, JsonValue>,
1272
+ ): void {
1273
+ const partial = blocks.partial;
1274
+ closeThinking(stream, blocks);
1275
+ closeText(stream, blocks);
1276
+ const toolCall = { type: "toolCall" as const, id, name, arguments: args };
1277
+ partial.content.push(toolCall);
1278
+ const contentIndex = partial.content.length - 1;
1279
+ stream.push({ type: "toolcall_start", contentIndex, partial });
1280
+ stream.push({ type: "toolcall_end", contentIndex, toolCall, partial });
1281
+ partial.stopReason = "toolUse";
1282
+ stream.push({ type: "done", reason: "toolUse", message: partial });
1283
+ stream.end();
1284
+ }
1285
+
1286
+ /** ACP edit-class tool names that carry a file-path arg and land the file on
1287
+ * disk (observed live: edit_file, create_file, write_file on agy 1.5.11).
1288
+ * Read/execute tools also match the arg-shape heuristic but produce no diff
1289
+ * (unchanged content), so the gate avoids mislabeling them as edits. */
1290
+ const ACP_EDIT_TOOLS = new Set(["edit_file", "create_file", "write_to_file", "write_file"]);
1291
+
1292
+ export function consumeActivity(
1293
+ stream: AssistantMessageEventStream,
1294
+ blocks: BlockState,
1295
+ activity: DriverActivity,
1296
+ diffCtx: TurnDiffContext,
1297
+ cwd: string,
1298
+ feats: ActivityFeatures,
1299
+ ): "parked" | "continue" {
1300
+ const partial = blocks.partial;
1301
+ // Subagent roster folds BEFORE any rendering branch: pure in-memory
1302
+ // telemetry over the same activities both engines emit, and it must see
1303
+ // spawn/message/manage steps regardless of how they render.
1304
+ feats.roster?.fold(activity);
1305
+ switch (activity.type) {
1306
+ case "text":
1307
+ appendText(stream, blocks, activity.delta);
1308
+ return "continue";
1309
+ case "thought":
1310
+ // Stream-json: token count only (no body). ACP: thought TEXT deltas —
1311
+ // rendered through the same thinking block pipeline (9.2).
1312
+ if (typeof activity.delta === "string" && activity.delta.length > 0) {
1313
+ appendThinking(stream, blocks, activity.delta);
1314
+ }
1315
+ return "continue";
1316
+ case "usage":
1317
+ toPiUsage(activity.usage, partial.usage);
1318
+ return "continue";
1319
+ case "tool_start":
1320
+ // Transient status while Antigravity executes; no Pi tool call or
1321
+ // model-facing result is produced. Persist a card only on completion.
1322
+ if (feats.engine === "acp" && feats.onNativeEvent) {
1323
+ try {
1324
+ feats.onNativeEvent({ name: activity.name, mcpServer: activity.mcpServer, status: "started", callId: callIdArg(activity.args) });
1325
+ } catch { /* UI failure must not fail the generation. */ }
1326
+ }
1327
+ if (looksBackgroundNativeCall(activity.args)) feats.onBackgroundArg?.(activity.args);
1328
+ return "continue";
1329
+ /** Bridge callId arg of an MCP tool call (bridge_poll_result requires it). */
1330
+ function callIdArg(args: Record<string, unknown>): string | undefined {
1331
+ const v = args.callId;
1332
+ return typeof v === "string" && v.length > 0 ? v : undefined;
1333
+ }
1334
+
1335
+ /** File-path argument of an ACP edit tool (observed: `file_path`); other
1336
+ * tool kinds (execute, read) don't carry one. Returns undefined for
1337
+ * non-edit tools. */
1338
+ function acpEditFileArg(args: Record<string, unknown>): string | undefined {
1339
+ for (const [k, v] of Object.entries(args)) {
1340
+ if (typeof v === "string" && v.trim() && /file|path/i.test(k)) return v;
1341
+ }
1342
+ return undefined;
1343
+ }
1344
+
1345
+ case "tool_done": {
1346
+ // Gate C (ACP): the server already executed the tool; nothing parks.
1347
+ // Edit display has TWO paths on ACP:
1348
+ // a) native diff in tool_call content[] (future builds / the
1349
+ // permission-request flow carries it; phase-2 probe shape);
1350
+ // b) auto-approved edits can send NO content: the file simply
1351
+ // lands on disk. Read it and diff against git HEAD - the same
1352
+ // output the stream-json engine produces, one readFileSync.
1353
+ if (feats.engine === "acp") {
1354
+ const d = activity.diff;
1355
+ const editFile = ACP_EDIT_TOOLS.has(activity.name) ? acpEditFileArg(activity.args) : undefined;
1356
+ const file = d?.path ?? (editFile ? (path.isAbsolute(editFile) ? editFile : path.resolve(cwd, editFile)) : undefined);
1357
+ let diffText = d ? formatInlineDiff(d.oldText ?? "", d.newText) : undefined;
1358
+ if (!d && file) {
1359
+ let disk = "";
1360
+ try {
1361
+ disk = fs.readFileSync(file, "utf8");
1362
+ } catch {
1363
+ /* deleted or unreadable: diffEdit degrades to a summary */
1364
+ }
1365
+ diffText = diffCtx.diffEdit(file, disk).text;
1366
+ }
1367
+ const command = ["CommandLine", "command_line", "command"].map((k) => activity.args[k]).find((v): v is string => typeof v === "string" && v.length > 0);
1368
+ let displayed = false;
1369
+ try {
1370
+ if (feats.onNativeEvent) {
1371
+ feats.onNativeEvent({ name: activity.name, mcpServer: activity.mcpServer, status: "completed", path: file, command, output: activity.output, diff: diffText, callId: callIdArg(activity.args) });
1372
+ displayed = true;
1373
+ }
1374
+ } catch { /* A stale renderer must never fail the model turn. */ }
1375
+ if (displayed) return "continue";
1376
+ if (file) {
1377
+ appendThinking(stream, blocks, `[agy edit: ${path.basename(file)}]\n`);
1378
+ if (diffText) appendThinking(stream, blocks, `${diffText}\n`);
1379
+ } else {
1380
+ appendThinking(stream, blocks, `[agy tool: ${activity.name}]\n`);
1381
+ }
1382
+ return "continue";
1383
+ }
1384
+ // G8 (stream-json): agy file edits surface a git-sourced diff in a
1385
+ // thinking block. The server sends no diff here, so OLD comes from git.
1386
+ let inputJson: string | undefined;
1387
+ try {
1388
+ inputJson = JSON.stringify(activity.args);
1389
+ } catch {
1390
+ inputJson = undefined;
1391
+ }
1392
+ const edit = inputJson ? parseEditToolInput(inputJson) : null;
1393
+ if (edit) {
1394
+ const absFile = path.isAbsolute(edit.file) ? edit.file : path.resolve(cwd, edit.file);
1395
+ const outcome = diffCtx.diffEdit(absFile, edit.content);
1396
+ const label = edit.description ?? path.basename(absFile);
1397
+ appendThinking(stream, blocks, `[agy edit: ${label}]\n`);
1398
+ if (outcome.text) appendThinking(stream, blocks, `${outcome.text}\n`);
1399
+ } else {
1400
+ appendThinking(stream, blocks, `[agy tool: ${activity.name}]\n`);
1401
+ }
1402
+ // Native re-exec: read-only agy tools re-run as REAL pi builtins so
1403
+ // their cards render natively. Everything else replays through the
1404
+ // display-only wrapper tool. Both end the pi call with toolUse and
1405
+ // resume on the toolResult continuation. Without a replay store
1406
+ // (feature off) keep the label-only behavior.
1407
+ if (!feats.replay || !feats.roundTrips) return "continue";
1408
+ if (activity.name === "call_mcp_tool") return "continue";
1409
+ const mapped = mapAgyToolToNative(activity.name, activity.args);
1410
+ if (mapped && (!feats.nativeActive || feats.nativeActive(mapped.tool))) {
1411
+ const id = nextRtId("nat");
1412
+ feats.roundTrips.track(id, mapped.tool);
1413
+ // pi requires a reasoning argument on read/edit-class builtin calls
1414
+ // (validated against the wrapped schema); harmless where absent.
1415
+ emitToolUse(stream, blocks, id, mapped.tool, {
1416
+ reasoning: `re-exec of agy ${activity.name} for display`,
1417
+ ...mapped.args,
1418
+ } as Record<string, JsonValue>);
1419
+ return "parked";
1420
+ }
1421
+ if (feats.nativeActive && !feats.nativeActive("antigravity")) {
1422
+ // Subagent sessions whitelist tools and drop the display wrapper;
1423
+ // emitting here would fail every card with "not found".
1424
+ feats.log?.("wrap-skip", { tool: activity.name }, "debug");
1425
+ return "continue";
1426
+ }
1427
+ {
1428
+ const id = nextRtId("wrap");
1429
+ feats.replay.set(id, activity.output ?? "(agy recorded no output)");
1430
+ feats.roundTrips.track(id, activity.name);
1431
+ emitToolUse(stream, blocks, id, "antigravity", { tool: activity.name, key: id });
1432
+ return "parked";
1433
+ }
1434
+ }
1435
+ case "tool_error":
1436
+ if (feats.engine === "acp" && feats.onNativeEvent) {
1437
+ try {
1438
+ feats.onNativeEvent({ name: activity.name, mcpServer: activity.mcpServer, status: "failed", output: activity.message });
1439
+ return "continue";
1440
+ } catch { /* Fall back to a thinking label. */ }
1441
+ }
1442
+ appendThinking(stream, blocks, `[agy tool: ${activity.name} failed: ${activity.message}]\n`);
1443
+ return "continue";
1444
+ case "bridge_call": {
1445
+ // Park the pi call: real tool name + args, toolUse stopReason. pi
1446
+ // executes; the toolResult returns on the next stream call.
1447
+ // Driver args are JSON-decoded off the agy wire, so the JsonValue
1448
+ // cast is sound.
1449
+ emitToolUse(stream, blocks, activity.callId, activity.name, activity.args as Record<string, JsonValue>);
1450
+ return "parked";
1451
+ }
1452
+ }
1453
+ }
1454
+
1455
+ /** The stream-json engine: persistent driver + toolUse round-trips. */
1456
+ async function runTurnDriver(
1457
+ stream: AssistantMessageEventStream,
1458
+ model: Model<Api>,
1459
+ context: TranscriptContext,
1460
+ options: SimpleStreamOptions | undefined,
1461
+ entries: AgyModelEntry[],
1462
+ store: SessionStore,
1463
+ deps: DriverDeps,
1464
+ ): Promise<void> {
1465
+ const partial = newAssistant(model);
1466
+ const blocks: BlockState = { partial, textIdx: null, thinkingIdx: null, started: false };
1467
+
1468
+ const cwd = (options as { cwd?: string } | undefined)?.cwd ?? process.cwd();
1469
+ const key = sessionKey(options, cwd, deps.engine);
1470
+ // Ephemeral helper calls (pi compaction / branch summarization set
1471
+ // cacheRetention: "none"; cache warming / replay callers set
1472
+ // disableContinuation: true) must run in a fresh, isolated agy
1473
+ // conversation: never reuse or mutate the live session's SessionStore
1474
+ // binding, never claim dead/stranded tool results, and never arm
1475
+ // background watchers for throwaway turns.
1476
+ const ephemeral = options?.cacheRetention === "none" || options?.disableContinuation === true;
1477
+ const existing = ephemeral ? null : store.get(key);
1478
+ const compactionHandoff =
1479
+ !ephemeral && !existing?.conversationId && Boolean(deps.pendingCompactionHandoff?.has(key));
1480
+ const messageCount = context.messages.length;
1481
+ const config = loadConfig();
1482
+ // Settle bookkeeping shared by both store.set paths: the boundary
1483
+ // fingerprint validates next turn's delta window, and the compaction
1484
+ // index suppresses summary re-injection once this turn delivered it.
1485
+ const settleBoundary = boundaryFingerprint(context.messages[messageCount - 1]);
1486
+ // Summary id carried forward from the record; the gate below overwrites it
1487
+ // only when a digest actually ships, so skipped turns never lose it.
1488
+ let settleSummaryId = existing?.digestSummaryId;
1489
+
1490
+ // Continuation: resolve parked round-trips from pi's toolResult messages,
1491
+ // then re-attach to the still-running agy turn. No new user event is sent:
1492
+ // agy receives the result via the bridge's MCP HTTP response.
1493
+ const results = collectToolResults(context.messages, deps.roundTrips.pendingIds);
1494
+ const isContinuation = results.length > 0;
1495
+ // Escalated calls answer through bridge_poll_result, not through an agy
1496
+ // turn waiting on the park, so note them before resolving.
1497
+ const escalatedNames = results
1498
+ .map((r) => deps.roundTrips.poll(r.toolCallId)?.name)
1499
+ .filter((n): n is string => Boolean(n));
1500
+ // Images ride tool results on BOTH engines (ACP probe 2026-09-05;
1501
+ // stream-json probe 2026-09-07: the CLI's MCP client delivers tool-result
1502
+ // image content to the model — two-tone PNG named from the result alone,
1503
+ // no decoders in the frame trail). The late-delivery PROMPT stays
1504
+ // text-only: image blocks ride driver.run images instead, so both
1505
+ // engines deliver them (ACP native prompt blocks; stream-json staged
1506
+ // files).
1507
+ for (const r of results)
1508
+ deps.roundTrips.resolve(r.toolCallId, r.text, r.isError, r.images);
1509
+
1510
+ // Late delivery: a toolResult whose park already failed (the abort/timeout
1511
+ // path failed the park while the pi tool kept running). The work is done,
1512
+ // so re-route the result to agy as a new prompt in the same conversation
1513
+ // instead of dropping it. Both drivers serialize run(), so delivery queues
1514
+ // behind agy's own salvaged turn when one is still active.
1515
+ // A pass that anchors a still-pending park (isContinuation) has nowhere to
1516
+ // put a late result: it can neither ride the pending call's HTTP response
1517
+ // nor start a new prompt. Leave the tombstone for the next fresh pass
1518
+ // instead of consuming it blind.
1519
+ const late: LateToolResult[] = [];
1520
+ if (!ephemeral && !isContinuation) {
1521
+ for (const r of collectToolResults(context.messages, deps.roundTrips.deadIds)) {
1522
+ const dead = deps.roundTrips.consumeDead(r.toolCallId);
1523
+ if (dead)
1524
+ late.push({
1525
+ name: dead.name,
1526
+ reason: dead.reason,
1527
+ text: r.text,
1528
+ isError: r.isError,
1529
+ images: r.images.length > 0 ? r.images : undefined,
1530
+ });
1531
+ }
1532
+ if (late.length > 0) {
1533
+ deps.log?.("late-result", { tools: late.map((l) => l.name), freshConversation: !existing?.conversationId }, "info");
1534
+ }
1535
+ } else if (!ephemeral && deps.roundTrips.deadIds.length > 0) {
1536
+ deps.log?.("late-result-deferred", { count: deps.roundTrips.deadIds.length }, "info");
1537
+ }
1538
+
1539
+ // Stranded escalated results: done but never delivered — the model ended
1540
+ // its turn instead of polling bridge_poll_result (observed live 2026-10:
1541
+ // the model stopped after the STILL RUNNING ack on an ask_user_question
1542
+ // and the user's answer stranded in the registry). The sweep is
1543
+ // registry-wide: a toolResult is consumed by its own pass, so a strand
1544
+ // that survives its first pass is only findable here. Claims are
1545
+ // single-use; entries stay pollable for a late model poll.
1546
+ let redeliveryConversation: string | undefined;
1547
+ const collectStranded = (): LateToolResult[] =>
1548
+ deps.roundTrips.claimAllUndelivered().map((view) => {
1549
+ redeliveryConversation ??= view.conversationId;
1550
+ deps.log?.("escalated-redelivery", { tool: view.name, callId: view.callId }, "info");
1551
+ return {
1552
+ callId: view.callId,
1553
+ name: view.name,
1554
+ reason: "you never received this result: you ended your turn without calling bridge_poll_result",
1555
+ text: view.text ?? "(no output)",
1556
+ isError: view.isError ?? false,
1557
+ images: view.images,
1558
+ };
1559
+ });
1560
+ // A rotation that lands mid-turn must win over any bind of a PRE-ROTATION
1561
+ // conversation: continuations and strand redeliveries both target the old
1562
+ // conversation id, so binding their outcomes would restore the
1563
+ // rotated-away binding and swallow the handoff. Evaluated at bind time:
1564
+ // the latch may arm after turn start.
1565
+ const rotationGuardArmed = (): boolean =>
1566
+ (isContinuation || redeliveryConversation !== undefined) &&
1567
+ deps.pendingCompactionHandoff?.has(key) === true;
1568
+ /** Stream-json has no image channel in the turn input: stage the blocks
1569
+ * to temp files and let the note point the model at the bridge read
1570
+ * tool, whose result images the CLI delivers (probe 2026-09-07). ACP
1571
+ * rides native content blocks; no staging there. */
1572
+ const stageImageNote = (imgs: Array<{ data: string; mimeType: string }>): string => {
1573
+ if (deps.engine === "acp" || imgs.length === 0) return "";
1574
+ const staged = stagePromptImages(imgs);
1575
+ if (!staged) {
1576
+ deps.log?.("turn-warning", { reason: "image-staging-failed", count: imgs.length }, "warn");
1577
+ // Silence would strand the pixels forever: on a redelivery the claim
1578
+ // is already consumed, so the model must at least learn the image
1579
+ // existed and re-request it.
1580
+ return `\n\n[${imgs.length} image(s) could not be delivered to this turn; ask the user to re-attach or re-read the original path.]`;
1581
+ }
1582
+ return `\n\n${buildImageNote(staged.paths)}`;
1583
+ };
1584
+
1585
+ const entry = entries.find((e) => e.id === model.id) ?? null;
1586
+ const agyModel = entry?.full ?? model.id;
1587
+ const effort = entry?.efforts?.length ? toAgyEffort(options?.reasoning, entry.efforts) : undefined;
1588
+
1589
+ let handle: TurnHandle | undefined;
1590
+ // Name of the carrier agent staged for THIS turn's fresh conversation, if
1591
+ // any. Recorded into stagedAgentByConversation once the outcome binds the
1592
+ // conversation id, so later gate-closed turns pass the same agent.
1593
+ let stagedAgentName: string | undefined;
1594
+ const active = isContinuation ? deps.driver.reentry() : null;
1595
+ if (active) {
1596
+ handle = active;
1597
+ } else {
1598
+ // Dead turn: claim NOW (single-use). A live turn claims after outcome
1599
+ // instead — claiming here would eat the post-outcome recovery.
1600
+ if (!ephemeral) late.push(...collectStranded());
1601
+ if (isContinuation && late.length === 0) {
1602
+ if (escalatedNames.length === 0) {
1603
+ deps.log?.("turn-error", { reason: "tool-result-no-active-turn" }, "warn");
1604
+ finalize(stream, blocks, "error", "tool result arrived but no antigravity turn is running");
1605
+ return;
1606
+ }
1607
+ // Escalated results, all already delivered through polls: the model
1608
+ // has them in context. Settle quietly instead of erroring.
1609
+ appendText(stream, blocks, `[bridge] ${escalatedNames.join(", ")} finished; the result is available via ${POLL_TOOL_NAME}.`);
1610
+ finalize(stream, blocks, "stop");
1611
+ return;
1612
+ }
1613
+ if (isContinuation && late.length > 0 && redeliveryConversation === undefined && !existing?.conversationId) {
1614
+ // The owning turn ended before binding a conversation (no stamp, no
1615
+ // store record): a context-free late prompt would hit a brand-new
1616
+ // agy conversation that never asked the question. Release the
1617
+ // claims and settle quietly; the result stays pollable and a later
1618
+ // pass with a bound conversation can still sweep it.
1619
+ for (const l of late) if (l.callId) deps.roundTrips.unclaim(l.callId);
1620
+ appendText(stream, blocks, `[bridge] ${escalatedNames.join(", ")} finished, but no conversation is bound to re-deliver into; the result stays available via ${POLL_TOOL_NAME}.`);
1621
+ finalize(stream, blocks, "stop");
1622
+ return;
1623
+ }
1624
+ // Fresh pass, or a stranded escalated result being re-delivered.
1625
+ const userPrompt = extractUserPrompt(context);
1626
+ const images = extractImages(context);
1627
+ // Resume pass (issue #8): pi's retry dropped the failed attempt from the
1628
+ // projected context, so the transcript ends in a toolResult or assistant
1629
+ // message and there is no user prompt, no pending park, and nothing
1630
+ // late. With a bound conversation, agy holds the task history: re-open
1631
+ // it with a synthetic resume prompt instead of the hard error below
1632
+ // (pi does not retry that error; it stalls unattended sessions). The
1633
+ // binding is required: "continue" into a brand-new conversation has no
1634
+ // task to continue. Restricted to the two retry tails: an empty
1635
+ // transcript (lastRole undefined) and a user tail both keep their
1636
+ // existing behavior.
1637
+ const lastRole = context.messages[context.messages.length - 1]?.role;
1638
+ const hasCompactionSummary = findLastCompactionIdx(context.messages) >= 0;
1639
+ const resume =
1640
+ !userPrompt &&
1641
+ images.length === 0 &&
1642
+ late.length === 0 &&
1643
+ Boolean(existing?.conversationId) &&
1644
+ (lastRole === "toolResult" || lastRole === "assistant");
1645
+ // Post-compaction mid-tool-loop resume: session_compact rotated the old
1646
+ // agy conversation (so existing is null), and pi's compacted transcript
1647
+ // ends in a toolResult or assistant message. Seed a fresh agy
1648
+ // conversation with the compaction summary + trailing messages instead
1649
+ // of failing with the unretryable "No user message" error.
1650
+ const compactionResume =
1651
+ !ephemeral &&
1652
+ !userPrompt &&
1653
+ images.length === 0 &&
1654
+ late.length === 0 &&
1655
+ !existing?.conversationId &&
1656
+ (compactionHandoff || hasCompactionSummary) &&
1657
+ (lastRole === "toolResult" || lastRole === "assistant");
1658
+ const prompt = resume ? RESUME_PROMPT : compactionResume ? COMPACTION_RESUME_PROMPT : userPrompt;
1659
+ if (resume) deps.log?.("resume-turn", { conversation: existing?.conversationId }, "error");
1660
+ if (compactionResume) deps.log?.("compaction-resume-turn", { key, handoff: compactionHandoff }, "info");
1661
+ // An image-only message (no text) is valid on the ACP engine; only fail
1662
+ // when there is nothing at all to send (no text, no images, no late
1663
+ // tool results to deliver).
1664
+ if (!prompt && images.length === 0 && late.length === 0) {
1665
+ deps.log?.("turn-error", { reason: "no-user-message" }, "error");
1666
+ finalize(stream, blocks, "error", "No user message to send to agy.");
1667
+ return;
1668
+ }
1669
+ const rawWatermark = existing?.lastMessageCount ?? 0;
1670
+ // Boundary fingerprint check (see boundaryFingerprint): a transcript
1671
+ // mutated under the stored count (/tree, /fork, context-hook rewrites)
1672
+ // resets the delta to the full digest instead of a silently wrong one.
1673
+ // Records written before the fingerprint existed (digestBoundary unset)
1674
+ // trust the count: the old code advanced it the same way, so reseting
1675
+ // would dump a one-time full delta of history agy already holds.
1676
+ const storedBoundary = existing?.digestBoundary;
1677
+ const watermark =
1678
+ rawWatermark > 0 &&
1679
+ (storedBoundary === undefined ||
1680
+ storedBoundary === boundaryFingerprint(context.messages[rawWatermark - 1]))
1681
+ ? rawWatermark
1682
+ : 0;
1683
+ // Late and resume turns re-open the conversation with a synthetic
1684
+ // prompt; the digest would re-send context agy already holds (against a
1685
+ // stale watermark: a failed pass never advances it), so skip it.
1686
+ // Post-compaction handoff / compactionResume always ships the digest
1687
+ // once even if config.digest is false, because the old agy conversation
1688
+ // was rotated and the fresh conversation has no prior history.
1689
+ const engine = deps.engine ?? config.engine;
1690
+ const promptBytes = Buffer.byteLength(prompt ?? "", "utf8");
1691
+ const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1692
+ const wantDigest = config.digest || compactionHandoff || compactionResume;
1693
+ const digest =
1694
+ wantDigest && maxChars !== null && late.length === 0 && !resume
1695
+ ? buildContextDigest(context.messages, watermark, {
1696
+ bound: Boolean(existing?.conversationId),
1697
+ seenSummaryId: existing?.digestSummaryId,
1698
+ maxChars,
1699
+ includeLast: compactionResume,
1700
+ })
1701
+ : "";
1702
+ // Byte-level fail closed (issue #2): the char budget over-reserves for
1703
+ // ASCII but a multibyte digest can still exceed the remaining byte
1704
+ // room. ACP carries no prompt cap, so the check is stream-json only.
1705
+ const digestFinal =
1706
+ digest &&
1707
+ engine !== "acp" &&
1708
+ promptBytes + STREAM_JSON_PROMPT_MARGIN + Buffer.byteLength(digest, "utf8") > STREAM_JSON_PROMPT_CAP
1709
+ ? ""
1710
+ : digest;
1711
+ // The delivered summary id persists only when a digest actually shipped:
1712
+ // late/resume/budget-skipped turns carry the previous id forward so the
1713
+ // summary is not lost to a turn that never delivered it.
1714
+ if (digestFinal) {
1715
+ const deliveredIdx = findLastCompactionIdx(context.messages);
1716
+ settleSummaryId = deliveredIdx >= 0 ? compactionFingerprint(context.messages[deliveredIdx]) : undefined;
1717
+ }
1718
+ // G1 delivery per engine. stream-json: digest rides inline in the prompt
1719
+ // (the CLI has no context channel). ACP: the server advertises
1720
+ // `embeddedContext`, so the digest ships as a native resource block
1721
+ // instead of prompt text (plan phase 3). The preamble framing goes INTO
1722
+ // the block: an unlabeled blob of other-agent turns is a mild injection
1723
+ // surface, and the model needs the use-for-continuity-only instruction.
1724
+ // The uri is suffixed per turn so a deduping server cannot serve stale
1725
+ // content on turn 2+.
1726
+ const embeddedDigest = deps.engine === "acp" && digestFinal ? digestFinal : undefined;
1727
+ // G10, fresh conversations only (bound conversations ride agy's own
1728
+ // history; re-sending would bloat every prompt and bust the cache).
1729
+ // stream-json delivery is a staged agent file, NOT prompt text: agy's
1730
+ // stream-json path silently drops any turn past a ~25KB input cap and
1731
+ // the dropped turn leaves the conversation permanently unresponsive
1732
+ // (issue #2, probed 2026-09-30), and the block routinely crossed it.
1733
+ // ACP keeps the inline block (JSON-RPC transport; --agent is a CLI
1734
+ // feature). A user-configured agent always wins: never clobber it.
1735
+ const gateOpen = config.systemPrompt && !existing?.conversationId;
1736
+ const rawSysPrompt = gateOpen ? getCurrentSystemPrompt(context.messages) || undefined : undefined;
1737
+ let sysPrompt = rawSysPrompt;
1738
+ let agent = config.agent;
1739
+ if (deps.engine !== "acp") {
1740
+ if (rawSysPrompt && !config.agent) {
1741
+ const stagedName = stageSyspromptAgent(
1742
+ [SYSTEM_PROMPT_PREAMBLE, rawSysPrompt, TOOL_PRIORITY_NOTE].join("\n\n"),
1743
+ );
1744
+ if (stagedName) {
1745
+ agent = stagedName;
1746
+ sysPrompt = undefined;
1747
+ stagedAgentName = stagedName;
1748
+ }
1749
+ // Staging failed: inline fallback. The silent-drop guard below
1750
+ // keeps the resulting cap failure visible instead of quiet.
1751
+ } else if (rawSysPrompt && config.agent && !warnedUserAgentConflict) {
1752
+ warnedUserAgentConflict = true;
1753
+ deps.log?.(
1754
+ "sysprompt-agent-conflict",
1755
+ { agent: config.agent, effect: "system prompt ships inline in the prompt (over-cap drop risk)" },
1756
+ "warn",
1757
+ );
1758
+ } else if (!rawSysPrompt && !config.agent && existing?.conversationId) {
1759
+ // Gate closed (bound conversation): pass the carrier staged for
1760
+ // THIS conversation, if any, so the driver profile never drifts on
1761
+ // "agent" and a respawned process reloads its own instructions.
1762
+ agent = stagedAgentByConversation.get(existing.conversationId);
1763
+ }
1764
+ }
1765
+ // Late/stranded image results ride driver.run images (the redelivery
1766
+ // prompt is text-only); user-message images ride them on ACP natively
1767
+ // and staged files on stream-json.
1768
+ const runImages = [...images, ...late.flatMap((l) => l.images ?? [])];
1769
+ const fullPrompt =
1770
+ (late.length > 0
1771
+ ? buildLateResultPrompt(late, prompt || undefined)
1772
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, prompt ?? "")) +
1773
+ stageImageNote(runImages);
1774
+ try {
1775
+ handle = await deps.driver.run({
1776
+ cwd,
1777
+ model: agyModel,
1778
+ effort,
1779
+ mode: config.mode,
1780
+ skipPermissions: config.skipPermissions,
1781
+ timeoutMin: config.turnTimeoutMin,
1782
+ inactivityMin: config.inactivityTimeoutMin,
1783
+ conversationId: redeliveryConversation ?? existing?.conversationId ?? null,
1784
+ prompt: fullPrompt,
1785
+ images: runImages.length > 0 ? runImages : undefined,
1786
+ agent,
1787
+ contextBlock: embeddedDigest
1788
+ ? {
1789
+ uri: `urn:pi-bridge:context-digest/${messageCount}`,
1790
+ text: `${DIGEST_PREAMBLE}\n\n${embeddedDigest}`,
1791
+ }
1792
+ : undefined,
1793
+ signal: options?.signal,
1794
+ });
1795
+ } catch (err) {
1796
+ const msg = err instanceof Error ? err.message : String(err);
1797
+ // Release stranded claims: the delivery never started, so the next
1798
+ // pass must find them undelivered (tombstone-borne items have no
1799
+ // callId and stay consumed, as before).
1800
+ for (const l of late) if (l.callId) deps.roundTrips.unclaim(l.callId);
1801
+ deps.log?.("turn-error", { reason: "driver-start-failed", error: msg }, "error");
1802
+ finalize(stream, blocks, "error", `agy failed to start: ${msg}`);
1803
+ return;
1804
+ }
1805
+ }
1806
+
1807
+ ensureStarted(stream, blocks);
1808
+ const diffCtx = new TurnDiffContext(createExecGitOps());
1809
+ // Background latch: one WaitMsBeforeAsync-shaped native call this turn is
1810
+ // enough; the watcher arms at the settled end, filtered by turnStartMs so
1811
+ // the cumulative task dir never re-reports older turns' logs.
1812
+ const turnStartMs = Date.now();
1813
+ let nativeBackgroundSeen = false;
1814
+ // Issue #16 guard: quota reclassification applies to text-only turns only.
1815
+ let sawToolOrThought = false;
1816
+ const feats: ActivityFeatures = {
1817
+ replay: deps.replay,
1818
+ nativeActive: deps.nativeActive,
1819
+ roundTrips: deps.roundTrips,
1820
+ engine: deps.engine,
1821
+ onNativeEvent: deps.onNativeEvent,
1822
+ onBackgroundArg: () => {
1823
+ nativeBackgroundSeen = true;
1824
+ },
1825
+ roster: deps.roster,
1826
+ log: deps.log,
1827
+ };
1828
+
1829
+ const drainTurn = async (h: TurnHandle): Promise<"parked" | undefined> => {
1830
+ for (;;) {
1831
+ const activity = await h.next();
1832
+ if (!activity) break;
1833
+ if (activity.type !== "text" && activity.type !== "usage") sawToolOrThought = true;
1834
+ if (consumeActivity(stream, blocks, activity, diffCtx, cwd, feats) === "parked") return "parked";
1835
+ }
1836
+ };
1837
+ if ((await drainTurn(handle)) === "parked") {
1838
+ // A park proves agy got the prompt and is working in this conversation.
1839
+ // Persist a first-turn binding now: otherwise a first-ever turn that
1840
+ // parks and then dies (failed continuation, process restart) leaves no
1841
+ // record, and the retry-dropped tail (issue #8) has nothing to resume
1842
+ // into. Only when no record exists: an unbound run() cannot have
1843
+ // recreated a conversation, so the snapshot id is the real one, and
1844
+ // the staged agent must move with the binding or a stream-json resume
1845
+ // re-runs without its carrier-agent profile.
1846
+ if (!ephemeral && !existing && !rotationGuardArmed()) {
1847
+ const parkedConv = deps.driver.snapshot().conversationId;
1848
+ if (parkedConv) {
1849
+ store.set(key, {
1850
+ conversationId: parkedConv,
1851
+ lastStepIdx: -1,
1852
+ lastMessageCount: messageCount,
1853
+ digestBoundary: settleBoundary,
1854
+ digestSummaryId: settleSummaryId,
1855
+ });
1856
+ deps.pendingCompactionHandoff?.delete(key);
1857
+ if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
1858
+ }
1859
+ }
1860
+ return;
1861
+ }
1862
+
1863
+ let outcome = await handle.outcome;
1864
+ // Issue #2 recovery paths. agy's stream-json prompt path silently drops an
1865
+ // over-cap turn (SUCCESS, empty response, zero usage, NO model step) and a
1866
+ // dropped turn leaves the conversation permanently unresponsive, so both
1867
+ // failures clear the binding instead of settling a quiet empty reply —
1868
+ // settling OK here would persist a dead conversation for every later turn
1869
+ // (probe 2026-09-30: resume of a dropped-turn conversation never returns
1870
+ // a result frame). stream-json only: the ACP driver leaves the evidence
1871
+ // fields undefined. modelOutputSeen === false keeps deadline kills of a
1872
+ // turn that demonstrably worked (it parked, so a model step arrived) on
1873
+ // the plain retryable error path: "conversation is dead" would be wrong
1874
+ // for a first turn, and deleting a park-time binding (issue #8) would
1875
+ // strip the retry of its conversation.
1876
+ const silentDrop = outcome.status === "OK" && outcome.modelOutputSeen === false;
1877
+ const poisonedResume =
1878
+ outcome.status === "ERROR" &&
1879
+ outcome.deadline !== undefined &&
1880
+ outcome.sawResult === false &&
1881
+ outcome.modelOutputSeen === false &&
1882
+ Boolean(existing?.conversationId);
1883
+ if (silentDrop || poisonedResume) {
1884
+ if (!ephemeral && (existing?.conversationId || outcome.conversationId)) {
1885
+ store.delete(key);
1886
+ if (outcome.conversationId) stagedAgentByConversation.delete(outcome.conversationId);
1887
+ }
1888
+ deps.log?.(
1889
+ "turn-error",
1890
+ {
1891
+ reason: silentDrop ? "silent-overcap-drop" : "poisoned-conversation",
1892
+ conversation: outcome.conversationId ?? null,
1893
+ },
1894
+ "error",
1895
+ );
1896
+ // A deadline with no model output is a stall/timeout, not the over-cap
1897
+ // signature: label it by its real cause (the deadline guard's recovered-
1898
+ // answer probe can settle OK with an empty response after the kill).
1899
+ const dropCause = outcome.deadline
1900
+ ? "the turn hit its time limit and produced no model output"
1901
+ : "the prompt was silently dropped (agy discards prompts past ~25KB with no error)";
1902
+ finalize(
1903
+ stream,
1904
+ blocks,
1905
+ "error",
1906
+ silentDrop
1907
+ ? `agy returned success but produced no model output: ${dropCause}. Common cause: a very large pasted prompt. The conversation binding was cleared; retry with a smaller prompt.`
1908
+ : "agy stopped responding on the resumed conversation (no response frame before the deadline; the conversation is dead). The binding was cleared, so the next antigravity turn starts a fresh conversation.",
1909
+ );
1910
+ return;
1911
+ }
1912
+ // Issue #16: agy streams the account quota notice as agent text and ends
1913
+ // the turn OK; settle it as a retryable error so provider failover fires.
1914
+ // Text-only turns only, and the binding is untouched below: the
1915
+ // conversation itself is healthy, unlike the silentDrop signature above.
1916
+ if (outcome.status === "OK" && !outcome.aborted && !sawToolOrThought) {
1917
+ const quota = detectQuotaNotice(outcome.response);
1918
+ if (quota) {
1919
+ deps.log?.("turn-error", { reason: "quota-exhausted", resetsIn: quota.resetsIn ?? null }, "error");
1920
+ finalize(stream, blocks, "error", quotaErrorMessage(quota));
1921
+ return;
1922
+ }
1923
+ }
1924
+ // Gap closer: the result landed while the turn was still live (reentry
1925
+ // above), the turn ended, and the model never polled. Same strand, same
1926
+ // fix: sweep and deliver as a late run in the same conversation. Single
1927
+ // shot: claims are single-use, so a re-delivered strand cannot reappear
1928
+ // here; a late run that parks hands recovery to the next pi pass.
1929
+ if (!ephemeral && isContinuation && outcome.status === "OK" && !outcome.aborted) {
1930
+ const more = collectStranded();
1931
+ if (more.length > 0) {
1932
+ const conv = redeliveryConversation ?? outcome.conversationId ?? existing?.conversationId ?? null;
1933
+ deps.log?.("escalated-redelivery-turn", { tools: more.map((s) => s.name), conversation: conv }, "info");
1934
+ const moreImages = more.flatMap((s) => s.images ?? []);
1935
+ try {
1936
+ const lateHandle = await deps.driver.run({
1937
+ cwd,
1938
+ model: agyModel,
1939
+ effort,
1940
+ mode: config.mode,
1941
+ skipPermissions: config.skipPermissions,
1942
+ timeoutMin: config.turnTimeoutMin,
1943
+ inactivityMin: config.inactivityTimeoutMin,
1944
+ conversationId: conv,
1945
+ prompt: buildLateResultPrompt(more) + stageImageNote(moreImages),
1946
+ images: moreImages.length > 0 ? moreImages : undefined,
1947
+ agent: config.agent ?? (conv ? stagedAgentByConversation.get(conv) : undefined),
1948
+ signal: options?.signal,
1949
+ });
1950
+ if ((await drainTurn(lateHandle)) === "parked") return;
1951
+ outcome = await lateHandle.outcome;
1952
+ } catch (err) {
1953
+ // Release the claims so the next pass can retry the delivery.
1954
+ for (const l of more) if (l.callId) deps.roundTrips.unclaim(l.callId);
1955
+ deps.log?.(
1956
+ "turn-error",
1957
+ { reason: "redelivery-start-failed", error: err instanceof Error ? err.message : String(err) },
1958
+ "error",
1959
+ );
1960
+ }
1961
+ }
1962
+ }
1963
+ if (!ephemeral && outcome.conversationId) {
1964
+ // A different id than the stored one means the driver recreated the
1965
+ // conversation under us (ACP session-load fallback, stream-json CLI
1966
+ // dropping a stale --conversation). The recreated conversation has seen
1967
+ // NOTHING, so the record's watermark would starve the digest forever and
1968
+ // its bound id would keep the sysPrompt gate closed. Drop the record:
1969
+ // the next turn resumes from watermark 0 with the gate re-armed (issue
1970
+ // #1). The recreation turn itself is past the gate, so it is the
1971
+ // documented residual; recovery starts on the next turn.
1972
+ if (existing?.conversationId && outcome.conversationId !== existing.conversationId) {
1973
+ store.delete(key);
1974
+ stagedAgentByConversation.delete(existing.conversationId);
1975
+ } else if (outcome.status === "OK" && !outcome.aborted) {
1976
+ if (rotationGuardArmed()) {
1977
+ deps.log?.("rotation-binding-deferred", { conversation: outcome.conversationId, key }, "info");
1978
+ } else {
1979
+ store.set(key, {
1980
+ conversationId: outcome.conversationId,
1981
+ lastStepIdx: -1,
1982
+ lastMessageCount: messageCount,
1983
+ digestBoundary: settleBoundary,
1984
+ digestSummaryId: settleSummaryId,
1985
+ });
1986
+ deps.pendingCompactionHandoff?.delete(key);
1987
+ if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
1988
+ }
1989
+ }
1990
+ // A failed or aborted turn on the SAME conversation keeps the pre-turn
1991
+ // record: whether the prompt actually landed in agy's DB is not
1992
+ // observable from here. Keeping the watermark re-delivers the missed
1993
+ // turn in the next digest (bounded by the digest cap); advancing it
1994
+ // would starve the conversation of context it may never have received.
1995
+ }
1996
+ if (outcome.aborted) {
1997
+ finalize(stream, blocks, "aborted", "Operation aborted");
1998
+ return;
1999
+ }
2000
+ if (outcome.status === "ERROR") {
2001
+ finalize(stream, blocks, "error", outcome.error ?? "agy turn failed");
2002
+ return;
2003
+ }
2004
+ if (blocks.textIdx === null && outcome.response) {
2005
+ appendText(stream, blocks, outcome.response);
2006
+ }
2007
+ if (blocks.textIdx === null && blocks.thinkingIdx === null) {
2008
+ ensureTextOpen(stream, blocks);
2009
+ }
2010
+ if (!ephemeral && nativeBackgroundSeen && outcome.conversationId) {
2011
+ deps.onNativeBackground?.({ conversationId: outcome.conversationId, turnStartMs });
2012
+ deps.log?.("native-background-arm", { conversation: outcome.conversationId, turnStartMs }, "info");
2013
+ }
2014
+ // Multi-inference billing sums in usage.input + usage.cacheRead can exceed
2015
+ // model.contextWindow even when live occupancy (totalTokens) is well under
2016
+ // the window. Clamp before emitting stop so pi-ai's isContextOverflow()
2017
+ // Case 2 does not trigger a phantom overflow compaction on a healthy turn.
2018
+ clampOverflowUsage(blocks.partial.usage, model.contextWindow);
2019
+ finalize(stream, blocks, "stop");
2020
+ }
2021
+
2022
+ /** Build the streamSimple closure. Captures the model catalog + session store
2023
+ * resolved at extension load. When a driver is provided, turns run on the
2024
+ * persistent stream-json engine (config.engine selects; stream remains as
2025
+ * fallback). */
2026
+ export function createStreamSimple(
2027
+ deps: StreamSimpleDeps,
2028
+ ): (model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) => AssistantMessageEventStream {
2029
+ const { entries, store, roundTrips } = deps;
2030
+
2031
+ return function streamSimple(model, context, options) {
2032
+ const stream = createAssistantMessageEventStream();
2033
+
2034
+ // Short-circuit pi-observational-memory background workers.
2035
+ // Observational memory workers declare caller-scoped tools (record_observations,
2036
+ // record_reflections, drop_observations). Antigravity models run in a closed backend
2037
+ // process with their own tool execution loop and do not support caller-scoped tools.
2038
+ // If dispatched to agy, the model sees tool instructions without tools and enters
2039
+ // an autonomous loop searching the disk for their implementation.
2040
+ // Returning a clean stop with empty content triggers OM's empty-observer backoff,
2041
+ // preventing high-frequency retries on subsequent turns.
2042
+ if (isObservationalMemoryContext(context)) {
2043
+ if (!warnedObservationalMemoryMismatch) {
2044
+ warnedObservationalMemoryMismatch = true;
2045
+ deps.log?.(
2046
+ "turn-warning",
2047
+ {
2048
+ reason: "observational-memory-unsupported",
2049
+ message:
2050
+ "Observational memory background workers cannot run against Antigravity models (caller-scoped tools unsupported). Configure a dedicated model under 'observational-memory.model' in settings.json.",
2051
+ },
2052
+ "warn",
2053
+ );
2054
+ }
2055
+ const partial = newAssistant(model);
2056
+ const blocks: BlockState = { partial, textIdx: null, thinkingIdx: null, started: false };
2057
+ finalize(stream, blocks, "stop");
2058
+ return stream;
2059
+ }
2060
+
2061
+ // Fire the async turn; return the stream synchronously per pi's contract.
2062
+ // Engine selection: the latched load-time engine when the extension
2063
+ // provides one, else the per-call config read (tests). One loadConfig()
2064
+ // read per turn, shared with the session key below.
2065
+ const config = loadConfig();
2066
+ const engine = deps.engine ?? config.engine;
2067
+ const selected = engine === "acp" && deps.acpDriver ? deps.acpDriver : deps.driver;
2068
+ // Plan-shaped provider turns are fail-closed on BOTH engines because
2069
+ // agy does not enforce review-only writes. Stream-json, probed
2070
+ // 2026-10-07: the engine WARNS that --mode plan is a no-op while
2071
+ // --disable-slash-commands is set, executes file writes even with
2072
+ // slash expansion left on (it stages a plan.md and still writes in the
2073
+ // same turn), ignores --agent toolset restrictions, and file writes
2074
+ // bypass the permission system entirely. A plan-labeled turn here is
2075
+ // write-capable, so refuse visibly instead of running false safety.
2076
+ if (config.readOnly || config.mode === "plan") {
2077
+ const partial = newAssistant(model);
2078
+ const blocks: BlockState = { partial, textIdx: null, thinkingIdx: null, started: false };
2079
+ if (config.readOnly) {
2080
+ deps.log?.("turn-error", { reason: "readonly-refused" }, "warn");
2081
+ finalize(
2082
+ stream,
2083
+ blocks,
2084
+ "error",
2085
+ "readOnly cannot be enforced on provider turns: the agy CLI has no review-only enforcement on any path. Plan mode stages a plan and executes the write in the same turn (probed 2026-10-07, google-antigravity/antigravity-cli#1181). Enforce read-only in the host (pi tool restrictions or the approval gate), then /agy readonly off.",
2086
+ );
2087
+ return stream;
2088
+ }
2089
+ deps.log?.("turn-error", { reason: "plan-refused" }, "warn");
2090
+ finalize(
2091
+ stream,
2092
+ blocks,
2093
+ "error",
2094
+ "Plan mode cannot be enforced on provider turns: the agy CLI stages a plan and executes writes in the same turn (probed 2026-10-07, google-antigravity/antigravity-cli#1181), and provider plan turns are disabled on ACP too. /agy mode accept-edits, and enforce review-only in the host.",
2095
+ );
2096
+ return stream;
2097
+ }
2098
+ if (selected && roundTrips) {
2099
+ void runTurnDriver(stream, model, context, options, entries, store, {
2100
+ driver: selected,
2101
+ roundTrips,
2102
+ replay: deps.replay,
2103
+ nativeActive: deps.nativeActive,
2104
+ onNativeEvent: deps.onNativeEvent,
2105
+ onNativeBackground: deps.onNativeBackground,
2106
+ roster: deps.roster,
2107
+ pendingCompactionHandoff: deps.pendingCompactionHandoff,
2108
+ // Record the engine of the driver that will ACTUALLY run: if the
2109
+ // ACP driver is absent, the config switch falls back to stream,
2110
+ // and keying the session as @acp would store a stream
2111
+ // conversationId under the wrong engine scope.
2112
+ engine: selected === deps.acpDriver ? "acp" : "stream-json",
2113
+ log: deps.log,
2114
+ });
2115
+ } else {
2116
+ // Miswired extension: no driver means no engine. Fail the turn visibly
2117
+ // instead of silently producing an empty assistant message.
2118
+ const partial = newAssistant(model);
2119
+ const blocks: BlockState = { partial, textIdx: null, thinkingIdx: null, started: false };
2120
+ deps.log?.("turn-error", { reason: "driver-not-configured" }, "warn");
2121
+ finalize(stream, blocks, "error", "antigravity driver not configured");
2122
+ }
2123
+ return stream;
2124
+ };
2125
+ }
2126
+
2127
+ /** Signal the start of the assistant turn exactly once. `start` is
2128
+ * turn-level (analogous to Anthropic's message_start), not per-block - the
2129
+ * per-block signals are text_start / thinking_start. */
2130
+ function ensureStarted(stream: AssistantMessageEventStream, b: BlockState): void {
2131
+ if (b.started) return;
2132
+ b.started = true;
2133
+ stream.push({ type: "start", partial: b.partial });
2134
+ }
2135
+
2136
+ /** Append a text delta (opens the block on first use). Module-level so both
2137
+ * engines share it. */
2138
+ function appendText(stream: AssistantMessageEventStream, b: BlockState, delta: string): void {
2139
+ ensureTextOpen(stream, b);
2140
+ textAt(b.partial, b.textIdx!).text += delta;
2141
+ stream.push({ type: "text_delta", contentIndex: b.textIdx!, delta, partial: b.partial });
2142
+ }
2143
+
2144
+ /** Append a thinking delta (opens the block on first use). */
2145
+ function appendThinking(stream: AssistantMessageEventStream, b: BlockState, delta: string): void {
2146
+ ensureThinkingOpen(stream, b);
2147
+ thinkingAt(b.partial, b.thinkingIdx!).thinking += delta;
2148
+ stream.push({ type: "thinking_delta", contentIndex: b.thinkingIdx!, delta, partial: b.partial });
2149
+ }
2150
+
2151
+ /** Open the text block, closing the thinking block first if it's open. */
2152
+ function ensureTextOpen(stream: AssistantMessageEventStream, b: BlockState): void {
2153
+ if (b.textIdx !== null) return;
2154
+ closeThinking(stream, b);
2155
+ ensureStarted(stream, b);
2156
+ b.partial.content.push({ type: "text", text: "" });
2157
+ b.textIdx = b.partial.content.length - 1;
2158
+ stream.push({ type: "text_start", contentIndex: b.textIdx, partial: b.partial });
2159
+ }
2160
+
2161
+ /** Open the thinking block, closing the text block first if it's open. */
2162
+ function ensureThinkingOpen(stream: AssistantMessageEventStream, b: BlockState): void {
2163
+ if (b.thinkingIdx !== null) return;
2164
+ closeText(stream, b);
2165
+ ensureStarted(stream, b);
2166
+ b.partial.content.push({ type: "thinking", thinking: "" });
2167
+ b.thinkingIdx = b.partial.content.length - 1;
2168
+ stream.push({ type: "thinking_start", contentIndex: b.thinkingIdx, partial: b.partial });
2169
+ }
2170
+
2171
+ function closeText(stream: AssistantMessageEventStream, b: BlockState): void {
2172
+ if (b.textIdx === null) return;
2173
+ const idx = b.textIdx;
2174
+ b.textIdx = null;
2175
+ stream.push({ type: "text_end", contentIndex: idx, content: textAt(b.partial, idx).text, partial: b.partial });
2176
+ }
2177
+
2178
+ function closeThinking(stream: AssistantMessageEventStream, b: BlockState): void {
2179
+ if (b.thinkingIdx === null) return;
2180
+ const idx = b.thinkingIdx;
2181
+ b.thinkingIdx = null;
2182
+ stream.push({ type: "thinking_end", contentIndex: idx, content: thinkingAt(b.partial, idx).thinking, partial: b.partial });
2183
+ }
2184
+
2185
+ // Typed accessors: AssistantMessage.content is a discriminated union, but we
2186
+ // always know which slot holds which block (we just pushed it). The cast is
2187
+ // sound and keeps every mutation site free of scattered `as` expressions.
2188
+ function textAt(p: AssistantMessage, idx: number): { type: "text"; text: string } {
2189
+ return p.content[idx] as { type: "text"; text: string };
2190
+ }
2191
+
2192
+ function thinkingAt(p: AssistantMessage, idx: number): { type: "thinking"; thinking: string } {
2193
+ return p.content[idx] as { type: "thinking"; thinking: string };
2194
+ }
2195
+
2196
+ /** Close any open block and push the terminal event. */
2197
+ function finalize(
2198
+ stream: AssistantMessageEventStream,
2199
+ b: BlockState,
2200
+ reason: "stop" | "error" | "aborted",
2201
+ message?: string,
2202
+ ): void {
2203
+ closeText(stream, b);
2204
+ closeThinking(stream, b);
2205
+ if (reason === "stop") {
2206
+ b.partial.stopReason = "stop";
2207
+ stream.push({ type: "done", reason: "stop", message: b.partial });
2208
+ } else {
2209
+ b.partial.stopReason = reason;
2210
+ if (message) b.partial.errorMessage = message;
2211
+ stream.push({ type: "error", reason, error: b.partial });
2212
+ }
2213
+ stream.end();
2214
+ }