omp-antigravity-acp-provider 0.1.27 → 0.1.29

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
@@ -18,7 +18,7 @@ This derivative adds OMP-specific provider registration, confirmed model/thinkin
18
18
  The repository vendors the upstream **0.1.15** source under `extension/vendor/pi-antigravity-acp-provider` (MIT, see `extension/vendor/pi-antigravity-acp-provider/LICENSE`). The standalone artifact bundles its runtime code, supervisor and signed runtime manifest; end users need no production npm dependencies. It does not contain a copy of upstream's Git history. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for the original copyright and license notice.
19
19
  ## Status
20
20
 
21
- Version 0.1.26 waits for ACP process exit during session lease handoff and isolates idle runtimes while keeping the 0.1.24 session-ownership and profile-isolation fixes. Restart all OMP processes after upgrading so they participate in session ownership.
21
+ Version 0.1.28 classifies macOS keychain failures explicitly, refuses a fresh Google login when the previous credential cannot be confirmed removed, and closes logout race windows so a quick re-login cannot lose its new keychain credential. It keeps the 0.1.26 session-lease, idle-runtime and 0.1.24 ownership fixes. Restart all OMP processes after upgrading so they participate in session ownership.
22
22
 
23
23
  Version 0.1.26 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.24 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
24
 
@@ -57,7 +57,7 @@ Or, inside OMP:
57
57
 
58
58
  Select **omp-antigravity-acp-provider** in the browser, install it, and restart OMP to load the provider.
59
59
 
60
- 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.26** 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.
60
+ 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.28** 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
61
 
62
62
  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.
63
63
 
@@ -81,7 +81,7 @@ omp plugin install npm:omp-antigravity-acp-provider
81
81
  To pin a specific release:
82
82
 
83
83
  ```sh
84
- omp plugin install npm:omp-antigravity-acp-provider@0.1.26
84
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.28
85
85
  ```
86
86
 
87
87
  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.
@@ -221,7 +221,7 @@ Session mappings use asynchronous file I/O and nonblocking cross-process lock re
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. 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.
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. When the server replies that `session/cancel` is not implemented (verified against `agy_acp_server` 1.4.3: `-32601`), the adapter instead holds the caller's abort and waits for the old turn to end naturally, keeping the transport open, freezing `agent_message_chunk`/thought/tool/plan updates so retained partial output stays consistent, and checkpointing the same warm session once the turn ends. This steering grace is activity-aware: every update from the draining turn — thinking chunks, output or tool activity — extends the wait, so long thinking or tool loops do not expire it; only a silent gap beyond `OMP_ACP_STEER_GRACE_MS` (default 60 seconds, `0` restores the legacy immediate rebuild) or the absolute `OMP_ACP_STEER_GRACE_MAX_MS` cap (default 5 minutes, `0` = uncapped) falls back to cold reconstruction. The vendored progress watchdog (10 minutes silent / 60 minutes busy) remains the outer safety net. 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
 
@@ -275,7 +275,7 @@ Session-file deletion is separate from the five-minute idle process shutdown. Co
275
275
  | --- | --- |
276
276
  | `off` | Keep session files, including replaced sessions. Ownership/lease bookkeeping remains enabled so cleanup can be enabled later. |
277
277
  | `conservative` (default) | Remove an old session after its OMP history is rebuilt (for example after `/compact`), a replacement successfully completes a turn, and all registered users of the old session have released it. Disposable model-discovery sessions and explicitly released one-shot side requests are also removed after their connection exits. Ordinary shutdown and idle eviction preserve resumable sessions. |
278
- | `balanced` | Keep unmapped replacement/one-shot copies for at least `recoveryDays` (default 1 day), including under quota pressure. Expire other unmapped owned data after `idleDays` (default 7 days) measured from the later of last use and first observation without a mapping. Above a soft budget, evict eligible unmapped data in activity order after the orphan grace (default 1 day). Saved OMP mappings, active sessions and OMP journals remain protected. |
278
+ | `balanced` | Keep unmapped replacement/one-shot copies for at least `recoveryDays` (default 1 day), including under quota pressure. Expire other unmapped owned data, and mapped conversations whose last activity exceeds `idleDays` (default 7 days), measured from the later of last use and first observation without a mapping. A reclaimed mapping is removed before its files, and the next turn rebuilds the conversation from OMP history. Above a soft budget, evict eligible unmapped data in activity order after the orphan grace (default 1 day). Active sessions, live leases, ambiguous mappings and OMP journals remain protected. |
279
279
  | `timeout` | Conservative cleanup plus removal of unmapped owned sessions whose last activity exceeds `idleDays`, or eligible unmapped sessions above a configured soft budget after the orphan grace period. Default 7 days; accepts fractional days (for example `0.5` for 12 hours), with a minimum of one hour and a maximum of 3650 days. Saved OMP mappings and live leases always override deletion. |
