@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/provider.ts CHANGED
@@ -41,6 +41,7 @@ import { mapAgyToolToNative } from "./native-tools.js";
41
41
  import { toAgyEffort, type AgyModelEntry } from "./models.js";
42
42
  import { SessionStore } from "./sessions.js";
43
43
  import { detectQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
44
+ import { redactText } from "./redact.js";
44
45
  import { loadConfig } from "./config.js";
45
46
  import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-gate.js";
46
47
  import type { ApprovalDecision, ApprovalPayload, ApprovalParkApi } from "./mcp-server.js";
@@ -287,6 +288,39 @@ function stripCompactionWrapping(t: string): string {
287
288
  return t.trim();
288
289
  }
289
290
 
291
+ /** Per-part body caps so one oversized entry cannot starve the delta budget
292
+ * (issue #25: a single >8KB tool result used to erase every earlier turn).
293
+ * Head+tail keeps the result's opening and its final summary/error lines. */
294
+ const TOOL_RESULT_HEAD = 800;
295
+ const TOOL_RESULT_TAIL = 300;
296
+
297
+ function capToolResultBody(t: string): string {
298
+ if (!t) return "(no text output)";
299
+ const overflow = t.length - TOOL_RESULT_HEAD - TOOL_RESULT_TAIL;
300
+ if (overflow <= 0) return t;
301
+ return `${t.slice(0, TOOL_RESULT_HEAD)}\n[${overflow} chars elided]\n${t.slice(-TOOL_RESULT_TAIL)}`;
302
+ }
303
+
304
+ const TOOL_CALL_ARGS_CAP = 200;
305
+
306
+ function renderToolCalls(content: unknown): string {
307
+ if (!Array.isArray(content)) return "";
308
+ const lines: string[] = [];
309
+ for (const b of content) {
310
+ if (typeof b !== "object" || b === null || (b as { type?: string }).type !== "toolCall") continue;
311
+ const { name, arguments: args } = b as { name?: string; arguments?: unknown };
312
+ let argsText: string;
313
+ try {
314
+ argsText = JSON.stringify(args ?? {});
315
+ } catch {
316
+ argsText = "(unserializable args)";
317
+ }
318
+ if (argsText.length > TOOL_CALL_ARGS_CAP) argsText = `${argsText.slice(0, TOOL_CALL_ARGS_CAP)}…`;
319
+ lines.push(`[tool call: ${name ?? "?"}(${redactText(argsText)})]`);
320
+ }
321
+ return lines.join("\n");
322
+ }
323
+
290
324
  export interface DigestOptions {
291
325
  /** Provider id whose assistant turns are already in agy's own DB and so
292
326
  * must be skipped to avoid double-counting. Default "antigravity". */
@@ -321,6 +355,13 @@ export interface DigestOptions {
321
355
  /** Soft cap on the digest body when no tighter budget applies. */
322
356
  const DIGEST_MAX_CHARS = 8000;
323
357
 
358
+ /** ACP digest cap: the embeddedContext transport carried a 120k-char probe
359
+ * block with exact needle recall at both block extremities
360
+ * (scripts/probe-acp-context.mjs, 2026-11-24), so 24k is transport-safe
361
+ * and shrinks the newest-first partial-render hole. stream-json keeps
362
+ * DIGEST_MAX_CHARS: its digest rides inline under the prompt byte cap. */
363
+ const ACP_DIGEST_MAX_CHARS = 24_000;
364
+
324
365
  /** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
325
366
  * the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
326
367
  * and the dropped turn leaves the conversation permanently unresponsive. */
@@ -329,13 +370,13 @@ const STREAM_JSON_PROMPT_CAP = 25_000;
329
370
  const STREAM_JSON_PROMPT_MARGIN = 4_096;
330
371
 
331
372
  /** Per-engine digest cap. ACP ships the digest as an embeddedContext
332
- resource block: no prompt cap applies, so the default cap stands. On
333
- stream-json the digest rides inline in the prompt, so it must fit under
373
+ resource block: no prompt cap applies, so the probe-raised cap stands.
374
+ On stream-json the digest rides inline in the prompt, so it must fit under
334
375
  the silent-drop budget alongside the user's own prompt bytes. Returns
335
376
  null when the budget is already exhausted (ship nothing rather than a
336
377
  digest that would push the turn over the drop cap). */
337
378
  export function digestMaxCharsForEngine(engine: string, promptLength: number): number | null {
338
- if (engine === "acp") return DIGEST_MAX_CHARS;
379
+ if (engine === "acp") return ACP_DIGEST_MAX_CHARS;
339
380
  const budget = STREAM_JSON_PROMPT_CAP - promptLength - STREAM_JSON_PROMPT_MARGIN;
340
381
  return budget > 0 ? Math.min(DIGEST_MAX_CHARS, budget) : null;
341
382
  }
@@ -393,16 +434,36 @@ export function compactionFingerprint(m: Message): string {
393
434
  * Fidelity note: other-provider assistant turns contribute only their text
394
435
  * blocks; tool-call and thinking blocks are dropped. The intent (which tool)
395
436
  * is lost, but their results still surface separately as toolResult messages. */
396
- export function buildContextDigest(
437
+ export interface DigestResult {
438
+ /** Digest body, "" when nothing rendered. */
439
+ text: string;
440
+ /** First index of the delta window (after clamp adjustments). */
441
+ windowStart: number;
442
+ /** Exclusive window end (run extraction boundary). */
443
+ windowEnd: number;
444
+ /** Oldest message index whose content is actually in the digest.
445
+ * == windowStart when the whole window rendered; == windowEnd when
446
+ * nothing fit; in between when the budget cut old turns (the pi-lens
447
+ * watermark invariant: the record may only claim delivery of what
448
+ * rendered). */
449
+ deliveredFrom: number;
450
+ }
451
+
452
+ export function buildContextDigestResult(
397
453
  messages: Message[],
398
454
  watermark: number,
399
455
  opts: DigestOptions = {},
400
- ): string {
456
+ ): DigestResult {
401
457
  const own = opts.ownProvider ?? "antigravity";
402
458
  const maxChars = opts.maxChars ?? DIGEST_MAX_CHARS;
403
- if (messages.length === 0) return "";
459
+ if (messages.length === 0) {
460
+ return { text: "", windowStart: 0, windowEnd: 0, deliveredFrom: 0 };
461
+ }
404
462
 
405
463
  const deltaParts: string[] = [];
464
+ // Message index each delta part was rendered from: the budget cut has to
465
+ // report which messages actually shipped, not just how many parts.
466
+ const partIdx: number[] = [];
406
467
 
407
468
  // 1. Compaction summary (never in agy's DB, so always high-value), but
408
469
  // only when THIS summary has not shipped in a previous digest.
@@ -438,19 +499,22 @@ export function buildContextDigest(
438
499
  const m = messages[i];
439
500
  if (m.role === "assistant") {
440
501
  if (opts.bound !== false && m.provider === own) continue; // our own turn: already in agy's DB
441
- const t = blocksToText(m.content).trim();
502
+ const t = [blocksToText(m.content).trim(), renderToolCalls(m.content)].filter(Boolean).join("\n");
442
503
  if (!t) continue;
443
504
  deltaParts.push(`[assistant turn from ${m.provider}]\n${t}`);
505
+ partIdx.push(i);
444
506
  } else if (m.role === "user") {
445
507
  const t = blocksToText(m.content);
446
508
  if (t.includes(COMPACTION_MARKER)) continue; // delivered as the summary part
447
509
  if (!t.trim()) continue;
448
510
  deltaParts.push(`[earlier user message]\n${t}`);
511
+ partIdx.push(i);
449
512
  } else if (m.role === "toolResult") {
450
513
  const t = blocksToText(m.content).trim();
451
514
  deltaParts.push(
452
- `[tool result: ${m.toolName}${m.isError ? " (error)" : ""}]\n${t || "(no text output)"}`,
515
+ `[tool result: ${m.toolName}${m.isError ? " (error)" : ""}]\n${capToolResultBody(t)}`,
453
516
  );
517
+ partIdx.push(i);
454
518
  }
455
519
  }
456
520
 
@@ -467,15 +531,18 @@ export function buildContextDigest(
467
531
  summaryPart = `${summaryPart.slice(0, room)}\n${MARKER}`;
468
532
  }
469
533
  let delta = deltaParts.join(SEP);
534
+ let oldestKept = partIdx.length > 0 ? partIdx[0] : end;
470
535
  if (maxChars > 0) {
471
536
  const budget = Math.max(0, maxChars - (summaryPart ? summaryPart.length + SEP.length : 0));
472
537
  if (delta.length > budget) {
473
538
  const kept: string[] = [];
474
539
  let used = 0;
540
+ oldestKept = end;
475
541
  for (let i = deltaParts.length - 1; i >= 0; i--) {
476
542
  const cost = deltaParts[i].length + (kept.length > 0 ? SEP.length : 0);
477
543
  if (used + cost > budget) break;
478
544
  kept.unshift(deltaParts[i]);
545
+ oldestKept = partIdx[i];
479
546
  used += cost;
480
547
  }
481
548
  if (kept.length > 0) {
@@ -487,9 +554,18 @@ export function buildContextDigest(
487
554
  }
488
555
  }
489
556
 
490
- return [summaryPart, delta]
557
+ const text = [summaryPart, delta]
491
558
  .filter((s): s is string => typeof s === "string" && s.length > 0)
492
559
  .join(SEP);
560
+ return { text, windowStart: start, windowEnd: end, deliveredFrom: text ? oldestKept : end };
561
+ }
562
+
563
+ export function buildContextDigest(
564
+ messages: Message[],
565
+ watermark: number,
566
+ opts: DigestOptions = {},
567
+ ): string {
568
+ return buildContextDigestResult(messages, watermark, opts).text;
493
569
  }
494
570
 
495
571
  /** Build a fresh AssistantMessage shell for this turn. Mutated as blocks
@@ -1552,6 +1628,11 @@ async function runTurnDriver(
1552
1628
  // Summary id carried forward from the record; the gate below overwrites it
1553
1629
  // only when a digest actually ships, so skipped turns never lose it.
1554
1630
  let settleSummaryId = existing?.digestSummaryId;
1631
+ // Settle writes (both store.set paths) use these: they default to normal
1632
+ // advance semantics and the digest build overrides them when a wanted
1633
+ // digest failed to ship (see the delivery invariant at the build site).
1634
+ let nextCount = messageCount;
1635
+ let nextBoundary: string | undefined = settleBoundary;
1555
1636
 
1556
1637
  // Continuation: resolve parked round-trips from pi's toolResult messages,
1557
1638
  // then re-attach to the still-running agy turn. No new user event is sent:
@@ -1790,16 +1871,17 @@ async function runTurnDriver(
1790
1871
  // agy's server-side prompt cache.
1791
1872
  const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
1792
1873
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1793
- const digest =
1874
+ const digestRes =
1794
1875
  wantDigest && maxChars !== null && late.length === 0 && !resume
1795
- ? buildContextDigest(context.messages, watermark, {
1876
+ ? buildContextDigestResult(context.messages, watermark, {
1796
1877
  bound: Boolean(existing?.conversationId),
1797
1878
  seenSummaryId: existing?.digestSummaryId,
1798
1879
  maxChars,
1799
1880
  end: run.runStart,
1800
1881
  includeLast: compactionResume,
1801
1882
  })
1802
- : "";
1883
+ : undefined;
1884
+ const digest = digestRes?.text ?? "";
1803
1885
  // Byte-level fail closed (issue #2): the char budget over-reserves for
1804
1886
  // ASCII but a multibyte digest can still exceed the remaining byte
1805
1887
  // room. ACP carries no prompt cap, so the check is stream-json only.
@@ -1809,6 +1891,35 @@ async function runTurnDriver(
1809
1891
  promptBytes + STREAM_JSON_PROMPT_MARGIN + Buffer.byteLength(digest, "utf8") > STREAM_JSON_PROMPT_CAP
1810
1892
  ? ""
1811
1893
  : digest;
1894
+ // Watermark delivery invariant (issue #25 follow-up): the record may
1895
+ // only claim what reached agy. When a built digest failed the byte
1896
+ // check, nothing shipped, so the settle write HOLDS the pre-turn
1897
+ // watermark - the whole window re-offers next turn, duplicating
1898
+ // nothing because nothing arrived. (maxChars null is defensive: a
1899
+ // spent budget co-occurs with runTruncated, which skips the digest
1900
+ // deliberately.) Partial renders (budget cut the oldest turns) still
1901
+ // advance: the hole can never re-fit under the newest-first budget,
1902
+ // and re-offering it every turn would re-embed cap-sized duplicate
1903
+ // blocks into agy's DB; the hole is logged instead.
1904
+ const digestDropped = wantDigest && (maxChars === null || (digest !== "" && !digestFinal));
1905
+ if (digestDropped) {
1906
+ nextCount = existing?.lastMessageCount ?? watermark;
1907
+ nextBoundary = existing?.digestBoundary;
1908
+ }
1909
+ deps.log?.(
1910
+ "digest",
1911
+ {
1912
+ engine,
1913
+ bound: Boolean(existing?.conversationId),
1914
+ maxChars,
1915
+ bytes: digestFinal ? Buffer.byteLength(digestFinal, "utf8") : 0,
1916
+ windowStart: digestRes?.windowStart,
1917
+ windowEnd: digestRes?.windowEnd,
1918
+ deliveredFrom: digestRes?.deliveredFrom,
1919
+ shipped: Boolean(digestFinal),
1920
+ },
1921
+ digestDropped ? "warn" : "info",
1922
+ );
1812
1923
  // The delivered summary id persists only when a digest actually shipped:
1813
1924
  // late/resume/budget-skipped turns carry the previous id forward so the
1814
1925
  // summary is not lost to a turn that never delivered it.
@@ -1867,6 +1978,40 @@ async function runTurnDriver(
1867
1978
  // prompt is text-only); user-message images ride them on ACP natively
1868
1979
  // and staged files on stream-json.
1869
1980
  const runImages = [...images, ...late.flatMap((l) => l.images ?? [])];
1981
+ // Issue #25: an ACP session/load failure silently creates a fresh agy
1982
+ // conversation mid-turn, and the bound-mode prompt (G10 gate closed by
1983
+ // the binding, bound:true digest skipping own turns) would ship blind.
1984
+ // This variant is built as-if-fresh; the driver swaps it in only when
1985
+ // the load actually fails. stream-json cannot detect that drop, so it
1986
+ // is ACP-only.
1987
+ const requestConversation = redeliveryConversation ?? existing?.conversationId ?? null;
1988
+ const acpFallback =
1989
+ deps.engine === "acp" && requestConversation && !resume && late.length === 0
1990
+ ? (() => {
1991
+ const fbSys = config.systemPrompt
1992
+ ? getCurrentSystemPrompt(context.messages) || undefined
1993
+ : undefined;
1994
+ const freshDigest = wantDigest
1995
+ ? buildContextDigestResult(context.messages, 0, {
1996
+ bound: false,
1997
+ maxChars: ACP_DIGEST_MAX_CHARS,
1998
+ end: run.runStart,
1999
+ includeLast: compactionResume,
2000
+ })
2001
+ : null;
2002
+ // Both features off: the variant would equal the plain prompt.
2003
+ if (!fbSys && !freshDigest?.text) return undefined;
2004
+ return {
2005
+ prompt: buildFullPrompt(fbSys, "", deliveredPrompt) + stageImageNote(runImages),
2006
+ contextBlock: freshDigest?.text
2007
+ ? {
2008
+ uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
2009
+ text: `${DIGEST_PREAMBLE}\n\n${freshDigest.text}`,
2010
+ }
2011
+ : undefined,
2012
+ };
2013
+ })()
2014
+ : undefined;
1870
2015
  const fullPrompt =
1871
2016
  (late.length > 0
1872
2017
  ? buildLateResultPrompt(late, deliveredPrompt || undefined)
@@ -1885,6 +2030,7 @@ async function runTurnDriver(
1885
2030
  prompt: fullPrompt,
1886
2031
  images: runImages.length > 0 ? runImages : undefined,
1887
2032
  agent,
2033
+ fallback: acpFallback,
1888
2034
  contextBlock: embeddedDigest
1889
2035
  ? {
1890
2036
  uri: `urn:pi-bridge:context-digest/${messageCount}`,
@@ -1950,8 +2096,8 @@ async function runTurnDriver(
1950
2096
  store.set(key, {
1951
2097
  conversationId: parkedConv,
1952
2098
  lastStepIdx: -1,
1953
- lastMessageCount: messageCount,
1954
- digestBoundary: settleBoundary,
2099
+ lastMessageCount: nextCount,
2100
+ digestBoundary: nextBoundary,
1955
2101
  digestSummaryId: settleSummaryId,
1956
2102
  });
1957
2103
  deps.pendingCompactionHandoff?.delete(key);
@@ -2080,8 +2226,8 @@ async function runTurnDriver(
2080
2226
  store.set(key, {
2081
2227
  conversationId: outcome.conversationId,
2082
2228
  lastStepIdx: -1,
2083
- lastMessageCount: messageCount,
2084
- digestBoundary: settleBoundary,
2229
+ lastMessageCount: nextCount,
2230
+ digestBoundary: nextBoundary,
2085
2231
  digestSummaryId: settleSummaryId,
2086
2232
  });
2087
2233
  deps.pendingCompactionHandoff?.delete(key);
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;