omp-antigravity-acp-provider 0.1.26 → 0.1.28

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.
Files changed (53) hide show
  1. package/README.md +24 -9
  2. package/extension/auth-sync.ts +104 -30
  3. package/extension/catalog-store.ts +32 -19
  4. package/extension/commands.ts +10 -8
  5. package/extension/context-settings.ts +3 -2
  6. package/extension/context-transfer.ts +33 -14
  7. package/extension/index.ts +31 -16
  8. package/extension/omp-context.ts +19 -0
  9. package/extension/omp-session-lifecycle.ts +135 -0
  10. package/extension/runtime-pool.ts +26 -13
  11. package/extension/runtime.mjs +207 -61
  12. package/extension/session-cleanup.ts +98 -25
  13. package/extension/session-store.ts +15 -3
  14. package/extension/tier-connection.ts +9 -2
  15. package/package.json +4 -3
  16. package/extension/vendor/pi-antigravity-acp-provider/LICENSE +0 -21
  17. package/extension/vendor/pi-antigravity-acp-provider/README.upstream.md +0 -144
  18. package/extension/vendor/pi-antigravity-acp-provider/package.json +0 -86
  19. package/extension/vendor/pi-antigravity-acp-provider/runtime-manifest.json +0 -205
  20. package/extension/vendor/pi-antigravity-acp-provider/src/acp/antigravity.ts +0 -170
  21. package/extension/vendor/pi-antigravity-acp-provider/src/acp/bounded-stream.ts +0 -148
  22. package/extension/vendor/pi-antigravity-acp-provider/src/acp/connection.ts +0 -443
  23. package/extension/vendor/pi-antigravity-acp-provider/src/acp/credential-storage.ts +0 -113
  24. package/extension/vendor/pi-antigravity-acp-provider/src/acp/errors.ts +0 -42
  25. package/extension/vendor/pi-antigravity-acp-provider/src/acp/events.ts +0 -66
  26. package/extension/vendor/pi-antigravity-acp-provider/src/acp/headless-oauth.ts +0 -196
  27. package/extension/vendor/pi-antigravity-acp-provider/src/acp/index.ts +0 -8
  28. package/extension/vendor/pi-antigravity-acp-provider/src/acp/integrity.ts +0 -64
  29. package/extension/vendor/pi-antigravity-acp-provider/src/acp/process.ts +0 -256
  30. package/extension/vendor/pi-antigravity-acp-provider/src/acp/prompt-watchdog.ts +0 -80
  31. package/extension/vendor/pi-antigravity-acp-provider/src/acp/proxy.ts +0 -54
  32. package/extension/vendor/pi-antigravity-acp-provider/src/acp/runtime-manifest.ts +0 -183
  33. package/extension/vendor/pi-antigravity-acp-provider/src/acp/session-state.ts +0 -76
  34. package/extension/vendor/pi-antigravity-acp-provider/src/acp/session-store.ts +0 -88
  35. package/extension/vendor/pi-antigravity-acp-provider/src/acp/setup.ts +0 -793
  36. package/extension/vendor/pi-antigravity-acp-provider/src/acp/store-lock.ts +0 -24
  37. package/extension/vendor/pi-antigravity-acp-provider/src/acp/supervisor.mjs +0 -101
  38. package/extension/vendor/pi-antigravity-acp-provider/src/config.ts +0 -114
  39. package/extension/vendor/pi-antigravity-acp-provider/src/constants.ts +0 -10
  40. package/extension/vendor/pi-antigravity-acp-provider/src/index.ts +0 -8
  41. package/extension/vendor/pi-antigravity-acp-provider/src/mcp/bridge.ts +0 -217
  42. package/extension/vendor/pi-antigravity-acp-provider/src/mcp/schema.ts +0 -223
  43. package/extension/vendor/pi-antigravity-acp-provider/src/models.ts +0 -192
  44. package/extension/vendor/pi-antigravity-acp-provider/src/provider.ts +0 -149
  45. package/extension/vendor/pi-antigravity-acp-provider/src/runtime.ts +0 -1116
  46. package/extension/vendor/pi-antigravity-acp-provider/src/status.ts +0 -77
  47. package/extension/vendor/pi-antigravity-acp-provider/src/stream/context.ts +0 -249
  48. package/extension/vendor/pi-antigravity-acp-provider/src/stream/index.ts +0 -3
  49. package/extension/vendor/pi-antigravity-acp-provider/src/stream/json.ts +0 -17
  50. package/extension/vendor/pi-antigravity-acp-provider/src/stream/pi-events.ts +0 -141
  51. package/extension/vendor/pi-antigravity-acp-provider/src/stream/usage.ts +0 -37
  52. package/extension/vendor/pi-antigravity-acp-provider/src/wizard.ts +0 -83
  53. package/scripts/build.mjs +0 -436
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.
@@ -165,6 +165,7 @@ After upgrading from an older adapter, run `/antigravity-acp refresh` once to re
165
165
  | `/antigravity-acp cleanup` | Show cleanup mode/deadline and check eligible local sessions |
