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.
@@ -6,6 +6,7 @@ import { installSessionRouting, type NativeToolMode } from "./tool-routing.ts";
6
6
  import { showAcpUpdate } from "./activity-presentation.ts";
7
7
  import { parseSessionUsage, usageDelta, type SessionUsage } from "./usage-accounting.ts";
8
8
  import type { SessionCleanup } from "./session-cleanup.ts";
9
+ import type { Diagnostics } from "./diagnostics.ts";
9
10
 
10
11
  export class TierConnection extends AntigravityAcpConnection {
11
12
  confirmedThinking: { model: string; effort: string } | undefined;
@@ -20,14 +21,19 @@ export class TierConnection extends AntigravityAcpConnection {
20
21
  private readonly usageCaptures = new Map<string, { text: string }>();
21
22
  private readonly usageCommands = new Set<string>();
22
23
  private cleanup?: SessionCleanup;
24
+ private diagnostics?: Diagnostics;
25
+ private readonly firstOutput = new Map<string, number>();
26
+ private readonly pendingOwned = new Set<string>();
27
+ private ownershipRetry?: Promise<void>;
23
28
  private cleanupLeases = new Map<string, string>();
24
29
  toolRouting: { nativeTools: NativeToolMode; channel: "pending" | "system-append" | "legacy-prompt" } | undefined;
25
30
 
26
- constructor(options: ConstructorParameters<typeof AntigravityAcpConnection>[0] & { ompNativeTools?: NativeToolMode; ompDebugToolUpdates?: boolean; ompUsageMode?: "auto" | "off"; ompCleanup?: SessionCleanup }) {
31
+ constructor(options: ConstructorParameters<typeof AntigravityAcpConnection>[0] & { ompNativeTools?: NativeToolMode; ompDebugToolUpdates?: boolean; ompUsageMode?: "auto" | "off"; ompCleanup?: SessionCleanup; ompDiagnostics?: Diagnostics }) {
27
32
  super(options);
28
33
  this.cleanup = options.ompCleanup;
34
+ this.diagnostics = options.ompDiagnostics;
29
35
  this.cleanup?.start();
30
- void this.process.exited.then(() => this.releaseCleanupLeases());
36
+ void this.process.exited.then(() => this.releaseCleanupLeases()).catch(() => {});
31
37
  this.debugToolUpdates = options.ompDebugToolUpdates ?? false;
32
38
  this.usageMode = options.ompUsageMode ?? "auto";
33
39
  this.setHandlers({ ...options.handlers, onUpdate: async notification => {
@@ -52,6 +58,10 @@ export class TierConnection extends AntigravityAcpConnection {
52
58
  }
53
59
  return;
54
60
  }
61
+ if (update.sessionUpdate === "agent_message_chunk" && this.firstOutput.has(notification.sessionId)) {
62
+ this.diagnostics?.record("acp.first-output", performance.now() - this.firstOutput.get(notification.sessionId)!);
63
+ this.firstOutput.delete(notification.sessionId);
64
+ }
55
65
  if (showAcpUpdate(notification, this.debugToolUpdates)) await options.handlers?.onUpdate?.(notification);
56
66
  } });
57
67
  if (options.ompNativeTools) {
@@ -70,25 +80,25 @@ export class TierConnection extends AntigravityAcpConnection {
70
80
  override async newSession(...args: Parameters<AntigravityAcpConnection["newSession"]>) {
71
81
  const session = await super.newSession(...args);
72
82
  if (this.cleanup) {
73
- try { this.cleanupLeases.set(session.sessionId, this.cleanup.acquire(session.sessionId, true, this.process.pid!)); }
74
- catch { console.warn("[ACP cleanup] Could not register new session; preserving its files."); }
83
+ try { this.cleanupLeases.set(session.sessionId, await this.cleanup.acquire(session.sessionId, true, this.process.pid!)); }
84
+ catch { this.pendingOwned.add(session.sessionId); console.warn("[ACP cleanup] Registration deferred; preserving session files and retrying."); }
75
85
  }
76
86
  this.usageBaselines.set(session.sessionId, { input: 0, completion: 0, thinking: 0, cached: 0, total: 0 });
77
87
  return session;
78
88
  }
79
89
 
80
- private protectSession(id: string) {
90
+ private async protectSession(id: string) {
81
91
  if (this.cleanup && !this.cleanupLeases.has(id)) {
82
92
  // Lease before the resume/load RPC, including while the server replays.
83
- this.cleanupLeases.set(id, this.cleanup.acquire(id, false, this.process.pid!));
93
+ this.cleanupLeases.set(id, await this.cleanup.acquire(id, false, this.process.pid!));
84
94
  }
85
95
  }
86
96
  override async resumeSession(...args: Parameters<AntigravityAcpConnection["resumeSession"]>) {
87
- this.protectSession(args[0]);
97
+ await this.protectSession(args[0]);
88
98
  return super.resumeSession(...args);
89
99
  }
90
100
  override async loadSession(...args: Parameters<AntigravityAcpConnection["loadSession"]>) {
91
- this.protectSession(args[0]);
101
+ await this.protectSession(args[0]);
92
102
  return super.loadSession(...args);
93
103
  }
94
104
  private dropSessionState(id: string) {
@@ -97,32 +107,45 @@ export class TierConnection extends AntigravityAcpConnection {
97
107
  this.usageBaselines?.delete(id);
98
108
  this.usageCommands?.delete(id);
99
109
  }
100
- retireForReplacement(key: string, id: string) {
110
+ async retireForReplacement(key: string, id: string) {
101
111
  this.dropSessionState(id);
102
- try { this.cleanup?.retire(key, id); } catch { /* Preserve files if bookkeeping is unavailable. */ }
112
+ try { await this.cleanup?.retire(key, id); } catch { /* Retried by the cleanup ledger. */ }
103
113
  }
104
- confirmReplacement(key: string, id: string) {
105
- try { this.cleanup?.confirm(key, id); } catch { /* Retry cleanup on a later successful turn. */ }
114
+ async confirmReplacement(key: string, id: string) {
115
+ try { await this.cleanup?.confirm(key, id, true); } catch { /* Retry cleanup on a later successful turn. */ }
106
116
  }
107
- discardSession(id: string) {
117
+ async discardSession(id: string) {
108
118
  // Explicitly disposable discovery sessions need no model replacement.
109
- this.retireForReplacement(`discovery:${id}`, id);
110
- this.confirmReplacement(`discovery:${id}`, "discovery-complete");
119
+ await this.retireForReplacement(`discovery:${id}`, id);
120
+ await this.confirmReplacement(`discovery:${id}`, "discovery-complete");
111
121
  }
112
- private releaseCleanupLeases() {
122
+ private async releaseCleanupLeases() {
113
123
  if (this.process.alive) return;
124
+ await this.retryOwnership();
114
125
  for (const [id, token] of this.cleanupLeases ?? []) {
115
- try { this.cleanup?.release(token); this.cleanupLeases.delete(id); } catch { /* Live PID leases fail closed. */ }
126
+ try { await this.cleanup?.release(token, true); this.cleanupLeases.delete(id); } catch { /* Live PID leases fail closed. */ }
116
127
  }
117
128
  }
118
129
  override async close() {
119
130
  await super.close();
120
- this.releaseCleanupLeases();
131
+ await this.releaseCleanupLeases();
121
132
  this.contextUsage?.clear();
122
133
  this.usageStatus?.clear();
123
134
  this.usageBaselines?.clear();
124
135
  this.usageCommands?.clear();
125
136
  this.usageCaptures?.clear();
137
+ this.firstOutput?.clear();
138
+ }
139
+ private async retryOwnership() {
140
+ if (this.ownershipRetry) return this.ownershipRetry;
141
+ const pending = this.retryOwnershipOnce(); this.ownershipRetry = pending;
142
+ try { await pending; } finally { if (this.ownershipRetry === pending) this.ownershipRetry = undefined; }
143
+ }
144
+ private async retryOwnershipOnce() {
145
+ for (const id of this.pendingOwned ?? []) {
146
+ try { this.cleanupLeases.set(id, await this.cleanup!.acquire(id, true, this.process.pid!)); this.pendingOwned.delete(id); }
147
+ catch { /* Unknown data stays protected if durable registration is unavailable. */ }
148
+ }
126
149
  }
127
150
 
128
151
  private async readUsage(sessionId: string, signal?: AbortSignal) {
@@ -144,7 +167,11 @@ export class TierConnection extends AntigravityAcpConnection {
144
167
  override async prompt(request: Parameters<AntigravityAcpConnection["prompt"]>[0], signal?: AbortSignal) {
145
168
  this.activePrompts++;
146
169
  const id = request.sessionId;
147
- try { this.cleanup?.touch(id); } catch { /* Cleanup must not affect inference. */ }
170
+ await this.retryOwnership();
171
+ let abortedAt: number | undefined;
172
+ const aborted = () => { abortedAt = performance.now(); };
173
+ signal?.addEventListener("abort", aborted, { once: true });
174
+ try { await this.cleanup?.touch(id); } catch { /* Cleanup must not affect inference. */ }
148
175
  try {
149
176
  const queryUsage = process.env.OMP_ACP_USAGE !== "off" && this.usageMode !== "off" && this.usageCommands.has(id);
150
177
  if (queryUsage && !this.usageBaselines.has(id)) {
@@ -153,7 +180,11 @@ export class TierConnection extends AntigravityAcpConnection {
153
180
  if (baseline) this.usageBaselines.set(id, baseline);
154
181
  } catch { /* Restore baseline is optional; never count the prior session as this turn. */ }
155
182
  }
183
+ const started = performance.now();
184
+ this.firstOutput?.set(id, started);
156
185
  const response = await super.prompt(request, signal);
186
+ this.diagnostics?.record("acp.prompt", performance.now() - started);
187
+ if (abortedAt !== undefined && ["cancelled", "end_turn"].includes(response.stopReason)) this.diagnostics?.record("acp.cancel-confirmation", performance.now() - abortedAt);
157
188
  const withContext = <T extends { _meta?: Record<string, unknown> }>(value: T): T => {
158
189
  const context = this.contextUsage.get(id);
159
190
  return context ? { ...value, _meta: { ...value._meta, ompContextTokens: context.used } } : value;
@@ -176,8 +207,10 @@ export class TierConnection extends AntigravityAcpConnection {
176
207
  return withContext(response);
177
208
  }
178
209
  } finally {
210
+ signal?.removeEventListener("abort", aborted);
211
+ this.firstOutput?.delete(id);
179
212
  this.activePrompts--;
180
- try { this.cleanup?.touch(id); } catch { /* Keep accounting optional. */ }
213
+ try { await this.cleanup?.touch(id); } catch { /* Keep accounting optional. */ }
181
214
  }
182
215
  }
183
216
 
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "omp-antigravity-acp-provider",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
+ "ompAcpBundle": 1,
4
5
  "description": "Google Antigravity ACP provider for Oh My Pi (OMP), with tool bridging and per-model thinking; derived from zacbemis/pi-antigravity-acp-provider",
5
6
  "type": "module",
6
7
  "license": "MIT",
@@ -42,18 +43,17 @@
42
43
  "test:auth": "bun scripts/test-auth-command.ts",
43
44
  "test:cleanup": "node scripts/test-cleanup-runtime.ts",
44
45
  "test:continuity": "node scripts/test-request-continuity.ts && node scripts/test-graceful-cancellation.ts",
46
+ "test:omp-compaction": "bun scripts/test-omp-compaction.ts",
45
47
  "check": "npm run build && npm test && npm run test:cleanup && npm run test:continuity && npm run test:graph && npm run test:commands",
46
48
  "prepack": "npm run build",
47
49
  "prepublishOnly": "npm run check",
48
50
  "test:graph": "bun scripts/test-load-graph.ts"
49
51
  },
50
- "dependencies": {
52
+ "devDependencies": {
51
53
  "@earendil-works/pi-ai": "1.3.0",
52
54
  "pi-antigravity-acp-provider": "0.1.15",
53
55
  "proper-lockfile": "4.1.2",
54
- "typebox": "1.3.36"
55
- },
56
- "devDependencies": {
56
+ "typebox": "1.3.36",
57
57
  "esbuild": "0.28.2"
58
58
  },
59
59
  "keywords": [
package/scripts/build.mjs CHANGED
@@ -7,6 +7,10 @@ import { build } from "esbuild";
7
7
  const require = createRequire(import.meta.url);
8
8
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
9
9
  const upstream = path.dirname(require.resolve("pi-antigravity-acp-provider/package.json"));
10
+ const assets = path.join(root, "extension/assets");
11
+ await fs.mkdir(path.join(assets, "src/acp"), { recursive: true });
12
+ await fs.copyFile(path.join(upstream, "src/acp/supervisor.mjs"), path.join(assets, "src/acp/supervisor.mjs"));
13
+ await fs.copyFile(path.join(upstream, "runtime-manifest.json"), path.join(assets, "runtime-manifest.json"));
10
14
  const exports = [
11
15
  ["createAntigravityProvider", "provider.ts"],
12
16
  ["AntigravityRuntime, PERMISSION_TOOL_NAME, PERMISSION_RESULT_KIND", "runtime.ts"],
@@ -22,7 +26,7 @@ const exports = [
22
26
  const result = await build({
23
27
  stdin: {
24
28
  contents: [
25
- ...exports.map(([names, file]) => `export { ${names} } from ${JSON.stringify(path.join(upstream, "src", file))};`),
29
+ ...exports.map(([names, file]) => `export { ${names} } from ${JSON.stringify(file === "acp/session-store.ts" ? path.join(root, "extension/session-store.ts") : path.join(upstream, "src", file))};`),
26
30
  `export { TierConnection } from ${JSON.stringify(path.join(root, "extension/tier-connection.ts"))};`,
27
31
  `export { SessionCleanup } from ${JSON.stringify(path.join(root, "extension/session-cleanup.ts"))};`,
28
32
  'export { Type } from "typebox";',
@@ -40,9 +44,8 @@ const result = await build({
40
44
  // on the consuming machine rather than embedded from the build machine.
41
45
  banner: { js: [
42
46
  'import { createRequire as __ompCreateRequire } from "node:module";',
43
- 'import { pathToFileURL as __ompPathToFileURL } from "node:url";',
44
47
  'const require = __ompCreateRequire(import.meta.url);',
45
- 'const __ompAssetURL = (specifier) => __ompPathToFileURL(require.resolve(specifier)).href;',
48
+ 'const __ompAssetURL = (specifier) => new URL(specifier.replace("pi-antigravity-acp-provider/", "./assets/"), import.meta.url).href;',
46
49
  ].join("\n") },
47
50
  external: ["@aws-sdk/client-s3"],
48
51
  plugins: [{
@@ -54,9 +57,17 @@ const result = await build({
54
57
  builder.onResolve({ filter: /^\.\/stream\/usage\.js$/ }, ({ importer }) => {
55
58
  if (importer === path.join(upstream, "src/runtime.ts")) return { path: path.join(root, "extension/usage.ts") };
56
59
  });
60
+ builder.onResolve({ filter: /^\.\/acp\/session-store\.js$/ }, ({ importer }) => {
61
+ if (importer === path.join(upstream, "src/runtime.ts")) return { path: path.join(root, "extension/session-store.ts") };
62
+ });
57
63
  builder.onLoad({ filter: /\/src\/runtime\.ts$/ }, async ({ path: file }) => {
58
64
  if (file !== path.join(upstream, "src/runtime.ts")) return;
59
65
  const patches = [
66
+ {
67
+ name: "validated message fingerprint memo",
68
+ anchor: 'return createHash("sha256").update(canonicalJson(value)).digest("hex");',
69
+ replacement: 'return ompMessageFingerprintMemo(message, value, () => createHash("sha256").update(canonicalJson(value)).digest("hex"));',
70
+ },
60
71
  {
61
72
  name: "context",
62
73
  anchor: "buildPromptParts(context, fresh, unseenStart)",
@@ -90,16 +101,19 @@ const result = await build({
90
101
  replacement: [
91
102
  "if (isAbort(error) || binding.abortRequested) {",
92
103
  "\t\t\t\tabortTurn(binding);",
93
- "\t\t\t\tif (binding.connection.process.alive && !binding.needsReconstruction &&",
104
+ "\t\t\t\tif (binding.connection.process.alive && !binding.ompInvalidated && !binding.needsReconstruction &&",
94
105
  "\t\t\t\t\t['cancelled', 'end_turn'].includes(binding.ompTerminalStopReason)) {",
95
106
  "\t\t\t\t\tbinding.messageCount = binding.pendingContextCount;",
96
107
  "\t\t\t\t\tbinding.historyFingerprint = binding.pendingContextFingerprint;",
97
108
  "\t\t\t\t\tbinding.expectedAssistantFingerprint = messageFingerprint((binding.writer ?? writer).message);",
98
109
  "\t\t\t\t\tbinding.ompCancelledCheckpoint = true;",
99
110
  "\t\t\t\t\tbinding.ompCancelledHadOutput = (binding.writer ?? writer).message.content.length > 0;",
100
- "\t\t\t\t\tthis.persistBinding(binding);",
111
+ "\t\t\t\t\tbinding.ompExpectedAssistantHasOutput = binding.ompCancelledHadOutput;",
112
+ "\t\t\t\t\tbinding.ompInFlight = false;",
113
+ "\t\t\t\t\ttry { this.persistBinding(binding); } catch (checkpointError) { await this.invalidateBinding(binding); throw checkpointError; }",
101
114
  "\t\t\t\t} else await this.invalidateBinding(binding);",
102
- "\t\t\t}",
115
+ "\t\t\t} else if (ompDispatched) await this.invalidateBinding(binding);",
116
+ "\t\t\telse binding.ompInFlight = false;",
103
117
  ].join("\n"),
104
118
  },
105
119
  {
@@ -113,13 +127,14 @@ const result = await build({
113
127
  replacement: "binding.ompTerminalStopReason = response.stopReason;\n\t\t\tif (binding.abortRequested) throw abortError();",
114
128
  },
115
129
  {
116
- name: "cancelled partial output must match retained OMP history",
130
+ name: "generated assistant boundary must match retained OMP history",
117
131
  anchor: "binding.needsReconstruction || binding.mode !== this.permissionMode ||",
118
132
  replacement: [
119
133
  "binding.needsReconstruction ||",
120
- "\t\t\t\t(binding.ompCancelledCheckpoint && (context.messages[binding.messageCount]?.role === 'assistant'",
121
- "\t\t\t\t\t? messageFingerprint(context.messages[binding.messageCount]) !== binding.expectedAssistantFingerprint",
122
- "\t\t\t\t\t: binding.ompCancelledHadOutput)) || binding.mode !== this.permissionMode ||",
134
+ "\t\t\t\t(binding.expectedAssistantFingerprint && context.messages[binding.messageCount]?.role === 'assistant' &&",
135
+ "\t\t\t\t\tmessageFingerprint(context.messages[binding.messageCount]) !== binding.expectedAssistantFingerprint) ||",
136
+ "\t\t\t\t((binding.ompExpectedAssistantHasOutput || (binding.ompCancelledCheckpoint && binding.ompCancelledHadOutput)) &&",
137
+ "\t\t\t\t\tcontext.messages[binding.messageCount]?.role !== 'assistant') || binding.mode !== this.permissionMode ||",
123
138
  ].join("\n"),
124
139
  },
125
140
  {
@@ -155,7 +170,153 @@ const result = await build({
155
170
  }
156
171
  contents = contents.replace(patch.anchor, patch.replacement);
157
172
  }
173
+ // Convert every store/checkpoint call at its owning async boundary.
174
+ // Never hide an asynchronous write behind the upstream synchronous API.
175
+ const asyncPatches = [
176
+ ["private persistBinding(binding: Binding): void", "private async persistBinding(binding: Binding): Promise<void>"],
177
+ ["private noteContinuationInstructions(binding: Binding, context: Context): void", "private async noteContinuationInstructions(binding: Binding, context: Context): Promise<void>"],
178
+ ["private async closeBindings(): Promise<void> {", "private async closeBindings(): Promise<void> {\n const closingTurns = [...this.resolvedBindings].flatMap(binding => binding.turnCompletion ? [binding.turnCompletion] : []);"],
179
+ ["\t\tthis.persistBinding(createdBinding);", "\t\tthis.persistBinding(createdBinding);\n\t\tthis.assertEpoch(epoch);"],
180
+ ["if (removeSaved && binding.piSessionId) this.sessionStore?.remove(binding.piSessionId);\n\t\t\tthis.bindings.delete(key);", "this.bindings.delete(key);\n\t\t\tif (removeSaved && binding.piSessionId) this.sessionStore?.remove(binding.piSessionId);"],
181
+ ];
182
+ for (const [anchor, replacement] of asyncPatches) {
183
+ if (contents.split(anchor).length !== 2) throw new Error(`Pinned async store seam changed: ${anchor}`);
184
+ contents = contents.replace(anchor, replacement);
185
+ }
186
+ for (const [anchor, replacement, count] of [
187
+ ["this.persistBinding(", "await this.persistBinding(", 3],
188
+ ["this.noteContinuationInstructions(binding, context);", "const continuationTurn = binding.turnCompletion; await this.noteContinuationInstructions(binding, context); if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();", 2],
189
+ ["this.sessionStore?.", "await this.sessionStore?.", 8],
190
+ ]) {
191
+ if (contents.split(anchor).length !== count + 1) throw new Error(`Pinned store call sites changed: ${anchor}`);
192
+ contents = contents.replaceAll(anchor, replacement);
193
+ }
194
+ // Continuity transactions are adapter-owned. Keep explicit pinned seams
195
+ // so an upstream update cannot silently bypass the write-ahead marker.
196
+ const continuityPatches = [
197
+ ['interface Binding {', 'interface Binding {\n ompInFlight: boolean; ompInvalidated: boolean; ompDropPromise?: Promise<void>; ompExpectedAssistantHasOutput: boolean;'],
198
+ ['let completeTurn: (() => void) | undefined;', 'let ompDispatched = false;\n\t\tlet completeTurn: (() => void) | undefined;'],
199
+ ['if (existing) return existing;', `if (existing) {
200
+ const value = await existing;
201
+ if (!value.ompInvalidated) return value;
202
+ await value.ompDropPromise;
203
+ if (this.bindings.get(key) === existing) this.bindings.delete(key);
204
+ return this.getBinding(key, model, acpModelId, apiKey, writer, tools, signal);
205
+ }`],
206
+ ['if (value === createdBinding && this.bindings.get(key) === current) this.bindings.delete(key);',
207
+ 'if (value === createdBinding && this.bindings.get(key) === current && !createdBinding.ompInvalidated) this.bindings.delete(key);'],
208
+ ['const saved = piSessionId ? await this.sessionStore?.get(piSessionId) : undefined;', `let saved = piSessionId ? await this.sessionStore?.get(piSessionId) : undefined;
209
+ if (saved && (saved.ompCheckpointVersion !== 1 || saved.ompInFlight !== false)) {
210
+ await connection.retireForReplacement?.(key, saved.acpSessionId);
211
+ await this.ompRemoveSaved(saved.piSessionId, saved.acpSessionId);
212
+ saved = undefined;
213
+ }`],
214
+ ['const createdBinding: Binding = {', `const createdBinding: Binding = {
215
+ ompInFlight: false, ompInvalidated: false,
216
+ ompExpectedAssistantHasOutput: restored && saved?.ompExpectedAssistantHasOutput === true,`],
217
+ ['const response = await binding.connection.prompt(', `if (options.signal?.aborted) throw abortError();
218
+ binding.ompInFlight = true;
219
+ await this.persistBinding(binding);
220
+ this.assertEpoch(epoch);
221
+ if (binding.ompInvalidated || !binding.connection.process.alive) throw new AntigravityAcpError('protocol', 'ACP session closed before prompt dispatch');
222
+ if (options.signal?.aborted) throw abortError();
223
+ ompDispatched = true;
224
+ const response = await binding.connection.prompt(`],
225
+ ['binding.expectedAssistantFingerprint = messageFingerprint(activeWriter.message);', `binding.expectedAssistantFingerprint = messageFingerprint(activeWriter.message.content.length
226
+ ? activeWriter.message : { ...activeWriter.message, content: [{ type: 'text', text: '' }] });
227
+ binding.ompExpectedAssistantHasOutput = activeWriter.message.content.some(block => block.type !== 'text' || block.text.length > 0);
228
+ binding.ompInFlight = false;`],
229
+ ['if (!binding.piSessionId) return;', 'if (!binding.piSessionId || binding.ompInvalidated) return;'],
230
+ ['acpModelId: binding.modelId,', 'acpModelId: binding.modelId,\n ompCheckpointVersion: 1, ompInFlight: binding.ompInFlight === true, ompExpectedAssistantHasOutput: binding.ompExpectedAssistantHasOutput === true,'],
231
+ ['if (binding.needsReconstruction) { await this.sessionStore?.remove(binding.piSessionId); return; }',
232
+ 'if (binding.needsReconstruction) { await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId); return; }'],
233
+ ];
234
+ for (const [anchor, replacement] of continuityPatches) {
235
+ if (contents.split(anchor).length !== 2) throw new Error(`Pinned continuity seam changed: ${anchor}`);
236
+ contents = contents.replace(anchor, replacement);
237
+ }
238
+ // Fallbacks after incomplete tools/permissions must not reload the same
239
+ // backend. The two owning branches share this exact adjacent seam.
240
+ const fallback = 'await this.dropBinding(key, binding);\n\t\t\t\tbinding = await this.getBinding(';
241
+ if (contents.split(fallback).length !== 3) throw new Error('Pinned incomplete continuation fallbacks changed');
242
+ contents = contents.replaceAll(fallback, 'await this.invalidateBinding(binding);\n\t\t\t\tbinding = await this.getBinding(');
243
+ const claimStart = 'binding.writer = writer;\n\t\t\t\tconst continuationTurn = binding.turnCompletion;';
244
+ const claimEnd = 'await this.awaitContinuation(binding, options.signal);\n\t\t\t\treturn;';
245
+ if (contents.split(claimStart).length !== 3 || contents.split(claimEnd).length !== 3) throw new Error('Pinned continuation ownership seams changed');
246
+ contents = contents.replaceAll(claimStart, 'return await claimContinuation(binding, async () => {\n\t\t\t\t' + claimStart)
247
+ .replaceAll(claimEnd, 'await this.awaitContinuation(binding, options.signal);\n\t\t\t\t}, () => this.invalidateBinding(binding));');
248
+ const dropPattern = /\tprivate async dropBinding\([\s\S]*?\n\tprivate confirmedMode\(/g;
249
+ if ([...contents.matchAll(dropPattern)].length !== 1) throw new Error('Pinned binding teardown seam changed');
250
+ contents = contents.replace(dropPattern, `\tprivate async ompRemoveSaved(piSessionId: string, acpSessionId: string): Promise<void> {
251
+ if (typeof this.sessionStore?.removeIfMatches === 'function') await this.sessionStore.removeIfMatches(piSessionId, acpSessionId);
252
+ else await this.sessionStore?.remove(piSessionId);
253
+ }
254
+ private async dropBinding(key: string, binding: Binding, removeSaved = false): Promise<void> {
255
+ if (removeSaved) binding.ompInvalidated = true;
256
+ if (binding.ompDropPromise) {
257
+ await binding.ompDropPromise;
258
+ if (removeSaved && binding.piSessionId) await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
259
+ return;
260
+ }
261
+ const dropping = (async () => {
262
+ const current = this.bindings.get(key);
263
+ this.resolvedBindings.delete(binding);
264
+ cancelPermission(binding);
265
+ cancelPiTools(binding, 'Antigravity session closed before Pi returned the tool result');
266
+ const closing = Promise.allSettled([binding.connection.close(), binding.bridge?.close() ?? Promise.resolve()]);
267
+ try {
268
+ if (removeSaved) {
269
+ binding.connection.retireForReplacement?.(key, binding.session.sessionId);
270
+ if (binding.piSessionId) await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
271
+ }
272
+ } finally {
273
+ await closing;
274
+ if (current && (await current) === binding && this.bindings.get(key) === current) this.bindings.delete(key);
275
+ }
276
+ })();
277
+ binding.ompDropPromise = dropping;
278
+ await dropping;
279
+ }
280
+ private confirmedMode(`);
281
+ const flushAnchor = "\n\tprivate async runQueued(";
282
+ const beforeQueue = contents.slice(0, contents.indexOf(flushAnchor));
283
+ const endClose = beforeQueue.lastIndexOf("\n\t}");
284
+ // Await active turns' checkpoint writes, not queued callers which may
285
+ // themselves be waiting for this permission-mode change to complete.
286
+ contents = contents.slice(0, endClose) + "\n\t\tawait Promise.allSettled(closingTurns);\n\t\tawait this.sessionStore?.flush?.();" + contents.slice(endClose);
287
+ const classStart = contents.indexOf("export class AntigravityRuntime {");
288
+ const helpersStart = contents.indexOf("\nfunction messagesFingerprint(");
289
+ if (classStart < 0 || helpersStart < classStart) throw new Error("Pinned runtime class seam changed");
290
+ const methods = contents.slice(classStart, helpersStart)
291
+ .replaceAll("messagesFingerprint(", "this.ompMessagesFingerprint(")
292
+ .replaceAll("messageFingerprint(", "this.ompMessageFingerprint(")
293
+ .replaceAll("piToolFingerprint(", "this.ompToolsFingerprint(");
294
+ contents = contents.slice(0, classStart) + methods + contents.slice(helpersStart);
295
+ contents = contents.replace("export class AntigravityRuntime {", `export class AntigravityRuntime {
296
+ private readonly ompSystemMemo = createStructuredFingerprintMemo();
297
+ private readonly ompToolsMemo = createStructuredFingerprintMemo();
298
+ private ompMessagesFingerprint(messages: Context["messages"]): string { return messagesFingerprint(messages, this.ompSystemMemo); }
299
+ private ompMessageFingerprint(message: Context["messages"][number]): string { return messageFingerprint(message, this.ompSystemMemo); }
300
+ private ompToolsFingerprint(tools: NonNullable<Context["tools"]>): string { return this.ompToolsMemo(tools, () => piToolFingerprint(tools)); }
301
+ `);
302
+ const fingerprintPatches = [
303
+ ['function messagesFingerprint(messages: Context["messages"]): string {', 'function messagesFingerprint(messages: Context["messages"], systemMemo?: any): string {'],
304
+ ['const fingerprints = messages.map(messageFingerprint);', 'const fingerprints = messages.map(message => messageFingerprint(message, systemMemo));'],
305
+ ['function messageFingerprint(message: Context["messages"][number]): string {', 'function messageFingerprint(message: Context["messages"][number], systemMemo?: any): string {'],
306
+ ['return ompMessageFingerprintMemo(message, value, () => createHash("sha256").update(canonicalJson(value)).digest("hex"));', 'const compute = () => createHash("sha256").update(canonicalJson(value)).digest("hex"); return message.role === "system" && systemMemo ? systemMemo(value, compute) : ompMessageFingerprintMemo(message, value, compute);'],
307
+ ['await this.sessionStore?.flush?.();', 'try { await this.sessionStore?.flush?.(); } finally { this.ompSystemMemo.clear(); this.ompToolsMemo.clear(); }'],
308
+ ];
309
+ for (const [anchor, replacement] of fingerprintPatches) {
310
+ if (contents.split(anchor).length !== 2) throw new Error(`Pinned structured fingerprint seam changed: ${anchor}`);
311
+ contents = contents.replace(anchor, replacement);
312
+ }
313
+ contents = `import { createStructuredFingerprintMemo } from ${JSON.stringify(path.join(root, "extension/structured-fingerprint.ts"))};\n` + contents;
314
+ contents = contents.replaceAll("binding.connection.retireForReplacement?.(", "await binding.connection.retireForReplacement?.(")
315
+ .replaceAll("binding.connection.confirmReplacement?.(", "await binding.connection.confirmReplacement?.(")
316
+ .replaceAll("binding.connection.discardSession?.(", "await binding.connection.discardSession?.(");
158
317
  contents = `import { drainCancelledTurn } from ${JSON.stringify(path.join(root, "extension/turn-cancellation.ts"))};\n` + contents;
318
+ contents = `import { claimContinuation } from ${JSON.stringify(path.join(root, "extension/continuation-claim.ts"))};\n` + contents;
319
+ contents = `import { createHistoryFingerprintMemo } from ${JSON.stringify(path.join(root, "extension/history-fingerprint.ts"))};\nconst ompMessageFingerprintMemo = createHistoryFingerprintMemo();\n` + contents;
159
320
  return { contents, loader: "ts" };
160
321
  });
161
322
  builder.onLoad({ filter: /\/src\/acp\/connection\.ts$/ }, async ({ path: file }) => {