omp-antigravity-acp-provider 0.2.2 → 0.3.1

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 (44) hide show
  1. package/AGENT_INSTALL.md +2 -2
  2. package/README.md +13 -13
  3. package/THIRD_PARTY_LICENSES.txt +70 -39
  4. package/extension/acp-compaction.ts +14 -2
  5. package/extension/acp-errors.ts +11 -3
  6. package/extension/adapter-config.ts +1 -1
  7. package/extension/ambient.d.ts +23 -0
  8. package/extension/assets/zip-archive.mjs +10839 -0
  9. package/extension/auth-sync.ts +94 -13
  10. package/extension/commands.ts +13 -16
  11. package/extension/context-settings.ts +2 -2
  12. package/extension/index.ts +74 -38
  13. package/extension/model-catalog.ts +4 -4
  14. package/extension/omp-context.ts +14 -3
  15. package/extension/omp-session-lifecycle.ts +3 -3
  16. package/extension/quota-usage.ts +3 -2
  17. package/extension/runtime/acp/bounded-stream.ts +78 -24
  18. package/extension/runtime/acp/connection.ts +18 -6
  19. package/extension/runtime/binding.ts +2 -2
  20. package/extension/runtime/config.ts +1 -1
  21. package/extension/runtime/managed.ts +2 -1
  22. package/extension/runtime/models.ts +17 -10
  23. package/extension/runtime/prompt.ts +90 -50
  24. package/extension/runtime/provider.ts +39 -11
  25. package/extension/runtime/runtime.ts +75 -45
  26. package/extension/runtime/stream/pi-events.ts +3 -3
  27. package/extension/runtime/tools/bridge.ts +20 -8
  28. package/extension/runtime/tools/relay.ts +2 -2
  29. package/extension/runtime/zip-archive.ts +1 -0
  30. package/extension/runtime.d.mts +1 -0
  31. package/extension/runtime.mjs +18314 -35379
  32. package/extension/secret-service.ts +28 -0
  33. package/extension/selectors.ts +8 -7
  34. package/extension/session-store.ts +7 -7
  35. package/extension/tier-connection.ts +39 -8
  36. package/extension/tool-policy.ts +2 -2
  37. package/extension/tool-relay-protocol.d.mts +5 -0
  38. package/extension/tool-routing.ts +40 -23
  39. package/extension/transcript-routing.ts +16 -3
  40. package/extension/turn-cancellation.ts +1 -1
  41. package/extension/usage-db.ts +42 -22
  42. package/extension/usage.ts +1 -1
  43. package/licenses/{pi-ai-1.3.0.txt → pi-mit.txt} +1 -2
  44. package/package.json +10 -8
@@ -3,6 +3,7 @@ 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 { randomUUID } from "node:crypto";
6
7
  import { clearAntigravityCredentials, inspectAntigravityAuth, resolveAntigravityAcpDirectory } from "./runtime.mjs";
7
8
  import type { AntigravityAuthHealth } from "./runtime/acp/antigravity.ts";
8
9
  import { createSecretService, runSecretTool } from "./secret-service.ts";
@@ -16,7 +17,7 @@ const execFileAsync = promisify(execFile);
16
17
  // parameter so tests can drive a stub executable through the same code path.
17
18
  // Captured stderr is matched in memory only; it is never logged or persisted.
18
19
  export function runSecurity(args: string[], bin = "/usr/bin/security"): Promise<void> {
19
- return execFileAsync(bin, args, { stdio: ["ignore", "ignore", "pipe"], timeout: 3000 }).then(() => undefined);
20
+ return execFileAsync(bin, args, { timeout: 3000 }).then(() => undefined);
20
21
  }
21
22
 
22
23
  // errSecItemNotFound reaches the caller as exit code 44 (OSStatus -25300
@@ -93,14 +94,15 @@ function emailFromTokenJson(raw: string): string | undefined {
93
94
  } catch { return undefined; }
94
95
  }
95
96
 
