omp-antigravity-acp-provider 0.1.20 → 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.
- package/README.md +10 -8
- package/extension/context-transfer.ts +25 -0
- package/extension/continuation-claim.ts +20 -0
- package/extension/runtime.mjs +139 -50
- package/extension/session-store.ts +5 -1
- package/package.json +2 -1
- package/scripts/build.mjs +99 -7
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.
|
|
22
|
+
Version 0.1.21 protects plan refinement from the official single-step text limit and fixes uncertain checkpoints, duplicate tool continuations and stale-session reconstruction. Restart OMP after upgrading to load the new code.
|
|
23
23
|
|
|
24
|
-
Version 0.1.
|
|
24
|
+
Version 0.1.21 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 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.
|
|
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.21** 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.
|
|
85
|
+
omp plugin install npm:omp-antigravity-acp-provider@0.1.21
|
|
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
|
|
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
|
|
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
|
|
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,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
|
+
}
|
package/extension/runtime.mjs
CHANGED
|
@@ -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,24 +59973,25 @@ var AntigravityRuntime = class {
|
|
|
59939
59973
|
const result = findPermissionResult(context, pending.id);
|
|
59940
59974
|
if (!result) {
|
|
59941
59975
|
cancelPermission(binding);
|
|
59942
|
-
await this.
|
|
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
|
|
59946
|
-
|
|
59947
|
-
|
|
59948
|
-
|
|
59949
|
-
|
|
59950
|
-
|
|
59951
|
-
|
|
59952
|
-
|
|
59953
|
-
|
|
59954
|
-
|
|
59955
|
-
|
|
59956
|
-
|
|
59957
|
-
|
|
59958
|
-
|
|
59959
|
-
|
|
59979
|
+
return 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
|
+
await this.awaitContinuation(binding, options.signal);
|
|
59994
|
+
}, () => this.invalidateBinding(binding));
|
|
59960
59995
|
}
|
|
59961
59996
|
}
|
|
59962
59997
|
if (binding.pendingTools.size > 0) {
|
|
@@ -59966,21 +60001,22 @@ var AntigravityRuntime = class {
|
|
|
59966
60001
|
}));
|
|
59967
60002
|
if (results.some((result) => result.message === void 0)) {
|
|
59968
60003
|
cancelPiTools(binding, "Pi continued without returning every requested tool result");
|
|
59969
|
-
await this.
|
|
60004
|
+
await this.invalidateBinding(binding);
|
|
59970
60005
|
binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
|
|
59971
60006
|
} else {
|
|
59972
|
-
binding
|
|
59973
|
-
|
|
59974
|
-
|
|
59975
|
-
|
|
59976
|
-
|
|
59977
|
-
|
|
59978
|
-
|
|
59979
|
-
|
|
59980
|
-
|
|
59981
|
-
|
|
59982
|
-
|
|
59983
|
-
|
|
60007
|
+
return await claimContinuation(binding, async () => {
|
|
60008
|
+
binding.writer = writer;
|
|
60009
|
+
const continuationTurn = binding.turnCompletion;
|
|
60010
|
+
await this.noteContinuationInstructions(binding, context);
|
|
60011
|
+
if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();
|
|
60012
|
+
binding.pendingContextCount = context.messages.length;
|
|
60013
|
+
binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
|
|
60014
|
+
for (const { pending, message } of results) {
|
|
60015
|
+
binding.pendingTools.delete(pending.invocation.id);
|
|
60016
|
+
pending.resolve(toMcpToolResult(message));
|
|
60017
|
+
}
|
|
60018
|
+
await this.awaitContinuation(binding, options.signal);
|
|
60019
|
+
}, () => this.invalidateBinding(binding));
|
|
59984
60020
|
}
|
|
59985
60021
|
}
|
|
59986
60022
|
const previous = this.queues.get(key) ?? Promise.resolve();
|
|
@@ -59990,13 +60026,14 @@ var AntigravityRuntime = class {
|
|
|
59990
60026
|
});
|
|
59991
60027
|
this.queues.set(key, queue);
|
|
59992
60028
|
await previous;
|
|
60029
|
+
let ompDispatched = false;
|
|
59993
60030
|
let completeTurn;
|
|
59994
60031
|
let onTurnAbort;
|
|
59995
60032
|
try {
|
|
59996
60033
|
await this.modeChanges;
|
|
59997
60034
|
this.assertEpoch(epoch);
|
|
59998
60035
|
binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
|
|
59999
|
-
if (binding.needsReconstruction || binding.
|
|
60036
|
+
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
60037
|
await this.dropBinding(key, binding, true);
|
|
60001
60038
|
binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
|
|
60002
60039
|
}
|
|
@@ -60035,6 +60072,13 @@ var AntigravityRuntime = class {
|
|
|
60035
60072
|
options.signal.addEventListener("abort", onTurnAbort, { once: true });
|
|
60036
60073
|
if (options.signal.aborted) onTurnAbort();
|
|
60037
60074
|
}
|
|
60075
|
+
if (options.signal?.aborted) throw abortError();
|
|
60076
|
+
binding.ompInFlight = true;
|
|
60077
|
+
await this.persistBinding(binding);
|
|
60078
|
+
this.assertEpoch(epoch);
|
|
60079
|
+
if (binding.ompInvalidated || !binding.connection.process.alive) throw new AntigravityAcpError("protocol", "ACP session closed before prompt dispatch");
|
|
60080
|
+
if (options.signal?.aborted) throw abortError();
|
|
60081
|
+
ompDispatched = true;
|
|
60038
60082
|
const response = await binding.connection.prompt(
|
|
60039
60083
|
{ sessionId: binding.session.sessionId, prompt: parts.prompt },
|
|
60040
60084
|
options.signal
|
|
@@ -60049,7 +60093,9 @@ var AntigravityRuntime = class {
|
|
|
60049
60093
|
activeWriter.message.rawStopReason = response.stopReason;
|
|
60050
60094
|
binding.messageCount = binding.pendingContextCount || parts.messageCount;
|
|
60051
60095
|
binding.historyFingerprint = binding.pendingContextFingerprint;
|
|
60052
|
-
binding.expectedAssistantFingerprint = this.ompMessageFingerprint(activeWriter.message);
|
|
60096
|
+
binding.expectedAssistantFingerprint = this.ompMessageFingerprint(activeWriter.message.content.length ? activeWriter.message : { ...activeWriter.message, content: [{ type: "text", text: "" }] });
|
|
60097
|
+
binding.ompExpectedAssistantHasOutput = activeWriter.message.content.some((block) => block.type !== "text" || block.text.length > 0);
|
|
60098
|
+
binding.ompInFlight = false;
|
|
60053
60099
|
if (response.stopReason !== "cancelled") binding.ompCancelledCheckpoint = false;
|
|
60054
60100
|
await this.persistBinding(binding);
|
|
60055
60101
|
if (response.stopReason === "end_turn") {
|
|
@@ -60070,15 +60116,23 @@ var AntigravityRuntime = class {
|
|
|
60070
60116
|
binding.writer?.fail(error62, isAbort(error62));
|
|
60071
60117
|
if (isAbort(error62) || binding.abortRequested) {
|
|
60072
60118
|
abortTurn(binding);
|
|
60073
|
-
if (binding.connection.process.alive && !binding.needsReconstruction && ["cancelled", "end_turn"].includes(binding.ompTerminalStopReason)) {
|
|
60119
|
+
if (binding.connection.process.alive && !binding.ompInvalidated && !binding.needsReconstruction && ["cancelled", "end_turn"].includes(binding.ompTerminalStopReason)) {
|
|
60074
60120
|
binding.messageCount = binding.pendingContextCount;
|
|
60075
60121
|
binding.historyFingerprint = binding.pendingContextFingerprint;
|
|
60076
60122
|
binding.expectedAssistantFingerprint = this.ompMessageFingerprint((binding.writer ?? writer).message);
|
|
60077
60123
|
binding.ompCancelledCheckpoint = true;
|
|
60078
60124
|
binding.ompCancelledHadOutput = (binding.writer ?? writer).message.content.length > 0;
|
|
60079
|
-
|
|
60125
|
+
binding.ompExpectedAssistantHasOutput = binding.ompCancelledHadOutput;
|
|
60126
|
+
binding.ompInFlight = false;
|
|
60127
|
+
try {
|
|
60128
|
+
await this.persistBinding(binding);
|
|
60129
|
+
} catch (checkpointError) {
|
|
60130
|
+
await this.invalidateBinding(binding);
|
|
60131
|
+
throw checkpointError;
|
|
60132
|
+
}
|
|
60080
60133
|
} else await this.invalidateBinding(binding);
|
|
60081
|
-
}
|
|
60134
|
+
} else if (ompDispatched) await this.invalidateBinding(binding);
|
|
60135
|
+
else binding.ompInFlight = false;
|
|
60082
60136
|
if (!binding.connection.process.alive) await this.dropBinding(key, binding);
|
|
60083
60137
|
throw error62;
|
|
60084
60138
|
} finally {
|
|
@@ -60131,7 +60185,13 @@ var AntigravityRuntime = class {
|
|
|
60131
60185
|
async getBinding(key, model, acpModelId, apiKey, writer, tools, signal) {
|
|
60132
60186
|
this.assertActive();
|
|
60133
60187
|
const existing = this.bindings.get(key);
|
|
60134
|
-
if (existing)
|
|
60188
|
+
if (existing) {
|
|
60189
|
+
const value = await existing;
|
|
60190
|
+
if (!value.ompInvalidated) return value;
|
|
60191
|
+
await value.ompDropPromise;
|
|
60192
|
+
if (this.bindings.get(key) === existing) this.bindings.delete(key);
|
|
60193
|
+
return this.getBinding(key, model, acpModelId, apiKey, writer, tools, signal);
|
|
60194
|
+
}
|
|
60135
60195
|
const created = this.createBinding(key, model, acpModelId, apiKey, writer, tools ?? [], signal).catch((error62) => {
|
|
60136
60196
|
if (this.bindings.get(key) === created) this.bindings.delete(key);
|
|
60137
60197
|
throw error62;
|
|
@@ -60167,7 +60227,12 @@ var AntigravityRuntime = class {
|
|
|
60167
60227
|
}
|
|
60168
60228
|
const mcpServers = mcpServer ? [mcpServer] : [];
|
|
60169
60229
|
const piSessionId = key.startsWith("sid:") ? key.slice(4) : void 0;
|
|
60170
|
-
|
|
60230
|
+
let saved = piSessionId ? await this.sessionStore?.get(piSessionId) : void 0;
|
|
60231
|
+
if (saved && (saved.ompCheckpointVersion !== 1 || saved.ompInFlight !== false)) {
|
|
60232
|
+
await connection.retireForReplacement?.(key, saved.acpSessionId);
|
|
60233
|
+
await this.ompRemoveSaved(saved.piSessionId, saved.acpSessionId);
|
|
60234
|
+
saved = void 0;
|
|
60235
|
+
}
|
|
60171
60236
|
let session;
|
|
60172
60237
|
let restored = false;
|
|
60173
60238
|
if (saved?.cwd === cwd) {
|
|
@@ -60205,6 +60270,9 @@ var AntigravityRuntime = class {
|
|
|
60205
60270
|
this.assertEpoch(epoch);
|
|
60206
60271
|
if (mode !== this.permissionMode) throw new AntigravityAcpError("protocol", "Permission mode changed during session setup; retry the turn");
|
|
60207
60272
|
const createdBinding = {
|
|
60273
|
+
ompInFlight: false,
|
|
60274
|
+
ompInvalidated: false,
|
|
60275
|
+
ompExpectedAssistantHasOutput: restored && saved?.ompExpectedAssistantHasOutput === true,
|
|
60208
60276
|
key,
|
|
60209
60277
|
cwd,
|
|
60210
60278
|
connection,
|
|
@@ -60244,7 +60312,7 @@ var AntigravityRuntime = class {
|
|
|
60244
60312
|
void bridge?.close().catch(() => void 0);
|
|
60245
60313
|
const current = this.bindings.get(key);
|
|
60246
60314
|
if (current) void current.then((value) => {
|
|
60247
|
-
if (value === createdBinding && this.bindings.get(key) === current) this.bindings.delete(key);
|
|
60315
|
+
if (value === createdBinding && this.bindings.get(key) === current && !createdBinding.ompInvalidated) this.bindings.delete(key);
|
|
60248
60316
|
}).catch(() => void 0);
|
|
60249
60317
|
}).catch(() => void 0);
|
|
60250
60318
|
return createdBinding;
|
|
@@ -60254,15 +60322,18 @@ var AntigravityRuntime = class {
|
|
|
60254
60322
|
}
|
|
60255
60323
|
}
|
|
60256
60324
|
async persistBinding(binding) {
|
|
60257
|
-
if (!binding.piSessionId) return;
|
|
60325
|
+
if (!binding.piSessionId || binding.ompInvalidated) return;
|
|
60258
60326
|
if (binding.needsReconstruction) {
|
|
60259
|
-
await this.
|
|
60327
|
+
await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
|
|
60260
60328
|
return;
|
|
60261
60329
|
}
|
|
60262
60330
|
await this.sessionStore?.save({
|
|
60263
60331
|
piSessionId: binding.piSessionId,
|
|
60264
60332
|
acpSessionId: binding.session.sessionId,
|
|
60265
60333
|
acpModelId: binding.modelId,
|
|
60334
|
+
ompCheckpointVersion: 1,
|
|
60335
|
+
ompInFlight: binding.ompInFlight === true,
|
|
60336
|
+
ompExpectedAssistantHasOutput: binding.ompExpectedAssistantHasOutput === true,
|
|
60266
60337
|
ompCancelledCheckpoint: binding.ompCancelledCheckpoint === true,
|
|
60267
60338
|
ompCancelledHadOutput: binding.ompCancelledHadOutput === true,
|
|
60268
60339
|
cwd: binding.cwd,
|
|
@@ -60339,17 +60410,35 @@ var AntigravityRuntime = class {
|
|
|
60339
60410
|
else if (activity.type === "tool" || activity.type === "plan") binding.writer.thinking(activity.text);
|
|
60340
60411
|
}
|
|
60341
60412
|
}
|
|
60413
|
+
async ompRemoveSaved(piSessionId, acpSessionId) {
|
|
60414
|
+
if (typeof this.sessionStore?.removeIfMatches === "function") await this.sessionStore.removeIfMatches(piSessionId, acpSessionId);
|
|
60415
|
+
else await this.sessionStore?.remove(piSessionId);
|
|
60416
|
+
}
|
|
60342
60417
|
async dropBinding(key, binding, removeSaved = false) {
|
|
60343
|
-
if (removeSaved)
|
|
60344
|
-
|
|
60345
|
-
|
|
60346
|
-
this.
|
|
60347
|
-
|
|
60348
|
-
}
|
|
60349
|
-
|
|
60350
|
-
|
|
60351
|
-
|
|
60352
|
-
|
|
60418
|
+
if (removeSaved) binding.ompInvalidated = true;
|
|
60419
|
+
if (binding.ompDropPromise) {
|
|
60420
|
+
await binding.ompDropPromise;
|
|
60421
|
+
if (removeSaved && binding.piSessionId) await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
|
|
60422
|
+
return;
|
|
60423
|
+
}
|
|
60424
|
+
const dropping = (async () => {
|
|
60425
|
+
const current = this.bindings.get(key);
|
|
60426
|
+
this.resolvedBindings.delete(binding);
|
|
60427
|
+
cancelPermission(binding);
|
|
60428
|
+
cancelPiTools(binding, "Antigravity session closed before Pi returned the tool result");
|
|
60429
|
+
const closing = Promise.allSettled([binding.connection.close(), binding.bridge?.close() ?? Promise.resolve()]);
|
|
60430
|
+
try {
|
|
60431
|
+
if (removeSaved) {
|
|
60432
|
+
await binding.connection.retireForReplacement?.(key, binding.session.sessionId);
|
|
60433
|
+
if (binding.piSessionId) await this.ompRemoveSaved(binding.piSessionId, binding.session.sessionId);
|
|
60434
|
+
}
|
|
60435
|
+
} finally {
|
|
60436
|
+
await closing;
|
|
60437
|
+
if (current && await current === binding && this.bindings.get(key) === current) this.bindings.delete(key);
|
|
60438
|
+
}
|
|
60439
|
+
})();
|
|
60440
|
+
binding.ompDropPromise = dropping;
|
|
60441
|
+
await dropping;
|
|
60353
60442
|
}
|
|
60354
60443
|
confirmedMode(binding) {
|
|
60355
60444
|
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.
|
|
3
|
+
"version": "0.1.21",
|
|
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\
|
|
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: "
|
|
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.
|
|
132
|
-
"\t\t\t\t\
|
|
133
|
-
"\t\t\t\t
|
|
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, '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(`);
|
|
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
|
});
|