omp-antigravity-acp-provider 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,7 +19,7 @@ The repository keeps the OMP adapter sources separately and installs upstream ve
19
19
 
20
20
  ## Status
21
21
 
22
- Version 0.1.8 supports all models advertised by the official ACP server. Tested with macOS, OMP 18.12.3, upstream provider 0.1.15 and official ACP runtime 1.4.1. Other platforms and OMP versions are not yet verified.
22
+ Version 0.1.10 supports all models advertised by the official ACP server. Tested with macOS, OMP 18.12.3, upstream provider 0.1.15 and official ACP runtime 1.4.1. Other platforms and OMP versions are not yet verified.
23
23
 
24
24
  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.
25
25
 
@@ -33,7 +33,7 @@ Google's consumer-plan policies can restrict third-party agent access even throu
33
33
  - Duplicate gray ACP tool-status lines are hidden by default, with an optional debug display switch. OMP tool calls/results and actual thought summaries remain visible.
34
34
  - Lazy ACP startup; model selection and cached listing do not launch the server.
35
35
  - Runtimes scoped to OMP sessions, including recovery after a planning session is disposed.
36
- - OAuth credentials owned by Antigravity; OMP stores only a non-secret marker.
36
+ - OMP `/login` support plus `/antigravity-acp login`, `logout` and `account` commands; the full local logout also removes the macOS keychain entry that the Antigravity server owns.
37
37
  - API-equivalent cost estimates, not subscription billing or quota measurements.
38
38
 
39
39
  ## Install from the OMP marketplace
@@ -56,7 +56,7 @@ Or, inside OMP:
56
56
 
57
57
  Select **omp-antigravity-acp-provider** in the browser, install it, and restart OMP to load the provider.
58
58
 
59
- 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.8** prebuilt npm adapter and production dependencies on first load. It disables npm install scripts, skips Pi CLI peer installation, and performs no local compilation. Node.js 22.19+ and npm must be on PATH. First preparation needs internet access and roughly **150 MiB** of disk space; later loads reuse the installed cache without npm network access.
59
+ 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.10** prebuilt npm adapter and production dependencies on first load. It disables npm install scripts, skips Pi CLI peer installation, and performs no local compilation. Node.js 22.19+ and npm must be on PATH. First preparation needs internet access and roughly **150 MiB** of disk space; later loads reuse the installed cache without npm network access.
60
60
 
61
61
  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.
62
62
 
@@ -80,7 +80,7 @@ omp plugin install npm:omp-antigravity-acp-provider
80
80
  To pin a specific release:
81
81
 
82
82
  ```sh
83
- omp plugin install npm:omp-antigravity-acp-provider@0.1.8
83
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.10
84
84
  ```
85
85
 
86
86
  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.
@@ -137,6 +137,8 @@ This repository does not change an existing OMP installation or overwrite its se
137
137
  3. Run `/antigravity-acp refresh` to discover the models actually advertised for the account.
138
138
  4. Select a model with `/model` and use OMP's thinking control to select a supported effort.
139
139
 
140
+ `/antigravity-acp login` runs the same Google authorization through a command dialog without touching OMP's stored account record; use it to re-authenticate or switch the Antigravity-side Google account. `/antigravity-acp account` shows the current authentication state on both sides.
141
+
140
142
  First use or login may download the official runtime. The observed macOS runtime occupies about **383 MiB**; size varies by platform/version. It lives outside this repository under `~/.local/opt/agy-acp/`. Do not remove it while ACP processes are running.
141
143
 
142
144
  If OMP's `enabledModels` whitelist is configured, add `antigravity-acp/*` alongside your existing entries in `~/.omp/agent/config.yml` to allow newly discovered models. Use individual `antigravity-acp/<server-model-id>` entries instead if you prefer a restricted list. The adapter does not rewrite that whitelist or any model-role preset.
@@ -147,6 +149,9 @@ After upgrading from an older adapter, run `/antigravity-acp refresh` once to re
147
149
 
