omp-antigravity-acp-provider 0.1.44 → 0.2.2

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 (63) hide show
  1. package/AGENT_INSTALL.md +1 -1
  2. package/README.md +87 -20
  3. package/THIRD_PARTY_NOTICES.md +12 -1
  4. package/extension/acp-errors.ts +37 -10
  5. package/extension/adapter-config.ts +123 -6
  6. package/extension/assets/src/acp/supervisor.mjs +4 -1
  7. package/extension/auth-sync.ts +245 -55
  8. package/extension/catalog-store.ts +52 -26
  9. package/extension/commands.ts +54 -156
  10. package/extension/index.ts +459 -98
  11. package/extension/model-catalog.ts +37 -3
  12. package/extension/omp-session-lifecycle.ts +13 -2
  13. package/extension/omp-session-source.ts +16 -5
  14. package/extension/runtime/acp/antigravity.ts +185 -0
  15. package/extension/runtime/acp/bounded-stream.ts +171 -0
  16. package/extension/runtime/acp/connection.ts +507 -0
  17. package/extension/runtime/acp/credential-storage.ts +113 -0
  18. package/extension/runtime/acp/errors.ts +54 -0
  19. package/extension/runtime/acp/events.ts +66 -0
  20. package/extension/runtime/acp/headless-oauth.ts +209 -0
  21. package/extension/runtime/acp/prompt-watchdog.ts +80 -0
  22. package/extension/runtime/acp/proxy.ts +54 -0
  23. package/extension/runtime/acp/runtime-manifest.ts +185 -0
  24. package/extension/runtime/acp/session-state.ts +76 -0
  25. package/extension/runtime/asset.ts +24 -0
  26. package/extension/runtime/binding.ts +145 -0
  27. package/extension/runtime/config.ts +119 -0
  28. package/extension/runtime/constants.ts +18 -0
  29. package/extension/runtime/history-seed.ts +227 -0
  30. package/extension/runtime/image-history.ts +233 -0
  31. package/extension/runtime/index.ts +23 -0
  32. package/extension/runtime/launch.ts +545 -0
  33. package/extension/runtime/managed.ts +872 -0
  34. package/extension/runtime/models.ts +192 -0
  35. package/extension/runtime/process.ts +281 -0
  36. package/extension/{context-transfer.ts → runtime/prompt.ts} +183 -70
  37. package/extension/runtime/provider.ts +149 -0
  38. package/extension/runtime/routing.ts +47 -0
  39. package/extension/runtime/runtime-manifest.json +205 -0
  40. package/extension/runtime/runtime.ts +2204 -0
  41. package/extension/runtime/status.ts +87 -0
  42. package/extension/runtime/stream/json.ts +17 -0
  43. package/extension/runtime/stream/pi-events.ts +142 -0
  44. package/extension/runtime/stream/usage.ts +37 -0
  45. package/extension/runtime/supervisor.mjs +113 -0
  46. package/extension/{tool-args.ts → runtime/tools/args.ts} +1 -1
  47. package/extension/runtime/tools/bridge.ts +331 -0
  48. package/extension/{tool-relay.ts → runtime/tools/relay.ts} +8 -3
  49. package/extension/runtime/tools/schema.ts +256 -0
  50. package/extension/runtime.mjs +2793 -1239
  51. package/extension/secret-service.ts +85 -0
  52. package/extension/session-cleanup.ts +49 -2
  53. package/extension/session-store.ts +1 -1
  54. package/extension/tier-connection.ts +248 -56
  55. package/extension/tool-order.ts +4 -2
  56. package/extension/tool-routing.ts +112 -30
  57. package/extension/usage-accounting.ts +6 -2
  58. package/extension/usage-db.ts +95 -22
  59. package/extension/usage.ts +1 -1
  60. package/package.json +10 -6
  61. package/extension/acp-runtime-source.ts +0 -310
  62. package/extension/history-fingerprint.ts +0 -80
  63. package/extension/structured-fingerprint.ts +0 -63
@@ -3,7 +3,9 @@ import { setTimeout as delay } from "node:timers/promises";
3
3
  import { promisify } from "node:util";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
- import { clearAntigravityCredentials, hasAntigravityAuth, resolveAntigravityAcpDirectory } from "./runtime.mjs";
6
+ import { clearAntigravityCredentials, inspectAntigravityAuth, resolveAntigravityAcpDirectory } from "./runtime.mjs";
7
+ import type { AntigravityAuthHealth } from "./runtime/acp/antigravity.ts";
8
+ import { createSecretService, runSecretTool } from "./secret-service.ts";
7
9
  import type { TierConnection } from "./tier-connection.ts";
