@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,404 @@
1
+ // Discover models from `agy models` and project them into pi's Model shape so
2
+ // they appear in the /model picker as antigravity/<slug>.
3
+ //
4
+ // agy prints TWO columns per line: "<slug> <display label>". --model takes
5
+ // ONLY the slug (col 1); the label is display-only. Verified live 2026-10:
6
+ // gemini-3.8-flash-high Gemini 3.8 Flash (High)
7
+ // gemini-3.8-flash-medium Gemini 3.8 Flash (Medium) (+ -low)
8
+ // gemini-3.1-pro-high Gemini 3.1 Pro (High) (Pro has NO medium)
9
+ // claude-sonnet-5-5-high Claude Sonnet 5.5 (High) (+ -medium, -low)
10
+ //
11
+ // Gemini AND Claude models are collapsed to a BASE slug (gemini-3.8-flash,
12
+ // claude-sonnet-5-5) and exposed with a thinking-effort toggle whose levels
13
+ // match exactly the tiers agy offers that base (verified: Pro rejects medium;
14
+ // Claude 5.5 accepts low/medium/high). The picked level is sent as agy
15
+ // --effort; a bare base slug is INVALID on its own (agy: "requires --effort"),
16
+ // so effort is always passed. Only unverified families keep agy's exact slug
17
+ // with no toggle, so an unknown future family degrades safely; the retired
18
+ // gpt-oss family is dropped outright (HIDDEN_FAMILY_RE). Google's Antigravity
19
+ // subscription bills all of these through agy.
20
+
21
+ import { spawn } from "node:child_process";
22
+ import fs from "node:fs";
23
+ import path from "node:path";
24
+ import type { Api, Model, ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
25
+
26
+ import { bridgeDir } from "./config.js";
27
+
28
+ const DISCOVERY_TIMEOUT_MS = 8_000;
29
+
30
+ /** Stdout ceiling for `agy models`. Real output is a few KB of ASCII slugs;
31
+ * anything past 1 MiB is a runaway process. Fail closed to "" so the
32
+ * fallback catalog engages instead of letting the buffer grow without
33
+ * limit. The check counts decoded string length (UTF-16 code units), not
34
+ * raw bytes — a deliberate proxy, since the margin between a few KB of
35
+ * real output and 1 MiB dwarfs any encoding difference. */
36
+ export const MODELS_OUTPUT_CAP_BYTES = 1024 * 1024;
37
+
38
+ /** Reasoning-effort tiers agy accepts via --effort. */
39
+ export type AgyEffort = "low" | "medium" | "high";
40
+
41
+ /** low < medium < high, for sorting/clamping. */
42
+ const EFFORT_RANK: Record<AgyEffort, number> = { low: 0, medium: 1, high: 2 };
43
+
44
+ /** pi thinking-effort order mirrors agy's, for clamping. */
45
+ export const AGY_EFFORT_ORDER: readonly AgyEffort[] = ["low", "medium", "high"];
46
+
47
+ /** Map pi's thinking level onto one of the tiers `efforts` the base actually
48
+ * supports, clamping to the nearest available. agy rejects an effort tier a
49
+ * base doesn't list (e.g. medium on Pro), so we never emit one. Shared by the
50
+ * provider turns AND the AskAntigravity delegation tool (thinking/effort
51
+ * params): one vocabulary, one clamp. When pi sends no level we fall to the
52
+ * first available tier. */
53
+ export function toAgyEffort(
54
+ reasoning: ThinkingLevel | undefined,
55
+ efforts: readonly AgyEffort[],
56
+ ): AgyEffort {
57
+ let candidate: AgyEffort;
58
+ switch (reasoning) {
59
+ case "minimal":
60
+ case "low":
61
+ candidate = "low";
62
+ break;
63
+ case "medium":
64
+ candidate = "medium";
65
+ break;
66
+ case "high":
67
+ case "xhigh":
68
+ case "max":
69
+ candidate = "high";
70
+ break;
71
+ default:
72
+ candidate = efforts[0] ?? "low";
73
+ }
74
+ if (efforts.includes(candidate)) return candidate;
75
+ const i = AGY_EFFORT_ORDER.indexOf(candidate);
76
+ for (let j = i; j < AGY_EFFORT_ORDER.length; j++) {
77
+ if (efforts.includes(AGY_EFFORT_ORDER[j])) return AGY_EFFORT_ORDER[j];
78
+ }
79
+ for (let j = i - 1; j >= 0; j--) {
80
+ if (efforts.includes(AGY_EFFORT_ORDER[j])) return AGY_EFFORT_ORDER[j];
81
+ }
82
+ return efforts[0] ?? "low";
83
+ }
84
+
85
+ /** Split an agy slug into (base, tier). tier is null when the slug has no
86
+ * -high/-medium/-low suffix - a shape only unverified families should
87
+ * produce now, and those stay whole. Every Claude slug carries a tier
88
+ * suffix and collapses to its base. */
89
+ const TIER_RE = /^(.+)-(high|medium|low)$/;
90
+
91
+ /** agy emits clean slug ids (gemini-3.6-flash-high). Validate col1 of each
92
+ * line so a banner / auth / "Fetching models…" line can't register as a
93
+ * model, and a leading-dash token (e.g. "-high") can't reach agy's flag
94
+ * parser as --model. First char must be alphanumeric; the slug must contain
95
+ * at least one hyphen (every real agy slug does: family-version-name), which
96
+ * also drops a prose banner word split out of col1 ("Available"). */
97
+ const MODEL_LINE_RE = /^[A-Za-z0-9][A-Za-z0-9._]*-[A-Za-z0-9._-]*$/;
98
+
99
+ /** Model families VERIFIED to accept base-slug + --effort. Only these collapse
100
+ * to a base slug with a thinking toggle. Any other family stays as agy's exact
101
+ * qualified slug (always valid on its own), so an unknown or fixed-thinking
102
+ * family degrades safely instead of forcing an unsupported --effort. Add a
103
+ * family here only after confirming base+--effort is accepted for it.
104
+ * Claude 5.5 verified live 2026-10: base+--effort accepted; a bare base is
105
+ * rejected ("requires --effort"). */
106
+ const EFFORT_CAPABLE_FAMILIES: readonly RegExp[] = [/^gemini-/, /^claude-/];
107
+
108
+ /** Families dropped outright, even while `agy models` still lists them: the
109
+ * fixed-thinking single slug loses to the cheaper effort-tiered options and
110
+ * its removal upstream is already announced, so we stop offering it now. */
111
+ const HIDDEN_FAMILY_RE = /^gpt-oss-/;
112
+
113
+ export interface AgyModelEntry {
114
+ /** Exact agy --model string to pass: a base slug ("gemini-3.8-flash") when
115
+ * effort-driven, else agy's full qualified slug (unverified family). */
116
+ full: string;
117
+ /** pi model id, e.g. "gemini-3-8-flash". */
118
+ id: string;
119
+ /** Present iff this is an effort-driven base slug. Lists the tiers agy
120
+ * accepts for it; pi's thinking toggle picks among them and we always pass
121
+ * --effort. Absent => fixed model, never pass --effort. */
122
+ efforts?: AgyEffort[];
123
+ }
124
+
125
+ /** Spawn a read-only agy listing subcommand and return its raw stdout text.
126
+ * Returns "" on any failure (non-zero exit, spawn error, watchdog timeout,
127
+ * or output cap). Bounded by timeoutMs (default DISCOVERY_TIMEOUT_MS) so a
128
+ * hung agy (auth prompt, network stall) can't block the caller, and by
129
+ * capBytes (default MODELS_OUTPUT_CAP_BYTES) so a runaway agy can't grow
130
+ * the buffer without limit. Shared by the model catalog (spawned ONCE per
131
+ * load, provider + tool catalog), the agent roster, and the quota fetch
132
+ * (which passes its own 30s budget: /usage answers in ~10s live). */
133
+ export async function spawnAgyRaw(
134
+ binary: string,
135
+ args: string[],
136
+ timeoutMs: number = DISCOVERY_TIMEOUT_MS,
137
+ capBytes: number = MODELS_OUTPUT_CAP_BYTES,
138
+ ): Promise<string> {
139
+ try {
140
+ return await new Promise<string>((resolve, reject) => {
141
+ const proc = spawn(binary, args, {
142
+ stdio: ["ignore", "pipe", "ignore"],
143
+ shell: false,
144
+ });
145
+ proc.stdout?.setEncoding("utf8");
146
+ let out = "";
147
+ let done = false;
148
+ let capped = false;
149
+ const finish = (v: string) => {
150
+ if (done) return;
151
+ done = true;
152
+ clearTimeout(watchdog);
153
+ resolve(v);
154
+ };
155
+ proc.stdout?.on("data", (d: string) => {
156
+ if (capped) return;
157
+ if (out.length + d.length > capBytes) {
158
+ capped = true;
159
+ try {
160
+ proc.kill("SIGKILL");
161
+ } catch {
162
+ /* already gone */
163
+ }
164
+ finish("");
165
+ return;
166
+ }
167
+ out += d;
168
+ });
169
+ proc.on("error", (err) => {
170
+ clearTimeout(watchdog);
171
+ reject(err);
172
+ });
173
+ proc.on("close", (code) => finish(code === 0 ? out : ""));
174
+ const watchdog = setTimeout(() => {
175
+ try {
176
+ proc.kill("SIGKILL");
177
+ } catch {
178
+ /* already gone */
179
+ }
180
+ finish("");
181
+ }, timeoutMs);
182
+ });
183
+ } catch {
184
+ return "";
185
+ }
186
+ }
187
+
188
+ /** Spawn `agy models`: the model catalog listing. */
189
+ export async function spawnAgyModelsRaw(binary: string): Promise<string> {
190
+ return spawnAgyRaw(binary, ["models"]);
191
+ }
192
+
193
+ // --- catalog cache ----------------------------------------------------------
194
+ //
195
+ // `agy models` can take seconds (OAuth refresh, cold start) and its output
196
+ // rarely changes. We persist it to <agentDir>/antigravity-bridge/models-
197
+ // cache.json with a short TTL so reloads serve instantly and only re-spawn in
198
+ // the background when stale. Only successful (non-empty) output is cached, so
199
+ // a broken agy is never sticky.
200
+
201
+ export const MODELS_CACHE_TTL_MS = 5 * 60_000;
202
+
203
+ function modelsCachePath(): string {
204
+ return path.join(bridgeDir(), "models-cache.json");
205
+ }
206
+
207
+ interface ModelsCache {
208
+ raw: string;
209
+ savedAt: number;
210
+ }
211
+
212
+ /** Read and validate the models cache. Returns null when missing or corrupt. */
213
+ function readModelsCache(cachePath: string = modelsCachePath()): ModelsCache | null {
214
+ try {
215
+ const parsed = JSON.parse(fs.readFileSync(cachePath, "utf8")) as unknown;
216
+ if (
217
+ parsed &&
218
+ typeof parsed === "object" &&
219
+ !Array.isArray(parsed) &&
220
+ typeof (parsed as ModelsCache).raw === "string" &&
221
+ typeof (parsed as ModelsCache).savedAt === "number"
222
+ ) {
223
+ return parsed as ModelsCache;
224
+ }
225
+ } catch {
226
+ /* missing or corrupt: treat as no cache */
227
+ }
228
+ return null;
229
+ }
230
+
231
+ /** Atomically persist the raw catalog text (temp + rename, mode 0o600).
232
+ * Best-effort: a write failure just means the next load re-spawns. */
233
+ function writeModelsCache(raw: string, cachePath: string = modelsCachePath()): void {
234
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
235
+ const tmp = `${cachePath}.${process.pid}.tmp`;
236
+ try {
237
+ fs.writeFileSync(tmp, JSON.stringify({ raw, savedAt: Date.now() }, null, 2) + "\n", {
238
+ mode: 0o600,
239
+ });
240
+ fs.renameSync(tmp, cachePath);
241
+ } catch {
242
+ try {
243
+ fs.unlinkSync(tmp);
244
+ } catch {
245
+ /* nothing to clean */
246
+ }
247
+ }
248
+ }
249
+
250
+ /** Fire-and-forget refresh of the models cache. Called on a stale-cache load so
251
+ * the next load sees fresh data without this one having to wait on agy. */
252
+ export function refreshModelsInBackground(
253
+ binary: string,
254
+ cachePath: string = modelsCachePath(),
255
+ ): void {
256
+ void spawnAgyModelsRaw(binary)
257
+ .then((raw) => {
258
+ if (raw) writeModelsCache(raw, cachePath);
259
+ })
260
+ .catch(() => {
261
+ /* best effort: leave the stale cache in place */
262
+ });
263
+ }
264
+
265
+ /** Load the raw `agy models` text for catalog derivation, optimized for load
266
+ * time:
267
+ * - Fresh cache (< MODELS_CACHE_TTL_MS): return it, no spawn.
268
+ * - Stale cache (>= TTL): return it instantly, refresh in the background.
269
+ * - No cache: spawn once (blocks), persist. First-ever load only.
270
+ *
271
+ * pi registers providers with a static model list, so a background refresh only
272
+ * updates the cache for the NEXT load; the current session keeps whatever this
273
+ * returned. The provider falls back to FALLBACK_MODELS when the raw yields no
274
+ * Gemini entries (agy missing/auth-failed). */
275
+ export async function loadModelCatalogRaw(
276
+ binary: string,
277
+ cachePath: string = modelsCachePath(),
278
+ ): Promise<string> {
279
+ const cache = readModelsCache(cachePath);
280
+ if (cache) {
281
+ if (Date.now() - cache.savedAt < MODELS_CACHE_TTL_MS) return cache.raw;
282
+ refreshModelsInBackground(binary, cachePath);
283
+ return cache.raw;
284
+ }
285
+ // No cache: populate it. Blocks once; later loads hit the cache above.
286
+ const raw = await spawnAgyModelsRaw(binary);
287
+ if (raw) writeModelsCache(raw, cachePath);
288
+ return raw;
289
+ }
290
+
291
+ /** Parse raw `agy models` text into the provider's model entries.
292
+ *
293
+ * Effort-driven bases (>= 2 tier variants in the catalog, verified
294
+ * effort-capable family) collapse to one BASE-slug entry carrying the tiers
295
+ * they accept. Models with 0 or 1 tier variants keep agy's exact qualified
296
+ * slug: without a verified effort-capable family match, --effort is never
297
+ * risked. Hidden families are dropped outright. Insertion order of
298
+ * first-seen bases is preserved. */
299
+ export function entriesFromRaw(raw: string): AgyModelEntry[] {
300
+ // agy prints TWO columns: "<slug> <display label>". --model takes only the
301
+ // slug, so split col1 and validate THAT; the label is display-only. A
302
+ // bare-slug line (no whitespace) splits to itself, so this also tolerates
303
+ // the legacy one-column shape.
304
+ const groups = new Map<string, { lines: string[]; tiers: Set<AgyEffort> }>();
305
+ for (const line of raw.split("\n")) {
306
+ const slug = line.trim().split(/\s+/)[0] ?? "";
307
+ if (!slug || !MODEL_LINE_RE.test(slug)) continue;
308
+ if (HIDDEN_FAMILY_RE.test(slug)) continue;
309
+ const m = TIER_RE.exec(slug);
310
+ const base = m ? (m[1] as string) : slug;
311
+ const tier = m ? (m[2] as AgyEffort) : null;
312
+ let g = groups.get(base);
313
+ if (!g) {
314
+ g = { lines: [], tiers: new Set<AgyEffort>() };
315
+ groups.set(base, g);
316
+ }
317
+ g.lines.push(slug);
318
+ if (tier) g.tiers.add(tier);
319
+ }
320
+ const entries: AgyModelEntry[] = [];
321
+ for (const [base, g] of groups) {
322
+ const efforts = [...g.tiers].sort((a, b) => EFFORT_RANK[a] - EFFORT_RANK[b]);
323
+ if (efforts.length >= 2 && EFFORT_CAPABLE_FAMILIES.some((re) => re.test(base))) {
324
+ entries.push({ full: base, id: slugify(base), efforts });
325
+ } else {
326
+ for (const line of g.lines) entries.push({ full: line, id: slugify(line) });
327
+ }
328
+ }
329
+ return entries.filter((e) => e.id.length > 0);
330
+ }
331
+
332
+ /** Run `agy models`, return parsed model entries. Returns [] on any failure
333
+ * (non-fatal - the provider falls back to a hardcoded set). */
334
+ export async function discoverAgyModels(binary: string): Promise<AgyModelEntry[]> {
335
+ return entriesFromRaw(await spawnAgyModelsRaw(binary));
336
+ }
337
+
338
+ /** "Gemini 3.6 Flash (Medium)" -> "gemini-3-6-flash-medium".
339
+ * Lowercase, non-alphanumerics -> "-", collapsed, trimmed. */
340
+ export function slugify(full: string): string {
341
+ return full
342
+ .toLowerCase()
343
+ .replace(/[^a-z0-9]+/g, "-")
344
+ .replace(/^-+|-+$/g, "");
345
+ }
346
+
347
+ /** Build the thinkingLevelMap for an effort-driven base: hide "off" and
348
+ * "minimal" always (agy has no no-thinking mode; a base REQUIRES an effort),
349
+ * and hide any of low/medium/high the base doesn't offer (e.g. Pro has no
350
+ * medium). pi's getSupportedThinkingLevels treats a null value as hidden, so
351
+ * the toggle then shows exactly agy's slider stops. */
352
+ function thinkingLevelMapFor(efforts: readonly AgyEffort[]): ThinkingLevelMap {
353
+ const map: Record<string, string | null> = { off: null, minimal: null };
354
+ for (const level of ["low", "medium", "high"] as const) {
355
+ if (!efforts.includes(level)) map[level] = null;
356
+ }
357
+ return map as ThinkingLevelMap;
358
+ }
359
+
360
+ /** Project an agy entry to pi's Model shape. `input` advertises accepted
361
+ * inputs; both engines accept images (ACP native content blocks,
362
+ * stream-json staged files), so callers pass ["text", "image"] uniformly. */
363
+ export function toPiModel(entry: AgyModelEntry, input: Array<"text" | "image"> = ["text"]): Model<Api> {
364
+ const effortDriven = !!entry.efforts && entry.efforts.length > 0;
365
+ return {
366
+ id: entry.id,
367
+ name: entry.full,
368
+ api: "agy-bridge" as Api,
369
+ provider: "antigravity",
370
+ // baseUrl/apiKey are not used (streamSimple intercepts everything), but
371
+ // pi requires non-empty values. The "agy-bridge" api string is a custom
372
+ // sentinel that no built-in provider claims, so it can never collide.
373
+ baseUrl: "agy-bridge://antigravity",
374
+ // reasoning=true only for effort-driven bases => pi shows the toggle.
375
+ // Unverified families get no toggle: --effort support is unknown, so
376
+ // none is ever sent.
377
+ reasoning: effortDriven,
378
+ ...(effortDriven ? { thinkingLevelMap: thinkingLevelMapFor(entry.efforts!) } : {}),
379
+ // Input advertising comes from the caller: both engines deliver
380
+ // user-attached images now.
381
+ input,
382
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
383
+ // Gemini long context. agy doesn't expose the real per-model window in
384
+ // `agy models`; 1M is the documented Gemini ceiling.
385
+ contextWindow: 1_000_000,
386
+ maxTokens: 65_536,
387
+ };
388
+ }
389
+
390
+ /** Fallback catalog used when `agy models` fails at load (binary missing,
391
+ * auth not yet done, network stall). Keeps the picker populated so the user
392
+ * can still select a model and get a clear runtime error instead of an empty
393
+ * list. Update these when agy ships new Gemini versions. */
394
+ export const FALLBACK_MODELS: AgyModelEntry[] = [
395
+ // First entry = offline picker default; keep it aligned with the configured
396
+ // AskAntigravity default (config.ts) so the default stays resolvable when
397
+ // `agy models` fails.
398
+ { full: "gemini-4-hydrogen", id: "gemini-4-hydrogen", efforts: ["low", "medium", "high"] },
399
+ { full: "gemini-3.8-flash", id: "gemini-3-8-flash", efforts: ["low", "medium", "high"] },
400
+ { full: "gemini-3.1-pro", id: "gemini-3-1-pro", efforts: ["low", "high"] },
401
+ { full: "claude-sonnet-5-5", id: "claude-sonnet-5-5", efforts: ["low", "medium", "high"] },
402
+ ];
403
+
404
+
@@ -0,0 +1,104 @@
1
+ // Native re-execution mapping - agy read-only tools whose work pi can redo
2
+ // cheaply and safely with its own builtins. The provider emits these as native
3
+ // pi toolCalls (real builtin name, pi-schema args); pi executes the real
4
+ // builtin, so cards render with pi's own renderers.
5
+ //
6
+ // Mutating tools (commands, edits, writes) and agy-specialty tools are never
7
+ // re-executed - they replay through the display-only `antigravity` wrapper
8
+ // tool.
9
+
10
+ export interface NativeToolCall {
11
+ /** pi builtin tool name (`read`, `ls`, `grep`, `find`). */
12
+ tool: string;
13
+ /** Arguments conforming to the builtin's schema. */
14
+ args: Record<string, unknown>;
15
+ }
16
+
17
+ function str(input: Record<string, unknown>, keys: string[]): string | undefined {
18
+ for (const key of keys) {
19
+ const value = input[key];
20
+ if (typeof value === "string" && value.trim()) return value;
21
+ }
22
+ return undefined;
23
+ }
24
+
25
+ function num(input: Record<string, unknown>, keys: string[]): number | undefined {
26
+ for (const key of keys) {
27
+ const value = input[key];
28
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) return value;
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ function onlyKeys(input: Record<string, unknown>, allowed: readonly string[]): boolean {
34
+ const accepted = new Set(allowed);
35
+ return Object.entries(input).every(
36
+ ([key, value]) => value === undefined || value === null || accepted.has(key),
37
+ );
38
+ }
39
+
40
+ const VIEW_PATH_KEYS = [
41
+ "path",
42
+ "Path",
43
+ "AbsolutePath",
44
+ "absolute_path",
45
+ "TargetFile",
46
+ "target_file",
47
+ "FilePath",
48
+ "file_path",
49
+ ] as const;
50
+ const START_LINE_KEYS = ["StartLine", "start_line", "startLine"] as const;
51
+ const END_LINE_KEYS = ["EndLine", "end_line", "endLine"] as const;
52
+
53
+ /** Map an agy tool step to a native pi toolCall when re-execution is safe.
54
+ * Returns undefined for everything that must stay on the replay wrapper. */
55
+ export function mapAgyToolToNative(
56
+ tool: string,
57
+ args: Record<string, unknown>,
58
+ ): NativeToolCall | undefined {
59
+ switch (tool) {
60
+ case "view_file": {
61
+ if (!onlyKeys(args, [...VIEW_PATH_KEYS, ...START_LINE_KEYS, ...END_LINE_KEYS])) {
62
+ return undefined;
63
+ }
64
+ const path = str(args, [...VIEW_PATH_KEYS]);
65
+ const start = num(args, [...START_LINE_KEYS]);
66
+ const end = num(args, [...END_LINE_KEYS]);
67
+ if (!path || (end !== undefined && start === undefined) || (start && end && end < start)) {
68
+ return undefined;
69
+ }
70
+ return {
71
+ tool: "read",
72
+ args: {
73
+ path,
74
+ ...(start === undefined ? {} : { offset: start }),
75
+ ...(start === undefined || end === undefined ? {} : { limit: end - start + 1 }),
76
+ },
77
+ };
78
+ }
79
+ case "list_dir": {
80
+ const keys = ["path", "Path", "DirectoryPath", "directory", "Directory"];
81
+ if (!onlyKeys(args, keys)) return undefined;
82
+ const path = str(args, keys);
83
+ return path ? { tool: "ls", args: { path } } : undefined;
84
+ }
85
+ case "grep_search": {
86
+ const patternKeys = ["query", "Query", "pattern", "Pattern"];
87
+ const pathKeys = ["search_path", "SearchPath", "path", "Path"];
88
+ if (!onlyKeys(args, [...patternKeys, ...pathKeys])) return undefined;
89
+ const pattern = str(args, patternKeys);
90
+ const path = str(args, pathKeys);
91
+ return pattern ? { tool: "grep", args: path ? { pattern, path } : { pattern } } : undefined;
92
+ }
93
+ case "find_by_name": {
94
+ const patternKeys = ["pattern", "Pattern", "glob", "name"];
95
+ const pathKeys = ["search_directory", "SearchDirectory", "path", "Path", "directory"];
96
+ if (!onlyKeys(args, [...patternKeys, ...pathKeys])) return undefined;
97
+ const pattern = str(args, patternKeys);
98
+ const path = str(args, pathKeys);
99
+ return pattern ? { tool: "find", args: path ? { pattern, path } : { pattern } } : undefined;
100
+ }
101
+ default:
102
+ return undefined;
103
+ }
104
+ }
@@ -0,0 +1,125 @@
1
+ // Parked-turn stall probe (stream-json engine only).
2
+ //
3
+ // The stall guard fails a turn after N minutes of stdout silence. But agy
4
+ // sometimes finishes its answer without streaming it (parked turn): the
5
+ // response only ever lands in the conversation's brain transcript. Before
6
+ // failing, this module reads the transcript tail and looks for a DONE,
7
+ // MODEL-sourced final-response step written DURING the turn. One found, the
8
+ // driver can settle the turn OK with the withheld answer instead of
9
+ // throwing away finished work.
10
+ //
11
+ // Live-verified format (agy 1.2.10, transcript_full.jsonl last line):
12
+ // {"step_index":1,"source":"MODEL","type":"PLANNER_RESPONSE",
13
+ // "status":"DONE","created_at":"2026-09-08T16:11:43Z","content":"..."}
14
+ // A corpus sweep (2026-09-24, 9205 response steps across all local
15
+ // transcripts) shows PLANNER_RESPONSE is the only *RESPONSE type agy
16
+ // writes, so the gate matches it exactly. A deeper sweep during the agy
17
+ // peer review (2026-09-25, 9547 steps) found 96.6% of PLANNER_RESPONSE
18
+ // steps carry tool_calls — they are intermediate plan-and-act steps whose
19
+ // content is status text ("Running test..."), NOT answers. The probe
20
+ // therefore requires the NEWEST step written during the turn to be a
21
+ // clean, tool-free response; any other newer step means the turn was
22
+ // still mid-flight. If a future agy renames the type, the probe degrades
23
+ // to the old stall-fail — the safe direction.
24
+ // The ACP engine writes no transcript under its brain tree (probed
25
+ // 2026-09-24) and reports turn completion itself, so this probe is
26
+ // deliberately stream-json-only.
27
+
28
+ import { open } from "node:fs/promises";
29
+ import { agyConversationDir } from "./agy-paths.js";
30
+
31
+ /** How much of the transcript tail to read. One final step is a few KiB;
32
+ * 512KiB covers it plus slack for big tool-step lines above it. */
33
+ export const PARKED_PROBE_MAX_BYTES = 512 * 1024;
34
+
35
+ /** Clock tolerance for "written during the turn": transcript timestamps are
36
+ * second-precision and may come from a slightly skewed source. */
37
+ const CREATED_AT_TOLERANCE_MS = 2_000;
38
+
39
+ /** Pull the parked answer out of a transcript tail. Scans from the END;
40
+ * the FIRST step written during the turn decides: a clean, tool-free DONE
41
+ * MODEL response yields its content; any other step from the turn (tool
42
+ * output, error, plan step with tool_calls) means no answer landed and
43
+ * the probe returns undefined. Steps older than the turn (clock tolerance
44
+ * 2s) end the scan. Malformed or foreign lines are skipped without
45
+ * deciding. Pure; exported for tests. */
46
+ export function extractParkedAnswer(
47
+ tail: string,
48
+ turnStartedMs: number,
49
+ ): string | undefined {
50
+ const lines = tail.split("\n");
51
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
52
+ const line = lines[i]?.trim();
53
+ if (!line) continue;
54
+ let step: {
55
+ source?: unknown;
56
+ type?: unknown;
57
+ status?: unknown;
58
+ created_at?: unknown;
59
+ content?: unknown;
60
+ tool_calls?: unknown;
61
+ };
62
+ try {
63
+ step = JSON.parse(line) as typeof step;
64
+ } catch {
65
+ continue;
66
+ }
67
+ if (typeof step.created_at !== "string") continue;
68
+ const createdAtMs = Date.parse(step.created_at);
69
+ if (Number.isNaN(createdAtMs)) continue;
70
+ if (createdAtMs < turnStartedMs - CREATED_AT_TOLERANCE_MS) break;
71
+
72
+ // The newest step written during this turn must be a completed MODEL
73
+ // response without tool calls. Intermediate tool steps, errors, or
74
+ // non-terminal responses mean the turn did not finish with a parked answer.
75
+ if (step.source !== "MODEL" || step.status !== "DONE") return undefined;
76
+ if (step.type !== "PLANNER_RESPONSE") return undefined;
77
+ if (Array.isArray(step.tool_calls) && step.tool_calls.length > 0) return undefined;
78
+ if (typeof step.content !== "string" || step.content.length === 0) return undefined;
79
+ return step.content;
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ /** Read at most `maxBytes` from the end of a file. Empty string on any
85
+ * error (missing file, permission, ...) — the caller degrades to the old
86
+ * stall-fail behavior. */
87
+ export async function readTranscriptTail(filePath: string, maxBytes: number): Promise<string> {
88
+ let handle;
89
+ try {
90
+ handle = await open(filePath, "r");
91
+ } catch {
92
+ return "";
93
+ }
94
+ try {
95
+ const { size } = await handle.stat();
96
+ const start = Math.max(0, size - maxBytes);
97
+ const length = size - start;
98
+ const buffer = Buffer.alloc(length);
99
+ let read = 0;
100
+ while (read < length) {
101
+ const { bytesRead } = await handle.read(buffer, read, length - read, start + read);
102
+ if (bytesRead === 0) break;
103
+ read += bytesRead;
104
+ }
105
+ return buffer.subarray(0, read).toString("utf8");
106
+ } catch {
107
+ return "";
108
+ } finally {
109
+ await handle.close().catch(() => {});
110
+ }
111
+ }
112
+
113
+ /** Probe one stream-json conversation's transcript for a parked answer.
114
+ * Undefined whenever nothing usable is found (missing transcript, no DONE
115
+ * step from this turn) — never throws; the stall guard must not fail. */
116
+ export async function parkedTurnAnswer(
117
+ conversationId: string,
118
+ turnStartedMs: number,
119
+ home: string | undefined = undefined,
120
+ ): Promise<string | undefined> {
121
+ const transcript = `${agyConversationDir("stream-json", conversationId, home)}/.system_generated/logs/transcript_full.jsonl`;
122
+ const tail = await readTranscriptTail(transcript, PARKED_PROBE_MAX_BYTES);
123
+ if (tail === "") return undefined;
124
+ return extractParkedAnswer(tail, turnStartedMs);
125
+ }