omp-antigravity-acp-provider 0.1.19 → 0.1.21

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.
@@ -26,6 +26,23 @@ export interface TransferContext {
26
26
  messages: TransferMessage[];
27
27
  }
28
28
 
29
+ // The official harness applies a 64,000-token per-step conversion limit,
30
+ // independently of the model window. Its overflow path keeps only the first
31
+ // 192,000 UTF-8 bytes. Reserve room for USER_REQUEST/time metadata added by ACP;
32
+ // otherwise a cold replay can silently lose its newest question at the tail.
33
+ export const ACP_STEP_TEXT_BYTES = 188_000;
34
+
35
+ export function promptTextBytes(prompt: TransferBlock[]): number {
36
+ let bytes = 0;
37
+ for (const block of prompt) {
38
+ if (block.type === "text") bytes += Buffer.byteLength(block.text ?? "", "utf8") + 2;
39
+ else if (block.type === "resource" && block.resource) {
40
+ bytes += Buffer.byteLength(`Embedded resource (${block.resource.uri}):\n${block.resource.text}`, "utf8") + 2;
41
+ }
42
+ }
43
+ return bytes;
44
+ }
45
+
29
46
  export function currentSystemInstructions(context: TransferContext): string {
30
47
  const prompt = getCurrentSystemPrompt(context.messages as never) || context.systemPrompt || "";
31
48
  if (Buffer.byteLength(prompt, "utf8") > 134_217_728) throw new Error("OMP system instructions exceed the 128 MiB hard transfer ceiling; reduce them rather than truncating instructions");
@@ -144,6 +161,14 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
144
161
  const bytes = instructionsBytes + historyBytes + tailBytes + imageWireChars + imageCount * 10;
145
162
  const budget = historyBudget(undefined, process.env, options.maxTransferBytes);
146
163
  if (bytes > budget) throw new Error(`Request payload too large (413): local ACP transfer needs ${bytes} bytes; budget is ${budget}. Use OMP /compact or raise maxTransferBytes. No history was silently truncated.`);
164
+ const textBytes = promptTextBytes(prompt);
165
+ if (textBytes > ACP_STEP_TEXT_BYTES) {
166
+ // OMP recognizes this as context overflow, including inside its adaptive
167
+ // summary-window loop. Reject before session/prompt rather than letting the
168
+ // harness truncate and answer an older request. Never put request text in
169
+ // this error, and never let a user wire/window override disable this guard.
170
+ throw new Error(`Maximum context length exceeded: official Antigravity ACP single-step text needs ${textBytes} bytes; safe budget is ${ACP_STEP_TEXT_BYTES} bytes. Compact the conversation with OMP /compact and retry. A larger contextWindow or maxTransferBytes does not raise this server limit. No history or current request was sent or silently truncated.`);
171
+ }
147
172
  const estimatedTokens =
148
173
  (instructionsText ? estimateTransferTokens(instructionsText, 0, instructionsBytes - 108) : 0) +
149
174
  (historyText ? estimateTransferTokens(historyText, 0, historyBytes - 100) : 0) +
@@ -0,0 +1,20 @@
1
+ const owners = new WeakSet<object>();
2
+
3
+ // Tool/permission continuations must run while the original prompt is waiting
4
+ // for them, so they cannot use that prompt's queue. Claim before the first await
5
+ // instead; a duplicate caller must never replace the owner's response writer.
6
+ export async function claimContinuation(
7
+ binding: object,
8
+ work: () => Promise<void>,
9
+ invalidate: () => Promise<void>,
10
+ ): Promise<void> {
11
+ if (owners.has(binding)) throw new Error("ACP continuation is already in progress for this session");
12
+ owners.add(binding);
13
+ try { await work(); }
14
+ catch (error) {
15
+ // A failed owner must not leave its server waiting for tools with a writer
16
+ // that has already failed. Preserve the original error if cleanup also fails.
17
+ try { await invalidate(); } catch { /* The durable in-flight marker remains unsafe to restore. */ }
18
+ throw error;
19
+ } finally { owners.delete(binding); }
20
+ }
@@ -0,0 +1,40 @@
1
+ import fs from "node:fs";
2
+ import { writeJsonAtomic, isMissingFileError } from "./fs-atomic.ts";
3
+ export class Diagnostics {
4
+ private enabled = false;
5
+ private readonly samples: Array<{ stage: string; ms: number }> = [];
6
+ constructor(private readonly file: string) {
7
+ try { this.enabled = JSON.parse(fs.readFileSync(file, "utf8")).enabled === true; } catch (e) { if (!isMissingFileError(e)) this.enabled = false; }
8
+ }
9
+ configure(enabled: boolean) { writeJsonAtomic(this.file, { enabled }, false); this.enabled = enabled; if (!enabled) this.samples.length = 0; }
10
+ reset() { this.samples.length = 0; }
11
+ record(stage: string, ms: number) {
12
+ if (!this.enabled || !Number.isFinite(ms) || ms < 0) return;
13
+ this.samples.push({ stage, ms }); if (this.samples.length > 128) this.samples.shift();
14
+ }
15
+ sync<T>(stage: string, work: () => T): T { if (!this.enabled) return work(); const t = performance.now(); try { return work(); } finally { this.record(stage, performance.now() - t); } }
16
+ async measure<T>(stage: string, work: () => Promise<T>): Promise<T> { if (!this.enabled) return work(); const t = performance.now(); try { return await work(); } finally { this.record(stage, performance.now() - t); } }
17
+ status() {
18
+ const stages: { [key: string]: { count: number; medianMs: number; maxMs: number } } = {};
19
+ for (const name of new Set(this.samples.map(s => s.stage))) {
20
+ const values = this.samples.filter(s => s.stage === name).map(s => s.ms).sort((a, b) => a - b);
21
+ stages[name] = { count: values.length, medianMs: +values[Math.floor(values.length / 2)].toFixed(3), maxMs: +values.at(-1)!.toFixed(3) };
22
+ }
23
+ return { enabled: this.enabled, samples: this.samples.length, capacity: 128, stages };
24
+ }
25
+ }
26
+
27
+ // Instrument only adapter-controlled methods. No request content, model output,
28
+ // account identifiers or session IDs are collected or persisted.
29
+ export function instrumentRuntime(runtime: object, diagnostics: Diagnostics) {
30
+ for (const [method, stage] of [["ompMessagesFingerprint", "history.compare"], ["ompToolsFingerprint", "tools.compare"]]) {
31
+ const original = Reflect.get(runtime, method) as (...args: unknown[]) => unknown;
32
+ Reflect.set(runtime, method, (...args: unknown[]) => diagnostics.sync(stage, () => original.apply(runtime, args)));
33
+ }
34
+ for (const [method, stage] of [["getBinding", "session.binding"], ["createBinding", "session.initialize-or-restore"], ["persistBinding", "checkpoint.write"]]) {
35
+ const original = Reflect.get(runtime, method) as (...args: unknown[]) => Promise<unknown>;
36
+ Reflect.set(runtime, method, (...args: unknown[]) => diagnostics.measure(stage, () => original.apply(runtime, args)));
37
+ }
38
+ const drop = Reflect.get(runtime, "dropBinding") as (...args: unknown[]) => Promise<unknown>;
39
+ Reflect.set(runtime, "dropBinding", (...args: unknown[]) => diagnostics.measure(args[2] ? "session.rebuild" : "session.close", () => drop.apply(runtime, args)));
40
+ }
@@ -0,0 +1,80 @@
1
+ // Cache only large, simple payloads. Identity locates an entry; the live values
2
+ // must still match an independent snapshot before its digest can be reused.
3
+ import { types } from "node:util";
4
+
5
+ const UNSUPPORTED = Symbol("unsupported snapshot");
6
+ const MIN_STRING = 2048;
7
+ const MAX_NODES = 128;
8
+ type Snapshot = { value: unknown; digest: string };
9
+
10
+ function worthCaching(content: unknown): boolean {
11
+ if (typeof content === "string") return content.length >= MIN_STRING;
12
+ if (!Array.isArray(content) || types.isProxy(content)) return false;
13
+ for (let i = 0; i < Math.min(content.length, 32); i++) {
14
+ const block = Object.getOwnPropertyDescriptor(content, String(i))?.value;
15
+ if (!block || typeof block !== "object" || types.isProxy(block)) continue;
16
+ for (const key of ["text", "data", "thinking"]) {
17
+ const value = Object.getOwnPropertyDescriptor(block, key)?.value;
18
+ if (typeof value === "string" && value.length >= MIN_STRING) return true;
19
+ }
20
+ }
21
+ return false;
22
+ }
23
+
24
+ // Snapshot construction never retains a live mutable container or invokes an
25
+ // accessor. Reject exotic prototypes, aliases/cycles and sparse/custom arrays.
26
+ function snapshot(value: any, budget = { nodes: 0 }, seen = new Set<object>()): any {
27
+ if (++budget.nodes > MAX_NODES) return UNSUPPORTED;
28
+ if (value === null || typeof value !== "object") {
29
+ return ["function", "symbol", "bigint"].includes(typeof value) ? UNSUPPORTED : value;
30
+ }
31
+ const array = Array.isArray(value);
32
+ if (types.isProxy(value) || seen.has(value) || Object.getPrototypeOf(value) !== (array ? Array.prototype : Object.prototype)) return UNSUPPORTED;
33
+ seen.add(value);
34
+ const keys = Object.keys(value);
35
+ if (keys.length > MAX_NODES || (array && (keys.length !== value.length ||
36
+ Object.getOwnPropertyNames(value).length !== keys.length + 1))) return UNSUPPORTED;
37
+ const result = array ? [] : Object.create(null);
38
+ for (let i = 0; i < keys.length; i++) {
39
+ const key = keys[i];
40
+ if (array && key !== String(i)) return UNSUPPORTED;
41
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
42
+ if (!Object.hasOwn(descriptor, "value")) return UNSUPPORTED;
43
+ const child = snapshot(descriptor.value, budget, seen);
44
+ if (child === UNSUPPORTED) return UNSUPPORTED;
45
+ result[key] = child;
46
+ }
47
+ return result;
48
+ }
49
+
50
+ function matches(value: any, saved: any, budget = { nodes: 0 }): boolean {
51
+ if (++budget.nodes > MAX_NODES) return false;
52
+ if (value === null || typeof value !== "object") return Object.is(value, saved);
53
+ const array = Array.isArray(value);
54
+ if (types.isProxy(value) || !saved || typeof saved !== "object" || array !== Array.isArray(saved) ||
55
+ Object.getPrototypeOf(value) !== (array ? Array.prototype : Object.prototype)) return false;
56
+ const keys = Object.keys(value);
57
+ if (keys.length > MAX_NODES || keys.length !== Object.keys(saved).length ||
58
+ (array && (value.length !== saved.length || Object.getOwnPropertyNames(value).length !== keys.length + 1))) return false;
59
+ for (const key of keys) {
60
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
61
+ if (!Object.hasOwn(descriptor, "value") || !Object.hasOwn(saved, key) ||
62
+ !matches(descriptor.value, saved[key], budget)) return false;
63
+ }
64
+ return true;
65
+ }
66
+
67
+ export function createHistoryFingerprintMemo() {
68
+ const entries = new WeakMap<object, Snapshot>();
69
+ return (message: object, value: any, compute: () => string): string => {
70
+ const previous = entries.get(message);
71
+ if (previous && matches(value, previous.value)) return previous.digest;
72
+ // Drop stale strings even if canonical serialization subsequently throws.
73
+ if (previous) entries.delete(message);
74
+ if (!worthCaching(value.content)) return compute();
75
+ const saved = snapshot(value);
76
+ const digest = compute();
77
+ if (saved !== UNSUPPORTED) entries.set(message, { value: saved, digest });
78
+ return digest;
79
+ };
80
+ }
@@ -5,6 +5,8 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { applyApiCostEstimate } from "./pricing.ts";
7
7
  import { SessionRuntimePool } from "./runtime-pool.ts";
8
+ import { createStructuredFingerprintMemo } from "./structured-fingerprint.ts";
9
+ import { Diagnostics, instrumentRuntime } from "./diagnostics.ts";
8
10
  import { stableTools } from "./tool-order.ts";
9
11
  import { loadContextSettings } from "./context-settings.ts";
10
12
  import { selectRuntimeModel, type PublicCatalogModel } from "./model-catalog.ts";
@@ -63,8 +65,8 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
63
65
  const sessionStorePath = path.join(stateDir, "sessions.json");
64
66
  const sessionStore = new AcpSessionStore(sessionStorePath);
65
67
  const cleanup = new SessionCleanup(stateDir);
66
- // AcpSessionStore.read is private upstream; count saved records from the
67
- // file so /antigravity-acp account needs no live runtime.
68
+ const diagnostics = new Diagnostics(path.join(stateDir, "diagnostics.json"));
69
+ // Count saved records from disk so /antigravity-acp account needs no runtime.
68
70
  const savedSessionCount = (): number => {
69
71
  try {
70
72
  const parsed: unknown = JSON.parse(fs.readFileSync(sessionStorePath, "utf8"));
@@ -90,10 +92,14 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
90
92
  if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 0 || (idleTimeoutMs > 0 && idleTimeoutMs < 1000)) {
91
93
  throw new Error("OMP_ACP_IDLE_TIMEOUT_MS must be 0 (disabled) or an integer of at least 1000");
92
94
  }
95
+ const maxIdleEntries = Number(process.env.OMP_ACP_MAX_IDLE_RUNTIMES ?? 2);
96
+ if (!Number.isSafeInteger(maxIdleEntries) || maxIdleEntries < 0) throw new Error("OMP_ACP_MAX_IDLE_RUNTIMES must be a nonnegative integer (0 disables the cap)");
97
+ const toolProjectionMemo = createStructuredFingerprintMemo();
98
+ let toolRevision = 0;
93
99
 
94
100
  let lastToolAudit: ToolAuditSummary | undefined;
95
101
  let cachedToolProjection: {
96
- ref: readonly { name: string }[] | undefined;
102
+ revision: string;
97
103
  tools: { name: string }[];
98
104
  availableNames: string;
99
105
  audit: ToolAuditSummary;
@@ -108,6 +114,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
108
114
  ompDebugToolUpdates: toolPolicy.debugToolUpdates,
109
115
  ompUsageMode: contextSettings.defaults.usageMode ?? "auto",
110
116
  ompCleanup: cleanup,
117
+ ompDiagnostics: diagnostics,
111
118
  });
112
119
  connections.add(connection);
113
120
  ownedConnections.add(connection);
@@ -117,12 +124,13 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
117
124
  });