280
280
 
281
281
  ```text
@@ -335,6 +335,8 @@ Optional environment settings, applied when OMP starts:
335
335
  | `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it, otherwise `1000`–`2147483647` (Node timer range) |
336
336
  | `OMP_ACP_MAX_IDLE_RUNTIMES` | `2` | Per-process idle runtime LRU limit; `0` disables the limit. Busy/leased runtimes remain protected |
337
337
  | `OMP_ACP_USAGE` | context.json or auto | `off` forces supplemental queries off, including when the saved option is auto |
338
+ | `OMP_ACP_STEER_GRACE_MS` | `60000` | Steering grace when `session/cancel` is unimplemented: max silent gap while waiting for the old turn, `0`–`600000`; `0` rebuilds immediately |
339
+ | `OMP_ACP_STEER_GRACE_MAX_MS` | `300000` | Absolute cap on one steering wait however active the turn; `0` = uncapped, otherwise `100`–`3600000` |
338
340
 
339
341
  When automatic usage is enabled and `/usage` is advertised by the official server, the adapter queries it after each completed ACP prompt and computes a difference from the previous cumulative snapshot. A restored session first establishes a baseline so its old tokens are not charged again. These are main-agent totals and can include multiple internal model calls. Thinking tokens count toward estimated output cost. Queries are bounded by a five-second deadline; unavailable/malformed usage or a counter reset does not turn a successful model answer into a billing claim. Native ACP response usage takes priority when supplied. Query failures can cancel/retire the connection; subsequent work can restore the server session.
340
342
 
@@ -1,5 +1,6 @@
1
- import { execFileSync } from "node:child_process";
1
+ import { execFile } from "node:child_process";
2
2
  import { setTimeout as delay } from "node:timers/promises";
3
+ import { promisify } from "node:util";
3
4
  import fs from "node:fs";
4
5
  import path from "node:path";
5
6
  import { clearAntigravityCredentials, hasAntigravityAuth, resolveAntigravityAcpDirectory } from "./runtime.mjs";
@@ -7,30 +8,54 @@ import type { TierConnection } from "./tier-connection.ts";
7
8
 
8
9
  export const MARKER = "pi-antigravity-acp:managed-by-antigravity";
9
10
 
11
+ const execFileAsync = promisify(execFile);
12
+
13
+ // The real /usr/bin/security subprocess boundary, with its own binary
14
+ // parameter so tests can drive a stub executable through the same code path.
15
+ // Captured stderr is matched in memory only; it is never logged or persisted.
16
+ export function runSecurity(args: string[], bin = "/usr/bin/security"): Promise<void> {
17
+ return execFileAsync(bin, args, { stdio: ["ignore", "ignore", "pipe"], timeout: 3000 }).then(() => undefined);
18
+ }
19
+
20
+ // errSecItemNotFound reaches the caller as exit code 44 (OSStatus -25300
21
+ // truncated to 8 bits). The stderr wording separates it from any other
22
+ // OSStatus whose truncated code also lands on 44.
23
+ function isConfirmedMissing(error: unknown): boolean {
24
+ if (!error || typeof error !== "object") return false;
25
+ const detail = error as { killed?: unknown; signal?: unknown; code?: unknown; stderr?: unknown };
26
+ return detail.killed !== true && detail.signal == null && detail.code === 44
27
+ && typeof detail.stderr === "string" && /could not be found/.test(detail.stderr);
28
+ }
29
+
10
30
  // macOS keychain operations behind one mutable object so offline command
11
31
  // tests can substitute them without touching the user's real keychain.
