omp-antigravity-acp-provider 0.1.20 → 0.1.22

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/README.md CHANGED
@@ -19,9 +19,9 @@ The repository keeps the OMP adapter sources separately and uses upstream versio
19
19
 
20
20
  ## Status
21
21
 
22
- Version 0.1.20 includes resource-management improvements, verified OMP-deletion reconciliation and standalone packaging. Restart OMP after upgrading to load the new code.
22
+ Version 0.1.22 fixes a 0.1.21 regression that rejected normal successive tool/permission batches as an already active continuation. It retains plan-refinement size protection, durable checkpoints and stale-session reconstruction. Restart OMP after upgrading to load the new code.
23
23
 
24
- Version 0.1.20 supports all models advertised by the official ACP server. Tested with macOS, OMP 18.12.5, upstream provider 0.1.15 and official ACP runtime 1.4.1. Other platforms and OMP versions are not yet verified.
24
+ Version 0.1.22 supports all models advertised by the official ACP server. Earlier live inference was tested with macOS, OMP 18.12.5, upstream provider 0.1.15 and official ACP runtime 1.4.1. The 0.1.21–0.1.22 continuity fixes are verified offline, including OMP 18.13.3 catalog loading and the local OMP summarizer source. Other platforms and full interactive Refine plan behavior with a real model remain unverified.
25
25
 
26
26
  Google's consumer-plan policies can restrict third-party agent access even through the official CLI or ACP executable. An official transport does not establish permission to use a subscription in OMP. Check the current [Antigravity FAQ](https://www.antigravity.google/docs/faq/) and [terms](https://antigravity.google/terms) for your account.
27
27
 
@@ -58,7 +58,7 @@ Or, inside OMP:
58
58
 
59
59
  Select **omp-antigravity-acp-provider** in the browser, install it, and restart OMP to load the provider.
60
60
 
61
- OMP's marketplace installer currently copies Git content without installing npm dependencies. This marketplace therefore ships a small source launcher that retrieves the exact published **0.1.20** prebuilt npm adapter on first load. It disables npm install scripts and performs no local compilation. Node.js 22.19+ and npm must be on PATH. The standalone build bundles the required code and supervisor assets with no production dependencies: a clean test installation occupied approximately **2.6 MiB** (477 KiB tarball), down from roughly 150 MiB with the old dependency tree. This excludes the separately downloaded Google runtime. First preparation needs internet access; later loads reuse the installed cache without npm network access.
61
+ OMP's marketplace installer currently copies Git content without installing npm dependencies. This marketplace therefore ships a small source launcher that retrieves the exact published **0.1.22** prebuilt npm adapter on first load. It disables npm install scripts and performs no local compilation. Node.js 22.19+ and npm must be on PATH. The standalone build bundles the required code and supervisor assets with no production dependencies: a clean test installation occupied approximately **2.6 MiB** (477 KiB tarball), down from roughly 150 MiB with the old dependency tree. This excludes the separately downloaded Google runtime. First preparation needs internet access; later loads reuse the installed cache without npm network access.
62
62
 
63
63
  The launcher stores its versioned dependencies in `.runtime/` inside the installed marketplace plugin's cache directory. Uninstalling the marketplace plugin removes that cache when it is no longer referenced by another scope. Google credentials and the separately downloaded official ACP runtime are unaffected.
64
64
 
@@ -82,7 +82,7 @@ omp plugin install npm:omp-antigravity-acp-provider
82
82
  To pin a specific release:
83
83
 
84
84
  ```sh
85
- omp plugin install npm:omp-antigravity-acp-provider@0.1.20
85
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.22
86
86
  ```
87
87
 
88
88
  Restart OMP after installation. The npm package includes the built adapter; users do not need esbuild or a manual build step. Disable any older ACP adapter for the same provider before loading this package.
@@ -217,17 +217,17 @@ Never include those user data directories, OAuth callback URLs, account identifi
217
217
 
218
218
  Each runtime also keeps bounded, value-validated system-message and tool-definition snapshots. Equivalent new containers reuse the existing canonical fingerprint/tool projection fingerprint; every selected field is still checked, including in-place schema edits and non-enumerable schema properties. Unsupported shapes fall back to the original algorithm. Each of the two caches holds one entry, capped at 32,768 value nodes, 131,072 primitive snapshot items and 2,097,152 UTF-16 code units in keys/string values; these are local snapshot limits, not model tokens or context limits. Tool execution closures are not retained, and runtime teardown clears the caches.
219
219
 
