@orbit-labs-ai/pi-antigravity 0.0.0-stage → 0.0.2

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 (67) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/CHANGELOG.zh-CN.md +36 -0
  3. package/LICENSE +22 -0
  4. package/README.md +138 -2
  5. package/README.zh-CN.md +139 -0
  6. package/docs/upstream.md +49 -0
  7. package/extensions/index.ts +2418 -0
  8. package/package.json +73 -4
  9. package/src/acp/connection.ts +662 -0
  10. package/src/acp/driver.ts +1115 -0
  11. package/src/acp/events.ts +324 -0
  12. package/src/acp/history-sync.ts +221 -0
  13. package/src/acp/home.ts +144 -0
  14. package/src/acp/jsonrpc.ts +243 -0
  15. package/src/acp/setup.ts +108 -0
  16. package/src/acp/usage-estimate.ts +61 -0
  17. package/src/agents.ts +64 -0
  18. package/src/agy-install.ts +93 -0
  19. package/src/agy-paths.ts +30 -0
  20. package/src/agy-setup.ts +81 -0
  21. package/src/agy-version.ts +292 -0
  22. package/src/approval-detect.ts +161 -0
  23. package/src/approval-gate.ts +274 -0
  24. package/src/approval-hook.ts +326 -0
  25. package/src/artifacts-ui.ts +88 -0
  26. package/src/artifacts.ts +144 -0
  27. package/src/ask-tool.ts +1247 -0
  28. package/src/atomic-write.ts +42 -0
  29. package/src/background-watch.ts +226 -0
  30. package/src/bridge-catalog.ts +282 -0
  31. package/src/compaction-preempt.ts +69 -0
  32. package/src/config.ts +708 -0
  33. package/src/daily-log.ts +205 -0
  34. package/src/dialog-lock.ts +48 -0
  35. package/src/diff-render.ts +207 -0
  36. package/src/driver-types.ts +202 -0
  37. package/src/driver.ts +904 -0
  38. package/src/engine-picker.ts +213 -0
  39. package/src/frame-guard.ts +38 -0
  40. package/src/handoff-toast.ts +21 -0
  41. package/src/history-projection.ts +210 -0
  42. package/src/history-sync.ts +311 -0
  43. package/src/mcp-registration.ts +380 -0
  44. package/src/mcp-server.ts +648 -0
  45. package/src/models.ts +402 -0
  46. package/src/native-fileops.ts +40 -0
  47. package/src/native-tools.ts +108 -0
  48. package/src/parked-turn.ts +125 -0
  49. package/src/patch-cleanup.ts +518 -0
  50. package/src/poll-fold.ts +55 -0
  51. package/src/prompt-images.ts +93 -0
  52. package/src/provider.ts +3303 -0
  53. package/src/queued-messages.ts +150 -0
  54. package/src/quota-notice.ts +40 -0
  55. package/src/redact.ts +27 -0
  56. package/src/runtime.ts +329 -0
  57. package/src/sessions.ts +220 -0
  58. package/src/skills.ts +207 -0
  59. package/src/stream-events.ts +161 -0
  60. package/src/stream-sanitizer.ts +180 -0
  61. package/src/subagent-roster.ts +244 -0
  62. package/src/sysprompt-agent.ts +176 -0
  63. package/src/tasks-ui.ts +91 -0
  64. package/src/tasks.ts +174 -0
  65. package/src/usage.ts +174 -0
  66. package/src/version.ts +32 -0
  67. package/src/web-tools.ts +320 -0
