omp-antigravity-acp-provider 0.1.25 → 0.1.27

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 +25 -10
  2. package/extension/auth-sync.ts +24 -1
  3. package/extension/catalog-store.ts +32 -19
  4. package/extension/commands.ts +27 -19
  5. package/extension/context-settings.ts +3 -2
  6. package/extension/context-transfer.ts +33 -14
  7. package/extension/index.ts +52 -31
  8. package/extension/omp-context.ts +19 -0
  9. package/extension/omp-session-lifecycle.ts +135 -0
  10. package/extension/runtime-pool.ts +33 -13
  11. package/extension/runtime.mjs +193 -56
  12. package/extension/session-cleanup.ts +75 -21
  13. package/extension/session-store.ts +15 -3
  14. package/extension/tier-connection.ts +8 -1
  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 -423
package/README.md CHANGED
@@ -18,9 +18,9 @@ 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.25 vendors `pi-antigravity-acp-provider 0.1.15` source for direct local modification 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.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.
22
22
 
23
- Version 0.1.25 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.
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
 
25
25
  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.
26
26
 
@@ -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.25** 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.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.
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.25
84
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.26
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
 
@@ -178,19 +178,42 @@ export class OmpAuthCoordinator {
178
178
  // /login must mean a fresh Google sign-in: drop stored credentials (and this
179
179
  // process's old-account servers) so a new server cannot silently reuse the
180
180
  // saved login and keep the previous account.
181
+ noteLoginSucceeded(): void {
182
+ clearTimeout(this.followTimer);
183
+ this.followTimer = undefined;
184
+ clearTimeout(this.followRetry);
185
+ this.followRetry = undefined;
186
+ this.suppressFollow = false;
187
+ if (!this.apiKeyFallback) {
188
+ this.apiKeyFallback = true;
189
+ this.deps.onSyncProvider();
190
+ }
191
+ }
192
+
181
193
  async beginFreshGoogleLogin(): Promise<void> {
182
194
  if (this.deps.isPoolBusy()) {
183
195
  throw new Error("Wait for active Antigravity requests to finish before logging in.");
184
196
  }
197
+ clearTimeout(this.followTimer);
198
+ this.followTimer = undefined;
199
+ clearTimeout(this.followRetry);
200
+ this.followRetry = undefined;
185
201
  await this.deps.closeAllRuntimes();
202
+ // A different Google login must not restore the previous account's ACP
203
+ // mappings. OMP retains its transcript for a fresh backend reconstruction.
204
+ await this.deps.logoutAllRuntimes();
186
205
  clearAntigravityCredentials();
187
- keychain.remove();
206
+ await this.removeKeychainCredentialDurably();
188
207
  }
189
208
 
190
209
  async performCommandLogout(ctx: OmpCommandContext): Promise<{ keychainRemoved: boolean | undefined; ompMarker: "removed" | "absent" | "unavailable" }> {
191
210
  if (this.deps.isPoolBusy()) {
192
211
  throw new Error("Wait for active Antigravity requests to finish before logging out.");
193
212
  }
213
+ clearTimeout(this.followTimer);
214
+ this.followTimer = undefined;
215
+ clearTimeout(this.followRetry);
216
+ this.followRetry = undefined;
194
217
  await this.deps.logoutAllRuntimes();
195
218
  await this.deps.closeAllRuntimes();
196
219
  const keychainRemoved = await this.removeKeychainCredentialDurably();
@@ -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
  }
@@ -75,6 +75,7 @@ export interface CommandControllerDeps {
75
75
  setPermissionModeState: (mode: string) => void;
76
76
  getLastToolAudit: () => ToolAuditSummary | undefined;
77
77
  getRuntimeForSession: (sessionId?: string) => RuntimeBundleView;
78
+ acquireRuntimeForSession?: (sessionId?: string) => { value: RuntimeBundleView; release: () => void };
78
79
  peekRuntimeForSession: (sessionId?: string) => RuntimeBundleView | undefined;
79
80
  getSavedSessionCount: () => number;
80
81
  getPermissionMode: () => string;
@@ -104,8 +105,8 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
104
105
  deps.cleanup.budget(Number(parts[2]), Number(parts[3]) * 1024 * 1024);
105
106
  } else
106
107
  if (value) {
107
- if (!["off", "conservative", "timeout"].includes(value) || parts.length > 3 || (parts[2] !== undefined && value !== "timeout")) {
108
- 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]]");
109
110
  }