148
150
  | Command | Purpose |
149
151
  | --- | --- |
152
+ | `/antigravity-acp account` | Authentication state on both the OMP and Antigravity sides |
153
+ | `/antigravity-acp login` | Run the Antigravity Google authorization in a command dialog |
154
+ | `/antigravity-acp logout` | Clear Antigravity credentials, saved ACP sessions and OMP's marker record |
150
155
  | `/antigravity-acp status` | Runtime, confirmed thinking and usage information |
151
156
  | `/antigravity-acp usage` | Current ACP context occupancy, accounting source and cache-data availability |
152
157
  | `/antigravity-acp usage auto` | Enable supplemental usage queries |
@@ -154,6 +159,10 @@ After upgrading from an older adapter, run `/antigravity-acp refresh` once to re
154
159
  | `/antigravity-acp context` | Show saved settings and effective per-model budgets |
155
160
  | `/antigravity-acp context set default KEY NUMBER` | Set a default token or payload setting |
156
161
  | `/antigravity-acp context set MODEL KEY NUMBER` | Override one advertised model ID |
162
+ | `/antigravity-acp cleanup` | Show cleanup mode/deadline and check eligible local sessions |
163
+ | `/antigravity-acp cleanup off` | Disable automatic session-file deletion |
164
+ | `/antigravity-acp cleanup conservative` | Delete confirmed replaced/disposable sessions only (default) |
165
+ | `/antigravity-acp cleanup timeout DAYS` | Also delete inactive owned sessions after DAYS (default 7) |
157
166
  | `/antigravity-acp tools` | Available and omitted OMP tool schemas after a request |
158
167
  | `/antigravity-acp refresh` | Explicit network discovery and local catalog refresh |
159
168
  | `/antigravity-acp native-tools prefer` | Prefer OMP tools; retain native built-ins (default) |
@@ -166,6 +175,10 @@ After upgrading from an older adapter, run `/antigravity-acp refresh` once to re
166
175
 
167
176
  The initial permission mode follows upstream configuration, whose default is `yolo`. Native Antigravity tools have separate execution permissions from OMP tools.
168
177
 
178
+ ### Sign out
179
+
180
+ OMP's `/logout` removes only OMP's stored non-secret marker record for this provider; it cannot reach the Google credentials that the Antigravity runtime keeps in its own storage. `/antigravity-acp logout` performs the complete local logout: it closes this process's ACP runtimes, clears saved ACP session mappings, deletes the local token file and the settings auth choice, removes the matching macOS keychain entry when present, and removes OMP's marker record. It refuses to run while Antigravity requests are active. If OMP's marker cannot be removed through the host API, the command says so and OMP's `/logout` finishes the job.
181
+
169
182
  The debug switch controls gray `[Antigravity tool: …]` and `[Antigravity tool update: …]` lines. It defaults to off and applies immediately to this process's active ACP connections. Normal OMP tool displays/results, real thought chunks and plan messages are preserved. The option is saved as `debugToolUpdates` in `omp-tools.json` alongside `nativeTools`; toggling either option preserves the other. Existing policy files without the debug field default to off. Other OMP processes need a restart to read a setting changed elsewhere. `OMP_ACP_TRACE=1` is a separate, opt-in terminal diagnostic setting.
170
183
 
171
184
  ## OMP tool routing and native-tool mode
@@ -194,7 +207,7 @@ Never include those user data directories, OAuth callback URLs, account identifi
194
207
 
195
208
  ## Context continuity and local performance
196
209
 