96
- // The signed-in Google account, from the ACP server's token file only.
97
- // Keychain-stored tokens report no email: reading the macOS keychain secret
98
- // would require the account password on every call, so that path is removed.
99
- export function antigravityAccountEmail(): string | undefined {
97
+ // The signed-in Google account from the ACP token file, then the Linux
98
+ // Secret Service metadata when the file is absent. The keyring payload is
99
+ // parsed only for the non-secret email claim.
100
+ export async function antigravityAccountEmail(): Promise<string | undefined> {
100
101
  try {
101
- return emailFromTokenJson(fs.readFileSync(path.join(resolveAntigravityAcpDirectory(), "acp_token.json"), "utf8"));
102
+ const fileEmail = emailFromTokenJson(fs.readFileSync(path.join(resolveAntigravityAcpDirectory(), "acp_token.json"), "utf8"));
103
+ if (fileEmail) return fileEmail;
102
104
  } catch { /* no token file */ }
103
- return undefined;
105
+ return await secretService.accountEmail?.();
104
106
  }
105
107
 
106
108
  // Timing knobs for following OMP-side logouts; mutable so offline tests can
@@ -212,7 +214,7 @@ export interface OmpCommandContext {
212
214
  // the model registry surface is host version dependent and absent in tests.
213
215
  export function ompCredentialSummary(ctx: OmpCommandContext | undefined) {
214
216
  try {
215
- const stored = ctx?.modelRegistry?.authStorage?.credentials?.getOAuth?.("antigravity-acp");
217
+ const stored = ctx?.modelRegistry?.authStorage?.credentials?.getOAuth?.("antigravity-acp-provider");
216
218
  if (!stored) return { present: false };
217
219
  return {
218
220
  present: true,
@@ -230,9 +232,9 @@ export async function removeOmpCredentialRecord(ctx: OmpCommandContext | undefin
230
232
  try {
231
233
  const credentials = ctx?.modelRegistry?.authStorage?.credentials;
232
234
  if (!credentials?.remove || !credentials.getOAuth) return "unavailable";
233
- if (!credentials.getOAuth("antigravity-acp")) return "absent";
234
- await credentials.remove("antigravity-acp");
235
- try { await ctx?.modelRegistry?.refreshProvider?.("antigravity-acp", "online"); } catch { /* advisory only */ }
235
+ if (!credentials.getOAuth("antigravity-acp-provider")) return "absent";
236
+ await credentials.remove("antigravity-acp-provider");
237
+ try { await ctx?.modelRegistry?.refreshProvider?.("antigravity-acp-provider", "online"); } catch { /* advisory only */ }
236
238
  return "removed";
237
239
  } catch { return "unavailable"; }
238
240
  }
@@ -242,6 +244,7 @@ export interface AuthCoordinatorDeps {
242
244
  on: (name: string, handler: (event: unknown, ctx: OmpCommandContext) => unknown) => void;
243
245
  };
244
246
  connections: Set<TierConnection>;
247
+ stateDir?: string;
245
248
  isPoolBusy: () => boolean;
246
249
  logoutAllRuntimes: () => Promise<void>;
247
250
  closeAllRuntimes: () => Promise<void>;
@@ -294,12 +297,86 @@ export class OmpAuthCoordinator {
294
297
  apiKeyFallback = true;
295
298
  private followTimer: NodeJS.Timeout | undefined;
296
299
  private followRetry: NodeJS.Timeout | undefined;
300
+ private loginLockToken: string | undefined;
297
301
 
298
302
  constructor(private readonly deps: AuthCoordinatorDeps) {}
299
303
 
304
+ private get loginLockPath(): string | undefined {
305
+ return this.deps.stateDir ? path.join(this.deps.stateDir, "login-in-progress.json") : undefined;
306
+ }
307
+
308
+ private isProcessAlive(pid: number): boolean {
309
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
310
+ try { process.kill(pid, 0); return true; }
311
+ catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
312
+ }
313
+
314
+ private readActiveLoginLock(): { pid: number; token: string; startedAt: number } | undefined {
315
+ const file = this.loginLockPath;
316
+ if (!file) return undefined;
317
+ try {
318
+ const raw = JSON.parse(fs.readFileSync(file, "utf8")) as { pid?: unknown; token?: unknown; startedAt?: unknown } | null;
319
+ if (typeof raw?.pid !== "number" || typeof raw?.token !== "string" || typeof raw?.startedAt !== "number") return undefined;
320
+ const age = Date.now() - raw.startedAt;
321
+ if (age > 10 * 60_000 || age < -60_000 || !this.isProcessAlive(raw.pid)) {
322
+ try { fs.rmSync(file, { force: true }); } catch { /* Stale lock cleanup is best effort. */ }
323
+ return undefined;
324
+ }
325
+ return { pid: raw.pid, token: raw.token, startedAt: raw.startedAt };
326
+ } catch {
327
+ return undefined;
328
+ }
329
+ }
330
+
331
+ private acquireLoginLock(): void {
332
+ const file = this.loginLockPath;
333
+ if (!file) return;
334
+ const existing = this.readActiveLoginLock();
335
+ if (existing) {
336
+ if (existing.pid !== process.pid) {
337
+ throw new Error("Another OMP session is already signing in to Antigravity. Complete or cancel that login first.");
338
+ }
339
+ if (this.loginLockToken === existing.token) return;
340
+ try { fs.rmSync(file, { force: true }); } catch { /* Retry the atomic create once. */ }
341
+ }
342
+ const token = randomUUID();
343
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
344
+ for (let attempt = 0; attempt < 2; attempt++) {
345
+ try {
346
+ fs.writeFileSync(file, JSON.stringify({ pid: process.pid, token, startedAt: Date.now() }), { mode: 0o600, flag: "wx" });
347
+ this.loginLockToken = token;
348
+ return;
349
+ } catch (error) {
350
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
351
+ const active = this.readActiveLoginLock();
352
+ if (active && active.pid !== process.pid) {
353
+ throw new Error("Another OMP session is already signing in to Antigravity. Complete or cancel that login first.");
354
+ }
355
+ if (active && active.pid === process.pid && active.token === this.loginLockToken) return;
356
+ try { fs.rmSync(file, { force: true }); } catch { /* Retry the atomic create once. */ }
357
+ }
358
+ }
359
+ throw new Error("Unable to acquire the Antigravity login lock.");
360
+ }
361
+
362
+ private endFreshGoogleLogin(): void {
363
+ const file = this.loginLockPath;
364
+ const token = this.loginLockToken;
365
+ this.loginLockToken = undefined;
366
+ if (!file || !token) return;
367
+ try {
368
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as { token?: unknown } | null;
369
+ if (parsed?.token === token) fs.rmSync(file, { force: true });
370
+ } catch { /* Already cleared or inaccessible. */ }
371
+ }
372
+
373
+ releaseContext(ctx?: OmpCommandContext): void {
374
+ if (!ctx || this.activeContext === ctx) this.activeContext = undefined;
375
+ }
376
+
300
377
  ompMarkerStored(ctx: OmpCommandContext | undefined): boolean | undefined {
301
378
  try {
302
- return Boolean(ctx?.modelRegistry?.authStorage?.credentials?.getOAuth?.("antigravity-acp"));
379
+ return Boolean(ctx?.modelRegistry?.authStorage?.credentials?.getOAuth?.("antigravity-acp-provider"));
303
380
  } catch { return undefined; }
304
381
  }
305
382
 
@@ -346,6 +423,7 @@ export class OmpAuthCoordinator {
346
423
  this.followTimer = undefined;
347
424
  clearTimeout(this.followRetry);
348
425
  this.followRetry = undefined;
426
+ this.endFreshGoogleLogin();
349
427
  if (!this.apiKeyFallback) {
350
428
  this.apiKeyFallback = true;
351
429
  this.deps.onSyncProvider();
@@ -358,6 +436,7 @@ export class OmpAuthCoordinator {
358
436
  this.baseSuppressFollow = false;
359
437
  clearTimeout(this.followTimer);
360
438
  this.followTimer = undefined;
439
+ this.endFreshGoogleLogin();
361
440
  this.restoreApiKeyFallback(this.activeContext);
362
441
  }
363
442
 
@@ -373,6 +452,7 @@ export class OmpAuthCoordinator {
373
452
  if (this.deps.isPoolBusy()) {
374
453
  throw new Error("Wait for active Antigravity requests to finish before logging in.");
375
454
  }
455
+ this.acquireLoginLock();
376
456
  // OMP removes the stale marker while the browser sign-in is still running.
377
457
  // That generation change must not be mistaken for a user logout and close
378
458
  // the new ACP runtime before the login can finish, so suppress it before
@@ -408,6 +488,7 @@ export class OmpAuthCoordinator {
408
488
  if (this.activeLogins.delete(attempt) && this.activeLogins.size === 0) {
409
489
  this.suppressFollow = this.baseSuppressFollow || performance.now() < this.disabledUntil;
410
490
  this.baseSuppressFollow = false;
491
+ this.endFreshGoogleLogin();
411
492
  }
412
493
  throw error;
413
494
  }
@@ -500,7 +581,7 @@ export class OmpAuthCoordinator {
500
581
  // destroy the Antigravity-side login. OMP emits credential_disabled for
501
582
  // those, but not for user-initiated removals such as /logout.
502
583
  this.deps.pi.on("credential_disabled", (event: unknown) => {
503
- if (event && typeof event === "object" && "provider" in event && event.provider === "antigravity-acp") {
584
+ if (event && typeof event === "object" && "provider" in event && event.provider === "antigravity-acp-provider") {
504
585
  this.disabledUntil = performance.now() + logoutFollow.disabledSuppressionMs;
505
586
  this.suppressFollow = true;
506
587
  }
@@ -7,6 +7,10 @@ import { DEFAULT_USAGE_MODE, updateContextSettings, resolveContextOptions, saveC
7
7
  import type { CatalogStore, ConfiguredCatalogModel } from "./catalog-store.ts";
8
8
  import type { SessionCleanup, CleanupMode } from "./session-cleanup.ts";
9
9
  import type { TierConnection } from "./tier-connection.ts";
10
+ import type { AssistantMessageEvent, Context, TranscriptContext } from "@earendil-works/pi-ai";
11
+ import type { PermissionMode } from "./runtime/config.ts";
12
+ import type { AntigravityModel } from "./runtime/models.ts";
13
+ import type { OmpStreamOptions } from "./runtime/runtime.ts";
10
14
 
11
15
  export interface RuntimeSnapshotProcess {
12
16
  mcpHttp: boolean;
@@ -29,20 +33,13 @@ export interface RuntimeSnapshotView {
29
33
  processes: RuntimeSnapshotProcess[];
30
34
  }
31
35
 
32
- export interface StreamUsageLike { input?: unknown; output?: unknown; cacheRead?: unknown; cost?: unknown }
33
- export interface StreamEventLike {
34
- message?: { usage?: StreamUsageLike; timestamp?: number };
35
- partial?: { usage?: StreamUsageLike; timestamp?: number };
36
- }
37
-
38
36
  export interface RuntimeBundleView {
39
37
  runtime: {
40
38
  snapshot: () => Promise<RuntimeSnapshotView>;
41
- setPermissionMode: (mode: string) => Promise<void>;
39
+ setPermissionMode: (mode: PermissionMode) => Promise<void>;
42
40
  logout: () => Promise<void>;
43
41
  close: () => Promise<void>;
44
42
  getPermission: (requestId: string) => { id: string; title: string; options: Array<{ id?: string; label: string }> } | undefined;
45
- sessionStore?: { read: () => unknown[]; clear: () => void };
46
43
  };
47
44
  provider: {
48
45
  auth: {
@@ -51,11 +48,11 @@ export interface RuntimeBundleView {
51
48
  signal?: AbortSignal;
52
49
  notify: (event: { message?: string; links?: Array<{ url: string }> }) => void;
53
50
  prompt: (request: { message: string; placeholder?: string }) => Promise<string>;
54
- }) => Promise<unknown>;
51
+ }) => Promise<Record<string, unknown>>;
55
52
  refresh: (credentials: unknown) => Promise<unknown>;
56
53
  };
57
54
  };
58
- streamSimple: (model: { id: string }, context: unknown, options?: unknown) => AsyncIterable<StreamEventLike>;
55
+ streamSimple(model: AntigravityModel, context: Context | TranscriptContext, options?: OmpStreamOptions): AsyncIterable<AssistantMessageEvent>;
59
56
  };
60
57
  isBusy: () => boolean;
61
58
  }
@@ -154,8 +151,8 @@ const SUBCOMMANDS: SubcommandSpec[] = [
154
151
  {
155
152
  name: "native-tools",
156
153
  description: "Native ACP tool exposure",
157
- usage: "prefer|disabled",
158
- values: [["prefer", "Let OMP tools shadow ACP natives (default)"], ["disabled", "Disable ACP-native tools for strict OMP-tool sessions"]],
154
+ usage: "disabled|prefer",
155
+ values: [["disabled", "Disable ACP-native tools for strict OMP-tool sessions (default)"], ["prefer", "Let OMP tools shadow ACP natives"]],
159
156
  },
160
157
  {
161
158
  name: "permissions",
@@ -398,7 +395,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
398
395
  }
399
396
 
400
397
  if (command === "native-tools") {
401
- if (parts.length !== 2) throw new Error("Usage: /antigravity-acp native-tools prefer|disabled");
398
+ if (parts.length !== 2) throw new Error("Usage: /antigravity-acp native-tools disabled|prefer");
402
399
  const mode: NativeToolMode = parseNativeToolMode(value);
403
400
  const next = { ...deps.getToolPolicy(), nativeTools: mode };
404
401
  saveToolPolicy(deps.toolPolicyPath, next);
@@ -440,7 +437,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
440
437
  throw error;
441
438
  }
442
439
  const auth = await inspectAcpAuth();
443
- const email = antigravityAccountEmail();
440
+ const email = await antigravityAccountEmail();
444
441
  ctx.ui.notify(`Antigravity Google login finished${email ? ` as ${email}` : ""} — fresh sign-in; ACP auth: ${auth.status}${auth.authType ? ` (${auth.authType})` : ""}.`, "info");
445
442
  return;
446
443
  }
@@ -457,14 +454,14 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
457
454
  if (value) throw new Error("Usage: /antigravity-acp account");
458
455
  const auth = await inspectAcpAuth();
459
456
  let ompSource: string | undefined;
460
- try { ompSource = ctx?.modelRegistry?.authStorage?.keys?.describe?.("antigravity-acp", sessionIdOf(ctx)); } catch { /* host version dependent */ }
457
+ try { ompSource = ctx?.modelRegistry?.authStorage?.keys?.describe?.("antigravity-acp-provider", sessionIdOf(ctx)); } catch { /* host version dependent */ }
461
458
  // Reading saved state needs no live runtime; show live numbers only
462
459
  // when a runtime for this session already exists.
463
460
  const bundle = deps.peekRuntimeForSession(sessionIdOf(ctx));
464
461
  const snapshot = await bundle?.runtime.snapshot();
465
462
  const permissionMode = deps.getPermissionMode();
466
463
  const omp = ompCredentialSummary(ctx);
467
- const accountEmail = antigravityAccountEmail();
464
+ const accountEmail = await antigravityAccountEmail();
468
465
  const googleAccount = accountEmail
469
466
  ?? (auth.keyring === true ? "signed in · system keyring entry; email unavailable"
470
467
  : (await keychain.present()) === true ? "signed in · keychain token; email unavailable"
@@ -55,9 +55,9 @@ export function saveContextSettings(file: string, settings: ContextSettings) {
55
55
  export function updateContextSettings(settings: ContextSettings, target: string, key: string, value: number | string): ContextSettings {
56
56
  if (["__proto__", "constructor", "prototype"].includes(target)) throw new Error("Invalid model ID");
57
57
  const next = structuredClone(settings);
58
- const options: Record<string, unknown> = target === "default" ? next.defaults
58
+ const options: ContextOptions = target === "default" ? next.defaults
59
59
  : Object.hasOwn(next.models, target) ? next.models[target]! : (next.models[target] = {});
60
- options[key] = value;
60
+ Reflect.set(options, key, value);
61
61
  validate(options, target === "default");
62
62
  return next;
63
63
  }
@@ -22,7 +22,8 @@ import { ownerRoutingId, sessionOwnerId } from "./runtime/routing.ts";
22
22
  import { createStructuredFingerprintMemo } from "./runtime/binding.ts";
23
23
  import { Diagnostics, instrumentRuntime } from "./diagnostics.ts";
24
24
  import { stableTools } from "./tool-order.ts";
25
- import { toolDeclarations, normalizeOmpSystemDeltas, type OmpToolDeclaration } from "./omp-context.ts";
25
+ import type { Context, Message, Tool } from "@earendil-works/pi-ai";
26
+ import { toolDeclarations, normalizeOmpSystemDeltas } from "./omp-context.ts";
26
27
  import { OmpSessionLifecycle, type OmpProviderSessionState } from "./omp-session-lifecycle.ts";
27
28
  import { DEFAULT_USAGE_MODE, loadContextSettings, type ContextSettings } from "./context-settings.ts";
28
29
  import { PARTNER_FALLBACK_MODELS, projectCatalog, selectRuntimeModel, type PublicCatalogModel } from "./model-catalog.ts";
@@ -93,7 +94,7 @@ export function resolveAdapterStateDir(env: NodeJS.ProcessEnv = process.env, hom
93
94
  // CatalogStore marks these entries as unverified until a real refresh lands.
94
95
  export function offlineFallbackModels(): PublicCatalogModel[] {
95
96
  return [
96
- ...(FALLBACK_MODELS as PublicCatalogModel[]),
97
+ ...FALLBACK_MODELS,
97
98
  ...projectCatalog([
98
99
  { modelId: "gemini-4-argon-low", name: "Gemini 4 Argon (low)" },
99
100
  { modelId: "gemini-4-argon-medium", name: "Gemini 4 Argon (medium)" },
@@ -169,7 +170,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
169
170
  usageMode: legacyContextSettings.defaults.usageMode,
170
171
  diagnostics: legacyDiagnostics.status().enabled,
171
172
  });
172
- let contextSettings = {
173
+ let contextSettings: ContextSettings = {
173
174
  ...legacyContextSettings,
174
175
  defaults: { ...legacyContextSettings.defaults, usageMode: adapterConfig.usageMode },
175
176
  };
@@ -242,7 +243,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
242
243
  if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 0 || idleTimeoutMs > 2_147_483_647 || (idleTimeoutMs > 0 && idleTimeoutMs < 1000)) {
243
244
  throw new Error("OMP_ACP_IDLE_TIMEOUT_MS must be 0 (disabled) or an integer between 1000 and 2147483647");
244
245
  }
245
- const maxIdleEntries = Number(process.env.OMP_ACP_MAX_IDLE_RUNTIMES ?? 2);
246
+ const maxIdleEntries = Number(process.env.OMP_ACP_MAX_IDLE_RUNTIMES ?? 1);
246
247
  if (!Number.isSafeInteger(maxIdleEntries) || maxIdleEntries < 0) throw new Error("OMP_ACP_MAX_IDLE_RUNTIMES must be a nonnegative integer (0 disables the cap)");
247
248
  const toolProjectionMemo = createStructuredFingerprintMemo();
248
249
  let toolRevision = 0;
@@ -250,17 +251,19 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
250
251
  let lastToolAudit: ToolAuditSummary | undefined;
251
252
  let cachedToolProjection: {
252
253
  revision: string;
253
- tools: OmpToolDeclaration[];
254
+ tools: Tool[];
254
255
  audit: ToolAuditSummary;
255
256
  } | undefined;
256
257
 
257
258
  // A spawn is described once so warmup and a real request can compare the
258
259
  // exact target, cwd, permission process flag and tool policy before a
259
260
  // standby is reused.
260
- function prepareSpawn(options: ConstructorParameters<typeof TierConnection>[0]): {
261
+ interface PreparedSpawn {
261
262
  options: ConstructorParameters<typeof TierConnection>[0];
262
263
  signature: WarmupSignature;
263
- } {
264
+ }
265
+
266
+ function prepareSpawn(options: ConstructorParameters<typeof TierConnection>[0]): PreparedSpawn {
264
267
  const profile = currentPermissionProfile();
265
268
  const env = ensureLoopbackBypass({
266
269
  ...process.env,
@@ -321,7 +324,16 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
321
324
  // adapter opt-in there; production uses the default factory and the env flag.
322
325
  const warmupEnabled = warmupSetting()
323
326
  && (createConnection === defaultConnectionFactory || options.warmup === true);
324
- let warmupStandby: { connection: TierConnection; signature: WarmupSignature } | undefined;
327
+ interface WarmupStandby {
328
+ connection: TierConnection;
329
+ signature: WarmupSignature;
330
+ idleTimer?: NodeJS.Timeout;
331
+ }
332
+ const standbyTtlMs = Number(process.env.OMP_ACP_STANDBY_TTL_MS ?? 300_000);
333
+ if (!Number.isSafeInteger(standbyTtlMs) || standbyTtlMs < 0 || standbyTtlMs > 2_147_483_647) {
334
+ throw new Error("OMP_ACP_STANDBY_TTL_MS must be 0 or an integer between 1 and 2147483647");
335
+ }
336
+ let warmupStandby: WarmupStandby | undefined;
325
337
  let warmupTask: Promise<void> | undefined;
326
338
  let warmupTaskKey: string | undefined;
327
339
  let warmupStarting: TierConnection | undefined;
@@ -371,6 +383,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
371
383
  if (starting) void closeWarmupConnection(starting);
372
384
  const ready = warmupStandby;
373
385
  warmupStandby = undefined;
386
+ if (ready?.idleTimer) clearTimeout(ready.idleTimer);
374
387
  if (ready) void closeWarmupConnection(ready.connection);
375
388
  }
376
389
 
@@ -384,7 +397,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
384
397
  // never duplicates a discovery or install already in flight.
385
398
  await prepareRuntime();
386
399
  if (stale()) return;
387
- let prepared: ReturnType<typeof prepareSpawn>;
400
+ let prepared: PreparedSpawn;
388
401
  try {
389
402
  prepared = prepareSpawn({ cwd: process.cwd() });
390
403
  } catch {
@@ -415,12 +428,27 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
415
428
  await closeWarmupConnection(connection);
416
429
  return;
417
430
  }
418
- warmupStandby = { connection, signature: prepared.signature };
431
+ const entry: WarmupStandby = { connection, signature: prepared.signature };
432
+ warmupStandby = entry;
433
+ if (standbyTtlMs > 0) {
434
+ entry.idleTimer = setTimeout(() => {
435
+ if (warmupStandby !== entry) return;
436
+ warmupStandby = undefined;
437
+ void closeWarmupConnection(entry.connection);
438
+ }, standbyTtlMs);
439
+ entry.idleTimer.unref?.();
440
+ }
441
+ void connection.process?.exited.finally(() => {
442
+ if (entry.idleTimer) clearTimeout(entry.idleTimer);
443
+ entry.idleTimer = undefined;
444
+ if (warmupStandby === entry) warmupStandby = undefined;
445
+ });
419
446
  } catch { /* Warmup is best effort; the cold path remains available. */ }
420
447
  }
421
448
 
422
449
  function startWarmup(): void {
423
450
  if (!warmupEnabled) return;
451
+ if (connections.size > 0 || runtimes.values().length > 0) return;
424
452
  const key = currentWarmupKey();
425
453
  if (warmupStandby && warmupKeyOf(warmupStandby.signature) === key) return;
426
454
  if (warmupTask && warmupTaskKey === key) return;
@@ -450,10 +478,12 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
450
478
  if (!ready || handlers === undefined) return undefined;
451
479
  if (!sameWarmupSignature(ready.signature, signature) || ready.connection.process?.alive === false
452
480
  || typeof ready.connection.rebindHandlers !== "function") {
481
+ if (ready.idleTimer) clearTimeout(ready.idleTimer);
453
482
  warmupStandby = undefined;
454
483
  void closeWarmupConnection(ready.connection);
455
484
  return undefined;
456
485
  }
486
+ if (ready.idleTimer) clearTimeout(ready.idleTimer);
457
487
  warmupStandby = undefined;
458
488
  ready.connection.rebindHandlers(handlers);
459
489
  return ready.connection;
@@ -487,10 +517,10 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
487
517
 
488
518
  // A side routing id shares its parent's runtime entry, so a new one-shot id
489
519
  // never spawns a fresh process. Only a full owner close tears it down.
490
- const lifecycle = new OmpSessionLifecycle(id => runtimes.close(ownerRoutingId(id)), async id => {
520
+ const lifecycle: OmpSessionLifecycle = new OmpSessionLifecycle(id => runtimes.close(ownerRoutingId(id)), async id => {
491
521
  if (id) await cleanup.releaseSession(id);
492
522
  }, ownerRoutingId);
493
- const runtimes = new SessionRuntimePool<RuntimeBundleView>(() => {
523
+ const runtimes: SessionRuntimePool<RuntimeBundleView> = new SessionRuntimePool<RuntimeBundleView>(() => {
494
524
  const ownedConnections = new Set<TierConnection>();
495
525
  const runtime = new AntigravityRuntime((options: ConstructorParameters<typeof TierConnection>[0]) => {
496
526
  const requested = {
@@ -531,6 +561,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
531
561
  const sessionIdOf = (ctx: OmpCommandContext | undefined): string | undefined => ctx?.sessionManager?.getSessionId?.();
532
562
  pi.on("session_shutdown", async (_event: unknown, ctx: OmpCommandContext) => {
533
563
  const failures: unknown[] = [];
564
+ auth.releaseContext(ctx);
534
565
  const sessionId = sessionIdOf(ctx);
535
566
  if (sessionId) {
536
567
  const routingId = routing.forget(sessionId, ctx?.sessionManager?.getSessionFile?.());
@@ -555,13 +586,14 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
555
586
  // Re-registering without an apiKey does not clear OMP's stored key
556
587
  // config; unregister first so a logout report finds no remaining
557
588
  // "provider config (fallback)" source.
558
- try { pi.unregisterProvider?.("antigravity-acp"); } catch { /* older hosts */ }
559
- try { adapted.registerProvider(); } catch { /* advisory */ }
589
+ try { pi.unregisterProvider?.("antigravity-acp-provider"); } catch { /* older hosts */ }
590
+ tryRegisterProvider();
560
591
  }
561
592
 
562
593
  const auth = new OmpAuthCoordinator({
563
594
  pi,
564
595
  connections,
596
+ stateDir,
565
597
  isPoolBusy: () => runtimes.values().some(bundle => bundle.isBusy()),
566
598
  logoutAllRuntimes: async () => {
567
599
  await Promise.all(runtimes.values().map(bundle => bundle.runtime.logout()));
@@ -608,13 +640,14 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
608
640
  const handleSourceTransition = async (event: unknown, ctx: OmpCommandContext) => {
609
641
  routing.clearPending();
610
642
  const transcriptId = sessionIdOf(ctx), file = ctx.sessionManager?.getSessionFile?.();
611
- const reason: unknown = typeof event === "object" && event !== null ? Reflect.get(event, "reason") : undefined;
643
+ const eventRecord = typeof event === "object" && event !== null ? event : undefined;
644
+ const reason: unknown = eventRecord ? Reflect.get(eventRecord, "reason") : undefined;
612
645
  if ((reason === "new" || reason === "resume" || reason === "fork" || reason === "branch" || reason === "btw")
613
646
  && !transcriptId?.includes(":side:")) {
614
647
  if (!transcriptId || !file) {
615
648
  routing.invalidateUnknownSource();
616
649
  } else {
617
- const candidate: unknown = Reflect.get(event, "previousSessionFile");
650
+ const candidate: unknown = eventRecord ? Reflect.get(eventRecord, "previousSessionFile") : undefined;
618
651
  const previousFile = typeof candidate === "string" ? candidate : undefined;
619
652
  const previousTranscriptId = previousFile ? await sourceId(previousFile).catch(() => undefined) : undefined;
620
653
  routing.noteSourceSwitch(reason, transcriptId, file, previousTranscriptId, previousFile);
@@ -674,13 +707,14 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
674
707
  const modelRecord = typeof model === "object" && model !== null ? model : undefined;
675
708
  const provider = Reflect.get(event, "provider") ?? Reflect.get(event, "providerId")
676
709
  ?? (modelRecord ? Reflect.get(modelRecord, "provider") ?? Reflect.get(modelRecord, "api") : undefined);
677
- if (typeof provider === "string" && provider.length > 0) return provider === "antigravity-acp";
710
+ if (typeof provider === "string" && provider.length > 0) return provider === "antigravity-acp-provider";
678
711
  const id = Reflect.get(event, "modelId") ?? (modelRecord ? Reflect.get(modelRecord, "id") : undefined);
679
712
  return typeof id === "string"
680
713
  && (catalogStore.upstreamModels.has(id) || catalogStore.currentModels.some(candidate => candidate.id === id));
681
714
  };
682
715
  pi.on("model_select", (event: unknown) => {
683
716
  if (isAntigravitySelection(event)) requestWarmup();
717
+ else invalidateWarmup();
684
718
  });
685
719
 
686
720
  async function loadQuotaSnapshot(signal?: AbortSignal): Promise<AntigravityQuotaSnapshot | undefined> {
@@ -743,20 +777,23 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
743
777
  closeAllRuntimes: closePool,
744
778
  onModelsUpdated: models => {
745
779
  initialModels = models;
746
- adapted.registerProvider();
780
+ registerProvider();
747
781
  },
748
782
  }),
749
783
  getArgumentCompletions: createAntigravityArgumentCompletions({ catalog: catalogStore }),
750
784
  });
751
785
 
752
- const adapted = new Proxy(pi, {
753
- get(target, key) {
754
- if (key !== "registerProvider") {
755
- const value = Reflect.get(target, key);
756
- return typeof value === "function" ? value.bind(target) : value;
757
- }
758
- return () => target.registerProvider("antigravity-acp", {
759
- api: "antigravity-acp",
786
+ function tryRegisterProvider(): void {
787
+ try {
788
+ registerProvider();
789
+ } catch {
790
+ return;
791
+ }
792
+ }
793
+
794
+ function registerProvider(): void {
795
+ pi.registerProvider("antigravity-acp-provider", {
796
+ api: "antigravity-acp-provider",
760
797
  baseUrl: "acp://antigravity",
761
798
  // A config apiKey keeps OMP's own logout report claiming a remaining
762
799
  // "provider config (fallback)" source, but dropping it entirely hides
@@ -772,11 +809,11 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
772
809
  },
773
810
  streamSimple(
774
811
  model: { id: string },
775
- context: { tools?: OmpToolDeclaration[]; systemPrompt?: string | string[]; messages: unknown[] },
812
+ context: { tools?: Tool[]; systemPrompt?: string | string[]; messages: Message[] },
776
813
  options?: { apiKey?: string; sessionId?: string; parentSessionId?: string; promptCacheKey?: string; reasoning?: string; signal?: AbortSignal; providerSessionState?: Map<string, OmpProviderSessionState> },
777
814
  ) {
778
815
  const inputTools = toolDeclarations(context.tools ?? []);
779
- let tools: OmpToolDeclaration[];
816
+ let tools: Tool[];
780
817
  const cached = cachedToolProjection;
781
818
  const revision = toolProjectionMemo(inputTools, () => String(++toolRevision));
782
819
  // Validate live definitions, including mutation of the same array.
@@ -796,7 +833,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
796
833
  };
797
834
  cachedToolProjection = { revision, tools, audit: lastToolAudit };
798
835
  }
799
- const routedContext = {
836
+ const routedContext: Context = {
800
837
  ...context,
801
838
  tools,
802
839
  messages: normalizeOmpSystemDeltas(context.messages),
@@ -832,7 +869,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
832
869
  // of only filling the lookup map; otherwise the model selector
833
870
  // keeps the offline effort list until the next restart.
834
871
  initialModels = await catalogStore.refresh(contextSettings, options?.apiKey);
835
- try { adapted.registerProvider(); } catch { /* advisory */ }
872
+ tryRegisterProvider();
836
873
  }
837
874
  if (options?.signal?.aborted) throw new Error("ACP request cancelled during startup");
838
875
  const original = catalogStore.upstreamModels.get(model.id);
@@ -845,7 +882,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
845
882
  await runtime.setPermissionMode(currentPermissionProfile().wireMode);
846
883
  const stream = provider.streamSimple(selectRuntimeModel(original, options?.reasoning), routedContext, { ...options, sessionId: routingId });
847
884
  for await (const event of stream) {
848
- const message = event.message ?? event.partial;
885
+ const message = "message" in event ? event.message : "partial" in event ? event.partial : undefined;
849
886
  if (message?.usage) applyApiCostEstimate(model.id, message.usage, message.timestamp ?? Date.now());
850
887
  deferred.stream.push(event);
851
888
  }
@@ -890,12 +927,12 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
890
927
  for (const link of event.links) callbacks.onAuth({ url: link.url, instructions: event.message });
891
928
  } else callbacks.onProgress?.(event.message);
892
929
  },
893
- prompt: (request: { message: string; placeholder: string }) => callbacks.onPrompt({ message: request.message, placeholder: request.placeholder }),
930
+ prompt: (request: { message: string; placeholder?: string }) => callbacks.onPrompt({ message: request.message, placeholder: request.placeholder }),
894
931
  });
895
932
  auth.noteLoginSucceeded(loginAttempt);
896
933
  // Record the signed-in account on the marker credential so OMP's
897
934
  // account list can label it; the email is identity data, not a secret.
898
- const email = antigravityAccountEmail();
935
+ const email = await antigravityAccountEmail();
899
936
  return email ? { ...result, email } : result;
900
937
  } finally {
901
938
  lease.release();
@@ -918,10 +955,9 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
918
955
  },
919
956
  getApiKey: () => MARKER,
920
957
  },
921
- });
922
- },
923
- });
924
- adapted.registerProvider();
958
+ });
959
+ }
960
+ registerProvider();
925
961
 
926
962
  let startupRefresh: Promise<void> | undefined;
927
963
  refreshModelsOnStartup = () => {
@@ -931,7 +967,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
931
967
  startupRefresh = catalogStore.refresh(contextSettings)
932
968
  .then(models => {
933
969
  initialModels = models;
934
- adapted.registerProvider();
970
+ registerProvider();
935
971
  })
936
972
  .catch(() => { /* Keep the cached catalog. */ });
937
973
  return startupRefresh;
@@ -11,15 +11,15 @@ export interface AdvertisedModel {
11
11
  export interface PublicCatalogModel {
12
12
  id: string;
13
13
  name: string;
14
- api: "antigravity-acp";
15
- provider: "antigravity-acp";
14
+ api: "antigravity-acp-provider";
15
+ provider: "antigravity-acp-provider";
16
16
  baseUrl?: string;
17
17
  reasoning: boolean;
18
18
  input: string[];
19
19
  contextWindow: number;
20
20
  maxTokens: number;
21
21
  cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
22
- thinkingLevelMap?: Record<string, string | null>;
22
+ thinkingLevelMap?: Partial<Record<string, string | null>>;
23
23
  thinking?: { mode: "effort"; efforts: string[]; defaultLevel?: string };
24
24
  }
25
25
  const ROUTE_PREFIX = "__omp_acp_thought__:";
@@ -96,7 +96,7 @@ function publicModel(id: string, name: string, map: Record<string, string> = {},
96
96
  const defaultLevel = current && (efforts as readonly string[]).includes(current) ? current
97
97
  : efforts.includes("high") ? "high" : efforts.includes("medium") ? "medium" : efforts[0];
98
98
  return {
99
- id, name, api: "antigravity-acp", provider: "antigravity-acp", baseUrl: "",
99
+ id, name, api: "antigravity-acp-provider", provider: "antigravity-acp-provider", baseUrl: "",
100
100
  reasoning: efforts.length > 0, input: ["text", "image"],
101
101
  // These are conservative client metadata defaults, not inferred server limits.
102
102
  contextWindow: known?.contextWindow ?? 32_768,