@estebanforge/pi-antigravity-bridge 1.13.1 → 1.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/provider.ts CHANGED
@@ -99,33 +99,80 @@ function zeroUsage(): Usage {
99
99
  };
100
100
  }
101
101
 
102
- /** Extract the latest user message as a flat prompt string. agy maintains its
103
- * own conversation history via --conversation, so we collapse pi's structured
104
- * message to text. Returns null if the last message isn't a user message. */
105
- function extractUserPrompt(context: TranscriptContext): string | null {
106
- const last = context.messages[context.messages.length - 1];
107
- if (!last || last.role !== "user") return null;
108
- const content = last.content;
109
- if (typeof content === "string") return content;
110
- // Flatten text blocks; images ride separately via extractImages (native
111
- // blocks on ACP, staged files on stream-json via prompt-images.ts).
112
- return content
113
- .filter((b): b is { type: "text"; text: string } => b.type === "text")
114
- .map((b) => b.text)
115
- .join("\n")
116
- .trim() || null;
102
+ /** Flatten one message's text + image blocks (pi-ai ImageContent: base64
103
+ * data + mimeType). The pre-#24 extraction shape, kept for the untrusted-
104
+ * boundary fallback and the single-message resume paths. */
105
+ function lastMessageParts(m: Message | undefined): { text: string | null; images: Array<{ data: string; mimeType: string }> } {
106
+ if (!m || m.role !== "user") return { text: null, images: [] };
107
+ if (typeof m.content === "string") return { text: m.content.trim() || null, images: [] };
108
+ const images: Array<{ data: string; mimeType: string }> = [];
109
+ const texts: string[] = [];
110
+ for (const b of m.content) {
111
+ if (b.type === "text") texts.push(b.text);
112
+ else if (b.type === "image") images.push({ data: b.data, mimeType: b.mimeType });
113
+ }
114
+ return { text: texts.join("\n").trim() || null, images };
117
115
  }
118
116
 
119
- /** Image blocks of the latest user message (pi-ai ImageContent: base64 data
120
- * + mimeType). On the ACP engine they ride session/prompt as native
121
- * content blocks; on stream-json they are staged to temp files and the
122
- * prompt names the paths (see prompt-images.ts). */
123
- function extractImages(context: TranscriptContext): Array<{ data: string; mimeType: string }> {
124
- const last = context.messages[context.messages.length - 1];
125
- if (!last || last.role !== "user" || typeof last.content === "string") return [];
126
- return last.content
127
- .filter((b): b is { type: "image"; data: string; mimeType: string } => b.type === "image")
128
- .map((b) => ({ data: b.data, mimeType: b.mimeType }));
117
+ /** pi-side history shapes that can sit inside a trailing user run; a run
118
+ * member matching one truncates the run to the messages after it. */
119
+ function isBacklogUserShape(text: string): boolean {
120
+ return text.includes(COMPACTION_MARKER) || text.startsWith(BRANCH_SUMMARY_PREFIX) || text.startsWith(BASH_RUN_PREFIX);
121
+ }
122
+
123
+ /** The trailing run of role:"user" messages is the active turn: pi stacks
124
+ * the prompt, queued nextTurn messages, and before_agent_start notes as
125
+ * consecutive user messages, so reading only the LAST one dropped every
126
+ * earlier prompt text and image (issue #24). The run is left-bounded by
127
+ * the validated watermark: messages at or before it belong to turns agy
128
+ * already saw (a failed pass never advances the watermark, so joining them
129
+ * could re-execute a half-run task; they stay digest/continuity context).
130
+ * A mismatched boundary fingerprint makes the count untrustworthy, so the
131
+ * run collapses to the last message - the pre-#24 behavior - instead of
132
+ * guessing. `texts` feeds the stream-json per-member truncation guard. */
133
+ function extractTrailingUserRun(
134
+ messages: Message[],
135
+ watermark: number,
136
+ boundaryTrusted: boolean,
137
+ ): { prompt: string | null; images: Array<{ data: string; mimeType: string }>; runStart: number; texts: string[] } {
138
+ const last = messages.length - 1;
139
+ const empty = { prompt: null, images: [], runStart: messages.length, texts: [] };
140
+ if (last < 0 || messages[last].role !== "user") return empty;
141
+ if (!boundaryTrusted) {
142
+ const only = lastMessageParts(messages[last]);
143
+ return { prompt: only.text, images: only.images, runStart: last, texts: only.text ? [only.text] : [] };
144
+ }
145
+ let start = last;
146
+ while (start > 0 && messages[start - 1].role === "user") start--;
147
+ for (let i = start; i < messages.length; i++) {
148
+ if (isBacklogUserShape(blocksToText(messages[i].content))) start = i + 1;
149
+ }
150
+ if (watermark > start) start = watermark;
151
+ if (start > last) {
152
+ // The stored count reaches past the run (a transcript that shrank
153
+ // under a matching or stale boundary - pi's retry re-emits look
154
+ // exactly like this): the pre-#24 read is the only safe one.
155
+ const only = lastMessageParts(messages[last]);
156
+ return { prompt: only.text, images: only.images, runStart: last, texts: only.text ? [only.text] : [] };
157
+ }
158
+ const texts: string[] = [];
159
+ const images: Array<{ data: string; mimeType: string }> = [];
160
+ for (let i = start; i <= last; i++) {
161
+ const m = messages[i];
162
+ if (typeof m.content === "string") {
163
+ if (m.content.trim()) texts.push(m.content);
164
+ continue;
165
+ }
166
+ for (const b of m.content) {
167
+ if (b.type === "text") {
168
+ if (b.text.trim()) texts.push(b.text);
169
+ } else if (b.type === "image") {
170
+ images.push({ data: b.data, mimeType: b.mimeType });
171
+ }
172
+ }
173
+ }
174
+ const prompt = texts.join("\n\n").trim() || null;
175
+ return { prompt, images, runStart: start, texts };
129
176
  }
130
177
 
131
178
  // --- G1: pi-side context digest --------------------------------------------------
@@ -140,6 +187,14 @@ function extractImages(context: TranscriptContext): Array<{ data: string; mimeTy
140
187
 
141
188
  const COMPACTION_MARKER = "compacted into the following summary";
142
189
 
190
+ /** pi's convertToLlm maps branch summaries and bash runs to role:"user", so
191
+ * a watermark-0 transcript can hold them as backlog inside a trailing user
192
+ * run. Neither contains COMPACTION_MARKER, so the run scan (issue #24)
193
+ * needs their shapes too (core/messages.js BRANCH_SUMMARY_PREFIX /
194
+ * bashExecutionToText). */
195
+ const BRANCH_SUMMARY_PREFIX = "The following is a summary of a branch";
196
+ const BASH_RUN_PREFIX = "Ran `";
197
+
143
198
  /** Synthetic prompt for a resume turn (issue #8): pi's retry dropped the
144
199
  * failed attempt from the projected context (_omitRecoveryAttempt), leaving
145
200
  * a toolResult or assistant tail with no live agy turn. The bound
@@ -253,8 +308,14 @@ export interface DigestOptions {
253
308
  /** Include the trailing message in the delta window instead of reserving
254
309
  * it as the current user prompt. Used when resuming into a fresh
255
310
  * post-compaction conversation whose transcript ends in a toolResult or
256
- * assistant message. Default false. */
311
+ * assistant message. Default false. Ignored when `end` is set. */
257
312
  includeLast?: boolean;
313
+ /** Exclusive window end. The trailing user run (issue #24) joins the
314
+ * prompt, so its members must not reappear as digest continuity
315
+ * context; the provider passes the run's start index here. Default:
316
+ * length-1 (reserve the last message as the prompt), or length when
317
+ * includeLast is set. */
318
+ end?: number;
258
319
  }
259
320
 
260
321
  /** Soft cap on the digest body when no tighter budget applies. */
@@ -367,7 +428,12 @@ export function buildContextDigest(
367
428
  } else if (watermark > messages.length) {
368
429
  start = 0;
369
430
  }
370
- const end = opts.includeLast ? messages.length : Math.max(0, messages.length - 1);
431
+ const end =
432
+ opts.end !== undefined
433
+ ? opts.end
434
+ : opts.includeLast
435
+ ? messages.length
436
+ : Math.max(0, messages.length - 1);
371
437
  for (let i = start; i < end; i++) {
372
438
  const m = messages[i];
373
439
  if (m.role === "assistant") {
@@ -1622,8 +1688,24 @@ async function runTurnDriver(
1622
1688
  return;
1623
1689
  }
1624
1690
  // Fresh pass, or a stranded escalated result being re-delivered.
1625
- const userPrompt = extractUserPrompt(context);
1626
- const images = extractImages(context);
1691
+ // Watermark first: the trailing user run is left-bounded by it, so
1692
+ // failed-turn backlog never joins the prompt (issue #24 / issue #1).
1693
+ const rawWatermark = existing?.lastMessageCount ?? 0;
1694
+ // Boundary fingerprint check (see boundaryFingerprint): a transcript
1695
+ // mutated under the stored count (/tree, /fork, context-hook rewrites)
1696
+ // resets the delta to the full digest instead of a silently wrong one.
1697
+ // Records written before the fingerprint existed (digestBoundary unset)
1698
+ // trust the count: the old code advanced it the same way, so reseting
1699
+ // would dump a one-time full delta of history agy already holds.
1700
+ const storedBoundary = existing?.digestBoundary;
1701
+ const boundaryTrusted =
1702
+ rawWatermark === 0 ||
1703
+ storedBoundary === undefined ||
1704
+ storedBoundary === boundaryFingerprint(context.messages[rawWatermark - 1]);
1705
+ const watermark = rawWatermark > 0 && boundaryTrusted ? rawWatermark : 0;
1706
+ const run = extractTrailingUserRun(context.messages, watermark, boundaryTrusted);
1707
+ const userPrompt = run.prompt;
1708
+ const images = run.images;
1627
1709
  // Resume pass (issue #8): pi's retry dropped the failed attempt from the
1628
1710
  // projected context, so the transcript ends in a toolResult or assistant
1629
1711
  // message and there is no user prompt, no pending park, and nothing
@@ -1666,20 +1748,6 @@ async function runTurnDriver(
1666
1748
  finalize(stream, blocks, "error", "No user message to send to agy.");
1667
1749
  return;
1668
1750
  }
1669
- const rawWatermark = existing?.lastMessageCount ?? 0;
1670
- // Boundary fingerprint check (see boundaryFingerprint): a transcript
1671
- // mutated under the stored count (/tree, /fork, context-hook rewrites)
1672
- // resets the delta to the full digest instead of a silently wrong one.
1673
- // Records written before the fingerprint existed (digestBoundary unset)
1674
- // trust the count: the old code advanced it the same way, so reseting
1675
- // would dump a one-time full delta of history agy already holds.
1676
- const storedBoundary = existing?.digestBoundary;
1677
- const watermark =
1678
- rawWatermark > 0 &&
1679
- (storedBoundary === undefined ||
1680
- storedBoundary === boundaryFingerprint(context.messages[rawWatermark - 1]))
1681
- ? rawWatermark
1682
- : 0;
1683
1751
  // Late and resume turns re-open the conversation with a synthetic
1684
1752
  // prompt; the digest would re-send context agy already holds (against a
1685
1753
  // stale watermark: a failed pass never advances it), so skip it.
@@ -1687,15 +1755,48 @@ async function runTurnDriver(
1687
1755
  // once even if config.digest is false, because the old agy conversation
1688
1756
  // was rotated and the fresh conversation has no prior history.
1689
1757
  const engine = deps.engine ?? config.engine;
1690
- const promptBytes = Buffer.byteLength(prompt ?? "", "utf8");
1758
+ // A joined run can outgrow the stream-json silent-drop cap on its own
1759
+ // (issue #24): the digest budget used to absorb these bytes. Truncate
1760
+ // oldest-first, keeping the newest run members; synthetic resume
1761
+ // prompts have no run behind them and keep their existing behavior.
1762
+ let deliveredPrompt = prompt ?? "";
1763
+ let runTruncated = false;
1764
+ if (engine !== "acp" && run.texts.length > 0) {
1765
+ const budget = STREAM_JSON_PROMPT_CAP - STREAM_JSON_PROMPT_MARGIN;
1766
+ if (Buffer.byteLength(deliveredPrompt, "utf8") > budget) {
1767
+ const kept: string[] = [];
1768
+ let used = 0;
1769
+ for (let i = run.texts.length - 1; i >= 0; i--) {
1770
+ const cost = Buffer.byteLength(run.texts[i], "utf8") + 2;
1771
+ if (used + cost > budget - 16) break;
1772
+ kept.unshift(run.texts[i]);
1773
+ used += cost;
1774
+ }
1775
+ runTruncated = true;
1776
+ if (kept.length > 0) {
1777
+ deliveredPrompt = `[truncated]\n${kept.join("\n\n")}`;
1778
+ } else {
1779
+ // A single member bigger than the whole budget: hard-slice it
1780
+ // (visible truncation) rather than ship a silently dropped
1781
+ // turn (issue #2) or an empty prompt.
1782
+ const head = Buffer.from(run.texts[run.texts.length - 1], "utf8").subarray(0, Math.max(0, budget - 32));
1783
+ deliveredPrompt = `[truncated]\n${head.toString("utf8")}`;
1784
+ }
1785
+ }
1786
+ }
1787
+ const promptBytes = Buffer.byteLength(deliveredPrompt, "utf8");
1788
+ // A truncated run ships alone: the digest budget is spent, and a
1789
+ // marker-only digest beside a sliced prompt is noise that also breaks
1790
+ // agy's server-side prompt cache.
1791
+ const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
1691
1792
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1692
- const wantDigest = config.digest || compactionHandoff || compactionResume;
1693
1793
  const digest =
1694
1794
  wantDigest && maxChars !== null && late.length === 0 && !resume
1695
1795
  ? buildContextDigest(context.messages, watermark, {
1696
1796
  bound: Boolean(existing?.conversationId),
1697
1797
  seenSummaryId: existing?.digestSummaryId,
1698
1798
  maxChars,
1799
+ end: run.runStart,
1699
1800
  includeLast: compactionResume,
1700
1801
  })
1701
1802
  : "";
@@ -1768,8 +1869,8 @@ async function runTurnDriver(
1768
1869
  const runImages = [...images, ...late.flatMap((l) => l.images ?? [])];
1769
1870
  const fullPrompt =
1770
1871
  (late.length > 0
1771
- ? buildLateResultPrompt(late, prompt || undefined)
1772
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, prompt ?? "")) +
1872
+ ? buildLateResultPrompt(late, deliveredPrompt || undefined)
1873
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt)) +
1773
1874
  stageImageNote(runImages);
1774
1875
  try {
1775
1876
  handle = await deps.driver.run({
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;