166
166
  | `/antigravity-acp cleanup off` | Disable automatic session-file deletion |
167
167
  | `/antigravity-acp cleanup conservative` | Delete confirmed replaced/disposable sessions only (default) |
168
+ | `/antigravity-acp cleanup balanced [DAYS]` | Keep recovery copies for 1 day, expire unmapped data after 7 days, and set soft 50-session/512-MiB defaults |
168
169
  | `/antigravity-acp cleanup timeout DAYS` | Also delete inactive unmapped owned sessions after DAYS (default 7) |
169
170
  | `/antigravity-acp cleanup budget MAX_SESSIONS MAX_MIB` | Set soft session-count/size budgets; `0` disables each limit |
170
171
  | `/antigravity-acp diagnostics [on\|off\|reset]` | Show bounded timing samples, enable/disable collection, or clear samples (default off) |
@@ -224,6 +225,8 @@ New user requests supersede an interrupted ACP turn, including pending tool call
224
225
 
225
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).
226
227
 
228
+ Routing uses the provider request's `sessionId`, independently of shared prompt-cache keys and the UI transcript ID. OMP's provider-state close/release hooks cover `/fresh`, reset and side-request lifetimes; old deferred requests cannot dispatch after closure, and replacement requests wait for teardown. Duplicate/ambiguous mappings are rebuilt, and a fresh Google login clears previous-account mappings. Concurrent identical input snapshots are rejected instead of dispatched twice; the same text in a distinct later user turn remains valid. Only tool names, descriptions and schemas enter ACP history fingerprints, excluding mutable OMP host objects. See the [source review and transition coverage](docs/session-transition-audit-2026-10-30.md). Run `npm run test:omp-sessions` for an isolated offline integration with the installed OMP CLI and a fake ACP transport; it creates no Google sessions and performs no inference.
229
+
227
230
  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).
228
231
 
229
232
  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.
@@ -266,18 +269,20 @@ Active sessions are reused. After five idle minutes, the adapter closes its ACP
266
269
 
267
270
  ### Local ACP session cleanup
268
271
 
269
- Session-file deletion is separate from the five-minute idle process shutdown. Configure one of three modes:
272
+ Session-file deletion is separate from the five-minute idle process shutdown. Configure one of four modes:
270
273
 
271
274
  | Mode | Behavior |
272
275
  | --- | --- |
273
276
  | `off` | Keep session files, including replaced sessions. Ownership/lease bookkeeping remains enabled so cleanup can be enabled later. |
274
- | `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 are also removed after their connection exits. Ordinary shutdown and idle eviction preserve resumable sessions. |
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. |
275
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. |
276
280
 
277
281
  ```text
278
282
  /antigravity-acp cleanup
279
283
  /antigravity-acp cleanup off
280
284
  /antigravity-acp cleanup conservative
285
+ /antigravity-acp cleanup balanced
281
286
  /antigravity-acp cleanup timeout 7
282
287
  /antigravity-acp cleanup budget 50 512