118
125
  return connection;
119
126
  }, permissionMode, sessionStore);
127
+ instrumentRuntime(runtime, diagnostics);
120
128
  return {
121
129
  runtime,
122
130
  provider: createAntigravityProvider(runtime).provider,
123
131
  isBusy: () => [...ownedConnections].some(connection => connection.activePrompts > 0),
124
132
  };
125
- }, bundle => bundle.runtime.close(), { timeoutMs: idleTimeoutMs, canDispose: bundle => !bundle.isBusy() });
133
+ }, bundle => bundle.runtime.close(), { timeoutMs: idleTimeoutMs, maxIdleEntries, canDispose: bundle => !bundle.isBusy() });
126
134
 
127
135
  const sessionIdOf = (ctx: OmpCommandContext | undefined): string | undefined => ctx?.sessionManager?.getSessionId?.();
128
136
  pi.on("session_shutdown", async (_event: unknown, ctx: OmpCommandContext) => {
@@ -132,6 +140,8 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
132
140
  } else {
133
141
  await runtimes.closeAll();
134
142
  }
143
+ await sessionStore.flush();
144
+ if (!runtimes.values().length) await cleanup.stop();
135
145
  });
136
146
 
137
147
  function syncProviderRegistration() {
@@ -150,14 +160,22 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
150
160
  await Promise.all(runtimes.values().map(bundle => bundle.runtime.logout()));
151
161
  // Finish the Antigravity-side cleanup even when the pool is empty,
152
162
  // instead of instantiating a runtime just to log it out.
153
- sessionStore.clear();
163
+ await sessionStore.clear();
154
164
  clearAntigravityCredentials();
155
165
  },
