@herbertgao/pi-extensions 2026.11.18 → 2026.11.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +2 -23
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  64. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
  65. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  66. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
  67. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  68. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  69. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  70. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  71. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  72. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  73. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
  74. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  75. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  76. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
  77. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  78. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
  80. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  82. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  84. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  85. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  86. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  87. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  88. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  89. package/node_modules/pi-commandcode-provider/README.md +3 -2
  90. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  91. package/node_modules/pi-commandcode-provider/package.json +4 -3
  92. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  93. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  94. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  95. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  96. package/package.json +11 -14
  97. package/node_modules/pi-antigravity/README.md +0 -298
  98. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  99. package/node_modules/pi-antigravity/package.json +0 -87
  100. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  101. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  102. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  103. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  104. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  105. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  106. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  107. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  108. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  109. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  110. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  111. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  112. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  113. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  114. package/node_modules/pi-antigravity/src/index.ts +0 -547
  115. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  116. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  117. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  118. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  119. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  120. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  121. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  122. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  123. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  124. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  125. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  126. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  127. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  128. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  129. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  130. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  131. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  132. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  133. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  134. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  135. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  136. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  137. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  138. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  139. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  140. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  141. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  142. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  143. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  144. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  145. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  146. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  147. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  148. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  149. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  150. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  151. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -0,0 +1,160 @@