283
288
  ```
@@ -288,15 +293,25 @@ Settings persist in `~/.omp/agent/antigravity-acp-provider/cleanup.json`:
288
293
  { "mode": "conservative", "idleDays": 7, "maxSessions": 0, "maxBytes": 0, "orphanGraceDays": 1, "batchSize": 8 }
289
294
  ```
290
295
 
291
- The optional budgets default to disabled (`0`); the command accepts MiB and saves bytes. Size accounting uses logical file sizes rather than allocated APFS space. In `off` and `conservative`, exceeding a budget only produces a status warning. In `timeout`, budget eviction uses least-recent activity among unmapped, unleased owned sessions after `orphanGraceDays` (default 1 day, range 1 hour–3650 days). Mapped and active sessions can keep usage above the budget. The grace period applies to budget eviction; confirmed replacement and ordinary idle expiry have their own eligibility rules.
296
+ The optional budgets default to disabled (`0`); the command accepts MiB and saves bytes. `cleanup balanced` sets missing budgets to 50 sessions and 512 MiB, resets ordinary orphan retention to 7 days (or the supplied DAYS), and supplies a 1-day orphan grace and recovery window. Existing explicit budgets, including disabled (`0`) limits, are preserved. The default remains `conservative`; installing an update does not switch an existing policy.
297
+
298
+ For example, the balanced preset without prior overrides saves:
299
+
300
+ ```json
301
+ { "mode": "balanced", "idleDays": 7, "maxSessions": 50, "maxBytes": 536870912, "orphanGraceDays": 1, "recoveryDays": 1 }
302
+ ```
303
+
304
+ Size accounting uses logical file sizes rather than allocated APFS space. In `off` and `conservative`, exceeding a budget only produces a status warning. In `timeout` and `balanced`, budget eviction uses least-recent activity among unmapped, unleased owned sessions after `orphanGraceDays` (default 1 day, range 1 hour–3650 days). Mapped and active sessions can keep usage above the budget. The balanced recovery window cannot be bypassed by either quota pressure or ordinary idle expiry; `recoveryDays` accepts 1 hour–3650 days. Explicitly deleted OMP journals retain their separate deletion-confirmation rules.
292
305
 
293
306
  Commands take effect immediately; direct file edits are read on the next cleanup check. Checks run when the cleanup service starts, after replacement/release, on the inspection command, and every 15 minutes while the service is running. Replacement/release persists bookkeeping before scheduling file cleanup in the background. Each batch removes at most `batchSize` sessions (default 8, range 1–100); eligible overflow schedules another batch after one second. OMP must be running for timed checks; the deadline is not an exact scheduled deletion time. No additional model requests, tokenizer downloads or background worker processes are used.
294
307
 
295
- Only sessions created and registered by this adapter version onward are eligible. Pre-existing/unidentified ACP sessions are preserved. All cleanup modes protect IDs in saved `sessions.json` mappings. The registry is separated by the resolved ACP storage root, and tracks both OMP and ACP supervisor PIDs across participating processes. Resume/load acquires a lease before replay; the cross-process lease lock remains held during asynchronous deletion. Busy/corrupt registries, malformed mappings and unsafe paths defer deletion. Failed lifecycle updates remain in a bounded in-memory retry queue (1024 entries) until the next successful transaction; a process crash can lose queued intentions, so deletion is never guaranteed. The status shows mapped/unmapped/active counts, logical bytes, deferred work, failures and pending updates. Restart older OMP instances when upgrading: clients that do not implement these leases, or external clients manually opening the same session, are outside this coordination mechanism.
308
+ Only sessions created and registered by this adapter version onward are eligible. Pre-existing/unidentified ACP sessions are preserved. All cleanup modes protect IDs in saved `sessions.json` mappings. The registry is separated by the resolved ACP storage root, and tracks both OMP and ACP supervisor PIDs across participating processes. Resume/load acquires a lease before replay; the cross-process lease lock remains held during asynchronous deletion. Busy/corrupt registries, malformed mappings and unsafe paths defer deletion. Failed lifecycle updates remain in a bounded in-memory retry queue (1024 entries) until the next successful transaction; a process crash can lose queued intentions, so deletion is never guaranteed. The status shows mapped/unmapped/active counts, logical bytes, bytes reclaimed in the latest batch, copies retained for recovery, deferred work, failures and pending updates. Restart older OMP instances when upgrading: clients that do not implement these leases, or external clients manually opening the same session, are outside this coordination mechanism.
309
+
310
+ OMP explicitly releases routing IDs for final one-shot side requests. After runtime teardown, the adapter persists a disposable marker and conditionally removes only that request's matching owned mapping; newer, duplicated or shared mappings are preserved. A reused routing ID waits for this cleanup before dispatch. This also works after idle runtime eviction. If a process exits between marking and unmapping, later collection repairs the interruption; restoration refuses a finally released ACP ID. Generic provider close, process shutdown, switching sessions, and reusable side conversations do not mark their mappings disposable. Balanced mode retains the released ACP files as a temporary recovery copy; it does not add them to OMP history or expose a recovery UI.
296
311
 
