@estebanforge/pi-antigravity-bridge 1.13.2 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -174,6 +175,11 @@ export interface AgyConfig {
174
175
  * message, and a conversation opened mid-session starts without prior
175
176
  * pi-side context. */
176
177
  digest: boolean;
178
+ /** Migration marker (issue #25): set once when a stale persisted
179
+ * digest:false from the pre-default-flip era is upgraded to the ON
180
+ * default. Presence keeps later deliberate `/agy digest off` choices
181
+ * from being re-migrated. */
182
+ digestMigrated?: boolean;
177
183
  /** Prepend pi's composed system prompt (pi tool guidance + the global
178
184
  * agent-dir AGENTS.md and ancestor AGENTS.md/CLAUDE.md) to the FIRST
179
185
  * prompt of each fresh agy conversation.
@@ -270,11 +276,11 @@ export function parseCapMinutes(raw: string | number | undefined, fallback: numb
270
276
  const BOOLISH_TRUE = new Set(["1", "true", "on"]);
271
277
  const BOOLISH_FALSE = new Set(["0", "false", "off"]);
272
278
 
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 {
279
+ /** The literal boolean grammar shared by parseBoolish, parseReadOnlyValue,
280
+ * and saveConfig's pass-through: JSON booleans, the /agy vocabulary as
281
+ * strings (case/whitespace tolerated), and the JSON numbers 0/1. Returns
282
+ * undefined for anything outside the grammar. */
283
+ function parseBoolishLiteral(raw: unknown): boolean | undefined {
278
284
  if (typeof raw === "boolean") return raw;
279
285
  if (raw === 0 || raw === 1) return raw === 1;
280
286
  if (typeof raw === "string") {
@@ -282,27 +288,32 @@ function parseBoolish(raw: unknown, label: string, fallback: boolean, warnings:
282
288
  if (BOOLISH_TRUE.has(v)) return true;
283
289
  if (BOOLISH_FALSE.has(v)) return false;
284
290
  }
291
+ return undefined;
292
+ }
293
+
294
+ /** Parse a config.json boolean that a hand editor may have written as a
295
+ * string ("off", "false", "0" - the README and /agy vocabulary) or as the
296
+ * JSON numbers 0/1. Present but unparseable values fall back to the given
297
+ * default and warn; the silence is what made issue #23 invisible. */
298
+ function parseBoolish(raw: unknown, label: string, fallback: boolean, warnings: string[]): boolean {
299
+ const v = parseBoolishLiteral(raw);
300
+ if (v !== undefined) return v;
285
301
  if (raw === undefined || raw === null) return fallback;
286
302
  warnings.push(`${label}: ${JSON.stringify(raw)} is not a recognized boolean (true/false, on/off, 1/0); using default ${fallback}`);
287
303
  return fallback;
288
304
  }
289
305
 
290
306
  /** File-path readOnly parse: the AGY_READONLY env grammar mirrored (issue
291
- * #23). Explicit blank and spelled-out falsities are OFF, every other
307
+ * #23). Explicit blanks and spelled-out falsities are OFF, every other
292
308
  * present value counts as ON so a typo can never disable the safety knob. */
293
309
  function parseReadOnlyValue(raw: unknown, warnings: string[]): boolean {
294
310
  const failClosed = (rawValue: unknown): boolean => {
295
311
  warnings.push(`readOnly: ${JSON.stringify(rawValue)} is not a recognized boolean (true/false, on/off, 1/0); failing closed to true`);
296
312
  return true;
297
313
  };
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
- }
314
+ const v = parseBoolishLiteral(raw);
315
+ if (v !== undefined) return v;
316
+ if (typeof raw === "string" && raw === "") return false;
306
317
  if (raw === undefined || raw === null) return DEFAULTS.readOnly;
307
318
  return failClosed(raw);
308
319
  }
@@ -338,12 +349,26 @@ export function removeLegacyAcpBin(configFile: string = configPath()): boolean {
338
349
  const acp = file.acp as Record<string, unknown>;
339
350
  if (!("bin" in acp)) return false;
340
351
  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);
352
+ writeJsonAtomic(configFile, file);
344
353
  return true;
345
354
  }
346
355
 