156
166
  closeAllRuntimes: () => runtimes.closeAll(),
157
167
  onSyncProvider: syncProviderRegistration,
158
168
  });
159
169
 
160
- pi.on("session_start", async (_event: unknown, ctx: OmpCommandContext) => { auth.watchOmpCredentials(ctx); });
170
+ const trackOmpSource = async (_event: unknown, ctx: OmpCommandContext) => {
171
+ const id = ctx.sessionManager?.getSessionId?.(), file = ctx.sessionManager?.getSessionFile?.();
172
+ if (id && file) try { await cleanup.trackSource(id, file); } catch { /* Unproven or not-yet-persisted sources remain protected. */ }
173
+ };
174
+ pi.on("session_start", async (event: unknown, ctx: OmpCommandContext) => {
175
+ auth.watchOmpCredentials(ctx); await trackOmpSource(event, ctx); cleanup.start();
176
+ });
177
+ pi.on("agent_end", trackOmpSource);
178
+ pi.on("session_switch", trackOmpSource);
161
179
 
162
180
  pi.registerTool({
163
181
  name: PERMISSION_TOOL_NAME,
@@ -192,6 +210,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
192
210
  contextPath,
193
211
  toolPolicyPath,
194
212
  cleanup,
213
+ diagnostics,
195
214
  connections,
196
215
  auth,
197
216
  catalog: catalogStore,
@@ -244,10 +263,9 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
244
263
  let tools: Array<{ name: string }>;
245
264
  let availableNames: string;
246
265
  const cached = cachedToolProjection;
247
- // Hosts may rebuild the tools array each turn; equal contents hit.
248
- if (cached && (cached.ref === inputTools ||
249
- (cached.ref !== undefined && cached.ref.length === inputTools.length &&
250
- inputTools.every((tool, index) => tool === cached.ref![index])))) {
266
+ const revision = toolProjectionMemo(inputTools, () => String(++toolRevision));
267
+ // Validate live definitions, including mutation of the same array.
268
+ if (cached && cached.revision === revision) {
251
269
  tools = cached.tools;
252
270
  availableNames = cached.availableNames;
253
271
  lastToolAudit = cached.audit;
@@ -265,7 +283,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
265
283
  available: available.map(tool => tool.name),
266
284
  omitted,
267
285
  };
268
- cachedToolProjection = { ref: inputTools, tools, availableNames, audit: lastToolAudit };
286
+ cachedToolProjection = { revision, tools, availableNames, audit: lastToolAudit };
269
287
  }
270
288
  const routedContext = {
271
289
  ...context,
@@ -281,7 +299,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
281
299
  void (async () => {
282
300
  try {
283
301
  if (options?.signal?.aborted) throw new Error("ACP request cancelled before startup");
284
- await prepareRuntime();
302
+ await diagnostics.measure("runtime.prepare", prepareRuntime);
285
303
  if (options?.signal?.aborted) throw new Error("ACP request cancelled during startup");
286
304
  if (!catalogStore.upstreamModels.has(model.id)) await catalogStore.refresh(contextSettings);
287
305
  const original = catalogStore.upstreamModels.get(model.id);
@@ -0,0 +1,60 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ export interface OmpSessionSource {
5
+ id: string;
6
+ file: string;
7
+ root: string;
8
+ device: number;
9
+ inode: number;
10
+ missingSince?: number;
11
+ }
12
+
13
+ export async function sourceRoot(root: string) {
14
+ if (await fs.realpath(root) !== path.resolve(root)) throw new Error("Unsafe OMP session root");
15
+ const stat = await fs.stat(root);
16
+ if (!stat.isDirectory()) throw new Error("Invalid OMP session root");
17
+ return stat;
18
+ }
19
+
20
+ // Read only a bounded prefix, never a full transcript. OMP can put a title
21
+ // slot before the session header. No header means insufficient deletion proof.
22
+ export async function sourceId(file: string): Promise<string> {
23
+ if (await fs.realpath(file) !== path.resolve(file)) throw new Error("Symlinked OMP session");
24
+ const handle = await fs.open(file, "r");
25
+ try {
26
+ if (!(await handle.stat()).isFile()) throw new Error("Invalid OMP session file");
27
+ const buffer = Buffer.alloc(65536);
28
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
29
+ for (const line of buffer.toString("utf8", 0, bytesRead).split("\n").slice(0, 4)) {
30
+ try {
31
+ const header = JSON.parse(line);
32
+ if (header.type === "session" && typeof header.id === "string") return header.id;
33
+ } catch { /* A partial line cannot prove identity. */ }
34
+ }
35
+ throw new Error("OMP session header unavailable");
36
+ } finally { await handle.close(); }
37
+ }
38
+
39
+ // Missing files may have moved between workspace buckets. Search only the
40
+ // known managed root, with bounded work and no symlinks; any ambiguity preserves
41
+ // the ACP session. Called only after a tracked file disappears.
42
+ export async function findSources(root: string): Promise<Map<string, string>> {
43
+ let entries = 0;
44
+ const sources = new Map<string, string>();
45
+ async function visit(dir: string, depth: number): Promise<void> {
46
+ if (depth > 4) throw new Error("OMP source scan depth exceeded");
47
+ for (const item of await fs.readdir(dir, { withFileTypes: true })) {
48
+ if (++entries > 20000) throw new Error("OMP source scan limit exceeded");
49
+ if (item.isSymbolicLink()) throw new Error("Ambiguous symlink in OMP session root");
50
+ const file = path.join(dir, item.name);
51
+ if (item.isDirectory()) {
52
+ // Only journal buckets, not the adjacent per-session artifact trees.
53
+ if (/^\d{4}-\d\d-\d\d.*_[\da-f-]+$/i.test(item.name)) continue;
54
+ await visit(file, depth + 1);
55
+ } else if (item.isFile() && item.name.endsWith(".jsonl")) sources.set(await sourceId(file), file);
56
+ }
57
+ }
58
+ await visit(root, 0);
59
+ return sources;
60
+ }
@@ -4,11 +4,12 @@ export class SessionRuntimePool<T> {
4
4
  private readonly entries = new Map<string | undefined, T>();
5
5
  private readonly leases = new Map<T, number>();
6
6
  private readonly timers = new Map<T, NodeJS.Timeout>();
7
+ private readonly disposing = new Set<Promise<void>>();
7
8
 
8
9
  constructor(
9
10
  private readonly create: () => T,
10
11
  private readonly dispose: (entry: T) => Promise<void>,
11
- private readonly idle: { timeoutMs: number; canDispose?: (entry: T) => boolean } = { timeoutMs: 0 },
12
+ private readonly idle: { timeoutMs: number; maxIdleEntries?: number; canDispose?: (entry: T) => boolean } = { timeoutMs: 0 },
12
13
  ) {}
13
14
 
14
15
  get(sessionId?: string): T {
@@ -17,7 +18,9 @@ export class SessionRuntimePool<T> {
17
18
  entry = this.create();
18
19
  this.entries.set(sessionId, entry);
19
20
  }
21
+ this.entries.delete(sessionId); this.entries.set(sessionId, entry);
20
22
  this.schedule(sessionId, entry);
23
+ this.trim(entry);
21
24
  return entry;
22
25
  }
23
26
 
@@ -37,8 +40,21 @@ export class SessionRuntimePool<T> {
37
40
  const count = (this.leases.get(value) ?? 1) - 1;
38
41
  if (count > 0) this.leases.set(value, count); else this.leases.delete(value);
39
42
  if (this.entries.get(sessionId) === value) this.schedule(sessionId, value);
43
+ this.trim();
40
44
  } };
41
45
  }
46
+ private trim(protectedEntry?: T) {
47
+ const cap = this.idle.maxIdleEntries ?? 0;
48
+ if (!cap) return;
49
+ const idle = [...this.entries].filter(([, entry]) => !this.leases.has(entry) && this.idle.canDispose?.(entry) !== false);
50
+ let remaining = idle.length;
51
+ for (const [key, entry] of idle) {
52
+ if (remaining <= cap) break;
53
+ if (entry === protectedEntry) continue;
54
+ void this.close(key).catch(() => {});
55
+ remaining--;
56
+ }
57
+ }
42
58
 
43
59
  private clearTimer(entry: T) {
44
60
  clearTimeout(this.timers.get(entry));
@@ -67,7 +83,12 @@ export class SessionRuntimePool<T> {
67
83
  const entry = this.entries.get(sessionId);
68
84
  // Detach before awaiting teardown so a new turn cannot reuse a closed runtime.
69
85
  this.entries.delete(sessionId);
70
- if (entry) { this.clearTimer(entry); this.leases.delete(entry); await this.dispose(entry); }
86
+ if (entry) {
87
+ this.clearTimer(entry); this.leases.delete(entry);
88
+ const pending = this.dispose(entry);
89
+ this.disposing.add(pending);
90
+ try { await pending; } finally { this.disposing.delete(pending); }
91
+ }
71
92
  }
72
93
 
73
94
  async closeAll(): Promise<void> {
@@ -75,5 +96,6 @@ export class SessionRuntimePool<T> {
75
96
  this.entries.clear();
76
97
  for (const entry of entries) { this.clearTimer(entry); this.leases.delete(entry); }
77
98
  await Promise.allSettled(entries.map(entry => this.dispose(entry)));
99
+ await Promise.allSettled(this.disposing);
78
100
  }
79
101
  }