12
- export const keychain = {
13
- // Check existence only. Never retrieve credentials from the keychain.
14
- present(): boolean | undefined {
15
- if (process.platform !== "darwin") return undefined;
32
+ // present/remove resolve to true (present / removed), false (confirmed
33
+ // absent), or undefined (not macOS); any other subprocess failure rejects
34
+ // with a fixed credential-free message.
35
+ export function createKeychain(run: (args: string[]) => Promise<void>, platform: NodeJS.Platform = process.platform) {
36
+ const check = async (args: string[], failure: string): Promise<boolean | undefined> => {
37
+ if (platform !== "darwin") return undefined;
16
38
  try {
17
- execFileSync("/usr/bin/security", ["find-generic-password", "-s", "gemini", "-a", "antigravity-acp"], { stdio: "ignore", timeout: 3000 });
39
+ await run(args);
18
40
  return true;
19
- } catch { return false; }
20
- },
21
- // Local logout for macOS keychain storage. The Antigravity server owns this
22
- // item; removing it is required for a complete logout when no token file exists.
23
- remove(): boolean | undefined {
24
- if (process.platform !== "darwin") return undefined;
25
- try {
26
- execFileSync("/usr/bin/security", ["delete-generic-password", "-s", "gemini", "-a", "antigravity-acp"], { stdio: "ignore", timeout: 3000 });
27
- return true;
28
- } catch { return false; }
29
- },
30
- // Never read the stored secret: the item's ACL does not authorize the
31
- // security CLI, so every `find-generic-password -w` would pop the macOS
32
- // keychain password dialog. Only attribute-only lookups are prompt-free.
33
- };
41
+ } catch (error) {
42
+ if (isConfirmedMissing(error)) return false;
43
+ throw new Error(failure);
44
+ }
45
+ };
46
+ return {
47
+ // Check existence only: the item's ACL does not authorize the security
48
+ // CLI, so a `find-generic-password -w` would pop the macOS keychain
49
+ // password dialog. Attribute-only lookups stay prompt-free.
50
+ present: (): Promise<boolean | undefined> => check(["find-generic-password", "-s", "gemini", "-a", "antigravity-acp"], "Unable to inspect the Antigravity keychain entry"),
51
+ // Local logout for macOS keychain storage. The Antigravity server owns
52
+ // this item; removing it is required for a complete logout when no token
53
+ // file exists.
54
+ remove: (): Promise<boolean | undefined> => check(["delete-generic-password", "-s", "gemini", "-a", "antigravity-acp"], "Unable to remove the Antigravity keychain entry"),
55
+ };
56
+ }
57
+
58
+ export const keychain = createKeychain(runSecurity);
34
59
 