8
10
 
9
11
  export const MARKER = "pi-antigravity-acp:managed-by-antigravity";
@@ -27,11 +29,14 @@ function isConfirmedMissing(error: unknown): boolean {
27
29
  && typeof detail.stderr === "string" && /could not be found/.test(detail.stderr);
28
30
  }
29
31
 
32
+ export const KEYCHAIN_SERVICE = "gemini";
33
+ // The managed runtime stores the token under `antigravity-acp`; the agy CLI
34
+ // stores it under `antigravity`. Both are local logins, and logout must clear
35
+ // whichever entry the active channel wrote.
36
+ export const KEYCHAIN_ACCOUNTS = ["antigravity-acp", "antigravity"] as const;
37
+
30
38
  // macOS keychain operations behind one mutable object so offline command
31
39
  // tests can substitute them without touching the user's real keychain.
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
40
  export function createKeychain(run: (args: string[]) => Promise<void>, platform: NodeJS.Platform = process.platform) {
36
41
  const check = async (args: string[], failure: string): Promise<boolean | undefined> => {
37
42
  if (platform !== "darwin") return undefined;
@@ -43,20 +48,41 @@ export function createKeychain(run: (args: string[]) => Promise<void>, platform:
43
48
  throw new Error(failure);
44
49
  }
45
50
  };
51
+ const argsFor = (command: "find-generic-password" | "delete-generic-password", account: string): string[] =>
52
+ [command, "-s", KEYCHAIN_SERVICE, "-a", account];
53
+ const present = async (): Promise<boolean | undefined> => {
54
+ if (platform !== "darwin") return undefined;
55
+ for (const account of KEYCHAIN_ACCOUNTS) {
56
+ if (await check(argsFor("find-generic-password", account), "Unable to inspect the Antigravity keychain entry")) return true;
57
+ }
58
+ return false;
59
+ };
60
+ const remove = async (): Promise<boolean | undefined> => {
61
+ if (platform !== "darwin") return undefined;
62
+ let removed = false;
63
+ for (const account of KEYCHAIN_ACCOUNTS) {
64
+ if (await check(argsFor("delete-generic-password", account), "Unable to remove the Antigravity keychain entry")) removed = true;
65
+ }
66
+ return removed;
67
+ };
46
68
  return {
69
+ applicable: platform === "darwin",
47
70
  // Check existence only: the item's ACL does not authorize the security
48
71
  // CLI, so a `find-generic-password -w` would pop the macOS keychain
49
72
  // 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"),
73
+ present,
74
+ // Both accounts are cleared so a
75
+ // later channel switch cannot revive the previous login.
76
+ remove,
55
77
  };
56
78
  }
57
79
 
58
80
  export const keychain = createKeychain(runSecurity);
59
81
 