356
+ /** One-time handoff for upgraders from the digest-off default era (issue
357
+ * #25): pre-flip saves baked digest:false into config.json as a bare
358
+ * default, and silently keeping it makes mid-session handoffs lose
359
+ * history. Runs at session_start (loadConfig stays side-effect free);
360
+ * AGY_DIGEST env wins; the marker key keeps a deliberate post-migration
361
+ * `/agy digest off` from being flipped back. Returns whether a stale
362
+ * false was rewritten (caller warns once). */
363
+ export function migrateStaleDigestDefault(configFile: string = configPath()): { migrated: boolean } {
364
+ const file = readConfigFile(configFile);
365
+ if (process.env.AGY_DIGEST !== undefined) return { migrated: false };
366
+ if (file.digestMigrated) return { migrated: false };
367
+ if (file.digest !== false) return { migrated: false };
368
+ saveConfig({ digest: true, digestMigrated: true }, configFile);
369
+ return { migrated: true };
370
+ }
371
+
347
372
  /** Load config merged over defaults. Env vars override the file when set. */
348
373
  export function loadConfig(configFile: string = configPath()): AgyConfig {
349
374
  let file: Partial<AgyConfig> = readConfigFile(configFile);
@@ -515,24 +540,6 @@ function narrowEngine(raw: string): Engine {
515
540
  return raw === "acp" || raw === "stream-json" ? raw : DEFAULT_ENGINE;
516
541
  }
517
542
 
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
543
  /** Atomically persist a config patch (temp + rename). Merges onto the RAW
537
544
  * FILE values, never loadConfig(): env overrides must not be baked into the
538
545
  * file (AGY_READONLY=1 in the env would otherwise persist readOnly: true to
@@ -562,10 +569,22 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
562
569
  patchAcp?.sessionTimeoutMs ?? fileAcp.sessionTimeoutMs,
563
570
  DEFAULTS.acp.sessionTimeoutMs,
564
571
  ),
565
- sessionRetryOnTimeout: patchAcp?.sessionRetryOnTimeout ?? (fileAcp.sessionRetryOnTimeout === true),
572
+ // Silent literal-grammar pass-through (saveConfig has no warning
573
+ // channel; loadConfig already reports junk at startup / /agy doctor).
574
+ sessionRetryOnTimeout:
575
+ patchAcp?.sessionRetryOnTimeout
576
+ ?? parseBoolishLiteral(fileAcp.sessionRetryOnTimeout)
577
+ ?? DEFAULTS.acp.sessionRetryOnTimeout,
566
578
  };
567
- const next: AgyConfig = {
568
- ...DEFAULTS,
579
+ // The DEFAULTS 0 is a load-time placeholder (defaultTurnTimeoutMin resolves
580
+ // per TTY state); persisting it would flip absence into "cap disabled"
581
+ // (parseCapMinutes reads 0 as off) on the next load.
582
+ const { turnTimeoutMin: _placeholder, ...defaultsOnDisk } = DEFAULTS;
583
+ // On-disk shape, not AgyConfig: turnTimeoutMin is written only when the
584
+ // file or the patch carries it, and a blanket cast would drop checking
585
+ // for every other key in the literal.
586
+ const next: Omit<AgyConfig, "turnTimeoutMin"> & Partial<Pick<AgyConfig, "turnTimeoutMin">> = {
587
+ ...defaultsOnDisk,
569
588
  ...file,
570
589
  ...(file.approvals !== undefined
571
590
  ? { approvals: { gateMode: fileApprovals.gateMode ?? DEFAULTS.approvals.gateMode, mode: fileApprovals.mode ?? DEFAULTS.approvals.mode } }
@@ -576,6 +595,6 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
576
595
  // Computed per load; a raw file spread must never persist it.
577
596
  parseWarnings: undefined,
578
597
  };
579
- writeConfigJson(configFile, next);
580
- return next;
598
+ writeJsonAtomic(configFile, next);
599
+ return next as AgyConfig;
581
600
  }
@@ -39,6 +39,14 @@ export interface DriverTurnRequest extends DriverProfile {
39
39
  * resource block instead of inline prompt text (G1 on ACP). Stream-json
40
40
  * embeds the digest in the prompt string and ignores this. */
41
41
  contextBlock?: { uri: string; text: string };
42
+ /** Fresh-session variant for the ACP load-failure path (issue #25): when
43
+ * session/load fails and the driver falls back to a new session, it
44
+ * swaps prompt/contextBlock for this, so the fresh conversation still
45
+ * receives the system prompt and the full bound:false digest instead of
46
+ * answering blind. The provider prebuilds it for bound turns; the
47
+ * stream-json driver ignores it (the CLI drops stale ids silently and
48
+ * the swap point is undetectable). */
49
+ fallback?: { prompt: string; contextBlock?: { uri: string; text: string } };
42
50
  signal?: AbortSignal;
43
51
  /** Overall turn cap in minutes (default 10). Fractional values are valid
44
52
  * (tests use sub-minute caps). 0 disables the cap. */
@@ -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;