@@ -0,0 +1,2418 @@
1
+ // @orbit-labs-ai/pi-antigravity - extension entry point.
2
+ //
3
+ // Registers Gemini (via the agy CLI) as a pi model provider so it shows up in
4
+ // the /model picker as antigravity/gemini-*. When selected, pi routes each turn
5
+ // through streamSimple, which feeds the persistent stream-json driver process
6
+ // and streams the agent text back into pi's TUI.
7
+ //
8
+ // Architectural wall (cannot be worked around - see PLAN.md):
9
+ // agy runs its OWN closed tool loop against --add-dir. pi's read/write/edit/
10
+ // bash tools never fire. Tool activity is surfaced as thinking events
11
+ // ("[agy tool: editing foo.ts]") for visibility, but the edits already landed
12
+ // on disk and pi's inline diff review does not engage.
13
+ //
14
+ // /agy command: full runtime config surface (engine, mode, permissions,
15
+ // bridge tools, model, thinking, digest, system prompt) plus doctor,
16
+ // authentication instructions, patch-cleanup, and session clear. Config persists to
17
+ // <agentDir>/pi-antigravity/config.json so toggles survive restarts.
18
+
19
+ import os from "node:os";
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import {
23
+ type ExtensionAPI,
24
+ type ExtensionCommandContext,
25
+ type ExtensionUIContext,
26
+ createBashToolDefinition,
27
+ createEditToolDefinition,
28
+ createWriteToolDefinition,
29
+ } from "@earendil-works/pi-coding-agent";
30
+ import { Text } from "@earendil-works/pi-tui";
31
+ import { DIALOG_OPTIONS, DialogMenu, dialogBlocked, type DialogRow } from "@estebanforge/pi-tui-dialogs";
32
+ import {
33
+ entriesFromRaw,
34
+ FALLBACK_MODELS,
35
+ loadModelCatalogRaw,
36
+ toPiModel,
37
+ type AgyModelEntry,
38
+ } from "../src/models.js";
39
+ import type { SessionStore } from "../src/sessions.js";
40
+ import {
41
+ APPROVAL_PARK_MS,
42
+ POLL_TOOL_NAME,
43
+ ToolRoundTrips,
44
+ WrapperReplay,
45
+ createStreamSimple,
46
+ defaultEscalateAfterMs,
47
+ formatEscalatedAck,
48
+ answerPoll,
49
+ clearSteerCursor,
50
+ rotateSessionOnCompaction,
51
+ sessionKey,
52
+ type NativeDisplayEvent,
53
+ } from "../src/provider.js";
54
+ import { handoffToast } from "../src/handoff-toast.js";
55
+ import { getPackageVersion } from "../src/version.js";
56
+ import { collectNativeFileOps } from "../src/native-fileops.js";
57
+ import { preemptParkedTurnForCompaction } from "../src/compaction-preempt.js";
58
+ import { PollRunFolder, type PollRunData } from "../src/poll-fold.js";
59
+ import {
60
+ createShadowTool,
61
+ stripMarkerFields,
62
+ bashSettingsOptions,
63
+ type AnyToolDefinition,
64
+ type GatePolicy,
65
+ } from "../src/approval-gate.js";
66
+ import { detectPermissionGateExtensions, resolveGateMode } from "../src/approval-detect.js";
67
+ import { hookScriptSource, removeGateHooks, stageGateHooks, sweepWorkspaceGateGroups } from "../src/approval-hook.js";
68
+ import { StreamDriver } from "../src/driver.js";
69
+ import { AcpDriver } from "../src/acp/driver.js";
70
+ import { removeStagedAgyHome, stageAgyHome, sweepStagedAgyHomes, writeOwnBridgeEntry } from "../src/acp/home.js";
71
+ import { cleanupManagedAcpInstall } from "../src/acp/setup.js";
72
+ import { agyAuthenticationMessage } from "../src/agy-install.js";
73
+ import { createAgySetupOffer } from "../src/agy-setup.js";
74
+ import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
75
+ import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
76
+ import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, migrateLegacyBridgeState, migrateStaleDigestDefault, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
77
+ import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, shouldOfferEnginePicker, shouldWarnStreamJson, showEnginePicker, showStreamJsonWarning, streamJsonKeptMessage, streamJsonSavePatch } from "../src/engine-picker.js";
78
+ import { agyVersionVerdict, agyUpdateMessage, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
79
+ import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
80
+ import { formatSubagentRoster, SubagentRoster } from "../src/subagent-roster.js";
81
+ import { spawn } from "node:child_process";
82
+ import { fetchAgyQuota, formatAgyQuotaReport } from "../src/usage.js";
83
+ import { artifactOpenCommand, listAgyArtifacts } from "../src/artifacts.js";
84
+ import { showArtifactsBrowser } from "../src/artifacts-ui.js";
85
+ import { listAgyTasks, tailAgyTaskLog } from "../src/tasks.js";
86
+ import { showTasksBrowser } from "../src/tasks-ui.js";
87
+ import { agyConversationDir } from "../src/agy-paths.js";
88
+ import { armBackgroundWatch, rearmPlansFromEntries, type BackgroundWatchEntry, type BackgroundWatchHandle } from "../src/background-watch.js";
89
+ import { redactText } from "../src/redact.js";
90
+ import { createDailyLogger, type DailyLogger } from "../src/daily-log.js";
91
+ import { registerAskAntigravityTool, toolModelsFromRaw } from "../src/ask-tool.js";
92
+ import { registerWebTools } from "../src/web-tools.js";
93
+ import { bridgeMcpConfigDir, sweepStaleBridgeDirs, TOKEN_HEADER } from "../src/mcp-server.js";
94
+ import {
95
+ registerBridgeServer,
96
+ healBridgeSuppression,
97
+ sweepStaleBridgeServers,
98
+ } from "../src/mcp-registration.js";
99
+ import {
100
+ approvalHookScriptPath,
101
+ bridgeRealm,
102
+ liveSessionId,
103
+ type BridgeEndpoint,
104
+ type RealmSession,
105
+ } from "../src/runtime.js";
106
+ import {
107
+ ACTIVATE_SKILL_TOOL_NAME,
108
+ activateSkillSchema,
109
+ catalogSummary,
110
+ findSkillByName,
111
+ readSkillBody,
112
+ scanSkills,
113
+ type SkillLite,
114
+ } from "../src/skills.js";
115
+ import {
116
+ CALL_TOOL_NAME,
117
+ TOOL_INFO_TOOL_NAME,
118
+ bridgeCallToolDef,
119
+ bridgeToolInfoDef,
120
+ bridgedPiTools,
121
+ formatBridgeToolInfo,
122
+ parseBridgeCallRequest,
123
+ partitionBridgeTools,
124
+ codemodeCatalog,
125
+ serializeToolSchema,
126
+ } from "../src/bridge-catalog.js";
127
+ import { Type } from "typebox";
128
+ import { patchStatus, restorePatch } from "../src/patch-cleanup.js";
129
+ import { withDialogLock } from "../src/dialog-lock.js";
130
+
131
+ function resolveAgyBinary(): string {
132
+ return process.env.AGY_BIN || "agy";
133
+ }
134
+
135
+ export default async function piAntigravityExtension(pi: ExtensionAPI): Promise<void> {
136
+ // One-shot non-destructive migration from legacy <agentDir>/antigravity-bridge.
137
+ migrateLegacyBridgeState();
138
+ // Per-factory UI reference so child session_shutdown never clears the
139
+ // parent's UI context.
140
+ let activeUi: ExtensionUIContext | null = null;
141
+ ensureQueuedMessagesDefaults({ onlyIfDirExists: true });
142
+
143
+ // Claim the AskAntigravity tool for this process. Standalone ask-antigravity
144
+ // extensions check these flags and defer to avoid duplicate registration.
145
+ const globalFlags = globalThis as Record<symbol, unknown>;
146
+ globalFlags[Symbol.for("orbit.pi-antigravity:active")] = true;
147
+ globalFlags[Symbol.for("pi-antigravity-bridge:active")] = true;
148
+
149
+ const binary = resolveAgyBinary();
150
+
151
+ // Discover once at load. Failure is non-fatal: FALLBACK_MODELS keeps the
152
+ // picker populated so the user gets a clear runtime error from agy rather
153
+ // than an empty model list. /reload re-runs this and refreshes after an
154
+ // `agy update`.
155
+ // loadModelCatalogRaw serves a short-TTL cache (<agentDir>/pi-antigravity/
156
+ // models-cache.json) so reloads are instant and only re-spawn in the
157
+ // background when stale. Derive both catalogs from the same raw text
158
+ // (provider's slugified Gemini entries + the tool's family/version/tier
159
+ // entries).
160
+ const raw = await loadModelCatalogRaw(binary);
161
+ const discovered = entriesFromRaw(raw);
162
+ const toolModels = toolModelsFromRaw(raw);
163
+ const usingFallback = discovered.length === 0;
164
+ const entries: AgyModelEntry[] = usingFallback ? FALLBACK_MODELS : discovered;
165
+ // Engine latched at load: /agy engine takes effect on the next pi start
166
+ // (documented). Everything below resolves from THIS value - per-call
167
+ // config reads would let a mid-session flip leave ToolRoundTrips,
168
+ // kickIdle, and reentry pointing at the other engine (round-7 finding).
169
+ const engine: Engine = loadConfig().engine;
170
+ // Engine switching requires a restart, so the catalog-time engine read is
171
+ // authoritative for input advertising. Both engines accept images: ACP
172
+ // rides native content blocks; stream-json stages user attachments to
173
+ // temp files and the prompt points the model at them (prompt-images.ts).
174
+ const modelInput: Array<"text" | "image"> = ["text", "image"];
175
+ const models = entries.map((e) => toPiModel(e, modelInput));
176
+
177
+ // failAll reasons the bridge treats as routine (turn end / shutdown
178
+ // sweep), not faults. Shared by the emitters below and the mcpLog
179
+ // classifier so the substring match cannot drift from the text.
180
+ const FAIL_REASON_TURN_END = "antigravity turn ended with an unresolved pi tool call";
181
+ const FAIL_REASON_SHUTDOWN = "antigravity session shut down";
182
+
183
+ // Daily file log: every sink below feeds <configRoot>/extensions-data/
184
+ // orbit-labs-ai/pi-antigravity/logs/<YYYY-MM-DD>.ndjson, where
185
+ // configRoot is dirname(getAgentDir()) (see
186
+ // src/daily-log.ts). Fire-and-forget, secrets redacted, old days pruned.
187
+ // Support flow: "attach the last days' files from that dir".
188
+ const fileLog = createDailyLogger({ dir: logsDir() });
189
+ // Warn tier = user-facing: the default file log keeps ONLY errors (zero
190
+ // routine disk traffic), so a warn that never reaches the UI is lost.
191
+ // Every warn toasts here instead; AGY_DEBUG=1 restores the full file
192
+ // trail. Silent exceptions: deliberate aborts (pi already shows
193
+ // "Operation aborted") and connection exits (the turn's own error block
194
+ // carries real crashes). call-tool-fail needs no exclusion here: its tier
195
+ // is debug or error, never warn. No UI (headless): warn text falls back
196
+ // to stderr.
197
+ const rawFileLog = fileLog.log.bind(fileLog);
198
+ fileLog.log = (event, data, level) => {
199
+ rawFileLog(event, data, level);
200
+ if (level !== "warn") return;
201
+ if (event.startsWith("abort:") || event === "connection-exited") return;
202
+ const d = (data ?? {}) as Record<string, unknown>;
203
+ let text: string;
204
+ if (event === "round-trip-fail") {
205
+ text = `Bridge tool call failed: ${String(d.name ?? "tool")} (${String(d.reason ?? "unknown")})`;
206
+ } else if (event.startsWith("stall:")) {
207
+ text = "Antigravity stalled with no output; the turn was stopped";
208
+ } else if (event.startsWith("timeout:")) {
209
+ text = "Antigravity turn timed out";
210
+ } else if (event.startsWith("exit:") && event !== "exit:0") {
211
+ text = "Antigravity process exited unexpectedly";
212
+ } else if (event === "turn-error") {
213
+ text = `Antigravity turn issue: ${String(d.reason ?? "unknown")}`;
214
+ } else {
215
+ text = `Antigravity warning: ${event}`;
216
+ }
217
+ if (activeUi) activeUi.notify(text, "warning");
218
+ else process.stderr.write(`[pi-antigravity] ${text}\n`);
219
+ };
220
+ fileLog.log(
221
+ "extension-load",
222
+ { engine, models: models.length, fallback: usingFallback, bridge: loadConfig().bridgeTools, askTool: loadConfig().askTool, webTools: loadConfig().webTools },
223
+ "info",
224
+ );
225
+
226
+ const realm = bridgeRealm();
227
+ const store = realm.store;
228
+ // MCP bridge handle, declared early: the ACP engine reads the bridge port
229
+ // at session/new / session/load time.
230
+ let mcpHandle: BridgeEndpoint | null = null;
231
+ let currentSessionManager: unknown;
232
+ let lastConversationId: string | undefined;
233
+ let realmSession: RealmSession | null = null;
234
+ // Session-only visibility overrides; never change either application's MCP config.
235
+ const hiddenBridgeTools = new Set<string>();
236
+ const getBridgeTools = () => bridgedPiTools(pi.getAllTools(), pi.getActiveTools(), loadConfig().bridgeTools, hiddenBridgeTools, engine);
237
+ // Staged gate hooks do not stop agy's own request_permission path, so when
238
+ // true the ACP driver stops letting skipPermissions auto-allow it.
239
+ let gateActive = false;
240
+ // Set while a required approval gate is not staged; provider turns are
241
+ // refused until the shadows are registered (fail closed).
242
+ let gateUnavailable: string | undefined;
243
+ let managedAcpCleanupRan = false;
244
+ let legacyConfigCleanupRan = false;
245
+ let digestMigrationRan = false;
246
+ let legacyConfigCleanupFailed = false;
247
+ let legacyEnvAcpWarningShown = false;
248
+ let legacyFileAcpWarningShown = false;
249
+ let agySetupOffer: (() => Promise<void>) | null = null;
250
+ let agyMissingWarned = false;
251
+ let agyVersionWarned = false;
252
+ let agyVersionMessage = "";
253
+ // Two turn engines behind one contract: `agy acp` (default for new
254
+ // installs) and the stream-json `agy` CLI
255
+ // (fallback). Neither spawns anything until its first turn.
256
+ // ACP log routing: only genuine failures reach stderr. Routine lifecycle
257
+ // (driver-created, spawn, session-new, ...) stays in the driver's
258
+ // #lifecycle ring buffer, visible via /agy doctor. An unfiltered sink fired
259
+ // console.error at extension load ("driver-created"), before any UI exists,
260
+ // and leaked raw driver lines into the terminal on every startup.
261
+ const acpFailures = new Set([
262
+ "start-failed", "spawn-error", "parse-error", "write-failed",
263
+ "mode-apply-failed", "timeout", "stall", "auth-required",
264
+ "session-load-failed-creating-fresh", "connection-exited", "cancel-failed",
265
+ "unsupported-server-request", "session-op-timeout", "session-new-retry",
266
+ ]);
267
+ const streamDriver = new StreamDriver();
268
+ // Mirror the stream driver's lifecycle ring into the daily file log
269
+ // (spawn/exit/abort/stall/recycle). The ACP driver reaches the same file
270
+ // through acpLog below.
271
+ streamDriver.log = (msg, data) => {
272
+ // Level classification mirrors acpLog's failure set: stalls, aborts,
273
+ // timeouts and nonzero exits are the "what broke" greps (warn);
274
+ // turn-start is the per-turn skeleton (info); everything else is
275
+ // verbose-only (debug, needs AGY_DEBUG).
276
+ const failed =
277
+ msg.startsWith("timeout:") ||
278
+ msg.startsWith("stall:") ||
279
+ msg.startsWith("abort:") ||
280
+ (msg.startsWith("exit:") && msg !== "exit:0");
281
+ let level: "warn" | "info" | "debug" = "debug";
282
+ if (failed) level = "warn";
283
+ else if (msg === "turn-start") level = "info";
284
+ fileLog.log(msg, data, level);
285
+ };
286
+ // --- Isolated stream-json MCP home (issue #14) ----------------------------
287
+ // ACP has isolated its MCP view since the private-home work. stream-json
288
+ // spawned against the GLOBAL config, where every session's pi-bridge-<pid>
289
+ // entry is visible to every agy on the machine - and agy hot-reloads the
290
+ // watched config, so the ask-tool suppression dances cannot protect
291
+ // long-lived provider sessions. When the CLI parses --gemini_dir, each
292
+ // stream-json child gets a staged home instead: the global servers minus
293
+ // every foreign bridge, plus this session's own entry (enabled - the
294
+ // suppression marker never applies to our own home, a private-home agy
295
+ // does not read the global file at all).
296
+ const agentsRootOverride = Boolean(process.env.AGY_AGENTS_ROOT);
297
+ // The override must gate the PROBE too, not just staging: carriers stage
298
+ // under AGY_AGENTS_ROOT, outside the home's live agents view.
299
+ const streamHomeProbe = engine === "stream-json" && !agentsRootOverride ? await probeGeminiDirFlag(binary) : undefined;
300
+ const homeMode = resolveStreamHomeMode({ engine, agentsRootOverride, probe: streamHomeProbe });
301
+ const streamHome: { isolated: boolean; path: string | undefined; fallbackReason?: string } = {
302
+ isolated: homeMode === "isolated",
303
+ path: undefined,
304
+ };
305
+ if (homeMode === "isolated") {
306
+ if (streamHomeProbe?.unverifiedVersion) {
307
+ fileLog.log("gemini-dir-unverified", { version: streamHomeProbe.version, verifiedFloor: MIN_GEMINI_DIR_VERSION }, "info");
308
+ }
309
+ streamDriver.stagedHome = () => {
310
+ if (streamHome.path) return streamHome.path;
311
+ try {
312
+ streamHome.path = stageAgyHome({
313
+ prefix: "agy-home",
314
+ ownBridge: mcpHandle
315
+ ? { pid: process.pid, port: mcpHandle.port, token: mcpHandle.token, tokenHeader: TOKEN_HEADER }
316
+ : undefined,
317
+ });
318
+ } catch (err) {
319
+ fileLog.log("stream-home-stage-failed", { error: String(err) }, "warn");
320
+ // The per-pid --add-dir config is not the stream-json delivery
321
+ // path; restore the global registration so the bridge stays
322
+ // reachable when the staged home is unusable. "none" still skips:
323
+ // no pi tools exposed means nothing to reach.
324
+ if (mcpHandle && loadConfig().bridgeTools !== "none") {
325
+ registerBridgeServer({ pid: process.pid, port: mcpHandle.port, token: mcpHandle.realmToken, tokenHeader: TOKEN_HEADER });
326
+ }
327
+ return undefined;
328
+ }
329
+ return streamHome.path;
330
+ };
331
+ streamDriver.releaseStagedHome = (home) => {
332
+ if (streamHome.path === home) streamHome.path = undefined;
333
+ removeStagedAgyHome(home);
334
+ };
335
+ } else if (homeMode === "override-skip") {
336
+ fileLog.log("stream-home-skipped", { reason: "AGY_AGENTS_ROOT override" }, "info");
337
+ } else if (engine === "stream-json") {
338
+ const version = streamHomeProbe?.version ?? "unknown";
339
+ let why = `agy ${version} refused --gemini_dir`;
340
+ if (streamHomeProbe?.detail === "timeout") {
341
+ why = `the agy --gemini_dir probe timed out (agy ${version})`;
342
+ } else if (streamHomeProbe?.detail === "spawn-failure") {
343
+ why = `the agy --gemini_dir probe failed to run (agy ${version})`;
344
+ }
345
+ streamHome.fallbackReason = why;
346
+ fileLog.log("gemini-dir-refused", { version, detail: streamHomeProbe?.detail ?? "refused" }, "warn");
347
+ }
348
+ const acpLog = (msg: string, data?: unknown): void => {
349
+ const expectedExit =
350
+ msg === "connection-exited" &&
351
+ (data as { expected?: boolean } | undefined)?.expected === true;
352
+ let level: "debug" | "warn" | "info" = "debug";
353
+ if (!expectedExit) {
354
+ if (acpFailures.has(msg)) level = "warn";
355
+ else if (msg === "turn-start") level = "info";
356
+ }
357
+ fileLog.log(msg, data, level);
358
+ };
359
+ const acpDriver = new AcpDriver({
360
+ bin: binary,
361
+ binArgs: ["acp"],
362
+ isolateHome: true,
363
+ // Resolved per turn: /agy and AGY_USAGE_ESTIMATE changes apply without
364
+ // a restart. Without this the driver defaults to "estimate" and the
365
+ // config knob (incl. "off") is dead.
366
+ usageEstimate: () => loadConfig().acp.usageEstimate,
367
+ sessionOpTimeoutMs: () => loadConfig().acp.sessionTimeoutMs,
368
+ sessionRetryOnTimeout: () => loadConfig().acp.sessionRetryOnTimeout,
369
+ // ACP request_permission parity with the approval gate: with the gate
370
+ // off, skipPermissions turns auto-allow in the driver. With the gate
371
+ // staged (gateActive) skipPermissions never applies, because the hook
372
+ // does not stop agy's own permission path: approvals.mode allow
373
+ // answers allow, deny answers deny, everything else opens a dialog
374
+ // (esc and headless deny fail-closed) under the shared dialog lock.
375
+ permissionPolicy: () => (loadConfig().approvals.mode === "allow" ? "auto" : "deny"),
376
+ gateActive: () => gateActive,
377
+ onPermissionRequest: async (req) => {
378
+ const ui = activeUi;
379
+ if (loadConfig().approvals.mode === "deny" || !ui) return undefined;
380
+ return withDialogLock(async () => {
381
+ const labels = req.options.map((o) => o.name ?? o.kind ?? o.optionId ?? "?");
382
+ const title = req.toolCall?.title ? `agy requests: ${req.toolCall.title}` : "agy requests permission";
383
+ const picked = await ui.select(title, labels);
384
+ if (picked === undefined) return undefined;
385
+ const idx = labels.indexOf(picked);
386
+ return idx >= 0 ? (req.options[idx]?.optionId ?? undefined) : undefined;
387
+ });
388
+ },
389
+ log: acpLog,
390
+ mcpServers: () => {
391
+ const handle = mcpHandle;
392
+ if (!handle) return [];
393
+ // The bridge 403s any request without the shared-secret header; the
394
+ // stream engine carries it via mcp_config.json, ACP via headers[].
395
+ return [
396
+ {
397
+ name: "pi-bridge",
398
+ type: "http",
399
+ url: `http://127.0.0.1:${handle.port}/mcp`,
400
+ headers: [{ name: TOKEN_HEADER, value: handle.token }],
401
+ },
402
+ ];
403
+ },
404
+ });
405
+ // The active engine is resolved from the latched load-time value.
406
+ const activeDriver = (): TurnDriver => (engine === "acp" ? acpDriver : streamDriver);
407
+ // The provider's stream-json slot gets the STREAM driver explicitly - never
408
+ // activeDriver(), or a load-time acp engine would make deps.driver and
409
+ // deps.acpDriver the same object and break the engine identity check.
410
+ const driver = streamDriver;
411
+ // The no-patch pi-tool round-trip store: the MCP bridge parks calls here;
412
+ // the provider emits them as real pi toolUse turns and completes them from
413
+ // the next call's toolResult.
414
+ const roundTrips = new ToolRoundTrips(
415
+ activeDriver,
416
+ (s, d, level) =>
417
+ fileLog.log(
418
+ s,
419
+ d,
420
+ level ?? (s === "round-trip-fail" ? "warn" : "debug"),
421
+ ),
422
+ // Delegation tools hold the sync window 120s (issue #6); config adds
423
+ // extra long-running names, re-read per call so edits apply live.
424
+ { escalateAfterMs: (name) => defaultEscalateAfterMs(name, loadConfig().escalateLongTools) },
425
+ );
426
+ const replay = new WrapperReplay();
427
+ // Subagent roster: folded from every driver activity (both engines) via
428
+ // the provider; /agy subagents renders it. In-memory, process-lifetime.
429
+ const roster = new SubagentRoster();
430
+ // ACP tool activity is display-only: durable Pi entries with native-looking
431
+ // titles and optional diffs. Unlike a synthetic Pi toolCall this does not
432
+ // re-execute edits, park the turn, or add tool results to model context.
433
+ if (engine === "acp") {
434
+ pi.registerEntryRenderer<NativeDisplayEvent>("agy-native-event", (entry, { expanded }, theme) => {
435
+ const event = entry.data;
436
+ // Collapsed detail: most-specific signal wins (path, command, agy's own
437
+ // display text). The name is NOT a fallback here - it rendered "ls ls"
438
+ // duplication whenever the event carried neither path nor command.
439
+ const firstLine = (value: string | undefined): string | undefined => value?.split(/\r?\n/, 1)[0].trim() || undefined;
440
+ const detail = event?.path ? path.basename(event.path) : firstLine(event?.query) ?? firstLine(event?.command) ?? firstLine(event?.output);
441
+ const status = event?.status === "failed" ? theme.fg("error", "✗") : theme.fg("success", "✓");
442
+ const lines = [`${status} ${theme.fg("toolTitle", event?.name ?? "Antigravity")}${detail ? ` ${theme.fg("muted", detail.slice(0, 160))}` : ""}`];
443
+ if (expanded) {
444
+ if (event?.path) lines.push(theme.fg("dim", event.path));
445
+ if (event?.diff) {
446
+ for (const line of event.diff.split("\n")) {
447
+ let color: "toolDiffAdded" | "toolDiffRemoved" | "toolDiffContext" = "toolDiffContext";
448
+ if (line.startsWith("+")) color = "toolDiffAdded";
449
+ else if (line.startsWith("-")) color = "toolDiffRemoved";
450
+ lines.push(theme.fg(color, line));
451
+ }
452
+ }
453
+ if (event?.output && (!event.diff || event.status === "failed")) lines.push(theme.fg("toolOutput", event.output));
454
+ }
455
+ return new Text(lines.join("\n"), 0, 0);
456
+ });
457
+ // Collapsed poll runs: one ♊︎-marked counted line per consecutive poll
458
+ // burst instead of one entry per poll.
459
+ pi.registerEntryRenderer<PollRunData>("agy-poll-run", (entry, { expanded }, theme) => {
460
+ const run = entry.data;
461
+ const count = run?.count ?? 0;
462
+ const label = `Poll ${run?.target ?? "bridge call"} (x${count}${run?.state === "failed" ? ", failed" : ""})`;
463
+ const lines = [`♊︎ ${theme.fg("toolTitle", POLL_TOOL_NAME)} ${theme.fg("muted", label)}`];
464
+ if (expanded && run) {
465
+ const time = (iso: string): string => new Date(iso).toLocaleTimeString();
466
+ lines.push(theme.fg("dim", `${count} ${count === 1 ? "poll" : "polls"}, ${time(run.firstAt)} → ${time(run.lastAt)}`));
467
+ }
468
+ return new Text(lines.join("\n"), 0, 0);
469
+ });
470
+ }
471
+ let pendingNativeTools = 0;
472
+ const pollRuns = new PollRunFolder();
473
+ const closePollRun = (): void => {
474
+ const settled = pollRuns.flush();
475
+ if (settled) pi.appendEntry<PollRunData>("agy-poll-run", settled);
476
+ setDimStatus("agy-poll", undefined);
477
+ };
478
+ // Footer statuses render muted, matching pi-hostname's dim treatment.
479
+ const setDimStatus = (key: string, text: string | undefined): void => {
480
+ const ui = activeUi;
481
+ if (!ui) return;
482
+ ui.setStatus(key, text === undefined ? undefined : ui.theme.fg("dim", text));
483
+ };
484
+ const onNativeEvent = (event: NativeDisplayEvent): void => {
485
+ if (engine !== "acp") return;
486
+ // Polls are bridge-local (never get a genuine Pi card); the mcpServer
487
+ // tag is unreliable on these frames, so the tool name discriminates.
488
+ if (event.name === POLL_TOOL_NAME) {
489
+ const view = event.callId ? roundTrips.poll(event.callId) : undefined;
490
+ const switched = pollRuns.add(view?.name ?? "unknown call", view?.state ?? "running", new Date());
491
+ if (switched) pi.appendEntry<PollRunData>("agy-poll-run", switched);
492
+ const open = pollRuns.open;
493
+ setDimStatus("agy-poll", open ? `♊︎ bridge_poll_result → ${open.target} (x${open.count})` : undefined);
494
+ return;
495
+ }
496
+ closePollRun();
497
+ if (/^pi-bridge(?:-\d+)?$/.test(event.mcpServer ?? "")) return;
498
+ // MCP calls through our own pi-bridge already have genuine Pi tool cards;
499
+ // only native Antigravity / other MCP events need display-only entries.
500
+ if (event.status === "started") {
501
+ pendingNativeTools++;
502
+ setDimStatus("agy-native", `agy ${event.name}… (${pendingNativeTools})`);
503
+ return;
504
+ }
505
+ pendingNativeTools = Math.max(0, pendingNativeTools - 1);
506
+ if (pendingNativeTools === 0) activeUi?.setStatus("agy-native", undefined);
507
+ // Bound persisted session size; the ACP result and diff may be megabytes.
508
+ // path stays whole: the compaction fileOps (#32) fold it verbatim.
509
+ pi.appendEntry<NativeDisplayEvent>("agy-native-event", {
510
+ ...event,
511
+ output: event.output?.slice(0, 4000),
512
+ diff: event.diff?.slice(0, 12000),
513
+ command: event.command?.slice(0, 500),
514
+ query: event.query?.slice(0, 500),
515
+ });
516
+ };
517
+ // Native re-exec only emits for builtins actually active in the session;
518
+ // anything else (or an unknown name) falls back to the wrapper card.
519
+ const nativeActive = (name: string): boolean => {
520
+ try {
521
+ return pi.getActiveTools().includes(name);
522
+ } catch {
523
+ return false;
524
+ }
525
+ };
526
+ // A settled turn cannot answer its parked calls; the driver never sees
527
+ // ToolRoundTrips, so the provider bridges the two here (both engines).
528
+ // The file log records the outcome first: ERROR/aborted turns are the
529
+ // single most useful support signal.
530
+ const onTurnEnd = (outcome: TurnOutcome) => {
531
+ fileLog.log(
532
+ "turn-end",
533
+ // Error text can embed the child's stderr tail; cap it in line with
534
+ // the ACP driver's 200-char stderr slices.
535
+ { status: outcome.status, error: outcome.error?.slice(0, 500), aborted: outcome.aborted },
536
+ outcome.status === "OK" ? "info" : "warn",
537
+ );
538
+ roundTrips.failAll(FAIL_REASON_TURN_END);
539
+ // Closes a poll run that no display event flushed.
540
+ closePollRun();
541
+ // Stamp live escalations with the ended turn's conversation: the park
542
+ // pass returns before the provider's store.set, so a first-turn park
543
+ // has no other record of where its result must be re-delivered.
544
+ if (outcome.conversationId) {
545
+ lastConversationId = outcome.conversationId;
546
+ roundTrips.stampConversation(outcome.conversationId);
547
+ }
548
+ };
549
+ streamDriver.onTurnEnd = onTurnEnd;
550
+ acpDriver.onTurnEnd = onTurnEnd;
551
+ // Pi's normal footer receives the incremental usage above. Mark the
552
+ // numbers as estimates in the status area too; ACP currently drops the
553
+ // SDK's exact usage metadata before it reaches the client.
554
+ if (engine === "acp") {
555
+ let lastUsageStatus = "";
556
+ // Per-session usage accumulator. Replace-per-message, never sum-per-event:
557
+ // message_update refires with growing totals while an assistant message
558
+ // streams, so adding on every event would double-count.
559
+ const usageByMessage = new Map<number, { input: number; output: number; cacheRead: number }>();
560
+ let usageTurnStart = { calls: 0, input: 0, output: 0, cacheRead: 0 };
561
+ const usageSums = () => {
562
+ let input = 0;
563
+ let output = 0;
564
+ let cacheRead = 0;
565
+ for (const u of usageByMessage.values()) {
566
+ input += u.input;
567
+ output += u.output;
568
+ cacheRead += u.cacheRead;
569
+ }
570
+ return { input, output, cacheRead, calls: usageByMessage.size };
571
+ };
572
+ pi.on("agent_start", () => {
573
+ usageTurnStart = usageSums();
574
+ });
575
+ pi.on("message_update", (event, ctx) => {
576
+ if (!ctx.hasUI || event.message.role !== "assistant" || event.message.provider !== "antigravity" || loadConfig().acp.usageEstimate === "off") return;
577
+ const { input, output, cacheRead } = event.message.usage;
578
+ // AssistantMessage carries no id; the request-start timestamp is the
579
+ // per-inference key and is stable across streaming updates.
580
+ usageByMessage.set(event.message.timestamp, { input, output, cacheRead });
581
+ const sums = usageSums();
582
+ const cacheBase = sums.input + sums.cacheRead;
583
+ const cachePct = cacheBase > 0 ? Math.round((sums.cacheRead / cacheBase) * 100) : 0;
584
+ const status = ctx.ui.theme.fg("dim", `ACP ≈ ${input} in / ${output} out · cache ${cachePct}% · ${sums.calls} calls`);
585
+ if (status !== lastUsageStatus) {
586
+ lastUsageStatus = status;
587
+ ctx.ui.setStatus("agy-usage", status);
588
+ }
589
+ });
590
+ const clearUsageStatus = (_event: unknown, ctx: { hasUI: boolean; ui: ExtensionUIContext }) => {
591
+ const sums = usageSums();
592
+ const turn = {
593
+ calls: sums.calls - usageTurnStart.calls,
594
+ input: sums.input - usageTurnStart.input,
595
+ output: sums.output - usageTurnStart.output,
596
+ cacheRead: sums.cacheRead - usageTurnStart.cacheRead,
597
+ };
598
+ if (turn.calls > 0) {
599
+ const base = turn.input + turn.cacheRead;
600
+ fileLog.log("turn-usage", { ...turn, cachePct: base > 0 ? Math.round((turn.cacheRead / base) * 100) : 0 });
601
+ }
602
+ lastUsageStatus = "";
603
+ if (ctx.hasUI) ctx.ui.setStatus("agy-usage", undefined);
604
+ };
605
+ pi.on("agent_end", (event, ctx) => {
606
+ clearUsageStatus(event, ctx);
607
+ usageByMessage.clear();
608
+ pendingNativeTools = 0;
609
+ closePollRun();
610
+ if (ctx.hasUI) ctx.ui.setStatus("agy-native", undefined);
611
+ });
612
+ pi.on("session_shutdown", (event, ctx) => {
613
+ clearUsageStatus(event, ctx);
614
+ pendingNativeTools = 0;
615
+ if (ctx.hasUI) ctx.ui.setStatus("agy-native", undefined);
616
+ });
617
+ }
618
+ // agy-native background-task watcher (src/background-watch.ts). The
619
+ // provider flags turns that used the WaitMsBeforeAsync shape; at the
620
+ // settled turn end this arms a filesystem watcher over the conversation's
621
+ // task logs and wakes the model when they go quiet. One watcher per
622
+ // conversation; armed/settled pi entries survive /resume so a reload
623
+ // mid-watch re-arms instead of losing the completion notice.
624
+ const backgroundWatchers = new Map<string, BackgroundWatchHandle>();
625
+ let backgroundWatchDisposed = false;
626
+ const sendTaskWake = (content: string): void => {
627
+ if (backgroundWatchDisposed) return;
628
+ try {
629
+ // Custom message at user-role authority: redact secrets, banner and
630
+ // liveness-only wording come from buildTaskWakeContent.
631
+ pi.sendMessage({ customType: "agy-background-task", content: redactText(content), display: true }, { triggerTurn: true, deliverAs: "followUp" });
632
+ } catch {
633
+ // Stale runtime after shutdown won the race; the notice is lost, stay quiet.
634
+ }
635
+ };
636
+ const armConversationWatcher = (conversationId: string, turnStartMs: number, opts?: { armedAt?: number; recordArmed?: boolean }): void => {
637
+ const conversationDir = agyConversationDir(engine, conversationId);
638
+ backgroundWatchers.get(conversationId)?.stop();
639
+ const armedAt = opts?.armedAt ?? Date.now();
640
+ if (opts?.recordArmed !== false) {
641
+ try {
642
+ pi.appendEntry<BackgroundWatchEntry>("agy-background-watch", { kind: "armed", conversationId, turnStartMs, armedAt });
643
+ } catch { /* persistence is best-effort; the in-memory watch still works */ }
644
+ }
645
+ const handle = armBackgroundWatch({
646
+ conversationId,
647
+ conversationDir,
648
+ turnStartMs,
649
+ listTasks: listAgyTasks,
650
+ tail: tailAgyTaskLog,
651
+ onSettle: (result) => {
652
+ try {
653
+ pi.appendEntry<BackgroundWatchEntry>("agy-background-watch", { kind: "settled", conversationId, armedAt, settledAt: Date.now(), taskIds: result.taskIds });
654
+ } catch { /* best-effort */ }
655
+ },
656
+ sendWake: sendTaskWake,
657
+ log: fileLog.log.bind(fileLog),
658
+ });
659
+ backgroundWatchers.set(conversationId, handle);
660
+ };
661
+ // Reload resume: pi wipes extension module state on /new, /resume, /fork
662
+ // and /reload while the agy-side task keeps running. Armed records without
663
+ // a settled twin re-arm; the settled record prevents any double wake.
664
+ pi.on("session_start", (_event, ctx) => {
665
+ try {
666
+ const records: Array<{ customType: string; data: unknown }> = [];
667
+ for (const e of ctx.sessionManager.getEntries()) {
668
+ if ("customType" in e && e.customType === "agy-background-watch") {
669
+ records.push({ customType: e.customType, data: (e as { data?: unknown }).data });
670
+ }
671
+ }
672
+ for (const plan of rearmPlansFromEntries(records)) {
673
+ if (!backgroundWatchers.has(plan.conversationId)) {
674
+ armConversationWatcher(plan.conversationId, plan.turnStartMs, { armedAt: plan.armedAt, recordArmed: false });
675
+ fileLog.log("background-watch-rearm", { conversation: plan.conversationId, armedAt: plan.armedAt }, "info");
676
+ }
677
+ }
678
+ } catch (err) {
679
+ fileLog.log("background-watch-sweep-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
680
+ }
681
+ });
682
+ // Bindings must reach disk before the host exits (headless/print modes
683
+ // exit right after session_shutdown).
684
+ pi.on("session_shutdown", () => store.flush());
685
+ // Session keys whose bound agy conversation was rotated on session_compact
686
+ // so the next turn starts a fresh backend conversation and ships the
687
+ // compaction summary once (even when config.digest is disabled).
688
+ const pendingCompactionHandoff = new Set<string>();
689
+ pi.on("session_shutdown", () => {
690
+ backgroundWatchDisposed = true;
691
+ for (const handle of backgroundWatchers.values()) handle.stop();
692
+ backgroundWatchers.clear();
693
+ pendingCompactionHandoff.clear();
694
+ });
695
+ pi.on("session_before_compact", async (event) => {
696
+ try {
697
+ // Native ACP activity lives only in display entries the summarizer
698
+ // never sees; fileOps is what carries it into the summary (#32).
699
+ // Older peer builds may omit branchEntries despite the type (#32).
700
+ collectNativeFileOps(event.branchEntries ?? [], event.preparation.fileOps);
701
+ } catch (err) {
702
+ fileLog.log("native-fileops-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
703
+ }
704
+ try {
705
+ // A parked turn can only be unparked by the continuation the
706
+ // summarizer itself blocks, so close it before the summary runs (#33).
707
+ const preempted = await preemptParkedTurnForCompaction(activeDriver(), roundTrips, {
708
+ log: (msg, data, level) => fileLog.log(msg, data, level ?? "info"),
709
+ });
710
+ if (preempted && activeUi) {
711
+ activeUi.notify(
712
+ "Compaction interrupted a parked agy turn; its tool results will be re-sent to the next agy conversation.",
713
+ "warning",
714
+ );
715
+ }
716
+ } catch (err) {
717
+ fileLog.log(
718
+ "compaction-preempt-error",
719
+ { error: err instanceof Error ? err.message : String(err) },
720
+ "warn",
721
+ );
722
+ }
723
+ });
724
+ pi.on("session_compact", (_event, ctx) => {
725
+ try {
726
+ // Shape-cast as in model_select below: tolerate pi builds whose dts
727
+ // omits getSessionId.
728
+ const sm = ctx.sessionManager as { getSessionId?: () => string };
729
+ const sid = sm.getSessionId?.();
730
+ const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
731
+ clearSteerCursor(key);
732
+ const rotated = rotateSessionOnCompaction(store, key, pendingCompactionHandoff);
733
+ if (rotated) {
734
+ fileLog.log("session-compact-rotate", { key, previousConversation: rotated }, "info");
735
+ }
736
+ } catch (err) {
737
+ fileLog.log("session-compact-rotate-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
738
+ }
739
+ });
740
+ // Model-switch handoff toast: entering an unbound antigravity model
741
+ // mid-session opens a fresh agy conversation on the next turn; the
742
+ // digest re-delivers pi-side context into it. UI only.
743
+ pi.on("model_select", (event, ctx) => {
744
+ try {
745
+ const msg = handoffToast({
746
+ api: event.model?.api,
747
+ digestEnabled: loadConfig().digest,
748
+ source: event.source,
749
+ bound: (() => {
750
+ // Shape-cast as in the session_compact handler above: tolerate pi
751
+ // builds whose dts omits getSessionId.
752
+ const sm = ctx.sessionManager as { getSessionId?: () => string };
753
+ const sid = sm.getSessionId?.();
754
+ const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
755
+ return store.get(key) !== null;
756
+ })(),
757
+ hasContext: ctx.sessionManager
758
+ .getEntries()
759
+ .some((e) => (e as { type?: string }).type === "message"),
760
+ });
761
+ if (msg && ctx.hasUI) ctx.ui.notify(msg, "info");
762
+ } catch (err) {
763
+ fileLog.log("handoff-toast-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
764
+ }
765
+ });
766
+ const streamSimple = createStreamSimple({
767
+ entries,
768
+ store,
769
+ driver,
770
+ acpDriver,
771
+ roundTrips,
772
+ replay,
773
+ nativeActive,
774
+ onNativeEvent,
775
+ onNativeBackground: (info) => armConversationWatcher(info.conversationId, info.turnStartMs),
776
+ roster,
777
+ gateUnavailable: () => gateUnavailable,
778
+ pendingCompactionHandoff,
779
+ hasActiveTool: (name) => pi.getActiveTools().includes(name),
780
+ engine,
781
+ log: fileLog.log.bind(fileLog),
782
+ });
783
+
784
+ const joinRealm = () =>
785
+ realm.join({
786
+ sessionId: () => liveSessionId(currentSessionManager),
787
+ streamSimple,
788
+ hasActiveTurn: () => (engine === "acp" ? acpDriver.activeHandle !== null : streamDriver.activeHandle !== null),
789
+ conversationId: () =>
790
+ (engine === "acp" ? acpDriver.snapshot().conversationId : streamDriver.snapshot().conversationId)
791
+ ?? lastConversationId,
792
+ });
793
+
794
+ pi.registerProvider("antigravity", {
795
+ name: "Antigravity (agy)",
796
+ baseUrl: "agy-bridge://antigravity",
797
+ apiKey: "not-used",
798
+ api: "agy-bridge",
799
+ models: models.map((m) => ({
800
+ id: m.id,
801
+ name: m.name,
802
+ api: m.api,
803
+ reasoning: m.reasoning,
804
+ thinkingLevelMap: m.thinkingLevelMap,
805
+ input: m.input,
806
+ cost: m.cost,
807
+ contextWindow: m.contextWindow,
808
+ maxTokens: m.maxTokens,
809
+ })),
810
+ // pi-ai's provider registry is process-global and every session's factory
811
+ // call registers again: register the realm's stable dispatcher so each
812
+ // call routes to its own session's streamSimple.
813
+ streamSimple: realm.streamSimple,
814
+ });
815
+
816
+ registerAgyCommand(pi, {
817
+ entries,
818
+ store,
819
+ usingFallback,
820
+ driver,
821
+ acpDriver,
822
+ engine,
823
+ getMcpPort: () => mcpHandle?.port ?? null,
824
+ streamIsolated: streamHome.isolated,
825
+ bridgeTools: getBridgeTools,
826
+ hiddenBridgeTools,
827
+ fileLog,
828
+ roster,
829
+ pendingCompactionHandoff,
830
+ checkAgySetup,
831
+ setActiveUi: (ui) => {
832
+ activeUi = ui;
833
+ },
834
+ });
835
+
836
+ // AskAntigravity tool: one-shot delegation to agy (ported from
837
+ // pi-ask-antigravity). When both extensions are installed, the bridge wins
838
+ // and pi-ask-antigravity registers nothing (its load-time defer guard
839
+ // detects this package via import.meta.resolve). Opt-out: askTool=false
840
+ // (config file, AGY_ASK_TOOL, /agy ask, or the picker) skips registration
841
+ // entirely - users who want only the provider keep a clean tool list.
842
+ // Note: the active flag below is set regardless of askTool, so
843
+ // pi-ask-antigravity keeps deferring even then: off means NO delegation
844
+ // tool from either package, not a fallback to pi-ask-antigravity.
845
+ if (loadConfig().askTool) await registerAskAntigravityTool(pi, toolModels, fileLog.log.bind(fileLog));
846
+ // Web tools are opt-in (config.webTools, default off): Antigravity sessions
847
+ // already have native web tools; these serve NON-Antigravity providers.
848
+ if (loadConfig().webTools) registerWebTools(pi, { log: fileLog.log.bind(fileLog) });
849
+
850
+ // Display-only wrapper tool: the provider emits mutating agy steps as
851
+ // toolCalls against it (never re-executed - execute() replays the output
852
+ // agy already recorded). Empty description on purpose: no model should
853
+ // call it, it exists so pi renders proper toolCall/toolResult cards.
854
+ // It must stay active, since pi executes only active tools and the
855
+ // provider's emitted calls would otherwise fail "not found", but
856
+ // prepareLoadout leaves its declaration out of every model request and
857
+ // model-only exposure keeps it out of codemode's callable catalog.
858
+ pi.registerTool({
859
+ name: "antigravity",
860
+ label: "Antigravity",
861
+ description: "",
862
+ exposure: "model-only",
863
+ prepareLoadout: () => ({ hiddenDeclarations: ["antigravity"] }),
864
+ parameters: Type.Object({
865
+ tool: Type.String({ description: "agy tool name that produced this step." }),
866
+ key: Type.String({ description: "Internal replay key. Do not fabricate." }),
867
+ }),
868
+ execute: async (_toolCallId, params) => {
869
+ const key = (params as { key?: string }).key ?? "";
870
+ const output = replay.take(key) ?? `(no recorded output for ${key})`;
871
+ return { content: [{ type: "text", text: output }], details: { replay: true } };
872
+ },
873
+ });
874
+
875
+ function offerSetup(ui: ExtensionUIContext, explicit = false): void {
876
+ if (agySetupOffer && explicit) {
877
+ ui.notify(`CLI setup was already offered in this session. ${agyMissingMessage()}`, "info");
878
+ }
879
+ agySetupOffer ??= createAgySetupOffer({
880
+ ui,
881
+ binaryOverride: process.env.AGY_BIN || undefined,
882
+ missingMessage: agyMissingMessage,
883
+ log: (event, data, level) => fileLog.log(event, data, level),
884
+ });
885
+ void agySetupOffer();
886
+ }
887
+
888
+ // Availability checks never block bridge startup. The setup offer owns
889
+ // prompting, deduplication, and failure containment.
890
+ async function checkAgySetup(ctx: { ui: ExtensionUIContext; mode: string }, selectedEngine: Engine, explicit = false): Promise<void> {
891
+ try {
892
+ if (!isAgyInstalled(binary)) {
893
+ if (ctx.mode === "tui") {
894
+ offerSetup(ctx.ui, explicit);
895
+ } else if (!agyMissingWarned) {
896
+ agyMissingWarned = true;
897
+ process.stderr.write(`[pi-antigravity] ${agyMissingMessage()}\n`);
898
+ }
899
+ return;
900
+ }
901
+ if (agyVersionWarned) {
902
+ // The installer no-ops on an existing install, so re-offering it
903
+ // on an explicit re-check would toast a false "installed" (issue #19).
904
+ if (explicit && ctx.mode === "tui") ctx.ui.notify(agyVersionMessage, "warning");
905
+ return;
906
+ }
907
+ const rawCheck = await checkAgyCliVersion(binary);
908
+ const floor = selectedEngine === "acp" ? MIN_AGY_ACP_VERSION : MIN_AGY_VERSION;
909
+ const check = agyVersionVerdict(rawCheck.raw, floor);
910
+ if (check.status !== "unsupported") return;
911
+ agyVersionWarned = true;
912
+ agyVersionMessage = agyUpdateMessage(check.version ?? rawCheck.raw, floor);
913
+ if (ctx.mode === "tui") {
914
+ ctx.ui.notify(agyVersionMessage, "warning");
915
+ } else {
916
+ process.stderr.write(`[pi-antigravity] ${agyVersionMessage}\n`);
917
+ }
918
+ } catch (err) {
919
+ fileLog.log("agy-version-check", { error: String(err) }, "warn");
920
+ }
921
+ }
922
+
923
+ // MCP tool bridge: expose pi's tools to agy over localhost Streamable HTTP.
924
+ // Calls park in the provider's round-trip store and complete through pi's
925
+ // normal toolUse loop (native cards, permissions, hooks) - no patch, no
926
+ // privileged API. Started on session_start, torn down on session_shutdown.
927
+ pi.on("session_start", async (event, ctx) => {
928
+ currentSessionManager = ctx.sessionManager;
929
+ realmSession ??= joinRealm();
930
+ if (ctx.hasUI) activeUi = ctx.ui;
931
+ // First-run engine picker: ask once, on the first interactive start,
932
+ // which turn engine to use. Skipped headless (ctx.mode !== "tui"),
933
+ // when AGY_ENGINE is set, or once any config file exists (any save -
934
+ // even of an unrelated knob - means the user has been here before).
935
+ // esc = decide later: nothing is written, the picker reappears next
936
+ // start. Like /agy engine, the choice applies on the next start
937
+ // (drivers wire at load). The await intentionally runs before the
938
+ // bridge startup below: on a genuine first run the modal blocks input
939
+ // anyway, so the delay is invisible.
940
+ let setupEngine = engine;
941
+ if (event.reason === "startup" && ctx.mode === "tui" && shouldOfferEnginePicker(configPath())) {
942
+ // Best-effort, like the legacy-patch notice below: a picker failure
943
+ // (mid-prompt TUI teardown, resize races) must never take down the
944
+ // rest of session_start - the MCP bridge startup included. The
945
+ // default engine keeps working untouched.
946
+ try {
947
+ const picked = await showEnginePicker(ctx.ui);
948
+ if (picked) {
949
+ // Consent gate: a first-run stream-json pick gets the same
950
+ // warning as every other path before it persists anything.
951
+ let chosen: Engine | undefined = picked;
952
+ if (picked === "stream-json") {
953
+ const verdict = await showStreamJsonWarning(ctx.ui);
954
+ if (verdict === undefined) {
955
+ // Decide later: nothing persisted, this session runs the
956
+ // acp default, the picker re-asks next start.
957
+ ctx.ui.notify("Stream-json not confirmed; this session runs the acp default. Decide later with /agy engine.", "info");
958
+ chosen = undefined;
959
+ } else {
960
+ chosen = verdict === "acp" ? "acp" : "stream-json";
961
+ if (chosen === "stream-json") ctx.ui.notify(streamJsonKeptMessage(), "warning");
962
+ }
963
+ }
964
+ if (chosen) {
965
+ setupEngine = chosen;
966
+ saveConfig(streamJsonSavePatch(chosen, chosen === "stream-json"));
967
+ ctx.ui.notify(savedEngineMessage(chosen), "info");
968
+ }
969
+ }
970
+ } catch (err) {
971
+ fileLog.log("engine-picker", { error: String(err) }, "warn");
972
+ process.stderr.write(`[pi-antigravity] engine picker failed: ${String(err)}\n`);
973
+ }
974
+ }
975
+ // stream-json consent migration (google-antigravity/antigravity-cli#1890):
976
+ // existing installs resolved to stream-json (the legacy silent fallback or
977
+ // an old explicit choice) see the warning once; esc re-asks next start,
978
+ // exactly like the first-run picker. AGY_ENGINE=stream-json skips the
979
+ // modal: typing the env var is the explicit act. The switch persists for
980
+ // the next start (drivers wire at load), like /agy engine.
981
+ try {
982
+ const cfg = loadConfig();
983
+ if (
984
+ (event.reason === "startup" || event.reason === "resume") &&
985
+ ctx.mode === "tui" &&
986
+ process.env.AGY_ENGINE === undefined &&
987
+ shouldWarnStreamJson(cfg.engine, cfg.streamJsonAcknowledged)
988
+ ) {
989
+ const verdict = await showStreamJsonWarning(ctx.ui);
990
+ if (verdict === "keep") {
991
+ saveConfig(streamJsonSavePatch("stream-json", true));
992
+ ctx.ui.notify(streamJsonKeptMessage(), "warning");
993
+ } else if (verdict === "acp" && loadConfig().mode !== "plan") {
994
+ saveConfig(streamJsonSavePatch("acp", true));
995
+ ctx.ui.notify(savedEngineMessage("acp"), "info");
996
+ } else if (verdict === "acp") {
997
+ // Plan mode blocks ACP: refuse without persisting so the
998
+ // modal re-asks once the mode allows the switch.
999
+ ctx.ui.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
1000
+ }
1001
+ }
1002
+ } catch (err) {
1003
+ fileLog.log("streamjson-warning", { error: String(err) }, "warn");
1004
+ process.stderr.write(`[pi-antigravity] stream-json warning failed: ${String(err)}\n`);
1005
+ }
1006
+ // The retired acp.bin key heals itself in the config file; the env var
1007
+ // lives outside our reach, so it is the only case that still warns.
1008
+ // Independent once-flags: a failed cleanup must never suppress the
1009
+ // env-var warning (or vice versa) for the rest of the process.
1010
+ if (!legacyConfigCleanupRan) {
1011
+ legacyConfigCleanupRan = true;
1012
+ try {
1013
+ removeLegacyAcpBin();
1014
+ } catch (err) {
1015
+ legacyConfigCleanupFailed = true;
1016
+ fileLog.log("legacy-acp-config-cleanup", { error: String(err) }, "error");
1017
+ }
1018
+ }
1019
+ // One-time digest-default migration (issue #25): a config saved before
1020
+ // the default flip carries digest:false as a bare default, silently
1021
+ // keeping mid-session context handoffs off. Best-effort like the
1022
+ // cleanup above: a failure must never block session_start.
1023
+ if (!digestMigrationRan) {
1024
+ digestMigrationRan = true;
1025
+ try {
1026
+ const migrated = migrateStaleDigestDefault().migrated;
1027
+ fileLog.log("digest-default-migration", { migrated }, migrated ? "info" : "debug");
1028
+ if (migrated && ctx.hasUI) {
1029
+ ctx.ui.notify(
1030
+ "digest was still off from an older default; enabled it (keeps context visible on model switches). Keep it off with /agy digest off.",
1031
+ "info",
1032
+ );
1033
+ }
1034
+ } catch (err) {
1035
+ fileLog.log("digest-default-migration", { error: String(err) }, "warn");
1036
+ }
1037
+ }
1038
+ if (!legacyEnvAcpWarningShown && process.env.AGY_ACP_BIN?.trim()) {
1039
+ legacyEnvAcpWarningShown = true;
1040
+ const msg = "AGY_ACP_BIN is set but no longer used; turns run \"agy acp\" from the CLI. Remove it from your shell config, then start a new terminal.";
1041
+ if (ctx.hasUI) ctx.ui.notify(msg, "warning");
1042
+ else process.stderr.write(`[pi-antigravity] ${msg}\n`);
1043
+ }
1044
+ if (!legacyFileAcpWarningShown && legacyConfigCleanupFailed) {
1045
+ legacyFileAcpWarningShown = true;
1046
+ const msg = `Couldn't remove the old "bin" setting from ${configPath()} (details in the bridge log). Delete the "bin" line under "acp" by hand; turns run "agy acp" from the CLI.`;
1047
+ if (ctx.hasUI) ctx.ui.notify(msg, "warning");
1048
+ else process.stderr.write(`[pi-antigravity] ${msg}\n`);
1049
+ }
1050
+ // A hand editor never runs /agy: surface parse fallbacks where they
1051
+ // happen (issue #23). Headless sessions keep the stderr record.
1052
+ const configWarnings = loadConfig().parseWarnings;
1053
+ if (configWarnings?.length) {
1054
+ const msg = configWarningsMessage(configWarnings);
1055
+ if (ctx.hasUI) ctx.ui.notify(msg, "warning");
1056
+ else process.stderr.write(`[pi-antigravity] ${msg}\n`);
1057
+ }
1058
+ if (!managedAcpCleanupRan) {
1059
+ managedAcpCleanupRan = true;
1060
+ try {
1061
+ const cleanup = cleanupManagedAcpInstall();
1062
+ if (cleanup.removedBuilds.length > 0) fileLog.log("legacy-acp-cleanup", cleanup, "info");
1063
+ } catch (err) {
1064
+ fileLog.log("legacy-acp-cleanup", { error: String(err) }, "warn");
1065
+ }
1066
+ }
1067
+ void checkAgySetup(ctx, setupEngine);
1068
+ // Legacy cleanup: users who ran the old consent-gated patcher still
1069
+ // carry pi.invokeTool in their installed pi. Inert, but tell them once
1070
+ // and offer /agy patch-cleanup. Never auto-edits the install.
1071
+ try {
1072
+ if (!loadConfig().patchCleanupNotified && patchStatus().present) {
1073
+ // Flag after surfacing, not before: headless sessions log to
1074
+ // stderr (ctx.ui.notify is a no-op without a UI), so the notice
1075
+ // is never silently dropped.
1076
+ const msg =
1077
+ "Your pi install still carries the old pi.invokeTool patch. It is unused and harmless; a pi update also removes it. To restore the original files from the backup now: /agy patch-cleanup";
1078
+ if (ctx.hasUI) ctx.ui.notify(msg, "info");
1079
+ else process.stderr.write(`[pi-antigravity] ${msg}\n`);
1080
+ saveConfig({ patchCleanupNotified: true });
1081
+ }
1082
+ } catch {
1083
+ /* detection is best-effort */
1084
+ }
1085
+ // Bridge failure logger. Routine lifecycle (listening,
1086
+ // bridge-config-written/removed, closed) is normal startup/teardown
1087
+ // traffic: toasting it every session, or pinning it via stderr in
1088
+ // headless mode, was noise. Only genuine failures surface - as a
1089
+ // warning toast (ctx.ui.notify, ephemeral) or stderr when headless.
1090
+ // Per-turn success events (list-tools / call-tool) stay silent.
1091
+ const mcpLog = (s: string, d?: unknown) => {
1092
+ const failures = new Set([
1093
+ "http-error", "bridge-config-write-failed", "call-tool-fail",
1094
+ "transport-error", "handleRequest-error", "request-error",
1095
+ "request-handler-error", "unauthorized",
1096
+ ]);
1097
+ // Daily file log gets every bridge event (call-tool/list-tools
1098
+ // traffic included - it is how a parked round-trip is traced); the
1099
+ // filters below only decide what reaches the user. Bridge calls
1100
+ // start/end at info (one record per tool call, the fragile-path
1101
+ // skeleton); list-tools and startup chatter stay verbose.
1102
+ // Routine abort traffic (failAll on turn end / session shutdown
1103
+ // answers every parked call with an error) is not a fault: debug
1104
+ // only. Any other call-tool-fail is a real rejection (e.g. "no
1105
+ // active antigravity turn" from a client that should not see the
1106
+ // bridge) and lands at error tier - default mode records errors
1107
+ // only, so this is the sole durable trace of the incident.
1108
+ const detail = (d as { msg?: string } | undefined)?.msg ?? "";
1109
+ const routineAbort =
1110
+ s === "call-tool-fail" &&
1111
+ (detail.includes(FAIL_REASON_TURN_END) || detail.includes(FAIL_REASON_SHUTDOWN));
1112
+ let level: "debug" | "info" | "warn" | "error" = "debug";
1113
+ if (!failures.has(s)) {
1114
+ if (s === "call-tool" || s === "call-tool-ok") level = "info";
1115
+ } else if (!routineAbort) {
1116
+ level = s === "call-tool-fail" ? "error" : "warn";
1117
+ }
1118
+ fileLog.log(s, d, level);
1119
+ if (routineAbort) return;
1120
+ if (!failures.has(s)) return;
1121
+ const msg = `[pi-antigravity mcp] ${s}${d !== undefined ? " " + JSON.stringify(d) : ""}`;
1122
+ if (ctx.hasUI) ctx.ui.notify(msg, "warning");
1123
+ else process.stderr.write(`${msg}\n`);
1124
+ };
1125
+ // Sweep crashed sessions even when the bridge is disabled.
1126
+ sweepStaleBridgeServers();
1127
+ sweepStaleBridgeDirs();
1128
+ sweepStagedAgyHomes();
1129
+ // Start the bridge unless the user turned it off. No patch gate, no
1130
+ // consent flow: calls route through pi's normal toolUse loop. The
1131
+ // approval gate rides the same listener, so an active gate keeps it
1132
+ // running even with bridgeTools "none" (no pi tools are listed):
1133
+ // hiding pi tools from agy must never un-gate agy's native tools.
1134
+ const bridgeMode: BridgeTools = loadConfig().bridgeTools;
1135
+ // One resolution per session_start: the staging block below must gate
1136
+ // on the SAME verdict, or a mid-start flip leaves the gate unstaged
1137
+ // while gateUnavailable says pending (every turn refused until restart).
1138
+ const gateMode = resolveGateMode(loadConfig().approvals.gateMode, detectPermissionGateExtensions());
1139
+ if (mcpHandle) return; // already running (reload re-fires session_start)
1140
+ gateUnavailable = gateMode === "off" ? undefined : "approval gate not staged yet";
1141
+ if (bridgeMode === "none" && gateMode === "off") return; // user opted out
1142
+ // pi loads project skill locations only after the project is trusted;
1143
+ // mirror that gate. Global skill dirs are always scanned.
1144
+ const skills: SkillLite[] = scanSkills(ctx.isProjectTrusted() ? { projectDir: process.cwd() } : {});
1145
+ const listTools = () => {
1146
+ // /mcp and pi.setActiveTools() update the same live catalog. ACP gets
1147
+ // this endpoint through session/new or session/load; no global config write.
1148
+ const mode = loadConfig().bridgeTools;
1149
+ const authorized = getBridgeTools();
1150
+ const codemode = mode === "codemode" ? codemodeCatalog(authorized) : null;
1151
+ const { direct, proxied } = partitionBridgeTools(authorized);
1152
+ const directDefs = codemode
1153
+ ? codemode.direct
1154
+ : direct.map((t) => ({
1155
+ name: t.name,
1156
+ description: t.description ?? t.name,
1157
+ inputSchema: serializeToolSchema(t.parameters),
1158
+ }));
1159
+ const tools = directDefs;
1160
+ const proxiedForInfo = codemode ? codemode.proxied : proxied;
1161
+ if (mode !== "none" && proxiedForInfo.length > 0) {
1162
+ tools.push(bridgeToolInfoDef(proxiedForInfo), bridgeCallToolDef());
1163
+ }
1164
+ if (skills.length > 0 && mode !== "none") {
1165
+ tools.push({
1166
+ name: ACTIVATE_SKILL_TOOL_NAME,
1167
+ description: `Activate a pi Agent Skill by name. Catalog:\n${catalogSummary(skills)}`,
1168
+ inputSchema: activateSkillSchema(skills) as object,
1169
+ });
1170
+ }
1171
+ // Bridge-local, like activate_skill: answered from the escalation
1172
+ // registry without a pi round-trip. Pairs with the STILL RUNNING
1173
+ // early-ack that keeps slow calls under agy's ~180s request deadline.
1174
+ tools.push({
1175
+ name: POLL_TOOL_NAME,
1176
+ description:
1177
+ "Fetch the result of a long-running bridge tool call that answered STILL RUNNING with a callId. The poll blocks up to 110 seconds for the result; call it again immediately if it still reports running.",
1178
+ inputSchema: {
1179
+ type: "object",
1180
+ properties: { callId: { type: "string", description: "callId from the STILL RUNNING answer" } },
1181
+ required: ["callId"],
1182
+ },
1183
+ });
1184
+ return tools;
1185
+ };
1186
+ // activate_skill never round-trips through pi: the bridge answers it
1187
+ // directly by reading the SKILL.md (pi has no skill tool to execute).
1188
+ const bridgeOnToolCall = (
1189
+ callId: string,
1190
+ name: string,
1191
+ args: Record<string, unknown>,
1192
+ signal: AbortSignal,
1193
+ ) => {
1194
+ // Bridge-local, like activate_skill: answered from the escalation
1195
+ // registry, never parked into pi.
1196
+ if (name === POLL_TOOL_NAME) {
1197
+ const wanted = typeof args.callId === "string" ? args.callId : "";
1198
+ mcpLog("poll-tool", { callId: wanted });
1199
+ return answerPoll(roundTrips, wanted, signal, mcpLog);
1200
+ }
1201
+ if (name === TOOL_INFO_TOOL_NAME) {
1202
+ const { proxied } = partitionBridgeTools(getBridgeTools());
1203
+ return Promise.resolve(
1204
+ roundTrips.attachPendingMidTurnSteer(formatBridgeToolInfo(proxied, args.names), TOOL_INFO_TOOL_NAME, signal),
1205
+ );
1206
+ }
1207
+ const dispatchPiTool = (targetName: string, targetArgs: Record<string, unknown>) =>
1208
+ roundTrips.onToolCall(callId, targetName, targetArgs, signal).then((r) => {
1209
+ // Early-ack: answer the HTTP request before agy's ~180s client
1210
+ // deadline with a poll handle; pi keeps executing meanwhile.
1211
+ if (!("escalated" in r)) return r;
1212
+ mcpLog("call-tool-escalated", { name: targetName, callId: r.callId });
1213
+ return roundTrips.attachPendingMidTurnSteer(formatEscalatedAck(r), "escalated-ack", signal);
1214
+ });
1215
+ if (name === CALL_TOOL_NAME) {
1216
+ const parsed = parseBridgeCallRequest(args, getBridgeTools());
1217
+ if (!parsed.ok) {
1218
+ return Promise.resolve(
1219
+ roundTrips.attachPendingMidTurnSteer(
1220
+ { content: [{ type: "text", text: parsed.error }], isError: true },
1221
+ CALL_TOOL_NAME,
1222
+ signal,
1223
+ ),
1224
+ );
1225
+ }
1226
+ return dispatchPiTool(parsed.name, parsed.args);
1227
+ }
1228
+ if (name !== ACTIVATE_SKILL_TOOL_NAME) {
1229
+ // Direct calls by tool name stay authorized so cached schemas from
1230
+ // earlier sessions still work, while disabled/hidden tools stay blocked.
1231
+ if (!getBridgeTools().some((tool) => tool.name === name)) {
1232
+ return Promise.resolve(
1233
+ roundTrips.attachPendingMidTurnSteer(
1234
+ { content: [{ type: "text", text: `Pi tool ${name} is not active or not exposed to Antigravity` }], isError: true },
1235
+ name,
1236
+ signal,
1237
+ ),
1238
+ );
1239
+ }
1240
+ return dispatchPiTool(name, args);
1241
+ }
1242
+ const wanted = typeof args.name === "string" ? args.name : "";
1243
+ const skill = loadConfig().bridgeTools !== "none" ? findSkillByName(skills, wanted) : undefined;
1244
+ const body = skill ? readSkillBody(skill) : `unknown skill: ${wanted || "(none given)"}`;
1245
+ return Promise.resolve(
1246
+ roundTrips.attachPendingMidTurnSteer(
1247
+ {
1248
+ content: [
1249
+ {
1250
+ type: "text",
1251
+ text: skill ? `${body}\n\n[skill resources dir: ${skill.dir}]` : `Error: ${body}`,
1252
+ },
1253
+ ],
1254
+ isError: !skill,
1255
+ },
1256
+ ACTIVATE_SKILL_TOOL_NAME,
1257
+ signal,
1258
+ ),
1259
+ );
1260
+ };
1261
+ const r = await realmSession.attachBridge(
1262
+ {
1263
+ listTools,
1264
+ onToolCall: bridgeOnToolCall,
1265
+ onApproval: (ticket, payload) => roundTrips.onApproval(ticket, payload),
1266
+ },
1267
+ mcpLog,
1268
+ );
1269
+ if (r.ok && r.handle) {
1270
+ mcpHandle = r.handle;
1271
+ // Entries a crashed delegation left suppressed are healed here,
1272
+ // but only when no live delegation is in
1273
+ // flight anywhere (marker-aware heal). A blind re-enable used to
1274
+ // un-hide the bridge during another session's active delegation.
1275
+ // Global-config hygiene runs on BOTH engines: a crashed stream-json
1276
+ // session must not leave dead-pid entries or stuck suppression flags
1277
+ // for the next one.
1278
+ if (r.first) healBridgeSuppression();
1279
+ // ACP supplies the bridge per-session (session/new | session/load).
1280
+ // stream-json skips the global file entirely when the isolated home
1281
+ // is active (issue #14): this session's bridge rides the staged
1282
+ // config instead, so no other agy on the machine can see or call it.
1283
+ // bridgeTools "none" skips it too: with no pi tools exposed, a global
1284
+ // entry would only announce the listener to agy processes the user
1285
+ // opted out of; the gate needs no registration (its hook rides the
1286
+ // session's own add-dir).
1287
+ if (engine === "stream-json" && !streamHome.isolated && bridgeMode !== "none") {
1288
+ if (r.first) {
1289
+ registerBridgeServer({
1290
+ pid: process.pid,
1291
+ port: r.handle.port,
1292
+ token: r.handle.realmToken,
1293
+ tokenHeader: TOKEN_HEADER,
1294
+ });
1295
+ }
1296
+ } else if (streamHome.path) {
1297
+ // Bridge enabled after the home was staged without one: refresh
1298
+ // the staged copy directly. agy reads the home once at spawn;
1299
+ // the running child sees it on its next start.
1300
+ try {
1301
+ writeOwnBridgeEntry(streamHome.path, { pid: process.pid, port: r.handle.port, token: r.handle.token, tokenHeader: TOKEN_HEADER });
1302
+ } catch (err) {
1303
+ fileLog.log("stream-home-entry-failed", { error: String(err) }, "warn");
1304
+ }
1305
+ }
1306
+ if (streamHome.fallbackReason) {
1307
+ // Isolation degraded to the legacy global path: say so once.
1308
+ const msg = `[pi-antigravity] ${streamHome.fallbackReason}; using the global MCP registration (issue #14 isolation unavailable).`;
1309
+ if (ctx.hasUI) ctx.ui.notify(msg, "warning");
1310
+ else process.stderr.write(`${msg}\n`);
1311
+ }
1312
+ // --- Approval gate (docs/TODO.md 2.5) ------------------------------
1313
+ // agy native tool calls pass through a pi-side approval: a PreToolUse
1314
+ // hook parks in the bridge, the provider emits a shadow toolUse, and
1315
+ // pi's permission extensions gate it like any native call. Off until
1316
+ // enabled (auto = on only when a third-party gate extension exists).
1317
+ {
1318
+ const cfg = loadConfig();
1319
+ const mode = gateMode;
1320
+ gateActive = mode !== "off";
1321
+ if (mode !== "off" && engine === "acp") {
1322
+ // Staged-home hook delivery is probe-verified on agy 1.5.12
1323
+ // only (issue #18); older ACP builds may not honor it. Warn
1324
+ // so a silently inert gate is at least visible in the log.
1325
+ const cli = await checkAgyCliVersion(resolveAgyBinary());
1326
+ if (cli.status === "ok" && agyVersionVerdict(cli.raw, "1.5.12").status === "unsupported") {
1327
+ fileLog.log("approval-gate-agy-version-unverified", { version: cli.raw }, "warn");
1328
+ }
1329
+ }
1330
+ if (mode === "dedicated") {
1331
+ // The explicit antigravity_approve variant is planned; until it
1332
+ // ships, dedicated stages the same shadow tools. Say so, so the
1333
+ // config value never lies silently.
1334
+ fileLog.log("approval-dedicated-as-shadow", {}, "warn");
1335
+ }
1336
+ // Legacy cleanup (issue #5): 1.6.x staged the gate into the shared
1337
+ // workspace hooks.json, where standalone IDE/CLI sessions load it.
1338
+ // Staging now lives in the session-private add-dir; sweep groups left
1339
+ // behind by dead sessions from the old scheme. Live sessions' and
1340
+ // foreign groups are never touched.
1341
+ if (r.first) {
1342
+ const sweptLegacy = sweepWorkspaceGateGroups(process.cwd());
1343
+ if (sweptLegacy > 0) fileLog.log("approval-workspace-swept", { swept: sweptLegacy }, "info");
1344
+ }
1345
+ if (mode === "off") {
1346
+ // Gate off: drop this session's private hooks file.
1347
+ const unstaged = removeGateHooks();
1348
+ if (unstaged.wrote) fileLog.log("approval-unstaged", unstaged, "info");
1349
+ } else {
1350
+ // Script: per-realm file; 0600 because the realm token is
1351
+ // embedded (peer review 2026-09-07). Re-stage idempotently so
1352
+ // a partial failure on an earlier session never leaves the
1353
+ // gate un-staged while gateActive is true.
1354
+ const scriptPath = approvalHookScriptPath();
1355
+ fs.mkdirSync(path.dirname(scriptPath), { recursive: true, mode: 0o700 });
1356
+ fs.writeFileSync(
1357
+ scriptPath,
1358
+ hookScriptSource({
1359
+ port: r.handle.port,
1360
+ token: r.handle.realmToken,
1361
+ deadlineMs: APPROVAL_PARK_MS,
1362
+ }),
1363
+ { mode: 0o600 },
1364
+ );
1365
+ // Private per-realm staging (issue #5 isolation): the gate group goes
1366
+ // into the bridge add-dir that ONLY this process's agy receives.
1367
+ const staged = stageGateHooks(bridgeMcpConfigDir(), {
1368
+ port: r.handle.port,
1369
+ token: r.handle.realmToken,
1370
+ scriptPath,
1371
+ parkBudgetMs: APPROVAL_PARK_MS,
1372
+ });
1373
+ fileLog.log("approval-staged", { mode, script: scriptPath, ...staged }, staged.wrote ? "info" : "debug");
1374
+
1375
+ // Shadow bases: factory twins of pi's own builtins (public API).
1376
+ // pi.getAllTools() is unusable here: it returns ToolInfo, which
1377
+ // strips execute. Marker calls never execute; non-marker calls
1378
+ // delegate to the twins, so behavior matches the standard
1379
+ // builtins. The shadow replaces bash for EVERY model, so the
1380
+ // twin gets the same shellCommandPrefix/shellPath settings pi
1381
+ // gives its own bash (session-level bash-operations overrides
1382
+ // are still not inherited; documented in README).
1383
+ const gateCwd = process.cwd();
1384
+ const bases: Record<string, AnyToolDefinition> = {
1385
+ // SAFETY: pi's concrete bash ToolDefinition<TSchema, TDetails> is invariant in its generics; shadow registry stores heterogeneous definitions by name.
1386
+ bash: createBashToolDefinition(gateCwd, bashSettingsOptions(pi)) as unknown as AnyToolDefinition,
1387
+ // SAFETY: pi's concrete write ToolDefinition<TSchema, TDetails> is invariant in its generics; shadow registry stores heterogeneous definitions by name.
1388
+ write: createWriteToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1389
+ // SAFETY: pi's concrete edit ToolDefinition<TSchema, TDetails> is invariant in its generics; shadow registry stores heterogeneous definitions by name.
1390
+ edit: createEditToolDefinition(gateCwd) as unknown as AnyToolDefinition,
1391
+ };
1392
+ const askMode = cfg.approvals.mode;
1393
+ const policy: GatePolicy = async ({ tool, params, ctx }) => {
1394
+ if (askMode === "allow") return { allow: true };
1395
+ if (askMode === "deny") {
1396
+ return { allow: false, reason: `blocked by approval gate (mode: deny): ${tool}` };
1397
+ }
1398
+ const extCtx = ctx as { hasUI?: boolean; ui?: Pick<ExtensionUIContext, "confirm"> } | undefined;
1399
+ if (!extCtx?.hasUI || typeof extCtx.ui?.confirm !== "function") {
1400
+ return { allow: false, reason: `approval gate: no UI to approve ${tool} (headless)` };
1401
+ }
1402
+ let what: string;
1403
+ if (typeof params.command === "string") {
1404
+ what = params.command;
1405
+ } else if (typeof params.path === "string") {
1406
+ what = params.path;
1407
+ } else {
1408
+ what = JSON.stringify(stripMarkerFields(params)).slice(0, 200);
1409
+ }
1410
+ // Dialog lock: parallel agy tool approvals queue up instead of
1411
+ // clobbering the live dialog (which silently loses the approval).
1412
+ // Capture the narrowed method: TS drops the guard's narrowing
1413
+ // inside the deferred closure.
1414
+ const uiConfirm = extCtx.ui.confirm.bind(extCtx.ui);
1415
+ const ok = await withDialogLock(() =>
1416
+ uiConfirm(`agy ${tool}?`, what, { timeout: APPROVAL_PARK_MS }),
1417
+ );
1418
+ return ok ? { allow: true } : { allow: false, reason: `declined in pi (agy ${tool})` };
1419
+ };
1420
+ const handle = r.handle;
1421
+ for (const [, base] of Object.entries(bases)) {
1422
+ pi.registerTool(
1423
+ createShadowTool(base, policy, { verifyTicket: (t) => handle.approvals.has(t) }),
1424
+ );
1425
+ }
1426
+ // The park is wired ONLY after the shadows are registered: an
1427
+ // approval toolUse must never dispatch to the REAL builtin and
1428
+ // execute locally.
1429
+ roundTrips.approvalPark = handle.approvals;
1430
+ gateUnavailable = undefined;
1431
+ }
1432
+ }
1433
+ } else {
1434
+ if (gateUnavailable) gateUnavailable = `MCP listener failed: ${r.reason}`;
1435
+ process.stderr.write(`[pi-antigravity] MCP tool bridge disabled: ${r.reason}\n`);
1436
+ }
1437
+ });
1438
+ pi.on("session_shutdown", async () => {
1439
+ // The UI is going away; a later auth-url must fall back to stderr
1440
+ // instead of toasting into a dead UI (where it would be lost).
1441
+ activeUi = null;
1442
+ const h = mcpHandle;
1443
+ mcpHandle = null;
1444
+ try {
1445
+ // "recycle", NOT "shutdown": pi fires session_shutdown on /new, /resume
1446
+ // and /fork (docs/extensions.md session lifecycle), not only on process
1447
+ // exit. The drivers are process-lifetime singletons; closing them with
1448
+ // "shutdown" latched them permanently and every later turn failed with
1449
+ // "ACP driver is shut down." (regression 2026-09-07). Recycle kills the
1450
+ // connection now; the next turn respawns it. event.reason is
1451
+ // deliberately ignored: recycle is correct even on real process exit
1452
+ // ("quit") - the connection kill is identical and nothing runs after.
1453
+ await streamDriver.close("recycle", "session shutdown");
1454
+ await acpDriver.close("recycle", "session shutdown");
1455
+ roundTrips.failAll(FAIL_REASON_SHUTDOWN);
1456
+ await h?.close();
1457
+ hiddenBridgeTools.clear();
1458
+ } finally {
1459
+ // Leaving the realm revokes this session's route; only the last session
1460
+ // to leave tears down the shared listener and per-realm artifacts.
1461
+ await realmSession?.leave();
1462
+ realmSession = null;
1463
+ }
1464
+ });
1465
+ }
1466
+
1467
+ // --- /agy command -----------------------------------------------------------
1468
+
1469
+ interface AgyCommandCtx {
1470
+ entries: AgyModelEntry[];
1471
+ store: SessionStore;
1472
+ usingFallback: boolean;
1473
+ driver: TurnDriver;
1474
+ acpDriver: AcpDriver;
1475
+ /** Engine latched at extension load (see the provider wiring note). */
1476
+ engine: Engine;
1477
+ getMcpPort: () => number | null;
1478
+ /** stream-json MCP-home isolation state (issue #14): false when the CLI
1479
+ * refused --gemini_dir or a sandbox override kept the legacy path. */
1480
+ streamIsolated: boolean;
1481
+ bridgeTools: () => Array<{ name: string }>;
1482
+ hiddenBridgeTools: Set<string>;
1483
+ /** Daily file logger (src/daily-log.ts); command + doctor surfacing. */
1484
+ fileLog: DailyLogger;
1485
+ /** Live subagent roster (folded in the provider); /agy subagents. */
1486
+ roster: SubagentRoster;
1487
+ pendingCompactionHandoff: Set<string>;
1488
+ checkAgySetup: (ctx: { ui: ExtensionUIContext; mode: string }, engine: Engine, explicit?: boolean) => Promise<void>;
1489
+ setActiveUi: (ui: ExtensionUIContext) => void;
1490
+ }
1491
+
1492
+ interface PendingConfig {
1493
+ mode?: AgyMode;
1494
+ readOnly?: boolean;
1495
+ skipPermissions?: boolean;
1496
+ defaultModel?: string;
1497
+ defaultThinking?: ThinkingTier;
1498
+ turnTimeoutMin?: number;
1499
+ askTool?: boolean;
1500
+ webTools?: boolean;
1501
+ bridgeTools?: BridgeTools;
1502
+ digest?: boolean;
1503
+ systemPrompt?: boolean;
1504
+ acp?: Partial<AcpConfig>;
1505
+ }
1506
+
1507
+ function settingsRows(_ctx: AgyCommandCtx): string[] {
1508
+ const config = loadConfig();
1509
+ const perm = config.skipPermissions ? "auto-approved (DANGEROUS)" : "prompt (hangs in -p)";
1510
+ // padEnd keyed to the longest label ("AskAntigravity thinking:") so the
1511
+ // value column stays aligned as labels grow. Doctor-only state (engine,
1512
+ // models, sessions, config path) lives in /agy doctor, not here: one
1513
+ // surface per concern — this is the config surface, doctor is health.
1514
+ const row = (label: string, value: string) => ` ${label.padEnd(24)} ${value}`;
1515
+ return [
1516
+ row("mode:", config.mode),
1517
+ row(
1518
+ "readOnly:",
1519
+ config.readOnly ? "on (provider turns are refused)" : "off",
1520
+ ),
1521
+ row("permissions:", perm),
1522
+ row("AskAntigravity tool:", config.askTool ? "on" : "off"),
1523
+ row("Web tools:", config.webTools ? "on" : "off"),
1524
+ row("AskAntigravity model:", config.defaultModel),
1525
+ row("AskAntigravity thinking:", config.defaultThinking),
1526
+ row("bridge tools:", config.bridgeTools),
1527
+ row("digest:", config.digest ? "on" : "off"),
1528
+ row("system prompt:", config.systemPrompt ? "on" : "off"),
1529
+ // issue #23: unparseable hand-edited values must not fail silently.
1530
+ ...(config.parseWarnings ?? []).map((w, i) => row(i === 0 ? "config warnings:" : "", w)),
1531
+ ];
1532
+ }
1533
+
1534
+ function statusText(ctx: AgyCommandCtx): string {
1535
+ const config = loadConfig();
1536
+ const source = ctx.usingFallback ? "fallback (agy models failed)" : "discovered";
1537
+ return [
1538
+ `Pi Antigravity v${getPackageVersion()} (@orbit-labs-ai/pi-antigravity)`,
1539
+ ` engine: ${config.engine}${config.engine === "stream-json" ? " (agy CLI fallback)" : " (agy acp)"}`,
1540
+ ` models: ${ctx.entries.length} ${source}`,
1541
+ ...settingsRows(ctx),
1542
+ ` sessions: ${ctx.store.size} bound`,
1543
+ ` config: ${configPath()}`,
1544
+ "",
1545
+ "Subcommands: /agy auth, /agy auth-manual, /agy engine stream-json|acp, /agy mode plan|accept-edits, /agy readonly on|off, /agy permissions on|off, /agy ask on|off, /agy model <alias>, /agy thinking low|medium|high|xhigh, /agy agent <name|off>, /agy subagents, /agy quota, /agy artifacts [open <n|name>], /agy tasks [tail <id>], /agy bridge all|mcp|codemode|none, /agy tools [hide|show <name>|reset], /agy web on|off, /agy digest on|off, /agy system-prompt on|off, /agy timeout <1-1440|off>, /agy patch-cleanup, /agy clear, /agy doctor",
1546
+ ].join("\n");
1547
+ }
1548
+
1549
+
1550
+ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1551
+ pi.registerCommand("agy", {
1552
+ description:
1553
+ "Antigravity provider: doctor (health + settings), settings picker, clear sessions. Usage: /agy [doctor|auth|auth-manual|engine stream-json|acp|mode plan|accept-edits|readonly on|off|permissions on|off|ask on|off|model <alias>|thinking low|medium|high|xhigh|agent <name|off>|subagents|quota|artifacts [open <n|name>]|tasks [tail <id>]|bridge all|mcp|codemode|none|tools [hide|show <name>|reset]|web on|off|digest on|off|system-prompt on|off|timeout <1-1440|off>|patch-cleanup|clear]",
1554
+ handler: async (args, cmdCtx: ExtensionCommandContext) => {
1555
+ const ui = cmdCtx.ui;
1556
+ if (ui) ctx.setActiveUi(ui);
1557
+ const mode = cmdCtx.mode;
1558
+ const [rawSub, rawVal] = (args ?? "").trim().split(/\s+/);
1559
+ const sub = rawSub?.toLowerCase();
1560
+ const val = rawVal?.toLowerCase();
1561
+ ctx.fileLog.log("agy-command", { args }, "info");
1562
+
1563
+ // Direct subcommands work everywhere (headless + TUI).
1564
+ if (sub === "clear") {
1565
+ ctx.store.clear();
1566
+ ctx.pendingCompactionHandoff.clear();
1567
+ ui?.notify("Cleared all antigravity session bindings.", "info");
1568
+ return;
1569
+ }
1570
+ if (sub === "patch-cleanup") {
1571
+ const st = patchStatus();
1572
+ if (!st.present) {
1573
+ ui?.notify(
1574
+ st.root
1575
+ ? `No invokeTool patch detected on pi ${st.version}. Nothing to clean.`
1576
+ : "Could not locate the installed pi package. Nothing cleaned.",
1577
+ "info",
1578
+ );
1579
+ return;
1580
+ }
1581
+ const r = restorePatch();
1582
+ ui?.notify(
1583
+ r.ok
1584
+ ? `Restored ${r.restoredFiles.length} file(s) from ${r.backupDir}. The running session is unaffected; the files on disk are clean again.`
1585
+ : `patch-cleanup failed: ${r.reason}`,
1586
+ r.ok ? "info" : "error",
1587
+ );
1588
+ return;
1589
+ }
1590
+ if (sub === "timeout") {
1591
+ // Free-type entry point for the turn cap (the TUI picker only offers
1592
+ // presets). Same sanity rules as loadConfig: 1..MAX valid, off/0
1593
+ // disables, anything else rejected with the valid range.
1594
+ const live = loadConfig();
1595
+ const cur = live.turnTimeoutMin;
1596
+ if (!val) {
1597
+ ui?.notify(
1598
+ `Turn time cap: ${cur === 0 ? "off (no cap)" : `${cur}m`}. Usage: /agy timeout <1-${MAX_TURN_CAP_MIN}|off>. Default: off on an interactive pi, 20m headless.`,
1599
+ "info",
1600
+ );
1601
+ return;
1602
+ }
1603
+ const parsed = val === "off" ? 0 : parseCapMinutes(val, Number.NaN);
1604
+ if (Number.isNaN(parsed)) {
1605
+ ui?.notify(`Invalid turn cap "${val}". Use 1-${MAX_TURN_CAP_MIN} minutes, or off/0 to disable.`, "error");
1606
+ return;
1607
+ }
1608
+ saveConfig({ turnTimeoutMin: parsed });
1609
+ ui?.notify(
1610
+ parsed === 0
1611
+ ? `Turn time cap disabled. The inactivity stall guard (${live.inactivityTimeoutMin}m silence) still applies.`
1612
+ : `Turn time cap set to ${parsed}m. Takes effect next turn.`,
1613
+ "info",
1614
+ );
1615
+ return;
1616
+ }
1617
+ if (sub === "engine") {
1618
+ if (val === "acp" || val === "stream-json") {
1619
+ if (val === "acp" && loadConfig().mode === "plan") {
1620
+ ui?.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
1621
+ return;
1622
+ }
1623
+ // Consent gate (google-antigravity/antigravity-cli#1890): the
1624
+ // TUI warning modal runs once, before stream-json ever takes
1625
+ // effect. Headless has no modal surface: apply with the
1626
+ // one-line notice instead.
1627
+ let engineChoice: "acp" | "stream-json" = val;
1628
+ let warned = false;
1629
+ if (engineChoice === "stream-json" && shouldWarnStreamJson("stream-json", loadConfig().streamJsonAcknowledged)) {
1630
+ if (!ui || mode !== "tui") {
1631
+ ui?.notify(streamJsonKeptMessage(), "warning");
1632
+ } else {
1633
+ const verdict = await showStreamJsonWarning(ui);
1634
+ if (verdict === undefined) {
1635
+ ui.notify(`engine unchanged: ${loadConfig().engine}.`, "info");
1636
+ return;
1637
+ }
1638
+ if (verdict === "acp" && loadConfig().mode === "plan") {
1639
+ ui.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
1640
+ return;
1641
+ }
1642
+ engineChoice = verdict === "acp" ? "acp" : "stream-json";
1643
+ warned = true;
1644
+ }
1645
+ }
1646
+ const next = saveConfig(streamJsonSavePatch(engineChoice, warned));
1647
+ if (next.engine !== "acp") {
1648
+ ui?.notify("engine set to stream-json. Takes effect on the next pi start (or /reload).", "info");
1649
+ return;
1650
+ }
1651
+ ui?.notify("engine set to acp. Turns will use `agy acp` and the CLI's existing authentication. Takes effect on the next pi start (or /reload).", "info");
1652
+ void ctx.checkAgySetup(cmdCtx, "acp", true);
1653
+ } else if (!val && mode === "tui" && ui) {
1654
+ // Same modal as the first-run wizard: switching engines deserves
1655
+ // the explanations, not a bare usage line. Semantics match the
1656
+ // direct path above: plan blocks acp and restart applies the switch.
1657
+ await runEngineModal(ui, ctx);
1658
+ } else {
1659
+ ui?.notify(`current engine: ${loadConfig().engine}\nusage: /agy engine stream-json|acp`, "info");
1660
+ }
1661
+ return;
1662
+ }
1663
+ if (sub === "auth") {
1664
+ ui?.notify(agyAuthenticationMessage(), "info");
1665
+ return;
1666
+ }
1667
+ if (sub === "auth-manual") {
1668
+ ui?.notify(
1669
+ [
1670
+ "Both engines use the agy CLI and its cached Google credentials.",
1671
+ "",
1672
+ "Install on Linux or macOS:",
1673
+ " curl -fsSL https://antigravity.google/cli/install.sh | bash",
1674
+ "Install on Windows PowerShell:",
1675
+ " irm https://antigravity.google/cli/install.ps1 | iex",
1676
+ "",
1677
+ agyAuthenticationMessage(),
1678
+ ].join("\n"),
1679
+ "info",
1680
+ );
1681
+ return;
1682
+ }
1683
+ if (sub === "doctor") {
1684
+ const config = loadConfig();
1685
+ const engine = ctx.engine;
1686
+ const snap = (engine === "acp" ? ctx.acpDriver : ctx.driver).snapshot();
1687
+ const port = ctx.getMcpPort();
1688
+ const rawCliCheck = await checkAgyCliVersion(resolveAgyBinary());
1689
+ const cliFloor = engine === "acp" ? MIN_AGY_ACP_VERSION : MIN_AGY_VERSION;
1690
+ const cliCheck = rawCliCheck.status === "ok" || rawCliCheck.status === "unsupported"
1691
+ ? agyVersionVerdict(rawCliCheck.raw, cliFloor)
1692
+ : rawCliCheck;
1693
+ const lines = [
1694
+ `Pi Antigravity v${getPackageVersion()} doctor (no tokens spent)`,
1695
+ ` engine: ${engine}`,
1696
+ ` bridge: ${config.bridgeTools}${port ? ` (port ${port})` : " (not running)"}`,
1697
+ ...(config.bridgeTools === "codemode" && !pi.getActiveTools().includes("codemode")
1698
+ ? [" bridge: codemode tool INACTIVE in pi; the engine sees an all-mode catalog without the codemode note. Activate with --tools codemode or the defaultTools setting."]
1699
+ : []),
1700
+ ` driver: ${snap.state}${snap.pid ? ` pid=${snap.pid}` : ""}${snap.conversationId ? ` session=${snap.conversationId.slice(0, 8)}` : ""}`,
1701
+ ` driver stats: spawns=${snap.stats.spawns} turns=${snap.stats.turns} reused=${snap.stats.reused} recycles=${snap.stats.recycles}${snap.stats.lastRecycleReason ? ` (last: ${snap.stats.lastRecycleReason})` : ""}`,
1702
+ ` sessions: ${ctx.store.size} bound`,
1703
+ ` models: ${ctx.entries.length} ${ctx.usingFallback ? "FALLBACK (agy models failed)" : "discovered"}`,
1704
+ ` agy cli: ${describeAgyVersionCheck(cliCheck)} (min ${cliFloor})`,
1705
+ ` config: ${configPath()}`,
1706
+ ` logs: ${logsDir()} (attach recent days' files when reporting issues; set AGY_DEBUG=1 to capture details)`,
1707
+ ];
1708
+ if (snap.engine === "acp" && snap.acp) {
1709
+ lines.push(
1710
+ ` acp session: ${snap.acp.sessionId ?? "(none)"}`,
1711
+ ` acp server: ${snap.acp.serverVersion ?? "unknown"}${snap.acp.agentTitle ? ` (${snap.acp.agentTitle})` : ""}`,
1712
+ ` acp stats: prompts=${snap.acp.prompts} created=${snap.acp.sessionsCreated} loaded=${snap.acp.sessionsLoaded} kills=${snap.acp.kills} reconnects=${snap.acp.reconnects}`,
1713
+ );
1714
+ // Gate B watch: silent while the server offers no token counts; one
1715
+ // line the day it starts (then real usage mapping is worth wiring).
1716
+ if (snap.acp.usageSeen) {
1717
+ lines.push(" acp tokens: NATIVE exact usage in PromptResponse");
1718
+ } else if (config.acp.usageEstimate !== "off") {
1719
+ lines.push(` acp tokens: ESTIMATED client-side (mode: ${config.acp.usageEstimate}; auto-off once the server sends real usage)`);
1720
+ }
1721
+ }
1722
+ if (snap.lifecycle.length > 0) {
1723
+ lines.push(" lifecycle (last 5):");
1724
+ for (const entry of snap.lifecycle.slice(-5)) lines.push(` ${entry}`);
1725
+ }
1726
+ if (engine === "acp") lines.push(" acp transport: agy acp (shared CLI authentication, isolated MCP home)");
1727
+ if (engine === "acp" && resolveGateMode(config.approvals.gateMode, detectPermissionGateExtensions()) !== "off"
1728
+ && rawCliCheck.status === "ok" && agyVersionVerdict(rawCliCheck.raw, "1.5.12").status === "unsupported") {
1729
+ // Same condition as the session_start wiring warn, surfaced here
1730
+ // because a daily-log-only signal is easy to miss (review S2).
1731
+ lines.push(` approval gate: ON but hook delivery is verified only on agy >= 1.5.12 (this: ${rawCliCheck.raw}; issue #18)`);
1732
+ }
1733
+ if (engine === "stream-json" && ctx.streamIsolated) lines.push(" stream transport: agy stream-json (shared CLI authentication, isolated MCP home)");
1734
+ if (engine === "stream-json" && !ctx.streamIsolated) lines.push(" stream transport: agy stream-json (shared CLI authentication, GLOBAL MCP registration: isolation unavailable)");
1735
+ const retiredAuth = path.join(os.homedir(), ".gemini", "antigravity-acp");
1736
+ if (fs.existsSync(retiredAuth)) lines.push(` retired auth: ${retiredAuth} is unused; remove it manually when no longer needed`);
1737
+ // The config surface lives here too, so doctor is the ONE status
1738
+ // surface (former /agy status is gone).
1739
+ lines.push("", "settings:", ...settingsRows(ctx));
1740
+ ui?.notify(lines.join("\n"), "info");
1741
+ return;
1742
+ }
1743
+ if (sub === "mode") {
1744
+ if (val === "plan" || val === "accept-edits") {
1745
+ if (val === "plan" && ctx.engine === "acp") {
1746
+ ui?.notify("plan cannot be enforced on provider turns: the CLI does not gate writes under plan (google-antigravity/antigravity-cli#1181), and provider plan turns are disabled on ACP. /agy mode accept-edits.", "warning");
1747
+ return;
1748
+ }
1749
+ const next = saveConfig({ mode: val as AgyMode });
1750
+ // readOnly fail-closes provider turns regardless of this knob;
1751
+ // never let the confirmation imply turns will run. loadConfig, not
1752
+ // next: saveConfig merges the raw file, so an env-only readOnly
1753
+ // would otherwise read as off here.
1754
+ const effectiveReadonly = loadConfig().readOnly;
1755
+ if (effectiveReadonly) {
1756
+ ui?.notify(`mode set to ${next.mode}, but readOnly is on: provider turns are refused. /agy readonly off to lift.`, "info");
1757
+ } else if (val === "plan") {
1758
+ ui?.notify(`mode set to plan: provider turns are REFUSED (the CLI does not gate writes under plan, google-antigravity/antigravity-cli#1181). Only the AskAntigravity tool uses this mode.`, "info");
1759
+ } else {
1760
+ ui?.notify(`mode set to ${next.mode}`, "info");
1761
+ }
1762
+ } else {
1763
+ const cfg = loadConfig();
1764
+ ui?.notify(
1765
+ `current mode: ${cfg.mode}${cfg.readOnly ? " (readOnly on: provider turns are refused)" : ""}\nusage: /agy mode plan|accept-edits`,
1766
+ "info",
1767
+ );
1768
+ }
1769
+ return;
1770
+ }
1771
+ if (sub === "readonly") {
1772
+ if (val === "on" || val === "off") {
1773
+ const next = saveConfig({ readOnly: val === "on" });
1774
+ ui?.notify(
1775
+ next.readOnly
1776
+ ? "readOnly is on: provider turns and AskAntigravity are REFUSED (the agy CLI has no review-only enforcement on any path; probed 2026-10-07). Enforce read-only in the host, then /agy readonly off."
1777
+ : "readOnly off: provider turns follow /agy mode again.",
1778
+ "info",
1779
+ );
1780
+ // Compare effective vs saved: the env can force either direction
1781
+ // (AGY_READONLY=1 keeps refusals on after /agy readonly off;
1782
+ // AGY_READONLY=0 silently keeps readOnly off after /agy readonly on).
1783
+ if (loadConfig().readOnly !== next.readOnly) {
1784
+ ui?.notify(`AGY_READONLY is set in this environment and overrides the config: readOnly stays ${loadConfig().readOnly ? "on (refusing)" : "off"} until you unset it.`, "warning");
1785
+ }
1786
+ } else {
1787
+ const cfg = loadConfig();
1788
+ ui?.notify(
1789
+ `readOnly is ${cfg.readOnly ? "on (provider turns and AskAntigravity are refused)" : "off"}\nusage: /agy readonly on|off. Fail-closed: the CLI has no review-only enforcement on any path (probed 2026-10-07), so on = refuse.`,
1790
+ "info",
1791
+ );
1792
+ }
1793
+ return;
1794
+ }
1795
+ if (sub === "tasks") {
1796
+ const engine = ctx.engine;
1797
+ const snap = (engine === "acp" ? ctx.acpDriver : ctx.driver).snapshot();
1798
+ const conversationId = snap.conversationId ?? undefined;
1799
+ if (!conversationId) {
1800
+ ui?.notify("no Antigravity conversation bound yet; run a turn first.", "warning");
1801
+ return;
1802
+ }
1803
+ const dir = agyConversationDir(engine, conversationId);
1804
+ const rest = (args ?? "").trim().split(/\s+/);
1805
+
1806
+ // /agy tasks tail <id>: last bytes of one task log into chat.
1807
+ // Resolved against the scanned list, not a rebuilt filename:
1808
+ // the id->filename convention must not live in two places.
1809
+ if (rest[0]?.toLowerCase() === "tail") {
1810
+ const id = Number(rest[1]);
1811
+ if (!Number.isInteger(id) || id < 0) {
1812
+ ui?.notify("usage: /agy tasks tail <id>. /agy tasks lists them.", "warning");
1813
+ return;
1814
+ }
1815
+ const tasks = await listAgyTasks(dir);
1816
+ const task = tasks.find((t) => t.id === id);
1817
+ if (!task) {
1818
+ ui?.notify(`no task #${id} in this conversation. /agy tasks lists them.`, "warning");
1819
+ return;
1820
+ }
1821
+ const tail = await tailAgyTaskLog(task.logPath);
1822
+ if (tail === "") {
1823
+ ui?.notify(`task #${id} has no readable log.`, "warning");
1824
+ return;
1825
+ }
1826
+ const lines = tail.split("\n");
1827
+ const body = lines.length > 40 ? `…\n${lines.slice(-40).join("\n")}` : tail;
1828
+ ui?.notify(`task #${id} tail:\n${body}`, "info");
1829
+ return;
1830
+ }
1831
+
1832
+ // Dashboard form; r rescans by re-listing fresh.
1833
+ let tasks = await listAgyTasks(dir);
1834
+ if (tasks.length === 0) {
1835
+ ui?.notify("no background tasks recorded for this conversation.", "info");
1836
+ return;
1837
+ }
1838
+ if (!ui) {
1839
+ const lines = tasks.map((t) => {
1840
+ let state = "liveness?";
1841
+ if (t.livenessKnown) state = t.active ? "ACTIVE" : "idle";
1842
+ return `#${t.id} ${state} ${t.bytes}B`;
1843
+ });
1844
+ process.stdout.write(`${[`antigravity tasks (${tasks.length}):`, ...lines].join("\n")}\n`);
1845
+ return;
1846
+ }
1847
+ for (;;) {
1848
+ const action = await showTasksBrowser(ui, tasks, tasks[0]?.livenessKnown ?? false);
1849
+ if (action.type === "rescan") {
1850
+ tasks = await listAgyTasks(dir);
1851
+ if (tasks.length === 0) {
1852
+ ui?.notify("no background tasks recorded for this conversation.", "info");
1853
+ }
1854
+ continue;
1855
+ }
1856
+ break;
1857
+ }
1858
+ return;
1859
+ }
1860
+ if (sub === "artifacts") {
1861
+ const engine = ctx.engine;
1862
+ const snap = (engine === "acp" ? ctx.acpDriver : ctx.driver).snapshot();
1863
+ const conversationId = snap.conversationId ?? undefined;
1864
+ if (!conversationId) {
1865
+ ui?.notify("no Antigravity conversation bound yet; run a turn first.", "warning");
1866
+ return;
1867
+ }
1868
+ const dir = agyConversationDir(engine, conversationId);
1869
+ const rest = (args ?? "").trim().split(/\s+/).slice(1);
1870
+ const openWord = rest[0]?.toLowerCase();
1871
+
1872
+ // /agy artifacts open <name|index>: direct open, no overlay.
1873
+ if (openWord === "open") {
1874
+ const artifacts = await listAgyArtifacts(dir);
1875
+ if (artifacts.length === 0) {
1876
+ ui?.notify("no artifacts in this conversation.", "info");
1877
+ return;
1878
+ }
1879
+ const target = rest.slice(1).join(" ").trim();
1880
+ if (target === "") {
1881
+ ui?.notify("usage: /agy artifacts open <name|index>. /agy artifacts lists them.", "warning");
1882
+ return;
1883
+ }
1884
+ const byIndex = /^\d+$/.test(target) ? Number(target) : undefined;
1885
+ let artifact = byIndex !== undefined ? artifacts[byIndex] : undefined;
1886
+ if (byIndex === undefined) {
1887
+ const needle = target.toLowerCase();
1888
+ artifact = artifacts.find((a) => a.name.toLowerCase() === needle);
1889
+ if (!artifact) {
1890
+ const matches = artifacts.filter((a) => a.name.toLowerCase().includes(needle));
1891
+ if (matches.length === 1) artifact = matches[0];
1892
+ }
1893
+ }
1894
+ if (!artifact) {
1895
+ ui?.notify(`no unique artifact matches ${JSON.stringify(target)}. /agy artifacts lists them.`, "warning");
1896
+ return;
1897
+ }
1898
+ const openCmd = artifactOpenCommand();
1899
+ if (!openCmd) {
1900
+ ui?.notify(`no file-open handler for ${process.platform}; the file is at ${artifact.absolutePath}`, "warning");
1901
+ return;
1902
+ }
1903
+ spawn(openCmd.cmd, [artifact.absolutePath], { detached: true, stdio: "ignore", shell: false }).unref();
1904
+ ui?.notify(`opened ${artifact.name}`, "info");
1905
+ return;
1906
+ }
1907
+
1908
+ // Browser loop; r rescans by re-listing fresh. The first scan is
1909
+ // reused so the emptiness gate does not cost a second readdir pass.
1910
+ let artifacts = await listAgyArtifacts(dir);
1911
+ if (artifacts.length === 0) {
1912
+ ui?.notify("no artifacts in this conversation (media dirs appear once agy generates or receives files).", "info");
1913
+ return;
1914
+ }
1915
+ if (!ui) {
1916
+ // Headless: no overlay is possible; print the indexed list.
1917
+ const lines = artifacts.map((a, i) => `${i} ${a.name} (${a.kind}, ${a.bytes}B)`);
1918
+ process.stdout.write(`${[`antigravity artifacts (${artifacts.length}):`, ...lines].join("\n")}\n`);
1919
+ return;
1920
+ }
1921
+ for (;;) {
1922
+ const action = await showArtifactsBrowser(ui, artifacts);
1923
+ if (action.type === "rescan") {
1924
+ artifacts = await listAgyArtifacts(dir);
1925
+ continue;
1926
+ }
1927
+ if (action.type === "open") {
1928
+ const openCmd = artifactOpenCommand();
1929
+ if (!openCmd) {
1930
+ ui.notify(`no file-open handler for ${process.platform}.`, "warning");
1931
+ continue;
1932
+ }
1933
+ spawn(openCmd.cmd, [action.artifact.absolutePath], { detached: true, stdio: "ignore", shell: false }).unref();
1934
+ }
1935
+ break;
1936
+ }
1937
+ return;
1938
+ }
1939
+ if (sub === "quota") {
1940
+ // Quota lives in the CLI's Google identity. A pure-ACP install
1941
+ // without the CLI is a supported shape; say what is missing instead
1942
+ // of rendering a fetch failure.
1943
+ const bin = resolveAgyBinary();
1944
+ if (!isAgyInstalled(bin)) {
1945
+ ui?.notify(
1946
+ "quota comes from the agy CLI, which is not installed. ACP-only setups can install the CLI separately (same Google account) to see subscription quota (/agy doctor shows what IS available).",
1947
+ "warning",
1948
+ );
1949
+ return;
1950
+ }
1951
+ // /usage answers in ~10s live; surface the wait instead of a dead
1952
+ // command line.
1953
+ ui?.setStatus("agy-quota", "checking agy quota…");
1954
+ try {
1955
+ const report = await fetchAgyQuota(bin);
1956
+ if (report === undefined) {
1957
+ ui?.notify("quota unavailable: agy did not return a /usage payload (see /agy doctor for binary health).", "warning");
1958
+ return;
1959
+ }
1960
+ ui?.notify(formatAgyQuotaReport(report), "info");
1961
+ } finally {
1962
+ ui?.setStatus("agy-quota", undefined);
1963
+ }
1964
+ return;
1965
+ }
1966
+ if (sub === "subagents") {
1967
+ const entries = ctx.roster.snapshot();
1968
+ if (entries.length === 0) {
1969
+ ui?.notify("antigravity subagents: none tracked this session\n\nagy spawns subagents as ordinary tool steps; they appear here once a turn uses them.", "info");
1970
+ return;
1971
+ }
1972
+ ui?.notify(formatSubagentRoster(entries), "info");
1973
+ return;
1974
+ }
1975
+ if (sub === "agent") {
1976
+ // ACP has no per-turn agent slot in the protocol: refuse instead of
1977
+ // silently ignoring a configured agent.
1978
+ if (ctx.engine === "acp") {
1979
+ ui?.notify("the ACP engine has no per-turn agent selection. /agy engine stream-json first.", "warning");
1980
+ return;
1981
+ }
1982
+ const name = (args ?? "").trim().split(/\s+/).slice(1).join(" ").trim();
1983
+ if (!name) {
1984
+ const agents = await listAgyAgents(resolveAgyBinary());
1985
+ const current = loadConfig().agent;
1986
+ const formattedAgents = agents.map((a) => `${a === current ? ">" : " "} ${a}`).join("\n");
1987
+ const agentList = agents.length > 0 ? formattedAgents : "(no custom agents defined)";
1988
+ ui?.notify(`current agent: ${current ?? "(agy default)"}\n\n${agentList}\n\nusage: /agy agent <name|off>`, "info");
1989
+ return;
1990
+ }
1991
+ if (name === "off" || name === "none" || name === "default") {
1992
+ saveConfig({ agent: undefined });
1993
+ ui?.notify("agent cleared: agy default", "info");
1994
+ return;
1995
+ }
1996
+ if (!isValidAgyAgentName(name)) {
1997
+ ui?.notify(`invalid agent name: ${name} (use letters, digits, dot, dash, underscore)`, "warning");
1998
+ return;
1999
+ }
2000
+ saveConfig({ agent: name });
2001
+ ui?.notify(`agent set: ${name} (takes effect on the next stream-json turn)`, "info");
2002
+ return;
2003
+ }
2004
+ if (sub === "permissions") {
2005
+ if (val === "on" || val === "off") {
2006
+ const next = saveConfig({ skipPermissions: val === "on" });
2007
+ const warn = next.skipPermissions ? "\nWARNING: agy can now run arbitrary commands without review." : "";
2008
+ ui?.notify(`permissions: ${next.skipPermissions ? "auto-approved (DANGEROUS)" : "prompt"}${warn}`, next.skipPermissions ? "warning" : "info");
2009
+ } else {
2010
+ ui?.notify(`permissions: ${loadConfig().skipPermissions ? "auto-approved (DANGEROUS)" : "prompt"}\nusage: /agy permissions on|off\n(off hangs any run_command in non-interactive mode)`, "info");
2011
+ }
2012
+ return;
2013
+ }
2014
+ if (sub === "bridge") {
2015
+ if (val === "all" || val === "mcp" || val === "none" || val === "codemode") {
2016
+ const next = saveConfig({ bridgeTools: val });
2017
+ ui?.notify(
2018
+ ctx.getMcpPort() === null
2019
+ ? `bridge ${next.bridgeTools}. The bridge server is not running; /reload to apply.`
2020
+ : `bridge ${next.bridgeTools}. The active catalog and call guard update now; ACP may keep cached tool schemas until a session reloads or an agy process restarts (/reload applies it).`,
2021
+ "info",
2022
+ );
2023
+ if (val === "codemode" && !pi.getActiveTools().includes("codemode")) {
2024
+ ui?.notify(
2025
+ "pi's codemode tool is inactive, so the engine sees an all-mode catalog and no codemode note. Activate it first: --tools codemode, the defaultTools setting, or /tools.",
2026
+ "warning",
2027
+ );
2028
+ }
2029
+ } else {
2030
+ ui?.notify(`bridge: ${loadConfig().bridgeTools}\nusage: /agy bridge all|mcp|codemode|none\n all: active pi tools except the core builtins (ACP declares the seven defaults directly; pi 1.x builtin MCP and tool_search tools bridge on both engines). mcp: active pi-mcp-adapter tools, pi 1.x builtin MCP and tool_search tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active; without it this behaves like all, minus ACP's direct builtins). none: no pi tools (an active approval gate still runs the listener gate-only).`, "info");
2031
+ }
2032
+ return;
2033
+ }
2034
+ if (sub === "tools") {
2035
+ const name = (args ?? "").trim().split(/\s+/).slice(2).join(" ");
2036
+ if (val === "reset") {
2037
+ ctx.hiddenBridgeTools.clear();
2038
+ ui?.notify("Antigravity tool visibility reset for this Pi session. Pi's active tools are unchanged.", "info");
2039
+ } else if ((val === "hide" || val === "show") && name) {
2040
+ if (!pi.getAllTools().some((tool) => tool.name === name)) {
2041
+ ui?.notify(`Unknown Pi tool: ${name}`, "error");
2042
+ return;
2043
+ }
2044
+ if (val === "hide") ctx.hiddenBridgeTools.add(name);
2045
+ else ctx.hiddenBridgeTools.delete(name);
2046
+ ui?.notify(`${name}: ${val === "hide" ? "hidden from Antigravity" : "visible if active in Pi"}. No MCP config changed.`, "info");
2047
+ } else {
2048
+ ui?.notify(`Exposed active Pi tools: ${ctx.bridgeTools().map((tool) => tool.name).join(", ") || "(none)"}\nHidden in this session: ${[...ctx.hiddenBridgeTools].join(", ") || "(none)"}\n/agy tools hide|show <exact Pi tool name> | reset\nUse Pi's /mcp or pi.setActiveTools() to change the underlying active tools.`, "info");
2049
+ }
2050
+ return;
2051
+ }
2052
+ if (sub === "model") {
2053
+ if (val && val.length > 0) {
2054
+ const next = saveConfig({ defaultModel: val });
2055
+ ui?.notify(`AskAntigravity default model set to ${next.defaultModel}`, "info");
2056
+ } else {
2057
+ ui?.notify(`AskAntigravity model: ${loadConfig().defaultModel} (fallback; callers may override per call)\nusage: /agy model flash|pro|gemini|<exact>`, "info");
2058
+ }
2059
+ return;
2060
+ }
2061
+ if (sub === "ask") {
2062
+ if (val === "on" || val === "off") {
2063
+ const next = saveConfig({ askTool: val === "on" });
2064
+ ui?.notify(
2065
+ next.askTool
2066
+ ? "AskAntigravity tool on. Registered on the next pi start (or /reload)."
2067
+ : "AskAntigravity tool off. It is removed from the model's tool list on the next pi start (or /reload). Provider and models stay.",
2068
+ "info",
2069
+ );
2070
+ } else {
2071
+ ui?.notify(`AskAntigravity tool: ${loadConfig().askTool ? "on" : "off"}\nusage: /agy ask on|off`, "info");
2072
+ }
2073
+ return;
2074
+ }
2075
+ if (sub === "web") {
2076
+ if (val === "on" || val === "off") {
2077
+ const next = saveConfig({ webTools: val === "on" });
2078
+ ui?.notify(
2079
+ next.webTools
2080
+ ? "Web tools on: agy_web_search and agy_read_url register on the next pi start (or /reload). Each call spends Antigravity quota."
2081
+ : "Web tools off: agy_web_search and agy_read_url will not register on the next pi start (or /reload).",
2082
+ "info",
2083
+ );
2084
+ } else {
2085
+ ui?.notify(`Web tools: ${loadConfig().webTools ? "on" : "off"}\nusage: /agy web on|off\nExposes agy_web_search + agy_read_url as Pi tools for ANY provider (Antigravity sessions already have native web tools). Default off; each call spends Antigravity quota.`, "info");
2086
+ }
2087
+ return;
2088
+ }
2089
+ if (sub === "digest") {
2090
+ if (val === "on" || val === "off") {
2091
+ const next = saveConfig({ digest: val === "on" });
2092
+ ui?.notify(
2093
+ next.digest
2094
+ ? "digest on. pi-side context ships when the delta is non-empty (fresh-conversation handoff, other-provider turns, pi-side tool runs, compaction summaries), each piece once. Pure antigravity sessions keep byte-stable prompts."
2095
+ : "digest off. agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context.",
2096
+ "info",
2097
+ );
2098
+ } else {
2099
+ ui?.notify(`digest: ${loadConfig().digest ? "on" : "off"}\nusage: /agy digest on|off`, "info");
2100
+ }
2101
+ return;
2102
+ }
2103
+ if (sub === "system-prompt") {
2104
+ if (val === "on" || val === "off") {
2105
+ const next = saveConfig({ systemPrompt: val === "on" });
2106
+ ui?.notify(
2107
+ next.systemPrompt
2108
+ ? "system-prompt on. pi's system prompt (incl. global and project AGENTS.md) is prepended to the first prompt of each new agy conversation. Existing conversations keep the version they started with."
2109
+ : "system-prompt off. agy runs on its own system prompt; pi instructions and AGENTS.md files are not sent.",
2110
+ "info",
2111
+ );
2112
+ } else {
2113
+ ui?.notify(`system-prompt: ${loadConfig().systemPrompt ? "on" : "off"}\nusage: /agy system-prompt on|off`, "info");
2114
+ }
2115
+ return;
2116
+ }
2117
+
2118
+ if (sub === "thinking") {
2119
+ if (val === "low" || val === "medium" || val === "high" || val === "xhigh") {
2120
+ const next = saveConfig({ defaultThinking: val as ThinkingTier });
2121
+ ui?.notify(`AskAntigravity default thinking set to ${next.defaultThinking}`, "info");
2122
+ } else {
2123
+ ui?.notify(`AskAntigravity thinking: ${loadConfig().defaultThinking} (fallback; callers may override per call)\nusage: /agy thinking low|medium|high|xhigh|xhigh`, "info");
2124
+ }
2125
+ return;
2126
+ }
2127
+
2128
+
2129
+ // No subcommand: print status, or open the picker in TUI. The old
2130
+ // "status" alias is retired; /agy doctor is the one status surface.
2131
+ if (sub) {
2132
+ const pointer = sub === "status" ? "/agy status was removed; use /agy doctor.\n" : "";
2133
+ ui?.notify(`${pointer}unknown subcommand: ${sub}\n${statusText(ctx)}`, "warning");
2134
+ return;
2135
+ }
2136
+
2137
+ if (mode !== "tui" || !ui) {
2138
+ ui?.notify(statusText(ctx), "info");
2139
+ return;
2140
+ }
2141
+
2142
+ await openAgyPicker(ui, ctx);
2143
+ },
2144
+ });
2145
+ }
2146
+
2147
+ /** Interactive settings picker (TUI only). Rows: the runtime config surface
2148
+ * (mode, permissions, model, thinking, bridge, digest, system prompt) plus
2149
+ * the engine row, which resolves the menu on Enter and opens the same
2150
+ * picker modal as /agy engine (self-service binary + auth setup for acp). */
2151
+ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promise<void> {
2152
+ const config = loadConfig();
2153
+ const pending: PendingConfig = {};
2154
+
2155
+ const rows: DialogRow[] = [
2156
+ // Value-less action row: DialogMenu resolves the menu with this id on
2157
+ // Enter (see runEngineModal below); every other row cycles in place.
2158
+ engineSettingsRow(config.engine),
2159
+ {
2160
+ id: "mode",
2161
+ label: "Execution mode",
2162
+ description:
2163
+ "accept-edits: agy applies edits directly. plan: provider turns are REFUSED (the CLI cannot enforce review-only, upstream #1181); AskAntigravity plan runs add a restricted agent as a damper. Takes effect next turn.",
2164
+ currentValue: config.mode,
2165
+ values: ["accept-edits", "plan"],
2166
+ },
2167
+ {
2168
+ id: "readonly",
2169
+ label: "Read-only provider turns",
2170
+ description:
2171
+ "on: provider turns are REFUSED (fail-closed; the CLI has no review-only enforcement on any path). Enforce read-only in the host instead.",
2172
+ currentValue: config.readOnly ? "on" : "off",
2173
+ values: ["off", "on"],
2174
+ },
2175
+ {
2176
+ id: "permissions",
2177
+ label: "Permissions",
2178
+ description:
2179
+ "auto-approved: --dangerously-skip-permissions (required so commands don't hang in -p mode). prompt: agy asks y/n (hangs non-interactively).",
2180
+ currentValue: config.skipPermissions ? "auto-approved" : "prompt",
2181
+ values: ["auto-approved", "prompt"],
2182
+ },
2183
+ {
2184
+ id: "ask",
2185
+ label: "AskAntigravity tool",
2186
+ description:
2187
+ "Register the AskAntigravity one-shot delegation tool. off removes it from the model's tool list (provider and models stay, even with the separate pi-ask-antigravity package installed). Takes effect on the next pi start (or /reload).",
2188
+ currentValue: config.askTool ? "on" : "off",
2189
+ values: ["on", "off"],
2190
+ },
2191
+ {
2192
+ id: "web",
2193
+ label: "Web tools",
2194
+ description:
2195
+ "Register agy_web_search + agy_read_url as Pi tools for ANY provider. Default off: Antigravity sessions already have native web tools, and each call spends Antigravity quota. Takes effect on the next pi start (or /reload).",
2196
+ currentValue: config.webTools ? "on" : "off",
2197
+ values: ["on", "off"],
2198
+ },
2199
+ {
2200
+ id: "model",
2201
+ label: "AskAntigravity model",
2202
+ description:
2203
+ "AskAntigravity one-shot delegation tool: model used when its caller omits the model param. Callers may override per call; this is only the fallback. flash/pro/gemini, or an exact id. Does not affect the provider model you pick in /model.",
2204
+ currentValue: config.defaultModel,
2205
+ values: ["flash", "pro", "gemini", "gemini-4-hydrogen"],
2206
+ },
2207
+ {
2208
+ id: "thinking",
2209
+ label: "AskAntigravity thinking",
2210
+ description:
2211
+ "AskAntigravity one-shot delegation tool: thinking tier used when the call names none. Callers may override per call; this is only the fallback. Pro has no Medium; it falls back to nearest.",
2212
+ currentValue: config.defaultThinking,
2213
+ values: ["low", "medium", "high", "xhigh"],
2214
+ },
2215
+ {
2216
+ id: "bridge",
2217
+ label: "Bridge tools",
2218
+ description:
2219
+ "Which pi tools the MCP bridge exposes to agy. all (default): every pi tool except the core builtins; pi 1.x builtin MCP and tool_search tools ride the proxied pair on both engines, and on ACP the builtins (read, ls, grep, find, edit, write, bash) are declared directly so long commands ride the poll machinery. mcp: pi-mcp-adapter tools, pi 1.x builtin MCP and tool_search tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active, e.g. --tools codemode). none: no pi tools (an active approval gate still runs the listener gate-only).",
2220
+ currentValue: config.bridgeTools,
2221
+ values: ["all", "mcp", "codemode", "none"],
2222
+ },
2223
+ {
2224
+ id: "turn-cap",
2225
+ label: "Turn time cap",
2226
+ description:
2227
+ "Max minutes for ONE agy turn before the bridge kills it. Default: no cap on an interactive pi (abort with Esc), 20 headless. 0 disables; 1-1440 enables the gate. Free type via /agy timeout <minutes|off> or config.json. Takes effect next turn.",
2228
+ currentValue: String(config.turnTimeoutMin),
2229
+ values: ["0", "1", "5", "10", "15", "30", "60", "120", "360", "720", "1440"],
2230
+ },
2231
+ {
2232
+ id: "digest",
2233
+ label: "Context digest",
2234
+ description:
2235
+ "Ship pi-side context (handoffs, other-provider turns, compactions) to agy when the delta is non-empty. Pure antigravity sessions keep byte-stable prompts.",
2236
+ currentValue: config.digest ? "on" : "off",
2237
+ values: ["on", "off"],
2238
+ },
2239
+ {
2240
+ id: "system-prompt",
2241
+ label: "System prompt",
2242
+ description:
2243
+ "Prepend pi's system prompt (incl. AGENTS.md files) to the first prompt of each new agy conversation.",
2244
+ currentValue: config.systemPrompt ? "on" : "off",
2245
+ values: ["on", "off"],
2246
+ },
2247
+ {
2248
+ id: "acp-session-timeout",
2249
+ label: "ACP session timeout (ms)",
2250
+ description:
2251
+ "Timeout in ms for ACP session/new, session/load, and session/close. Default 20000 (20s). Raise only on slow/proxied networks; custom values (1000-300000) can be set in config.json or AGY_ACP_SESSION_TIMEOUT_MS.",
2252
+ currentValue: String(config.acp.sessionTimeoutMs),
2253
+ values: ["20000", "30000", "45000", "60000", "90000"],
2254
+ },
2255
+ {
2256
+ id: "acp-session-retry",
2257
+ label: "ACP session/new retry (advanced)",
2258
+ description:
2259
+ "WARNING: disabled by default. Retries session/new once on silent timeout while agy acp is alive. Doubles total wait time on dead networks and may not recover if agy's internal socket is wedged.",
2260
+ currentValue: config.acp.sessionRetryOnTimeout ? "on" : "off",
2261
+ values: ["off", "on"],
2262
+ },
2263
+ ];
2264
+
2265
+ const resolved = await ui.custom<string | undefined>(
2266
+ (host, theme, _kb, done) => {
2267
+ const menu = new DialogMenu(
2268
+ host,
2269
+ theme,
2270
+ {
2271
+ title: "Pi Antigravity",
2272
+ subtitle: `Config file: ${configPath()} — changes save when the dialog closes`,
2273
+ rows,
2274
+ footer: "↑↓ navigate · Enter/Space cycle · Type to search · Esc close",
2275
+ onChange: (id, newValue) => {
2276
+ if (id === "mode") {
2277
+ pending.mode = newValue as AgyMode;
2278
+ } else if (id === "readonly") {
2279
+ pending.readOnly = newValue === "on";
2280
+ } else if (id === "permissions") {
2281
+ pending.skipPermissions = newValue === "auto-approved";
2282
+ } else if (id === "model") {
2283
+ pending.defaultModel = newValue;
2284
+ } else if (id === "thinking") {
2285
+ pending.defaultThinking = newValue as ThinkingTier;
2286
+ } else if (id === "ask") {
2287
+ pending.askTool = newValue === "on";
2288
+ } else if (id === "web") {
2289
+ pending.webTools = newValue === "on";
2290
+ } else if (id === "bridge") {
2291
+ pending.bridgeTools = newValue as BridgeTools;
2292
+ } else if (id === "turn-cap") {
2293
+ pending.turnTimeoutMin = Number(newValue);
2294
+ } else if (id === "digest") {
2295
+ pending.digest = newValue === "on";
2296
+ } else if (id === "system-prompt") {
2297
+ pending.systemPrompt = newValue === "on";
2298
+ } else if (id === "acp-session-timeout") {
2299
+ pending.acp = {
2300
+ ...pending.acp,
2301
+ sessionTimeoutMs: Number(newValue),
2302
+ };
2303
+ } else if (id === "acp-session-retry") {
2304
+ pending.acp = {
2305
+ ...pending.acp,
2306
+ sessionRetryOnTimeout: newValue === "on",
2307
+ };
2308
+ }
2309
+ },
2310
+ },
2311
+ (rowId) => done(rowId),
2312
+ );
2313
+ return {
2314
+ render: (w: number) => menu.render(w),
2315
+ invalidate: () => menu.invalidate(),
2316
+ handleInput: (data: string) => {
2317
+ menu.handleInput(data);
2318
+ host.requestRender();
2319
+ },
2320
+ };
2321
+ },
2322
+ { ...DIALOG_OPTIONS, blocked: dialogBlocked("Antigravity provider") },
2323
+ );
2324
+
2325
+ if (Object.keys(pending).length === 0) {
2326
+ if (resolved === ENGINE_SETTINGS_ROW_ID) await runEngineModal(ui, ctx);
2327
+ return;
2328
+ }
2329
+
2330
+ // The picker cannot switch engines (command-only: /agy engine), but the
2331
+ // mode row can still produce plan while the engine is acp - either the
2332
+ // session-latched engine or the on-disk one, which the Switch engine row
2333
+ // can change mid-session without a restart. Plan cannot be enforced on
2334
+ // provider turns on either engine; refuse the combination.
2335
+ const nextMode = pending.mode ?? config.mode;
2336
+ if (nextMode === "plan" && (ctx.engine === "acp" || config.engine === "acp")) {
2337
+ ui.notify(
2338
+ "plan cannot be enforced on provider turns (google-antigravity/antigravity-cli#1181); provider plan turns are disabled on ACP too. /agy mode accept-edits.",
2339
+ "warning",
2340
+ );
2341
+ return;
2342
+ }
2343
+
2344
+ try {
2345
+ const next = saveConfig(pending);
2346
+ const onOff = (b: boolean): string => (b ? "on" : "off");
2347
+ const changedParts: string[] = [];
2348
+ if (pending.mode) changedParts.push(`mode=${next.mode}`);
2349
+ if (pending.readOnly !== undefined) changedParts.push(`readOnly=${onOff(next.readOnly)}`);
2350
+ if (pending.skipPermissions !== undefined) {
2351
+ changedParts.push(`permissions=${next.skipPermissions ? "auto-approved" : "prompt"}`);
2352
+ }
2353
+ if (pending.askTool !== undefined) changedParts.push(`AskAntigravity tool=${onOff(next.askTool)}`);
2354
+ if (pending.webTools !== undefined) changedParts.push(`webTools=${onOff(next.webTools)}`);
2355
+ if (pending.defaultModel !== undefined) changedParts.push(`AskAntigravity model=${next.defaultModel}`);
2356
+ if (pending.defaultThinking !== undefined) changedParts.push(`AskAntigravity thinking=${next.defaultThinking}`);
2357
+ if (pending.bridgeTools !== undefined) changedParts.push(`bridge=${next.bridgeTools}`);
2358
+ if (pending.digest !== undefined) changedParts.push(`digest=${onOff(next.digest)}`);
2359
+ if (pending.systemPrompt !== undefined) changedParts.push(`system-prompt=${onOff(next.systemPrompt)}`);
2360
+ if (pending.turnTimeoutMin !== undefined) {
2361
+ changedParts.push(`turn cap=${next.turnTimeoutMin === 0 ? "off" : `${next.turnTimeoutMin}m`}`);
2362
+ }
2363
+ if (pending.acp?.sessionTimeoutMs !== undefined) {
2364
+ changedParts.push(`ACP session timeout=${next.acp.sessionTimeoutMs}ms`);
2365
+ }
2366
+ if (pending.acp?.sessionRetryOnTimeout !== undefined) {
2367
+ changedParts.push(`ACP session/new retry=${onOff(next.acp.sessionRetryOnTimeout)}`);
2368
+ }
2369
+ const changed = changedParts.join(", ");
2370
+ ui.notify(`Saved: ${changed}`, "info");
2371
+ } catch (err) {
2372
+ ui.notify(
2373
+ `Failed to save config: ${err instanceof Error ? err.message : String(err)}`,
2374
+ "error",
2375
+ );
2376
+ }
2377
+
2378
+ if (resolved === ENGINE_SETTINGS_ROW_ID) await runEngineModal(ui, ctx);
2379
+ }
2380
+
2381
+ /** The engine-pick modal shared by /agy engine (no args) and the settings
2382
+ * picker's engine row: the same explanations as the first-run wizard and the
2383
+ * same semantics: plan blocks acp and restart applies the switch. */
2384
+ async function runEngineModal(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promise<void> {
2385
+ const current = loadConfig().engine;
2386
+ let picked = await showEnginePicker(ui);
2387
+ if (picked === undefined) {
2388
+ ui.notify(`engine unchanged: ${current}.`, "info");
2389
+ return;
2390
+ }
2391
+ if (picked === current) {
2392
+ ui.notify(`engine is already ${current}. Restart applies it if set this session.`, "info");
2393
+ return;
2394
+ }
2395
+ // Consent gate: picking stream-json in the picker resolves only after the
2396
+ // warning; esc lands here as undefined above, so nothing is persisted.
2397
+ if (picked === "stream-json" && shouldWarnStreamJson("stream-json", loadConfig().streamJsonAcknowledged)) {
2398
+ const verdict = await showStreamJsonWarning(ui);
2399
+ if (verdict === undefined) {
2400
+ ui.notify(`engine unchanged: ${current}.`, "info");
2401
+ return;
2402
+ }
2403
+ if (verdict === "keep") {
2404
+ saveConfig({ engine: "stream-json", streamJsonAcknowledged: true });
2405
+ ui.notify(streamJsonKeptMessage(), "warning");
2406
+ ui.notify("Takes effect on the next pi start (or /reload).", "info");
2407
+ return;
2408
+ }
2409
+ picked = "acp";
2410
+ }
2411
+ if (picked === "acp" && loadConfig().mode === "plan") {
2412
+ ui.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
2413
+ return;
2414
+ }
2415
+ saveConfig({ engine: picked });
2416
+ ui.notify(savedEngineMessage(picked), "info");
2417
+ if (picked === "acp") void ctx.checkAgySetup({ ui, mode: "tui" }, "acp", true);
2418
+ }