197
- The adapter now transfers complete replay history within a bounded budget, including historical image attachments. It no longer silently keeps only a 32,000-character history tail. If a transfer does not fit, it stops with an explicit error requesting OMP `/compact` or smaller attachments. This is a local transfer limit, not Antigravity's model context window or its internal compaction threshold. Active requests, history text and system instructions share the text budget; images have a conservative allowance and a separate total payload ceiling of 8 MiB. No automatic summarization or extra inference is added by the transfer layer.
210
+ The adapter now transfers complete replay history within a bounded budget, including historical image attachments. It no longer silently keeps only a 32,000-character history tail. If a transfer does not fit, it stops with an explicit error requesting OMP `/compact` or smaller attachments. This is a local transfer limit, not Antigravity's model context window or its internal compaction threshold. Active requests, history text and system instructions share the token and wire budgets; images also have a separate decoded-data limit. No automatic summarization or extra inference is added by the transfer layer.
198
211
 
199
212
  Token budgets and wire payload size are independent; the former 500,000-byte clamp is removed. The default wire payload limit is 16 MiB, configurable up to 128 MiB. Image data additionally defaults to an 8 MiB decoded payload limit. 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.
200
213
 
@@ -234,6 +247,37 @@ Merge that map with existing model-specific entries before running the command.
234
247
 
235
248
  Active sessions are reused. After five idle minutes, the adapter closes its ACP runtime, bridge and child processes; the next request tries to restore the saved server session. Active streams, outstanding ACP prompts, tools and permission waits prevent eviction. No background model prewarming, quota polling or tokenizer model download is performed.
236
249
 