35
60
  function emailFromTokenJson(raw: string): string | undefined {
36
61
  try {
@@ -68,8 +93,8 @@ export function formatLogoutSummary(options: { keychainRemoved: boolean | undefi
68
93
  (options.keychainRemoved === false ? " The macOS keychain entry was not present or not removable." : "");
69
94
  }
70
95
 
71
- export function authReady(): boolean {
72
- return hasAntigravityAuth() || keychain.present() === true;
96
+ export async function authReady(): Promise<boolean> {
97
+ return hasAntigravityAuth() || (await keychain.present()) === true;
73
98
  }
74
99
 
75
100
  export interface OmpCommandContext {
@@ -167,12 +192,12 @@ export class OmpAuthCoordinator {
167
192
  await Promise.race([Promise.allSettled(pending), delay(10_000)]);
168
193
  }
169
194
  for (let attempt = 0; attempt < 3; attempt++) {
170
- if (keychain.present() === false) return true;
171
- const removed = keychain.remove();
195
+ if ((await keychain.present()) === false) return true;
196
+ const removed = await keychain.remove();
172
197
  if (removed !== true) return removed;
173
198
  await delay(400);
174
199
  }
175
- return keychain.present() === false;
200
+ return (await keychain.present()) === false;
176
201
  }
177
202
 
178
203
  // /login must mean a fresh Google sign-in: drop stored credentials (and this
@@ -203,7 +228,11 @@ export class OmpAuthCoordinator {
203
228
  // mappings. OMP retains its transcript for a fresh backend reconstruction.
204
229
  await this.deps.logoutAllRuntimes();
205
230
  clearAntigravityCredentials();
206
- await this.removeKeychainCredentialDurably();
231
+ // The old keychain entry must be gone before a new sign-in can start; an
232
+ // unconfirmed removal refuses the login instead of silently reusing it.
233
+ if (await this.removeKeychainCredentialDurably() === false) {
234
+ throw new Error("Unable to confirm removal of the Antigravity keychain entry");
235
+ }
207
236
  }
208
237
 
209
238
  async performCommandLogout(ctx: OmpCommandContext): Promise<{ keychainRemoved: boolean | undefined; ompMarker: "removed" | "absent" | "unavailable" }> {
@@ -220,7 +249,16 @@ export class OmpAuthCoordinator {
220
249
  // Removing the marker ourselves must not trigger the follow-up logout.
221
250
  this.selfLogout = true;
222
251
  let ompMarker: "removed" | "absent" | "unavailable";
223
- try { ompMarker = await removeOmpCredentialRecord(ctx); } finally { this.selfLogout = false; }
252
+ try {
253
+ ompMarker = await removeOmpCredentialRecord(ctx);
254
+ if (ompMarker !== "unavailable") {
255
+ // A generation event firing after the selfLogout window would compare
256
+ // against a stale markerPresent and schedule a redundant follow-up.
257
+ this.markerPresent = this.ompMarkerStored(ctx);
258
+ clearTimeout(this.followTimer);
259
+ this.followTimer = undefined;
260
+ }
261
+ } finally { this.selfLogout = false; }
224
262
  if (ompMarker !== "unavailable") {
225
263
  // Drop the config apiKey with the marker even without the watcher.
226
264
  this.apiKeyFallback = false;
@@ -235,13 +273,16 @@ export class OmpAuthCoordinator {
235
273
  clearTimeout(this.followRetry);
236
274
  this.followRetry = setTimeout(() => {
237
275
  this.followRetry = undefined;
238
- if (this.ompMarkerStored(ctx) === false) void this.finishFollowedLogout(ctx);
276
+ if (this.ompMarkerStored(ctx) === false) this.runFollowedLogout(ctx);
239
277
  }, logoutFollow.retryMs);
240
278
  this.followRetry.unref?.();
241
279
  return;
242
280
  }
243
281
  await this.deps.logoutAllRuntimes();
244
282
  await this.deps.closeAllRuntimes();
283
+ // A quick re-login can restore the marker while the steps above await;
284
+ // a restored or unknown marker keeps the new keychain entry untouched.
285
+ if (this.ompMarkerStored(ctx) !== false) return;
245
286
  const keychainRemoved = await this.removeKeychainCredentialDurably();
246
287
  // Keep the confirmation terse; /antigravity-acp account shows the details.
247
288
  try {
@@ -249,6 +290,16 @@ export class OmpAuthCoordinator {
249
290
  } catch { /* the host UI may already be gone */ }
250
291
  }
251
292
 
293
+ // The follow-up runs detached from timer callbacks; a failure must not
294
+ // become an unhandled rejection, and the notice stays credential-free.
295
+ private runFollowedLogout(ctx: OmpCommandContext): void {
296
+ void this.finishFollowedLogout(ctx).catch(() => {
297
+ try {
298
+ ctx?.ui?.notify?.("Antigravity ACP: the logout OMP started could not be finished. Run /antigravity-acp logout to retry.", "error");
299
+ } catch { /* the host UI may already be gone */ }
300
+ });
301
+ }
302
+
252
303
  watchOmpCredentials(ctx: OmpCommandContext | undefined): void {
253
304
  if (this.watchingCredentials || !ctx) return;
254
305
  const credentials = ctx.modelRegistry?.authStorage?.credentials;
@@ -296,7 +347,7 @@ export class OmpAuthCoordinator {
296
347
  this.deps.onSyncProvider();
297
348
  return;
298
349
  }
299
- void this.finishFollowedLogout(ctx);
350
+ this.runFollowedLogout(ctx);
300
351
  }, logoutFollow.delayMs);
301
352
  this.followTimer.unref?.();
302
353
  });
@@ -238,7 +238,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
238
238
  // fields, with OMP-specific lines in the same style.
239
239
  ctx.ui.notify([
240
240
  "Antigravity ACP account",
241
- `Google account: ${antigravityAccountEmail() ?? (keychain.present() === true ? "signed in (token in macOS keychain; email not read)" : "not signed in")}`,
241
+ `Google account: ${antigravityAccountEmail() ?? ((await keychain.present()) === true ? "signed in (token in macOS keychain; email not read)" : "not signed in")}`,
242
242
  `Authentication: ${auth.status}${auth.authType ? ` (${auth.authType})` : ""}`,
243
243
  `Credential storage (preflight): ${describeCredentialStorage()}`,
244
244
  `OMP marker record: ${marker}`,
@@ -302,6 +302,6 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
302
302
  }
303
303
 
304
304
  const policy = deps.getToolPolicy();
305
- ctx.ui.notify(`Antigravity ACP (OMP adapter)\nAuth storage: ${authReady() ? "configured (ACP-owned token file or macOS keychain)" : inspectAntigravityAuth().status}\nPermissions: ${snapshot.permissionMode}\nNative tools: ${policy.nativeTools}\nDebug tool updates: ${policy.debugToolUpdates ? "on" : "off"}\nTool routing: ${JSON.stringify([...deps.connections].map(connection => connection.toolRouting).filter(Boolean))}\nActive sessions: ${snapshot.bindings}\nConfirmed thinking: ${JSON.stringify([...deps.connections].map(connection => connection.confirmedThinking).filter(Boolean))}\nUsage: ${JSON.stringify(snapshot.metrics)}\n${JSON.stringify(snapshot.processes)}`, "info");
305
+ ctx.ui.notify(`Antigravity ACP (OMP adapter)\nAuth storage: ${(await authReady()) ? "configured (ACP-owned token file or macOS keychain)" : inspectAntigravityAuth().status}\nPermissions: ${snapshot.permissionMode}\nNative tools: ${policy.nativeTools}\nDebug tool updates: ${policy.debugToolUpdates ? "on" : "off"}\nTool routing: ${JSON.stringify([...deps.connections].map(connection => connection.toolRouting).filter(Boolean))}\nActive sessions: ${snapshot.bindings}\nConfirmed thinking: ${JSON.stringify([...deps.connections].map(connection => connection.confirmedThinking).filter(Boolean))}\nUsage: ${JSON.stringify(snapshot.metrics)}\n${JSON.stringify(snapshot.processes)}`, "info");
306
306
  };
307
307
  }
@@ -0,0 +1,10 @@
1
+ // Single source for the "<base>-<effort>" advertised ID suffix. Both the
2
+ // catalog projection and API cost lookup must agree, or pricing silently
3
+ // misses the variants the catalog advertises.
4
+ export const EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
5
+ export const LEGACY_EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORTS.join("|")})$`);
6
+
7
+ export function splitLegacyEffort(modelId: string): { base: string; effort: string } | undefined {
8
+ const match = modelId.match(LEGACY_EFFORT_SUFFIX);
9
+ return match ? { base: match[1]!, effort: match[2]! } : undefined;
10
+ }
@@ -1,5 +1,6 @@
1
1
  // Public OMP models are derived only from server-advertised IDs and choices.
2
- export const EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
2
+ import { EFFORTS, splitLegacyEffort } from "./efforts.ts";
3
+ export { EFFORTS, splitLegacyEffort };
3
4
  export interface AdvertisedModel {
4
5
  modelId: string;
5
6
  name: string;
@@ -22,12 +23,7 @@ export interface PublicCatalogModel {
22
23
  thinking?: { mode: "effort"; efforts: string[]; defaultLevel?: string };
23
24
  }
24
25
  const ROUTE_PREFIX = "__omp_acp_thought__:";
25
- // Single source for the legacy "<base>-<effort>" advertised ID suffix.
26
- const LEGACY_EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORTS.join("|")})$`);
27
- export function splitLegacyEffort(modelId: string): { base: string; effort: string } | undefined {
28
- const match = modelId.match(LEGACY_EFFORT_SUFFIX);
29
- return match ? { base: match[1]!, effort: match[2]! } : undefined;
30
- }
26
+ // The legacy "<base>-<effort>" suffix lives in efforts.ts so pricing agrees.
31
27
  export function validId(value: unknown): value is string {
32
28
  return typeof value === "string" && value.length > 0 && value.length <= 256 &&
33
29
  value === value.trim() && !/[\u0000-\u001f\u007f]/u.test(value);
@@ -115,8 +115,12 @@ export class OmpSessionLifecycle {
115
115
  closeSession(id: RoutingId, released = false): Promise<void> {
116
116
  for (const ticket of [...this.tickets.get(id) ?? []]) { ticket.closed = true; ticket.scope.retainedIds.delete(id); this.forget(ticket); }
117
117
  const previous = this.closing.get(id), closed = this.closeRuntime(id), teardown = this.closing.get(id);
118
- const pending = Promise.all([previous, closed, teardown]).then(async () => {
118
+ const pending = Promise.allSettled([previous, closed, teardown]).then(async results => {
119
+ // Teardown failures must not skip unbinding: a leaked release keeps the
120
+ // one-shot mapping alive and the cleanup registry out of sync.
119
121
  if (released) await this.releaseRuntime(id);
122
+ const failure = results.find((result): result is PromiseRejectedResult => result.status === "rejected");
123
+ if (failure) throw failure.reason;
120
124
  });
121
125
  // Reusing an ID must also wait for removal of its prior one-shot mapping.
122
126
  this.closing.set(id, pending);
@@ -36,11 +36,18 @@ export async function sourceId(file: string): Promise<string> {
36
36
  } finally { await handle.close(); }
37
37
  }
38
38
 
39
+ export interface OmpSourceScan {
40
+ sources: Map<string, string>;
41
+ // False when some journal header could not be read. Absence then proves
42
+ // nothing: the missing session may live in a file this scan could not parse.
43
+ complete: boolean;
44
+ }
45
+
39
46
  // Missing files may have moved between workspace buckets. Search only the
40
47
  // known managed root, with bounded work and no symlinks; any ambiguity preserves
41
48
  // the ACP session. Called only after a tracked file disappears.
42
- export async function findSources(root: string): Promise<Map<string, string>> {
43
- let entries = 0;
49
+ export async function findSources(root: string): Promise<OmpSourceScan> {
50
+ let entries = 0, complete = true;
44
51
  const sources = new Map<string, string>();
45
52
  async function visit(dir: string, depth: number): Promise<void> {
46
53
  if (depth > 4) throw new Error("OMP source scan depth exceeded");
@@ -52,9 +59,15 @@ export async function findSources(root: string): Promise<Map<string, string>> {
52
59
  // Only journal buckets, not the adjacent per-session artifact trees.
53
60
  if (/^\d{4}-\d\d-\d\d.*_[\da-f-]+$/i.test(item.name)) continue;
54
61
  await visit(file, depth + 1);
55
- } else if (item.isFile() && item.name.endsWith(".jsonl")) sources.set(await sourceId(file), file);
62
+ } else if (item.isFile() && item.name.endsWith(".jsonl")) {
63
+ // A crashed writer can leave an empty or truncated journal. That file
64
+ // proves nothing about its own session, but it must not blind the scan
65
+ // for every other one, so it only marks the scan incomplete.
66
+ try { sources.set(await sourceId(file), file); }
67
+ catch { complete = false; }
68
+ }
56
69
  }
57
70
  }
58
71
  await visit(root, 0);
59
- return sources;
72
+ return { sources, complete };
60
73
  }
@@ -1,8 +1,10 @@
1
+ import { splitLegacyEffort } from "./efforts.ts";
2
+
1
3
  // USD per 1M tokens, Gemini Developer API Standard tier.
2
4
  // Source: https://ai.google.dev/gemini-api/docs/pricing (checked 2026-10-19).
3
5
  // These are API-equivalent estimates, not Antigravity subscription charges.
4
6
  export function officialApiCost(modelId: string, at = Date.now()) {
5
- const id = modelId.replace(/-(low|medium|high)$/, "");
7
+ const id = splitLegacyEffort(modelId)?.base ?? modelId;
6
8
  if (id === "gemini-4-argon") {
7
9
  // Use the undiscounted list price, ignoring introductory rates.
8
10
  return { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 0 };