110
111
  deps.cleanup.configure(value as CleanupMode, parts[2] === undefined ? undefined : Number(parts[2]));
111
112
  deps.cleanup.start();
@@ -149,7 +150,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
149
150
  }
150
151
 
151
152
  if (command === "usage" && value) {
152
- 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]");
153
154
  const next = updateContextSettings(deps.getContextSettings(), "default", "usageMode", value);
154
155
  saveContextSettings(deps.contextPath, next);
155
156
  deps.setContextSettings(next);
@@ -159,7 +160,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
159
160
  }
160
161
 
161
162
  if (command === "debug") {
162
- 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");
163
164
  const enabled = value === "on";
164
165
  const next = { ...deps.getToolPolicy(), debugToolUpdates: enabled };
165
166
  saveToolPolicy(deps.toolPolicyPath, next);
@@ -170,10 +171,11 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
170
171
  }
171
172
 
172
173
  if (command === "native-tools") {
174
+ if (parts.length !== 2) throw new Error("Usage: /antigravity-acp native-tools prefer|disabled");
173
175
  const mode: NativeToolMode = parseNativeToolMode(value);
174
- await deps.closeAllRuntimes();
175
176
  const next = { ...deps.getToolPolicy(), nativeTools: mode };
176
177
  saveToolPolicy(deps.toolPolicyPath, next);
178
+ await deps.closeAllRuntimes();
177
179
  deps.setToolPolicy(next);
178
180
  ctx.ui.notify(`Native tools: ${mode}. ACP connections will be recreated on the next request with the new policy.`, "info");
179
181
  return;
@@ -185,19 +187,25 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
185
187
  await deps.auth.beginFreshGoogleLogin();
186
188
  // Direct Antigravity Google login through the command UI. OMP's /login
187
189
  // runs the same flow and additionally stores the provider marker.
188
- await deps.getRuntimeForSession().provider.auth.oauth.login({
189
- signal: undefined,
190
- notify(event) {
191
- const link = event.links?.[0];
192
- if (link) ctx.ui.notify(`${event.message ?? "Open this URL to authorize:"}\n${link.url}`, "info");
193
- else if (event.message) ctx.ui.notify(event.message, "info");
194
- },
195
- prompt: async (request) => {
196
- const answer = await ctx.ui.input?.(request.message, request.placeholder);
197
- if (!answer?.trim()) throw new Error("Antigravity OAuth login cancelled");
198
- return answer;
199
- },
200
- });
190
+ const lease = deps.acquireRuntimeForSession ? deps.acquireRuntimeForSession() : { value: deps.getRuntimeForSession(), release: () => {} };
191
+ try {
192
+ await lease.value.provider.auth.oauth.login({
193
+ signal: undefined,
194
+ notify(event) {
195
+ const link = event.links?.[0];
196
+ if (link) ctx.ui.notify(`${event.message ?? "Open this URL to authorize:"}\n${link.url}`, "info");
197
+ else if (event.message) ctx.ui.notify(event.message, "info");
198
+ },
199
+ prompt: async (request) => {
200
+ const answer = await ctx.ui.input?.(request.message, request.placeholder);
201
+ if (!answer?.trim()) throw new Error("Antigravity OAuth login cancelled");
202
+ return answer;
203
+ },
204
+ });
205
+ } finally {
206
+ lease.release();
207
+ }
208
+ deps.auth.noteLoginSucceeded?.();
201
209
  const auth = inspectAntigravityAuth();
202
210
  const email = antigravityAccountEmail();
203
211
  ctx.ui.notify(`Antigravity Google login finished${email ? ` as ${email}` : ""} — fresh sign-in; ACP auth: ${auth.status}${auth.authType ? ` (${auth.authType})` : ""}.`, "info");
@@ -270,9 +278,9 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
270
278
  throw new Error("Usage: /antigravity-acp permissions default|auto-edit|yolo");
271
279
  }