250
+ ### Local ACP session cleanup
251
+
252
+ Session-file deletion is separate from the five-minute idle process shutdown. Configure one of three modes:
253
+
254
+ | Mode | Behavior |
255
+ | --- | --- |
256
+ | `off` | Keep session files, including replaced sessions. Ownership/lease bookkeeping remains enabled so cleanup can be enabled later. |
257
+ | `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. |
258
+ | `timeout` | Conservative cleanup plus removal of owned sessions whose last activity exceeds `idleDays`. 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. Live leases always override the deadline. |
259
+
260
+ ```text
261
+ /antigravity-acp cleanup
262
+ /antigravity-acp cleanup off
263
+ /antigravity-acp cleanup conservative
264
+ /antigravity-acp cleanup timeout 7
265
+ ```
266
+
267
+ Settings persist in `~/.omp/agent/antigravity-acp-provider/cleanup.json`:
268
+
269
+ ```json
270
+ { "mode": "conservative", "idleDays": 7 }
271
+ ```
272
+
273
+ 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. 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.
274
+
275
+ Only sessions created and registered by this adapter version onward are eligible. Pre-existing/unidentified ACP sessions are preserved. 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. Busy/corrupt registries and unsafe paths defer deletion. 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.
276
+
277
+ 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.
278
+
279
+ Timeout cleanup sacrifices ACP-only reasoning/checkpoint state. The next request reconstructs a session from OMP's retained history and can incur replay latency and a different token count. Cache expiry is not assumed or guaranteed. Conservative mode avoids that tradeoff for ordinary resumable sessions; it does not bound the number of unrelated OMP conversations you keep.
280
+
237
281
  Optional environment settings, applied when OMP starts:
238
282
 
239
283
  | Setting | Default | Effect |
@@ -244,6 +288,8 @@ Optional environment settings, applied when OMP starts:
244
288
 
245
289
  When automatic usage is enabled and `/usage` is advertised by the official server, the adapter queries it after each completed ACP prompt and computes a difference from the previous cumulative snapshot. A restored session first establishes a baseline so its old tokens are not charged again. These are main-agent totals and can include multiple internal model calls. Thinking tokens count toward estimated output cost. Queries are bounded by a five-second deadline; unavailable/malformed usage or a counter reset does not turn a successful model answer into a billing claim. Native ACP response usage takes priority when supplied. Query failures can cancel/retire the connection; subsequent work can restore the server session.
246
290
 
291
+ Supplemental queries default to `auto` for compatibility; the example above opts out. Use `/antigravity-acp usage off` to reduce the delay between the last text chunk and OMP regaining control, or `auto` to retain available token/cache/cost estimates. In a Flash Low test with three turns per mode, that final delay had a median of **282 ms with auto vs 21 ms with off** (261 ms less). Individual queries took 241–580 ms. This small sample does not establish a universal speedup, and total response time also varies with inference. Turning queries off preserves ACP context-occupancy updates used by OMP compaction; missing accounting data stays unavailable.
292
+
247
293
  ACP `usage_update.used` is passed to OMP separately as `usage.contextTokens`, rather than treating aggregate billable consumption as context occupancy. OMP 18.12.3 recognizes this field; it can still use a local stored-history estimate when deciding whether to compact. Google continues to control its own internal summaries.
248
294
 
249
295
  Stable tool ordering and stable context-resource identifiers avoid unnecessary client-side prefix changes. They do not guarantee implicit cache hits. `/antigravity-acp usage` marks cache information as `unknown` when Google omits it; zero cache fields in OMP's numeric usage structure must not be read as proof of zero backend caching. If cache counts are missing, the API-equivalent estimate prices input as uncached and cannot reflect any unreported cache discount. This is not a subscription bill or a measurement of quota deduction.
@@ -269,6 +315,8 @@ See the [0.1.8 context/compaction and usage benchmark](docs/context-compaction-0
269
315
 
270
316
  `npm run test:usage` uses Bun and mocked protocol responses to verify restored-session baselines, counter resets, query failures and advertised-command gating without starting ACP. `bun scripts/verify-continuity-live.ts --live` is a separate Flash-only probe of long history, synthetic tools, usage accounting and idle process reclamation/restoration; it consumes quota. Its one-second idle setting is isolated to the test process and is not the production default.
271
317
 
318
+ `npm run test:auth` uses Bun with an isolated `GEMINI_HOME`, a stubbed keychain and a stubbed OAuth flow to verify the account view, login dialog mapping, logout cleanup and the active-request guard without starting ACP. Real Google login and logout change account state, so they are not part of any automated test.
319
+
272
320
  `npm run test:packed` additionally requires OMP on PATH. It installs the exact npm tarball into a temporary consumer directory with development dependencies omitted and install scripts disabled, checks runtime assets, and loads its model catalog with ACP execution disabled. It downloads production dependencies and removes the temporary installation afterward.
273
321
 
274
322
  `npm run test:marketplace` exercises catalog discovery, installation, automatic provider loading, offline cache reuse and uninstallation in a temporary named OMP profile. It downloads the published adapter and cleans the entire test profile afterward. Add `-- --remote` after publishing catalog changes to test the GitHub source instead of the local working tree. No model inference is performed.
@@ -12,18 +12,62 @@ import { EFFORTS, projectCatalog, readModels, selectRuntimeModel } from "./model
12
12
  import { advertisedRecord, choices, selector } from "./selectors.ts";
13
13
  import { TOOL_ROUTING, parseNativeToolMode } from "./tool-routing.ts";
14
14
  import { loadNativeToolMode, loadToolPolicy, saveNativeToolMode, saveDebugToolUpdates } from "./tool-policy.ts";
15
- import { Type, createAntigravityProvider, AntigravityRuntime, PERMISSION_TOOL_NAME, PERMISSION_RESULT_KIND, loadConfig, savePermissionMode, inspectAntigravityAuth, hasAntigravityAuth, AcpSessionStore, ensureAntigravityAcpReady, TierConnection, planToolProjection, PiEventWriter } from "./runtime.mjs";
15
+ import { Type, createAntigravityProvider, AntigravityRuntime, PERMISSION_TOOL_NAME, PERMISSION_RESULT_KIND, loadConfig, savePermissionMode, inspectAntigravityAuth, hasAntigravityAuth, AcpSessionStore, ensureAntigravityAcpReady, TierConnection, planToolProjection, PiEventWriter, SessionCleanup } from "./runtime.mjs";
16
16
 
17
17
  const MARKER = "pi-antigravity-acp:managed-by-antigravity";
18
18
 
19
+ // macOS keychain operations behind one mutable object so offline command
20
+ // tests can substitute them without touching the user's real keychain.
21
+ export const keychain = {
22
+ // Check existence only. Never retrieve credentials from the keychain.
23
+ present(): boolean | undefined {
24
+ if (process.platform !== "darwin") return undefined;
25
+ try {
26
+ execFileSync("/usr/bin/security", ["find-generic-password", "-s", "gemini", "-a", "antigravity-acp"], { stdio: "ignore", timeout: 3000 });
27
+ return true;
28
+ } catch { return false; }
29
+ },
30
+ // Local logout for macOS keychain storage. The Antigravity server owns this
31
+ // item; removing it is required for a complete logout when no token file exists.
32
+ remove(): boolean | undefined {
33
+ if (process.platform !== "darwin") return undefined;
34
+ try {
35
+ execFileSync("/usr/bin/security", ["delete-generic-password", "-s", "gemini", "-a", "antigravity-acp"], { stdio: "ignore", timeout: 3000 });
36
+ return true;
37
+ } catch { return false; }
38
+ },
39
+ };
40
+
19
41
  function authReady() {
20
- if (hasAntigravityAuth()) return true;
21
- if (process.platform !== "darwin") return false;
42
+ return hasAntigravityAuth() || keychain.present() === true;
43
+ }
44
+
45
+ // OMP stores only the non-secret marker credential. Read it defensively:
46
+ // the model registry surface is host version dependent and absent in tests.
47
+ function ompCredentialSummary(ctx: any) {
48
+ try {
49
+ const stored = ctx?.modelRegistry?.authStorage?.credentials?.getOAuth?.("antigravity-acp");
50
+ if (!stored) return { present: false };
51
+ return {
52
+ present: true,
53
+ record: stored.refresh === MARKER ? "managed marker (non-secret)" : "oauth",
54
+ authorizedAt: typeof stored.authorizedAt === "number" ? new Date(stored.authorizedAt).toISOString() : undefined,
55
+ };
56
+ } catch (error: any) {
57
+ return { present: undefined, error: error instanceof Error ? error.message : String(error) };
58
+ }
59
+ }
60
+
61
+ // Removes OMP's stored marker record so one command completes the logout.
62
+ async function removeOmpCredentialRecord(ctx: any): Promise<"removed" | "absent" | "unavailable"> {
22
63
  try {
23
- // Check existence only. Never retrieve credentials from the keychain.
24
- execFileSync("/usr/bin/security", ["find-generic-password", "-s", "gemini", "-a", "antigravity-acp"], { stdio: "ignore", timeout: 3000 });
25
- return true;
26
- } catch { return false; }
64
+ const credentials = ctx?.modelRegistry?.authStorage?.credentials;
65
+ if (!credentials?.remove || !credentials.getOAuth) return "unavailable";
66
+ if (!credentials.getOAuth("antigravity-acp")) return "absent";
67
+ await credentials.remove("antigravity-acp");
68
+ try { await ctx.modelRegistry.refreshProvider?.("antigravity-acp", "online"); } catch { /* advisory only */ }
69
+ return "removed";
70
+ } catch { return "unavailable"; }
27
71
  }
28
72
 
29
73
  export default async function (pi: any) {
@@ -37,6 +81,7 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
37
81
  const toolPolicyPath = path.join(stateDir, "omp-tools.json");
38
82
  const contextPath = path.join(stateDir, "context.json");
39
83
  let contextSettings = loadContextSettings(contextPath);
84
+ const cleanup = new SessionCleanup(stateDir);
40
85
  // Loading this global extension must not start ACP or query Google.
41
86
  let readiness: Promise<void> | undefined;
42
87
  function prepareRuntime() {
@@ -57,7 +102,7 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
57
102
  const runtime = new AntigravityRuntime((options: any) => {
58
103
  const policy = loadToolPolicy(toolPolicyPath);
59
104
  const connection = new TierConnection({ ...options, ompNativeTools: policy.nativeTools, ompDebugToolUpdates: policy.debugToolUpdates,
60
- ompUsageMode: contextSettings.defaults.usageMode ?? "auto" });
105
+ ompUsageMode: contextSettings.defaults.usageMode ?? "auto", ompCleanup: cleanup });
61
106
  connections.add(connection);
62
107
  ownedConnections.add(connection);
63
108
  void connection.process.exited.finally(() => connections.delete(connection));
@@ -94,10 +139,23 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
94
139
  },
95
140
  });
96
141
  pi.registerCommand("antigravity-acp", {
97
- description: "Inspect ACP status/tools/usage/context, configure budgets, toggle debug, refresh models or set tool policies",
142
+ description: "Inspect ACP status/account/tools/usage/context/cleanup, manage Antigravity login/logout, configure budgets, toggle debug, refresh models or set tool policies",
98
143
  async handler(args: string, ctx: any) {
99
144
  const parts = args.trim().split(/\s+/);
100
145
  const [command, value] = parts;
146
+ if (command === "cleanup") {
147
+ if (value) {
148
+ if (!["off", "conservative", "timeout"].includes(value) || parts.length > 3 || (parts[2] !== undefined && value !== "timeout")) {
149
+ throw new Error("Usage: /antigravity-acp cleanup [off|conservative|timeout [DAYS]]");
150
+ }
151
+ cleanup.configure(value, parts[2] === undefined ? undefined : Number(parts[2]));
152
+ cleanup.start();
153
+ }
154
+ const removed = cleanup.collect();
155
+ ctx.ui.notify(JSON.stringify({ ...cleanup.status(), removed,
156
+ note: "Active sessions are protected. Timeout cleanup loses ACP-only state; OMP history is retained." }, null, 2), "info");
157
+ return;
158
+ }
101
159
  if (command === "context") {
102
160
  if (value === "set") {
103
161
  const [, , target, key, raw] = parts;
@@ -138,6 +196,70 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
138
196
  ctx.ui.notify(`Native tools: ${mode}. ACP connections will be recreated on the next request with the new policy.`, "info");
139
197
  return;
140
198
  }
199
+ if (command === "login") {
200
+ if (value) throw new Error("Usage: /antigravity-acp login");
201
+ await prepareRuntime();
202
+ // Direct Antigravity Google login through the command UI. OMP's /login
203
+ // runs the same flow and additionally stores the provider marker.
204
+ await runtimes.get().provider.auth.oauth.login({
205
+ signal: undefined,
206
+ notify(event: any) {
207
+ const link = event.links?.[0];
208
+ if (link) ctx.ui.notify(`${event.message ?? "Open this URL to authorize:"}\n${link.url}`, "info");
209
+ else if (event.message) ctx.ui.notify(event.message, "info");
210
+ },
211
+ prompt: async (request: any) => {
212
+ const answer = await ctx.ui.input(request.message, request.placeholder);
213
+ if (!answer?.trim()) throw new Error("Antigravity OAuth login cancelled");
214
+ return answer;
215
+ },
216
+ });
217
+ const auth = inspectAntigravityAuth();
218
+ ctx.ui.notify(`Antigravity Google login finished. ACP auth: ${auth.status}${auth.authType ? ` (${auth.authType})` : ""}.\nRun /antigravity-acp account to inspect the stored state, or OMP /login to also record the provider marker in OMP's account list.`, "info");
219
+ return;
220
+ }
221
+ if (command === "logout") {
222
+ if (value) throw new Error("Usage: /antigravity-acp logout");
223
+ if (runtimes.values().some(bundle => bundle.isBusy())) {
224
+ throw new Error("Wait for active Antigravity requests to finish before logging out.");
225
+ }
226
+ // Ensure a runtime (and its ACP session store) exists even before any request.
227
+ runtimes.get();
228
+ // runtime.logout() closes ACP connections, clears saved sessions and
229
+ // removes the local token file plus the settings auth choice.
230
+ await Promise.all(runtimes.values().map(bundle => bundle.runtime.logout()));
231
+ await runtimes.closeAll();
232
+ const keychainRemoved = keychain.remove();
233
+ const ompMarker = await removeOmpCredentialRecord(ctx);
234
+ const after = inspectAntigravityAuth();
235
+ ctx.ui.notify([
236
+ "Antigravity ACP logout",
237
+ `ACP auth after logout: ${after.status}${after.authType ? ` (${after.authType})` : ""}`,
238
+ `macOS keychain entry: ${keychainRemoved === undefined ? "not applicable (non-macOS)" : keychainRemoved ? "removed" : "not present or not removable"}`,
239
+ "Saved ACP sessions: cleared",
240
+ `OMP marker record: ${ompMarker === "removed" ? "removed" : ompMarker === "absent" ? "was not stored" : "could not be removed; run /logout to drop it"}`,
241
+ "Run /antigravity-acp login or OMP /login to sign in again.",
242
+ ].join("\n"), "info");
243
+ return;
244
+ }
245
+ if (command === "account") {
246
+ if (value) throw new Error("Usage: /antigravity-acp account");
247
+ const auth = inspectAntigravityAuth();
248
+ let ompSource: string | undefined;
249
+ try { ompSource = ctx?.modelRegistry?.authStorage?.keys?.describe?.("antigravity-acp", sessionIdOf(ctx)); } catch { /* host version dependent */ }
250
+ const snapshot = await runtimes.get(sessionIdOf(ctx)).runtime.snapshot();
251
+ ctx.ui.notify(JSON.stringify({
252
+ provider: "antigravity-acp",
253
+ ompCredential: ompCredentialSummary(ctx),
254
+ ompAuthSource: ompSource,
255
+ acpAuth: { status: auth.status, authType: auth.authType, tokenFile: auth.tokenFile, settingsFile: auth.settingsFile, usable: authReady() },
256
+ macOSKeychainEntry: keychain.present(),
257
+ savedAcpSessions: runtimes.get(sessionIdOf(ctx)).runtime.sessionStore?.read().length ?? 0,
258
+ runtime: { permissionMode: snapshot.permissionMode, activeSessions: snapshot.bindings },
259
+ note: "Google OAuth tokens stay in Antigravity-owned storage (~/.gemini/antigravity-acp or the macOS keychain). OMP stores only a non-secret marker. /antigravity-acp logout clears both sides; OMP /logout removes only the marker.",
260
+ }, null, 2), "info");
261
+ return;
262
+ }
141
263
  const { runtime } = runtimes.get(sessionIdOf(ctx));
142
264
  if (command === "usage") {
143
265
  ctx.ui.notify(JSON.stringify({ configured: contextSettings.defaults.usageMode ?? "auto",
@@ -193,10 +315,12 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
193
315
  }
194
316
  async function discoverModels() {
195
317
  await prepareRuntime();
196
- const connection = new TierConnection({ cwd: process.cwd() });
318
+ const connection = new TierConnection({ cwd: process.cwd(), ompCleanup: cleanup });
319
+ let discoveredSession: string | undefined;
197
320
  try {
198
321
  await connection.initialize();
199
322
  const session = await connection.newSession(process.cwd());
323
+ discoveredSession = session.sessionId;
200
324
  const modern = choices(selector(session, "model"));
201
325
  if (modern.length) {
202
326
  const models = [];
@@ -212,6 +336,7 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
212
336
  if (!models.length) throw new Error("Antigravity did not advertise any models");
213
337
  return models;
214
338
  } finally {
339
+ if (discoveredSession) connection.discardSession(discoveredSession);
215
340
  await connection.close();
216
341
  }
217
342
  }