omp-antigravity-acp-provider 0.2.2 → 0.2.4
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 +9 -11
- package/THIRD_PARTY_LICENSES.txt +70 -39
- package/extension/acp-compaction.ts +14 -2
- package/extension/acp-errors.ts +11 -3
- package/extension/adapter-config.ts +1 -1
- package/extension/ambient.d.ts +23 -0
- package/extension/assets/zip-archive.mjs +10839 -0
- package/extension/auth-sync.ts +88 -7
- package/extension/commands.ts +12 -15
- package/extension/context-settings.ts +2 -2
- package/extension/index.ts +71 -35
- package/extension/model-catalog.ts +1 -1
- package/extension/omp-context.ts +14 -3
- package/extension/quota-usage.ts +2 -1
- package/extension/runtime/acp/bounded-stream.ts +78 -24
- package/extension/runtime/acp/connection.ts +18 -6
- package/extension/runtime/binding.ts +2 -2
- package/extension/runtime/config.ts +1 -1
- package/extension/runtime/managed.ts +2 -1
- package/extension/runtime/models.ts +15 -8
- package/extension/runtime/prompt.ts +90 -50
- package/extension/runtime/provider.ts +38 -10
- package/extension/runtime/runtime.ts +74 -44
- package/extension/runtime/stream/pi-events.ts +3 -3
- package/extension/runtime/tools/bridge.ts +20 -8
- package/extension/runtime/tools/relay.ts +2 -2
- package/extension/runtime/zip-archive.ts +1 -0
- package/extension/runtime.d.mts +1 -0
- package/extension/runtime.mjs +18311 -35376
- package/extension/secret-service.ts +28 -0
- package/extension/selectors.ts +8 -7
- package/extension/session-store.ts +7 -7
- package/extension/tier-connection.ts +39 -8
- package/extension/tool-policy.ts +2 -2
- package/extension/tool-relay-protocol.d.mts +5 -0
- package/extension/tool-routing.ts +40 -23
- package/extension/transcript-routing.ts +16 -3
- package/extension/turn-cancellation.ts +1 -1
- package/extension/usage-db.ts +42 -22
- package/extension/usage.ts +1 -1
- package/licenses/{pi-ai-1.3.0.txt → pi-mit.txt} +1 -2
- package/package.json +10 -8
package/extension/auth-sync.ts
CHANGED
|
@@ -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, {
|
|
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
|
|
97
|
-
//
|
|
98
|
-
//
|
|
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
|
-
|
|
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
|
|
105
|
+
return await secretService.accountEmail?.();
|
|
104
106
|
}
|
|
105
107
|
|
|
106
108
|
// Timing knobs for following OMP-side logouts; mutable so offline tests can
|
|
@@ -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,9 +297,83 @@ 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
379
|
return Boolean(ctx?.modelRegistry?.authStorage?.credentials?.getOAuth?.("antigravity-acp"));
|
|
@@ -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
|
}
|
package/extension/commands.ts
CHANGED
|
@@ -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:
|
|
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
|
|
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
|
|
158
|
-
values: [["
|
|
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
|
|
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
|
}
|
|
@@ -464,7 +461,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
|
|
|
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:
|
|
58
|
+
const options: ContextOptions = target === "default" ? next.defaults
|
|
59
59
|
: Object.hasOwn(next.models, target) ? next.models[target]! : (next.models[target] = {});
|
|
60
|
-
options
|
|
60
|
+
Reflect.set(options, key, value);
|
|
61
61
|
validate(options, target === "default");
|
|
62
62
|
return next;
|
|
63
63
|
}
|
package/extension/index.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
...
|
|
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 ??
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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?.());
|
|
@@ -556,12 +587,13 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
|
|
|
556
587
|
// config; unregister first so a logout report finds no remaining
|
|
557
588
|
// "provider config (fallback)" source.
|
|
558
589
|
try { pi.unregisterProvider?.("antigravity-acp"); } catch { /* older hosts */ }
|
|
559
|
-
|
|
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
|
|
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(
|
|
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);
|
|
@@ -681,6 +714,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
|
|
|
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,19 +777,22 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
|
|
|
743
777
|
closeAllRuntimes: closePool,
|
|
744
778
|
onModelsUpdated: models => {
|
|
745
779
|
initialModels = models;
|
|
746
|
-
|
|
780
|
+
registerProvider();
|
|
747
781
|
},
|
|
748
782
|
}),
|
|
749
783
|
getArgumentCompletions: createAntigravityArgumentCompletions({ catalog: catalogStore }),
|
|
750
784
|
});
|
|
751
785
|
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
786
|
+
function tryRegisterProvider(): void {
|
|
787
|
+
try {
|
|
788
|
+
registerProvider();
|
|
789
|
+
} catch {
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function registerProvider(): void {
|
|
795
|
+
pi.registerProvider("antigravity-acp", {
|
|
759
796
|
api: "antigravity-acp",
|
|
760
797
|
baseUrl: "acp://antigravity",
|
|
761
798
|
// A config apiKey keeps OMP's own logout report claiming a remaining
|
|
@@ -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?:
|
|
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:
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
970
|
+
registerProvider();
|
|
935
971
|
})
|
|
936
972
|
.catch(() => { /* Keep the cached catalog. */ });
|
|
937
973
|
return startupRefresh;
|
|
@@ -19,7 +19,7 @@ export interface PublicCatalogModel {
|
|
|
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__:";
|
package/extension/omp-context.ts
CHANGED
|
@@ -1,22 +1,33 @@
|
|
|
1
|
+
import type { Message, Tool } from "@earendil-works/pi-ai";
|
|
2
|
+
|
|
1
3
|
export interface OmpToolDeclaration { name: string; description?: string; parameters?: unknown }
|
|
2
4
|
|
|
3
5
|
// OMP tools may be live AgentTool wrappers containing the entire session host,
|
|
4
6
|
// counters, executable closures and cycles. ACP bridges declarations only;
|
|
5
7
|
// tool execution still returns through OMP's own tool loop.
|
|
8
|
+
export function toolDeclarations(tools: readonly Tool[]): Tool[];
|
|
9
|
+
export function toolDeclarations(tools: readonly OmpToolDeclaration[]): OmpToolDeclaration[];
|
|
6
10
|
export function toolDeclarations(tools: readonly OmpToolDeclaration[]): OmpToolDeclaration[] {
|
|
7
11
|
return tools.map(tool => ({ name: tool.name, description: tool.description, parameters: tool.parameters }));
|
|
8
12
|
}
|
|
9
13
|
|
|
14
|
+
export function normalizeOmpSystemDeltas(messages: Message[]): Message[];
|
|
15
|
+
export function normalizeOmpSystemDeltas(messages: unknown[]): unknown[];
|
|
10
16
|
export function normalizeOmpSystemDeltas(messages: unknown[]): unknown[] {
|
|
11
17
|
if (!messages.some(message => message && typeof message === "object" && "role" in message && message.role === "system")) {
|
|
12
18
|
return messages;
|
|
13
19
|
}
|
|
14
20
|
return messages.map(message => {
|
|
15
21
|
if (!message || typeof message !== "object" || !("role" in message) || message.role !== "system") return message;
|
|
16
|
-
const
|
|
22
|
+
const toolsAdded = "toolsAdded" in message && Array.isArray(message.toolsAdded)
|
|
23
|
+
? toolDeclarations(message.toolsAdded)
|
|
24
|
+
: undefined;
|
|
25
|
+
const toolsRemoved = "toolsRemoved" in message && Array.isArray(message.toolsRemoved)
|
|
26
|
+
? message.toolsRemoved.map((tool: { name: string }) => ({ name: tool.name }))
|
|
27
|
+
: undefined;
|
|
17
28
|
return { ...message,
|
|
18
|
-
...(
|
|
19
|
-
...(
|
|
29
|
+
...(toolsAdded ? { toolsAdded } : {}),
|
|
30
|
+
...(toolsRemoved ? { toolsRemoved } : {}),
|
|
20
31
|
};
|
|
21
32
|
});
|
|
22
33
|
}
|
package/extension/quota-usage.ts
CHANGED
|
@@ -199,7 +199,8 @@ export function createQuotaUsageProvider(options: {
|
|
|
199
199
|
let shared = inFlight;
|
|
200
200
|
if (!shared) {
|
|
201
201
|
const controller = new AbortController();
|
|
202
|
-
|
|
202
|
+
let load: Promise<QuotaUsageReport | null> | undefined;
|
|
203
|
+
load = (async () => {
|
|
203
204
|
try {
|
|
204
205
|
const snapshot = await options.loadSnapshot(controller.signal);
|
|
205
206
|
if (!snapshot || controller.signal.aborted) return null;
|