220
- Session mappings use asynchronous file I/O and nonblocking cross-process lock retries, with ordered read/merge/atomic-rename writes compatible with existing `sessions.json` files. Cancellation checkpoints are awaited before the turn releases its queue; shutdown waits for active checkpoint writes. This keeps the event loop responsive during session-registry lock contention without acknowledging an unwritten checkpoint. Malformed JSON/non-array registries and I/O failures are reported rather than silently overwritten. Cleanup registry transactions, file scans and deletion also use asynchronous I/O; small command/configuration reads remain synchronous. This does not remove Google's cancellation-confirmation wait. See the [Esc performance implementation and measurements](docs/esc-session-performance-research.md#production-implementation) and [resource-management notes](docs/resource-management.md).
220
+ Session mappings use asynchronous file I/O and nonblocking cross-process lock retries, with ordered read/merge/atomic-rename writes. Each request saves a versioned in-flight marker before dispatch and clears it only with an accepted terminal checkpoint. A failed checkpoint, unknown prompt failure or incomplete tool/permission fallback cannot be trusted as a warm restoration point. Legacy mappings without the marker are reconstructed once from retained OMP history; subsequent clean checkpoints remain resumable. Invalidated turns cannot repersist old mappings, and conditional removal preserves a newer replacement. Local preflight failures retain known-good warm sessions. Cancellation checkpoints are awaited before the turn releases its queue; shutdown waits for active checkpoint writes and rechecks dispatch eligibility afterward. Malformed JSON/non-array registries and I/O failures are reported rather than silently overwritten. Cleanup registry transactions, file scans and deletion also use asynchronous I/O; small command/configuration reads remain synchronous. This does not remove Google's cancellation-confirmation wait. See the [continuity invariants](docs/session-continuity.md), [Esc performance implementation and measurements](docs/esc-session-performance-research.md#production-implementation) and [resource-management notes](docs/resource-management.md).
221
221
 
222
222
  History comparisons reuse SHA-256 digests for unchanged large, simple messages. Every lookup validates the selected live fields against an independent snapshot, including nested tool arguments and in-place text edits; object identity alone never establishes a match. Small messages (below 2,048 characters per text/image/thinking string), complex payloads and unsupported objects use the original algorithm. The digest format and all checks after asynchronous work remain unchanged, so saved sessions stay compatible. Weak keys allow snapshots to be reclaimed when OMP drops old messages, including after compaction. This reduces local comparison work; it does not increase Google's cache-hit rate or guarantee faster model generation. See the [offline benchmarks and memory measurements](docs/history-comparison-research.md#production-integration).
223
223
 
224
- New user requests supersede an interrupted ACP turn, including pending tool calls and permission prompts. The adapter cancels old waits and sends official `session/cancel`, then waits up to the existing 1.5-second cancellation deadline for the old turn to settle. A confirmed cancellation (or a clean completion racing with cancellation) keeps the warm ACP session when the transport is alive and the retained OMP history matches. New prompts queue behind that drain and are sent as new requests, never silently treated as old tool-result continuations. Ordinary completed turns and genuine tool continuations also stay warm.
224
+ New user requests supersede an interrupted ACP turn, including pending tool calls and permission prompts. The adapter cancels old waits and sends official `session/cancel`, then waits up to the existing 1.5-second cancellation deadline for the old turn to settle. A confirmed cancellation (or a clean completion racing with cancellation) keeps the warm ACP session when the transport is alive and the retained OMP history matches. New prompts queue behind that drain and are sent as new requests, never silently treated as old tool-result continuations. Ordinary completed turns and genuine tool continuations also stay warm. Tool/permission continuations claim one owner before asynchronous work; overlapping duplicates receive an explicit error instead of stealing the response stream. Changed or missing completed assistant output forces reconstruction so the backend and OMP-visible histories agree.
225
225
 
226
226
  The cancellation checkpoint records the accepted message boundary and the partial assistant output fingerprint, including across idle shutdown/resume. If cancellation is unacknowledged, the process fails, the history is edited/compacted, or previously emitted partial output is missing or changed in OMP, the adapter reconstructs from retained history instead. Thus Esc does not always create a new ACP session, but reuse is conditional rather than guaranteed. Cancelled turns skip supplemental `/usage` queries while retaining any ACP context-occupancy update. History is explicitly separated from the current request after official ACP text conversion; cold tool handoffs resume from completed results rather than restarting prior actions. Preserving a session avoids unnecessary replay but does not guarantee a backend cache hit. See the [Flash cancellation/cache research and implementation checks](docs/cache-cancellation-research.md).
227
227
 
228
- The adapter now transfers complete replay history within a bounded budget, including historical image attachments. It no longer silently keeps only a 32,000-character history tail. If a transfer does not fit, it stops with an explicit error requesting OMP `/compact` or smaller attachments. This is a local transfer limit, not Antigravity's model context window or its internal compaction threshold. Active requests, history text and system instructions share the token and wire budgets; images also have a separate decoded-data limit. No automatic summarization or extra inference is added by the transfer layer.
228
+ The adapter transfers complete replay history within bounded budgets, including historical image attachments. It does not silently keep only a history tail. The official harness also has a per-step text conversion limit independent of its model window: the inspected configuration limits a step to 64,000 tokens and truncates oversized text to its first 192,000 UTF-8 bytes. A large cold replay after **Refine plan** can therefore lose the latest question at the tail even when the advertised model window has room. The adapter rejects rendered prompt text above 188,000 bytes before `session/prompt`, leaving 4,000 bytes for official wrapping/metadata. The context-overflow error lets OMP use its existing compaction/retry flow; OMP's adaptive summary windows can split oversized summary input too. If compaction is disabled or cannot reduce the request, use `/compact` or reduce the input before retrying. The adapter itself neither summarizes nor adds inference. See [step-limit behavior and offline validation](docs/plan-refinement-step-limit.md).
229
229
 
