@herbertgao/pi-extensions 2026.11.17 → 2026.11.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +2 -23
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +12 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/index.ts +7 -0
  64. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/agent-badge.ts +244 -0
  65. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +1 -1
  66. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +10 -3
  67. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +18 -0
  68. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  69. package/node_modules/@herbertgao/pi-inline-skill-commands/README.md +18 -0
  70. package/node_modules/@herbertgao/pi-inline-skill-commands/package.json +1 -1
  71. package/node_modules/@herbertgao/pi-inline-skill-commands/src/index.ts +80 -0
  72. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +320 -102
  73. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  74. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -30
  75. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  76. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  77. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  78. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  80. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +27 -13
  82. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  84. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +217 -41
  85. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  86. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  87. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -93
  88. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  89. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  90. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  91. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  92. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  93. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  94. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  95. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  96. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  97. package/node_modules/pi-commandcode-provider/README.md +3 -2
  98. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  99. package/node_modules/pi-commandcode-provider/package.json +4 -3
  100. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  101. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  102. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  103. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  104. package/package.json +12 -15
  105. package/node_modules/pi-antigravity/README.md +0 -298
  106. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  107. package/node_modules/pi-antigravity/package.json +0 -87
  108. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  109. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  110. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  111. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  112. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  113. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  114. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  115. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  116. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  117. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  118. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  119. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  120. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  121. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  122. package/node_modules/pi-antigravity/src/index.ts +0 -547
  123. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  124. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  125. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  126. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  127. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  128. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  129. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  130. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  131. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  132. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  133. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  134. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  135. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  136. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  137. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  138. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  139. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  140. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  141. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  142. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  143. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  144. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  145. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  146. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  147. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  148. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  149. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  150. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  151. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  152. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  153. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  154. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  155. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  156. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  157. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  158. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  159. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -0,0 +1,1221 @@