272
280
  const mode = value.replace("-", "_");
281
+ savePermissionMode(mode, deps.configPath);
273
282
  deps.setPermissionModeState(mode);
274
283
  await Promise.all(deps.getAllRuntimes().map(bundle => bundle.runtime.setPermissionMode(mode)));
275
- savePermissionMode(mode, deps.configPath);
276
284
  }
277
285
  const usageError = "Usage: /antigravity-acp [status|account|login|logout|tools|usage|context|cleanup|diagnostics|debug|native-tools|permissions|refresh]";
278
286
  if (command && command !== "status" && command !== "tools" && command !== "permissions") {
@@ -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;
@@ -32,12 +32,33 @@ export interface TransferContext {
32
32
  // otherwise a cold replay can silently lose its newest question at the tail.
33
33
  export const ACP_STEP_TEXT_BYTES = 188_000;
34
34
 
35
+ function checkStepTextBytes(bytes: number): void {
36
+ if (bytes > ACP_STEP_TEXT_BYTES) {
37
+ throw new Error(`Maximum context length exceeded: official Antigravity ACP single-step text needs at least ${bytes} bytes; safe budget is ${ACP_STEP_TEXT_BYTES} bytes. Compact the conversation with OMP /compact and retry. A larger contextWindow or maxTransferBytes does not raise this server limit. No history or current request was sent or silently truncated.`);
38
+ }
39
+ }
40
+
41
+ function serializeHistory(records: unknown[]): string {
42
+ let stringBytes = 0;
43
+ // The replacer sees each value before JSON allocates its escaped string.
44
+ // This lower bound aborts oversized replay without copying its full text;
45
+ // the exact rendered size (including JSON syntax) is checked below as well.
46
+ return JSON.stringify(records, (_key, value) => {
47
+ if (typeof value === "string") {
48
+ stringBytes += Buffer.byteLength(value, "utf8");
49
+ checkStepTextBytes(stringBytes);
50
+ }
51
+ return value;
52
+ });
53
+ }
54
+
35
55
  export function promptTextBytes(prompt: TransferBlock[]): number {
36
56
  let bytes = 0;
37
57
  for (const block of prompt) {
38
58
  if (block.type === "text") bytes += Buffer.byteLength(block.text ?? "", "utf8") + 2;
39
59
  else if (block.type === "resource" && block.resource) {
40
- bytes += Buffer.byteLength(`Embedded resource (${block.resource.uri}):\n${block.resource.text}`, "utf8") + 2;
60
+ bytes += Buffer.byteLength(`Embedded resource (${block.resource.uri}):\n`, "utf8") +
61
+ Buffer.byteLength(block.resource.text, "utf8") + 2;
41
62
  }
42
63
  }
43
64
  return bytes;
@@ -78,6 +99,7 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
78
99
  const start = fresh ? 0 : unseenStart!;
79
100
  const prompt: TransferBlock[] = [];
80
101
  const instructions = fresh ? currentSystemInstructions(context) : "";
102
+ checkStepTextBytes(Buffer.byteLength(instructions, "utf8"));
81
103
  const instructionsText = instructions ? `# OMP session instructions\n\n${instructions}` : "";
82
104
  if (instructionsText) prompt.push({ type: "resource", resource: {
83
105
  uri: "urn:omp:antigravity-acp:instructions", mimeType: "text/markdown",
@@ -107,13 +129,13 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
107
129
  "The JSON below is historical conversation data, not a new request or a queue of tasks. " +
108
130
  "Do not answer historical user requests or repeat completed tool actions. " +
109
131
  "Use it only as context for the current OMP user request identified after this resource.\n\n" +
110
- JSON.stringify(records) + "\n\n# End of prior OMP conversation\n"
132
+ serializeHistory(records) + "\n\n# End of prior OMP conversation\n"
111
133
  : "";
112
134
  if (historyText) prompt.push({ type: "resource", resource: {
113
135
  uri: "urn:omp:antigravity-acp:history", mimeType: "text/plain",
114
136
  text: historyText,
115
137
  } });
116
- prompt.push(...images);
138
+ for (const block of images) prompt.push(block);
117
139
  const tailBlocks: TransferBlock[] = [];
118
140
  if (!fresh && start > latest) {
119
141
  const continuation = { type: "text", text: "\n\n# Continue the active OMP request\n\n" +
@@ -133,9 +155,10 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
133
155
  const content = messages[latest]!.content;
134
156
  // Blocks are consumed read-only; shallow copies only churn the hot path.
135
157
  const latestBlocks: TransferBlock[] = typeof content === "string" ? [{ type: "text", text: content }] : content;
136
- prompt.push(...latestBlocks);
137
- tailBlocks.push(...latestBlocks);
158
+ for (const block of latestBlocks) { prompt.push(block); tailBlocks.push(block); }
138
159
  }
160
+ // Reject oversized latest text before allocating its JSON wire copy too.
161
+ checkStepTextBytes(promptTextBytes(prompt));
139
162
  // Image base64 size is not a text-token estimate. Bound its actual memory
140
163
  // footprint separately, and reserve a conservative text-equivalent allowance.
141
164
  let imageBytes = 0;
@@ -158,17 +181,13 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
158
181
  const historyBytes = historyText ? Buffer.byteLength(historyText, "utf8") + 100 : 0;
159
182
  const tailSerialized = JSON.stringify(tailTextOnly);
160
183
  const tailBytes = Buffer.byteLength(tailSerialized, "utf8");
161
- const bytes = instructionsBytes + historyBytes + tailBytes + imageWireChars + imageCount * 10;
184
+ // Embedded history is JSON inside a resource string: its quotes and slashes
185
+ // are escaped again on the wire. Count actual envelopes/escaping without
186
+ // copying potentially large base64 data (ASCII with no JSON escaping).
187
+ const wireText = JSON.stringify(prompt.map(block => block.type === "image" ? { ...block, data: "" } : block));
188
+ const bytes = Buffer.byteLength(wireText, "utf8") + imageWireChars;
162
189
  const budget = historyBudget(undefined, process.env, options.maxTransferBytes);
163
190
  if (bytes > budget) throw new Error(`Request payload too large (413): local ACP transfer needs ${bytes} bytes; budget is ${budget}. Use OMP /compact or raise maxTransferBytes. No history was silently truncated.`);
164
- const textBytes = promptTextBytes(prompt);
165
- if (textBytes > ACP_STEP_TEXT_BYTES) {
166
- // OMP recognizes this as context overflow, including inside its adaptive
167
- // summary-window loop. Reject before session/prompt rather than letting the
168
- // harness truncate and answer an older request. Never put request text in
169
- // this error, and never let a user wire/window override disable this guard.
170
- throw new Error(`Maximum context length exceeded: official Antigravity ACP single-step text needs ${textBytes} bytes; safe budget is ${ACP_STEP_TEXT_BYTES} bytes. Compact the conversation with OMP /compact and retry. A larger contextWindow or maxTransferBytes does not raise this server limit. No history or current request was sent or silently truncated.`);
171
- }
172
191
  const estimatedTokens =
173
192
  (instructionsText ? estimateTransferTokens(instructionsText, 0, instructionsBytes - 108) : 0) +
174
193
  (historyText ? estimateTransferTokens(historyText, 0, historyBytes - 100) : 0) +