82
+ // The Linux Secret Service item behind the same mutable boundary as the macOS
83
+ // keychain, so offline command tests never reach the user's real keyring.
84
+ export const secretService = createSecretService(runSecretTool);
85
+
60
86
  function emailFromTokenJson(raw: string): string | undefined {
61
87
  try {
62
88
  const parsed = JSON.parse(raw) as { id_token?: unknown } | null;
@@ -78,23 +104,83 @@ export function antigravityAccountEmail(): string | undefined {
78
104
  }
79
105
 
80
106
  // Timing knobs for following OMP-side logouts; mutable so offline tests can
81
- // run the delayed detection without real waits.
82
- export const logoutFollow = { delayMs: 500, retryMs: 15_000 };
107
+ // run the delayed detection and the removal verification without real waits.
108
+ export const logoutFollow = {
109
+ delayMs: 500, retryMs: 15_000, removalRetryMs: 400, disabledSuppressionMs: 30_000,
110
+ };
83
111
 
84
112
  // Shared wording for both logout confirmations (direct command and the
85
113
  // follow-up that finishes a logout OMP started).
86
- export function formatLogoutSummary(options: { keychainRemoved: boolean | undefined; ompMarker?: "removed" | "absent" | "unavailable"; followed?: boolean }): string {
114
+ export function formatLogoutSummary(options: {
115
+ keychainRemoved: boolean | undefined;
116
+ keyringRemoved: boolean | undefined;
117
+ ompMarker?: "removed" | "absent" | "unavailable";
118
+ followed?: boolean;
119
+ }): string {
87
120
  const cleared = ["Google credentials", "saved ACP sessions"];
88
121
  if (options.keychainRemoved === true) cleared.push("the macOS keychain entry");
122
+ if (options.keyringRemoved === true) cleared.push("the system keyring entry");
89
123
  if (options.ompMarker === "removed") cleared.push("the OMP marker record");
90
124
  const list = cleared.slice(0, -1).join(", ") + " and " + cleared[cleared.length - 1];
91
125
  return `${options.followed ? "Antigravity ACP: finished the logout OMP started — " : "Antigravity ACP: logged out — "}${list} cleared.` +
92
126
  (options.ompMarker === "unavailable" ? " The OMP marker record could not be removed; run /logout to drop it." : "") +
93
- (options.keychainRemoved === false ? " The macOS keychain entry was not present or not removable." : "");
127
+ (options.keychainRemoved === false ? " The macOS keychain entry was not present or not removable." : "") +
128
+ (options.keyringRemoved === false ? " The system keyring entry was not present or not removable." : "");
129
+ }
130
+
131
+ // ACP auth health plus the Linux Secret Service fallback. The ACP server reads
132
+ // the system keyring before its file store, so a present keyring item is a
133
+ // complete local login even when no acp_token.json exists. A keyring probe that
134
+ // cannot reach the service (undefined) leaves the file-based health untouched:
135
+ // it is neither a stored credential nor a confirmed absence.
136
+ export interface AcpAuthHealth extends AntigravityAuthHealth {
137
+ keyring?: boolean;
138
+ }
139
+
140
+ interface RawAuthHealth {
141
+ status?: unknown;
142
+ authType?: unknown;
143
+ tokenFile?: unknown;
144
+ settingsFile?: unknown;
145
+ }
146
+
147
+ function authStatusOf(value: unknown): AntigravityAuthHealth["status"] | undefined {
148
+ switch (value) {
149
+ case "api-key-env":
150
+ case "oauth-refreshable":
151
+ case "configured-not-authenticated":
152
+ case "corrupt":
153
+ case "missing":
154
+ return value;
155
+ default:
156
+ return undefined;
157
+ }
158
+ }
159
+
160
+ export async function inspectAcpAuth(directory?: string, env: NodeJS.ProcessEnv = process.env): Promise<AcpAuthHealth> {
161
+ // The directory and the credential environment must describe the same child
162
+ // process: an explicit GEMINI_HOME relocates both the token file and the store.
163
+ const base: RawAuthHealth = inspectAntigravityAuth(directory ?? resolveAntigravityAcpDirectory(env), env);
164
+ const status = authStatusOf(base.status);
165
+ if (!status) throw new Error("Unable to inspect the Antigravity credential store");
166
+ const health: AcpAuthHealth = {
167
+ status,
168
+ tokenFile: base.tokenFile === true,
169
+ settingsFile: base.settingsFile === true,
170
+ ...(typeof base.authType === "string" ? { authType: base.authType } : {}),
171
+ };
172
+ // An API key or a refreshable token file is a complete login on its own; the
173
+ // keyring is only consulted when the file store reports no credential.
174
+ if (status !== "missing" && status !== "configured-not-authenticated") return health;
175
+ if ((await secretService.present()) !== true) return health;
176
+ return { ...health, status: "oauth-refreshable", authType: health.authType ?? "oauth-personal", keyring: true };
94
177
  }
95
178
 
96
- export async function authReady(): Promise<boolean> {
97
- return hasAntigravityAuth() || (await keychain.present()) === true;
179
+ export async function authReady(options: { allowKeychain?: boolean } = {}): Promise<boolean> {
180
+ const health = await inspectAcpAuth();
181
+ if (health.status === "api-key-env" || health.status === "oauth-refreshable") return true;
182
+ if (options.allowKeychain === false) return false;
183
+ return (await keychain.present()) === true;
98
184
  }
99
185
 
100
186
  export interface OmpCommandContext {
@@ -162,6 +248,36 @@ export interface AuthCoordinatorDeps {
162
248
  onSyncProvider: () => void;
163
249
  }
164
250
 
251
+ const freshGoogleLoginBrand = Symbol("fresh google login attempt");
252
+
253
+ export type FreshGoogleLoginAttempt = {
254
+ readonly [freshGoogleLoginBrand]: true;
255
+ };
256
+
257
+ interface CredentialStore {
258
+ applicable: boolean;
259
+ present: () => Promise<boolean | undefined>;
260
+ remove: () => Promise<boolean | undefined>;
261
+ }
262
+
263
+ // Clear one credential store and verify it. An entry that is already gone is an
264
+ // idempotent success; a store whose availability is unknown is never deleted
265
+ // blind and never certified; a removal that claims success but leaves the item
266
+ // in place is retried and then reported as unconfirmed.
267
+ async function removeStoreDurably(store: CredentialStore): Promise<boolean | undefined> {
268
+ let foundPresent = false;
269
+ for (let attempt = 0; attempt < 3; attempt++) {
270
+ const present = await store.present();
271
+ if (present === false) return true;
272
+ if (present === undefined) return foundPresent ? false : undefined;
273
+ foundPresent = true;
274
+ const removed = await store.remove();
275
+ if (removed !== true) return false;
276
+ await delay(logoutFollow.removalRetryMs);
277
+ }
278
+ return (await store.present()) === false;
279
+ }
280
+
165
281
  // OMP's oauth contract has no logout hook: /logout only removes the stored
166
282
  // marker credential. Watching the credential store's generation counter lets
167
283
  // this adapter finish the Antigravity-side logout when OMP reports removal.
@@ -170,6 +286,9 @@ export class OmpAuthCoordinator {
170
286
  private activeContext: OmpCommandContext | undefined;
171
287
  private markerPresent: boolean | undefined;
172
288
  private suppressFollow = false;
289
+ private baseSuppressFollow = false;
290
+ private readonly activeLogins = new Set<FreshGoogleLoginAttempt>();
291
+ private disabledUntil = 0;
173
292
  private selfLogout = false;
174
293
  // Whether registerProvider keeps the non-secret config apiKey fallback.
175
294
  apiKeyFallback = true;
@@ -184,59 +303,121 @@ export class OmpAuthCoordinator {
184
303
  } catch { return undefined; }
185
304
  }
186
305
 
187
- // A dying ACP server can flush its in-memory token back to the keychain,
188
- // racing a plain deletion and restoring the previous account. Wait for this
189
- // adapter's server processes to fully exit first, then verify the removal.
190
- async removeKeychainCredentialDurably(): Promise<boolean | undefined> {
306
+ // A dying ACP server can flush its in-memory token back to the keychain (or
307
+ // the Secret Service) racing a plain deletion and restoring the previous
308
+ // account. Wait for this adapter's server processes to fully exit first, then
309
+ // verify both stores.
310
+ async removeCredentialsDurably(): Promise<{ keychainRemoved: boolean | undefined; keyringRemoved: boolean | undefined }> {
191
311
  const pending = [...this.deps.connections].map(connection => connection.process.exited.catch(() => undefined));
192
312
  if (pending.length > 0) {
193
- await Promise.race([Promise.allSettled(pending), delay(10_000)]);
194
- }
195
- for (let attempt = 0; attempt < 3; attempt++) {
196
- if ((await keychain.present()) === false) return true;
197
- const removed = await keychain.remove();
198
- if (removed !== true) return removed;
199
- await delay(400);
313
+ let timer: NodeJS.Timeout | undefined;
314
+ try {
315
+ await Promise.race([
316
+ Promise.allSettled(pending),
317
+ new Promise<void>(resolve => {
318
+ timer = setTimeout(resolve, 10_000);
319
+ timer.unref?.();
320
+ }),
321
+ ]);
322
+ } finally {
323
+ clearTimeout(timer);
324
+ }
200
325
  }
201
- return (await keychain.present()) === false;
326
+ return {
327
+ keychainRemoved: await removeStoreDurably(keychain),
328
+ keyringRemoved: await removeStoreDurably(secretService),
329
+ };
202
330
  }
203
331
 
204
332
  // /login must mean a fresh Google sign-in: drop stored credentials (and this
205
333
  // process's old-account servers) so a new server cannot silently reuse the
206
334
  // saved login and keep the previous account.
207
- noteLoginSucceeded(): void {
335
+ noteLoginSucceeded(attempt: FreshGoogleLoginAttempt): void {
336
+ if (!this.activeLogins.delete(attempt)) return;
337
+ if (this.activeLogins.size > 0) {
338
+ this.baseSuppressFollow = false;
339
+ this.disabledUntil = 0;
340
+ return;
341
+ }
342
+ this.suppressFollow = false;
343
+ this.baseSuppressFollow = false;
344
+ this.disabledUntil = 0;
208
345
  clearTimeout(this.followTimer);
209
346
  this.followTimer = undefined;
210
347
  clearTimeout(this.followRetry);
211
348
  this.followRetry = undefined;
212
- this.suppressFollow = false;
213
349
  if (!this.apiKeyFallback) {
214
350
  this.apiKeyFallback = true;
215
351
  this.deps.onSyncProvider();
216
352
  }
217
353
  }
218
354
 
219
- async beginFreshGoogleLogin(): Promise<void> {
355
+ cancelFreshGoogleLogin(attempt: FreshGoogleLoginAttempt): void {
356
+ if (!this.activeLogins.delete(attempt) || this.activeLogins.size > 0) return;
357
+ this.suppressFollow = this.baseSuppressFollow || performance.now() < this.disabledUntil;
358
+ this.baseSuppressFollow = false;
359
+ clearTimeout(this.followTimer);
360
+ this.followTimer = undefined;
361
+ this.restoreApiKeyFallback(this.activeContext);
362
+ }
363
+
364
+ private restoreApiKeyFallback(ctx: OmpCommandContext | undefined): void {
365
+ // A confirmed marker deletion is a logged-out state, including when a
366
+ // browser login was cancelled. Never synthesize a credential fallback.
367
+ if ((this.ompMarkerStored(ctx) ?? this.markerPresent) === false || this.apiKeyFallback) return;
368
+ this.apiKeyFallback = true;
369
+ this.deps.onSyncProvider();
370
+ }
371
+
372
+ async beginFreshGoogleLogin(): Promise<FreshGoogleLoginAttempt> {
220
373
  if (this.deps.isPoolBusy()) {
221
374
  throw new Error("Wait for active Antigravity requests to finish before logging in.");
222
375
  }
223
- clearTimeout(this.followTimer);
224
- this.followTimer = undefined;
225
- clearTimeout(this.followRetry);
226
- this.followRetry = undefined;
227
- await this.deps.closeAllRuntimes();
228
- // A different Google login must not restore the previous account's ACP
229
- // mappings. OMP retains its transcript for a fresh backend reconstruction.
230
- await this.deps.logoutAllRuntimes();
231
- clearAntigravityCredentials();
232
- // The old keychain entry must be gone before a new sign-in can start; an
233
- // unconfirmed removal refuses the login instead of silently reusing it.
234
- if (await this.removeKeychainCredentialDurably() === false) {
235
- throw new Error("Unable to confirm removal of the Antigravity keychain entry");
376
+ // OMP removes the stale marker while the browser sign-in is still running.
377
+ // That generation change must not be mistaken for a user logout and close
378
+ // the new ACP runtime before the login can finish, so suppress it before
379
+ // the teardown below can yield.
380
+ const attempt: FreshGoogleLoginAttempt = { [freshGoogleLoginBrand]: true };
381
+ if (this.activeLogins.size === 0) {
382
+ this.baseSuppressFollow = this.suppressFollow;
383
+ }
384
+ this.activeLogins.add(attempt);
385
+ this.suppressFollow = true;
386
+ try {
387
+ clearTimeout(this.followTimer);
388
+ this.followTimer = undefined;
389
+ clearTimeout(this.followRetry);
390
+ this.followRetry = undefined;
391
+ await this.deps.closeAllRuntimes();
392
+ // A different Google login must not restore the previous account's ACP
393
+ // mappings. OMP retains its transcript for a fresh backend reconstruction.
394
+ await this.deps.logoutAllRuntimes();
395
+ clearAntigravityCredentials();
396
+ // The old credentials must be gone before a new sign-in can start; an
397
+ // unconfirmed removal refuses the login instead of silently reusing it.
398
+ const { keychainRemoved, keyringRemoved } = await this.removeCredentialsDurably();
399
+ if (keychainRemoved === false || keyringRemoved === false
400
+ || (keychain.applicable && keychainRemoved !== true)
401
+ || (secretService.applicable && keyringRemoved !== true)) {
402
+ throw new Error("Unable to confirm removal of the Antigravity credentials");
403
+ }
404
+ return attempt;
405
+ } catch (error) {
406
+ // A refused or aborted login cleans up its own identity. The caller has
407
+ // no identity to cancel until this method fulfills.
408
+ if (this.activeLogins.delete(attempt) && this.activeLogins.size === 0) {
409
+ this.suppressFollow = this.baseSuppressFollow || performance.now() < this.disabledUntil;
410
+ this.baseSuppressFollow = false;
411
+ }
412
+ throw error;
236
413
  }
237
414
  }
238
415
 
239
- async performCommandLogout(ctx: OmpCommandContext): Promise<{ keychainRemoved: boolean | undefined; ompMarker: "removed" | "absent" | "unavailable" }> {
416
+ async performCommandLogout(ctx: OmpCommandContext): Promise<{
417
+ keychainRemoved: boolean | undefined;
418
+ keyringRemoved: boolean | undefined;
419
+ ompMarker: "removed" | "absent" | "unavailable";
420
+ }> {
240
421
  if (this.deps.isPoolBusy()) {
241
422
  throw new Error("Wait for active Antigravity requests to finish before logging out.");
242
423
  }
@@ -246,7 +427,7 @@ export class OmpAuthCoordinator {
246
427
  this.followRetry = undefined;
247
428
  await this.deps.logoutAllRuntimes();
248
429
  await this.deps.closeAllRuntimes();
249
- const keychainRemoved = await this.removeKeychainCredentialDurably();
430
+ const { keychainRemoved, keyringRemoved } = await this.removeCredentialsDurably();
250
431
  // Removing the marker ourselves must not trigger the follow-up logout.
251
432
  this.selfLogout = true;
252
433
  let ompMarker: "removed" | "absent" | "unavailable";
@@ -265,7 +446,7 @@ export class OmpAuthCoordinator {
265
446
  this.apiKeyFallback = false;
266
447
  this.deps.onSyncProvider();
267
448
  }
268
- return { keychainRemoved, ompMarker };
449
+ return { keychainRemoved, keyringRemoved, ompMarker };
269
450
  }
270
451
 
271
452
  private async finishFollowedLogout(ctx: OmpCommandContext): Promise<void> {
@@ -284,12 +465,13 @@ export class OmpAuthCoordinator {
284
465
  await this.deps.logoutAllRuntimes();
285
466
  await this.deps.closeAllRuntimes();
286
467
  // A quick re-login can restore the marker while the steps above await;
287
- // a restored or unknown marker keeps the new keychain entry untouched.
468
+ // a restored or unknown marker keeps the new credentials untouched.
288
469
  if (this.ompMarkerStored(this.activeContext ?? activeCtx) !== false) return;
289
- const keychainRemoved = await this.removeKeychainCredentialDurably();
470
+ const { keychainRemoved, keyringRemoved } = await this.removeCredentialsDurably();
290
471
  // Keep the confirmation terse; /antigravity-acp account shows the details.
291
472
  try {
292
- (this.activeContext ?? activeCtx)?.ui?.notify?.(formatLogoutSummary({ keychainRemoved, followed: true }), "info");
473
+ (this.activeContext ?? activeCtx)?.ui?.notify?.(
474
+ formatLogoutSummary({ keychainRemoved, keyringRemoved, followed: true }), "info");
293
475
  } catch { /* the host UI may already be gone */ }
294
476
  }
295
477
 
@@ -319,6 +501,7 @@ export class OmpAuthCoordinator {
319
501
  // those, but not for user-initiated removals such as /logout.
320
502
  this.deps.pi.on("credential_disabled", (event: unknown) => {
321
503
  if (event && typeof event === "object" && "provider" in event && event.provider === "antigravity-acp") {
504
+ this.disabledUntil = performance.now() + logoutFollow.disabledSuppressionMs;
322
505
  this.suppressFollow = true;
323
506
  }
324
507
  });
@@ -328,7 +511,15 @@ export class OmpAuthCoordinator {
328
511
  if (current === undefined) return;
329
512
  const wasPresent = this.markerPresent === true;
330
513
  this.markerPresent = current;
331
- if (current) this.suppressFollow = false;
514
+ if (current) {
515
+ this.suppressFollow = false;
516
+ this.baseSuppressFollow = false;
517
+ this.disabledUntil = 0;
518
+ } else if (this.activeLogins.size > 0) {
519
+ this.suppressFollow = true;
520
+ } else if (performance.now() >= this.disabledUntil) {
521
+ this.suppressFollow = false;
522
+ }
332
523
  if (wasPresent !== current) {
333
524
  // Flip the config apiKey in the same synchronous tick as the marker
334
525
  // change: OMP's own logout report then finds no remaining
@@ -342,17 +533,16 @@ export class OmpAuthCoordinator {
342
533
  this.followTimer = setTimeout(() => {
343
534
  this.followTimer = undefined;
344
535
  if (process.env.OMP_ACP_FOLLOW_LOGOUT === "0") return;
345
- if (this.suppressFollow) {
536
+ if (this.suppressFollow && (this.activeLogins.size > 0 || performance.now() < this.disabledUntil)) {
346
537
  this.suppressFollow = false;
347
- this.apiKeyFallback = true;
348
- this.deps.onSyncProvider();
538
+ this.disabledUntil = 0;
539
+ this.restoreApiKeyFallback(activeCtx);
349
540
  return;
350
541
  }
351
542
  // A quick re-login after the removal cancels the cleanup.
352
543
  const currentCtx = this.activeContext ?? activeCtx;
353
544
  if (this.ompMarkerStored(currentCtx) !== false) {
354
- this.apiKeyFallback = true;
355
- this.deps.onSyncProvider();
545
+ this.restoreApiKeyFallback(currentCtx);
356
546
  return;
357
547
  }
358
548
  this.runFollowedLogout(currentCtx);
@@ -4,7 +4,7 @@ import { resolveContextOptions, type ContextSettings, type ResolvedContextOption
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";
7
- import { TierConnection } from "./runtime.mjs";
7
+ import { TierConnection, authenticateForCredential, usableApiKey } from "./runtime.mjs";
8
8
  import type { SessionCleanup } from "./session-cleanup.ts";
9
9
 
10
10
  export interface ConfiguredCatalogModel extends PublicCatalogModel {
@@ -15,9 +15,12 @@ export class CatalogStore {
15
15
  readonly upstreamModels = new Map<string, ConfiguredCatalogModel>();
16
16
  currentModels: ConfiguredCatalogModel[] = [];
17
17
  private sourceModels: PublicCatalogModel[] = [];
18
+ // False while only the adapter's offline fallback is loaded. A real cache or
19
+ // successful discovery flips this so inference does not keep re-discovering.
20
+ private upstreamKnown = false;
18
21
  private dynamicCache?: { stamp?: string; settings: string; models: ConfiguredCatalogModel[] };
19
- private discovery?: Promise<AdvertisedModel[]>;
20
- private refreshing?: Promise<ConfiguredCatalogModel[]>;
22
+ private readonly discoveries = new Map<string, Promise<AdvertisedModel[]>>();
23
+ private readonly refreshes = new Map<string, Promise<ConfiguredCatalogModel[]>>();
21
24
  private latestSettings?: ContextSettings;
22
25
 
23
26
  constructor(
@@ -25,14 +28,18 @@ export class CatalogStore {
25
28
  private readonly cleanup: SessionCleanup,
26
29
  private readonly prepareRuntime: () => Promise<void>,
27
30
  private readonly fallbackModels: () => PublicCatalogModel[],
28
- private readonly requireAuth: () => Promise<void> = async () => {},
31
+ private readonly requireAuth: (apiKey?: string) => Promise<void> = async () => {},
29
32
  private readonly createConnection: (options: ConstructorParameters<typeof TierConnection>[0]) => TierConnection =
30
33
  options => new TierConnection(options),
31
34
  ) {}
32
35
 
33
- projectWithSettings(models: PublicCatalogModel[], settings: ContextSettings): ConfiguredCatalogModel[] {
36
+ get hasUpstreamCatalog(): boolean {
37
+ return this.upstreamKnown;
38
+ }
39
+
40
+ projectWithSettings(models: PublicCatalogModel[], settings: ContextSettings, upstreamKnown = true): ConfiguredCatalogModel[] {
34
41
  const projected = this.project(models, settings);
35
- this.install(projected, models, settings);
42
+ this.install(projected, models, settings, upstreamKnown);
36
43
  return projected;
37
44
  }
38
45
 
@@ -54,15 +61,23 @@ export class CatalogStore {
54
61
  });
55
62
  }
56
63
 
57
- private install(models: ConfiguredCatalogModel[], sources: PublicCatalogModel[], settings: ContextSettings) {
64
+ private install(
65
+ models: ConfiguredCatalogModel[],
66
+ sources: PublicCatalogModel[],
67
+ settings: ContextSettings,
68
+ upstreamKnown = true,
69
+ ) {
58
70
  // Publish only after every model validates. Preserve source limits so a
59
71
  // removed override does not inherit the previous projected values.
60
72
  this.sourceModels = sources;
61
73
  this.latestSettings = settings;
62
74
  this.currentModels = models;
63
75
  this.dynamicCache = undefined;
76
+ this.upstreamKnown = upstreamKnown;
64
77
  this.upstreamModels.clear();
65
- for (const model of models) this.upstreamModels.set(model.id, model);
78
+ // Offline fallbacks stay selectable but are not proof that the server
79
+ // advertises them; the first inference must still discover the real catalog.
80
+ if (upstreamKnown) for (const model of models) this.upstreamModels.set(model.id, model);
66
81
  }
67
82
 
68
83
  readCachedCatalog(): AdvertisedModel[] {
@@ -76,7 +91,7 @@ export class CatalogStore {
76
91
  loadInitialOrCached(settings: ContextSettings): ConfiguredCatalogModel[] {
77
92
  const cached = this.readCachedCatalog();
78
93
  const base = cached.length ? projectCatalog(cached) : this.fallbackModels();
79
- this.currentModels = this.projectWithSettings(base, settings);
94
+ this.currentModels = this.projectWithSettings(base, settings, cached.length > 0);
80
95
  return this.currentModels;
81
96
  }
82
97
 
@@ -94,29 +109,34 @@ export class CatalogStore {
94
109
  }
95
110
  const cached = this.readCachedCatalog();
96
111
  const base = cached.length ? projectCatalog(cached) : this.fallbackModels();
97
- const models = this.projectWithSettings(base, settings);
112
+ const models = this.projectWithSettings(base, settings, cached.length > 0);
98
113
  this.dynamicCache = { stamp, settings: settingsKey, models };
99
114
  return models;
100
115
  }
101
116
 
102
117
  reconfigure(settings: ContextSettings): ConfiguredCatalogModel[] {
103
- return this.projectWithSettings(this.sourceModels, settings);
118
+ return this.projectWithSettings(this.sourceModels, settings, this.upstreamKnown);
104
119
  }
105
120
 
106
- async discoverModels(): Promise<AdvertisedModel[]> {
107
- if (this.discovery) return this.discovery;
108
- const pending = this.discoverOnce();
109
- this.discovery = pending;
121
+ async discoverModels(apiKey?: string): Promise<AdvertisedModel[]> {
122
+ const key = usableApiKey(apiKey) ?? "";
123
+ const existing = this.discoveries.get(key);
124
+ if (existing) return existing;
125
+ const pending = this.discoverOnce(apiKey);
126
+ this.discoveries.set(key, pending);
110
127
  try { return await pending; }
111
- finally { if (this.discovery === pending) this.discovery = undefined; }
128
+ finally { if (this.discoveries.get(key) === pending) this.discoveries.delete(key); }
112
129
  }
113
- private async discoverOnce(): Promise<AdvertisedModel[]> {
114
- await this.requireAuth();
130
+ private async discoverOnce(apiKey?: string): Promise<AdvertisedModel[]> {
131
+ await this.requireAuth(apiKey);
115
132
  await this.prepareRuntime();
116
133
  const connection = this.createConnection({ cwd: process.cwd(), ompCleanup: this.cleanup });
117
134
  let discoveredSession: string | undefined;
118
135
  try {
119
- await connection.initialize();
136
+ const initialize = await connection.initialize();
137
+ // An OMP-stored key is validated by the server's own API-key method; the
138
+ // managed marker and absent keys keep the local-login fallback.
139
+ await authenticateForCredential(connection, initialize, apiKey);
120
140
  const session = await connection.newSession(process.cwd());
121
141
  discoveredSession = session.sessionId;
122
142
  const modern = choices(selector(session, "model"));
@@ -145,14 +165,18 @@ export class CatalogStore {
145
165
  }
146
166
  }
147
167
 
148
- async refresh(settings: ContextSettings): Promise<ConfiguredCatalogModel[]> {
168
+ async refresh(settings: ContextSettings, apiKey?: string): Promise<ConfiguredCatalogModel[]> {
149
169
  this.latestSettings = settings;
150
- if (this.refreshing) return this.refreshing;
151
- const pending = this.refreshOnce(); this.refreshing = pending;
152
- try { return await pending; } finally { if (this.refreshing === pending) this.refreshing = undefined; }
170
+ const key = usableApiKey(apiKey) ?? "";
171
+ const existing = this.refreshes.get(key);
172
+ if (existing) return existing;
173
+ const pending = this.refreshOnce(apiKey);
174
+ this.refreshes.set(key, pending);
175
+ try { return await pending; }
176
+ finally { if (this.refreshes.get(key) === pending) this.refreshes.delete(key); }
153
177
  }
154
- private async refreshOnce(): Promise<ConfiguredCatalogModel[]> {
155
- const models = await this.discoverModels();
178
+ private async refreshOnce(apiKey?: string): Promise<ConfiguredCatalogModel[]> {
179
+ const models = await this.discoverModels(apiKey);
156
180
  const sources = projectCatalog(models);
157
181
  const settings = this.latestSettings ?? { defaults: {}, models: {} };
158
182
  const registered = this.project(sources, settings);
@@ -161,7 +185,9 @@ export class CatalogStore {
161
185
  discoveredAt: new Date().toISOString(),
162
186
  models,
163
187
  });
164
- this.install(registered, sources, settings);
188
+ // Discovery succeeded, so this catalog is now upstream-verified even when
189
+ // the cache write above is the only persistence step.
190
+ this.install(registered, sources, settings, true);
165
191
  return registered;
166
192
  }
167
193
  }