297
312
  Cleanup targets only the registered UUID's `.db`, SQLite journal/WAL/SHM files, `.meta`, and `brain/<UUID>` directory under the ACP storage root (normally `~/.gemini/antigravity-acp/`; respects `GEMINI_HOME`). Symlinked targets are preserved. Credentials, global settings, shared artifacts, workspace files and OMP's own conversation history are untouched. Local deletion is permanent and does not request deletion of Google's server-side logs. The current official ACP runtime does not advertise session deletion, so this uses the inspected local layout rather than an unsupported RPC.
298
313
 
299
- Timeout cleanup sacrifices ACP-only reasoning/checkpoint state for eligible unmapped sessions. If that session is later requested through another history source, the adapter reconstructs it from OMP's retained history and can incur replay latency and a different token count. Cache expiry is not assumed or guaranteed. Ordinary mapped conversations remain resumable in every mode; budgets cannot bound the number of mapped OMP conversations you keep.
314
+ Timeout and balanced cleanup sacrifice ACP-only reasoning/checkpoint state for eligible unmapped sessions. If that session is later requested through another history source, the adapter reconstructs it from OMP's retained history and can incur replay latency and a different token count. Cache expiry is not assumed or guaranteed. Ordinary mapped conversations remain resumable in every mode; budgets cannot bound the number of mapped OMP conversations you keep.
300
315
 
301
316
  ### Deleting an OMP conversation
302
317
 
@@ -317,7 +332,7 @@ Optional environment settings, applied when OMP starts:
317
332
  | Setting | Default | Effect |
318
333
  | --- | --- | --- |
319
334
  | `OMP_ACP_HISTORY_BYTES` | context.json or 16 MiB | Optional byte-limit override, 64 KiB–128 MiB; independent of token window |
320
- | `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it, positive values must be at least `1000` |
335
+ | `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it, otherwise `1000`–`2147483647` (Node timer range) |
321
336
  | `OMP_ACP_MAX_IDLE_RUNTIMES` | `2` | Per-process idle runtime LRU limit; `0` disables the limit. Busy/leased runtimes remain protected |
322
337
  | `OMP_ACP_USAGE` | context.json or auto | `off` forces supplemental queries off, including when the saved option is auto |
323
338
 