230
- Token budgets and wire payload size are independent; the former 500,000-byte clamp is removed. The default wire payload limit is 16 MiB, configurable up to 128 MiB. Image data additionally defaults to an 8 MiB decoded payload limit. The automatic input-token budget is `contextWindow - maxTokens - reserveTokens`, where reserve defaults to the smaller of 16,384 and 5% of the window. A lightweight Unicode-aware estimate checks serialized text plus approximately 4,096 tokens per image. This is not a Gemini tokenizer, cannot guarantee exact token counts and does not include every hidden server instruction.
230
+ Token budgets, wire payload size and the per-step text limit are independent. The default wire payload limit is 16 MiB, configurable up to 128 MiB; raising it or `contextWindow` does not bypass the per-step text guard. Image data additionally defaults to an 8 MiB decoded payload limit and is not counted as rendered text. The automatic input-token budget is `contextWindow - maxTokens - reserveTokens`, where reserve defaults to the smaller of 16,384 and 5% of the window. A lightweight Unicode-aware estimate checks serialized text plus approximately 4,096 tokens per image. This is not a Gemini tokenizer, cannot guarantee exact token counts and does not include every hidden server instruction.
231
231
 
232
232
  Persist settings in `~/.omp/agent/antigravity-acp-provider/context.json`, or use the commands below. Defaults apply to every ACP model; entries under `models` override one advertised model ID. Model limits are client metadata and transfer budgets: they do not expand Google's server window or set an unsupported ACP generation-output parameter.
233
233
 
@@ -349,6 +349,8 @@ See the [0.1.8 context/compaction and usage benchmark](docs/context-compaction-0
349
349
 
350
350
  `npm test` runs offline regression tests for all-vendor catalogs, per-model thinking choices, selector routing, session ownership, restart-after-shutdown, asynchronous teardown and price calculations. It performs no model inference and consumes no account quota.
351
351
 
352
+ `npm run test:omp-compaction` additionally requires `OMP_ACP_TEST_OMP_SOURCE` pointing to an OMP source checkout with built dependencies. An optional `OMP_ACP_TEST_NATIVE_ADDON` can point to an installed OMP native addon when the checkout has no built addon. It runs OMP's real adaptive summary-window algorithm with synthetic completions, verifies that all history windows are visited, and checks that a compacted plan refinement retains the newest question. It performs no inference and does not modify the OMP checkout.
353
+
352
354
  `npm run test:usage` uses Bun and mocked protocol responses to verify restored-session baselines, counter resets, query failures and advertised-command gating without starting ACP. `bun scripts/verify-continuity-live.ts --live` is a separate Flash-only probe of long history, synthetic tools, usage accounting and idle process reclamation/restoration; it consumes quota. Its one-second idle setting is isolated to the test process and is not the production default.
353
355
 
354
356
  `npm run test:auth` uses Bun with an isolated `GEMINI_HOME`, a stubbed keychain and a stubbed OAuth flow to verify the account view (including Google-account email extraction from the stored id_token), login dialog mapping, logout cleanup, the active-request guard and the credential-store watch behind OMP-logout following (removal, automatic-disable suppression, re-login cancellation, opt-out and busy deferral) without starting ACP. Real Google login and logout change account state, so they are not part of any automated test.
@@ -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,23 @@
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
+ // Only attach the writer and deliver this batch's results inside work. Waiting
7
+ // for the ACP prompt to finish belongs outside the claim: it may request more
8
+ // tools/permissions, and those later batches must be allowed to attach a writer.
9
+ export async function claimContinuation(
10
+ binding: object,
11
+ work: () => Promise<void>,
12
+ invalidate: () => Promise<void>,
13
+ ): Promise<void> {
14
+ if (owners.has(binding)) throw new Error("ACP continuation is already in progress for this session");
15
+ owners.add(binding);
16
+ try { await work(); }
17
+ catch (error) {
18
+ // A failed owner must not leave its server waiting for tools with a writer
19
+ // that has already failed. Preserve the original error if cleanup also fails.
20
+ try { await invalidate(); } catch { /* The durable in-flight marker remains unsafe to restore. */ }
21
+ throw error;
22
+ } finally { owners.delete(binding); }
23
+ }
@@ -19240,6 +19240,24 @@ function createHistoryFingerprintMemo() {
19240
19240
  };
19241
19241
  }
19242
19242
 
19243
+ // extension/continuation-claim.ts
19244
+ var owners = /* @__PURE__ */ new WeakSet();
19245
+ async function claimContinuation(binding, work, invalidate) {
19246
+ if (owners.has(binding)) throw new Error("ACP continuation is already in progress for this session");
19247
+ owners.add(binding);
19248
+ try {
19249
+ await work();
19250
+ } catch (error62) {
19251
+ try {
19252
+ await invalidate();
19253
+ } catch {
19254
+ }
19255
+ throw error62;
19256
+ } finally {
19257
+ owners.delete(binding);
19258
+ }
19259
+ }
19260
+
19243
19261
  // extension/turn-cancellation.ts