1
+ // The AskAntigravity tool: delegate a self-contained sub-task to Google
2
+ // Antigravity's `agy` CLI. Ported from pi-ask-antigravity v1.1.0 so this
3
+ // extension (pi-antigravity-bridge) provides BOTH the streaming provider AND
4
+ // the one-shot delegation tool - the same shape as pi-claude-bridge.
5
+ //
6
+ // One self-contained tool. Spawns `agy -p`, streams its stdout as partial
7
+ // output, returns the final response. agy runs its OWN tool loop (read,
8
+ // write, edit, exec) inside the workspace.
9
+ //
10
+ // When both pi-antigravity-bridge and pi-ask-antigravity are installed, the
11
+ // bridge wins: pi-ask-antigravity detects the bridge package and registers
12
+ // nothing (see its defer guard). This module is the single source of truth.
13
+
14
+ import { spawn } from "node:child_process";
15
+ import { randomBytes } from "node:crypto";
16
+ import * as fs from "node:fs";
17
+ import * as path from "node:path";
18
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
19
+ import { buildSessionContext } from "@earendil-works/pi-coding-agent";
20
+ import { Text } from "@earendil-works/pi-tui";
21
+ import { contentText, type ThinkingLevel } from "@earendil-works/pi-ai";
22
+ import { Type } from "typebox";
23
+ import {
24
+ BackgroundRunRegistry,
25
+ backgroundFlagText,
26
+ buildAgyArgs,
27
+ buildFinalPrompt,
28
+ buildTimeBudgetNotice,
29
+ createStopHandler,
30
+ createWakeSender,
31
+ MAX_TIMEOUT_MINUTES,
32
+ CONVERSATIONS_DIR,
33
+ CONV_ID_RE,
34
+ filterHiddenModels,
35
+ mergeCatalog,
36
+ newConversationId,
37
+ parseModelLine,
38
+ resolveAgyModel,
39
+ snapshotConversations,
40
+ summarizePrompt,
41
+ type ModelEntry,
42
+ type Mode,
43
+ } from "@estebanforge/pi-ask-shared";
44
+ import { extensionsDataDir, loadConfig, type AgyMode, type ThinkingTier } from "./config.js";
45
+ import { redactText } from "./redact.js";
46
+ import { acquireBridgeSuppression } from "./mcp-registration.js";
47
+ import { AGY_EFFORT_ORDER, spawnAgyModelsRaw, toAgyEffort } from "./models.js";
48
+ import { sweepStaleWebAgents, webAgentsRoot } from "./web-tools.js";
49
+
50
+ // --- Constants -------------------------------------------------------------
51
+
52
+ const AGY_DESCRIPTION = `Delegate a self-contained sub-task to Google Antigravity. agy is the CLI for Gemini, so this tool is reached under three equivalent names the user may use interchangeably: **gemini**, **antigravity**, and **agy**. When the user says "ask gemini", "ask antigravity", "ask agy", or otherwise refers to any of these, call THIS tool. agy runs its OWN tool loop: it can read, write, edit, and execute inside the workspace, then returns its final answer. Use for a second opinion from a different model family, Gemini-specific reasoning, or isolated sub-tasks you do not need to drive step-by-step. Provide a complete, self-contained task description; agy will not see this conversation.
53
+
54
+ TWO MODES (you choose):
55
+ - **One-shot (isolated)**: omit conversationId. agy starts fresh with no memory of prior calls. Use for independent questions.
56
+ - **Continued conversation**: pass the conversationId returned in the PREVIOUS call's details (details.conversationId). agy resumes that conversation with full context intact.
57
+
58
+ EXECUTION MODES (param: mode):
59
+ - **plan**: agy proposes a plan for review-shaped tasks. NOT a security boundary: the CLI does not gate writes under plan mode (upstream google-antigravity/antigravity-cli#1181, probed 2026-10-07: the write can execute in the same turn). The run additionally stages a temporary restricted agent whose toolset has no file-editing tools, as a damper, and the skip-permissions flag is never passed. Inline the material to review - a plan run cannot fetch it.
60
+ - **accept-edits**: agy applies edits directly inside the workspace. Default unless the configured mode is plan.
61
+
62
+ COMPACT OUTPUT (param: digest): when true, the prompt is prefixed to request compact digests instead of full file contents. Defaults on for plan, off for accept-edits.
63
+
64
+ THINKING LEVEL (params: thinking, effort - SYNONYMS for one knob):
65
+ - pi calls it thinking, agy calls it effort. Same thing. Pass ONE of the two.
66
+ - Values (pi vocabulary): minimal|low|medium|high|xhigh|max. Clamped to agy's low|medium|high; unknown values fall back to low. "peer review on high thinking" -> thinking: "high".
67
+ - An explicit level beats a tier embedded in model ("flash high") and the configured default. Omit both for the configured default.`;
68
+
69
+ // Delegations legitimately run long (research, review, analysis); a short
70
+ // default kills the run mid-task and the caller re-pays the whole prompt.
71
+ const DEFAULT_TIMEOUT_MIN = 30;
72
+ const GRACE_AFTER_TIMEOUT_MS = 5000;
73
+ const STATUS_INTERVAL_MS = 1000;
74
+ const STATUS_TAIL_CHARS = 160;
75
+
76
+ // renderCall / renderResult preview limits (match pi-claude-bridge).
77
+ const PREVIEW_MAX_CHARS = 1000;
78
+ const PREVIEW_MAX_LINES = 6;
79
+ const DISCOVERY_POLL_ATTEMPTS = 5;
80
+ const DISCOVERY_POLL_MS = 100;
81
+
82
+ /** Parse raw `agy models` text into tool-catalog entries: the shared line
83
+ * grammar + hidden-family filter + static sonnet/opus overlay. Pure: no
84
+ * spawn. */
85
+ export function toolModelsFromRaw(raw: string): ModelEntry[] {
86
+ return mergeCatalog(
87
+ filterHiddenModels(
88
+ raw
89
+ .split("\n")
90
+ .map(parseModelLine)
91
+ .filter((e): e is ModelEntry => e !== null),
92
+ ),
93
+ );
94
+ }
95
+
96
+ /** Query `agy models` and return tool-catalog entries. Returns [] on failure.
97
+ * Kept for standalone use; the extension entry spawns once and parses via
98
+ * toolModelsFromRaw to avoid a second `agy models` invocation. */
99
+ export async function discoverToolModels(binary: string): Promise<ModelEntry[]> {
100
+ return toolModelsFromRaw(await spawnAgyModelsRaw(binary));
101
+ }
102
+
103
+ function extraArgs(): string[] {
104
+ const raw = process.env.AGY_EXTRA_ARGS;
105
+ return raw ? raw.split(/\s+/).filter((s) => s.length > 0) : [];
106
+ }
107
+
108
+ // --- Prompt assembly: shared peer adapter ----------------------------------
109
+ // PLAN_HEADLESS_GUARD / AGENT_REVIEW_GUARD / buildFinalPrompt live in
110
+ // pi-ask-shared (peers/antigravity.ts); the bridge inherits the identical
111
+ // guard discipline. Re-exported for the bridge's own tests.
112
+ export { AGENT_REVIEW_GUARD, buildFinalPrompt, PLAN_HEADLESS_GUARD } from "@estebanforge/pi-ask-shared";
113
+
114
+ // --- Plan-mode reviewer agent ----------------------------------------------
115
+
116
+ /** Temp agent dirs share the ~/.gemini/config/agents discovery root with the
117
+ * web delegates; AGY_AGENTS_ROOT overrides for tests and sandboxes. */
118
+ export function askAgentsRoot(): string {
119
+ return process.env.AGY_AGENTS_ROOT ?? webAgentsRoot();
120
+ }
121
+
122
+ const ASK_AGENT_PREFIX = "pi-bridge-ask-";
123
+ const ASK_AGENT_TOOLS = ["view_file", "run_command"];
124
+
125
+ /** agent.md for the plan-mode reviewer. The tools list is a damper, not a
126
+ * guarantee: with no file-editing tool present the model has no edit tool in
127
+ * its menu (probed 2026-09-28 on agy 1.2.12: the toolset reports "none" for
128
+ * edits; re-verify on 1.3.x), but the CLI itself does not enforce
129
+ * review-only under plan mode (upstream google-antigravity/antigravity-cli
130
+ * #1181, probed 2026-10-07: the write can execute in the same turn).
131
+ * commandExecutionPolicy auto is what lets read commands run headless with
132
+ * no user allow rules. Never add a write-capable tool here. */
133
+ export function reviewerAgentMd(name: string): string {
134
+ return [
135
+ "---",
136
+ `name: ${name}`,
137
+ "description: Temporary Pi plan-mode reviewer",
138
+ "mainAgent: true",
139
+ "subagent: false",
140
+ "model: inherit",
141
+ "excludeDefaultComponents: true",
142
+ "inheritCustomizations: false",
143
+ "inheritMcp: false",
144
+ "commandExecutionPolicy: auto",
145
+ "tools:",
146
+ ...ASK_AGENT_TOOLS.map((t) => ` - ${t}`),
147
+ "skills: []",
148
+ "rules: []",
149
+ "agents: []",
150
+ "mcpServers: []",
151
+ "---",
152
+ "",
153
+ "You are a strict read-only code reviewer. Review, analyze, and plan; never modify anything.",
154
+ "",
155
+ ].join("\n");
156
+ }
157
+
158
+ /** Stage one unique reviewer agent (agent.md + pid marker) under root. Same
159
+ * hygiene doctrine as the web delegates: nonce-named, cleaned in finally,
160
+ * orphans swept by pid marker at registration. */
161
+ export function stageReviewerAgent(root: string): { name: string; dir: string } {
162
+ fs.mkdirSync(root, { recursive: true });
163
+ const name = `${ASK_AGENT_PREFIX}${process.pid}-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
164
+ const dir = path.join(root, name);
165
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
166
+ fs.writeFileSync(path.join(dir, "agent.md"), reviewerAgentMd(name), { mode: 0o600 });
167
+ fs.writeFileSync(path.join(dir, ".pid"), `${process.pid}\n`, { mode: 0o600 });
168
+ return { name, dir };
169
+ }
170
+
171
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
172
+
173
+ // --- One-shot agy run -------------------------------------------------------
174
+
175
+ type AskLogFn = (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
176
+
177
+ /** Terminal result of one `agy -p` lifecycle. */
178
+ interface AgyOutcome {
179
+ exitCode: number;
180
+ aborted: boolean;
181
+ timedOut: boolean;
182
+ /** Full stdout, trimmed. Empty means the headless auto-deny failure mode. */
183
+ answerText: string;
184
+ }
185
+
186
+ /** Tool-result shape the execute path returns; keeps the background helper's literals narrow. */
187
+ interface AskToolResult {
188
+ content: Array<{ type: "text"; text: string }>;
189
+ details: AgyDetails;
190
+ }
191
+
192
+ /**
193
+ * Spawns `agy -p` and resolves when the process tree closes. Blocking and
194
+ * background runs share this lifecycle. Owns the delegation-suppression
195
+ * window for the WHOLE run: agy watches the global mcp_config and
196
+ * hot-reloads it, so a mid-run re-enable pokes the live delegation
197
+ * (observed live 2026-09-09). Background runs outlive execute()'s return,
198
+ * which is why the window lives here and not in the caller's finally.
199
+ */
200
+ async function runAgyProcess(o: {
201
+ binary: string;
202
+ args: string[];
203
+ cwd: string;
204
+ timeoutMin: number;
205
+ startAt: number;
206
+ /** Mutated in place: conversationId discovery, stderr, outcome fields. */
207
+ details: AgyDetails;
208
+ isContinuation: boolean;
209
+ snapshot: ReturnType<typeof snapshotConversations> | null;
210
+ background: boolean;
211
+ /** Blocking passes pi's per-run signal; background passes none on purpose: a later Esc must not kill a detached run. */
212
+ signal?: AbortSignal;
213
+ /** Blocking only: throttled progress partials. */
214
+ onPartial?: (text: string) => void;
215
+ /** Background only: hands over the tree-kill switch as soon as it exists. */
216
+ registerKill?: (kill: () => void) => void;
217
+ /** Background only: the child closed; discovery/classification still running. Arms the stop handler's finishing guard. */
218
+ onClose?: () => void;
219
+ log?: AskLogFn;
220
+ }): Promise<AgyOutcome> {
221
+ const restoreBridge = acquireBridgeSuppression();
222
+ let bridgeReleased = false;
223
+ const releaseBridge = () => {
224
+ if (bridgeReleased) return;
225
+ bridgeReleased = true;
226
+ restoreBridge();
227
+ };
228
+ let out = "";
229
+ // Local: o.snapshot narrowing does not survive into the bind-poll closure.
230
+ const snapshot = o.snapshot;
231
+ const statusInterval = o.onPartial
232
+ ? setInterval(() => {
233
+ const elapsed = Math.floor((Date.now() - o.startAt) / 1000);
234
+ const tail = out.slice(-STATUS_TAIL_CHARS);
235
+ const text = tail ? `(running ${elapsed}s)\n…${tail}` : `(running ${elapsed}s)`;
236
+ o.onPartial!(text);
237
+ }, STATUS_INTERVAL_MS)
238
+ : null;
239
+
240
+ try {
241
+ // Bind the conversation id DURING the run (agy is alive then) so the
242
+ // pid-based /proc FD resolver can disambiguate when a concurrent agy
243
+ // also drops a new .db. Awaited after the run; the post-exit loop
244
+ // below is the fallback for runs that exit before the poll binds.
245
+ let bindDuringRun: Promise<void> = Promise.resolve();
246
+ const outcome = await new Promise<{ exitCode: number; aborted: boolean; timedOut: boolean }>((resolveP, rejectP) => {
247
+ const proc = spawn(o.binary, o.args, {
248
+ cwd: o.cwd,
249
+ stdio: ["ignore", "pipe", "pipe"],
250
+ shell: false,
251
+ detached: true,
252
+ });
253
+ proc.stdout?.setEncoding("utf8");
254
+ proc.stderr?.setEncoding("utf8");
255
+ // Valve: a runaway child must not grow these without bound over a
256
+ // detached run's lifetime (timeouts can reach days).
257
+ proc.stdout?.on("data", (d: string) => {
258
+ if (out.length < 1_000_000) out += d;
259
+ });
260
+ proc.stderr?.on("data", (d: string) => {
261
+ if (o.details.stderr.length < 65_536) o.details.stderr += d;
262
+ });
263
+
264
+ if (!o.isContinuation && snapshot && proc.pid) {
265
+ bindDuringRun = (async () => {
266
+ for (let attempt = 0; attempt < DISCOVERY_POLL_ATTEMPTS; attempt++) {
267
+ if (o.details.conversationId) return;
268
+ if (proc.exitCode !== null) return; // agy gone: scan useless now
269
+ const found = newConversationId(CONVERSATIONS_DIR, snapshot, {
270
+ pid: proc.pid,
271
+ });
272
+ if (found) {
273
+ o.details.conversationId = found;
274
+ return;
275
+ }
276
+ await sleep(DISCOVERY_POLL_MS);
277
+ }
278
+ })().catch(() => {
279
+ /* best-effort: a bind error must never fail an otherwise-OK turn */
280
+ });
281
+ }
282
+
283
+ let sigkillTimer: ReturnType<typeof setTimeout> | undefined;
284
+ let watchdog: ReturnType<typeof setTimeout> | undefined;
285
+ let settled = false;
286
+ let timedOut = false;
287
+
288
+ const killTree = () => {
289
+ try {
290
+ if (proc.pid) process.kill(-proc.pid, "SIGTERM");
291
+ } catch {
292
+ /* process group already gone */
293
+ }
294
+ if (!sigkillTimer) {
295
+ sigkillTimer = setTimeout(() => {
296
+ try {
297
+ if (proc.pid) process.kill(-proc.pid, "SIGKILL");
298
+ } catch {
299
+ /* give up */
300
+ }
301
+ }, GRACE_AFTER_TIMEOUT_MS);
302
+ }
303
+ };
304
+
305
+ // Hand the tree-kill switch to the background registry before the
306
+ // watchdog arms, so /agy-stop can land the moment the run exists.
307
+ o.registerKill?.(killTree);
308
+
309
+ const cleanup = () => {
310
+ if (watchdog) clearTimeout(watchdog);
311
+ if (sigkillTimer) clearTimeout(sigkillTimer);
312
+ if (o.signal) o.signal.removeEventListener("abort", onAbort);
313
+ releaseBridge();
314
+ o.onClose?.();
315
+ };
316
+ const onAbort = () => killTree();
317
+
318
+ watchdog = setTimeout(() => {
319
+ timedOut = true;
320
+ killTree();
321
+ }, o.timeoutMin * 60_000);
322
+
323
+ if (o.signal) {
324
+ if (o.signal.aborted) killTree();
325
+ else o.signal.addEventListener("abort", onAbort, { once: true });
326
+ }
327
+
328
+ const finish = (code: number | null) => {
329
+ if (settled) return;
330
+ settled = true;
331
+ cleanup();
332
+ resolveP({ exitCode: code ?? 0, aborted: !!o.signal?.aborted, timedOut });
333
+ };
334
+
335
+ proc.on("error", (err) => {
336
+ cleanup();
337
+ rejectP(err);
338
+ });
339
+ // Settle on close, never exit: exit can strand unread stdout
340
+ // (truncated answer) and would clear the SIGKILL escalation while
341
+ // group members are still dying.
342
+ proc.on("close", finish);
343
+ });
344
+
345
+ // Let the during-run bind poll finish (it bails immediately once agy
346
+ // has exited, so this rarely blocks).
347
+ await bindDuringRun;
348
+
349
+ o.details.exitCode = outcome.exitCode;
350
+ o.details.aborted = outcome.aborted;
351
+ o.details.timedOut = outcome.timedOut;
352
+ // details ride the tool result and are persisted in session files;
353
+ // stderr can carry auth material, so it is scrubbed at this boundary.
354
+ o.details.stderr = redactText(o.details.stderr);
355
+ o.details.durationMs = Date.now() - o.startAt;
356
+ o.log?.(
357
+ "ask-end",
358
+ { exitCode: outcome.exitCode, aborted: outcome.aborted, timedOut: outcome.timedOut, empty: !out.trim(), background: o.background, durationMs: o.details.durationMs, conversationId: o.details.conversationId },
359
+ outcome.exitCode !== 0 || outcome.aborted || outcome.timedOut || !out.trim() ? "warn" : "info",
360
+ );
361
+
362
+ if (!o.isContinuation && !o.details.conversationId && snapshot) {
363
+ for (let attempt = 0; attempt < DISCOVERY_POLL_ATTEMPTS; attempt++) {
364
+ const found = newConversationId(CONVERSATIONS_DIR, snapshot);
365
+ if (found) {
366
+ o.details.conversationId = found;
367
+ break;
368
+ }
369
+ await sleep(DISCOVERY_POLL_MS);
370
+ }
371
+ }
372
+
373
+ return { ...outcome, answerText: out.trim() };
374
+ } finally {
375
+ if (statusInterval) clearInterval(statusInterval);
376
+ // Belt and braces: cleanup() already releases on close/error; this
377
+ // covers paths that never reached the process (sync spawn throw).
378
+ releaseBridge();
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Builds the model/user-facing answer text for every terminal outcome.
384
+ * Pure except the empty-output marker it stamps on details. Blocking and
385
+ * background share it so both surfaces read identically.
386
+ */
387
+ function shapeFinalText(details: AgyDetails, outcome: AgyOutcome, timeoutMin: number): string {
388
+ const text = outcome.answerText;
389
+
390
+ if (outcome.aborted) {
391
+ return text ? `agy was aborted. Partial output:\n\n${text}` : "agy was aborted before producing output.";
392
+ }
393
+
394
+ if (outcome.timedOut) {
395
+ const note = `agy exceeded the ${timeoutMin}m timeout and was killed`;
396
+ return text ? `${text}\n\n[${note}]` : note;
397
+ }
398
+
399
+ if (outcome.exitCode !== 0) {
400
+ // stderr can carry auth material; the note is chat-visible.
401
+ const stderr = redactText(details.stderr.trim());
402
+ const note = stderr
403
+ ? `agy exited with status ${outcome.exitCode}: ${stderr}`
404
+ : `agy exited with status ${outcome.exitCode}`;
405
+ return text ? `${text}\n\n[${note}]` : note;
406
+ }
407
+
408
+ // Exit 0 with nothing on stdout is still a failure for the
409
+ // delegator: headless agy auto-denies a permission-gated tool call
410
+ // (e.g. the command gate in plan mode), prints the reason only to
411
+ // stderr, and ends cleanly. Falling through to the success path here
412
+ // returned just the conversation footer, which read as an empty
413
+ // success (silent-failure bug found 2026-09-25).
414
+ if (!text) {
415
+ details.empty = true;
416
+ const stderr = redactText(details.stderr.trim());
417
+ const note = [
418
+ "agy exited cleanly but produced no output.",
419
+ stderr ? `stderr: ${stderr}` : null,
420
+ "Common cause: a tool call needed a permission that headless mode cannot prompt for (typically the command gate in plan mode), so it was auto-denied and the turn ended with no answer. Recovery: retry in plan mode with all needed content inlined in the prompt - plan runs cannot fetch it, commands are denied. Or rerun outside plan mode with skipPermissions, or add your own permissions.allow rules in ~/.gemini/antigravity-cli/settings.json.",
421
+ ]
422
+ .filter(Boolean)
423
+ .join(" ");
424
+ return note;
425
+ }
426
+
427
+ const footer = details.conversationId
428
+ ? `\n\n[agy conversationId: ${details.conversationId} - pass as conversationId to continue this conversation]`
429
+ : "";
430
+ return text + footer;
431
+ }
432
+
433
+ // --- Registration ----------------------------------------------------------
434
+
435
+ /** Register the AskAntigravity tool. Call once from the extension entry.
436
+ * `entries` is the merged live+overlay catalog discovered at load. */
437
+ export async function registerAskAntigravityTool(
438
+ pi: ExtensionAPI,
439
+ entries: ModelEntry[],
440
+ /** Daily file log sink (src/daily-log.ts). Records lifecycle, never
441
+ * prompt text. Level matches DailyLogger: debug is the AGY_DEBUG-only
442
+ * verbose tier; info/warn/error always land. */
443
+ log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void,
444
+ ): Promise<void> {
445
+ // Orphan sweep for the plan-mode reviewer agents (SIGKILL can skip the
446
+ // run's finally): same pid-marker doctrine as the web delegates.
447
+ try {
448
+ sweepStaleWebAgents(askAgentsRoot(), Date.now(), ASK_AGENT_PREFIX);
449
+ } catch {
450
+ // a sweep failure must never block registration
451
+ }
452
+
453
+ // --- Background-run state (one set per registration/load) ----------------
454
+ // Pi wipes module state on /new, /resume, /fork and /reload: an in-flight
455
+ // background run is killed and its result is never delivered. Accepted
456
+ // trade-off, same as the standalone pi-ask-antigravity extension.
457
+ const registry = new BackgroundRunRegistry({ toolName: "ask-antigravity" });
458
+ const kills = new Map<string, () => void>();
459
+ // Staged-artifact cleanup (contextFile + reviewer agent dir), keyed by run:
460
+ // the session_shutdown backstop runs these when a hard exit would skip the
461
+ // close-path cleanup.
462
+ const cleanups = new Map<string, () => void>();
463
+ // One run per conversationId at a time: two runs resuming the same
464
+ // conversation interleave their turns inside agy's SQLite state.
465
+ const busyHandles = new Set<string>();
466
+ // The child closed but the answer is not settled yet (discovery +
467
+ // classification): a stop in this window must refuse instead of settling
468
+ // failed and discarding a computed answer.
469
+ const finishing = new Set<string>();
470
+ // The wake is chat-visible and persisted: run it through the bridge's
471
+ // secret redactor like every other reassembled-output boundary.
472
+ const sendWake = createWakeSender(pi, {
473
+ customType: "ask-antigravity-result",
474
+ isDisposed: () => registry.isDisposed(),
475
+ redact: redactText,
476
+ });
477
+ const stopBackground = createStopHandler(registry, {
478
+ kill: (run) => kills.get(run.runId)?.(),
479
+ onStopped: (run) =>
480
+ sendWake({
481
+ toolLabel: "agy",
482
+ runId: run.runId,
483
+ ok: false,
484
+ elapsedS: Math.round((Date.now() - run.startedAt) / 1000),
485
+ error: "stopped via /agy-stop",
486
+ }),
487
+ // The guard keeps /agy-stop from discarding an answer that already
488
+ // finished computing and is riding discovery to its wake.
489
+ guard: (run) =>
490
+ finishing.has(run.runId) ? `Run ${run.runId} already finished; its result is being delivered.` : null,
491
+ });
492
+ pi.on("session_shutdown", () => {
493
+ // Latch first so close-handler wakes stay silent, then kill children,
494
+ // then sweep staged artifacts (a hard exit would skip the close path).
495
+ for (const run of registry.dispose()) kills.get(run.runId)?.();
496
+ for (const fn of cleanups.values()) fn();
497
+ cleanups.clear();
498
+ kills.clear();
499
+ });
500
+ pi.registerCommand("agy-stop", {
501
+ description: "Stop a background AskAntigravity run (id prefix, or the only running one). Usage: /agy-stop [runId]",
502
+ handler: async (args, ctx) => {
503
+ const message = await stopBackground(args ?? "");
504
+ if (ctx.hasUI) ctx.ui.notify(message, "info");
505
+ },
506
+ });
507
+
508
+ /** Fire-and-forget background run: registry slot, detached agy, wake on
509
+ * settle. Mirrors the standalone pi-ask-antigravity extension call for
510
+ * call; only the suppression window and the redaction are bridge-local. */
511
+ const startBackgroundRun = (o: {
512
+ summary: string;
513
+ binary: string;
514
+ args: string[];
515
+ workdir: string;
516
+ timeoutMin: number;
517
+ startAt: number;
518
+ details: AgyDetails;
519
+ contextFile: string | null;
520
+ reviewerAgent: { name: string; dir: string } | null;
521
+ modelLabel: string;
522
+ isContinuation: boolean;
523
+ snapshot: ReturnType<typeof snapshotConversations> | null;
524
+ conversationId?: string;
525
+ }): AskToolResult => {
526
+ const cleanupStaging = () => {
527
+ // Both staged artifacts must outlive the execute() return in
528
+ // background mode: agy reads them mid-run.
529
+ if (o.contextFile) {
530
+ try {
531
+ fs.unlinkSync(o.contextFile);
532
+ } catch {}
533
+ }
534
+ if (o.reviewerAgent) {
535
+ try {
536
+ fs.rmSync(o.reviewerAgent.dir, { recursive: true, force: true });
537
+ } catch {}
538
+ }
539
+ };
540
+ registry.sweep();
541
+ if (o.conversationId && busyHandles.has(o.conversationId)) {
542
+ cleanupStaging();
543
+ return {
544
+ content: [
545
+ {
546
+ type: "text",
547
+ text: `background refused: conversation ${o.conversationId} already has a background run. Wait for its wake message, or use blocking mode.`,
548
+ },
549
+ ],
550
+ details: { ...o.details, refused: true },
551
+ };
552
+ }
553
+ if (o.conversationId) busyHandles.add(o.conversationId);
554
+ let run;
555
+ try {
556
+ run = registry.start(summarizePrompt(o.summary));
557
+ } catch (err) {
558
+ if (o.conversationId) busyHandles.delete(o.conversationId);
559
+ cleanupStaging();
560
+ const msg = err instanceof Error ? err.message : String(err);
561
+ return {
562
+ content: [
563
+ {
564
+ type: "text",
565
+ text: `background refused: ${msg}. Use blocking (omit background) or free a slot with /agy-stop.`,
566
+ },
567
+ ],
568
+ details: { ...o.details, refused: true },
569
+ };
570
+ }
571
+ const runId = run.runId;
572
+ cleanups.set(runId, cleanupStaging);
573
+ log?.(
574
+ "ask-start",
575
+ { model: o.details.resolvedModel, thinking: o.details.thinking, mode: o.details.mode, digest: o.details.digest, continue: o.isContinuation, timeoutMin: o.timeoutMin, background: true },
576
+ "info",
577
+ );
578
+ void runAgyProcess({
579
+ binary: o.binary,
580
+ args: o.args,
581
+ cwd: o.workdir,
582
+ timeoutMin: o.timeoutMin,
583
+ startAt: o.startAt,
584
+ details: o.details,
585
+ isContinuation: o.isContinuation,
586
+ snapshot: o.snapshot,
587
+ background: true,
588
+ registerKill: (kill) => {
589
+ kills.set(runId, kill);
590
+ },
591
+ onClose: () => finishing.add(runId),
592
+ log,
593
+ })
594
+ .then((outcome) => {
595
+ kills.delete(runId);
596
+ const finalText = shapeFinalText(o.details, outcome, o.timeoutMin);
597
+ const elapsedS = Math.round((Date.now() - o.startAt) / 1000);
598
+ const handle = o.details.conversationId ? `conversationId=${o.details.conversationId}` : undefined;
599
+ const failed = outcome.timedOut || outcome.exitCode !== 0 || !outcome.answerText;
600
+ // The settle latch makes /agy-stop and shutdown win races
601
+ // against this handler: a false return means their wake went out.
602
+ const settled = registry.settle(runId, {
603
+ status: failed ? "failed" : "done",
604
+ output: finalText,
605
+ handle,
606
+ error: outcome.timedOut
607
+ ? `timeout after ${o.timeoutMin}m`
608
+ : outcome.exitCode !== 0
609
+ ? `exit status ${outcome.exitCode}`
610
+ : !outcome.answerText
611
+ ? "agy exited cleanly but produced no output"
612
+ : undefined,
613
+ });
614
+ if (!settled) return;
615
+ if (outcome.timedOut) {
616
+ const partial = outcome.answerText
617
+ ? ` Partial output: ${redactText(outcome.answerText).slice(0, 400)}`
618
+ : "";
619
+ sendWake({ toolLabel: "agy", runId, ok: false, elapsedS, error: `timeout after ${o.timeoutMin}m.${partial}`, handle });
620
+ } else if (outcome.exitCode !== 0) {
621
+ // stderr can carry auth material; the reason is chat-visible.
622
+ const reason = redactText(o.details.stderr.trim()).slice(0, 400) || `exit status ${outcome.exitCode}`;
623
+ sendWake({ toolLabel: "agy", runId, ok: false, elapsedS, error: reason, handle });
624
+ } else if (!outcome.answerText) {
625
+ sendWake({ toolLabel: "agy", runId, ok: false, elapsedS, error: "agy exited cleanly but produced no output (headless auto-deny?)", handle });
626
+ } else {
627
+ sendWake({ toolLabel: "agy", runId, ok: true, elapsedS, handle }, finalText);
628
+ }
629
+ })
630
+ .catch((err) => {
631
+ kills.delete(runId);
632
+ const msg = err instanceof Error ? err.message : String(err);
633
+ // Settle first: an /agy-stop that won the race owns the wake.
634
+ const settled = registry.settle(runId, { status: "failed", error: msg });
635
+ if (!settled) return;
636
+ sendWake({ toolLabel: "agy", runId, ok: false, error: `failed to run agy: ${msg}` });
637
+ })
638
+ .finally(() => {
639
+ cleanups.delete(runId);
640
+ finishing.delete(runId);
641
+ cleanupStaging();
642
+ if (o.conversationId) busyHandles.delete(o.conversationId);
643
+ });
644
+ return {
645
+ content: [
646
+ {
647
+ type: "text",
648
+ text: `Background run ${runId} started (model=${o.modelLabel}). The result arrives as a message when agy finishes; the resume handle (conversationId) comes with it when agy reports one. Do not poll. Continue with other work or end the turn.`,
649
+ },
650
+ ],
651
+ details: { ...o.details },
652
+ };
653
+ };
654
+
655
+ pi.registerTool({
656
+ name: "AskAntigravity",
657
+ label: "Ask Antigravity",
658
+ description: AGY_DESCRIPTION,
659
+ parameters: Type.Object({
660
+ prompt: Type.String({
661
+ description:
662
+ "Self-contained task for agy. Include all context agy needs; it cannot see this conversation.",
663
+ }),
664
+ cwd: Type.Optional(
665
+ Type.String({
666
+ description: "Absolute workspace path agy runs in. Defaults to the current project root.",
667
+ }),
668
+ ),
669
+ model: Type.Optional(
670
+ Type.String({
671
+ description:
672
+ "Model alias or exact id. Friendly: 'flash', 'pro', 'gemini'. Add a tier: 'flash high'. Pin a version: '3.5 flash'. Exact: 'gemini-3.6-flash-medium'. Omit for the configured default.",
673
+ }),
674
+ ),
675
+ thinking: Type.Optional(
676
+ Type.String({
677
+ description:
678
+ "Thinking level (= agy effort tier). pi vocabulary: minimal|low|medium|high|xhigh|max, clamped to agy's low|medium|high (unknown values fall back to low). Overrides a tier embedded in `model`. Omit for the configured default.",
679
+ }),
680
+ ),
681
+ effort: Type.Optional(
682
+ Type.String({
683
+ description:
684
+ "Alias for `thinking` (agy's own name for the same knob). Pass ONE of the two; different values on both is an error.",
685
+ }),
686
+ ),
687
+ mode: Type.Optional(
688
+ Type.Union([Type.Literal("plan"), Type.Literal("accept-edits")], {
689
+ description:
690
+ "agy execution mode. 'plan' = plan-shaped run: the CLI does not enforce review-only (see the tool description); the staged reviewer agent's toolset omits file-editing tools as a damper. 'accept-edits' = agy applies edits. Omit to follow the configured default (plan when config mode is plan, else accept-edits).",
691
+ }),
692
+ ),
693
+ digest: Type.Optional(
694
+ Type.Boolean({
695
+ description:
696
+ "Request compact digests instead of full file contents. Defaults on for plan, off for accept-edits.",
697
+ }),
698
+ ),
699
+ conversationId: Type.Optional(
700
+ Type.String({
701
+ description:
702
+ "Omit for a one-shot. To CONTINUE a previous agy conversation, pass the conversationId returned in that call's details.",
703
+ }),
704
+ ),
705
+ timeoutMinutes: Type.Optional(
706
+ Type.Number({ description: `Hard cap on the agy run in minutes. Default ${DEFAULT_TIMEOUT_MIN}. Fractional minutes allowed; must be above 0 and at most ${MAX_TIMEOUT_MINUTES}. The prompt carries a matching [TIME BUDGET] notice.` }),
707
+ ),
708
+ includeContext: Type.Optional(
709
+ Type.Boolean({
710
+ description:
711
+ "When true, export the current pi conversation (resolved, as markdown) to a temp file inside the workspace and tell agy to read it first. Default false (isolated one-shot). Opt in only when the user explicitly wants agy to see the full conversation; it costs agy tokens to read.",
712
+ }),
713
+ ),
714
+ background: Type.Optional(
715
+ Type.Boolean({
716
+ description: backgroundFlagText("conversationId"),
717
+ default: false,
718
+ }),
719
+ ),
720
+ }),
721
+ renderCall(args, theme, _context) {
722
+ // Show RESOLVED model/thinking/mode (config defaults applied) so the
723
+ // row identifies what will actually run, not just explicit args.
724
+ const cfg = loadConfig();
725
+ const requestedModel = (args.model as string | undefined)?.trim() || cfg.defaultModel;
726
+ const thinkingArg = (args.thinking as string | undefined) ?? (args.effort as string | undefined);
727
+ const resolved =
728
+ resolveAgyModel(
729
+ requestedModel,
730
+ entries,
731
+ cfg.defaultThinking,
732
+ thinkingArg ? toAgyEffort(thinkingArg as ThinkingLevel, AGY_EFFORT_ORDER) : undefined,
733
+ ) ?? { model: requestedModel };
734
+ const thinking: ThinkingTier = resolved.effort ?? cfg.defaultThinking;
735
+ // Same default rule as execute: plan when the configured mode is
736
+ // plan, so the row always names what will actually run.
737
+ const mode: AgyMode =
738
+ (args.mode as AgyMode | undefined) ?? (cfg.mode === "plan" ? "plan" : "accept-edits");
739
+ const useDigest = typeof args.digest === "boolean" ? args.digest : mode === "plan";
740
+ const isContinue =
741
+ typeof args.conversationId === "string" && CONV_ID_RE.test(args.conversationId);
742
+
743
+ const tags: string[] = [`model=${resolved.model}`, `thinking=${thinking}`];
744
+ if (mode !== "accept-edits") tags.push(`mode=${mode}`);
745
+ if (useDigest) tags.push("digest");
746
+ if (isContinue) tags.push("continue");
747
+ if (args.includeContext) tags.push("context=full");
748
+ if (args.background) tags.push("bg");
749
+
750
+ let text = theme.fg("success", theme.bold("AskAntigravity "));
751
+ text += `${theme.fg("accent", `[${tags.join(", ")}]`)} `;
752
+
753
+ const prompt = String(args.prompt ?? "");
754
+ const truncated = prompt.length > PREVIEW_MAX_CHARS ? prompt.slice(0, PREVIEW_MAX_CHARS) : prompt;
755
+ const lines = truncated.split("\n").slice(0, PREVIEW_MAX_LINES);
756
+ text += theme.fg("muted", `"${lines.join("\n")}"`);
757
+ if (prompt.length > PREVIEW_MAX_CHARS || prompt.split("\n").length > PREVIEW_MAX_LINES) {
758
+ text += theme.fg("dim", " …");
759
+ }
760
+ return new Text(text, 0, 0);
761
+ },
762
+ renderResult(result, { expanded, isPartial }, theme, context) {
763
+ const d = result.details as AgyDetails | undefined;
764
+ if (isPartial) {
765
+ const status = result.content[0]?.type === "text" ? result.content[0].text : "working...";
766
+ return new Text(theme.fg("success", "◉ AskAntigravity ") + theme.fg("muted", status), 0, 0);
767
+ }
768
+
769
+ const body = result.content[0]?.type === "text" ? result.content[0].text : "";
770
+ const errored =
771
+ !!d?.refused || d?.exitCode !== 0 || !!d?.aborted || !!d?.timedOut || !!d?.empty;
772
+
773
+ let text = errored
774
+ ? theme.fg("error", "✗ AskAntigravity error")
775
+ : theme.fg("success", "✓ AskAntigravity");
776
+
777
+ const rTags: string[] = [];
778
+ if (d?.resolvedModel || d?.model) rTags.push(`model=${d?.resolvedModel ?? d?.model}`);
779
+ if (d?.thinking) rTags.push(`thinking=${d.thinking}`);
780
+ if (d?.mode && d.mode !== "accept-edits") rTags.push(`mode=${d.mode}`);
781
+ if (d?.includeContext) rTags.push("context=full");
782
+ if (rTags.length) text += ` ${theme.fg("accent", `[${rTags.join(", ")}]`)}`;
783
+ if (d?.durationMs) text += ` ${theme.fg("dim", `${(d.durationMs / 1000).toFixed(1)}s`)}`;
784
+
785
+ if (expanded) {
786
+ if (body) text += `\n${theme.fg("toolOutput", body)}`;
787
+ } else {
788
+ const truncated = body.length > PREVIEW_MAX_CHARS ? body.slice(0, PREVIEW_MAX_CHARS) : body;
789
+ const lines = truncated.split("\n").slice(0, PREVIEW_MAX_LINES);
790
+ if (lines.length) text += `\n${theme.fg("toolOutput", lines.join("\n"))}`;
791
+ if (body.length > PREVIEW_MAX_CHARS || body.split("\n").length > PREVIEW_MAX_LINES) {
792
+ text += `\n${theme.fg("dim", `… (${context.keyHint("app.tools.expand", "to expand")})`)}`;
793
+ }
794
+ }
795
+ return new Text(text, 0, 0);
796
+ },
797
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
798
+ // Circular-delegation guard: refuse if already running through the
799
+ // antigravity provider.
800
+ if (ctx.model?.provider === "antigravity" || ctx.model?.provider === "agy") {
801
+ return {
802
+ content: [
803
+ {
804
+ type: "text",
805
+ text: "Error: AskAntigravity cannot be used when the active provider is already antigravity - you're already running through it.",
806
+ },
807
+ ],
808
+ details: emptyDetails(),
809
+ };
810
+ }
811
+
812
+ const config = loadConfig();
813
+ // readOnly refusal (fail-closed): the kill switch covers this tool too.
814
+ // It must not be bypassable with an explicit mode param: the CLI has no
815
+ // review-only enforcement (upstream google-antigravity/antigravity-cli
816
+ // #1181), so a plan-labeled run here is not read-only.
817
+ if (config.readOnly) {
818
+ return {
819
+ content: [
820
+ {
821
+ type: "text",
822
+ text: 'readOnly is on: AskAntigravity is refused (fail-closed; the agy CLI has no review-only enforcement, google-antigravity/antigravity-cli#1181). Run /agy readonly off to use this tool.',
823
+ },
824
+ ],
825
+ details: emptyDetails(),
826
+ };
827
+ }
828
+ const requestedModel = (params.model as string | undefined) ?? config.defaultModel;
829
+ if (typeof params.model === "string" && params.model.trim().startsWith("-")) {
830
+ return {
831
+ content: [
832
+ {
833
+ type: "text",
834
+ text: `model value "${params.model}" starts with "-" - not a valid model id.`,
835
+ },
836
+ ],
837
+ details: emptyDetails(requestedModel),
838
+ };
839
+ }
840
+ if (
841
+ typeof params.thinking === "string" &&
842
+ typeof params.effort === "string" &&
843
+ params.thinking !== params.effort
844
+ ) {
845
+ return {
846
+ content: [
847
+ {
848
+ type: "text",
849
+ text: "thinking and effort are synonyms for the same knob - pass one, not both with different values.",
850
+ },
851
+ ],
852
+ details: emptyDetails(requestedModel),
853
+ };
854
+ }
855
+ const thinkingArg = (params.thinking as string | undefined) ?? (params.effort as string | undefined);
856
+ const preferredTier = thinkingArg
857
+ ? toAgyEffort(thinkingArg as ThinkingLevel, AGY_EFFORT_ORDER)
858
+ : undefined;
859
+ const resolved =
860
+ resolveAgyModel(requestedModel, entries, config.defaultThinking, preferredTier) ?? {
861
+ model: requestedModel,
862
+ };
863
+
864
+ const start = Date.now();
865
+ const cwd = params.cwd || ctx.cwd || process.cwd();
866
+ try {
867
+ const stat = fs.statSync(cwd);
868
+ if (!stat.isDirectory()) {
869
+ return {
870
+ content: [{ type: "text", text: `cwd is not a directory: ${cwd}` }],
871
+ details: emptyDetails(requestedModel, resolved.model),
872
+ };
873
+ }
874
+ } catch {
875
+ return {
876
+ content: [{ type: "text", text: `cwd does not exist: ${cwd}` }],
877
+ details: emptyDetails(requestedModel, resolved.model),
878
+ };
879
+ }
880
+
881
+ const timeoutMin = params.timeoutMinutes ?? DEFAULT_TIMEOUT_MIN;
882
+ if (!(timeoutMin > 0 && Number.isFinite(timeoutMin) && timeoutMin <= MAX_TIMEOUT_MINUTES)) {
883
+ // timeoutMinutes: 0 would arm runProcess's watchdog with a 0ms
884
+ // timeout (Node clamps to 1ms) and kill the peer instantly.
885
+ return {
886
+ content: [{ type: "text", text: `timeoutMinutes must be a positive number of minutes up to ${MAX_TIMEOUT_MINUTES} (for example 0.5 for 30 seconds).` }],
887
+ details: emptyDetails(requestedModel, resolved.model),
888
+ };
889
+ }
890
+
891
+ const rawConvId = params.conversationId;
892
+ const isContinuation =
893
+ typeof rawConvId === "string" && rawConvId.length > 0 && CONV_ID_RE.test(rawConvId);
894
+ const snapshot = isContinuation ? null : snapshotConversations(CONVERSATIONS_DIR);
895
+
896
+ const mode: AgyMode =
897
+ (params.mode as AgyMode | undefined) ?? (config.mode === "plan" ? "plan" : "accept-edits");
898
+ // Plan runs stage a restricted reviewer agent: its tools list has NO
899
+ // file-editing tool, a toolset-level damper on edits (the prompt
900
+ // guard alone was observed failing once - a sub-agent still edited
901
+ // files; the CLI itself does not enforce review-only, upstream
902
+ // #1181).
903
+ // Staging failure degrades to the legacy fallback: no agent, no skip
904
+ // flag, the stricter command-forbidding guard.
905
+ let reviewerAgent: { name: string; dir: string } | null = null;
906
+ if (mode === "plan") {
907
+ try {
908
+ reviewerAgent = stageReviewerAgent(askAgentsRoot());
909
+ } catch {
910
+ reviewerAgent = null;
911
+ }
912
+ }
913
+ const useDigest: boolean =
914
+ typeof params.digest === "boolean" ? params.digest : mode === "plan";
915
+ // Budget notice into the prompt BEFORE buildFinalPrompt: the plan-mode
916
+ // guard banners must stay the final text (last-read recency), so the
917
+ // notice can't go after them. The builder itself stays notice-free so
918
+ // callers can't double-wrap.
919
+ const budget = buildTimeBudgetNotice(timeoutMin * 60_000);
920
+ const finalPrompt: string = buildFinalPrompt(
921
+ budget ? `${params.prompt}\n\n${budget}` : params.prompt,
922
+ mode,
923
+ useDigest,
924
+ reviewerAgent !== null,
925
+ );
926
+
927
+ // Opt-in full-context export (isolated stays the default).
928
+ let contextFile: string | null = null;
929
+ if (params.includeContext) {
930
+ try {
931
+ const { messages } = buildSessionContext(ctx.sessionManager.getBranch());
932
+ if (messages.length) {
933
+ const md = renderAgentMessagesMarkdown(messages);
934
+ const ctxDir = askContextDir();
935
+ fs.mkdirSync(ctxDir, { recursive: true });
936
+ contextFile = path.join(
937
+ ctxDir,
938
+ `.ask-context-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.md`,
939
+ );
940
+ fs.writeFileSync(contextFile, md, { mode: 0o600 });
941
+ }
942
+ } catch {
943
+ contextFile = null;
944
+ }
945
+ }
946
+ const effectivePrompt = contextFile
947
+ ? `The full pi conversation context (as markdown) is at: ${contextFile}\nRead that file first for context, then do the task below.\n\n---\n\n${finalPrompt}`
948
+ : finalPrompt;
949
+
950
+ log?.(
951
+ "ask-start",
952
+ { model: resolved.model, thinking: resolved.effort ?? config.defaultThinking, mode, digest: useDigest, continue: isContinuation, timeoutMin, background: false },
953
+ "info",
954
+ );
955
+ // Build argv via the shared peer adapter (see buildAgyArgs there for
956
+ // the flag-order contract and the fail-closed plan-run rules). The
957
+ // bridge's permissions gate is truthy (`!== false`), so an unset
958
+ // config counts as enabled - same knob as the provider.
959
+ const args = buildAgyArgs({
960
+ cwd,
961
+ resolved,
962
+ mode,
963
+ reviewerAgentName: reviewerAgent?.name ?? null,
964
+ skipPermissions: config.skipPermissions !== false,
965
+ conversationId: isContinuation ? (rawConvId as string) : null,
966
+ timeoutMinutes: timeoutMin,
967
+ addDirs: contextFile ? [askContextDir()] : [],
968
+ extraArgs: extraArgs(),
969
+ prompt: effectivePrompt,
970
+ });
971
+
972
+ const details: AgyDetails = {
973
+ model: requestedModel,
974
+ resolvedModel: resolved.model,
975
+ thinking: resolved.effort ?? config.defaultThinking,
976
+ mode,
977
+ digest: useDigest,
978
+ conversationId: isContinuation ? (rawConvId as string) : null,
979
+ includeContext: contextFile !== null,
980
+ exitCode: 0,
981
+ aborted: false,
982
+ timedOut: false,
983
+ durationMs: 0,
984
+ stderr: "",
985
+ };
986
+
987
+ const binary = process.env.AGY_BIN || "agy";
988
+
989
+ const cleanupStaging = () => {
990
+ if (contextFile) {
991
+ try {
992
+ fs.unlinkSync(contextFile);
993
+ } catch {}
994
+ }
995
+ if (reviewerAgent) {
996
+ try {
997
+ fs.rmSync(reviewerAgent.dir, { recursive: true, force: true });
998
+ } catch {}
999
+ }
1000
+ };
1001
+
1002
+ // Background: hand the run to the registry and return at once. The
1003
+ // result travels back through sendMessage (wake), not this call.
1004
+ if (params.background) {
1005
+ if (ctx.mode === "print" || ctx.mode === "json") {
1006
+ cleanupStaging();
1007
+ return {
1008
+ content: [
1009
+ {
1010
+ type: "text",
1011
+ text: "background is not available in print/json mode: the process exits before the result message can arrive. Call again without background.",
1012
+ },
1013
+ ],
1014
+ details: { ...details, refused: true },
1015
+ };
1016
+ }
1017
+ return startBackgroundRun({
1018
+ summary: params.prompt,
1019
+ binary,
1020
+ args,
1021
+ workdir: cwd,
1022
+ timeoutMin,
1023
+ startAt: start,
1024
+ details,
1025
+ contextFile,
1026
+ reviewerAgent,
1027
+ modelLabel: resolved.model ?? requestedModel,
1028
+ isContinuation,
1029
+ snapshot,
1030
+ conversationId: isContinuation ? (rawConvId as string) : undefined,
1031
+ });
1032
+ }
1033
+
1034
+ // One run per conversationId at a time, blocking included: a blocking
1035
+ // resume and a background resume of the same conversation would
1036
+ // interleave turns inside agy's session state. Declared out here so
1037
+ // the finally can see it; set only when THIS call takes the lock.
1038
+ let lockAcquired = false;
1039
+ try {
1040
+ if (isContinuation && busyHandles.has(rawConvId as string)) {
1041
+ cleanupStaging();
1042
+ return {
1043
+ content: [
1044
+ {
1045
+ type: "text",
1046
+ text: `conversation ${rawConvId} already has a run in flight. Wait for its result; if it is a background run, /agy-stop can stop it.`,
1047
+ },
1048
+ ],
1049
+ details: emptyDetails(requestedModel, resolved.model),
1050
+ };
1051
+ }
1052
+ lockAcquired = isContinuation;
1053
+ if (lockAcquired) busyHandles.add(rawConvId as string);
1054
+
1055
+ const outcome = await runAgyProcess({
1056
+ binary,
1057
+ args,
1058
+ cwd,
1059
+ timeoutMin,
1060
+ startAt: start,
1061
+ details,
1062
+ isContinuation,
1063
+ snapshot,
1064
+ background: false,
1065
+ signal,
1066
+ onPartial: onUpdate
1067
+ ? (text) => {
1068
+ onUpdate({
1069
+ content: [{ type: "text", text }],
1070
+ details: { ...details, durationMs: Date.now() - start },
1071
+ });
1072
+ }
1073
+ : undefined,
1074
+ log,
1075
+ });
1076
+
1077
+ const finalText = shapeFinalText(details, outcome, timeoutMin);
1078
+
1079
+ if (outcome.aborted || outcome.timedOut || outcome.exitCode !== 0) {
1080
+ return { content: [{ type: "text", text: finalText }], details };
1081
+ }
1082
+
1083
+ // Exit 0 with no output keeps its dedicated failure result
1084
+ // (headless auto-deny); see shapeFinalText for the note.
1085
+ if (!outcome.answerText) {
1086
+ return { content: [{ type: "text", text: finalText }], details };
1087
+ }
1088
+
1089
+ // Clear the last partial status line (claude-bridge idiom) so the
1090
+ // running-tail preview doesn't linger under the final answer.
1091
+ onUpdate?.({
1092
+ content: [{ type: "text", text: "" }],
1093
+ details: { ...details },
1094
+ });
1095
+
1096
+ return {
1097
+ content: [{ type: "text", text: finalText }],
1098
+ details,
1099
+ };
1100
+ } catch (err) {
1101
+ details.durationMs = Date.now() - start;
1102
+ const msg = err instanceof Error ? err.message : String(err);
1103
+ log?.("ask-fail", { error: msg, durationMs: details.durationMs }, "error");
1104
+ return { content: [{ type: "text", text: `failed to run agy: ${msg}` }], details };
1105
+ } finally {
1106
+ if (lockAcquired) busyHandles.delete(rawConvId as string);
1107
+ cleanupStaging();
1108
+ }
1109
+ },
1110
+ });
1111
+ }
1112
+
1113
+ // --- Full-context export (opt-in includeContext) --------------------------
1114
+ // NOTE: duplicated per pi-ask-* / bridge package (each is self-contained).
1115
+ // Duck-typed over role/content to tolerate AgentMessage's union + custom types.
1116
+
1117
+ // Tool-call inputs and tool-result bodies are clamped so the exported
1118
+ // transcript stays reviewable; the agent can re-read any source file by path.
1119
+ // User/assistant prose is kept in full (that IS the conversation).
1120
+ const CONTEXT_BLOCK_MAX_CHARS = 2000;
1121
+
1122
+ function clampBlock(text: unknown, limit = CONTEXT_BLOCK_MAX_CHARS): string {
1123
+ const t = String(text ?? "");
1124
+ return t.length > limit ? `${t.slice(0, limit)}\n…[truncated, ${t.length - limit} more chars]` : t;
1125
+ }
1126
+
1127
+ /** Render resolved pi AgentMessages to a readable markdown transcript.
1128
+ * Pure: no IO. Caller writes the returned string to a temp file. */
1129
+ function renderAgentMessagesMarkdown(messages: readonly unknown[]): string {
1130
+ const lines: string[] = [
1131
+ "# Pi conversation context",
1132
+ "",
1133
+ `_Exported for full-context delegation. ${messages.length} message(s)._`,
1134
+ "",
1135
+ ];
1136
+ for (const raw of messages) {
1137
+ const m = raw as { role?: string; content?: unknown };
1138
+ const role = m.role ?? "message";
1139
+ const content = m.content;
1140
+ if (role === "assistant") {
1141
+ const blocks = (Array.isArray(content) ? content : []) as ReadonlyArray<{
1142
+ type: string;
1143
+ text?: string;
1144
+ name?: string;
1145
+ input?: unknown;
1146
+ }>;
1147
+ const text = blocks
1148
+ .filter((b) => b.type === "text")
1149
+ .map((b) => b.text ?? "")
1150
+ .join("\n");
1151
+ if (text.trim()) lines.push("## Assistant", "", text, "");
1152
+ for (const b of blocks) {
1153
+ if (b.type === "toolCall" || b.type === "tool_use") {
1154
+ const input = clampBlock(
1155
+ typeof b.input === "string" ? b.input : JSON.stringify(b.input ?? ""),
1156
+ 500,
1157
+ );
1158
+ lines.push(`> tool call: ${b.name ?? "(unknown)"}(${input})`, "");
1159
+ }
1160
+ }
1161
+ } else if (role === "toolResult" || role === "tool_result" || role === "tool") {
1162
+ const text = contentText(content as any);
1163
+ if (text.trim()) lines.push("## Tool result", "", clampBlock(text), "");
1164
+ } else {
1165
+ const text = contentText(content as any);
1166
+ if (text.trim()) lines.push(`## ${role}`, "", clampBlock(text), "");
1167
+ }
1168
+ }
1169
+ return lines.join("\n");
1170
+ }
1171
+
1172
+ /** Centralized scratch dir for full-context exports (see src/config.ts
1173
+ * extensionsDataDir). */
1174
+ function askContextDir(): string {
1175
+ return extensionsDataDir();
1176
+ }
1177
+
1178
+ interface AgyDetails {
1179
+ model: string | null;
1180
+ resolvedModel: string | null;
1181
+ thinking: ThinkingTier | null;
1182
+ mode: AgyMode;
1183
+ digest: boolean;
1184
+ conversationId: string | null;
1185
+ includeContext: boolean;
1186
+ exitCode: number;
1187
+ aborted: boolean;
1188
+ timedOut: boolean;
1189
+ // Exit 0 with no answer on stdout (the empty-output failure branch).
1190
+ // renderResult flips to the error glyph on it.
1191
+ empty?: boolean;
1192
+ // The call was refused before any spawn (validation, lock, cap, kill
1193
+ // switch). renderResult flips to the error glyph on it.
1194
+ refused?: boolean;
1195
+ durationMs: number;
1196
+ stderr: string;
1197
+ }
1198
+
1199
+ function emptyDetails(
1200
+ model: string | null = null,
1201
+ resolvedModel: string | null = null,
1202
+ thinking: ThinkingTier | null = null,
1203
+ includeContext: boolean = false,
1204
+ ): AgyDetails {
1205
+ return {
1206
+ model,
1207
+ resolvedModel,
1208
+ thinking,
1209
+ mode: "accept-edits",
1210
+ digest: false,
1211
+ includeContext,
1212
+ conversationId: null,
1213
+ exitCode: 0,
1214
+ aborted: false,
1215
+ timedOut: false,
1216
+ durationMs: 0,
1217
+ stderr: "",
1218
+ // Every emptyDetails caller is a refusal path.
1219
+ refused: true,
1220
+ };
1221
+ }