@estebanforge/pi-antigravity-bridge 1.11.0 → 1.12.0

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.12.0] - 2026-11-19
6
+
7
+ ### Fixed
8
+
9
+ - **Every bridge-owned path now follows pi's agent dir (`PI_CODING_AGENT_DIR` / `getAgentDir()`) instead of hardcoded `~/.pi` (issue #17).** Isolated or rebranded pi homes (Gentle Shell-style wrappers) previously got their config, session bindings, model cache, ACP homes, per-pid agy-mcp dirs, patch backups, support logs, and suppression marker written under `~/.pi` anyway, and skill discovery plus permission-extension detection read the wrong home. All state now derives from one `bridgeDir()`/`extensionsDataDir()` helper pair anchored at `getAgentDir()`, skill discovery mirrors pi's own loader (`<agentDir>/skills` user, `<project>/<CONFIG_DIR_NAME>/skills` project), and detection markers follow each writer's verified layout: gotgenes and monroewilliams resolve globals via `getAgentDir()` (the old literal `~/.agent/pi-permissions.jsonc` marker matched no path any published monroewilliams release ever wrote, so installs it silently missed now detect), while rhedbull and the project policy file stay on the literal `.pi` paths their packages hardcode. Default installs resolve byte-identical to before; env-override users start fresh — existing `sessions.json` conversation bindings and the model cache under the old path are not migrated. `CONFIG_PATH`/`STORE_PATH`/`MODELS_CACHE_PATH`/`BRIDGE_BASE`/`PATCH_BACKUP_DIR` consts became functions (`configPath()` et al.) so the resolution is per-call, and the `{ home }`/`{ cwd }` test seams gained an `agentDir` override.
10
+ - **The approval gate now covers the ACP engine and agy 1.5.11's tool family (issue #18).** Two live-captured gaps closed on the mapping side: `write_file {Path, Content}` was never gated (the system-prompt carrier explicitly requests this tool, so new-file writes sailed past the gate even on stream-json), and `edit_file {Path, Target, Replacement}` mapped to an empty path that permission extensions cannot judge. `write_file` joined `GATED_AGY_TOOLS` (one source feeding the hook matcher, the deny set, and the mapping), the mapping accepts the new arg names with the older spellings as fallbacks, and a gated write/edit whose target path resolves empty (or a multi-replace with no resolvable chunk) now denies before parking instead of forwarding decision garbage; a cross-check test pins every gated name to a working mapping.
11
+ On the engine side, the ACP server was silently excluded: the gate was staged for every session but only the stream-json driver delivered it, so with the gate on, ACP turns (the default engine) ran native tools ungated while `approvals.mode` promised enforcement. A live probe on agy 1.5.12 (`scripts/probe-acp-hooks.mjs`, workspace positive control fired) showed the server honors PreToolUse hooks from the staged home's `config/hooks.json`, so the connection now merges the session's gate group into the staged home at spawn (`mergeGateGroupIntoAcpHome`, foreign groups preserved, no-op when the gate is off). Gate state stays load-latched: mid-session gate changes take effect on the next pi session, same as stream-json staging. Delivery is probe-verified on agy 1.5.12 only; the session wiring warns in the log and /agy doctor lists the gate as delivery-unverified when an older agy serves a gated ACP session, and the full park round trip on a live ACP server remains tracked in docs/TODO.md section 3b.
12
+ - **ACP turns that end without model output now explain themselves (issue #18).** agy 1.5.11 ended a turn with the non-ACP stopReason `stop` after a native `run_command` failed, the driver mapped the unknown reason to a clean OK, and the pi caller received an empty final report with no trace of the failure. Unknown stop reasons are now logged (`acp-unknown-stop-reason`), and an OK turn with no model text whose native tool failed settles with a synthetic report naming the tool and its error instead of silence. Model output still wins: a failed tool followed by a normal answer never gets the note.
13
+
5
14
  ## [1.11.0] - 2026-11-18
6
15
 
7
16
  ### Added
package/README.md CHANGED
@@ -9,7 +9,7 @@ If you also have [`@estebanforge/pi-ask-antigravity`](https://github.com/Esteban
9
9
 
10
10
  You pick a Gemini model in pi's `/model` picker. pi routes each turn through this provider. A single persistent `agy` process runs in your workspace; pi feeds it each turn, parses its stream-json events, and streams the agent text back into pi token by token. Token usage is live.
11
11
 
12
- Multi-turn works. The provider binds a pi session to an agy conversation id (persisted under `~/.pi/agent/antigravity-bridge/sessions.json`) and resumes it on the next turn via `--conversation <id>`. agy keeps its own history, so only the latest user message is sent each turn.
12
+ Multi-turn works. The provider binds a pi session to an agy conversation id (persisted under `<agentDir>/antigravity-bridge/sessions.json`, following `PI_CODING_AGENT_DIR`/`getAgentDir()`) and resumes it on the next turn via `--conversation <id>`. agy keeps its own history, so only the latest user message is sent each turn.
13
13
 
14
14
  ### Two engines
15
15
 
@@ -36,7 +36,7 @@ Residual limits (with or without the bridge):
36
36
 
37
37
  While agy is the active model it normally cannot see pi's universe of extensions: agentmemory, codegraph, web search, slack/asana, the `Ask*` delegations, and any other installed pi tool. This extension optionally bridges that gap.
38
38
 
39
- The bridge starts a localhost MCP server inside pi's process. The exposed catalog is computed live from pi's active tools on every `tools/list` and re-checked immediately before every `tools/call`: the `bridgeTools` mode, the session's `/agy tools` hidden set, and the bridge's own internal tools (`AskAntigravity`, the display-only `antigravity` wrapper, `activate_skill`, `bridge_poll_result`, the `agy_web_search`/`agy_read_url` wrappers) are filtered each time, and a call for anything outside the fresh set is rejected - a cached MCP catalog is not authorization. A call that passes routes into pi's own tool loop via the round-trip described below. Discovery has two layers. The provider's agy gets a per-invocation config: the bridge writes `.agents/mcp_config.json` into a bridge-controlled dir (`~/.pi/agent/antigravity-bridge/agy-mcp-<pid>/`) and the driver passes that dir as an extra `--add-dir` when it spawns agy. A per-pid entry (`pi-bridge-<pid>`) is also registered in the user's global agy config (`~/.gemini/config/mcp_config.json`; foreign servers preserved, stale entries swept at start), so agy builds that read only the global config still find the bridge.
39
+ The bridge starts a localhost MCP server inside pi's process. The exposed catalog is computed live from pi's active tools on every `tools/list` and re-checked immediately before every `tools/call`: the `bridgeTools` mode, the session's `/agy tools` hidden set, and the bridge's own internal tools (`AskAntigravity`, the display-only `antigravity` wrapper, `activate_skill`, `bridge_poll_result`, the `agy_web_search`/`agy_read_url` wrappers) are filtered each time, and a call for anything outside the fresh set is rejected - a cached MCP catalog is not authorization. A call that passes routes into pi's own tool loop via the round-trip described below. Discovery has two layers. The provider's agy gets a per-invocation config: the bridge writes `.agents/mcp_config.json` into a bridge-controlled dir (`<agentDir>/antigravity-bridge/agy-mcp-<pid>/`) and the driver passes that dir as an extra `--add-dir` when it spawns agy. A per-pid entry (`pi-bridge-<pid>`) is also registered in the user's global agy config (`~/.gemini/config/mcp_config.json`; foreign servers preserved, stale entries swept at start), so agy builds that read only the global config still find the bridge.
40
40
 
41
41
  **Upstream pi APIs only.** Bridge calls park in the provider's round-trip store; the provider ends the pi assistant message with a `toolUse` stop reason for the real pi tool, pi executes it in its own loop (native cards, permissions, hooks), and the toolResult completes the parked MCP response on the next stream call.
42
42
 
@@ -73,7 +73,7 @@ cards for read-only steps.
73
73
 
74
74
  ## Approval gate (agy native tools)
75
75
 
76
- agy runs its own agent loop with native tools (`run_command`, `create_file`, `edit_file`, ...), which pi's permission extensions never saw. The optional approval gate routes those calls through a pi-side approval: a staged PreToolUse hook parks the call, the provider surfaces it as a shadow `bash`/`write`/`edit` toolUse, and your permission extension (or the built-in ask/allow/deny fallback) decides before agy executes it. Off by default (`approvals.gateMode: auto` enables it only when a pi permission extension is detected); denials fail closed; read-only agy tools stay ungated. On ACP turns the server has its own per-tool permission ask: when one fires (`skipPermissions` off), the request parks on a real pi dialog instead of a silent deny, and allow-always choices are remembered per connection.
76
+ agy runs its own agent loop with native tools (`run_command`, `create_file`, `edit_file`, ...), which pi's permission extensions never saw. The optional approval gate routes those calls through a pi-side approval: a staged PreToolUse hook parks the call, the provider surfaces it as a shadow `bash`/`write`/`edit` toolUse, and your permission extension (or the built-in ask/allow/deny fallback) decides before agy executes it. Off by default (`approvals.gateMode: auto` enables it only when a pi permission extension is detected); denials fail closed; read-only agy tools stay ungated. Both engines are covered: stream-json receives the staged hooks via `--add-dir`, and the ACP server reads them from the staged home's `config/hooks.json` (issue #18). On ACP turns the server also has its own per-tool permission ask: when one fires (`skipPermissions` off), the request parks on a real pi dialog instead of a silent deny, and allow-always choices are remembered per connection. On ACP turns the server has its own per-tool permission ask: when one fires (`skipPermissions` off), the request parks on a real pi dialog instead of a silent deny, and allow-always choices are remembered per connection.
77
77
 
78
78
  Full mechanics, configuration, and a sample gate extension: [docs/APPROVAL-GATE.md](docs/APPROVAL-GATE.md).
79
79
 
@@ -131,7 +131,7 @@ The `activate_skill` catalog mirrors pi's directory-based skill discovery: the t
131
131
 
132
132
  ### The /agy command
133
133
 
134
- `/agy` configures the provider at runtime. Settings persist to `~/.pi/agent/antigravity-bridge/config.json` and take effect on the next turn.
134
+ `/agy` configures the provider at runtime. Settings persist to `<agentDir>/antigravity-bridge/config.json` (pi's agent dir, so `PI_CODING_AGENT_DIR` is honored) and take effect on the next turn.
135
135
 
136
136
  ```
137
137
  /agy status summary, or open the full settings picker (TUI)
@@ -191,7 +191,7 @@ For isolation when running any agent that executes commands without a confirmati
191
191
  | `AGY_DEFAULT_MODEL` | Default model for the `AskAntigravity` tool: `flash`/`pro`/`gemini`, or an exact id such as `gemini-4-hydrogen`. Default `gemini-4-hydrogen`; the tier suffix rides `AGY_DEFAULT_THINKING`. Wins over the config file. |
192
192
  | `AGY_DEFAULT_THINKING` | Default thinking tier for the `AskAntigravity` tool: `low`/`medium`/`high`. Anything else falls back to `medium`. Wins over the config file. |
193
193
  | `AGY_DEBUG` | `1`/`true`/`on` writes the full trail to the daily log (driver lifecycle, raw bridge traffic). Default off: **only `error` records land on disk** - routine disk writes are zero for regular users, and warnings surface as UI toasts instead. |
194
- | `AGY_APPROVALS` | Approval gate mode: `auto` (default; gate on only when a pi permission extension is detected), `shadow` (force the shadow-tool gate on), `dedicated`, `off`. Unknown values fall back to `auto`, so a typo can never force the gate on. Wins over `config.approvals.gateMode`. |
194
+ | `AGY_APPROVALS` | Approval gate mode: `auto` (default; gate on only when a pi permission extension is detected), `shadow` (force the shadow-tool gate on), `dedicated`, `off`. Unknown values fall back to `auto`, so a typo can never force the gate on. Wins over `config.approvals.gateMode`. Works on both engines: stream-json via `--add-dir`, ACP via the staged home's `config/hooks.json` (issue #18). |
195
195
  | `AGY_APPROVALS_MODE` | Fallback decision when no permission extension answers a gated call: `ask` (interactive prompt), `allow`, `deny` (headless default). Wins over `config.approvals.mode`. |
196
196
 
197
197
  ## Debug logs
@@ -199,9 +199,11 @@ For isolation when running any agent that executes commands without a confirmati
199
199
  The extension keeps a daily log on your machine, sorted by day:
200
200
 
201
201
  ```
202
- ~/.pi/extensions-data/estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson
202
+ <configRoot>/extensions-data/estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson
203
203
  ```
204
204
 
205
+ `configRoot` is dirname of pi's agent dir (`~/.pi` by default; `PI_CODING_AGENT_DIR` relocates it).
206
+
205
207
  One JSON record per line. Two verbosity tiers keep the disk cost at zero for regular users: by default only `error` records land on disk - everything routine (turn starts, tool calls, escalations, commands, driver failures) is withheld. Warnings are not lost: the extension toasts each one in the pi UI (bridge tool failures, stalls, timeouts, process exits), so users see them and can report them; deliberate aborts and failures pi already renders as the turn's own error block stay silent. Set `AGY_DEBUG=1` before reproducing a problem for the full trail: per-event driver lifecycle (spawn, exit, session load/new, unparks), turn starts and outcomes, bridge tool calls, escalations and poll traffic, late deliveries, list-tools traffic, recycle causes, and the raw bridge chatter. `/agy doctor` prints the log directory.
206
208
 
207
209
  Notes:
@@ -14,7 +14,7 @@
14
14
  // /agy command: full runtime config surface (engine, mode, permissions,
15
15
  // bridge tools, model, thinking, digest, system prompt) plus doctor,
16
16
  // authentication instructions, patch-cleanup, and session clear. Config persists to
17
- // ~/.pi/agent/antigravity-bridge/config.json so toggles survive restarts.
17
+ // <agentDir>/antigravity-bridge/config.json so toggles survive restarts.
18
18
 
19
19
  import os from "node:os";
20
20
  import fs from "node:fs";
@@ -67,7 +67,7 @@ import { agyAuthenticationMessage } from "../src/agy-install.js";
67
67
  import { createAgySetupOffer } from "../src/agy-setup.js";
68
68
  import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
69
69
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
70
- import { CONFIG_PATH, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
70
+ import { configPath, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
71
71
  import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
72
72
  import { agyVersionVerdict, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
73
73
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
@@ -138,7 +138,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
138
138
  // picker populated so the user gets a clear runtime error from agy rather
139
139
  // than an empty model list. /reload re-runs this and refreshes after an
140
140
  // `agy update`.
141
- // loadModelCatalogRaw serves a short-TTL cache (~/.pi/agent/antigravity-bridge/
141
+ // loadModelCatalogRaw serves a short-TTL cache (<agentDir>/antigravity-bridge/
142
142
  // models-cache.json) so reloads are instant and only re-spawn in the
143
143
  // background when stale. Derive both catalogs from the same raw text
144
144
  // (provider's slugified Gemini entries + the tool's family/version/tier
@@ -166,8 +166,9 @@ export default async function (pi: ExtensionAPI): Promise<void> {
166
166
  const FAIL_REASON_TURN_END = "antigravity turn ended with an unresolved pi tool call";
167
167
  const FAIL_REASON_SHUTDOWN = "antigravity session shut down";
168
168
 
169
- // Daily file log: every sink below feeds ~/.pi/extensions-data/
170
- // estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson (see
169
+ // Daily file log: every sink below feeds <configRoot>/extensions-data/
170
+ // estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson, where
171
+ // configRoot is dirname(getAgentDir()) (see
171
172
  // src/daily-log.ts). Fire-and-forget, secrets redacted, old days pruned.
172
173
  // Support flow: "attach the last days' files from that dir".
173
174
  const fileLog = createDailyLogger({ dir: logsDir() });
@@ -776,7 +777,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
776
777
  // bridge startup below: on a genuine first run the modal blocks input
777
778
  // anyway, so the delay is invisible.
778
779
  let setupEngine = engine;
779
- if (event.reason === "startup" && ctx.mode === "tui" && shouldOfferEnginePicker(CONFIG_PATH)) {
780
+ if (event.reason === "startup" && ctx.mode === "tui" && shouldOfferEnginePicker(configPath())) {
780
781
  // Best-effort, like the legacy-patch notice below: a picker failure
781
782
  // (mid-prompt TUI teardown, resize races) must never take down the
782
783
  // rest of session_start - the MCP bridge startup included. The
@@ -814,7 +815,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
814
815
  }
815
816
  if (!legacyFileAcpWarningShown && legacyConfigCleanupFailed) {
816
817
  legacyFileAcpWarningShown = true;
817
- const msg = `Couldn't remove the old "bin" setting from ${CONFIG_PATH} (details in the bridge log). Delete the "bin" line under "acp" by hand; turns run "agy acp" from the CLI.`;
818
+ const msg = `Couldn't remove the old "bin" setting from ${configPath()} (details in the bridge log). Delete the "bin" line under "acp" by hand; turns run "agy acp" from the CLI.`;
818
819
  if (ctx.hasUI) ctx.ui.notify(msg, "warning");
819
820
  else console.error(`[antigravity-bridge] ${msg}`);
820
821
  }
@@ -899,7 +900,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
899
900
  if (mcpHandle) return; // already running (reload re-fires session_start)
900
901
  // pi loads project skill locations only after the project is trusted;
901
902
  // mirror that gate. Global skill dirs are always scanned.
902
- const skills: SkillLite[] = scanSkills(ctx.isProjectTrusted() ? process.cwd() : undefined);
903
+ const skills: SkillLite[] = scanSkills(ctx.isProjectTrusted() ? { projectDir: process.cwd() } : {});
903
904
  const listTools = () => {
904
905
  // /mcp and pi.setActiveTools() update the same live catalog. ACP gets
905
906
  // this endpoint through session/new or session/load; no global config write.
@@ -1051,6 +1052,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1051
1052
  {
1052
1053
  const cfg = loadConfig();
1053
1054
  const mode = resolveGateMode(cfg.approvals.gateMode, detectPermissionGateExtensions());
1055
+ if (mode !== "off" && engine === "acp") {
1056
+ // Staged-home hook delivery is probe-verified on agy 1.5.12
1057
+ // only (issue #18); older ACP builds may not honor it. Warn
1058
+ // so a silently inert gate is at least visible in the log.
1059
+ const cli = await checkAgyCliVersion(resolveAgyBinary());
1060
+ if (cli.status === "ok" && agyVersionVerdict(cli.raw, "1.5.12").status === "unsupported") {
1061
+ fileLog.log("approval-gate-agy-version-unverified", { version: cli.raw }, "warn");
1062
+ }
1063
+ }
1054
1064
  if (mode === "dedicated") {
1055
1065
  // The explicit antigravity_approve variant is planned; until it
1056
1066
  // ships, dedicated stages the same shadow tools. Say so, so the
@@ -1256,7 +1266,7 @@ function statusText(ctx: AgyCommandCtx): string {
1256
1266
  ` models: ${ctx.entries.length} ${source}`,
1257
1267
  ...settingsRows(ctx),
1258
1268
  ` sessions: ${ctx.store.size} bound`,
1259
- ` config: ${CONFIG_PATH}`,
1269
+ ` config: ${configPath()}`,
1260
1270
  "",
1261
1271
  "Subcommands: /agy auth, /agy auth-manual, /agy engine stream-json|acp, /agy mode plan|accept-edits, /agy readonly on|off, /agy permissions on|off, /agy ask on|off, /agy model <alias>, /agy thinking low|medium|high, /agy agent <name|off>, /agy subagents, /agy quota, /agy artifacts [open <n|name>], /agy tasks [tail <id>], /agy bridge all|mcp|none, /agy tools [hide|show <name>|reset], /agy web on|off, /agy digest on|off, /agy system-prompt on|off, /agy timeout <1-1440|off>, /agy patch-cleanup, /agy clear, /agy doctor",
1262
1272
  ].join("\n");
@@ -1390,7 +1400,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1390
1400
  ` sessions: ${ctx.store.size} bound`,
1391
1401
  ` models: ${ctx.entries.length} ${ctx.usingFallback ? "FALLBACK (agy models failed)" : "discovered"}`,
1392
1402
  ` agy cli: ${describeAgyVersionCheck(cliCheck)} (min ${cliFloor})`,
1393
- ` config: ${CONFIG_PATH}`,
1403
+ ` config: ${configPath()}`,
1394
1404
  ` logs: ${logsDir()} (attach recent days' files when reporting issues; set AGY_DEBUG=1 to capture details)`,
1395
1405
  ];
1396
1406
  if (snap.engine === "acp" && snap.acp) {
@@ -1412,6 +1422,12 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1412
1422
  for (const entry of snap.lifecycle.slice(-5)) lines.push(` ${entry}`);
1413
1423
  }
1414
1424
  if (engine === "acp") lines.push(" acp transport: agy acp (shared CLI authentication, isolated MCP home)");
1425
+ if (engine === "acp" && resolveGateMode(config.approvals.gateMode, detectPermissionGateExtensions()) !== "off"
1426
+ && rawCliCheck.status === "ok" && agyVersionVerdict(rawCliCheck.raw, "1.5.12").status === "unsupported") {
1427
+ // Same condition as the session_start wiring warn, surfaced here
1428
+ // because a daily-log-only signal is easy to miss (review S2).
1429
+ lines.push(` approval gate: ON but hook delivery is verified only on agy >= 1.5.12 (this: ${rawCliCheck.raw}; issue #18)`);
1430
+ }
1415
1431
  if (engine === "stream-json" && ctx.streamIsolated) lines.push(" stream transport: agy stream-json (shared CLI authentication, isolated MCP home)");
1416
1432
  if (engine === "stream-json" && !ctx.streamIsolated) lines.push(" stream transport: agy stream-json (shared CLI authentication, GLOBAL MCP registration: isolation unavailable)");
1417
1433
  const retiredAuth = path.join(os.homedir(), ".gemini", "antigravity-acp");
@@ -1944,7 +1960,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
1944
1960
  theme,
1945
1961
  {
1946
1962
  title: "Antigravity provider",
1947
- subtitle: `Config file: ${CONFIG_PATH} — changes save when the dialog closes`,
1963
+ subtitle: `Config file: ${configPath()} — changes save when the dialog closes`,
1948
1964
  rows,
1949
1965
  footer: "↑↓ navigate · Enter/Space cycle · Type to search · Esc close",
1950
1966
  onChange: (id, newValue) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "Gemini provider for Pi on the Antigravity ACP server (official Google ACP) or the stream-json agy CLI. Use antigravity/* models in Pi. Full /model picker support. Models runs Pi's tools. ToS safe to use.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -19,6 +19,7 @@ import { frameCarriesUsage } from "./events.js";
19
19
  import type { AgyUsage } from "../driver-types.js";
20
20
  import { redactText } from "../redact.js";
21
21
  import { JsonRpcResponseError, JsonRpcSession, JsonRpcTimeoutError } from "./jsonrpc.js";
22
+ import { mergeGateGroupIntoAcpHome } from "../approval-hook.js";
22
23
  import { removeStagedAgyHome, stageAgyHome } from "./home.js";
23
24
 
24
25
  export interface AcpMcpServer {
@@ -171,6 +172,17 @@ export class AcpConnection {
171
172
  const args = [...(this.#opts.binArgs ?? [])];
172
173
  if (this.#opts.isolateHome) {
173
174
  this.#stagedHome = stageAgyHome(typeof this.#opts.isolateHome === "object" ? this.#opts.isolateHome : {});
175
+ // Deliver this session's approval gate group into the staged home:
176
+ // the ACP server honors hooks from config/hooks.json there (issue
177
+ // #18). No-op when the gate is off. A merge failure must not leak
178
+ // the staged home: release it and rethrow so the turn fails closed
179
+ // the same way a spawn failure does.
180
+ try {
181
+ mergeGateGroupIntoAcpHome(this.#stagedHome);
182
+ } catch (err) {
183
+ this.#releaseHome();
184
+ throw err;
185
+ }
174
186
  args.push("--gemini-dir", this.#stagedHome);
175
187
  }
176
188
  let child: ChildProcess;
package/src/acp/driver.ts CHANGED
@@ -23,7 +23,8 @@ import type { UsageEstimate } from "../config.js";
23
23
  import { AcpConnection, type AcpMcpServer, type AcpPermissionRequest } from "./connection.js";
24
24
  import type { AcpPermissionHandler } from "./connection.js";
25
25
  import { JsonRpcTimeoutError } from "./jsonrpc.js";
26
- import { mapStopReason, mapUpdate, TextAccumulator, type AcpEditDiff } from "./events.js";
26
+ import { KNOWN_STOP_REASONS, mapStopReason, mapUpdate, TextAccumulator, type AcpEditDiff } from "./events.js";
27
+ import { redactText } from "../redact.js";
27
28
  import { estimateTokens, synthesizeUsage } from "./usage-estimate.js";
28
29
  import type {
29
30
  AgyUsage,
@@ -121,6 +122,11 @@ interface ActiveTurn {
121
122
  /** toolCallId → tool name + args + optional native diff (diff rides on
122
123
  * the pending tool_call frame; updates don't repeat it). */
123
124
  toolCalls: Map<string, { name: string; args: Record<string, unknown>; diff?: AcpEditDiff; mcpServer?: string }>;
125
+ /** Issue #18 F4: a native tool failed this turn. With an OK stop and no
126
+ * model output the caller would otherwise receive an empty final report
127
+ * (the reporter's stopReason "stop" after a failed run_command). */
128
+ sawToolError: boolean;
129
+ lastToolError: { name: string; message: string } | null;
124
130
  }
125
131
 
126
132
  /** Map our config knobs onto ACP session modes. skipPermissions=false also
@@ -371,6 +377,11 @@ export class AcpDriver implements TurnDriver {
371
377
  this.#emit(turn, { type: "usage", usage: settleUsage });
372
378
  }
373
379
  const mapped = mapStopReason(result.stopReason);
380
+ if (!KNOWN_STOP_REASONS.has(String(result.stopReason))) {
381
+ // "stop" (issue #18 F4) is not an ACP enum value; silence would
382
+ // hide exactly the server drift that produced the empty report.
383
+ this.#log("acp-unknown-stop-reason", { stopReason: result.stopReason });
384
+ }
374
385
  this.#settle(turn, {
375
386
  conversationId: turn.sessionId,
376
387
  status: mapped.status,
@@ -491,6 +502,13 @@ export class AcpDriver implements TurnDriver {
491
502
  const entry = turn.toolCalls.get(mapped.toolCallId);
492
503
  turn.toolCalls.delete(mapped.toolCallId);
493
504
  const name = entry?.name ?? "tool";
505
+ // Only native failures feed the silent-failure note: bridge tool
506
+ // errors are pi's own parking surface (the provider already surfaces
507
+ // them), not an agy-native tool the model failed to recover from.
508
+ if (!mapped.mcpServer) {
509
+ turn.sawToolError = true;
510
+ turn.lastToolError = { name, message: mapped.message };
511
+ }
494
512
  this.#emit(turn, { type: "tool_error", name, message: mapped.message, mcpServer: mapped.mcpServer ?? entry?.mcpServer, toolCallId: mapped.toolCallId });
495
513
  return;
496
514
  }
@@ -664,6 +682,8 @@ export class AcpDriver implements TurnDriver {
664
682
  overallDeadline: null,
665
683
  overallRemainingMs: null,
666
684
  toolCalls: new Map(),
685
+ sawToolError: false,
686
+ lastToolError: null,
667
687
  };
668
688
  return turn;
669
689
  }
@@ -769,6 +789,16 @@ export class AcpDriver implements TurnDriver {
769
789
  this.#emit(turn, { type: "text", delta: flushed });
770
790
  }
771
791
  outcome.response = turn.response.text;
792
+ // Issue #18 F4: a native tool failed, the model never spoke, and the
793
+ // server still ended OK (its "stop" is not even an ACP enum value).
794
+ // An empty final report hides the failure from the pi caller.
795
+ if (outcome.status === "OK" && !outcome.aborted && !outcome.response.trim() && turn.sawToolError && turn.lastToolError) {
796
+ // rawOutput rides unfiltered in the message; redact, collapse to one
797
+ // line and cap - this text lands in the transcript and later in the
798
+ // model's context digest.
799
+ const detail = redactText(turn.lastToolError.message).replace(/\s+/g, " ").trim().slice(0, 300);
800
+ outcome.response = `[bridge] The turn ended without model output. A native tool failed earlier in this turn: ${turn.lastToolError.name}${detail ? ` (${detail})` : ""}.`;
801
+ }
772
802
  // Gate B stopgap: synthesize usage on clean turns while the server sends
773
803
  // none. Runs BEFORE close so the usage activity drains through the
774
804
  // normal #nextActivity loop (provider maps it onto partial.usage).
package/src/acp/events.ts CHANGED
@@ -223,6 +223,17 @@ export function mapStopReason(stopReason: unknown): {
223
223
  }
224
224
  }
225
225
 
226
+ /** Stop reasons the ACP spec defines. Anything else hitting mapStopReason's
227
+ * default (OK) is server drift; the driver logs it (issue #18 F4: agy sent
228
+ * the stream-json-style "stop"). */
229
+ export const KNOWN_STOP_REASONS: ReadonlySet<string> = new Set([
230
+ "end_turn",
231
+ "cancelled",
232
+ "max_tokens",
233
+ "refusal",
234
+ "max_turn_requests",
235
+ ]);
236
+
226
237
  /** Defensive accumulation with the cumulative-resend port. Native agy streams
227
238
  * deltas, so on
228
239
  * a compliant server the resend branch stays inert; it exists because the
package/src/acp/home.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { bridgeDir } from "../config.js";
4
5
  import { isPidAlive } from "../mcp-server.js";
5
6
  import { bridgeServerEntry, bridgeServerName, readGlobalMcpConfig } from "../mcp-registration.js";
6
7
 
@@ -17,7 +18,7 @@ function linkDirectory(source: string, target: string): void {
17
18
  * stream-json engine adopting homes; renaming it would strand existing
18
19
  * installs' unswept dirs, so both engines stage under it. */
19
20
  export function agyHomeStagingDir(): string {
20
- return path.join(os.homedir(), ".pi", "agent", "antigravity-bridge", "acp-homes");
21
+ return path.join(bridgeDir(), "acp-homes");
21
22
  }
22
23
 
23
24
  export interface StageAgyHomeOptions {
@@ -12,6 +12,7 @@
12
12
  import fs from "node:fs";
13
13
  import os from "node:os";
14
14
  import path from "node:path";
15
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
15
16
 
16
17
  /** npm names of the audited pi permission packages (docs/TODO.md 2.4). */
17
18
  export const KNOWN_GATE_PACKAGES = [
@@ -82,22 +83,31 @@ function containsName(lower: string, name: string): boolean {
82
83
  /**
83
84
  * Detect installed third-party permission extensions.
84
85
  *
85
- * @param opts.home HOME override for tests.
86
+ * Pi-owned candidates (settings.json) resolve against pi's agent dir and
87
+ * CONFIG_DIR_NAME so isolated or rebranded homes are seen. On-disk markers
88
+ * follow each writer's real layout (verified in the published tarballs,
89
+ * 2026-11-19): gotgenes and monroewilliams resolve globals via getAgentDir(),
90
+ * while rhedbull and the project policy file hardcode literal .pi — those
91
+ * must stay literal or detection misses real installs.
92
+ *
93
+ * @param opts.home HOME override for the literal-.pi markers (tests).
86
94
  * @param opts.cwd project dir override for tests (project settings).
95
+ * @param opts.agentDir pi agent dir override (tests).
87
96
  * @param opts.settingsFiles extra settings files to scan (tests).
88
97
  */
89
98
  export function detectPermissionGateExtensions(
90
- opts: { home?: string; cwd?: string; settingsFiles?: string[] } = {},
99
+ opts: { home?: string; cwd?: string; agentDir?: string; settingsFiles?: string[] } = {},
91
100
  ): GateExtensionHit[] {
92
101
  const home = opts.home ?? os.homedir();
93
102
  const cwd = opts.cwd ?? process.cwd();
103
+ const agentDir = opts.agentDir ?? getAgentDir();
94
104
  const hits: GateExtensionHit[] = [];
95
105
  const seen = new Set<string>();
96
106
 
97
107
  const settingsCandidates = [
98
108
  ...(opts.settingsFiles ?? []),
99
- path.join(home, ".pi", "agent", "settings.json"),
100
- path.join(cwd, ".pi", "settings.json"),
109
+ path.join(agentDir, "settings.json"),
110
+ path.join(cwd, CONFIG_DIR_NAME, "settings.json"),
101
111
  ];
102
112
  for (const file of settingsCandidates) {
103
113
  for (const entry of packagesFrom(file)) {
@@ -109,13 +119,18 @@ export function detectPermissionGateExtensions(
109
119
  }
110
120
  }
111
121
 
112
- // Known config-file markers from the audit. Presence of the config does
113
- // not prove the extension is installed, but every audited package writes
114
- // its config only after install + first run, which is evidence enough for
115
- // an opt-in default.
122
+ // On-disk config markers. Pi-resolved globals first: gotgenes reads
123
+ // getGlobalConfigDir(getAgentDir()); monroewilliams writes
124
+ // join(getAgentDir(), "pi-permissions.jsonc") (its default agent dir is
125
+ // getAgentDir(), so the old literal ~/.agent marker never matched any
126
+ // real install). Literal .pi below: rhedbull hardcodes homedir()/.pi,
127
+ // and both writers of the project policy file hardcode cwd/.pi.
128
+ // Marker presence is install evidence, not proof: every audited package
129
+ // writes its config only after install + first run, which is evidence
130
+ // enough for an opt-in default.
116
131
  const markers: Array<{ file: string; name: string }> = [
117
- { file: path.join(home, ".pi", "agent", "extensions", "pi-permission-system"), name: "@gotgenes/pi-permission-system" },
118
- { file: path.join(home, ".agent", "pi-permissions.jsonc"), name: "@monroewilliams/pi-permission-system" },
132
+ { file: path.join(agentDir, "extensions", "pi-permission-system"), name: "@gotgenes/pi-permission-system" },
133
+ { file: path.join(agentDir, "pi-permissions.jsonc"), name: "@monroewilliams/pi-permission-system" },
119
134
  { file: path.join(home, ".pi", "agent", "extensions", "permissions.json"), name: "@rhedbull/pi-permissions" },
120
135
  { file: path.join(cwd, ".pi", "agent", "pi-permissions.jsonc"), name: "@gotgenes/pi-permission-system" },
121
136
  ];
@@ -87,14 +87,32 @@ export interface ShadowMapping {
87
87
  }
88
88
 
89
89
  /** Map an agy native tool call (hook stdin payload) onto the shadow surface.
90
- * Field names follow the TODO 2.5 table: create_file is live-captured (F1);
91
- * the edit-class arg names are docs-attested and degrade gracefully - a
92
- * wrong guess only weakens the confirm-dialog text, never the decision
93
- * (the tool runs in agy's loop either way). Unknown names return null:
94
- * read-only tools are not gated. */
90
+ * Field names are runtime-attested: create_file is live-captured (F1), the
91
+ * write/edit pairs come from agy 1.5.11 PreToolUse captures (issue #18,
92
+ * Path/Content and Path/Target/Replacement) with the older docs-attested
93
+ * names kept as fallbacks. A gated write/edit whose target path cannot be
94
+ * resolved returns null - the caller denies before parking, because an
95
+ * empty-path shadow is decision garbage for path-prefix permission
96
+ * extensions. Other unknown names return null: read-only tools are not
97
+ * gated. */
95
98
  export function mapNativeToShadow(name: string, args: Record<string, unknown>): ShadowMapping | null {
96
99
  const a = args ?? {};
97
100
  const str = (v: unknown): string => (typeof v === "string" ? v : v === undefined || v === null ? "" : String(v));
101
+ const pick = (...vals: unknown[]): string => {
102
+ for (const v of vals) {
103
+ const s = str(v);
104
+ if (s !== "") return s;
105
+ }
106
+ return "";
107
+ };
108
+ const targetPath = (fallback: unknown): string | null => {
109
+ // A target path must be a non-empty string; anything else (numbers,
110
+ // objects, whitespace) is an unresolved target and denies below.
111
+ for (const v of [a.Path, fallback]) {
112
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
113
+ }
114
+ return null;
115
+ };
98
116
  switch (name) {
99
117
  case "run_command": {
100
118
  const input: Record<string, unknown> = { command: str(a.CommandLine) };
@@ -102,29 +120,36 @@ export function mapNativeToShadow(name: string, args: Record<string, unknown>):
102
120
  return { shadow: "bash", input };
103
121
  }
104
122
  case "write_to_file":
105
- case "create_file":
106
- return { shadow: "write", input: { path: str(a.TargetFile), content: str(a.CodeContent) } };
123
+ case "write_file":
124
+ case "create_file": {
125
+ const path = targetPath(a.TargetFile);
126
+ if (path === null) return null;
127
+ return { shadow: "write", input: { path, content: pick(a.Content, a.CodeContent) } };
128
+ }
107
129
  case "replace_file_content":
108
- case "edit_file":
130
+ case "edit_file": {
131
+ const path = targetPath(a.TargetFile);
132
+ if (path === null) return null;
109
133
  return {
110
134
  shadow: "edit",
111
135
  input: {
112
- path: str(a.TargetFile),
113
- edits: [{ oldText: str(a.SearchText), newText: str(a.ReplacementContent) }],
136
+ path,
137
+ edits: [{ oldText: pick(a.Target, a.SearchText), newText: pick(a.Replacement, a.ReplacementContent) }],
114
138
  },
115
139
  };
140
+ }
116
141
  case "multi_replace_file_content": {
142
+ const path = targetPath(a.TargetFile);
143
+ if (path === null) return null;
117
144
  const chunks = Array.isArray(a.ReplacementChunks) ? a.ReplacementChunks : [];
118
- return {
119
- shadow: "edit",
120
- input: {
121
- path: str(a.TargetFile),
122
- edits: chunks.map((c) => {
123
- const chunk = (c ?? {}) as Record<string, unknown>;
124
- return { oldText: str(chunk.SearchText), newText: str(chunk.ReplacementContent) };
125
- }),
126
- },
127
- };
145
+ const edits = chunks.map((c) => {
146
+ const chunk = (c ?? {}) as Record<string, unknown>;
147
+ return { oldText: pick(chunk.Target, chunk.SearchText), newText: pick(chunk.Replacement, chunk.ReplacementContent) };
148
+ });
149
+ // Fail closed: a path with no resolvable chunk is a shadow edit
150
+ // carrying no change information - deny instead of parking it.
151
+ if (edits.length === 0 || edits.every((e) => e.oldText === "" && e.newText === "")) return null;
152
+ return { shadow: "edit", input: { path, edits } };
128
153
  }
129
154
  default:
130
155
  return null;
@@ -65,9 +65,10 @@ function gateGroupPid(group: unknown): number | null {
65
65
  return m ? Number(m[1]) : null;
66
66
  }
67
67
 
68
- /** agy native tools worth gating: everything that mutates the machine. */
68
+ /** agy native tools worth gating: everything that mutates the machine.
69
+ * Includes both the legacy and the agy 1.5.11+ tool families (issue #18). */
69
70
  export const GATED_AGY_TOOLS =
70
- "create_file|write_to_file|replace_file_content|multi_replace_file_content|edit_file|run_command";
71
+ "create_file|write_to_file|write_file|replace_file_content|multi_replace_file_content|edit_file|run_command";
71
72
 
72
73
  /** The same list as a set, for the bridge's POST /approval validation: a
73
74
  * payload for anything else is answered with a direct deny (defense in
@@ -222,6 +223,60 @@ export function stageGateHooks(dir: string, opts: StageOptions): StageResult {
222
223
  return { wrote: true };
223
224
  }
224
225
 
226
+ /** Deliver this session's gate group into a staged ACP home's
227
+ * config/hooks.json. The staged home is private per connection (stageAgyHome),
228
+ * so foreign groups - the user's global hooks, copied in by stageAgyHome -
229
+ * are preserved and only this pid's group is added. An unparsable existing
230
+ * file is gate-only overwritten: agy could not have read it either. No-op
231
+ * only when the per-pid gate file is ABSENT (gate off at load); a staged
232
+ * file that exists but cannot be read, parsed, or does not carry this
233
+ * session's usable group throws, because running the spawn ungated while
234
+ * the gate is on would fail open (issue #18).
235
+ * mergeGateGroupIntoAcpHome's delivery is probed live on agy 1.5.12
236
+ * (scripts/probe-acp-hooks.mjs). */
237
+ export function mergeGateGroupIntoAcpHome(stagedHome: string, sourceDir: string = bridgeMcpConfigDir()): StageResult {
238
+ let staged: Record<string, unknown>;
239
+ try {
240
+ staged = JSON.parse(fs.readFileSync(gateHooksFile(sourceDir), "utf8")) as Record<string, unknown>;
241
+ } catch (err) {
242
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return { wrote: false, reason: "no staged gate" };
243
+ throw err;
244
+ }
245
+ // The source file is session-private (per-pid dir), so a parsable file
246
+ // without this session's usable group means something rewrote it between
247
+ // staging and merge - spawning ungated then would fail open.
248
+ const group: unknown = staged[gateGroupKey()];
249
+ if (!group || typeof group !== "object") {
250
+ throw new Error(`staged approval-gate file has no usable group for this session (${gateGroupKey()}); failing closed`);
251
+ }
252
+ const target = path.join(stagedHome, "config", "hooks.json");
253
+ let merged: Record<string, unknown> = {};
254
+ try {
255
+ const existing = JSON.parse(fs.readFileSync(target, "utf8")) as unknown;
256
+ if (existing && typeof existing === "object" && !Array.isArray(existing)) {
257
+ merged = existing as Record<string, unknown>;
258
+ }
259
+ } catch {
260
+ /* absent or unparsable: the merge result is gate-only */
261
+ }
262
+ merged[gateGroupKey()] = group;
263
+ const next = JSON.stringify(merged, null, 2) + "\n";
264
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
265
+ const tmp = `${target}.${process.pid}.tmp`;
266
+ try {
267
+ fs.writeFileSync(tmp, next, { mode: 0o600 });
268
+ fs.renameSync(tmp, target);
269
+ } catch (err) {
270
+ try {
271
+ fs.unlinkSync(tmp);
272
+ } catch {
273
+ /* nothing */
274
+ }
275
+ throw err;
276
+ }
277
+ return { wrote: true };
278
+ }
279
+
225
280
  /** Remove the private gate hooks file. The rest of the per-pid dir (the MCP
226
281
  * config) is managed by the bridge server lifecycle and stays until close. */
227
282
  export function removeGateHooks(dir: string = bridgeMcpConfigDir()): StageResult {
package/src/ask-tool.ts CHANGED
@@ -16,7 +16,7 @@ import { randomBytes } from "node:crypto";
16
16
  import * as fs from "node:fs";
17
17
  import * as path from "node:path";
18
18
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
19
- import { buildSessionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
19
+ import { buildSessionContext } from "@earendil-works/pi-coding-agent";
20
20
  import { Text } from "@earendil-works/pi-tui";
21
21
  import { contentText, type ThinkingLevel } from "@earendil-works/pi-ai";
22
22
  import { Type } from "typebox";
@@ -41,7 +41,7 @@ import {
41
41
  type ModelEntry,
42
42
  type Mode,
43
43
  } from "@estebanforge/pi-ask-shared";
44
- import { loadConfig, type AgyMode, type ThinkingTier } from "./config.js";
44
+ import { extensionsDataDir, loadConfig, type AgyMode, type ThinkingTier } from "./config.js";
45
45
  import { redactText } from "./redact.js";
46
46
  import { acquireBridgeSuppression } from "./mcp-registration.js";
47
47
  import { AGY_EFFORT_ORDER, spawnAgyModelsRaw, toAgyEffort } from "./models.js";
@@ -1169,11 +1169,10 @@ function renderAgentMessagesMarkdown(messages: readonly unknown[]): string {
1169
1169
  return lines.join("\n");
1170
1170
  }
1171
1171
 
1172
- /** Centralized scratch dir for full-context exports, following the
1173
- * ~/.pi/extensions-data/<author>/<extension>/ convention (see pi-token-cost-ledger).
1174
- * Derived from getAgentDir() so rebranded distros resolve correctly. */
1172
+ /** Centralized scratch dir for full-context exports (see src/config.ts
1173
+ * extensionsDataDir). */
1175
1174
  function askContextDir(): string {
1176
- return path.join(path.dirname(getAgentDir()), "extensions-data", "estebanforge", "pi-antigravity-bridge");
1175
+ return extensionsDataDir();
1177
1176
  }
1178
1177
 
1179
1178
  interface AgyDetails {
package/src/config.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Runtime config for the antigravity provider. Persisted at
2
- // ~/.pi/agent/antigravity-bridge/config.json so the /agy command can
2
+ // <agentDir>/antigravity-bridge/config.json so the /agy command can
3
3
  // toggle settings that take effect on the next turn.
4
4
  //
5
5
  // Knobs today:
@@ -11,31 +11,32 @@
11
11
  // and one-off runs can force a setting without editing the file.
12
12
 
13
13
  import fs from "node:fs";
14
- import os from "node:os";
15
14
  import path from "node:path";
15
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
16
16
  import { normalizeAgyAgentName } from "./agents.js";
17
17
 
18
- const CONFIG_PATH = path.join(
19
- os.homedir(),
20
- ".pi",
21
- "agent",
22
- "antigravity-bridge",
23
- "config.json",
24
- );
18
+ /** pi's agent dir (env override PI_CODING_AGENT_DIR, else ~/.pi/agent); every
19
+ * bridge-owned path derives from it so isolated or rebranded pi homes keep
20
+ * their state together (issue #17). */
21
+ export function bridgeDir(agentDir: string = getAgentDir()): string {
22
+ return path.join(agentDir, "antigravity-bridge");
23
+ }
24
+
25
+ export function configPath(agentDir: string = getAgentDir()): string {
26
+ return path.join(bridgeDir(agentDir), "config.json");
27
+ }
28
+
29
+ /** Scoped extensions-data convention shared with other EstebanForge
30
+ * extensions: <configRoot>/extensions-data/<author>/<name>, anchored at
31
+ * dirname(getAgentDir()) so it relocates with the agent dir too. */
32
+ export function extensionsDataDir(agentDir: string = getAgentDir()): string {
33
+ return path.join(path.dirname(agentDir), "extensions-data", "estebanforge", "pi-antigravity-bridge");
34
+ }
25
35
 
26
36
  /** Daily debug logs land here, sorted by day, for post-mortems and user
27
- * support (see src/daily-log.ts). Same homedir convention as CONFIG_PATH;
28
- * lives under the scoped extensions-data convention shared with other
29
- * EstebanForge extensions. */
30
- export function logsDir(): string {
31
- return path.join(
32
- os.homedir(),
33
- ".pi",
34
- "extensions-data",
35
- "estebanforge",
36
- "pi-antigravity-bridge",
37
- "logs",
38
- );
37
+ * support (see src/daily-log.ts). */
38
+ export function logsDir(agentDir: string = getAgentDir()): string {
39
+ return path.join(extensionsDataDir(agentDir), "logs");
39
40
  }
40
41
 
41
42
  /** Native `agy acp` is the default for new installs; stream-json remains
@@ -278,21 +279,21 @@ function readConfigFile(configPath: string): Partial<AgyConfig> {
278
279
  /** Strip the retired acp.bin key from the raw config file; returns true when
279
280
  * removed. Raw passthrough on purpose (no defaults merge): users keep their
280
281
  * minimal hand-edited shape instead of gaining the full default set. */
281
- export function removeLegacyAcpBin(configPath: string = CONFIG_PATH): boolean {
282
- const file = readConfigFile(configPath) as Record<string, unknown>;
282
+ export function removeLegacyAcpBin(configFile: string = configPath()): boolean {
283
+ const file = readConfigFile(configFile) as Record<string, unknown>;
283
284
  if (!file.acp || typeof file.acp !== "object" || Array.isArray(file.acp)) return false;
284
285
  const acp = file.acp as Record<string, unknown>;
285
286
  if (!("bin" in acp)) return false;
286
287
  delete acp.bin;
287
288
  // Rename would replace a dotfiles-managed symlink with a regular file;
288
289
  // write through the resolved target so the link survives.
289
- writeConfigJson(fs.realpathSync(configPath), file);
290
+ writeConfigJson(fs.realpathSync(configFile), file);
290
291
  return true;
291
292
  }
292
293
 
293
294
  /** Load config merged over defaults. Env vars override the file when set. */
294
- export function loadConfig(configPath: string = CONFIG_PATH): AgyConfig {
295
- let file: Partial<AgyConfig> = readConfigFile(configPath);
295
+ export function loadConfig(configFile: string = configPath()): AgyConfig {
296
+ let file: Partial<AgyConfig> = readConfigFile(configFile);
296
297
 
297
298
  // Env overrides file (matches the skipPermissions pattern).
298
299
  // The naive OR `env === "plan" || file.mode === "plan"` would ignore an
@@ -305,7 +306,7 @@ export function loadConfig(configPath: string = CONFIG_PATH): AgyConfig {
305
306
  // the acp default is for new installs only - an existing install keeps
306
307
  // the legacy stream-json engine. existsSync is false on EACCES too, which reads as fresh
307
308
  // and picks acp; an unreadable config dir is a broken install either way.
308
- const freshInstall = !fs.existsSync(configPath);
309
+ const freshInstall = !fs.existsSync(configFile);
309
310
  const engineFallback = freshInstall || file.engine !== undefined ? DEFAULT_ENGINE : "stream-json";
310
311
  const engine = narrowEngine(String(process.env.AGY_ENGINE ?? file.engine ?? engineFallback).toLowerCase());
311
312
 
@@ -484,8 +485,8 @@ function writeConfigJson(configPath: string, value: unknown): void {
484
485
  * legacy keys (acp.permissions) that loadConfig normalization drops. */
485
486
  export type ConfigPatch = Partial<Omit<AgyConfig, "acp">> & { acp?: Partial<AcpConfig> };
486
487
 
487
- export function saveConfig(patch: ConfigPatch, configPath: string = CONFIG_PATH): AgyConfig {
488
- const file = readConfigFile(configPath);
488
+ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()): AgyConfig {
489
+ const file = readConfigFile(configFile);
489
490
  // Null-safe on nested objects: a hand-edited or legacy file can carry
490
491
  // "acp": null; loadConfig tolerates it, so must saveConfig. Key presence
491
492
  // triggers normalization (a null becomes the default shape, never null).
@@ -497,7 +498,7 @@ export function saveConfig(patch: ConfigPatch, configPath: string = CONFIG_PATH)
497
498
  // write the acp default into an existing install's file on any unrelated
498
499
  // save, switching an existing install to ACP on the next start.
499
500
  const persistedEngine = patch.engine ?? file.engine
500
- ?? (fs.existsSync(configPath) ? "stream-json" : DEFAULT_ENGINE);
501
+ ?? (fs.existsSync(configFile) ? "stream-json" : DEFAULT_ENGINE);
501
502
  const { acp: patchAcp, ...restPatch } = patch;
502
503
  const mergedAcp: AcpConfig = {
503
504
  usageEstimate: patchAcp?.usageEstimate ?? fileAcp.usageEstimate ?? DEFAULTS.acp.usageEstimate,
@@ -517,8 +518,6 @@ export function saveConfig(patch: ConfigPatch, configPath: string = CONFIG_PATH)
517
518
  acp: mergedAcp,
518
519
  engine: narrowEngine(String(persistedEngine).toLowerCase()),
519
520
  };
520
- writeConfigJson(configPath, next);
521
+ writeConfigJson(configFile, next);
521
522
  return next;
522
523
  }
523
-
524
- export { CONFIG_PATH };
@@ -1,6 +1,8 @@
1
1
  // G8: surface agy's file edits as a diff in pi's thinking stream.
2
2
  //
3
- // agy edits with its OWN native `write_to_file` (full-file content), inside a
3
+ // agy edits with its OWN native full-file tools (write_to_file on legacy
4
+ // builds; write_file {Path, Content} on agy 1.5.11+, both parsed by
5
+ // parseEditToolInput's field-shape regexes, not by tool name), inside a
4
6
  // closed tool loop that lands changes on disk. pi's native colored diff viewer
5
7
  // is unreachable for agy turns (it is part of the tool-call lifecycle, and the
6
8
  // provider emits no toolCall blocks by design), so we compute a line-numbered
@@ -18,6 +18,7 @@
18
18
  import fs from "node:fs";
19
19
  import os from "node:os";
20
20
  import path from "node:path";
21
+ import { extensionsDataDir } from "./config.js";
21
22
 
22
23
  /** Name convention for the bridge's per-pid server entries. */
23
24
  export function bridgeServerName(pid: number): string {
@@ -174,18 +175,11 @@ export interface SuppressionMarker {
174
175
  delegators: Record<string, { since: number }>;
175
176
  }
176
177
 
177
- /** Marker path, mirroring the extensions-data convention (src/config.ts
178
- * logsDir). Lives OUTSIDE ~/.gemini so agy's watched config dir stays
179
- * untouched. */
180
- export function suppressionMarkerPath(home: string = os.homedir()): string {
181
- return path.join(
182
- home,
183
- ".pi",
184
- "extensions-data",
185
- "estebanforge",
186
- "pi-antigravity-bridge",
187
- "suppression.json",
188
- );
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");
189
183
  }
190
184
 
191
185
  /** A SIGKILLed pi can leave its marker entry behind, and pid reuse could
package/src/mcp-server.ts CHANGED
@@ -20,7 +20,6 @@
20
20
 
21
21
  import http from "node:http";
22
22
  import fs from "node:fs";
23
- import os from "node:os";
24
23
  import path from "node:path";
25
24
  import crypto from "node:crypto";
26
25
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -32,6 +31,7 @@ import {
32
31
  SUPPORTED_PROTOCOL_VERSIONS,
33
32
  } from "@modelcontextprotocol/sdk/types.js";
34
33
  import { GATED_AGY_TOOL_SET } from "./approval-hook.js";
34
+ import { bridgeDir } from "./config.js";
35
35
 
36
36
  /** Tools we do NOT expose to agy: it would just error (the provider is already
37
37
  * antigravity, so the tool's own guard refuses; advertising it is noise). */
@@ -137,12 +137,10 @@ function clampProtocolVersionHeader(req: http.IncomingMessage): void {
137
137
  }
138
138
  }
139
139
 
140
- const BRIDGE_BASE = path.join(os.homedir(), ".pi", "agent", "antigravity-bridge");
141
-
142
140
  /** Per-process config dir. Each pi session owns its own file, so concurrent
143
141
  * sessions never race on or cross-route through one shared config. */
144
142
  export function bridgeMcpConfigDir(): string {
145
- return path.join(BRIDGE_BASE, `agy-mcp-${process.pid}`);
143
+ return path.join(bridgeDir(), `agy-mcp-${process.pid}`);
146
144
  }
147
145
 
148
146
  function bridgeMcpConfigPath(): string {
@@ -166,7 +164,7 @@ export function isPidAlive(pid: number): boolean {
166
164
  }
167
165
 
168
166
  /** Best-effort cleanup of stale per-pid dirs left by crashed sessions. */
169
- export function sweepStaleBridgeDirs(baseDir: string = BRIDGE_BASE, alive: (pid: number) => boolean = isPidAlive): void {
167
+ export function sweepStaleBridgeDirs(baseDir: string = bridgeDir(), alive: (pid: number) => boolean = isPidAlive): void {
170
168
  let entries: string[];
171
169
  try {
172
170
  entries = fs.readdirSync(baseDir);
package/src/models.ts CHANGED
@@ -20,10 +20,11 @@
20
20
 
21
21
  import { spawn } from "node:child_process";
22
22
  import fs from "node:fs";
23
- import os from "node:os";
24
23
  import path from "node:path";
25
24
  import type { Api, Model, ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
26
25
 
26
+ import { bridgeDir } from "./config.js";
27
+
27
28
  const DISCOVERY_TIMEOUT_MS = 8_000;
28
29
 
29
30
  /** Stdout ceiling for `agy models`. Real output is a few KB of ASCII slugs;
@@ -192,20 +193,16 @@ export async function spawnAgyModelsRaw(binary: string): Promise<string> {
192
193
  // --- catalog cache ----------------------------------------------------------
193
194
  //
194
195
  // `agy models` can take seconds (OAuth refresh, cold start) and its output
195
- // rarely changes. We persist it to ~/.pi/agent/antigravity-bridge/models-
196
+ // rarely changes. We persist it to <agentDir>/antigravity-bridge/models-
196
197
  // cache.json with a short TTL so reloads serve instantly and only re-spawn in
197
198
  // the background when stale. Only successful (non-empty) output is cached, so
198
199
  // a broken agy is never sticky.
199
200
 
200
201
  export const MODELS_CACHE_TTL_MS = 5 * 60_000;
201
202
 
202
- const MODELS_CACHE_PATH = path.join(
203
- os.homedir(),
204
- ".pi",
205
- "agent",
206
- "antigravity-bridge",
207
- "models-cache.json",
208
- );
203
+ function modelsCachePath(): string {
204
+ return path.join(bridgeDir(), "models-cache.json");
205
+ }
209
206
 
210
207
  interface ModelsCache {
211
208
  raw: string;
@@ -213,7 +210,7 @@ interface ModelsCache {
213
210
  }
214
211
 
215
212
  /** Read and validate the models cache. Returns null when missing or corrupt. */
216
- function readModelsCache(cachePath: string = MODELS_CACHE_PATH): ModelsCache | null {
213
+ function readModelsCache(cachePath: string = modelsCachePath()): ModelsCache | null {
217
214
  try {
218
215
  const parsed = JSON.parse(fs.readFileSync(cachePath, "utf8")) as unknown;
219
216
  if (
@@ -233,7 +230,7 @@ function readModelsCache(cachePath: string = MODELS_CACHE_PATH): ModelsCache | n
233
230
 
234
231
  /** Atomically persist the raw catalog text (temp + rename, mode 0o600).
235
232
  * Best-effort: a write failure just means the next load re-spawns. */
236
- function writeModelsCache(raw: string, cachePath: string = MODELS_CACHE_PATH): void {
233
+ function writeModelsCache(raw: string, cachePath: string = modelsCachePath()): void {
237
234
  fs.mkdirSync(path.dirname(cachePath), { recursive: true });
238
235
  const tmp = `${cachePath}.${process.pid}.tmp`;
239
236
  try {
@@ -254,7 +251,7 @@ function writeModelsCache(raw: string, cachePath: string = MODELS_CACHE_PATH): v
254
251
  * the next load sees fresh data without this one having to wait on agy. */
255
252
  export function refreshModelsInBackground(
256
253
  binary: string,
257
- cachePath: string = MODELS_CACHE_PATH,
254
+ cachePath: string = modelsCachePath(),
258
255
  ): void {
259
256
  void spawnAgyModelsRaw(binary)
260
257
  .then((raw) => {
@@ -277,7 +274,7 @@ export function refreshModelsInBackground(
277
274
  * Gemini entries (agy missing/auth-failed). */
278
275
  export async function loadModelCatalogRaw(
279
276
  binary: string,
280
- cachePath: string = MODELS_CACHE_PATH,
277
+ cachePath: string = modelsCachePath(),
281
278
  ): Promise<string> {
282
279
  const cache = readModelsCache(cachePath);
283
280
  if (cache) {
@@ -41,9 +41,13 @@ import os from "node:os";
41
41
  import { execSync } from "node:child_process";
42
42
  import { fileURLToPath } from "node:url";
43
43
 
44
+ import { bridgeDir } from "./config.js";
45
+
44
46
  const PACKAGE_NAME = "@earendil-works/pi-coding-agent";
45
- const BRIDGE_BASE = path.join(os.homedir(), ".pi", "agent", "antigravity-bridge");
46
- export const PATCH_BACKUP_DIR = path.join(BRIDGE_BASE, "pi-patch-backup");
47
+
48
+ export function patchBackupDir(): string {
49
+ return path.join(bridgeDir(), "pi-patch-backup");
50
+ }
47
51
 
48
52
  /** One insertion site in one compiled file. */
49
53
  interface PatchSite {
@@ -424,7 +428,7 @@ function resolveRoot(opts: { root?: string }): { root: string; version: string }
424
428
  }
425
429
 
426
430
  function backupBaseOf(opts: { backupBase?: string }): string {
427
- return opts.backupBase ?? PATCH_BACKUP_DIR;
431
+ return opts.backupBase ?? patchBackupDir();
428
432
  }
429
433
 
430
434
  /** Report the current patch state without changing anything. */
package/src/provider.ts CHANGED
@@ -900,7 +900,7 @@ export class ToolRoundTrips {
900
900
  ? payload.toolCall.args
901
901
  : {}) as Record<string, unknown>;
902
902
  const mapped = mapNativeToShadow(native, args);
903
- if (!mapped) return deny(`tool ${native} is not in the approval matcher set`);
903
+ if (!mapped) return deny(`tool ${native} did not map to a shadow call (ungated or unresolved target path)`);
904
904
  const entry: PendingRoundTrip = {
905
905
  kind: "approval",
906
906
  name: mapped.shadow,
@@ -1248,10 +1248,10 @@ function emitToolUse(
1248
1248
  }
1249
1249
 
1250
1250
  /** ACP edit-class tool names that carry a file-path arg and land the file on
1251
- * disk (observed live: edit_file, create_file). Read/execute tools also
1252
- * match the arg-shape heuristic but produce no diff (unchanged content), so
1253
- * the gate avoids mislabeling them as edits. */
1254
- const ACP_EDIT_TOOLS = new Set(["edit_file", "create_file", "write_to_file"]);
1251
+ * disk (observed live: edit_file, create_file, write_file on agy 1.5.11).
1252
+ * Read/execute tools also match the arg-shape heuristic but produce no diff
1253
+ * (unchanged content), so the gate avoids mislabeling them as edits. */
1254
+ const ACP_EDIT_TOOLS = new Set(["edit_file", "create_file", "write_to_file", "write_file"]);
1255
1255
 
1256
1256
  export function consumeActivity(
1257
1257
  stream: AssistantMessageEventStream,
package/src/sessions.ts CHANGED
@@ -6,19 +6,15 @@
6
6
  //
7
7
  // The key is options.sessionId when pi provides it, else the cwd (single-
8
8
  // conversation-per-process fallback). Stored at
9
- // ~/.pi/agent/antigravity-bridge/sessions.json with atomic rename.
9
+ // <agentDir>/antigravity-bridge/sessions.json with atomic rename.
10
10
 
11
11
  import fs from "node:fs";
12
- import os from "node:os";
13
12
  import path from "node:path";
13
+ import { bridgeDir } from "./config.js";
14
14
 
15
- const STORE_PATH = path.join(
16
- os.homedir(),
17
- ".pi",
18
- "agent",
19
- "antigravity-bridge",
20
- "sessions.json",
21
- );
15
+ function defaultStorePath(): string {
16
+ return path.join(bridgeDir(), "sessions.json");
17
+ }
22
18
 
23
19
  export interface AgySession {
24
20
  conversationId: string;
@@ -85,7 +81,7 @@ export class SessionStore {
85
81
  private readonly removed = new Set<string>();
86
82
  private writeChain: Promise<void> = Promise.resolve();
87
83
 
88
- constructor(storePath: string = STORE_PATH) {
84
+ constructor(storePath: string = defaultStorePath()) {
89
85
  this.path = storePath;
90
86
  this.load();
91
87
  }
package/src/skills.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  import fs from "node:fs";
10
10
  import os from "node:os";
11
11
  import path from "node:path";
12
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
12
13
 
13
14
  export const ACTIVATE_SKILL_TOOL_NAME = "activate_skill";
14
15
 
@@ -41,9 +42,10 @@ function parseFrontmatter(raw: string): { name?: string; description?: string }
41
42
  // "docs/skills.md - Locations") so the bridge's activate_skill catalog
42
43
  // matches the [Skills] list pi shows in its system prompt:
43
44
  //
44
- // - Global: ~/.pi/agent/skills (pi style) and ~/.agents/skills (agents style,
45
+ // - Global: <agentDir>/skills (pi style) and ~/.agents/skills (agents style,
45
46
  // the cross-harness standard).
46
- // - Project: .pi/skills (pi style) and .agents/skills in cwd + ancestors up
47
+ // - Project: <project>/.pi/skills (pi style; CONFIG_DIR_NAME, so rebranded
48
+ // distros relocate it) and .agents/skills in cwd + ancestors up
47
49
  // to the git repo root (agents style).
48
50
  // - Both styles discover every directory holding a SKILL.md, recursively;
49
51
  // grouping folders (no SKILL.md) are descended into and a skill's contents
@@ -64,16 +66,29 @@ export interface SkillLocation {
64
66
 
65
67
  const MAX_DEPTH = 16; // symlink-loop insurance; real catalogs nest 1-2 levels
66
68
 
67
- /** Ordered skill locations for a session: pi global dirs, then project dirs
68
- * (project `.agents/skills` walks cwd ancestors up to the git root). */
69
- export function skillLocations(projectDir?: string, home: string = os.homedir()): SkillLocation[] {
69
+ export interface SkillScanOptions {
70
+ /** Project root: adds the project pi-skills dir and ancestor .agents/skills
71
+ * dirs (walked up to the git root). */
72
+ projectDir?: string;
73
+ /** HOME override for the cross-harness ~/.agents/skills dir (tests). */
74
+ home?: string;
75
+ /** pi agent dir override for pi's user skills dir (tests). */
76
+ agentDir?: string;
77
+ }
78
+
79
+ /** Ordered skill locations for a session, mirroring pi's own loader:
80
+ * <agentDir>/skills, then cross-harness ~/.agents/skills; with a projectDir
81
+ * also <project>/<CONFIG_DIR_NAME>/skills and each ancestor's .agents/skills. */
82
+ export function skillLocations(opts: SkillScanOptions = {}): SkillLocation[] {
83
+ const home = opts.home ?? os.homedir();
84
+ const agentDir = opts.agentDir ?? getAgentDir();
70
85
  const out: SkillLocation[] = [
71
- { dir: path.join(home, ".pi", "agent", "skills"), style: "pi" },
86
+ { dir: path.join(agentDir, "skills"), style: "pi" },
72
87
  { dir: path.join(home, ".agents", "skills"), style: "agents" },
73
88
  ];
74
- if (!projectDir) return out;
75
- out.push({ dir: path.join(projectDir, ".pi", "skills"), style: "pi" });
76
- let dir = path.resolve(projectDir);
89
+ if (!opts.projectDir) return out;
90
+ out.push({ dir: path.join(opts.projectDir, CONFIG_DIR_NAME, "skills"), style: "pi" });
91
+ let dir = path.resolve(opts.projectDir);
77
92
  for (;;) {
78
93
  out.push({ dir: path.join(dir, ".agents", "skills"), style: "agents" });
79
94
  if (path.dirname(dir) === dir || fs.existsSync(path.join(dir, ".git"))) break;
@@ -144,11 +159,11 @@ function scanLocation(loc: SkillLocation): SkillLite[] {
144
159
  }
145
160
 
146
161
  /** pi-faithful skill catalog: every skill pi itself would load, deduped by
147
- * name (first wins). `home` is injectable for tests. */
148
- export function scanSkills(projectDir?: string, home: string = os.homedir()): SkillLite[] {
162
+ * name (first wins). All roots are injectable for tests. */
163
+ export function scanSkills(opts: SkillScanOptions = {}): SkillLite[] {
149
164
  const seen = new Set<string>();
150
165
  const out: SkillLite[] = [];
151
- for (const loc of skillLocations(projectDir, home)) {
166
+ for (const loc of skillLocations(opts)) {
152
167
  for (const skill of scanLocation(loc)) {
153
168
  if (seen.has(skill.name)) continue;
154
169
  seen.add(skill.name);