@@ -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;
16
- try {
17
- execFileSync("/usr/bin/security", ["find-generic-password", "-s", "gemini", "-a", "antigravity-acp"], { stdio: "ignore", timeout: 3000 });
18
- 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;
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;
25
38
  try {
26
- execFileSync("/usr/bin/security", ["delete-generic-password", "-s", "gemini", "-a", "antigravity-acp"], { stdio: "ignore", timeout: 3000 });
39
+ await run(args);
27
40
  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,37 +192,73 @@ 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
179
204
  // process's old-account servers) so a new server cannot silently reuse the
180
205
  // saved login and keep the previous account.
206
+ noteLoginSucceeded(): void {
207
+ clearTimeout(this.followTimer);
208
+ this.followTimer = undefined;
209
+ clearTimeout(this.followRetry);
210
+ this.followRetry = undefined;
211
+ this.suppressFollow = false;
212
+ if (!this.apiKeyFallback) {
213
+ this.apiKeyFallback = true;
214
+ this.deps.onSyncProvider();
215
+ }
216
+ }
217
+
181
218
  async beginFreshGoogleLogin(): Promise<void> {
182
219
  if (this.deps.isPoolBusy()) {
183
220
  throw new Error("Wait for active Antigravity requests to finish before logging in.");
184
221
  }
222
+ clearTimeout(this.followTimer);
223
+ this.followTimer = undefined;
224
+ clearTimeout(this.followRetry);
225
+ this.followRetry = undefined;
185
226
  await this.deps.closeAllRuntimes();
227
+ // A different Google login must not restore the previous account's ACP
228
+ // mappings. OMP retains its transcript for a fresh backend reconstruction.
229
+ await this.deps.logoutAllRuntimes();
186
230
  clearAntigravityCredentials();
187
- keychain.remove();
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
+ }
188
236
  }
189
237
 
190
238
  async performCommandLogout(ctx: OmpCommandContext): Promise<{ keychainRemoved: boolean | undefined; ompMarker: "removed" | "absent" | "unavailable" }> {
191
239
  if (this.deps.isPoolBusy()) {
192
240
  throw new Error("Wait for active Antigravity requests to finish before logging out.");
193
241
  }
242
+ clearTimeout(this.followTimer);
243
+ this.followTimer = undefined;
244
+ clearTimeout(this.followRetry);
245
+ this.followRetry = undefined;
194
246
  await this.deps.logoutAllRuntimes();
195
247
  await this.deps.closeAllRuntimes();
196
248
  const keychainRemoved = await this.removeKeychainCredentialDurably();
197
249
  // Removing the marker ourselves must not trigger the follow-up logout.
198
250
  this.selfLogout = true;
199
251
  let ompMarker: "removed" | "absent" | "unavailable";
200
- 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; }
201
262
  if (ompMarker !== "unavailable") {
202
263
  // Drop the config apiKey with the marker even without the watcher.
203
264
  this.apiKeyFallback = false;
@@ -212,13 +273,16 @@ export class OmpAuthCoordinator {
212
273
  clearTimeout(this.followRetry);
213
274
  this.followRetry = setTimeout(() => {
214
275
  this.followRetry = undefined;
215
- if (this.ompMarkerStored(ctx) === false) void this.finishFollowedLogout(ctx);
276
+ if (this.ompMarkerStored(ctx) === false) this.runFollowedLogout(ctx);
216
277
  }, logoutFollow.retryMs);
217
278
  this.followRetry.unref?.();
218
279
  return;
219
280
  }
220
281
  await this.deps.logoutAllRuntimes();
221
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;
222
286
  const keychainRemoved = await this.removeKeychainCredentialDurably();
223
287
  // Keep the confirmation terse; /antigravity-acp account shows the details.
224
288
  try {
@@ -226,6 +290,16 @@ export class OmpAuthCoordinator {
226
290
  } catch { /* the host UI may already be gone */ }
227
291
  }
228
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
+
229
303
  watchOmpCredentials(ctx: OmpCommandContext | undefined): void {
230
304
  if (this.watchingCredentials || !ctx) return;
231
305
  const credentials = ctx.modelRegistry?.authStorage?.credentials;
@@ -273,7 +347,7 @@ export class OmpAuthCoordinator {
273
347
  this.deps.onSyncProvider();
274
348
  return;
275
349
  }
276
- void this.finishFollowedLogout(ctx);
350
+ this.runFollowedLogout(ctx);
277
351
  }, logoutFollow.delayMs);
278
352
  this.followTimer.unref?.();
279
353
  });
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import { writeJsonAtomic } from "./fs-atomic.ts";
3
- import { resolveContextOptions, type ContextOptions, type ContextSettings, type ResolvedContextOptions } from "./context-settings.ts";
3
+ import { resolveContextOptions, type ContextSettings, type ResolvedContextOptions } from "./context-settings.ts";
4
4
  import { EFFORTS, projectCatalog, readModels, type AdvertisedModel, type PublicCatalogModel } from "./model-catalog.ts";