1
+ // First-run onboarding: the engine picker plus the agy-presence warning.
2
+ //
3
+ // On the first interactive start (no config file yet, no AGY_ENGINE env) pi
4
+ // asks which native agy engine to use: stream-json or `agy acp`. The choice persists via saveConfig({ engine }) and,
5
+ // like /agy engine, takes effect on the next pi start (drivers wire at load).
6
+ // Startup checks the CLI once per process and offers setup when needed.
7
+ //
8
+ // UI: the shared framed choice modal from @estebanforge/pi-tui-dialogs
9
+ // (dialogChoice): one decision statement, a closed option list, esc cancels.
10
+
11
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
12
+ import { dialogChoice, type ChoiceOption, type DialogContext, type DialogRow } from "@estebanforge/pi-tui-dialogs";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { DEFAULT_ENGINE, type Engine } from "./config.js";
16
+
17
+ /** Picker order is the default answer order: acp (the default engine)
18
+ * preselected first, stream-json as the fallback. */
19
+ export const ENGINE_PICKER_ITEMS: ChoiceOption[] = [
20
+ {
21
+ value: "acp",
22
+ label: "ACP (agy acp)",
23
+ description: "default · ACP server in the agy CLI",
24
+ },
25
+ {
26
+ value: "stream-json",
27
+ label: "Stream-JSON CLI",
28
+ description: "the `agy` CLI, fallback",
29
+ },
30
+ ];
31
+
32
+ /** Intro paragraph above the list. Text wraps, so explanations stay here and
33
+ * option descriptions stay one-liners (the choice list truncates long lines). */
34
+ export const ENGINE_PICKER_INTRO = [
35
+ "Pick the engine that runs your Antigravity turns. Switch anytime with /agy engine (restart applies it).",
36
+ "",
37
+ "ACP (default): `agy acp`, the ACP server built into the agy CLI. Uses the same installation and Google sign-in as the CLI.",
38
+ "stream-json (fallback): the `agy` CLI you already installed and authenticated. Persistent process, streamed output.",
39
+ ].join("\n");
40
+
41
+ /** True only for a genuine first interactive run: no saved config yet (any
42
+ * existing file means the user has been here before) and no AGY_ENGINE env
43
+ * (env wins over the file, so the wizard would fight it). Fails closed to
44
+ * false - an fs error must never nag the user with a dialog. */
45
+ export function shouldOfferEnginePicker(
46
+ configPath: string,
47
+ env: NodeJS.ProcessEnv = process.env,
48
+ ): boolean {
49
+ if (env.AGY_ENGINE !== undefined) return false;
50
+ try {
51
+ return !fs.existsSync(configPath);
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ /** Narrow a picker value to an Engine. Items are our own constants, but an
58
+ * unknown value must never reach config as a cast string: it falls back to
59
+ * the default engine (acp), same rule as loadConfig's narrowing. */
60
+ export function toEngine(value: string): Engine {
61
+ return value === "acp" || value === "stream-json" ? value : DEFAULT_ENGINE;
62
+ }
63
+
64
+ /** Toast copy shown after the choice is saved. */
65
+ export function savedEngineMessage(engine: Engine): string {
66
+ return engine === "acp"
67
+ ? "Engine saved: acp. Turns will use `agy acp` and your existing CLI authentication. Restart applies the engine."
68
+ : "Engine saved: stream-json. Restart pi to apply.";
69
+ }
70
+
71
+ /** /agy settings row that opens the engine picker. Deliberately value-less:
72
+ * DialogMenu cycles rows that carry `values`, but resolves the menu with the
73
+ * row id on Enter for rows without — the caller then closes settings and
74
+ * opens the same modal as the first-run wizard. The active engine rides as
75
+ * the display value so the row reads like the rest of the surface. */
76
+ export const ENGINE_SETTINGS_ROW_ID = "engine";
77
+
78
+ export function engineSettingsRow(engine: Engine): DialogRow {
79
+ return {
80
+ id: ENGINE_SETTINGS_ROW_ID,
81
+ label: "Switch engine",
82
+ description:
83
+ "Open the engine picker (stream-json CLI vs agy acp). Enter opens it and closes settings; esc in the picker changes nothing. Restart applies a switch.",
84
+ currentValue: engine,
85
+ };
86
+ }
87
+
88
+ /** Bare-name suffix candidates per platform. Windows pins the probe to
89
+ * agy.exe: that is the only artifact Google ships there, and .bat/.cmd
90
+ * cannot spawn anyway (shell:false + EINVAL since CVE-2024-27980). */
91
+ function executableSuffixes(platform: NodeJS.Platform): string[] {
92
+ return platform === "win32" ? [".EXE"] : [""];
93
+ }
94
+
95
+ /** True when the `agy` CLI binary can be found. A binRef carrying a path
96
+ * separator must exist as a file - backslashes count as separators on
97
+ * win32, where path.join would mangle a bare "C:\..." AGY_BIN into a PATH
98
+ * segment. Otherwise the bare name is searched on PATH, appending the
99
+ * Windows candidate (agy.exe only: Google ships nothing else there, and
100
+ * an extensionless or .cmd file cannot be spawned anyway). A bare
101
+ * AGY_BIN that already ends in .exe probes the raw name too. Only a
102
+ * regular file counts; races fail closed. */
103
+ export function isAgyInstalled(
104
+ binRef: string,
105
+ env: NodeJS.ProcessEnv = process.env,
106
+ platform: NodeJS.Platform = process.platform,
107
+ ): boolean {
108
+ if (binRef.includes("/") || (platform === "win32" && binRef.includes("\\"))) {
109
+ try {
110
+ return fs.statSync(binRef).isFile();
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+ let suffixes = executableSuffixes(platform);
116
+ // A bare AGY_BIN=agy.exe already carries the extension; name+suffix
117
+ // would stat agy.exe.EXE and miss the real file (issue #11 class).
118
+ if (platform === "win32" && path.extname(binRef).toLowerCase() === ".exe") {
119
+ suffixes = ["", ...suffixes];
120
+ }
121
+ return (env.PATH ?? "")
122
+ .split(path.delimiter)
123
+ .filter(Boolean)
124
+ .some((dir) =>
125
+ suffixes.some((suffix) => {
126
+ try {
127
+ return fs.statSync(path.join(dir, binRef) + suffix).isFile();
128
+ } catch {
129
+ return false;
130
+ }
131
+ }),
132
+ );
133
+ }
134
+
135
+ /** Toast copy for the missing-CLI warning. Fires every pi start while the
136
+ * stream-json engine is active and the binary is absent. */
137
+ export function agyMissingMessage(): string {
138
+ return "The `agy` CLI is not installed. Install it from https://antigravity.google/product/antigravity-cli and log in on it to use Antigravity models.";
139
+ }
140
+
141
+ /** The kit's DialogContext wants the whole extension context, but both picker
142
+ * call sites hold only the ui object and are TUI-gated (ctx.mode === "tui")
143
+ * before they run. Wrap instead of threading two different ctx shapes. The
144
+ * cast is the pi-custom-options vs unknown-options signature gap; custom and
145
+ * notify exist at runtime on ExtensionUIContext. */
146
+ function asDialogContext(ui: ExtensionUIContext): DialogContext {
147
+ return { hasUI: true, mode: "tui", ui: ui as unknown as DialogContext["ui"] };
148
+ }
149
+
150
+ /** Render the choice modal via the shared dialog kit. Resolves with the
151
+ * chosen engine, or undefined when the user pressed esc (decide later -
152
+ * nothing is persisted). */
153
+ export async function showEnginePicker(ctx: ExtensionUIContext): Promise<Engine | undefined> {
154
+ const picked = await dialogChoice(asDialogContext(ctx), "Antigravity Bridge: choose your engine", {
155
+ description: ENGINE_PICKER_INTRO,
156
+ options: ENGINE_PICKER_ITEMS,
157
+ footer: "↑↓ navigate · enter select · esc decide later",
158
+ });
159
+ return picked === undefined ? undefined : toEngine(picked);
160
+ }
@@ -0,0 +1,38 @@
1
+ // Frame-guard: shared stdout framing defense for both engines.
2
+ //
3
+ // agy's stdout is a protocol stream, but foreign processes occasionally write
4
+ // into the same inherited pipe (the Chromium launcher behind a browser login
5
+ // prints "Opening in existing browser session." straight into it). Two
6
+ // defenses:
7
+ //
8
+ // 1. A hard per-frame ceiling: a line with no newline must never grow the
9
+ // reassembly buffer without bound. Breach = the peer is broken or
10
+ // hostile, the transport is dead.
11
+ // 2. Known-noise handling: a complete noise line is dropped before parsing;
12
+ // a noise FRAGMENT without a trailing newline glues itself onto the next
13
+ // real frame, so repair strips everything up to and including the marker.
14
+
15
+ /** Hard ceiling on one buffered (newline-terminated) frame. 32MB matches the
16
+ * reference ACP transport; real frames are KBs, machine-generated output
17
+ * with no newline for 32MB is a flood, not a frame. */
18
+ export const MAX_FRAME_BYTES = 32 * 1024 * 1024;
19
+
20
+ const NOISE_MARKERS = ["Opening in existing browser session."];
21
+
22
+ /** True when a complete line is pure known noise: drop before parsing. */
23
+ export function isKnownNoiseLine(line: string): boolean {
24
+ const trimmed = line.trim();
25
+ if (!trimmed) return false;
26
+ return NOISE_MARKERS.some((m) => trimmed === m);
27
+ }
28
+
29
+ /** Repair for the glue case: a noise fragment arrived without its newline and
30
+ * the next real frame is now "noise + json". Returns the remainder after the
31
+ * first known marker, or null when the line carries no marker. */
32
+ export function stripGluedNoise(line: string): string | null {
33
+ for (const marker of NOISE_MARKERS) {
34
+ const idx = line.indexOf(marker);
35
+ if (idx >= 0) return line.slice(idx + marker.length).trim();
36
+ }
37
+ return null;
38
+ }
@@ -0,0 +1,21 @@
1
+ /** Model-switch handoff toast (UI only): the message shown when the user
2
+ * lands on an antigravity bridge model that has no bound agy conversation,
3
+ * telling them pi-side context will re-deliver into the fresh conversation.
4
+ * Returns null when the toast must stay silent. */
5
+
6
+ const BRIDGE_API = "agy-bridge";
7
+
8
+ export function handoffToast(input: {
9
+ api: string | undefined;
10
+ digestEnabled: boolean;
11
+ bound: boolean;
12
+ hasContext: boolean;
13
+ source: "set" | "cycle" | "restore";
14
+ }): string | null {
15
+ if (input.source === "restore") return null;
16
+ if (input.api !== BRIDGE_API) return null;
17
+ if (!input.digestEnabled) return null;
18
+ if (input.bound) return null;
19
+ if (!input.hasContext) return null;
20
+ return "handoff context will ship to the new agy conversation";
21
+ }
@@ -0,0 +1,376 @@
1
+ // Per-pid bridge registration for the stream-json engine (docs/TODO.md
2
+ // section 1, step 2). The stream-json agy CLI discovers MCP servers from
3
+ // ~/.gemini/config/mcp_config.json (verified live 2026-09-07: a server
4
+ // registered via `agy mcp add --type http` was called by agy through its
5
+ // native call_mcp_tool wrapper, exact entry shape captured from agy's own
6
+ // writes):
7
+ //
8
+ // { "mcpServers": { "<name>": { "disabled": false,
9
+ // "headers": { "x-bridge-token": "..." }, "serverUrl": "http://..." } } }
10
+ //
11
+ // Native ACP gets a sanitized private copy; stream-json reads this file.
12
+ //
13
+ // Merge rules: foreign servers are preserved; corrupt JSON is refused (the
14
+ // file is shared user config - never clobber); writes are atomic.
15
+ //
16
+ // Run: npm test
17
+
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { extensionsDataDir } from "./config.js";
22
+
23
+ /** Name convention for the bridge's per-pid server entries. */
24
+ export function bridgeServerName(pid: number): string {
25
+ return `pi-bridge-${pid}`;
26
+ }
27
+
28
+ export function mcpConfigPath(home: string = os.homedir()): string {
29
+ return path.join(home, ".gemini", "config", "mcp_config.json");
30
+ }
31
+
32
+ export interface BridgeServerEntry {
33
+ disabled: boolean;
34
+ headers: Record<string, string>;
35
+ serverUrl: string;
36
+ }
37
+
38
+ type McpConfig = { mcpServers: Record<string, unknown> };
39
+
40
+ /** Tolerant read of the global mcp_config.json: strips a UTF-8 BOM and
41
+ * treats the CLI's fresh-install 0-byte file as no config (issue #11).
42
+ * Content that is not a JSON object still throws; ENOENT propagates.
43
+ * A malformed mcpServers value is NOT normalized here - staging wants
44
+ * strictness; registration normalizes at its own call site. */
45
+ export function readGlobalMcpConfig(file: string): McpConfig {
46
+ const raw = fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "");
47
+ const parsed = raw.trim() === "" ? { mcpServers: {} } : JSON.parse(raw);
48
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
49
+ throw new Error("mcp_config.json is not an object");
50
+ }
51
+ return parsed as McpConfig;
52
+ }
53
+
54
+ function readConfig(file: string): { ok: true; config: McpConfig } | { ok: false; reason: string } {
55
+ let config: McpConfig;
56
+ try {
57
+ config = readGlobalMcpConfig(file);
58
+ } catch (err) {
59
+ const code = (err as NodeJS.ErrnoException).code;
60
+ if (code === "ENOENT") return { ok: true, config: { mcpServers: {} } };
61
+ return { ok: false, reason: `mcp_config.json is not valid JSON; refusing to touch it (${String(err)})` };
62
+ }
63
+ if (!config.mcpServers || typeof config.mcpServers !== "object" || Array.isArray(config.mcpServers)) {
64
+ config.mcpServers = {};
65
+ }
66
+ return { ok: true, config };
67
+ }
68
+
69
+ function writeConfig(file: string, config: McpConfig): void {
70
+ // 0700/0600: the file carries the bridge's shared-secret token in its
71
+ // headers, and it lives in the USER'S global agy config (audit 2026-09-07:
72
+ // it previously landed at the umask default, typically world-readable).
73
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
74
+ const tmp = `${file}.${process.pid}.tmp`;
75
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });
76
+ fs.renameSync(tmp, file);
77
+ }
78
+
79
+ /** The canonical mcp_config.json entry shape for a bridge server. Single
80
+ * source for BOTH registration paths: the global per-pid entry
81
+ * (registerBridgeServer, marker-driven disabled flag) and the isolated-home
82
+ * own entry (always enabled - a private-home agy never reads global, so the
83
+ * marker never applies there, issue #14). */
84
+ export function bridgeServerEntry(entry: {
85
+ port: number;
86
+ token: string;
87
+ tokenHeader: string;
88
+ disabled?: boolean;
89
+ }): BridgeServerEntry {
90
+ return {
91
+ disabled: entry.disabled ?? false,
92
+ headers: { [entry.tokenHeader]: entry.token },
93
+ serverUrl: `http://127.0.0.1:${entry.port}/mcp`,
94
+ };
95
+ }
96
+
97
+ /** Register (or refresh) the bridge's per-pid server entry. Foreign servers
98
+ * in the file are preserved.
99
+ *
100
+ * One shared guard for delegation isolation: while ANY live delegation is
101
+ * in flight anywhere on the machine (per the suppression marker), a fresh
102
+ * registration lands disabled - the delegated agy must not discover a new
103
+ * bridge mid-run. The last release re-enables every entry again. */
104
+ export function registerBridgeServer(
105
+ entry: { pid: number; port: number; token: string; tokenHeader: string },
106
+ configPath: string = mcpConfigPath(),
107
+ opts: {
108
+ markerPath?: string;
109
+ isAlive?: (pid: number) => boolean;
110
+ now?: () => number;
111
+ } = {},
112
+ ): { wrote: boolean; disabled: boolean; reason?: string } {
113
+ const marker = readSuppressionMarker(opts.markerPath ?? suppressionMarkerPath());
114
+ const disabled = hasLiveDelegator(marker, opts.isAlive ?? pidAlive, (opts.now ?? Date.now)());
115
+ const read = readConfig(configPath);
116
+ if (!read.ok) return { wrote: false, disabled, reason: read.reason };
117
+ read.config.mcpServers[bridgeServerName(entry.pid)] = bridgeServerEntry({
118
+ port: entry.port,
119
+ token: entry.token,
120
+ tokenHeader: entry.tokenHeader,
121
+ disabled,
122
+ });
123
+ writeConfig(configPath, read.config);
124
+ return { wrote: true, disabled };
125
+ }
126
+
127
+ /** Remove the bridge's per-pid server entry (close path). */
128
+ export function unregisterBridgeServer(pid: number, configPath: string = mcpConfigPath()): { wrote: boolean } {
129
+ const read = readConfig(configPath);
130
+ if (!read.ok) return { wrote: false };
131
+ const name = bridgeServerName(pid);
132
+ if (!(name in read.config.mcpServers)) return { wrote: false };
133
+ delete read.config.mcpServers[name];
134
+ writeConfig(configPath, read.config);
135
+ return { wrote: true };
136
+ }
137
+
138
+ /** Flip `disabled` on every pi-bridge-* entry (foreign servers untouched).
139
+ *
140
+ * (1) Delegation isolation: the global config is read by ANY agy on the
141
+ * machine, so an `agy -p` we spawn ourselves (AskAntigravity) would discover
142
+ * live bridge entries and call tools the round-trip store cannot serve
143
+ * outside a live provider turn (fail-closed "no active antigravity turn",
144
+ * observed live 2026-09-15). agy reads the config once at startup, so a
145
+ * short suppression window around the spawn hides the bridge from it.
146
+ *
147
+ * (2) Startup healing (disabled=false): clears entries a crashed delegation
148
+ * left suppressed. */
149
+ export function setBridgeEntriesDisabled(
150
+ disabled: boolean,
151
+ configPath: string = mcpConfigPath(),
152
+ ): { wrote: boolean; changed: number; reason?: string } {
153
+ const read = readConfig(configPath);
154
+ if (!read.ok) return { wrote: false, changed: 0, reason: read.reason };
155
+ let changed = 0;
156
+ for (const [name, entry] of Object.entries(read.config.mcpServers)) {
157
+ if (!/^pi-bridge-\d+$/.test(name)) continue;
158
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
159
+ const e = entry as { disabled?: unknown };
160
+ if ((e.disabled === true) === disabled) continue;
161
+ e.disabled = disabled;
162
+ changed++;
163
+ }
164
+ if (changed === 0) return { wrote: false, changed: 0 };
165
+ writeConfig(configPath, read.config);
166
+ return { wrote: true, changed };
167
+ }
168
+
169
+ // --- Cross-process suppression marker --------------------------------------
170
+
171
+ /** Shape of the shared delegator marker (suppression.json). Keyed by pi pid;
172
+ * `since` is the acquire timestamp in ms since epoch. Coordination ONLY:
173
+ * the disabled flags in mcp_config.json stay the actual gate. */
174
+ export interface SuppressionMarker {
175
+ delegators: Record<string, { since: number }>;
176
+ }
177
+
178
+ /** Marker path, under the bridge's extensions-data dir (src/config.ts
179
+ * extensionsDataDir). Lives OUTSIDE ~/.gemini so agy's watched config dir
180
+ * stays untouched. */
181
+ export function suppressionMarkerPath(agentDir?: string): string {
182
+ return path.join(extensionsDataDir(agentDir), "suppression.json");
183
+ }
184
+
185
+ /** A SIGKILLed pi can leave its marker entry behind, and pid reuse could
186
+ * keep kill(pid,0) answering forever. The age bound caps that wedge: a
187
+ * delegation never legitimately runs this long, so an entry this old is
188
+ * dead regardless of what the pid probe says. */
189
+ const DELEGATOR_MAX_AGE_MS = 24 * 60 * 60 * 1000;
190
+
191
+ function readSuppressionMarker(file: string): SuppressionMarker {
192
+ try {
193
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
194
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { delegators: {} };
195
+ const delegators = (parsed as SuppressionMarker).delegators;
196
+ if (!delegators || typeof delegators !== "object" || Array.isArray(delegators)) {
197
+ return { delegators: {} };
198
+ }
199
+ return { delegators };
200
+ } catch {
201
+ // Missing or corrupt marker: fail-open to empty. Never worse than the
202
+ // pre-marker blind re-enable; the next write replaces the file.
203
+ return { delegators: {} };
204
+ }
205
+ }
206
+
207
+ function writeSuppressionMarker(file: string, marker: SuppressionMarker): void {
208
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
209
+ const tmp = `${file}.${process.pid}.tmp`;
210
+ fs.writeFileSync(tmp, JSON.stringify(marker, null, 2) + "\n", { mode: 0o600 });
211
+ fs.renameSync(tmp, file);
212
+ }
213
+
214
+ function delegatorLive(pid: string, entry: { since?: number } | undefined, isAlive: (pid: number) => boolean, now: number): boolean {
215
+ const n = Number(pid);
216
+ const since = typeof entry?.since === "number" ? entry.since : 0;
217
+ return Number.isFinite(n) && n > 0 && now - since < DELEGATOR_MAX_AGE_MS && isAlive(n);
218
+ }
219
+
220
+ function pruneDelegators(
221
+ marker: SuppressionMarker,
222
+ isAlive: (pid: number) => boolean,
223
+ now: number,
224
+ ): { kept: SuppressionMarker; pruned: string[] } {
225
+ const kept: SuppressionMarker = { delegators: {} };
226
+ const pruned: string[] = [];
227
+ for (const [pid, entry] of Object.entries(marker.delegators)) {
228
+ if (delegatorLive(pid, entry, isAlive, now)) kept.delegators[pid] = { since: entry.since };
229
+ else pruned.push(pid);
230
+ }
231
+ return { kept, pruned };
232
+ }
233
+
234
+ function hasLiveDelegator(marker: SuppressionMarker, isAlive: (pid: number) => boolean, now: number): boolean {
235
+ return Object.entries(marker.delegators).some(([pid, entry]) => delegatorLive(pid, entry, isAlive, now));
236
+ }
237
+
238
+ function bestEffortWriteMarker(file: string, marker: SuppressionMarker): void {
239
+ try {
240
+ writeSuppressionMarker(file, marker);
241
+ } catch {
242
+ // Coordination hint only; a failed write must never break a release or
243
+ // a heal. The disabled flags in mcp_config.json remain the gate.
244
+ }
245
+ }
246
+
247
+ // Pi replaces the runtime on /new,/resume,/fork,/reload: module state dies
248
+ // but globalThis survives within the process. The refcount must live there,
249
+ // or an old runtime's late release re-enables entries under a new runtime's
250
+ // live delegation.
251
+ const SUPPRESSION_REFS_KEY = Symbol.for("pi-antigravity-bridge.suppression-refs");
252
+ const suppressionRefs: Map<string, number> = ((globalThis as Record<symbol, unknown>)[SUPPRESSION_REFS_KEY] ??= new Map()) as Map<string, number>;
253
+
254
+ /** Reference-counted suppression for a self-spawned agy process (AskAntigravity
255
+ * delegation). First acquire disables every pi-bridge-* entry AND records
256
+ * this process's pid in the shared suppression marker; last release removes
257
+ * it and re-enables only when no LIVE delegator remains - so two pi sessions
258
+ * delegating concurrently no longer re-enable each other's entries
259
+ * (previously a same-process-only refcount raced on the shared file).
260
+ * Nested acquires in one process are free. Residual race: concurrent
261
+ * read-modify-write of the marker across processes is last-writer-wins
262
+ * (atomic rename), and a syscall-scale interleave can still briefly re-open
263
+ * the bridge during a live delegation; both are bounded, self-heal at the
264
+ * next release/heal, and degrade to the status-quo fail-closed deny. */
265
+ export function acquireBridgeSuppression(opts: SuppressionOptions = {}): () => void {
266
+ const configPath = opts.configPath ?? mcpConfigPath();
267
+ const markerPath = opts.markerPath ?? suppressionMarkerPath();
268
+ const pid = opts.pid ?? process.pid;
269
+ const isAlive = opts.isAlive ?? pidAlive;
270
+ const now = opts.now ?? Date.now;
271
+ const key = `${path.resolve(markerPath)}\u0000${pid}`;
272
+ const refs = (suppressionRefs.get(key) ?? 0) + 1;
273
+ suppressionRefs.set(key, refs);
274
+ if (refs === 1) {
275
+ // Marker BEFORE the config flip: a session-start heal racing between
276
+ // the two writes reads an empty marker and would re-enable entries for
277
+ // a delegation that is about to go live. Recording first shrinks that
278
+ // window to the config flip itself.
279
+ const marker = readSuppressionMarker(markerPath);
280
+ marker.delegators[String(pid)] = { since: now() };
281
+ bestEffortWriteMarker(markerPath, marker);
282
+ setBridgeEntriesDisabled(true, configPath);
283
+ }
284
+ let released = false;
285
+ return () => {
286
+ if (released) return;
287
+ released = true;
288
+ const left = Math.max(0, (suppressionRefs.get(key) ?? 1) - 1);
289
+ if (left === 0) suppressionRefs.delete(key);
290
+ else suppressionRefs.set(key, left);
291
+ if (left === 0) {
292
+ const marker = readSuppressionMarker(markerPath);
293
+ delete marker.delegators[String(pid)];
294
+ const { kept } = pruneDelegators(marker, isAlive, now());
295
+ bestEffortWriteMarker(markerPath, kept);
296
+ // Re-read right before the flip: an acquire that raced us between
297
+ // the marker write and this read is already live and must keep its
298
+ // suppression (a stale snapshot here would re-enable over it).
299
+ const fresh = readSuppressionMarker(markerPath);
300
+ if (Object.keys(fresh.delegators).length === 0) {
301
+ setBridgeEntriesDisabled(false, configPath);
302
+ }
303
+ }
304
+ };
305
+ }
306
+
307
+ export interface SuppressionOptions {
308
+ /** Global mcp_config.json path (default: the real user config). */
309
+ configPath?: string;
310
+ /** Cross-process delegator marker path (default: suppression.json in the
311
+ * bridge's extensions-data dir). */
312
+ markerPath?: string;
313
+ /** Delegator identity; defaults to this process's pid. Injectable so tests
314
+ * can simulate two sessions in one process. */
315
+ pid?: number;
316
+ isAlive?: (pid: number) => boolean;
317
+ now?: () => number;
318
+ }
319
+
320
+ /** Session-start heal, marker-aware. Prunes dead or stale delegators, then
321
+ * re-enables the entries ONLY when no live delegator remains. A blind
322
+ * re-enable here used to un-hide the bridge during another session's active
323
+ * delegation - a plain session start in a second window could reproduce the
324
+ * fail-closed deny this file exists to prevent. */
325
+ export function healBridgeSuppression(opts: SuppressionOptions = {}): {
326
+ pruned: string[];
327
+ reEnabled: boolean;
328
+ reason?: string;
329
+ } {
330
+ const configPath = opts.configPath ?? mcpConfigPath();
331
+ const markerPath = opts.markerPath ?? suppressionMarkerPath();
332
+ const isAlive = opts.isAlive ?? pidAlive;
333
+ const now = opts.now ?? Date.now;
334
+ const marker = readSuppressionMarker(markerPath);
335
+ const { kept, pruned } = pruneDelegators(marker, isAlive, now());
336
+ if (pruned.length > 0) bestEffortWriteMarker(markerPath, kept);
337
+ // Decide on a FRESH read, not the pruned snapshot: an acquire that raced
338
+ // us after our write is already live and must keep its suppression.
339
+ const fresh = readSuppressionMarker(markerPath);
340
+ if (Object.keys(fresh.delegators).length > 0) return { pruned, reEnabled: false };
341
+ const flip = setBridgeEntriesDisabled(false, configPath);
342
+ return { pruned, reEnabled: flip.changed > 0, reason: flip.reason };
343
+ }
344
+
345
+ /** Default liveness probe: can the signal be delivered? */
346
+ function pidAlive(pid: number): boolean {
347
+ try {
348
+ process.kill(pid, 0);
349
+ return true;
350
+ } catch {
351
+ return false;
352
+ }
353
+ }
354
+
355
+ /** Remove bridge entries whose owning pi process is gone (stale sweep, run
356
+ * at extension start). Foreign servers and live-pid entries are preserved.
357
+ * Entries not matching the per-pid name convention are never touched. */
358
+ export function sweepStaleBridgeServers(
359
+ configPath: string = mcpConfigPath(),
360
+ isAlive: (pid: number) => boolean = pidAlive,
361
+ ): { removed: string[]; reason?: string } {
362
+ const read = readConfig(configPath);
363
+ if (!read.ok) return { removed: [], reason: read.reason };
364
+ const removed: string[] = [];
365
+ for (const name of Object.keys(read.config.mcpServers)) {
366
+ const match = /^pi-bridge-(\d+)$/.exec(name);
367
+ if (!match) continue;
368
+ const pid = Number(match[1]);
369
+ if (Number.isFinite(pid) && !isAlive(pid)) {
370
+ delete read.config.mcpServers[name];
371
+ removed.push(name);
372
+ }
373
+ }
374
+ if (removed.length > 0) writeConfig(configPath, read.config);
375
+ return { removed };
376
+ }