omp-antigravity-acp-provider 0.1.22 → 0.1.23

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.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.
22
+ Version 0.1.23 adds cross-process session ownership, isolates adapter state by OMP agent directory, and preserves registries with unsupported records. Restart all OMP processes after upgrading so they participate in session ownership.
23
23
 
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.
24
+ Version 0.1.23 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.23 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.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.
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.23** 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.22
85
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.23
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.
@@ -49,8 +49,17 @@ interface OmpHostApi {
49
49
  registerCommand: (name: string, command: { description: string; handler: (args: string, ctx: OmpCommandContext) => Promise<void> }) => void;
50
50
  }
51
51
 
52
+ export function resolveAdapterStateDir(env: NodeJS.ProcessEnv = process.env, home = os.homedir()): string {
53
+ // OMP sets this to the active named profile's agent directory during CLI
54
+ // bootstrap; it also honors an explicit default-profile override.
55
+ const configured = env.PI_CODING_AGENT_DIR?.trim();
56
+ const agentDir = configured ? configured === "~" ? home : configured.startsWith("~/") ? path.join(home, configured.slice(2)) : path.resolve(configured)
57
+ : path.join(home, env.PI_CONFIG_DIR || ".omp", "agent");
58
+ return path.join(agentDir, "antigravity-acp-provider");
59
+ }
60
+
52
61
  export default async function (pi: OmpHostApi) {
53
- return registerOmpAdapter(pi, path.join(os.homedir(), ".omp/agent/antigravity-acp-provider"));
62
+ return registerOmpAdapter(pi, resolveAdapterStateDir());
54
63
  }
55
64
 
56
65
  // Explicit state injection keeps command integration tests away from user data.
@@ -19570,7 +19570,7 @@ function collapseSystemMessages(context) {
19570
19570
  }
19571
19571
 
19572
19572
  // node_modules/pi-antigravity-acp-provider/src/runtime.ts
19573
- import { createHash as createHash2 } from "node:crypto";
19573
+ import { createHash as createHash3 } from "node:crypto";
19574
19574
 
19575
19575
  // node_modules/@agentclientprotocol/sdk/dist/schema/index.js