5
5
  import { officialApiCost } from "./pricing.ts";
6
6
  import { advertisedRecord, choices, selector } from "./selectors.ts";
@@ -14,7 +14,8 @@ export interface ConfiguredCatalogModel extends PublicCatalogModel {
14
14
  export class CatalogStore {
15
15
  readonly upstreamModels = new Map<string, ConfiguredCatalogModel>();
16
16
  currentModels: ConfiguredCatalogModel[] = [];
17
- private dynamicCache?: { mtimeMs: number; size: number; settings: ContextSettings; models: ConfiguredCatalogModel[] };
17
+ private sourceModels: PublicCatalogModel[] = [];
18
+ private dynamicCache?: { stamp?: string; settings: string; models: ConfiguredCatalogModel[] };
18
19
  private discovery?: Promise<AdvertisedModel[]>;
19
20
  private refreshing?: Promise<ConfiguredCatalogModel[]>;
20
21
  private latestSettings?: ContextSettings;
@@ -27,8 +28,12 @@ export class CatalogStore {
27
28
  ) {}
28
29
 
29
30
  projectWithSettings(models: PublicCatalogModel[], settings: ContextSettings): ConfiguredCatalogModel[] {
30
- this.latestSettings = settings;
31
- this.upstreamModels.clear();
31
+ const projected = this.project(models, settings);
32
+ this.install(projected, models, settings);
33
+ return projected;
34
+ }
35
+
36
+ private project(models: PublicCatalogModel[], settings: ContextSettings): ConfiguredCatalogModel[] {
32
37
  return models.map(source => {
33
38
  const limits = resolveContextOptions(source, settings);
34
39
  const model: ConfiguredCatalogModel = {
@@ -42,11 +47,21 @@ export class CatalogStore {
42
47
  if (efforts.length && !model.thinking) {
43
48
  model.thinking = { mode: "effort", efforts, defaultLevel: efforts.includes("high") ? "high" : efforts[0]! };
44
49
  }
45
- this.upstreamModels.set(model.id, model);
46
50
  return model;
47
51
  });
48
52
  }
49
53
 
54
+ private install(models: ConfiguredCatalogModel[], sources: PublicCatalogModel[], settings: ContextSettings) {
55
+ // Publish only after every model validates. Preserve source limits so a
56
+ // removed override does not inherit the previous projected values.
57
+ this.sourceModels = sources;
58
+ this.latestSettings = settings;
59
+ this.currentModels = models;
60
+ this.dynamicCache = undefined;
61
+ this.upstreamModels.clear();
62
+ for (const model of models) this.upstreamModels.set(model.id, model);
63
+ }
64
+
50
65
  readCachedCatalog(): AdvertisedModel[] {
51
66
  try {
52
67
  const cache = JSON.parse(fs.readFileSync(this.cachePath, "utf8")) as { schemaVersion?: unknown; models?: unknown };
@@ -65,27 +80,24 @@ export class CatalogStore {
65
80
  // OMP's host may call fetchDynamicModels on every startup pass; stat-based
66
81
  // reuse avoids re-reading and re-projecting an unchanged cache file.
67
82
  getDynamicModels(settings: ContextSettings): ConfiguredCatalogModel[] {
83
+ let stamp: string | undefined;
68
84
  try {
69
85
  const stat = fs.statSync(this.cachePath);
70
- if (this.dynamicCache && this.currentModels.length > 0 &&
71
- this.dynamicCache.mtimeMs === stat.mtimeMs && this.dynamicCache.size === stat.size &&
72
- this.dynamicCache.settings === settings) {
73
- return this.dynamicCache.models;
74
- }
86
+ stamp = `${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`;
75
87
  } catch { /* Missing or unreadable cache: fall through to a fresh read. */ }
88
+ const settingsKey = JSON.stringify(settings);
89
+ if (this.dynamicCache && this.dynamicCache.stamp === stamp && this.dynamicCache.settings === settingsKey) {
90
+ return this.dynamicCache.models;
91
+ }
76
92
  const cached = this.readCachedCatalog();
77
93
  const base = cached.length ? projectCatalog(cached) : this.fallbackModels();
78
94
  const models = this.projectWithSettings(base, settings);
79
- try {
80
- const stat = fs.statSync(this.cachePath);
81
- this.dynamicCache = { mtimeMs: stat.mtimeMs, size: stat.size, settings, models };
82
- } catch { /* No cache file yet; nothing to key reuse on. */ }
95
+ this.dynamicCache = { stamp, settings: settingsKey, models };
83
96
  return models;
84
97
  }
85
98
 
86
99
  reconfigure(settings: ContextSettings): ConfiguredCatalogModel[] {
87
- this.currentModels = this.projectWithSettings(this.currentModels, settings);
88
- return this.currentModels;
100
+ return this.projectWithSettings(this.sourceModels, settings);
89
101
  }
90
102
 
91
103
  async discoverModels(): Promise<AdvertisedModel[]> {
@@ -131,14 +143,15 @@ export class CatalogStore {
131
143
  }
132
144
  private async refreshOnce(): Promise<ConfiguredCatalogModel[]> {
133
145
  const models = await this.discoverModels();
134
- this.upstreamModels.clear();
135
- const registered = this.projectWithSettings(projectCatalog(models), this.latestSettings ?? { defaults: {}, models: {} });
136
- this.currentModels = registered;
146
+ const sources = projectCatalog(models);
147
+ const settings = this.latestSettings ?? { defaults: {}, models: {} };
148
+ const registered = this.project(sources, settings);
137
149
  writeJsonAtomic(this.cachePath, {
138
150
  schemaVersion: 2,
139
151
  discoveredAt: new Date().toISOString(),
140
152
  models,
141
153
  });
154
+ this.install(registered, sources, settings);
142
155
  return registered;
143
156
  }
144
157
  }
@@ -105,8 +105,8 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
105
105
  deps.cleanup.budget(Number(parts[2]), Number(parts[3]) * 1024 * 1024);
106
106
  } else
107
107
  if (value) {
108
- if (!["off", "conservative", "timeout"].includes(value) || parts.length > 3 || (parts[2] !== undefined && value !== "timeout")) {
109
- throw new Error("Usage: /antigravity-acp cleanup [off|conservative|timeout [DAYS]]");
108
+ if (!["off", "conservative", "timeout", "balanced"].includes(value) || parts.length > 3 || (parts[2] !== undefined && !["timeout", "balanced"].includes(value))) {
109
+ throw new Error("Usage: /antigravity-acp cleanup [off|conservative|timeout|balanced [DAYS]]");
110
110
  }
111
111
  deps.cleanup.configure(value as CleanupMode, parts[2] === undefined ? undefined : Number(parts[2]));
112
112
  deps.cleanup.start();
@@ -150,7 +150,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
150
150
  }
151
151
 
152
152
  if (command === "usage" && value) {
153
- if (value !== "auto" && value !== "off") throw new Error("Usage: /antigravity-acp usage [auto|off]");
153
+ if (parts.length !== 2 || (value !== "auto" && value !== "off")) throw new Error("Usage: /antigravity-acp usage [auto|off]");
154
154
  const next = updateContextSettings(deps.getContextSettings(), "default", "usageMode", value);
155
155
  saveContextSettings(deps.contextPath, next);
156
156
  deps.setContextSettings(next);
@@ -160,7 +160,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
160
160
  }
161
161
 
162
162
  if (command === "debug") {
163
- if (value !== "on" && value !== "off") throw new Error("Usage: /antigravity-acp debug on|off");
163
+ if (parts.length !== 2 || (value !== "on" && value !== "off")) throw new Error("Usage: /antigravity-acp debug on|off");
164
164
  const enabled = value === "on";
165
165
  const next = { ...deps.getToolPolicy(), debugToolUpdates: enabled };
166
166
  saveToolPolicy(deps.toolPolicyPath, next);
@@ -171,10 +171,11 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
171
171
  }
172
172
 
173
173
  if (command === "native-tools") {
174
+ if (parts.length !== 2) throw new Error("Usage: /antigravity-acp native-tools prefer|disabled");
174
175
  const mode: NativeToolMode = parseNativeToolMode(value);
175
- await deps.closeAllRuntimes();
176
176
  const next = { ...deps.getToolPolicy(), nativeTools: mode };
177
177
  saveToolPolicy(deps.toolPolicyPath, next);
178
+ await deps.closeAllRuntimes();
178
179
  deps.setToolPolicy(next);
179
180
  ctx.ui.notify(`Native tools: ${mode}. ACP connections will be recreated on the next request with the new policy.`, "info");
180
181
  return;
@@ -204,6 +205,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
204
205
  } finally {
205
206
  lease.release();
206
207
  }
208
+ deps.auth.noteLoginSucceeded?.();
207
209
  const auth = inspectAntigravityAuth();
208
210
  const email = antigravityAccountEmail();
209
211
  ctx.ui.notify(`Antigravity Google login finished${email ? ` as ${email}` : ""} — fresh sign-in; ACP auth: ${auth.status}${auth.authType ? ` (${auth.authType})` : ""}.`, "info");
@@ -236,7 +238,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
236
238
  // fields, with OMP-specific lines in the same style.
237
239
  ctx.ui.notify([
238
240
  "Antigravity ACP account",
239
- `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")}`,
240
242
  `Authentication: ${auth.status}${auth.authType ? ` (${auth.authType})` : ""}`,
241
243
  `Credential storage (preflight): ${describeCredentialStorage()}`,
242
244
  `OMP marker record: ${marker}`,
@@ -276,9 +278,9 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
276
278
  throw new Error("Usage: /antigravity-acp permissions default|auto-edit|yolo");
277
279
  }
278
280
  const mode = value.replace("-", "_");
281
+ savePermissionMode(mode, deps.configPath);
279
282
  deps.setPermissionModeState(mode);
280
283
  await Promise.all(deps.getAllRuntimes().map(bundle => bundle.runtime.setPermissionMode(mode)));
281
- savePermissionMode(mode, deps.configPath);
282
284
  }
283
285
  const usageError = "Usage: /antigravity-acp [status|account|login|logout|tools|usage|context|cleanup|diagnostics|debug|native-tools|permissions|refresh]";
284
286
  if (command && command !== "status" && command !== "tools" && command !== "permissions") {
@@ -300,6 +302,6 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
300
302
  }
301
303
 
302
304
  const policy = deps.getToolPolicy();
303
- 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");
304
306
  };
305
307
  }
@@ -23,7 +23,7 @@ function validate(options: unknown, allowUsage: boolean): void {
23
23
  if (value !== "auto" && value !== "off") throw new Error("usageMode must be auto or off");
24
24
  continue;
25
25
  }
26
- const range = ranges[key as keyof ContextOptions];
26
+ const range = Object.hasOwn(ranges, key) ? ranges[key as keyof ContextOptions] : undefined;
27
27
  if (!range || !Number.isSafeInteger(value) || (value as number) < range[0] || (value as number) > range[1]) {
28
28
  throw new Error(`Invalid context setting ${key}${range ? `; expected ${range[0]}..${range[1]}` : ""}`);
29
29
  }
@@ -54,7 +54,8 @@ export function saveContextSettings(file: string, settings: ContextSettings) {
54
54
  export function updateContextSettings(settings: ContextSettings, target: string, key: string, value: number | string): ContextSettings {
55
55
  if (["__proto__", "constructor", "prototype"].includes(target)) throw new Error("Invalid model ID");
56
56
  const next = structuredClone(settings);
57
- const options: Record<string, unknown> = target === "default" ? next.defaults : (next.models[target] ??= {});
57
+ const options: Record<string, unknown> = target === "default" ? next.defaults
58
+ : Object.hasOwn(next.models, target) ? next.models[target]! : (next.models[target] = {});
58
59
  options[key] = value;
59
60
  validate(options, target === "default");
60
61
  return next;