@estebanforge/pi-antigravity-bridge 1.13.1 → 1.13.3

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,29 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.13.3] - 2026-11-23
6
+
7
+ ### Fixed
8
+
9
+ - **Multiple sessions in one process now share one bridge runtime instead of clobbering each other's provider and `process.pid` artifacts.** Subagent or multi-session spawns in the same JS realm previously overwrote the global provider registration and deleted `agy-mcp-<pid>`, `approval-hook-<pid>.js`, and global `mcp_config.json` entries on child shutdown while the parent was still running. A shared realm runtime (`src/runtime.ts`, `Symbol.for`-branded to survive `/reload`) now owns one `SessionStore`, routes `streamSimple` by live `options.sessionId` (failing closed when multiple sessions are active and unmatched), serves one MCP listener with per-session route tokens (`addRoute`), isolates per-factory `activeUi` and lazy `conversationId` attribution, stages gate hooks idempotently per `session_start`, and tears down per-realm artifacts (including keep-alive sockets) in a `try/finally` only when the last session leaves.
10
+
11
+ - **The approval gate no longer lets `skipPermissions` auto-allow `session/request_permission` on ACP turns.** Staged gate hooks do not stop `agy`'s own permission path, so a gate-active turn with `skipPermissions` previously bypassed the gate; when the gate is active, `approvals.mode` and the permission dialog now decide (`allow` answers allow, `deny`/headless denies, otherwise the dialog prompts). Permission log events also include the tool kind, redacted title, `toolCallId`, and field names.
12
+ - **`SessionStore.flush()` now drains queued session-binding writes on `session_shutdown`.** Headless/print runs exiting right after the final bind can no longer drop the last `sessions.json` update before the process exits.
13
+ - **`read_file` steps on stream-json now re-execute as native `read` calls.** Matches `agy` 1.5.14's rename of `view_file` (same `Path`/`StartLine`/`EndLine` shape; unknown keys still fall back to the wrapper).
14
+ - **The stream-json `mcp_config.json` and suppression-marker writes are now symlink-safe too.** The same dotfiles hazard as `config.json`: `mcp-registration.ts` wrote `~/.gemini/config/mcp_config.json` (register, disable flip, unregister, stale sweep) and `suppression.json` (delegation markers) via temp + rename over the raw path, so a symlinked file was silently replaced by a regular file on the first write. Both now go through a shared `writeJsonAtomic` helper (extracted from `config.ts`, one implementation for every bridge config writer) with the same resolution rules: the rename lands in the link target, a dangling link is written through, hard errors fail visibly. Per-file modes are unchanged (`0600` file, `0700` data dir).
15
+ - **`saveConfig` no longer replaces a symlinked config with a regular file.** The atomic write (temp + rename over the path) swapped a dotfiles-managed config symlink for a plain file on the first unrelated save. `writeConfigJson` now resolves the real target first and renames through it, so the link survives: a missing regular file falls back to the raw path (fresh install), a dangling symlink resolves through the link to its not-yet-existing target, and hard errors (EACCES, a link loop) fail the write visibly instead of falling back and replacing the link. This also backs `removeLegacyAcpBin`, whose explicit resolution it replaces.
16
+ - **`readOnly` now accepts the JSON numbers `0`/`1` the README already promised (issue #23 review).** The file-path parser handled only booleans and strings, so a hand-edited `"readOnly": 0` warned and failed closed to ON - the opposite of what the user wrote, while the warning text itself listed `1/0` as recognized spellings. The literal grammar (booleans, the numbers `0`/`1`, the `on`/`off` vocabulary) now lives in one shared helper used by the boolean parser, the readOnly path, and `saveConfig`; unrecognized values keep failing closed to ON with a warning.
17
+ - **`saveConfig` no longer collapses a hand-edited `acp.sessionRetryOnTimeout` to `false` on unrelated saves (issue #23 review).** The strict `=== true` pass-through discarded the boolish spellings `loadConfig` accepts (`"on"`, `"true"`, `"1"`, the numbers): any unrelated `/agy` toggle rewrote them to `false`. Saves now normalize through the same literal grammar; junk falls back to the default, an explicit patch still wins, `AGY_ACP_SESSION_RETRY` still never bakes into the file, and junk is rewritten (its doctor warning with it) on the first unrelated save - the same trade `sessionTimeoutMs` and `engine` already make.
18
+ - **`saveConfig` no longer invents `turnTimeoutMin: 0` on files that omit the key (issue #23 review).** The `0` in `DEFAULTS` is a load-time placeholder (the real cap resolves per TTY state), but the defaults spread persisted it, and `parseCapMinutes` reads an explicit `0` as "cap disabled" - so one unrelated save silently uncapped future headless turns on installs that never configured a cap. The key is now written only when the file or the patch carries it. Installs already carrying a `0` from an earlier save keep it: a stored `0` is indistinguishable from a deliberate "cap off", so the fix only stops new placeholder writes.
19
+
20
+ ## [1.13.2] - 2026-11-22
21
+
22
+ ### Fixed
23
+
24
+ - **Consecutive user messages no longer drop earlier prompts or images (issue #24).** The provider read only the LAST message, so a turn stacking `[user prompt, before_agent_start note]` shipped the note as the prompt: digest off lost the real prompt entirely, digest on demoted it into `[earlier user message]` continuity context (and could drop it on stream-json under the byte budget), and images attached to earlier messages never reached agy at all. The provider now joins the trailing run of `role: "user"` messages into one prompt with images unioned in order. The run is watermark-bounded - messages at or before the watermark belong to turns agy already saw, so failed-turn backlog never re-executes as prompt (the issue #1 guard holds) - and compaction summaries, branch summaries, and bash-run texts stop the run instead of sweeping into the prompt. The digest window ends at the run start so nothing double-delivers; a whitespace-only trailing message no longer kills the turn with "No user message"; and a joined run that would cross the stream-json silent-drop cap truncates oldest-first with a visible `[truncated]` marker and ships without the digest instead of a doomed turn.
25
+ - **Parse fallbacks surface where they happen, and `0`/`1` count as booleans (issue #23 review follow-up).** `parseBoolish` now also accepts the JSON numbers `0`/`1`; junk values keep the safe default and now warn on session start (toast in the UI, stderr headless) in addition to the `/agy doctor` row, because a hand editor never runs `/agy`. The README no longer misstates the `webTools` default and documents the env/file grammar asymmetry: `AGY_SKIP_PERMISSIONS` takes only `1`/`true` in the env, and a set env var skips the file parse entirely so it warns nothing about the value it overrides.
26
+ - **String booleans in config.json no longer silently enable a disabled option (issue #23).** The boolean keys (`readOnly`, `skipPermissions`, `askTool`, `webTools`, `digest`, `systemPrompt`, `acp.sessionRetryOnTimeout`) passed raw file values through `??`, so a hand-edited `"off"`, `"false"`, or `"0"` - the exact vocabulary the README and `/agy` display - was a truthy string and switched the option ON. The file path now parses the `/agy` vocabulary (`true`/`false`/`on`/`off`/`1`/`0`, case and whitespace tolerated); env parsing is unchanged. Present-but-unparseable values fall back to the key's default and surface a `config warnings:` row in `/agy doctor` instead of failing silently; `readOnly` fails closed (ON) on junk, mirroring `AGY_READONLY`; and `saveConfig` neither rewrites a hand-edited value on an unrelated toggle nor persists the computed warnings field. The same pass closes a crash in the class the reporter's table exposed: a non-string `defaultThinking`, `bridgeTools`, `approvals.gateMode`, `approvals.mode`, or `agent` threw on every bridge call (`.toLowerCase()`/`.trim()` on a non-string) and now falls back to the default like every other junk value.
27
+
5
28
  ## [1.13.1] - 2026-11-21
6
29
 
7
30
  ### Fixed
package/README.md CHANGED
@@ -115,16 +115,20 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
115
115
 
116
116
  | Key | Values | Default |
117
117
  | --- | --- | --- |
118
- | `askTool` | `on` (register the AskAntigravity delegation tool), `off` (no delegation tool; provider and models only) | `on` |
119
- | `webTools` | `off` (no web tools), `on` (register `agy_web_search` + `agy_read_url` as Pi tools, usable by ANY provider's model). Each call spawns a one-shot search-only `agy` agent (plan mode, bridge MCP inheritance off), gates the answer on an observed native `search_web`/`read_url_content` step, and spends Antigravity quota. Off by default: Antigravity sessions already have native web tools on both engines; these serve other providers | `off` |
118
+ | `askTool` | `true` (register the AskAntigravity delegation tool), `false` (no delegation tool; provider and models only) | `true` |
119
+ | `webTools` | `false` (no web tools), `true` (register `agy_web_search` + `agy_read_url` as Pi tools, usable by ANY provider's model). Each call spawns a one-shot search-only `agy` agent (plan mode, bridge MCP inheritance off), gates the answer on an observed native `search_web`/`read_url_content` step, and spends Antigravity quota. Off by default: Antigravity sessions already have native web tools on both engines; these serve other providers | `false` |
120
120
  | `bridgeTools` | `none` (bridge off), `all` (every non-builtin tool, incl. other `Ask*` delegations), `mcp` (pi-mcp-adapter tools + skills bridge only) | `all` |
121
- | `digest` | Self-gating delta of pi-side context (compaction summaries, other-provider turns, handoffs after a mid-session switch) shipped to agy only when the delta is non-empty, each piece once. Pure antigravity sessions get byte-stable prompts and an intact prompt cache. `off` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `on` |
122
- | `systemPrompt` | `on` (send pi's system prompt - operating instructions plus the global agent-dir `AGENTS.md` and ancestor `AGENTS.md`/`CLAUDE.md` - to the first prompt of each new agy conversation, plus a tool-priority note: Pi Bridge tools win over agy's native interactive ones, which never reach the user. Delivery: stream-json stages it as an agy agent file via `--agent`, off the prompt line - the CLI silently drops single prompts past a ~25KB cap and the dropped turn kills the conversation; the carrier declares the productive toolset explicitly (omitting `tools:` reads as a read-only set upstream, issue #13) plus `subagent: false` + `agents: []` so the native subagent tools stay masked (ACP carries no agent file, so its natives remain and the tool-priority note steers the model to pi delegation). ACP prepends it to the first prompt) or `off` (agy-native behavior) | `on` |
121
+ | `digest` | Self-gating delta of pi-side context (compaction summaries, other-provider turns, handoffs after a mid-session switch) shipped to agy only when the delta is non-empty, each piece once. Pure antigravity sessions get byte-stable prompts and an intact prompt cache. `false` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `true` |
122
+ | `systemPrompt` | `on` (send pi's system prompt - operating instructions plus the global agent-dir `AGENTS.md` and ancestor `AGENTS.md`/`CLAUDE.md` - to the first prompt of each new agy conversation, plus a tool-priority note: Pi Bridge tools win over agy's native interactive ones, which never reach the user. Delivery: stream-json stages it as an agy agent file via `--agent`, off the prompt line - the CLI silently drops single prompts past a ~25KB cap and the dropped turn kills the conversation; the carrier declares the productive toolset explicitly (omitting `tools:` reads as a read-only set upstream, issue #13) plus `subagent: false` + `agents: []` so the native subagent tools stay masked (ACP carries no agent file, so its natives remain and the tool-priority note steers the model to pi delegation). ACP prepends it to the first prompt) or `false` (agy-native behavior) | `true` |
123
+ | `readOnly` | `true`: fail-closed kill switch - every provider turn and the `AskAntigravity` tool are refused with a visible error (the CLI has no review-only enforcement, see [Permissions](#permissions) and [readOnly](#readonly)). In the file, any value that is not a recognized boolean spelling (or an explicit blank) also fails closed to `true` | `false` |
124
+ | `skipPermissions` | `true`: pass `--dangerously-skip-permissions` so agy tool calls never hang on an unanswerable prompt in non-interactive runs; DANGEROUS: agy executes commands without per-action review (see [Permissions](#permissions)). `false`: prompt instead - hangs any `run_command` in `-p` mode | `true` |
123
125
  | `turnTimeoutMin` | Overall cap on ONE agy turn, minutes, both engines. Parked time (pi-tool round-trips, escalated calls, human-gated approvals) does not count against it on either engine: the cap pauses with remaining-budget semantics and resumes on unpark. When it fires, the bridge kills the agy process mid-task ("ACP turn exceeded the 10m deadline" / "agy exceeded the 10m turn timeout") - it is a bridge cap, not a Google server limit. Default is TTY-aware: `0` (no cap) on an interactive pi - you are the backstop with Esc; `20` headless, where nobody can abort and one runaway turn blocks the serialized turn queue. Opt into a gate with 1-1440 (free type via `config.json` or `/agy timeout <1-1440|off>`, or the `/agy` picker's preset list); `0` disables explicitly; anything else falls back to the TTY-aware default. The 5m inactivity stall guard always still bounds a hung server | `0` TTY / `20` headless |
124
126
  | `inactivityTimeoutMin` | Silence cap, minutes, both engines: no stream-json stdout / no ACP session/update for this long fails the turn as a stall. `0` disables the guard. Parks (bridge calls, escalated calls, ACP permission dialogs) pause it; agy-native long steps such as builds do not. A false kill costs the whole turn, and on stream-json a stall kill with no result frame clears the conversation binding. Keep `5`; use `2`-`3` only when native steps are known to be short; do not use `1` | `5` |
125
127
  | `acp.sessionTimeoutMs` | Timeout in ms for ACP `session/new`, `session/load`, `session/set_config_option`, and `session/close`. Valid range: `1000`-`300000`. Raise only on slow or proxied networks | `20000` |
126
128
  | `acp.sessionRetryOnTimeout` | Advanced: transparently retry `session/new` once when it times out while `agy acp` is still alive. **Warning:** doubles total wait time on dead networks and may not recover if `agy`'s internal socket is wedged | `false` |
127
129
 
130
+ Boolean keys (`readOnly`, `skipPermissions`, `askTool`, `webTools`, `digest`, `systemPrompt`, `acp.sessionRetryOnTimeout`) take JSON booleans, the `/agy` vocabulary as strings (`on`/`off`, `1`/`0`, case and whitespace tolerated), and the JSON numbers `0`/`1`, so a hand-edited `"off"` means off instead of silently on (issue #23). Unrecognized values fall back to the key's default - `readOnly` falls closed to `true` - and surface a `config warnings:` row in `/agy doctor` plus a startup warning toast. The `AGY_*` env vars keep their own grammars: notably `AGY_SKIP_PERMISSIONS` does not accept `on` (only `1`/`true` enable there), and while an env var is set the matching file value is never parsed, so it emits no warning for the value it overrides.
131
+
128
132
  Env overrides: `AGY_BRIDGE_TOOLS`, `AGY_ASK_TOOL`, `AGY_WEB_TOOLS`, `AGY_DIGEST`, `AGY_SYSTEM_PROMPT`, `AGY_TURN_TIMEOUT_MIN`, `AGY_INACTIVITY_TIMEOUT_MIN`, `AGY_ACP_SESSION_TIMEOUT_MS`, `AGY_ACP_SESSION_RETRY`. Env wins over the file, so while `AGY_DIGEST` or `AGY_SYSTEM_PROMPT` is set, the matching `/agy digest` or `/agy system-prompt` toggle persists a value that never takes effect.
129
133
 
130
134
  The `activate_skill` catalog mirrors pi's directory-based skill discovery: the two global dirs plus project dirs, the latter only when pi has trusted the project (same gate pi itself applies). Pi's other skill sources - the `skills` settings array, `package.json` entries, and `--skill` CLI paths - are not mirrored and won't appear in the catalog.
@@ -166,7 +170,7 @@ Plan mode never receives the flag: the flag auto-approves every permission reque
166
170
 
167
171
  ### readOnly
168
172
 
169
- `"readOnly": true` in the config (or `AGY_READONLY=1`, or `/agy readonly on`) is a fail-closed kill switch: every provider turn AND the `AskAntigravity` tool are refused with a visible error instead of running write-capable under a read-only label. Built for callers like `pi -p --no-tools --model antigravity/...` health checks that must never mutate a workspace: with no review-only enforcement available in the CLI (see Permissions), a visible refusal is the only honest behavior. The knob covers provider turns and the ask tool; the web tools still spawn agy for searches. Default false.
173
+ `"readOnly": true` in the config (or `AGY_READONLY=1`, or `/agy readonly on`) is a fail-closed kill switch: every provider turn AND the `AskAntigravity` tool are refused with a visible error instead of running write-capable under a read-only label. Built for callers like `pi -p --no-tools --model antigravity/...` health checks that must never mutate a workspace: with no review-only enforcement available in the CLI (see Permissions), a visible refusal is the only honest behavior. The knob covers provider turns and the ask tool; the web tools still spawn agy for searches. Default false. In the config file, junk values fail closed too: anything that is not `true`/`false`/`on`/`off`/`1`/`0` (or an explicit empty string) reads as ON and adds a `config warnings:` row in `/agy doctor` (issue #23).
170
174
 
171
175
  For per-action review of agy's mutating native tools (`run_command`, `create_file`, `edit_file`, ...), see the [Approval gate](docs/APPROVAL-GATE.md): with it on, the call must pass a pi-side approval (your permission extension, or the built-in ask/allow/deny fallback) before agy executes it.
172
176
 
@@ -36,7 +36,7 @@ import {
36
36
  toPiModel,
37
37
  type AgyModelEntry,
38
38
  } from "../src/models.js";
39
- import { SessionStore } from "../src/sessions.js";
39
+ import type { SessionStore } from "../src/sessions.js";
40
40
  import {
41
41
  APPROVAL_PARK_MS,
42
42
  POLL_TOOL_NAME,
@@ -68,7 +68,7 @@ import { agyAuthenticationMessage } from "../src/agy-install.js";
68
68
  import { createAgySetupOffer } from "../src/agy-setup.js";
69
69
  import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
70
70
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
71
- 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
+ import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
72
72
  import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
73
73
  import { agyVersionVerdict, agyUpdateMessage, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
74
74
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
@@ -85,13 +85,19 @@ import { redactText } from "../src/redact.js";
85
85
  import { createDailyLogger, type DailyLogger } from "../src/daily-log.js";
86
86
  import { registerAskAntigravityTool, toolModelsFromRaw } from "../src/ask-tool.js";
87
87
  import { registerWebTools } from "../src/web-tools.js";
88
- import { bridgeMcpConfigDir, startMcpServer, sweepStaleBridgeDirs, TOKEN_HEADER, type McpServerHandle } from "../src/mcp-server.js";
88
+ import { bridgeMcpConfigDir, sweepStaleBridgeDirs, TOKEN_HEADER } from "../src/mcp-server.js";
89
89
  import {
90
90
  registerBridgeServer,
91
91
  healBridgeSuppression,
92
92
  sweepStaleBridgeServers,
93
- unregisterBridgeServer,
94
93
  } from "../src/mcp-registration.js";
94
+ import {
95
+ approvalHookScriptPath,
96
+ bridgeRealm,
97
+ liveSessionId,
98
+ type BridgeEndpoint,
99
+ type RealmSession,
100
+ } from "../src/runtime.js";
95
101
  import {
96
102
  ACTIVATE_SKILL_TOOL_NAME,
97
103
  activateSkillSchema,
@@ -117,15 +123,14 @@ import { Type } from "typebox";
117
123
  import { patchStatus, restorePatch } from "../src/patch-cleanup.js";
118
124
  import { withDialogLock } from "../src/dialog-lock.js";
119
125
 
120
- // Last UI seen (session_start / /agy commands). Module scope: both the
121
- // default export and registerAgyCommand assign it.
122
- let activeUi: ExtensionUIContext | null = null;
123
-
124
126
  function resolveAgyBinary(): string {
125
127
  return process.env.AGY_BIN || "agy";
126
128
  }
127
129
 
128
130
  export default async function (pi: ExtensionAPI): Promise<void> {
131
+ // Per-factory UI reference so child session_shutdown never clears the
132
+ // parent's UI context.
133
+ let activeUi: ExtensionUIContext | null = null;
129
134
  ensureQueuedMessagesDefaults({ onlyIfDirExists: true });
130
135
 
131
136
  // Claim the AskAntigravity tool for this process. pi-ask-antigravity (if also
@@ -210,16 +215,20 @@ export default async function (pi: ExtensionAPI): Promise<void> {
210
215
  "info",
211
216
  );
212
217
 
213
- const store = new SessionStore();
218
+ const realm = bridgeRealm();
219
+ const store = realm.store;
214
220
  // MCP bridge handle, declared early: the ACP engine reads the bridge port
215
221
  // at session/new / session/load time.
216
- let mcpHandle: McpServerHandle | null = null;
222
+ let mcpHandle: BridgeEndpoint | null = null;
223
+ let currentSessionManager: unknown;
224
+ let lastConversationId: string | undefined;
225
+ let realmSession: RealmSession | null = null;
217
226
  // Session-only visibility overrides; never change either application's MCP config.
218
227
  const hiddenBridgeTools = new Set<string>();
219
228
  const getBridgeTools = () => bridgedPiTools(pi.getAllTools(), pi.getActiveTools(), loadConfig().bridgeTools, hiddenBridgeTools);
220
- // Approval-gate hook script (per-pid, token embedded). Written at session
221
- // start when the gate is active; removed at session_shutdown.
222
- let gateScriptPath: string | null = null;
229
+ // Staged gate hooks do not stop agy's own request_permission path, so when
230
+ // true the ACP driver stops letting skipPermissions auto-allow it.
231
+ let gateActive = false;
223
232
  let managedAcpCleanupRan = false;
224
233
  let legacyConfigCleanupRan = false;
225
234
  let legacyConfigCleanupFailed = false;
@@ -298,7 +307,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
298
307
  // path; restore the global registration so the bridge stays
299
308
  // reachable when the staged home is unusable.
300
309
  if (mcpHandle) {
301
- registerBridgeServer({ pid: process.pid, port: mcpHandle.port, token: mcpHandle.token, tokenHeader: TOKEN_HEADER });
310
+ registerBridgeServer({ pid: process.pid, port: mcpHandle.port, token: mcpHandle.realmToken, tokenHeader: TOKEN_HEADER });
302
311
  }
303
312
  return undefined;
304
313
  }
@@ -338,11 +347,14 @@ export default async function (pi: ExtensionAPI): Promise<void> {
338
347
  usageEstimate: () => loadConfig().acp.usageEstimate,
339
348
  sessionOpTimeoutMs: () => loadConfig().acp.sessionTimeoutMs,
340
349
  sessionRetryOnTimeout: () => loadConfig().acp.sessionRetryOnTimeout,
341
- // ACP request_permission parity with the approval gate: skipPermissions
342
- // turns auto-allow in the driver; approvals.mode allow short-circuits
343
- // to the same synchronous allow; everything else opens a dialog (esc
344
- // and headless deny fail-closed) under the shared dialog lock.
350
+ // ACP request_permission parity with the approval gate: with the gate
351
+ // off, skipPermissions turns auto-allow in the driver. With the gate
352
+ // staged (gateActive) skipPermissions never applies, because the hook
353
+ // does not stop agy's own permission path: approvals.mode allow
354
+ // answers allow, deny answers deny, everything else opens a dialog
355
+ // (esc and headless deny fail-closed) under the shared dialog lock.
345
356
  permissionPolicy: () => (loadConfig().approvals.mode === "allow" ? "auto" : "deny"),
357
+ gateActive: () => gateActive,
346
358
  onPermissionRequest: async (req) => {
347
359
  const ui = activeUi;
348
360
  if (loadConfig().approvals.mode === "deny" || !ui) return undefined;
@@ -506,7 +518,10 @@ export default async function (pi: ExtensionAPI): Promise<void> {
506
518
  // Stamp live escalations with the ended turn's conversation: the park
507
519
  // pass returns before the provider's store.set, so a first-turn park
508
520
  // has no other record of where its result must be re-delivered.
509
- if (outcome.conversationId) roundTrips.stampConversation(outcome.conversationId);
521
+ if (outcome.conversationId) {
522
+ lastConversationId = outcome.conversationId;
523
+ roundTrips.stampConversation(outcome.conversationId);
524
+ }
510
525
  };
511
526
  streamDriver.onTurnEnd = onTurnEnd;
512
527
  acpDriver.onTurnEnd = onTurnEnd;
@@ -604,6 +619,9 @@ export default async function (pi: ExtensionAPI): Promise<void> {
604
619
  fileLog.log("background-watch-sweep-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
605
620
  }
606
621
  });
622
+ // Bindings must reach disk before the host exits (headless/print modes
623
+ // exit right after session_shutdown).
624
+ pi.on("session_shutdown", () => store.flush());
607
625
  // Session keys whose bound agy conversation was rotated on session_compact
608
626
  // so the next turn starts a fresh backend conversation and ships the
609
627
  // compaction summary once (even when config.digest is disabled).
@@ -671,6 +689,16 @@ export default async function (pi: ExtensionAPI): Promise<void> {
671
689
  log: fileLog.log.bind(fileLog),
672
690
  });
673
691
 
692
+ const joinRealm = () =>
693
+ realm.join({
694
+ sessionId: () => liveSessionId(currentSessionManager),
695
+ streamSimple,
696
+ hasActiveTurn: () => (engine === "acp" ? acpDriver.activeHandle !== null : streamDriver.activeHandle !== null),
697
+ conversationId: () =>
698
+ (engine === "acp" ? acpDriver.snapshot().conversationId : streamDriver.snapshot().conversationId)
699
+ ?? lastConversationId,
700
+ });
701
+
674
702
  pi.registerProvider("antigravity", {
675
703
  name: "Antigravity (agy)",
676
704
  baseUrl: "agy-bridge://antigravity",
@@ -687,7 +715,10 @@ export default async function (pi: ExtensionAPI): Promise<void> {
687
715
  contextWindow: m.contextWindow,
688
716
  maxTokens: m.maxTokens,
689
717
  })),
690
- streamSimple,
718
+ // pi-ai's provider registry is process-global and every session's factory
719
+ // call registers again: register the realm's stable dispatcher so each
720
+ // call routes to its own session's streamSimple.
721
+ streamSimple: realm.streamSimple,
691
722
  });
692
723
 
693
724
  registerAgyCommand(pi, {
@@ -705,6 +736,9 @@ export default async function (pi: ExtensionAPI): Promise<void> {
705
736
  roster,
706
737
  pendingCompactionHandoff,
707
738
  checkAgySetup,
739
+ setActiveUi: (ui) => {
740
+ activeUi = ui;
741
+ },
708
742
  });
709
743
 
710
744
  // AskAntigravity tool: one-shot delegation to agy (ported from
@@ -791,6 +825,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
791
825
  // normal toolUse loop (native cards, permissions, hooks) - no patch, no
792
826
  // privileged API. Started on session_start, torn down on session_shutdown.
793
827
  pi.on("session_start", async (event, ctx) => {
828
+ currentSessionManager = ctx.sessionManager;
829
+ realmSession ??= joinRealm();
794
830
  if (ctx.hasUI) activeUi = ctx.ui;
795
831
  // First-run engine picker: ask once, on the first interactive start,
796
832
  // which turn engine to use. Skipped headless (ctx.mode !== "tui"),
@@ -844,6 +880,14 @@ export default async function (pi: ExtensionAPI): Promise<void> {
844
880
  if (ctx.hasUI) ctx.ui.notify(msg, "warning");
845
881
  else console.error(`[antigravity-bridge] ${msg}`);
846
882
  }
883
+ // A hand editor never runs /agy: surface parse fallbacks where they
884
+ // happen (issue #23). Headless sessions keep the stderr record.
885
+ const configWarnings = loadConfig().parseWarnings;
886
+ if (configWarnings?.length) {
887
+ const msg = configWarningsMessage(configWarnings);
888
+ if (ctx.hasUI) ctx.ui.notify(msg, "warning");
889
+ else console.error(`[antigravity-bridge] ${msg}`);
890
+ }
847
891
  if (!managedAcpCleanupRan) {
848
892
  managedAcpCleanupRan = true;
849
893
  try {
@@ -1024,13 +1068,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1024
1068
  isError: !skill,
1025
1069
  });
1026
1070
  };
1027
- const r = await startMcpServer(
1071
+ const r = await realmSession.attachBridge(
1028
1072
  {
1029
1073
  listTools,
1030
1074
  onToolCall: bridgeOnToolCall,
1031
1075
  onApproval: (ticket, payload) => roundTrips.onApproval(ticket, payload),
1032
1076
  },
1033
- { log: mcpLog },
1077
+ mcpLog,
1034
1078
  );
1035
1079
  if (r.ok && r.handle) {
1036
1080
  mcpHandle = r.handle;
@@ -1041,18 +1085,20 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1041
1085
  // Global-config hygiene runs on BOTH engines: a crashed stream-json
1042
1086
  // session must not leave dead-pid entries or stuck suppression flags
1043
1087
  // for the next one.
1044
- healBridgeSuppression();
1088
+ if (r.first) healBridgeSuppression();
1045
1089
  // ACP supplies the bridge per-session (session/new | session/load).
1046
1090
  // stream-json skips the global file entirely when the isolated home
1047
1091
  // is active (issue #14): this session's bridge rides the staged
1048
1092
  // config instead, so no other agy on the machine can see or call it.
1049
1093
  if (engine === "stream-json" && !streamHome.isolated) {
1050
- registerBridgeServer({
1051
- pid: process.pid,
1052
- port: r.handle.port,
1053
- token: r.handle.token,
1054
- tokenHeader: TOKEN_HEADER,
1055
- });
1094
+ if (r.first) {
1095
+ registerBridgeServer({
1096
+ pid: process.pid,
1097
+ port: r.handle.port,
1098
+ token: r.handle.realmToken,
1099
+ tokenHeader: TOKEN_HEADER,
1100
+ });
1101
+ }
1056
1102
  } else if (streamHome.path) {
1057
1103
  // Bridge enabled after the home was staged without one: refresh
1058
1104
  // the staged copy directly. agy reads the home once at spawn;
@@ -1077,6 +1123,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1077
1123
  {
1078
1124
  const cfg = loadConfig();
1079
1125
  const mode = resolveGateMode(cfg.approvals.gateMode, detectPermissionGateExtensions());
1126
+ gateActive = mode !== "off";
1080
1127
  if (mode !== "off" && engine === "acp") {
1081
1128
  // Staged-home hook delivery is probe-verified on agy 1.5.12
1082
1129
  // only (issue #18); older ACP builds may not honor it. Warn
@@ -1097,34 +1144,35 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1097
1144
  // Staging now lives in the session-private add-dir; sweep groups left
1098
1145
  // behind by dead sessions from the old scheme. Live sessions' and
1099
1146
  // foreign groups are never touched.
1100
- const sweptLegacy = sweepWorkspaceGateGroups(process.cwd());
1101
- if (sweptLegacy > 0) fileLog.log("approval-workspace-swept", { swept: sweptLegacy }, "info");
1147
+ if (r.first) {
1148
+ const sweptLegacy = sweepWorkspaceGateGroups(process.cwd());
1149
+ if (sweptLegacy > 0) fileLog.log("approval-workspace-swept", { swept: sweptLegacy }, "info");
1150
+ }
1102
1151
  if (mode === "off") {
1103
- // Gate off: drop this session's private hooks file. Other sessions
1104
- // own their own per-pid files; nothing shared to preserve.
1152
+ // Gate off: drop this session's private hooks file.
1105
1153
  const unstaged = removeGateHooks();
1106
1154
  if (unstaged.wrote) fileLog.log("approval-unstaged", unstaged, "info");
1107
1155
  } else {
1108
- // Script: per-pid file; 0600 because the bridge token is
1109
- // embedded (peer review 2026-09-07).
1110
- const scriptPath = path.join(logsDir(), `approval-hook-${process.pid}.js`);
1156
+ // Script: per-realm file; 0600 because the realm token is
1157
+ // embedded (peer review 2026-09-07). Re-stage idempotently so
1158
+ // a partial failure on an earlier session never leaves the
1159
+ // gate un-staged while gateActive is true.
1160
+ const scriptPath = approvalHookScriptPath();
1111
1161
  fs.mkdirSync(path.dirname(scriptPath), { recursive: true, mode: 0o700 });
1112
1162
  fs.writeFileSync(
1113
1163
  scriptPath,
1114
1164
  hookScriptSource({
1115
1165
  port: r.handle.port,
1116
- token: r.handle.token,
1166
+ token: r.handle.realmToken,
1117
1167
  deadlineMs: APPROVAL_PARK_MS,
1118
1168
  }),
1119
1169
  { mode: 0o600 },
1120
1170
  );
1121
- gateScriptPath = scriptPath;
1122
- // Private per-pid staging (issue #5 isolation): the gate group goes
1123
- // into the bridge add-dir that ONLY this session's agy receives.
1124
- // Standalone sessions in the workspace never load it.
1171
+ // Private per-realm staging (issue #5 isolation): the gate group goes
1172
+ // into the bridge add-dir that ONLY this process's agy receives.
1125
1173
  const staged = stageGateHooks(bridgeMcpConfigDir(), {
1126
1174
  port: r.handle.port,
1127
- token: r.handle.token,
1175
+ token: r.handle.realmToken,
1128
1176
  scriptPath,
1129
1177
  parkBudgetMs: APPROVAL_PARK_MS,
1130
1178
  });
@@ -1190,31 +1238,25 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1190
1238
  activeUi = null;
1191
1239
  const h = mcpHandle;
1192
1240
  mcpHandle = null;
1193
- // "recycle", NOT "shutdown": pi fires session_shutdown on /new, /resume
1194
- // and /fork (docs/extensions.md session lifecycle), not only on process
1195
- // exit. The drivers are process-lifetime singletons; closing them with
1196
- // "shutdown" latched them permanently and every later turn failed with
1197
- // "ACP driver is shut down." (regression 2026-09-07). Recycle kills the
1198
- // connection now; the next turn respawns it. event.reason is
1199
- // deliberately ignored: recycle is correct even on real process exit
1200
- // ("quit") - the connection kill is identical and nothing runs after.
1201
- await streamDriver.close("recycle", "session shutdown");
1202
- await acpDriver.close("recycle", "session shutdown");
1203
- roundTrips.failAll(FAIL_REASON_SHUTDOWN);
1204
- await h?.close();
1205
- if (engine === "stream-json") unregisterBridgeServer(process.pid);
1206
- hiddenBridgeTools.clear();
1207
- // Approval gate: unstage hooks and remove the per-pid script. Pending
1208
- // approvals already failed closed via handle close (bridge shutdown deny).
1209
- const unstaged = removeGateHooks();
1210
- if (unstaged.wrote) fileLog.log("approval-unstaged", unstaged, "info");
1211
- if (gateScriptPath) {
1212
- try {
1213
- fs.rmSync(gateScriptPath, { force: true });
1214
- } catch {
1215
- /* best effort */
1216
- }
1217
- gateScriptPath = null;
1241
+ try {
1242
+ // "recycle", NOT "shutdown": pi fires session_shutdown on /new, /resume
1243
+ // and /fork (docs/extensions.md session lifecycle), not only on process
1244
+ // exit. The drivers are process-lifetime singletons; closing them with
1245
+ // "shutdown" latched them permanently and every later turn failed with
1246
+ // "ACP driver is shut down." (regression 2026-09-07). Recycle kills the
1247
+ // connection now; the next turn respawns it. event.reason is
1248
+ // deliberately ignored: recycle is correct even on real process exit
1249
+ // ("quit") - the connection kill is identical and nothing runs after.
1250
+ await streamDriver.close("recycle", "session shutdown");
1251
+ await acpDriver.close("recycle", "session shutdown");
1252
+ roundTrips.failAll(FAIL_REASON_SHUTDOWN);
1253
+ await h?.close();
1254
+ hiddenBridgeTools.clear();
1255
+ } finally {
1256
+ // Leaving the realm revokes this session's route; only the last session
1257
+ // to leave tears down the shared listener and per-realm artifacts.
1258
+ await realmSession?.leave();
1259
+ realmSession = null;
1218
1260
  }
1219
1261
  });
1220
1262
  }
@@ -1241,6 +1283,7 @@ interface AgyCommandCtx {
1241
1283
  roster: SubagentRoster;
1242
1284
  pendingCompactionHandoff: Set<string>;
1243
1285
  checkAgySetup: (ctx: { ui: ExtensionUIContext; mode: string }, engine: Engine, explicit?: boolean) => Promise<void>;
1286
+ setActiveUi: (ui: ExtensionUIContext) => void;
1244
1287
  }
1245
1288
 
1246
1289
  interface PendingConfig {
@@ -1280,6 +1323,8 @@ function settingsRows(ctx: AgyCommandCtx): string[] {
1280
1323
  row("bridge tools:", config.bridgeTools),
1281
1324
  row("digest:", config.digest ? "on" : "off"),
1282
1325
  row("system prompt:", config.systemPrompt ? "on" : "off"),
1326
+ // issue #23: unparseable hand-edited values must not fail silently.
1327
+ ...(config.parseWarnings ?? []).map((w, i) => row(i === 0 ? "config warnings:" : "", w)),
1283
1328
  ];
1284
1329
  }
1285
1330
 
@@ -1305,7 +1350,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1305
1350
  "Antigravity provider: doctor (health + settings), settings picker, clear sessions. Usage: /agy [doctor|auth|auth-manual|engine stream-json|acp|mode plan|accept-edits|readonly on|off|permissions on|off|ask on|off|model <alias>|thinking low|medium|high|agent <name|off>|subagents|quota|artifacts [open <n|name>]|tasks [tail <id>]|bridge all|mcp|none|tools [hide|show <name>|reset]|web on|off|digest on|off|system-prompt on|off|timeout <1-1440|off>|patch-cleanup|clear]",
1306
1351
  handler: async (args, cmdCtx: ExtensionCommandContext) => {
1307
1352
  const ui = cmdCtx.ui;
1308
- if (ui) activeUi = ui;
1353
+ if (ui) ctx.setActiveUi(ui);
1309
1354
  const mode = cmdCtx.mode;
1310
1355
  const sub = (args ?? "").trim().split(/\s+/)[0]?.toLowerCase();
1311
1356
  const val = (args ?? "").trim().split(/\s+/)[1]?.toLowerCase();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.13.1",
3
+ "version": "1.13.3",
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",
@@ -102,6 +102,18 @@ export interface AcpPermissionRequest {
102
102
 
103
103
  export type AcpPermissionHandler = (req: AcpPermissionRequest) => Promise<string | null | undefined>;
104
104
 
105
+ /** Tool identity of a permission request for the log: kind, redacted title,
106
+ * toolCallId and field names only (no raw input, so no file contents). */
107
+ function permissionToolIdentity(params: AcpPermissionRequest | undefined): Record<string, string | string[]> {
108
+ const tc = params?.toolCall;
109
+ const out: Record<string, string | string[]> = {};
110
+ if (tc && typeof tc === "object") out.fields = Object.keys(tc);
111
+ if (typeof tc?.kind === "string") out.kind = tc.kind;
112
+ if (typeof tc?.title === "string") out.title = redactText(tc.title).slice(0, 200);
113
+ if (typeof tc?.toolCallId === "string") out.toolCallId = tc.toolCallId;
114
+ return out;
115
+ }
116
+
105
117
 
106
118
  export class AcpConnection {
107
119
  #opts: AcpConnectionOptions;
@@ -421,12 +433,12 @@ export class AcpConnection {
421
433
  const policy = this.#opts.permissions?.() ?? "deny";
422
434
  if (policy === "auto") {
423
435
  const chosen = (allow ?? options[0])?.optionId;
424
- this.#opts.log("permission", { optionId: chosen, policy });
436
+ this.#opts.log("permission", { optionId: chosen, policy, tool: permissionToolIdentity(params) });
425
437
  return Promise.resolve({ outcome: { outcome: "selected", optionId: chosen } });
426
438
  }
427
439
  const handler = this.#opts.onPermissionRequest;
428
440
  if (!handler) {
429
- this.#opts.log("permission", { optionId: denyId, policy });
441
+ this.#opts.log("permission", { optionId: denyId, policy, tool: permissionToolIdentity(params) });
430
442
  return Promise.resolve(
431
443
  denyId !== undefined
432
444
  ? { outcome: { outcome: "selected", optionId: denyId } }
@@ -438,7 +450,7 @@ export class AcpConnection {
438
450
  const memKey = params?.toolCall?.title ? `${params.toolCall.kind ?? ""}|${params.toolCall.title}` : undefined;
439
451
  const remembered = memKey !== undefined ? this.#permissionMemory.get(memKey) : undefined;
440
452
  if (remembered !== undefined && options.some((o) => o.optionId === remembered)) {
441
- this.#opts.log("permission", { optionId: remembered, policy: "memory" });
453
+ this.#opts.log("permission", { optionId: remembered, policy: "memory", tool: permissionToolIdentity(params) });
442
454
  return Promise.resolve({ outcome: { outcome: "selected", optionId: remembered } });
443
455
  }
444
456
  const parkMs = this.#opts.permissionParkMs ?? PERMISSION_PARK_MS;
@@ -452,7 +464,7 @@ export class AcpConnection {
452
464
  settled = true;
453
465
  if (timer) clearTimeout(timer);
454
466
  this.#permissionPending.delete(settleCancel);
455
- this.#opts.log("permission", { optionId, policy: why });
467
+ this.#opts.log("permission", { optionId, policy: why, tool: permissionToolIdentity(params) });
456
468
  // undefined optionId (no reject option on the table) cancels
457
469
  // instead of selecting nothing.
458
470
  resolve(
package/src/acp/driver.ts CHANGED
@@ -59,10 +59,14 @@ export interface AcpDriverOptions {
59
59
  onPermissionRequest?: AcpPermissionHandler;
60
60
  /** Park budget for one permission dialog (tests shrink it). */
61
61
  permissionParkMs?: number;
62
- /** Standing policy consulted when the turn is not skipPermissions:
63
- * "auto" answers the first allow option synchronously, "deny" consults
64
- * the human handler or fail-closes. Default deny. */
62
+ /** Standing policy consulted when the turn is not skipPermissions, or
63
+ * skipPermissions is overridden by gateActive: "auto" answers the first
64
+ * allow option synchronously, "deny" consults the human handler or
65
+ * fail-closes. Default deny. */
65
66
  permissionPolicy?: () => "auto" | "deny";
67
+ /** True while the approval gate is staged: staged hooks do not stop
68
+ * agy's own request_permission path, so skipPermissions must not bypass it. */
69
+ gateActive?: () => boolean;
66
70
  /** Timeout in ms for session/new, session/load, set_config_option, and
67
71
  * session/close. Defaults to AcpConnection's 20000ms. */
68
72
  sessionOpTimeoutMs?: number | (() => number);
@@ -626,11 +630,12 @@ export class AcpDriver implements TurnDriver {
626
630
  cwd: request.cwd,
627
631
  mcpServers: this.#opts.mcpServers,
628
632
  log: (msg, data) => this.#log(msg, data),
629
- // Fail-closed permissions: skipPermissions answers allow; a standing
630
- // policy override (approvals.mode allow) may widen that; everything
633
+ // Fail-closed permissions: skipPermissions answers allow unless the
634
+ // approval gate is active; then (and for non-skip turns) a standing
635
+ // policy decides (approvals.mode allow widens to auto), everything
631
636
  // else goes to the human handler or denies.
632
637
  permissions: () =>
633
- this.#active?.request.skipPermissions
638
+ this.#active?.request.skipPermissions && !this.#opts.gateActive?.()
634
639
  ? "auto"
635
640
  : (this.#opts.permissionPolicy?.() ?? "deny"),
636
641
  onPermissionRequest: this.#opts.onPermissionRequest
@@ -0,0 +1,41 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export interface AtomicJsonWriteOptions {
5
+ /** File mode for the written file. Default 0600: these files carry secrets. */
6
+ mode?: number;
7
+ /** Mode for directories created on the way to the file. Default: process umask. */
8
+ dirMode?: number;
9
+ }
10
+
11
+ /** Atomic JSON write (temp + rename) for every shared config file. The
12
+ * rename goes through the symlink-resolved target so a dotfiles-managed
13
+ * link survives: an existing file resolves to its real path, a dangling
14
+ * link resolves one hop (the missing target is created through the link),
15
+ * a vanished non-link falls back to the raw path (fresh install), and any
16
+ * other resolution error (EACCES, a link loop) throws instead of silently
17
+ * replacing a link. The temp file lives in the target's directory so the
18
+ * rename never crosses devices. */
19
+ export function writeJsonAtomic(file: string, value: unknown, opts: AtomicJsonWriteOptions = {}): void {
20
+ let target = file;
21
+ try {
22
+ target = fs.realpathSync(file);
23
+ } catch (err) {
24
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
25
+ const st = fs.lstatSync(file, { throwIfNoEntry: false });
26
+ if (st?.isSymbolicLink()) target = path.resolve(path.dirname(file), fs.readlinkSync(file));
27
+ }
28
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: opts.dirMode });
29
+ const tmp = `${target}.${process.pid}.tmp`;
30
+ try {
31
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode: opts.mode ?? 0o600 });
32
+ fs.renameSync(tmp, target);
33
+ } catch (err) {
34
+ try {
35
+ fs.unlinkSync(tmp);
36
+ } catch {
37
+ /* nothing to clean */
38
+ }
39
+ throw err;
40
+ }
41
+ }