19244
19262
  async function drainCancelledTurn(binding, abort, signal, timeoutMs = 1500) {
19245
19263
  const completion = binding.turnCompletion;
@@ -44553,7 +44571,7 @@ var AcpSessionStore = class {
44553
44571
  }
44554
44572
  const parsed = JSON.parse(raw);
44555
44573
  if (!Array.isArray(parsed)) throw new Error("Invalid ACP session registry; refusing to overwrite it");
44556
- return parsed.filter((record3) => Boolean(record3) && typeof record3 === "object" && ["piSessionId", "acpSessionId", "acpModelId", "cwd", "historyFingerprint"].every((key) => typeof record3[key] === "string") && Number.isSafeInteger(record3.messageCount) && record3.messageCount >= 0 && Number.isFinite(record3.lastActive) && (record3.expectedAssistantFingerprint === void 0 || typeof record3.expectedAssistantFingerprint === "string"));
44574
+ return parsed.filter((record3) => Boolean(record3) && typeof record3 === "object" && ["piSessionId", "acpSessionId", "acpModelId", "cwd", "historyFingerprint"].every((key) => typeof record3[key] === "string") && Number.isSafeInteger(record3.messageCount) && record3.messageCount >= 0 && Number.isFinite(record3.lastActive) && (record3.expectedAssistantFingerprint === void 0 || typeof record3.expectedAssistantFingerprint === "string") && (record3.ompCheckpointVersion === void 0 || record3.ompCheckpointVersion === 1) && ["ompInFlight", "ompExpectedAssistantHasOutput", "ompCancelledCheckpoint", "ompCancelledHadOutput"].every((key) => record3[key] === void 0 || typeof record3[key] === "boolean"));
44557
44575
  }
