@estebanforge/pi-antigravity-bridge 1.13.2 → 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,21 @@
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
+
5
20
  ## [1.13.2] - 2026-11-22
6
21
 
7
22
  ### Fixed
@@ -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,
@@ -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"),
@@ -1032,13 +1068,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1032
1068
  isError: !skill,
1033
1069
  });
1034
1070
  };
1035
- const r = await startMcpServer(
1071
+ const r = await realmSession.attachBridge(
1036
1072
  {
1037
1073
  listTools,
1038
1074
  onToolCall: bridgeOnToolCall,
1039
1075
  onApproval: (ticket, payload) => roundTrips.onApproval(ticket, payload),
1040
1076
  },
1041
- { log: mcpLog },
1077
+ mcpLog,
1042
1078
  );
1043
1079
  if (r.ok && r.handle) {
1044
1080
  mcpHandle = r.handle;
@@ -1049,18 +1085,20 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1049
1085
  // Global-config hygiene runs on BOTH engines: a crashed stream-json
1050
1086
  // session must not leave dead-pid entries or stuck suppression flags
1051
1087
  // for the next one.
1052
- healBridgeSuppression();
1088
+ if (r.first) healBridgeSuppression();
1053
1089
  // ACP supplies the bridge per-session (session/new | session/load).
1054
1090
  // stream-json skips the global file entirely when the isolated home
1055
1091
  // is active (issue #14): this session's bridge rides the staged
1056
1092
  // config instead, so no other agy on the machine can see or call it.
1057
1093
  if (engine === "stream-json" && !streamHome.isolated) {
1058
- registerBridgeServer({
1059
- pid: process.pid,
1060
- port: r.handle.port,
1061
- token: r.handle.token,
1062
- tokenHeader: TOKEN_HEADER,
1063
- });
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
+ }
1064
1102
  } else if (streamHome.path) {
1065
1103
  // Bridge enabled after the home was staged without one: refresh
1066
1104
  // the staged copy directly. agy reads the home once at spawn;
@@ -1085,6 +1123,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1085
1123
  {
1086
1124
  const cfg = loadConfig();
1087
1125
  const mode = resolveGateMode(cfg.approvals.gateMode, detectPermissionGateExtensions());
1126
+ gateActive = mode !== "off";
1088
1127
  if (mode !== "off" && engine === "acp") {
1089
1128
  // Staged-home hook delivery is probe-verified on agy 1.5.12
1090
1129
  // only (issue #18); older ACP builds may not honor it. Warn
@@ -1105,34 +1144,35 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1105
1144
  // Staging now lives in the session-private add-dir; sweep groups left
1106
1145
  // behind by dead sessions from the old scheme. Live sessions' and
1107
1146
  // foreign groups are never touched.
1108
- const sweptLegacy = sweepWorkspaceGateGroups(process.cwd());
1109
- 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
+ }
1110
1151
  if (mode === "off") {
1111
- // Gate off: drop this session's private hooks file. Other sessions
1112
- // own their own per-pid files; nothing shared to preserve.
1152
+ // Gate off: drop this session's private hooks file.
1113
1153
  const unstaged = removeGateHooks();
1114
1154
  if (unstaged.wrote) fileLog.log("approval-unstaged", unstaged, "info");
1115
1155
  } else {
1116
- // Script: per-pid file; 0600 because the bridge token is
1117
- // embedded (peer review 2026-09-07).
1118
- 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();
1119
1161
  fs.mkdirSync(path.dirname(scriptPath), { recursive: true, mode: 0o700 });
1120
1162
  fs.writeFileSync(
1121
1163
  scriptPath,
1122
1164
  hookScriptSource({
1123
1165
  port: r.handle.port,
1124
- token: r.handle.token,
1166
+ token: r.handle.realmToken,
1125
1167
  deadlineMs: APPROVAL_PARK_MS,
1126
1168
  }),
1127
1169
  { mode: 0o600 },
1128
1170
  );
1129
- gateScriptPath = scriptPath;
1130
- // Private per-pid staging (issue #5 isolation): the gate group goes
1131
- // into the bridge add-dir that ONLY this session's agy receives.
1132
- // 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.
1133
1173
  const staged = stageGateHooks(bridgeMcpConfigDir(), {
1134
1174
  port: r.handle.port,
1135
- token: r.handle.token,
1175
+ token: r.handle.realmToken,
1136
1176
  scriptPath,
1137
1177
  parkBudgetMs: APPROVAL_PARK_MS,
1138
1178
  });
@@ -1198,31 +1238,25 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1198
1238
  activeUi = null;
1199
1239
  const h = mcpHandle;
1200
1240
  mcpHandle = null;
1201
- // "recycle", NOT "shutdown": pi fires session_shutdown on /new, /resume
1202
- // and /fork (docs/extensions.md session lifecycle), not only on process
1203
- // exit. The drivers are process-lifetime singletons; closing them with
1204
- // "shutdown" latched them permanently and every later turn failed with
1205
- // "ACP driver is shut down." (regression 2026-09-07). Recycle kills the
1206
- // connection now; the next turn respawns it. event.reason is
1207
- // deliberately ignored: recycle is correct even on real process exit
1208
- // ("quit") - the connection kill is identical and nothing runs after.
1209
- await streamDriver.close("recycle", "session shutdown");
1210
- await acpDriver.close("recycle", "session shutdown");
1211
- roundTrips.failAll(FAIL_REASON_SHUTDOWN);
1212
- await h?.close();
1213
- if (engine === "stream-json") unregisterBridgeServer(process.pid);
1214
- hiddenBridgeTools.clear();
1215
- // Approval gate: unstage hooks and remove the per-pid script. Pending
1216
- // approvals already failed closed via handle close (bridge shutdown deny).
1217
- const unstaged = removeGateHooks();
1218
- if (unstaged.wrote) fileLog.log("approval-unstaged", unstaged, "info");
1219
- if (gateScriptPath) {
1220
- try {
1221
- fs.rmSync(gateScriptPath, { force: true });
1222
- } catch {
1223
- /* best effort */
1224
- }
1225
- 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;
1226
1260
  }
1227
1261
  });
1228
1262
  }
@@ -1249,6 +1283,7 @@ interface AgyCommandCtx {
1249
1283
  roster: SubagentRoster;
1250
1284
  pendingCompactionHandoff: Set<string>;
1251
1285
  checkAgySetup: (ctx: { ui: ExtensionUIContext; mode: string }, engine: Engine, explicit?: boolean) => Promise<void>;
1286
+ setActiveUi: (ui: ExtensionUIContext) => void;
1252
1287
  }
1253
1288
 
1254
1289
  interface PendingConfig {
@@ -1315,7 +1350,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1315
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]",
1316
1351
  handler: async (args, cmdCtx: ExtensionCommandContext) => {
1317
1352
  const ui = cmdCtx.ui;
1318
- if (ui) activeUi = ui;
1353
+ if (ui) ctx.setActiveUi(ui);
1319
1354
  const mode = cmdCtx.mode;
1320
1355
  const sub = (args ?? "").trim().split(/\s+/)[0]?.toLowerCase();
1321
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.2",
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
+ }
package/src/config.ts CHANGED
@@ -14,6 +14,7 @@ import fs from "node:fs";
14
14
  import path from "node:path";
15
15
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
16
16
  import { normalizeAgyAgentName } from "./agents.js";
17
+ import { writeJsonAtomic } from "./atomic-write.js";
17
18
 
18
19
  /** pi's agent dir (env override PI_CODING_AGENT_DIR, else ~/.pi/agent); every
19
20
  * bridge-owned path derives from it so isolated or rebranded pi homes keep
@@ -270,11 +271,11 @@ export function parseCapMinutes(raw: string | number | undefined, fallback: numb
270
271
  const BOOLISH_TRUE = new Set(["1", "true", "on"]);
271
272
  const BOOLISH_FALSE = new Set(["0", "false", "off"]);
272
273
 
273
- /** Parse a config.json boolean that a hand editor may have written as a
274
- * string ("off", "false", "0" - the README and /agy vocabulary) or as the
275
- * JSON numbers 0/1. Present but unparseable values fall back to the given
276
- * default and warn; the silence is what made issue #23 invisible. */
277
- function parseBoolish(raw: unknown, label: string, fallback: boolean, warnings: string[]): boolean {
274
+ /** The literal boolean grammar shared by parseBoolish, parseReadOnlyValue,
275
+ * and saveConfig's pass-through: JSON booleans, the /agy vocabulary as
276
+ * strings (case/whitespace tolerated), and the JSON numbers 0/1. Returns
277
+ * undefined for anything outside the grammar. */
278
+ function parseBoolishLiteral(raw: unknown): boolean | undefined {
278
279
  if (typeof raw === "boolean") return raw;
279
280
  if (raw === 0 || raw === 1) return raw === 1;
280
281
  if (typeof raw === "string") {
@@ -282,27 +283,32 @@ function parseBoolish(raw: unknown, label: string, fallback: boolean, warnings:
282
283
  if (BOOLISH_TRUE.has(v)) return true;
283
284
  if (BOOLISH_FALSE.has(v)) return false;
284
285
  }
286
+ return undefined;
287
+ }
288
+
289
+ /** Parse a config.json boolean that a hand editor may have written as a
290
+ * string ("off", "false", "0" - the README and /agy vocabulary) or as the
291
+ * JSON numbers 0/1. Present but unparseable values fall back to the given
292
+ * default and warn; the silence is what made issue #23 invisible. */
293
+ function parseBoolish(raw: unknown, label: string, fallback: boolean, warnings: string[]): boolean {
294
+ const v = parseBoolishLiteral(raw);
295
+ if (v !== undefined) return v;
285
296
  if (raw === undefined || raw === null) return fallback;
286
297
  warnings.push(`${label}: ${JSON.stringify(raw)} is not a recognized boolean (true/false, on/off, 1/0); using default ${fallback}`);
287
298
  return fallback;
288
299
  }
289
300
 
290
301
  /** File-path readOnly parse: the AGY_READONLY env grammar mirrored (issue
291
- * #23). Explicit blank and spelled-out falsities are OFF, every other
302
+ * #23). Explicit blanks and spelled-out falsities are OFF, every other
292
303
  * present value counts as ON so a typo can never disable the safety knob. */
293
304
  function parseReadOnlyValue(raw: unknown, warnings: string[]): boolean {
294
305
  const failClosed = (rawValue: unknown): boolean => {
295
306
  warnings.push(`readOnly: ${JSON.stringify(rawValue)} is not a recognized boolean (true/false, on/off, 1/0); failing closed to true`);
296
307
  return true;
297
308
  };
298
- if (typeof raw === "boolean") return raw;
299
- if (typeof raw === "string") {
300
- if (raw === "") return false;
301
- const v = raw.trim().toLowerCase();
302
- if (BOOLISH_FALSE.has(v)) return false;
303
- if (BOOLISH_TRUE.has(v)) return true;
304
- return failClosed(raw);
305
- }
309
+ const v = parseBoolishLiteral(raw);
310
+ if (v !== undefined) return v;
311
+ if (typeof raw === "string" && raw === "") return false;
306
312
  if (raw === undefined || raw === null) return DEFAULTS.readOnly;
307
313
  return failClosed(raw);
308
314
  }
@@ -338,9 +344,7 @@ export function removeLegacyAcpBin(configFile: string = configPath()): boolean {
338
344
  const acp = file.acp as Record<string, unknown>;
339
345
  if (!("bin" in acp)) return false;
340
346
  delete acp.bin;
341
- // Rename would replace a dotfiles-managed symlink with a regular file;
342
- // write through the resolved target so the link survives.
343
- writeConfigJson(fs.realpathSync(configFile), file);
347
+ writeJsonAtomic(configFile, file);
344
348
  return true;
345
349
  }
346
350
 
@@ -515,24 +519,6 @@ function narrowEngine(raw: string): Engine {
515
519
  return raw === "acp" || raw === "stream-json" ? raw : DEFAULT_ENGINE;
516
520
  }
517
521
 
518
- /** Atomic JSON write (temp + rename, 0600) shared by every config writer. */
519
- function writeConfigJson(configPath: string, value: unknown): void {
520
- const dir = path.dirname(configPath);
521
- fs.mkdirSync(dir, { recursive: true });
522
- const tmp = `${configPath}.${process.pid}.tmp`;
523
- try {
524
- fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
525
- fs.renameSync(tmp, configPath);
526
- } catch (err) {
527
- try {
528
- fs.unlinkSync(tmp);
529
- } catch {
530
- /* nothing to clean */
531
- }
532
- throw err;
533
- }
534
- }
535
-
536
522
  /** Atomically persist a config patch (temp + rename). Merges onto the RAW
537
523
  * FILE values, never loadConfig(): env overrides must not be baked into the
538
524
  * file (AGY_READONLY=1 in the env would otherwise persist readOnly: true to
@@ -562,10 +548,22 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
562
548
  patchAcp?.sessionTimeoutMs ?? fileAcp.sessionTimeoutMs,
563
549
  DEFAULTS.acp.sessionTimeoutMs,
564
550
  ),
565
- sessionRetryOnTimeout: patchAcp?.sessionRetryOnTimeout ?? (fileAcp.sessionRetryOnTimeout === true),
551
+ // Silent literal-grammar pass-through (saveConfig has no warning
552
+ // channel; loadConfig already reports junk at startup / /agy doctor).
553
+ sessionRetryOnTimeout:
554
+ patchAcp?.sessionRetryOnTimeout
555
+ ?? parseBoolishLiteral(fileAcp.sessionRetryOnTimeout)
556
+ ?? DEFAULTS.acp.sessionRetryOnTimeout,
566
557
  };
567
- const next: AgyConfig = {
568
- ...DEFAULTS,
558
+ // The DEFAULTS 0 is a load-time placeholder (defaultTurnTimeoutMin resolves
559
+ // per TTY state); persisting it would flip absence into "cap disabled"
560
+ // (parseCapMinutes reads 0 as off) on the next load.
561
+ const { turnTimeoutMin: _placeholder, ...defaultsOnDisk } = DEFAULTS;
562
+ // On-disk shape, not AgyConfig: turnTimeoutMin is written only when the
563
+ // file or the patch carries it, and a blanket cast would drop checking
564
+ // for every other key in the literal.
565
+ const next: Omit<AgyConfig, "turnTimeoutMin"> & Partial<Pick<AgyConfig, "turnTimeoutMin">> = {
566
+ ...defaultsOnDisk,
569
567
  ...file,
570
568
  ...(file.approvals !== undefined
571
569
  ? { approvals: { gateMode: fileApprovals.gateMode ?? DEFAULTS.approvals.gateMode, mode: fileApprovals.mode ?? DEFAULTS.approvals.mode } }
@@ -576,6 +574,6 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
576
574
  // Computed per load; a raw file spread must never persist it.
577
575
  parseWarnings: undefined,
578
576
  };
579
- writeConfigJson(configFile, next);
580
- return next;
577
+ writeJsonAtomic(configFile, next);
578
+ return next as AgyConfig;
581
579
  }
@@ -19,6 +19,7 @@ import fs from "node:fs";
19
19
  import os from "node:os";
20
20
  import path from "node:path";
21
21
  import { extensionsDataDir } from "./config.js";
22
+ import { writeJsonAtomic } from "./atomic-write.js";
22
23
 
23
24
  /** Name convention for the bridge's per-pid server entries. */
24
25
  export function bridgeServerName(pid: number): string {
@@ -70,10 +71,7 @@ function writeConfig(file: string, config: McpConfig): void {
70
71
  // 0700/0600: the file carries the bridge's shared-secret token in its
71
72
  // headers, and it lives in the USER'S global agy config (audit 2026-09-07:
72
73
  // it previously landed at the umask default, typically world-readable).
73
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
74
- const tmp = `${file}.${process.pid}.tmp`;
75
- fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });
76
- fs.renameSync(tmp, file);
74
+ writeJsonAtomic(file, config, { dirMode: 0o700 });
77
75
  }
78
76
 
79
77
  /** The canonical mcp_config.json entry shape for a bridge server. Single
@@ -205,10 +203,7 @@ function readSuppressionMarker(file: string): SuppressionMarker {
205
203
  }
206
204
 
207
205
  function writeSuppressionMarker(file: string, marker: SuppressionMarker): void {
208
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
209
- const tmp = `${file}.${process.pid}.tmp`;
210
- fs.writeFileSync(tmp, JSON.stringify(marker, null, 2) + "\n", { mode: 0o600 });
211
- fs.renameSync(tmp, file);
206
+ writeJsonAtomic(file, marker, { dirMode: 0o700 });
212
207
  }
213
208
 
214
209
  function delegatorLive(pid: string, entry: { since?: number } | undefined, isAlive: (pid: number) => boolean, now: number): boolean {
package/src/mcp-server.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  // Hardening:
9
9
  // - The whole request handler is wrapped so a client error (ECONNRESET on a
10
10
  // killed-mid-call agy) can never crash the pi process.
11
- // - Per-process config dir (agy-mcp-<pid>): concurrent pi sessions each own
12
- // their file; no shared-file race, no cross-session routing.
11
+ // - Per-process config dir (agy-mcp-<pid>) and one realm-shared HTTP listener
12
+ // with per-session route tokens: concurrent sessions stay isolated.
13
13
  // - Shared-secret header: agy sends it from the config; a browser cannot set a
14
14
  // custom header on a simple cross-origin POST, so this blocks CSRF against
15
15
  // the loopback server. Combined with 127.0.0.1 binding.
@@ -82,6 +82,10 @@ export interface McpServerHandle {
82
82
  token: string;
83
83
  /** Approval-gate park controls (docs/TODO.md 2.5). */
84
84
  approvals: ApprovalParkApi;
85
+ /** Serve another bridge surface on this listener behind its own token.
86
+ * Requests carrying that token reach `deps`; requests carrying `token`
87
+ * keep reaching the deps passed to startMcpServer. remove() revokes it. */
88
+ addRoute: (deps: McpBridgeDeps) => { token: string; remove: () => void };
85
89
  close: () => Promise<void>;
86
90
  }
87
91
 
@@ -286,18 +290,26 @@ export async function startMcpServer(
286
290
  log?: (s: string, d?: unknown) => void;
287
291
  /** Test override for the per-park timeout (deny, fail closed). */
288
292
  approvalTimeoutMs?: number;
293
+ /** Write the add-dir `.agents/mcp_config.json` carrying `token` (default
294
+ * true). The shared realm listener sets this false so each session
295
+ * reaches it on its own route token. */
296
+ addDirConfig?: boolean;
289
297
  } = {},
290
298
  ): Promise<McpStartResult> {
291
299
  const log = opts.log ?? (() => {});
292
300
  const approvalTimeoutMs = opts.approvalTimeoutMs ?? APPROVAL_PARK_TIMEOUT_MS;
293
301
 
294
- const listHandler = async () => {
295
- const tools = deps.listTools();
302
+ const listHandler = async (surface: McpBridgeDeps) => {
303
+ const tools = surface.listTools();
296
304
  log("list-tools", { count: tools.length });
297
305
  return { tools };
298
306
  };
299
307
 
300
- const callHandler = async (request: { params: { name: string; arguments?: unknown } }, signal?: AbortSignal) => {
308
+ const callHandler = async (
309
+ surface: McpBridgeDeps,
310
+ request: { params: { name: string; arguments?: unknown } },
311
+ signal?: AbortSignal,
312
+ ) => {
301
313
  const { name, arguments: args } = request.params;
302
314
  // Progress probe: agy's MCP client killed long bridge calls at exactly
303
315
  // ~180s (see ACP-PROTOCOL-REFERENCE). If its requests ever carry a
@@ -310,7 +322,7 @@ export async function startMcpServer(
310
322
  const callId = crypto.randomUUID();
311
323
  log("call-tool", { name, callId });
312
324
  try {
313
- const r = await deps.onToolCall(
325
+ const r = await surface.onToolCall(
314
326
  callId,
315
327
  name,
316
328
  (args && typeof args === "object" ? args : {}) as Record<string, unknown>,
@@ -327,13 +339,13 @@ export async function startMcpServer(
327
339
  }
328
340
  };
329
341
 
330
- const makeServer = (signal: AbortSignal) => {
342
+ const makeServer = (surface: McpBridgeDeps, signal: AbortSignal) => {
331
343
  const s = new Server(
332
344
  { name: "pi-antigravity-bridge", version: "1.1.0" },
333
345
  { capabilities: { tools: {} } },
334
346
  );
335
- s.setRequestHandler(ListToolsRequestSchema, listHandler);
336
- s.setRequestHandler(CallToolRequestSchema, (request) => callHandler(request, signal));
347
+ s.setRequestHandler(ListToolsRequestSchema, () => listHandler(surface));
348
+ s.setRequestHandler(CallToolRequestSchema, (request) => callHandler(surface, request, signal));
337
349
  return s;
338
350
  };
339
351
 
@@ -371,13 +383,19 @@ export async function startMcpServer(
371
383
  res.writeHead(200, { "content-type": "application/json" });
372
384
  res.end(decisionBody({ allow: false, reason }));
373
385
  };
374
- const tokenOk = (req: http.IncomingMessage): boolean => {
386
+ // Extra surfaces (addRoute): token -> deps. The handle token keeps serving
387
+ // the deps passed in, so a single-surface caller sees no change.
388
+ const routes = new Map<string, McpBridgeDeps>();
389
+ const sameToken = (received: string, expected: string): boolean =>
390
+ received.length === expected.length && crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
391
+ const surfaceFor = (req: http.IncomingMessage): McpBridgeDeps | null => {
375
392
  const received = req.headers[TOKEN_HEADER];
376
- return (
377
- typeof received === "string" &&
378
- received.length === token.length &&
379
- crypto.timingSafeEqual(Buffer.from(received), Buffer.from(token))
380
- );
393
+ if (typeof received !== "string") return null;
394
+ if (sameToken(received, token)) return deps;
395
+ for (const [routeToken, routeDeps] of routes) {
396
+ if (sameToken(received, routeToken)) return routeDeps;
397
+ }
398
+ return null;
381
399
  };
382
400
  const readBody = async (req: http.IncomingMessage): Promise<string | null> => {
383
401
  let body = "";
@@ -394,7 +412,8 @@ export async function startMcpServer(
394
412
  res: http.ServerResponse,
395
413
  route: string,
396
414
  ): Promise<void> => {
397
- if (!tokenOk(req)) {
415
+ const surface = surfaceFor(req);
416
+ if (!surface) {
398
417
  log("unauthorized", { url: req.url });
399
418
  res.writeHead(403, { "content-type": "application/json" }).end('{"error":"forbidden"}');
400
419
  return;
@@ -425,7 +444,7 @@ export async function startMcpServer(
425
444
  denyDirect(res, `tool ${payload.toolCall.name} is not in the approval matcher set`);
426
445
  return;
427
446
  }
428
- if (typeof deps.onApproval !== "function") {
447
+ if (typeof surface.onApproval !== "function") {
429
448
  log("approval-unwired", { name: payload.toolCall.name });
430
449
  denyDirect(res, "approval gate is not wired; denying");
431
450
  return;
@@ -438,10 +457,11 @@ export async function startMcpServer(
438
457
  settlePark(ticket, { allow: false, reason: `approval gate timed out after ${Math.round(approvalTimeoutMs / 1000)}s` });
439
458
  log("approval-timeout", { ticket, name: payload.toolCall.name });
440
459
  }, approvalTimeoutMs);
460
+ timer.unref();
441
461
  parks.set(ticket, { name: payload.toolCall.name, since: Date.now(), timer });
442
462
  log("approval-parked", { ticket, name: payload.toolCall.name });
443
463
  try {
444
- deps.onApproval(ticket, payload);
464
+ surface.onApproval(ticket, payload);
445
465
  } catch (e) {
446
466
  // A throwing provider must never hang the hook: settle deny now.
447
467
  log("approval-onapproval-fail", { ticket, msg: e instanceof Error ? e.message : String(e) });
@@ -501,7 +521,8 @@ export async function startMcpServer(
501
521
  }
502
522
  // #3: require the shared-secret header. Constant-time compare so a
503
523
  // timing oracle can't recover the token byte-by-byte.
504
- if (!tokenOk(req)) {
524
+ const surface = surfaceFor(req);
525
+ if (!surface) {
505
526
  log("unauthorized", { url: req.url });
506
527
  res.writeHead(403, { "content-type": "application/json" }).end('{"error":"forbidden"}');
507
528
  return;
@@ -551,7 +572,7 @@ export async function startMcpServer(
551
572
  // Stateless: a fresh transport+server per request.
552
573
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
553
574
  transport.onerror = (e: Error) => log("transport-error", e.message);
554
- const server = makeServer(ac.signal);
575
+ const server = makeServer(surface, ac.signal);
555
576
  await server.connect(transport);
556
577
  await transport.handleRequest(req, res, parsed as object);
557
578
  } catch (e) {
@@ -582,8 +603,10 @@ export async function startMcpServer(
582
603
  return;
583
604
  }
584
605
  try {
585
- writeBridgeMcpConfig(port, token);
586
- log("bridge-config-written", { port, path: bridgeMcpConfigPath() });
606
+ if (opts.addDirConfig !== false) {
607
+ writeBridgeMcpConfig(port, token);
608
+ log("bridge-config-written", { port, path: bridgeMcpConfigPath() });
609
+ }
587
610
  } catch (e) {
588
611
  log("bridge-config-write-failed", e instanceof Error ? e.message : String(e));
589
612
  }
@@ -598,6 +621,11 @@ export async function startMcpServer(
598
621
  port,
599
622
  token,
600
623
  approvals: approvalsApi,
624
+ addRoute: (routeDeps) => {
625
+ const routeToken = crypto.randomBytes(24).toString("hex");
626
+ routes.set(routeToken, routeDeps);
627
+ return { token: routeToken, remove: () => void routes.delete(routeToken) };
628
+ },
601
629
  close: async () => {
602
630
  // Pending approvals fail closed on shutdown: the hook gets a
603
631
  // terminal deny instead of a 404 on its next poll.
@@ -605,7 +633,10 @@ export async function startMcpServer(
605
633
  if (p.terminal) continue;
606
634
  settlePark(ticket, { allow: false, reason: "approval gate bridge shut down" });
607
635
  }
608
- await new Promise<void>((r) => httpServer.close(() => r()));
636
+ routes.clear();
637
+ const closed = new Promise<void>((r) => httpServer.close(() => r()));
638
+ httpServer.closeAllConnections?.();
639
+ await closed;
609
640
  removeBridgeMcpConfig();
610
641
  disposeExitCleanup();
611
642
  log("bridge-config-removed", { port });
@@ -57,6 +57,8 @@ export function mapAgyToolToNative(
57
57
  args: Record<string, unknown>,
58
58
  ): NativeToolCall | undefined {
59
59
  switch (tool) {
60
+ // agy 1.5.14 renamed view_file to read_file (same Path/StartLine/EndLine args).
61
+ case "read_file":
60
62
  case "view_file": {
61
63
  if (!onlyKeys(args, [...VIEW_PATH_KEYS, ...START_LINE_KEYS, ...END_LINE_KEYS])) {
62
64
  return undefined;
package/src/runtime.ts ADDED
@@ -0,0 +1,310 @@
1
+ // Realm-wide bridge runtime for multi-session pi processes (e.g. subagents).
2
+ //
3
+ // When multiple sessions bind the extension factory in the same JS realm,
4
+ // module state is shared, pi-ai's provider registry is process-global (the last
5
+ // registerProvider wins), and each session fires its own session_start and
6
+ // session_shutdown. Left uncoordinated, a child session overwrites the parent's
7
+ // provider and its shutdown deletes process.pid-keyed artifacts (bridge dir,
8
+ // approval hook script, global MCP entry) while the parent still runs.
9
+ //
10
+ // One realm per JS realm (globalThis) owns the shared pieces:
11
+ // - SessionStore (single writer per sessions.json);
12
+ // - one stable streamSimple that routes each call by options.sessionId;
13
+ // - one MCP listener with per-session route tokens (sessions use their own
14
+ // token in ACP mcpServers / isolated stream-json home; shared per-realm
15
+ // artifacts carry realmToken and resolve to the active streaming session);
16
+ // - refcounted teardown of per-realm artifacts when the last session leaves.
17
+
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import {
21
+ createAssistantMessageEventStream,
22
+ type Api,
23
+ type AssistantMessage,
24
+ type AssistantMessageEventStream,
25
+ type Model,
26
+ type SimpleStreamOptions,
27
+ type TranscriptContext,
28
+ } from "@earendil-works/pi-ai";
29
+ import { logsDir } from "./config.js";
30
+ import { unregisterBridgeServer } from "./mcp-registration.js";
31
+ import { startMcpServer, type McpBridgeDeps, type McpServerHandle, type McpStartResult } from "./mcp-server.js";
32
+ import { SessionStore } from "./sessions.js";
33
+
34
+ const REALM_KEY = Symbol.for("pi-antigravity-bridge.runtime");
35
+ const REALM_BRAND = Symbol.for("pi-antigravity-bridge.realm.brand");
36
+
37
+ /** The approval hook script of this realm (one per process, realmToken embedded). */
38
+ export function approvalHookScriptPath(): string {
39
+ return path.join(logsDir(), `approval-hook-${process.pid}.js`);
40
+ }
41
+
42
+ /** Read the session manager's current session id live (changes across /new and /resume). */
43
+ export function liveSessionId(sessionManager: unknown): string | undefined {
44
+ if (typeof sessionManager !== "object" || sessionManager === null || !("getSessionId" in sessionManager)) {
45
+ return undefined;
46
+ }
47
+ const read = (sessionManager as { getSessionId?: unknown }).getSessionId;
48
+ if (typeof read !== "function") return undefined;
49
+ try {
50
+ const id: unknown = read.call(sessionManager);
51
+ return typeof id === "string" && id.length > 0 ? id : undefined;
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ export type BridgeStreamSimple = (
58
+ model: Model<Api>,
59
+ context: TranscriptContext,
60
+ options?: SimpleStreamOptions,
61
+ ) => AssistantMessageEventStream;
62
+
63
+ export interface SessionPort {
64
+ sessionId(): string | undefined;
65
+ streamSimple: BridgeStreamSimple;
66
+ hasActiveTurn(): boolean;
67
+ conversationId(): string | undefined;
68
+ }
69
+
70
+ /** A session's view of the bridge listener. `token` is the session's own
71
+ * route; `realmToken` is the listener token carried by per-realm artifacts. */
72
+ export type BridgeEndpoint = Omit<McpServerHandle, "addRoute"> & {
73
+ realmToken: string;
74
+ };
75
+
76
+ export interface BridgeAttachResult {
77
+ ok: boolean;
78
+ reason?: string;
79
+ handle?: BridgeEndpoint;
80
+ first: boolean;
81
+ }
82
+
83
+ export interface RealmSession {
84
+ attachBridge(deps: McpBridgeDeps, log: (event: string, data?: unknown) => void): Promise<BridgeAttachResult>;
85
+ leave(): Promise<void>;
86
+ }
87
+
88
+ export interface BridgeRealm {
89
+ readonly store: SessionStore;
90
+ readonly streamSimple: BridgeStreamSimple;
91
+ join(port: SessionPort): RealmSession;
92
+ }
93
+
94
+ interface Member {
95
+ port: SessionPort;
96
+ bridge?: McpBridgeDeps;
97
+ log?: (event: string, data?: unknown) => void;
98
+ route?: { token: string; remove(): void };
99
+ }
100
+
101
+ const NO_TURN = "no active antigravity turn; the pi tool bridge only works while an antigravity model is streaming";
102
+ const SEVERAL_TURNS =
103
+ "several antigravity sessions are streaming in this process and this request carries no session token";
104
+
105
+ class Realm implements BridgeRealm {
106
+ readonly [REALM_BRAND] = true;
107
+ #store: SessionStore | undefined;
108
+ readonly #members = new Set<Member>();
109
+ #starting: Promise<McpStartResult> | null = null;
110
+ #server: McpServerHandle | null = null;
111
+ #closing: Promise<void> = Promise.resolve();
112
+
113
+ get store(): SessionStore {
114
+ this.#store ??= new SessionStore();
115
+ return this.#store;
116
+ }
117
+
118
+ readonly streamSimple: BridgeStreamSimple = (model, context, options) => {
119
+ const member = this.#memberFor(options?.sessionId);
120
+ if (!member) return refusedStream(model, "Antigravity bridge: no live session in this process");
121
+ return member.port.streamSimple(model, context, options);
122
+ };
123
+
124
+ join(port: SessionPort): RealmSession {
125
+ const member: Member = { port };
126
+ this.#members.add(member);
127
+ let left = false;
128
+ return {
129
+ attachBridge: (deps, log) => this.#attach(member, deps, log),
130
+ leave: async () => {
131
+ if (left) return;
132
+ left = true;
133
+ member.route?.remove();
134
+ this.#members.delete(member);
135
+ if (this.#members.size === 0) await this.#teardown();
136
+ },
137
+ };
138
+ }
139
+
140
+ async dispose(): Promise<void> {
141
+ this.#members.clear();
142
+ await this.#teardown();
143
+ }
144
+
145
+ #memberFor(sessionId: string | undefined): Member | undefined {
146
+ const members = [...this.#members];
147
+ if (sessionId) {
148
+ // Prefer newest member when a reload temporarily overlaps two sessions with the same id.
149
+ for (let i = members.length - 1; i >= 0; i--) {
150
+ if (members[i].port.sessionId() === sessionId) return members[i];
151
+ }
152
+ for (let i = members.length - 1; i >= 0; i--) {
153
+ const id = members[i].port.sessionId();
154
+ if (id !== undefined && sessionId.startsWith(`${id}:`)) return members[i];
155
+ }
156
+ }
157
+ return members.length === 1 ? members[0] : undefined;
158
+ }
159
+
160
+ async #attach(
161
+ member: Member,
162
+ deps: McpBridgeDeps,
163
+ log: (event: string, data?: unknown) => void,
164
+ ): Promise<BridgeAttachResult> {
165
+ member.bridge = deps;
166
+ member.log = log;
167
+ const first = this.#starting === null;
168
+ const starting = (this.#starting ??= this.#closing.then(() =>
169
+ startMcpServer(this.#router, { log: (event, data) => this.#log(event, data), addDirConfig: false }),
170
+ ));
171
+ let started: McpStartResult;
172
+ try {
173
+ started = await starting;
174
+ } catch (err) {
175
+ if (this.#starting === starting) this.#starting = null;
176
+ throw err;
177
+ }
178
+ if (!started.ok || !started.handle) {
179
+ if (this.#starting === starting) this.#starting = null;
180
+ return { ok: false, reason: started.reason, first };
181
+ }
182
+ if (!this.#members.has(member)) {
183
+ return { ok: false, reason: "session ended before the bridge started", first };
184
+ }
185
+ const server = started.handle;
186
+ this.#server = server;
187
+ member.route?.remove();
188
+ const route = server.addRoute(deps);
189
+ member.route = route;
190
+ return {
191
+ ok: true,
192
+ first,
193
+ handle: {
194
+ port: server.port,
195
+ token: route.token,
196
+ realmToken: server.token,
197
+ approvals: server.approvals,
198
+ close: async () => route.remove(),
199
+ },
200
+ };
201
+ }
202
+
203
+ async #teardown(): Promise<void> {
204
+ const starting = this.#starting;
205
+ this.#starting = null;
206
+ this.#server = null;
207
+ if (!starting) return;
208
+ this.#closing = (async () => {
209
+ const started = await starting;
210
+ await started.handle?.close();
211
+ fs.rmSync(approvalHookScriptPath(), { force: true });
212
+ unregisterBridgeServer(process.pid);
213
+ })().catch(() => {
214
+ /* best effort */
215
+ });
216
+ await this.#closing;
217
+ }
218
+
219
+ readonly #router: McpBridgeDeps = {
220
+ listTools: () => {
221
+ const attached = [...this.#members].filter((m) => m.bridge);
222
+ const target = this.#streaming() ?? (attached.length === 1 ? attached[0] : undefined);
223
+ if (target?.bridge) return target.bridge.listTools();
224
+ this.#log("list-tools-refused", { reason: this.#unattributed(), sessions: attached.length });
225
+ return [];
226
+ },
227
+ onToolCall: (callId, name, args, signal) => {
228
+ const target = this.#streaming();
229
+ if (!target?.bridge) return Promise.reject(new Error(this.#unattributed()));
230
+ return target.bridge.onToolCall(callId, name, args, signal);
231
+ },
232
+ onApproval: (ticket, payload) => {
233
+ const conversationId = typeof payload.conversationId === "string" ? payload.conversationId : undefined;
234
+ const onApproval = this.#streaming(conversationId)?.bridge?.onApproval;
235
+ if (onApproval) {
236
+ onApproval(ticket, payload);
237
+ return;
238
+ }
239
+ this.#server?.approvals.resolve(ticket, { allow: false, reason: `approval gate: ${this.#unattributed()}` });
240
+ },
241
+ };
242
+
243
+ #streaming(conversationId?: string): Member | undefined {
244
+ const open = [...this.#members].filter((m) => m.bridge && m.port.hasActiveTurn());
245
+ if (open.length === 1) return open[0];
246
+ if (conversationId === undefined) return undefined;
247
+ const owners = open.filter((m) => m.port.conversationId() === conversationId);
248
+ return owners.length === 1 ? owners[0] : undefined;
249
+ }
250
+
251
+ #unattributed(): string {
252
+ const open = [...this.#members].filter((m) => m.bridge && m.port.hasActiveTurn());
253
+ return open.length > 1 ? SEVERAL_TURNS : NO_TURN;
254
+ }
255
+
256
+ #log(event: string, data?: unknown): void {
257
+ const sink = [...this.#members].find((m) => m.log)?.log;
258
+ if (!sink) return;
259
+ try {
260
+ sink(event, data);
261
+ } catch {
262
+ /* a dead session UI must never break the shared listener */
263
+ }
264
+ }
265
+ }
266
+
267
+ function refusedStream(model: Model<Api>, message: string): AssistantMessageEventStream {
268
+ const stream = createAssistantMessageEventStream();
269
+ const error: AssistantMessage = {
270
+ role: "assistant",
271
+ content: [],
272
+ api: model.api,
273
+ provider: model.provider,
274
+ model: model.id,
275
+ usage: {
276
+ input: 0,
277
+ output: 0,
278
+ cacheRead: 0,
279
+ cacheWrite: 0,
280
+ totalTokens: 0,
281
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
282
+ },
283
+ stopReason: "error",
284
+ errorMessage: message,
285
+ timestamp: Date.now(),
286
+ };
287
+ stream.push({ type: "error", reason: "error", error });
288
+ stream.end();
289
+ return stream;
290
+ }
291
+
292
+ function isRealm(value: unknown): value is Realm {
293
+ return typeof value === "object" && value !== null && Reflect.get(value, REALM_BRAND) === true;
294
+ }
295
+
296
+ /** This realm's bridge runtime, created on first use. */
297
+ export function bridgeRealm(): BridgeRealm {
298
+ const existing: unknown = Reflect.get(globalThis, REALM_KEY);
299
+ if (isRealm(existing)) return existing;
300
+ const realm = new Realm();
301
+ Reflect.set(globalThis, REALM_KEY, realm);
302
+ return realm;
303
+ }
304
+
305
+ /** Drop the realm (closing its listener) so each test starts clean. */
306
+ export async function __resetRealmForTests(): Promise<void> {
307
+ const existing: unknown = Reflect.get(globalThis, REALM_KEY);
308
+ Reflect.deleteProperty(globalThis, REALM_KEY);
309
+ if (isRealm(existing)) await existing.dispose();
310
+ }
package/src/sessions.ts CHANGED
@@ -190,6 +190,17 @@ export class SessionStore {
190
190
  });
191
191
  }
192
192
 
193
+ /** Resolve once every queued write (set, delete, clear) has reached disk,
194
+ * including writes queued while waiting. Never rejects: failed writes are
195
+ * already swallowed by the chain. */
196
+ async flush(): Promise<void> {
197
+ let pending: Promise<void>;
198
+ do {
199
+ pending = this.writeChain;
200
+ await pending;
201
+ } while (pending !== this.writeChain);
202
+ }
203
+
193
204
  /** Count persisted session bindings (for status display). */
194
205
  get size(): number {
195
206
  return Object.keys(this.cache).length;