19576
19576
  var AGENT_METHODS = {
@@ -44404,7 +44404,7 @@ function structuredErrorDetail(data) {
44404
44404
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
44405
44405
  import fs4 from "node:fs/promises";
44406
44406
  import path5 from "node:path";
44407
- import { randomUUID } from "node:crypto";
44407
+ import { createHash, randomUUID } from "node:crypto";
44408
44408
  import { setTimeout as delay2 } from "node:timers/promises";
44409
44409
 
44410
44410
  // node_modules/pi-antigravity-acp-provider/src/config.ts
@@ -44504,6 +44504,21 @@ var AcpSessionStore = class {
44504
44504
  async flush() {
44505
44505
  await tails.get(this.file);
44506
44506
  }
44507
+ // Hold ownership across restoration, prompts and warm idle reuse. The
44508
+ // registry write lock alone cannot prevent two processes restoring one ID.
44509
+ async acquireSessionLease(id, compromised) {
44510
+ const directory = path5.join(path5.dirname(this.file), "session-leases");
44511
+ await fs4.mkdir(directory, { recursive: true, mode: 448 });
44512
+ const target = path5.join(directory, createHash("sha256").update(id).digest("hex"));
44513
+ try {
44514
+ const release = await (0, import_proper_lockfile.lock)(target, { realpath: false, stale: 3e4, retries: 0, onCompromised: compromised });
44515
+ let done;
44516
+ return () => done ??= release();
44517
+ } catch (error62) {
44518
+ if (error62.code === "ELOCKED") throw new Error("This OMP session is already open in another ACP runtime. Close the other OMP session and retry.");
44519
+ throw error62;
44520
+ }
44521
+ }
44507
44522
  get(id) {
44508
44523
  return this.enqueue(async () => (await this.read()).find((record3) => record3.piSessionId === id && Date.now() - record3.lastActive <= 30 * 24 * 60 * 6e4));
44509
44524
  }
@@ -44571,7 +44586,9 @@ var AcpSessionStore = class {
44571
44586
  }
44572
44587
  const parsed = JSON.parse(raw);
44573
44588
  if (!Array.isArray(parsed)) throw new Error("Invalid ACP session registry; refusing to overwrite it");
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"));
44589
+ const valid = (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");
44590
+ if (!parsed.every(valid)) throw new Error("Invalid or unsupported ACP session registry record; refusing to overwrite it");
44591
+ return parsed;
44575
44592
  }
44576
44593
  async write(records) {
44577
44594
  if (!records.length) {
@@ -44652,7 +44669,7 @@ function clean(value) {
44652
44669
  // node_modules/pi-antigravity-acp-provider/src/acp/setup.ts
44653
44670
  var import_unzipper = __toESM(require_unzip2(), 1);
44654
44671
  import { execFile } from "node:child_process";
44655
- import { createHash } from "node:crypto";
44672
+ import { createHash as createHash2 } from "node:crypto";
44656
44673
  import fs6 from "node:fs";
44657
44674
  import os3 from "node:os";
44658
44675
  import path6 from "node:path";
@@ -45018,7 +45035,7 @@ async function validateRuntime(directory, release) {
45018
45035
  async function download(release, destination, onProgress) {
45019
45036
  const response = await fetch(release.archive, { signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS) });
45020
45037
  if (!response.ok || !response.body) throw new Error(`ACP server download returned HTTP ${response.status}`);
45021
- const hash2 = createHash("sha256");
45038
+ const hash2 = createHash2("sha256");
45022
45039
  let received = 0;
45023
45040
  let lastReported = 0;
45024
45041
  const progress = new TransformStream({
@@ -59936,6 +59953,7 @@ var AntigravityRuntime = class {
59936
59953
  })
59937
59954
  );
59938
59955
  await Promise.allSettled(closingTurns);
59956
+ await Promise.allSettled(pending.map(async (value) => (await value).ompReleaseLease?.()));
59939
59957
  try {
59940
59958
  await this.sessionStore?.flush?.();
59941
59959
  } finally {
@@ -60087,6 +60105,7 @@ var AntigravityRuntime = class {
60087
60105
  );
60088
60106
  if (onTurnAbort) options.signal?.removeEventListener("abort", onTurnAbort);
60089
60107
  const activeWriter = binding.writer ?? writer;
60108
+ if (binding.ompInvalidated) throw new AntigravityAcpError("protocol", "ACP session ownership was lost");
60090
60109
  binding.ompTerminalStopReason = response.stopReason;
60091
60110
  if (binding.abortRequested) throw abortError();
60092
60111
  const usage = usageFromPrompt2(response);
@@ -60206,6 +60225,8 @@ var AntigravityRuntime = class {
60206
60225
  let binding;
60207
60226
  let bridge;
60208
60227
  const epoch = this.bindingEpoch;
60228
+ let leaseLost = false;
60229
+ let releaseLease;
60209
60230
  const connection = this.createConnection({
60210
60231
  cwd,
60211
60232
  handlers: {
@@ -60214,6 +60235,15 @@ var AntigravityRuntime = class {
60214
60235
  }
60215
60236
  });
60216
60237
  try {
60238
+ if (key.startsWith("sid:") && typeof this.sessionStore?.acquireSessionLease === "function") {
60239
+ releaseLease = await this.sessionStore.acquireSessionLease(key.slice(4), () => {
60240
+ leaseLost = true;
60241
+ if (binding) binding.ompInvalidated = true;
60242
+ void connection.close().catch(() => {
60243
+ });
60244
+ });
60245
+ this.assertEpoch(epoch);
60246
+ }
60217
60247
  const initialize = await connection.initialize();
60218
60248
  this.assertEpoch(epoch);
60219
60249
  await authenticateForCredential(connection, initialize, apiKey, signal);
@@ -60274,6 +60304,7 @@ var AntigravityRuntime = class {
60274
60304
  const createdBinding = {
60275
60305
  ompInFlight: false,
60276
60306
  ompInvalidated: false,
60307
+ ompReleaseLease: releaseLease,
60277
60308
  ompExpectedAssistantHasOutput: restored && saved?.ompExpectedAssistantHasOutput === true,
60278
60309
  key,
60279
60310
  cwd,
@@ -60304,10 +60335,15 @@ var AntigravityRuntime = class {
60304
60335
  restored
60305
60336
  };
60306
60337
  binding = createdBinding;
60338
+ if (leaseLost) throw new AntigravityAcpError("protocol", "ACP session ownership was lost during initialization");
60307
60339
  await this.persistBinding(createdBinding);
60308
60340
  this.assertEpoch(epoch);
60309
60341
  this.resolvedBindings.add(createdBinding);
60310
60342
  void connection.process.exited.then(() => {
60343
+ const completion = createdBinding.turnCompletion;
60344
+ const retiring = createdBinding.ompDropPromise;
60345
+ void Promise.resolve(retiring ?? completion).then(() => createdBinding.ompReleaseLease?.()).catch(() => {
60346
+ });
60311
60347
  cancelPermission(createdBinding);
60312
60348
  cancelPiTools(createdBinding, "Antigravity process exited before Pi returned the tool result");
60313
60349
  this.resolvedBindings.delete(createdBinding);
@@ -60320,6 +60356,7 @@ var AntigravityRuntime = class {
60320
60356
  return createdBinding;
60321
60357
  } catch (error62) {
60322
60358
  await Promise.allSettled([connection.close(), bridge?.close() ?? Promise.resolve()]);
60359
+ await releaseLease?.();
60323
60360
  throw error62;
60324
60361
  }
60325
60362
  }
@@ -60436,6 +60473,7 @@ var AntigravityRuntime = class {
60436
60473
  }
60437
60474
  } finally {
60438
60475
  await closing;
60476
+ await binding.ompReleaseLease?.();
60439
60477
  if (current && await current === binding && this.bindings.get(key) === current) this.bindings.delete(key);
60440
60478
  }
60441
60479
  })();
@@ -60542,7 +60580,7 @@ function findPermissionResult(context, requestId) {
60542
60580
  }
60543
60581
  function messagesFingerprint(messages, systemMemo) {
60544
60582
  const fingerprints = messages.map((message) => messageFingerprint(message, systemMemo));
60545
- return createHash2("sha256").update(fingerprints.join("\n")).digest("hex");
60583
+ return createHash3("sha256").update(fingerprints.join("\n")).digest("hex");
60546
60584
  }
60547
60585
  function messageFingerprint(message, systemMemo) {
60548
60586
  let value;
@@ -60572,7 +60610,7 @@ function messageFingerprint(message, systemMemo) {
60572
60610
  isError: message.isError
60573
60611
  };
60574
60612
  }
60575
- const compute = () => createHash2("sha256").update(canonicalJson2(value)).digest("hex");
60613
+ const compute = () => createHash3("sha256").update(canonicalJson2(value)).digest("hex");
60576
60614
  return message.role === "system" && systemMemo ? systemMemo(value, compute) : ompMessageFingerprintMemo(message, value, compute);
60577
60615
  }
60578
60616
  function canonicalJson2(value) {
@@ -60606,7 +60644,7 @@ function cancelPermission(binding) {
60606
60644
  binding.permission = void 0;
60607
60645
  }
60608
60646
  function instructionFingerprint(context) {
60609
- return createHash2("sha256").update(currentSystemInstructions(context)).digest("hex");
60647
+ return createHash3("sha256").update(currentSystemInstructions(context)).digest("hex");
60610
60648
  }
60611
60649
  function abortTurn(binding) {
60612
60650
  binding.abortRequested = true;
@@ -61133,7 +61171,7 @@ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
61133
61171
  import fs10 from "node:fs";
61134
61172
  import afs from "node:fs/promises";
61135
61173
  import path10 from "node:path";
61136
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
61174
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
61137
61175
 
61138
61176
  // extension/omp-session-source.ts
61139
61177
  import fs9 from "node:fs/promises";
@@ -61211,7 +61249,7 @@ function live(pid) {
61211
61249
  return e.code !== "ESRCH";
61212
61250
  }
61213
61251
  }
61214
- var group = (key) => createHash3("sha256").update(key).digest("hex");
61252
+ var group = (key) => createHash4("sha256").update(key).digest("hex");
61215
61253
  var SessionCleanup = class {
61216
61254
  constructor(stateDir, acpDir = resolveAntigravityAcpDirectory(), now = Date.now, isLive = live) {
61217
61255
  this.stateDir = stateDir;
@@ -61219,7 +61257,7 @@ var SessionCleanup = class {
61219
61257
  this.now = now;
61220
61258
  this.isLive = isLive;
61221
61259
  this.policyPath = path10.join(stateDir, "cleanup.json");
61222
- this.registryPath = path10.join(stateDir, `cleanup-sessions-${createHash3("sha256").update(path10.resolve(acpDir)).digest("hex").slice(0, 16)}.json`);
61260
+ this.registryPath = path10.join(stateDir, `cleanup-sessions-${createHash4("sha256").update(path10.resolve(acpDir)).digest("hex").slice(0, 16)}.json`);
61223
61261
  }
61224
61262
  stateDir;
61225
61263
  acpDir;
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { randomUUID } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
5
  import { lock } from "proper-lockfile";
6
6
  import { resolvePiAgentDir } from "pi-antigravity-acp-provider/src/config.ts";
@@ -28,6 +28,21 @@ export class AcpSessionStore {
28
28
  return result;
29
29
  }
30
30
  async flush(): Promise<void> { await tails.get(this.file); }
31
+ // Hold ownership across restoration, prompts and warm idle reuse. The
32
+ // registry write lock alone cannot prevent two processes restoring one ID.
33
+ async acquireSessionLease(id: string, compromised: () => void): Promise<() => Promise<void>> {
34
+ const directory = path.join(path.dirname(this.file), "session-leases");
35
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
36
+ const target = path.join(directory, createHash("sha256").update(id).digest("hex"));
37
+ try {
38
+ const release = await lock(target, { realpath: false, stale: 30_000, retries: 0, onCompromised: compromised });
39
+ let done: Promise<void> | undefined;
40
+ return () => done ??= release();
41
+ } catch (error) {
42
+ if ((error as NodeJS.ErrnoException).code === "ELOCKED") throw new Error("This OMP session is already open in another ACP runtime. Close the other OMP session and retry.");
43
+ throw error;
44
+ }
45
+ }
31
46
  get(id: string): Promise<SavedSessionRecord | undefined> {
32
47
  return this.enqueue(async () => (await this.read()).find(record => record.piSessionId === id &&
33
48
  Date.now() - record.lastActive <= 30 * 24 * 60 * 60_000));
@@ -79,13 +94,15 @@ export class AcpSessionStore {
79
94
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
80
95
  const parsed: unknown = JSON.parse(raw);
81
96
  if (!Array.isArray(parsed)) throw new Error("Invalid ACP session registry; refusing to overwrite it");
82
- return parsed.filter((record): record is SavedSessionRecord => Boolean(record) && typeof record === "object" &&
97
+ const valid = (record: any): record is SavedSessionRecord => Boolean(record) && typeof record === "object" &&
83
98
  ["piSessionId", "acpSessionId", "acpModelId", "cwd", "historyFingerprint"].every(key => typeof record[key] === "string") &&
84
99
  Number.isSafeInteger(record.messageCount) && record.messageCount >= 0 && Number.isFinite(record.lastActive) &&
85
100
  (record.expectedAssistantFingerprint === undefined || typeof record.expectedAssistantFingerprint === "string") &&
86
101
  (record.ompCheckpointVersion === undefined || record.ompCheckpointVersion === 1) &&
87
102
  ["ompInFlight", "ompExpectedAssistantHasOutput", "ompCancelledCheckpoint", "ompCancelledHadOutput"].every(key =>
88
- record[key] === undefined || typeof record[key] === "boolean"));
103
+ record[key] === undefined || typeof record[key] === "boolean");
104
+ if (!parsed.every(valid)) throw new Error("Invalid or unsupported ACP session registry record; refusing to overwrite it");
105
+ return parsed;
89
106
  }
90
107
  private async write(records: SavedSessionRecord[]): Promise<void> {
91
108
  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.22",
3
+ "version": "0.1.23",
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",
package/scripts/build.mjs CHANGED
@@ -124,7 +124,7 @@ const result = await build({
124
124
  {
125
125
  name: "record official terminal reason before abort handling",
126
126
  anchor: "if (binding.abortRequested) throw abortError();",
127
- replacement: "binding.ompTerminalStopReason = response.stopReason;\n\t\t\tif (binding.abortRequested) throw abortError();",
127
+ replacement: "if (binding.ompInvalidated) throw new AntigravityAcpError('protocol', 'ACP session ownership was lost');\n\t\t\tbinding.ompTerminalStopReason = response.stopReason;\n\t\t\tif (binding.abortRequested) throw abortError();",
128
128
  },
129
129
  {
130
130
  name: "generated assistant boundary must match retained OMP history",
@@ -194,7 +194,7 @@ const result = await build({
194
194
  // Continuity transactions are adapter-owned. Keep explicit pinned seams
195
195
  // so an upstream update cannot silently bypass the write-ahead marker.
196
196
  const continuityPatches = [
197
- ['interface Binding {', 'interface Binding {\n ompInFlight: boolean; ompInvalidated: boolean; ompDropPromise?: Promise<void>; ompExpectedAssistantHasOutput: boolean;'],
197
+ ['interface Binding {', 'interface Binding {\n ompInFlight: boolean; ompInvalidated: boolean; ompDropPromise?: Promise<void>; ompExpectedAssistantHasOutput: boolean; ompReleaseLease?: () => Promise<void>;'],
198
198
  ['let completeTurn: (() => void) | undefined;', 'let ompDispatched = false;\n\t\tlet completeTurn: (() => void) | undefined;'],
199
199
  ['if (existing) return existing;', `if (existing) {
200
200
  const value = await existing;
@@ -213,6 +213,7 @@ const result = await build({
213
213
  }`],
214
214
  ['const createdBinding: Binding = {', `const createdBinding: Binding = {
215
215
  ompInFlight: false, ompInvalidated: false,
216
+ ompReleaseLease: releaseLease,
216
217
  ompExpectedAssistantHasOutput: restored && saved?.ompExpectedAssistantHasOutput === true,`],
217
218
  ['const response = await binding.connection.prompt(', `if (options.signal?.aborted) throw abortError();
218
219
  binding.ompInFlight = true;
@@ -235,6 +236,33 @@ const result = await build({
235
236
  if (contents.split(anchor).length !== 2) throw new Error(`Pinned continuity seam changed: ${anchor}`);
236
237
  contents = contents.replace(anchor, replacement);
237
238
  }
239
+ const leasePatches = [
240
+ ['const connection = this.createConnection({\n\t\t\tcwd,', 'let leaseLost = false;\n\t\tlet releaseLease: (() => Promise<void>) | undefined;\n\t\tconst connection = this.createConnection({\n\t\t\tcwd,'],
241
+ ['onPermission: (request) => this.requestPermission(binding, request),\n\t\t\t},\n\t\t});\n\t\ttry {\n\t\t\tconst initialize = await connection.initialize();', `onPermission: (request) => this.requestPermission(binding, request),
242
+ },
243
+ });
244
+ try {
245
+ if (key.startsWith('sid:') && typeof this.sessionStore?.acquireSessionLease === 'function') {
246
+ releaseLease = await this.sessionStore.acquireSessionLease(key.slice(4), () => { leaseLost = true; if (binding) binding.ompInvalidated = true; void connection.close().catch(() => {}); });
247
+ this.assertEpoch(epoch);
248
+ }
249
+ \t\t\tconst initialize = await connection.initialize();`],
250
+ ['void connection.process.exited.then(() => {\n\t\t\t\tcancelPermission(createdBinding);', `void connection.process.exited.then(() => {
251
+ const completion = createdBinding.turnCompletion;
252
+ const retiring = createdBinding.ompDropPromise;
253
+ void Promise.resolve(retiring ?? completion).then(() => createdBinding.ompReleaseLease?.()).catch(() => {});
254
+ \t\t\t\tcancelPermission(createdBinding);`],
255
+ ['binding = createdBinding;\n\t\t\tawait this.persistBinding(createdBinding);', `binding = createdBinding;
256
+ if (leaseLost) throw new AntigravityAcpError('protocol', 'ACP session ownership was lost during initialization');
257
+ \t\t\tawait this.persistBinding(createdBinding);`],
258
+ ['await Promise.allSettled([connection.close(), bridge?.close() ?? Promise.resolve()]);\n\t\t\tthrow error;', `await Promise.allSettled([connection.close(), bridge?.close() ?? Promise.resolve()]);
259
+ await releaseLease?.();
260
+ \t\t\tthrow error;`],
261
+ ];
262
+ for (const [anchor, replacement] of leasePatches) {
263
+ if (contents.split(anchor).length !== 2) throw new Error(`Pinned session lease seam changed: ${anchor}`);
264
+ contents = contents.replace(anchor, replacement);
265
+ }
238
266
  // Fallbacks after incomplete tools/permissions must not reload the same
239
267
  // backend. The two owning branches share this exact adjacent seam.
240
268
  const fallback = 'await this.dropBinding(key, binding);\n\t\t\t\tbinding = await this.getBinding(';
@@ -271,6 +299,7 @@ const result = await build({
271
299
  }
272
300
  } finally {
273
301
  await closing;
302
+ await binding.ompReleaseLease?.();
274
303
  if (current && (await current) === binding && this.bindings.get(key) === current) this.bindings.delete(key);
275
304
  }
276
305
  })();
@@ -283,7 +312,7 @@ const result = await build({
283
312
  const endClose = beforeQueue.lastIndexOf("\n\t}");
284
313
  // Await active turns' checkpoint writes, not queued callers which may
285
314
  // themselves be waiting for this permission-mode change to complete.
286
- contents = contents.slice(0, endClose) + "\n\t\tawait Promise.allSettled(closingTurns);\n\t\tawait this.sessionStore?.flush?.();" + contents.slice(endClose);
315
+ contents = contents.slice(0, endClose) + "\n\t\tawait Promise.allSettled(closingTurns);\n\t\tawait Promise.allSettled(pending.map(async value => (await value).ompReleaseLease?.()));\n\t\tawait this.sessionStore?.flush?.();" + contents.slice(endClose);
287
316
  const classStart = contents.indexOf("export class AntigravityRuntime {");
288
317
  const helpersStart = contents.indexOf("\nfunction messagesFingerprint(");
289
318
  if (classStart < 0 || helpersStart < classStart) throw new Error("Pinned runtime class seam changed");