44558
44576
  async write(records) {
44559
44577
  if (!records.length) {
@@ -59322,6 +59340,18 @@ function estimateTransferTokens(text, images = 0, utf8Bytes = Buffer.byteLength(
59322
59340
  }
59323
59341
 
59324
59342
  // extension/context-transfer.ts
59343
+ var ACP_STEP_TEXT_BYTES = 188e3;
59344
+ function promptTextBytes(prompt) {
59345
+ let bytes = 0;
59346
+ for (const block of prompt) {
59347
+ if (block.type === "text") bytes += Buffer.byteLength(block.text ?? "", "utf8") + 2;
59348
+ else if (block.type === "resource" && block.resource) {
59349
+ bytes += Buffer.byteLength(`Embedded resource (${block.resource.uri}):
59350
+ ${block.resource.text}`, "utf8") + 2;
59351
+ }
59352
+ }
59353
+ return bytes;
59354
+ }
59325
59355
  function currentSystemInstructions(context) {
59326
59356
  const prompt = getCurrentSystemPrompt(context.messages) || context.systemPrompt || "";
59327
59357
  if (Buffer.byteLength(prompt, "utf8") > 134217728) throw new Error("OMP system instructions exceed the 128 MiB hard transfer ceiling; reduce them rather than truncating instructions");
@@ -59421,6 +59451,10 @@ ${instructions}` : "";
59421
59451
  const bytes = instructionsBytes + historyBytes + tailBytes + imageWireChars + imageCount * 10;
59422
59452
  const budget = historyBudget(void 0, process.env, options.maxTransferBytes);
59423
59453
  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.`);
59454
+ const textBytes = promptTextBytes(prompt);
59455
+ if (textBytes > ACP_STEP_TEXT_BYTES) {
59456
+ 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.`);
59457
+ }
59424
59458
  const estimatedTokens = (instructionsText ? estimateTransferTokens(instructionsText, 0, instructionsBytes - 108) : 0) + (historyText ? estimateTransferTokens(historyText, 0, historyBytes - 100) : 0) + estimateTransferTokens(tailSerialized, imageCount, tailBytes);
59425
59459
  if (estimatedTokens > options.inputTokenBudget) throw new Error(`Maximum context length exceeded: local ACP estimate is ${estimatedTokens} tokens; input budget is ${options.inputTokenBudget}. Use OMP /compact. This is a heuristic estimate, not a server token count. No history was silently truncated.`);
59426
59460
  return { prompt, messageCount: messages.length };
@@ -59939,22 +59973,24 @@ var AntigravityRuntime = class {
59939
59973
  const result = findPermissionResult(context, pending.id);
59940
59974
  if (!result) {
59941
59975
  cancelPermission(binding);
59942
- await this.dropBinding(key, binding);
59976
+ await this.invalidateBinding(binding);
59943
59977
  binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
59944
59978
  } else {
59945
- binding.writer = writer;
59946
- const continuationTurn = binding.turnCompletion;
59947
- await this.noteContinuationInstructions(binding, context);
59948
- if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();
59949
- binding.pendingContextCount = context.messages.length;
59950
- binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
59951
- binding.permission = void 0;
59952
- clearTimeout(pending.timer);
59953
- if (!result.cancelled && result.optionId && pending.request.options.some((option) => option.optionId === result.optionId)) {
59954
- pending.resolve({ outcome: { outcome: "selected", optionId: result.optionId } });
59955
- } else {
59956
- pending.resolve({ outcome: { outcome: "cancelled" } });
59957
- }
59979
+ await claimContinuation(binding, async () => {
59980
+ binding.writer = writer;
59981
+ const continuationTurn = binding.turnCompletion;
59982
+ await this.noteContinuationInstructions(binding, context);
59983
+ if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();
59984
+ binding.pendingContextCount = context.messages.length;
59985
+ binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
59986
+ binding.permission = void 0;
59987
+ clearTimeout(pending.timer);
59988
+ if (!result.cancelled && result.optionId && pending.request.options.some((option) => option.optionId === result.optionId)) {
59989
+ pending.resolve({ outcome: { outcome: "selected", optionId: result.optionId } });
59990
+ } else {
59991
+ pending.resolve({ outcome: { outcome: "cancelled" } });
59992
+ }
59993
+ }, () => this.invalidateBinding(binding));
59958
59994
  await this.awaitContinuation(binding, options.signal);
59959
59995
  return;
59960
59996
  }
@@ -59966,19 +60002,21 @@ var AntigravityRuntime = class {
59966
60002
  }));
59967
60003
  if (results.some((result) => result.message === void 0)) {
59968
60004
  cancelPiTools(binding, "Pi continued without returning every requested tool result");
59969
- await this.dropBinding(key, binding);
60005
+ await this.invalidateBinding(binding);
59970
60006
  binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
59971
60007
  } else {
59972
- binding.writer = writer;
59973
- const continuationTurn = binding.turnCompletion;
59974
- await this.noteContinuationInstructions(binding, context);
59975
- if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();
59976
- binding.pendingContextCount = context.messages.length;
59977
- binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
59978
- for (const { pending, message } of results) {
59979
- binding.pendingTools.delete(pending.invocation.id);
59980
- pending.resolve(toMcpToolResult(message));
59981
- }
60008
+ await claimContinuation(binding, async () => {
60009
+ binding.writer = writer;
60010
+ const continuationTurn = binding.turnCompletion;
60011
+ await this.noteContinuationInstructions(binding, context);
60012
+ if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();
60013
+ binding.pendingContextCount = context.messages.length;
60014
+ binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
60015
+ for (const { pending, message } of results) {
60016
+ binding.pendingTools.delete(pending.invocation.id);
60017
+ pending.resolve(toMcpToolResult(message));
60018
+ }
60019
+ }, () => this.invalidateBinding(binding));
59982
60020
  await this.awaitContinuation(binding, options.signal);
59983
60021
  return;
59984
60022
  }
@@ -59990,13 +60028,14 @@ var AntigravityRuntime = class {
59990
60028
  });
59991
60029
  this.queues.set(key, queue);
59992
60030
  await previous;
60031
+ let ompDispatched = false;
59993
60032
  let completeTurn;
59994
60033
  let onTurnAbort;
59995
60034
  try {
59996
60035
  await this.modeChanges;
59997
60036
  this.assertEpoch(epoch);
59998
60037
  binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
59999
- if (binding.needsReconstruction || binding.ompCancelledCheckpoint && (context.messages[binding.messageCount]?.role === "assistant" ? this.ompMessageFingerprint(context.messages[binding.messageCount]) !== binding.expectedAssistantFingerprint : binding.ompCancelledHadOutput) || binding.mode !== this.permissionMode || this.confirmedMode(binding) !== this.permissionMode || binding.toolFingerprint !== this.ompToolsFingerprint(tools) || context.messages.length < binding.messageCount || this.ompMessagesFingerprint(context.messages.slice(0, binding.messageCount)) !== binding.historyFingerprint) {
60038
+ if (binding.needsReconstruction || binding.expectedAssistantFingerprint && context.messages[binding.messageCount]?.role === "assistant" && this.ompMessageFingerprint(context.messages[binding.messageCount]) !== binding.expectedAssistantFingerprint || (binding.ompExpectedAssistantHasOutput || binding.ompCancelledCheckpoint && binding.ompCancelledHadOutput) && context.messages[binding.messageCount]?.role !== "assistant" || binding.mode !== this.permissionMode || this.confirmedMode(binding) !== this.permissionMode || binding.toolFingerprint !== this.ompToolsFingerprint(tools) || context.messages.length < binding.messageCount || this.ompMessagesFingerprint(context.messages.slice(0, binding.messageCount)) !== binding.historyFingerprint) {
60000
60039
  await this.dropBinding(key, binding, true);
60001
60040
  binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
60002
60041
  }
@@ -60035,6 +60074,13 @@ var AntigravityRuntime = class {
60035
60074
  options.signal.addEventListener("abort", onTurnAbort, { once: true });
60036
60075
  if (options.signal.aborted) onTurnAbort();
60037
60076
  }
60077
+ if (options.signal?.aborted) throw abortError();
60078
+ binding.ompInFlight = true;
60079
+ await this.persistBinding(binding);
60080
+ this.assertEpoch(epoch);
60081
+ if (binding.ompInvalidated || !binding.connection.process.alive) throw new AntigravityAcpError("protocol", "ACP session closed before prompt dispatch");
60082
+ if (options.signal?.aborted) throw abortError();
60083
+ ompDispatched = true;
60038
60084
  const response = await binding.connection.prompt(
60039
60085
  { sessionId: binding.session.sessionId, prompt: parts.prompt },
60040
60086
  options.signal
@@ -60049,7 +60095,9 @@ var AntigravityRuntime = class {
60049
60095
  activeWriter.message.rawStopReason = response.stopReason;
60050
60096
  binding.messageCount = binding.pendingContextCount || parts.messageCount;
60051
60097
  binding.historyFingerprint = binding.pendingContextFingerprint;
60052
- binding.expectedAssistantFingerprint = this.ompMessageFingerprint(activeWriter.message);
60098
+ binding.expectedAssistantFingerprint = this.ompMessageFingerprint(activeWriter.message.content.length ? activeWriter.message : { ...activeWriter.message, content: [{ type: "text", text: "" }] });
60099
+ binding.ompExpectedAssistantHasOutput = activeWriter.message.content.some((block) => block.type !== "text" || block.text.length > 0);
60100
+ binding.ompInFlight = false;
60053
60101
  if (response.stopReason !== "cancelled") binding.ompCancelledCheckpoint = false;
60054
60102
  await this.persistBinding(binding);
60055
60103
  if (response.stopReason === "end_turn") {
@@ -60070,15 +60118,23 @@ var AntigravityRuntime = class {
60070
60118
  binding.writer?.fail(error62, isAbort(error62));
60071
60119
  if (isAbort(error62) || binding.abortRequested) {
60072
60120
  abortTurn(binding);
60073
- if (binding.connection.process.alive && !binding.needsReconstruction && ["cancelled", "end_turn"].includes(binding.ompTerminalStopReason)) {
60121
+ if (binding.connection.process.alive && !binding.ompInvalidated && !binding.needsReconstruction && ["cancelled", "end_turn"].includes(binding.ompTerminalStopReason)) {
60074
60122
  binding.messageCount = binding.pendingContextCount;
60075
60123
  binding.historyFingerprint = binding.pendingContextFingerprint;
60076
60124
  binding.expectedAssistantFingerprint = this.ompMessageFingerprint((binding.writer ?? writer).message);
60077
60125
  binding.ompCancelledCheckpoint = true;
60078
60126
  binding.ompCancelledHadOutput = (binding.writer ?? writer).message.content.length > 0;
60079
- await this.persistBinding(binding);
60127
+ binding.ompExpectedAssistantHasOutput = binding.ompCancelledHadOutput;
60128
+ binding.ompInFlight = false;
60129
+ try {
60130
+ await this.persistBinding(binding);
60131
+ } catch (checkpointError) {
60132
+ await this.invalidateBinding(binding);
60133
+ throw checkpointError;
60134
+ }
60080
60135
  } else await this.invalidateBinding(binding);
60081
- }
60136
+ } else if (ompDispatched) await this.invalidateBinding(binding);
60137
+ else binding.ompInFlight = false;
60082
60138
  if (!binding.connection.process.alive) await this.dropBinding(key, binding);
60083
60139
  throw error62;
60084
60140
  } finally {
@@ -60131,7 +60187,13 @@ var AntigravityRuntime = class {
60131
60187
  async getBinding(key, model, acpModelId, apiKey, writer, tools, signal) {
60132
60188
  this.assertActive();
60133
60189
  const existing = this.bindings.get(key);
60134
- if (existing) return existing;
60190
+ if (existing) {
60191
+ const value = await existing;
60192
+ if (!value.ompInvalidated) return value;
60193
+ await value.ompDropPromise;
60194
+ if (this.bindings.get(key) === existing) this.bindings.delete(key);
60195
+ return this.getBinding(key, model, acpModelId, apiKey, writer, tools, signal);
60196
+ }
60135
60197
  const created = this.createBinding(key, model, acpModelId, apiKey, writer, tools ?? [], signal).catch((error62) => {
60136
60198
  if (this.bindings.get(key) === created) this.bindings.delete(key);
60137
60199
  throw error62;
@@ -60167,7 +60229,12 @@ var AntigravityRuntime = class {
60167
60229
  }
60168
60230
  const mcpServers = mcpServer ? [mcpServer] : [];
60169
60231
  const piSessionId = key.startsWith("sid:") ? key.slice(4) : void 0;
60170
- const saved = piSessionId ? await this.sessionStore?.get(piSessionId) : void 0;
60232
+ let saved = piSessionId ? await this.sessionStore?.get(piSessionId) : void 0;
60233
+ if (saved && (saved.ompCheckpointVersion !== 1 || saved.ompInFlight !== false)) {
60234
+ await connection.retireForReplacement?.(key, saved.acpSessionId);
60235
+ await this.ompRemoveSaved(saved.piSessionId, saved.acpSessionId);
60236
+ saved = void 0;
60237
+ }
60171
60238
  let session;
60172
60239
  let restored = false;
60173
60240
  if (saved?.cwd === cwd) {
@@ -60205,6 +60272,9 @@ var AntigravityRuntime = class {
60205
60272
  this.assertEpoch(epoch);
60206
60273
  if (mode !== this.permissionMode) throw new AntigravityAcpError("protocol", "Permission mode changed during session setup; retry the turn");
60207
60274
  const createdBinding = {
60275
+ ompInFlight: false,
60276
+ ompInvalidated: false,
60277
+ ompExpectedAssistantHasOutput: restored && saved?.ompExpectedAssistantHasOutput === true,
60208
60278
  key,
60209
60279
  cwd,
60210
60280
  connection,
@@ -60244,7 +60314,7 @@ var AntigravityRuntime = class {
60244
60314
  void bridge?.close().catch(() => void 0);
60245
60315
  const current = this.bindings.get(key);
60246
60316
  if (current) void current.then((value) => {
60247
- if (value === createdBinding && this.bindings.get(key) === current) this.bindings.delete(key);
60317
+ if (value === createdBinding && this.bindings.get(key) === current && !createdBinding.ompInvalidated) this.bindings.delete(key);
60248
60318
  }).catch(() => void 0);
60249
60319
  }).catch(() => void 0);
60250
60320
  return createdBinding;
@@ -60254,15 +60324,18 @@ var AntigravityRuntime = class {
60254
60324
  }
60255
60325
  }
60256
60326
  async persistBinding(binding) {
60257
- if (!binding.piSessionId) return;
60327
+ if (!binding.piSessionId || binding.ompInvalidated) return;
60258
60328
  if (binding.needsReconstruction) {
60259
- await this.sessionStore?.remove(binding.piSessionId);
60329
+ await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
60260
60330
  return;
60261
60331
  }
60262
60332
  await this.sessionStore?.save({
60263
60333
  piSessionId: binding.piSessionId,
60264
60334
  acpSessionId: binding.session.sessionId,
60265
60335
  acpModelId: binding.modelId,
60336
+ ompCheckpointVersion: 1,
60337
+ ompInFlight: binding.ompInFlight === true,
60338
+ ompExpectedAssistantHasOutput: binding.ompExpectedAssistantHasOutput === true,
60266
60339
  ompCancelledCheckpoint: binding.ompCancelledCheckpoint === true,
60267
60340
  ompCancelledHadOutput: binding.ompCancelledHadOutput === true,
60268
60341
  cwd: binding.cwd,
@@ -60339,17 +60412,35 @@ var AntigravityRuntime = class {
60339
60412
  else if (activity.type === "tool" || activity.type === "plan") binding.writer.thinking(activity.text);
60340
60413
  }
60341
60414
  }
60415
+ async ompRemoveSaved(piSessionId, acpSessionId) {
60416
+ if (typeof this.sessionStore?.removeIfMatches === "function") await this.sessionStore.removeIfMatches(piSessionId, acpSessionId);
60417
+ else await this.sessionStore?.remove(piSessionId);
60418
+ }
60342
60419
  async dropBinding(key, binding, removeSaved = false) {
60343
- if (removeSaved) await binding.connection.retireForReplacement?.(key, binding.session.sessionId);
60344
- const current = this.bindings.get(key);
60345
- if (current && await current === binding && this.bindings.get(key) === current) {
60346
- this.bindings.delete(key);
60347
- if (removeSaved && binding.piSessionId) await this.sessionStore?.remove(binding.piSessionId);
60348
- }
60349
- this.resolvedBindings.delete(binding);
60350
- cancelPermission(binding);
60351
- cancelPiTools(binding, "Antigravity session closed before Pi returned the tool result");
60352
- await Promise.allSettled([binding.connection.close(), binding.bridge?.close() ?? Promise.resolve()]);
60420
+ if (removeSaved) binding.ompInvalidated = true;
60421
+ if (binding.ompDropPromise) {
60422
+ await binding.ompDropPromise;
60423
+ if (removeSaved && binding.piSessionId) await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
60424
+ return;
60425
+ }
60426
+ const dropping = (async () => {
60427
+ const current = this.bindings.get(key);
60428
+ this.resolvedBindings.delete(binding);
60429
+ cancelPermission(binding);
60430
+ cancelPiTools(binding, "Antigravity session closed before Pi returned the tool result");
60431
+ const closing = Promise.allSettled([binding.connection.close(), binding.bridge?.close() ?? Promise.resolve()]);
60432
+ try {
60433
+ if (removeSaved) {
60434
+ await binding.connection.retireForReplacement?.(key, binding.session.sessionId);
60435
+ if (binding.piSessionId) await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
60436
+ }
60437
+ } finally {
60438
+ await closing;
60439
+ if (current && await current === binding && this.bindings.get(key) === current) this.bindings.delete(key);
60440
+ }
60441
+ })();
60442
+ binding.ompDropPromise = dropping;
60443
+ await dropping;
60353
60444
  }
60354
60445
  confirmedMode(binding) {
60355
60446
  return sessionModes(binding.connection.getSessionState(binding.session.sessionId))?.currentModeId;
@@ -10,6 +10,7 @@ interface SavedSessionRecord {
10
10
  messageCount: number; historyFingerprint: string; lastActive: number;
11
11
  expectedAssistantFingerprint?: string;
12
12
  ompCancelledCheckpoint?: boolean; ompCancelledHadOutput?: boolean;
13
+ ompCheckpointVersion?: 1; ompInFlight?: boolean; ompExpectedAssistantHasOutput?: boolean;
13
14
  }
14
15
  const tails = new Map<string, Promise<unknown>>();
15
16
 
@@ -81,7 +82,10 @@ export class AcpSessionStore {
81
82
  return parsed.filter((record): record is SavedSessionRecord => Boolean(record) && typeof record === "object" &&
82
83
  ["piSessionId", "acpSessionId", "acpModelId", "cwd", "historyFingerprint"].every(key => typeof record[key] === "string") &&
83
84
  Number.isSafeInteger(record.messageCount) && record.messageCount >= 0 && Number.isFinite(record.lastActive) &&
84
- (record.expectedAssistantFingerprint === undefined || typeof record.expectedAssistantFingerprint === "string"));
85
+ (record.expectedAssistantFingerprint === undefined || typeof record.expectedAssistantFingerprint === "string") &&
86
+ (record.ompCheckpointVersion === undefined || record.ompCheckpointVersion === 1) &&
87
+ ["ompInFlight", "ompExpectedAssistantHasOutput", "ompCancelledCheckpoint", "ompCancelledHadOutput"].every(key =>
88
+ record[key] === undefined || typeof record[key] === "boolean"));
85
89
  }
86
90
  private async write(records: SavedSessionRecord[]): Promise<void> {
87
91
  if (!records.length) { await fs.rm(this.file, { force: true }); return; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-antigravity-acp-provider",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
4
4
  "ompAcpBundle": 1,
5
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",
6
6
  "type": "module",
@@ -43,6 +43,7 @@
43
43
  "test:auth": "bun scripts/test-auth-command.ts",
44
44
  "test:cleanup": "node scripts/test-cleanup-runtime.ts",
45
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",
46
47
  "check": "npm run build && npm test && npm run test:cleanup && npm run test:continuity && npm run test:graph && npm run test:commands",
47
48
  "prepack": "npm run build",
48
49
  "prepublishOnly": "npm run check",
package/scripts/build.mjs CHANGED
@@ -101,16 +101,19 @@ const result = await build({
101
101
  replacement: [
102
102
  "if (isAbort(error) || binding.abortRequested) {",
103
103
  "\t\t\t\tabortTurn(binding);",
104
- "\t\t\t\tif (binding.connection.process.alive && !binding.needsReconstruction &&",
104
+ "\t\t\t\tif (binding.connection.process.alive && !binding.ompInvalidated && !binding.needsReconstruction &&",
105
105
  "\t\t\t\t\t['cancelled', 'end_turn'].includes(binding.ompTerminalStopReason)) {",
106
106
  "\t\t\t\t\tbinding.messageCount = binding.pendingContextCount;",
107
107
  "\t\t\t\t\tbinding.historyFingerprint = binding.pendingContextFingerprint;",
108
108
  "\t\t\t\t\tbinding.expectedAssistantFingerprint = messageFingerprint((binding.writer ?? writer).message);",
109
109
  "\t\t\t\t\tbinding.ompCancelledCheckpoint = true;",
110
110
  "\t\t\t\t\tbinding.ompCancelledHadOutput = (binding.writer ?? writer).message.content.length > 0;",
111
- "\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; }",
112
114
  "\t\t\t\t} else await this.invalidateBinding(binding);",
113
- "\t\t\t}",
115
+ "\t\t\t} else if (ompDispatched) await this.invalidateBinding(binding);",
116
+ "\t\t\telse binding.ompInFlight = false;",
114
117
  ].join("\n"),
115
118
  },
116
119
  {
@@ -124,13 +127,14 @@ const result = await build({
124
127
  replacement: "binding.ompTerminalStopReason = response.stopReason;\n\t\t\tif (binding.abortRequested) throw abortError();",
125
128
  },
126
129
  {
127
- name: "cancelled partial output must match retained OMP history",
130
+ name: "generated assistant boundary must match retained OMP history",
128
131
  anchor: "binding.needsReconstruction || binding.mode !== this.permissionMode ||",
129
132
  replacement: [
130
133
  "binding.needsReconstruction ||",
131
- "\t\t\t\t(binding.ompCancelledCheckpoint && (context.messages[binding.messageCount]?.role === 'assistant'",
132
- "\t\t\t\t\t? messageFingerprint(context.messages[binding.messageCount]) !== binding.expectedAssistantFingerprint",
133
- "\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 ||",
134
138
  ].join("\n"),
135
139
  },
136
140
  {
@@ -187,6 +191,93 @@ const result = await build({
187
191
  if (contents.split(anchor).length !== count + 1) throw new Error(`Pinned store call sites changed: ${anchor}`);
188
192
  contents = contents.replaceAll(anchor, replacement);
189
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, 'await claimContinuation(binding, async () => {\n\t\t\t\t' + claimStart)
247
+ .replaceAll(claimEnd, '}, () => this.invalidateBinding(binding));\n\t\t\t\tawait this.awaitContinuation(binding, options.signal);\n\t\t\t\treturn;');
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(`);
190
281
  const flushAnchor = "\n\tprivate async runQueued(";
191
282
  const beforeQueue = contents.slice(0, contents.indexOf(flushAnchor));
192
283
  const endClose = beforeQueue.lastIndexOf("\n\t}");
@@ -224,6 +315,7 @@ const result = await build({
224
315
  .replaceAll("binding.connection.confirmReplacement?.(", "await binding.connection.confirmReplacement?.(")
225
316
  .replaceAll("binding.connection.discardSession?.(", "await binding.connection.discardSession?.(");
226
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;
227
319
  contents = `import { createHistoryFingerprintMemo } from ${JSON.stringify(path.join(root, "extension/history-fingerprint.ts"))};\nconst ompMessageFingerprintMemo = createHistoryFingerprintMemo();\n` + contents;
228
320
  return { contents, loader: "ts" };
229
321
  });