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.
Files changed (42) hide show
  1. package/README.md +9 -11
  2. package/THIRD_PARTY_LICENSES.txt +70 -39
  3. package/extension/acp-compaction.ts +14 -2
  4. package/extension/acp-errors.ts +11 -3
  5. package/extension/adapter-config.ts +1 -1
  6. package/extension/ambient.d.ts +23 -0
  7. package/extension/assets/zip-archive.mjs +10839 -0
  8. package/extension/auth-sync.ts +88 -7
  9. package/extension/commands.ts +12 -15
  10. package/extension/context-settings.ts +2 -2
  11. package/extension/index.ts +71 -35
  12. package/extension/model-catalog.ts +1 -1
  13. package/extension/omp-context.ts +14 -3
  14. package/extension/quota-usage.ts +2 -1
  15. package/extension/runtime/acp/bounded-stream.ts +78 -24
  16. package/extension/runtime/acp/connection.ts +18 -6
  17. package/extension/runtime/binding.ts +2 -2
  18. package/extension/runtime/config.ts +1 -1
  19. package/extension/runtime/managed.ts +2 -1
  20. package/extension/runtime/models.ts +15 -8
  21. package/extension/runtime/prompt.ts +90 -50
  22. package/extension/runtime/provider.ts +38 -10
  23. package/extension/runtime/runtime.ts +74 -44
  24. package/extension/runtime/stream/pi-events.ts +3 -3
  25. package/extension/runtime/tools/bridge.ts +20 -8
  26. package/extension/runtime/tools/relay.ts +2 -2
  27. package/extension/runtime/zip-archive.ts +1 -0
  28. package/extension/runtime.d.mts +1 -0
  29. package/extension/runtime.mjs +18311 -35376
  30. package/extension/secret-service.ts +28 -0
  31. package/extension/selectors.ts +8 -7
  32. package/extension/session-store.ts +7 -7
  33. package/extension/tier-connection.ts +39 -8
  34. package/extension/tool-policy.ts +2 -2
  35. package/extension/tool-relay-protocol.d.mts +5 -0
  36. package/extension/tool-routing.ts +40 -23
  37. package/extension/transcript-routing.ts +16 -3
  38. package/extension/turn-cancellation.ts +1 -1
  39. package/extension/usage-db.ts +42 -22
  40. package/extension/usage.ts +1 -1
  41. package/licenses/{pi-ai-1.3.0.txt → pi-mit.txt} +1 -2
  42. package/package.json +10 -8
@@ -44,6 +44,29 @@ function serviceUnavailable(failure: ExecFailure): boolean {
44
44
  || (typeof failure.stderr === "string" && UNAVAILABLE_STDERR.test(failure.stderr));
45
45
  }
46
46
 
47
+ function validEmail(value: unknown): string | undefined {
48
+ if (typeof value !== "string") return undefined;
49
+ const trimmed = value.trim();
50
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(trimmed) ? trimmed : undefined;
51
+ }
52
+
53
+ function extractEmailFromKeyringPayload(stdout: string): string | undefined {
54
+ const trimmed = stdout.trim();
55
+ if (!trimmed.startsWith("{")) return undefined;
56
+ try {
57
+ const parsed = JSON.parse(trimmed) as { id_token_email?: unknown; id_token?: unknown } | null;
58
+ const direct = validEmail(parsed?.id_token_email);
59
+ if (direct) return direct;
60
+ const idToken = parsed?.id_token;
61
+ if (typeof idToken === "string" && idToken.includes(".")) {
62
+ const claims = JSON.parse(Buffer.from(idToken.split(".")[1]!, "base64url").toString("utf8")) as { email?: unknown };
63
+ return validEmail(claims?.email);
64
+ }
65
+ } catch { /* Non-JSON or malformed payload; ignore without surfacing secrets. */ }
66
+ return undefined;
67
+ }
68
+
69
+
47
70
  // Linux Secret Service operations behind one mutable object so offline command
48
71
  // tests can substitute them without touching the user's real keyring.
49
72
  // present/remove resolve to true (present / removed), false (confirmed absent),
@@ -80,6 +103,11 @@ export function createSecretService(run: (args: string[]) => Promise<string>, pl
80
103
  return {
81
104
  applicable: platform === "linux",
82
105
  present: (): Promise<boolean | undefined> => platform === "linux" ? present() : Promise.resolve(undefined),
106
+ accountEmail: async (): Promise<string | undefined> => {
107
+ if (platform !== "linux") return undefined;
108
+ try { return extractEmailFromKeyringPayload(await run(LOOKUP)); }
109
+ catch { return undefined; }
110
+ },
83
111
  remove: (): Promise<boolean | undefined> => platform === "linux" ? remove() : Promise.resolve(undefined),
84
112
  };
85
113
  }
@@ -3,19 +3,20 @@ import { parseThoughtRoute, splitLegacyEffort, validId, type AdvertisedModel } f
3
3
  export interface ConfigOptionChoice {
4
4
  value?: unknown;
5
5
  name?: unknown;
6
- options?: ConfigOptionChoice[];
6
+ options?: ReadonlyArray<ConfigOptionChoice> | null;
7
7
  }
8
8
 
9
9
  export interface ConfigOption {
10
10
  id: string;
11
- type?: string;
12
- category?: string;
13
- currentValue?: string;
14
- options?: ConfigOptionChoice[];
11
+ type?: string | null;
12
+ category?: string | null;
13
+ description?: string | null;
14
+ currentValue?: string | boolean | null;
15
+ options?: ReadonlyArray<ConfigOptionChoice> | null;
15
16
  }
16
17
 
17
18
  export interface SelectorState {
18
- configOptions?: ConfigOption[] | null;
19
+ configOptions?: ReadonlyArray<ConfigOption> | null;
19
20
  }
20
21
 
21
22
  export function selector(state: SelectorState | undefined, category: "model" | "thought_level"): ConfigOption | undefined {
@@ -33,7 +34,7 @@ export function advertisedRecord(state: SelectorState | undefined, modelId: stri
33
34
  const thought = selector(state, "thought_level");
34
35
  return {
35
36
  modelId, name, selector: true,
36
- ...(thought ? { thoughtLevels: choices(thought).map(option => option.value), defaultThoughtLevel: thought.currentValue } : {}),
37
+ ...(thought ? { thoughtLevels: choices(thought).map(option => option.value), ...(typeof thought.currentValue === "string" ? { defaultThoughtLevel: thought.currentValue } : {}) } : {}),
37
38
  };
38
39
  }
39
40
 
@@ -172,15 +172,15 @@ export class AcpSessionStore {
172
172
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
173
173
  const parsed: unknown = JSON.parse(raw);
174
174
  if (!Array.isArray(parsed)) throw new Error("Invalid ACP session registry; refusing to overwrite it");
175
- const valid = (record: any): record is SavedSessionRecord => Boolean(record) && typeof record === "object" &&
176
- ["piSessionId", "acpSessionId", "acpModelId", "cwd", "historyFingerprint"].every(key => typeof record[key] === "string") &&
177
- Number.isSafeInteger(record.messageCount) && record.messageCount >= 0 && Number.isFinite(record.lastActive) &&
178
- (record.expectedAssistantFingerprint === undefined || typeof record.expectedAssistantFingerprint === "string") &&
175
+ const valid = (record: unknown): record is SavedSessionRecord => record !== null && typeof record === "object" &&
176
+ ["piSessionId", "acpSessionId", "acpModelId", "cwd", "historyFingerprint"].every(key => typeof Reflect.get(record, key) === "string") &&
177
+ Number.isSafeInteger(Reflect.get(record, "messageCount")) && Number(Reflect.get(record, "messageCount")) >= 0 && Number.isFinite(Reflect.get(record, "lastActive")) &&
178
+ (Reflect.get(record, "expectedAssistantFingerprint") === undefined || typeof Reflect.get(record, "expectedAssistantFingerprint") === "string") &&
179
179
  ["ompExpectedAssistantNormalized", "ompInstructionsFingerprint", "ompConversationFingerprint"].every(key =>
180
- record[key] === undefined || typeof record[key] === "string") &&
181
- (record.ompCheckpointVersion === undefined || record.ompCheckpointVersion === 1) &&
180
+ Reflect.get(record, key) === undefined || typeof Reflect.get(record, key) === "string") &&
181
+ (Reflect.get(record, "ompCheckpointVersion") === undefined || Reflect.get(record, "ompCheckpointVersion") === 1) &&
182
182
  ["ompInFlight", "ompExpectedAssistantHasOutput", "ompCancelledCheckpoint", "ompCancelledHadOutput"].every(key =>
183
- record[key] === undefined || typeof record[key] === "boolean");
183
+ Reflect.get(record, key) === undefined || typeof Reflect.get(record, key) === "boolean");
184
184
  if (!parsed.every(valid)) throw new Error("Invalid or unsupported ACP session registry record; refusing to overwrite it");
185
185
  return parsed;
186
186
  }
@@ -15,7 +15,7 @@ import type { SessionCleanup } from "./session-cleanup.ts";
15
15
  import type { Diagnostics } from "./diagnostics.ts";
16
16
  import { deferredAbortSignal, isSteerAbort, steerMode as resolveSteerMode, steerTimings as resolveSteerTimings, type SteerMode, type SteerTimings } from "./turn-cancellation.ts";
17
17
  import { PermissionIdentityRegistry } from "./permission-identity.ts";
18
- import type { AvailableCommand, McpServer, PromptResponse } from "@agentclientprotocol/sdk";
18
+ import type { AvailableCommand, InitializeResponse, McpServer, PromptResponse } from "@agentclientprotocol/sdk";
19
19
 
20
20
  const CONTINUATION_PROMPT = "Continue exactly where your previous output stopped. Do not repeat any earlier text.";
21
21
  function continuationLimit(): number {
@@ -256,7 +256,7 @@ export class TierConnection extends AntigravityAcpConnection {
256
256
  this.ompProjectedToolNames = [...names];
257
257
  }
258
258
 
259
- async initialize(signal?: AbortSignal) {
259
+ override async initialize(signal?: AbortSignal): Promise<InitializeResponse> {
260
260
  return normalizeInitializeResponse(await super.initialize(signal));
261
261
  }
262
262
 
@@ -332,7 +332,7 @@ export class TierConnection extends AntigravityAcpConnection {
332
332
  const notices: AcpCompactionNotice[] = [];
333
333
  for (const [sessionId, records] of this.compactions) {
334
334
  if (acpSessionId !== undefined && sessionId !== acpSessionId) continue;
335
- for (const record of records.values()) {
335
+ for (const [compactionId, record] of records) {
336
336
  if (record.notified || !isTerminalCompaction(record.status)) continue;
337
337
  record.notified = true;
338
338
  notices.push({
@@ -342,7 +342,9 @@ export class TierConnection extends AntigravityAcpConnection {
342
342
  summary: record.summary,
343
343
  ...(record.error !== undefined ? { error: record.error } : {}),
344
344
  });
345
+ records.delete(compactionId);
345
346
  }
347
+ if (records.size === 0) this.compactions.delete(sessionId);
346
348
  }
347
349
  return notices;
348
350
  }
@@ -375,6 +377,35 @@ export class TierConnection extends AntigravityAcpConnection {
375
377
  return routed._meta;
376
378
  }
377
379
 
380
+ private async retryStartupAuthRace<T>(signal: AbortSignal | undefined, call: () => Promise<T>): Promise<T> {
381
+ const started = performance.now();
382
+ try {
383
+ return await call();
384
+ } catch (error) {
385
+ const message = error instanceof Error ? error.message : String(error);
386
+ const isRace = !signal?.aborted
387
+ && this.process.alive
388
+ && performance.now() - started < 2_000
389
+ && /authentication required|auth_required|not logged in|not signed in/i.test(message)
390
+ && !/invalid_grant|api.?key/i.test(message);
391
+ if (!isRace) throw error;
392
+ await new Promise<void>(resolve => {
393
+ const onAbort = () => {
394
+ clearTimeout(timer);
395
+ resolve();
396
+ };
397
+ const timer = setTimeout(() => {
398
+ signal?.removeEventListener("abort", onAbort);
399
+ resolve();
400
+ }, 250);
401
+ signal?.addEventListener("abort", onAbort, { once: true });
402
+ timer.unref?.();
403
+ });
404
+ if (signal?.aborted || !this.process.alive) throw error;
405
+ return await call();
406
+ }
407
+ }
408
+
378
409
  override async newSession(
379
410
  cwd: string,
380
411
  signal?: AbortSignal,
@@ -382,7 +413,7 @@ export class TierConnection extends AntigravityAcpConnection {
382
413
  meta?: SessionMeta,
383
414
  ): Promise<AcpNewSessionResponse> {
384
415
  const routed = await this.sessionMeta({ cwd, mcpServers, ...(meta === undefined ? {} : { _meta: meta }) });
385
- const session = await super.newSession(cwd, signal, mcpServers, routed);
416
+ const session = await this.retryStartupAuthRace(signal, () => super.newSession(cwd, signal, mcpServers, routed));
386
417
  if (this.cleanup) {
387
418
  try { this.cleanupLeases.set(session.sessionId, await this.cleanup.acquire(session.sessionId, true, this.process.pid!)); }
388
419
  catch { this.pendingOwned.add(session.sessionId); console.warn("[ACP cleanup] Registration deferred; preserving session files and retrying."); }
@@ -409,7 +440,7 @@ export class TierConnection extends AntigravityAcpConnection {
409
440
  ): Promise<SessionState> {
410
441
  await this.protectSession(sessionId);
411
442
  const routed = await this.sessionMeta({ sessionId, cwd, mcpServers, ...(meta === undefined ? {} : { _meta: meta }) });
412
- const session = await super.resumeSession(sessionId, cwd, mcpServers, signal, routed);
443
+ const session = await this.retryStartupAuthRace(signal, () => super.resumeSession(sessionId, cwd, mcpServers, signal, routed));
413
444
  if ("availableCommands" in session && Array.isArray(session.availableCommands)) {
414
445
  this.updateUsageCommands(sessionId, session.availableCommands);
415
446
  }
@@ -424,7 +455,7 @@ export class TierConnection extends AntigravityAcpConnection {
424
455
  ): Promise<SessionState> {
425
456
  await this.protectSession(sessionId);
426
457
  const routed = await this.sessionMeta({ sessionId, cwd, mcpServers, ...(meta === undefined ? {} : { _meta: meta }) });
427
- const session = await super.loadSession(sessionId, cwd, mcpServers, signal, routed);
458
+ const session = await this.retryStartupAuthRace(signal, () => super.loadSession(sessionId, cwd, mcpServers, signal, routed));
428
459
  if ("availableCommands" in session && Array.isArray(session.availableCommands)) {
429
460
  this.updateUsageCommands(sessionId, session.availableCommands);
430
461
  }
@@ -604,7 +635,7 @@ export class TierConnection extends AntigravityAcpConnection {
604
635
  return response;
605
636
  }
606
637
 
607
- override async prompt(request: Parameters<AntigravityAcpConnection["prompt"]>[0], signal?: AbortSignal) {
638
+ override async prompt(request: Parameters<AntigravityAcpConnection["prompt"]>[0], signal?: AbortSignal): Promise<PromptResponse> {
608
639
  this.activePrompts++;
609
640
  const id = request.sessionId;
610
641
  this.noticeClosed?.delete(id);
@@ -650,7 +681,7 @@ export class TierConnection extends AntigravityAcpConnection {
650
681
  const response = await this.promptWithContinuations(request, deferred?.signal ?? signal);
651
682
  this.diagnostics?.record("acp.prompt", performance.now() - started);
652
683
  if (abortedAt !== undefined && ["cancelled", "end_turn"].includes(response.stopReason)) this.diagnostics?.record("acp.cancel-confirmation", performance.now() - abortedAt);
653
- const withContext = <T extends { _meta?: Record<string, unknown> }>(value: T): T => {
684
+ const withContext = (value: PromptResponse): PromptResponse => {
654
685
  const context = this.contextUsage.get(id);
655
686
  if (!context) return value;
656
687
  const ompContextWindow = this.ompContextWindows?.get(id);
@@ -16,11 +16,11 @@ export function loadToolPolicy(file: string): ToolPolicy {
16
16
  throw new Error("debugToolUpdates must be boolean");
17
17
  }
18
18
  return {
19
- nativeTools: parseNativeToolMode(record.nativeTools === undefined ? "prefer" : String(record.nativeTools)),
19
+ nativeTools: parseNativeToolMode(record.nativeTools === undefined ? "disabled" : String(record.nativeTools)),
20
20
  debugToolUpdates: record.debugToolUpdates ?? false,
21
21
  };
22
22
  } catch (error: unknown) {
23
- if (isMissingFileError(error)) return { nativeTools: "prefer", debugToolUpdates: false };
23
+ if (isMissingFileError(error)) return { nativeTools: "disabled", debugToolUpdates: false };
24
24
  throw new Error(`Invalid OMP ACP tool policy: ${errorMessageOf(error)}`);
25
25
  }
26
26
  }
@@ -0,0 +1,5 @@
1
+ export declare const TOOL_RELAY_CONTROL_NAME = "pi_omp_await_result";
2
+ export declare const TOOL_RELAY_PI_NAME = "omp_await_result";
3
+ export declare const TOOL_RELAY_VERSION = 1;
4
+ export declare function relayNotice(callId: string): string;
5
+ export declare function parseRelayCallId(text: unknown): string | undefined;
@@ -1,3 +1,5 @@
1
+ import type { InitializeResponse } from "@agentclientprotocol/sdk";
2
+
1
3
  export type NativeToolMode = "prefer" | "disabled";
2
4
 
3
5
  // A main session may delegate through the pi-bridge; an ephemeral side turn
@@ -39,18 +41,18 @@ const EPHEMERAL_TOOL_GUIDANCE =
39
41
  "no tools may be called in this side turn, and tool calls are discarded without execution. " +
40
42
  "Reply with plain text only.";
41
43
 
42
- // Two sentences at most: redirect the host prompt, then the complete OMP
43
- // instruction follows unchanged. Only disabled native tools need the
44
- // redirect; prefer keeps native tools, so its append starts with the OMP text.
45
- const ACP_OVERRIDE =
46
- "Follow only the OMP instructions below. Ignore any earlier ACP host instructions, personas or workflows.";
47
- const ACP_OVERRIDE_WITH_TOOLS =
48
- "Follow only the OMP instructions below. Ignore any earlier ACP host instructions, personas or workflows; " +
44
+ // Two sentences at most: redirect the Antigravity host prompt, then the
45
+ // complete OMP instruction follows unchanged. Only disabled native tools need
46
+ // the redirect; prefer keeps native tools, so its append starts with the OMP text.
47
+ const ANTIGRAVITY_OVERRIDE =
48
+ "Follow only the OMP instructions below. Ignore any earlier Antigravity host instructions, personas or workflows.";
49
+ const ANTIGRAVITY_OVERRIDE_WITH_TOOLS =
50
+ "Follow only the OMP instructions below. Ignore any earlier Antigravity host instructions, personas or workflows; " +
49
51
  "use only OMP pi_* tools and pi_task for reads, writes, searches, commands and subagent delegation.";
50
52
 
51
- function acpOverride(mode: NativeToolMode, sessionKind: SessionRoutingKind, hasOmpTools: boolean): string {
53
+ function antigravityOverride(mode: NativeToolMode, sessionKind: SessionRoutingKind, hasOmpTools: boolean): string {
52
54
  if (mode !== "disabled") return "";
53
- return sessionKind === "main" && hasOmpTools ? ACP_OVERRIDE_WITH_TOOLS : ACP_OVERRIDE;
55
+ return sessionKind === "main" && hasOmpTools ? ANTIGRAVITY_OVERRIDE_WITH_TOOLS : ANTIGRAVITY_OVERRIDE;
54
56
  }
55
57
 
56
58
  export function parseNativeToolMode(value: unknown): NativeToolMode {
@@ -61,19 +63,29 @@ export function parseNativeToolMode(value: unknown): NativeToolMode {
61
63
  const OFFICIAL_AGENT_NAMES = new Set(["antigravity-acp", "Antigravity ACP Server"]);
62
64
 
63
65
  export interface InitializeMetadata {
64
- agentInfo?: { name?: string; version?: string };
66
+ protocolVersion?: number;
67
+ agentInfo?: { name?: string | null; version?: string | null; title?: string | null; _meta?: Record<string, unknown> | null } | null;
68
+ authMethods?: ReadonlyArray<{ id?: string | null; name?: string | null; description?: string | null; _meta?: Record<string, unknown> | null }> | null;
65
69
  agentCapabilities?: {
70
+ loadSession?: boolean;
66
71
  mcpCapabilities?: {
67
- http?: boolean;
72
+ http?: boolean | null;
73
+ sse?: boolean | null;
74
+ acp?: boolean | null;
75
+ _meta?: Record<string, unknown> | null;
68
76
  [key: string]: unknown;
69
- };
70
- _meta?: {
71
- antigravity?: {
72
- systemPrompt?: { append?: boolean };
73
- };
74
- };
77
+ } | null;
78
+ promptCapabilities?: {
79
+ image?: boolean | null;
80
+ audio?: boolean | null;
81
+ embeddedContext?: boolean | null;
82
+ _meta?: Record<string, unknown> | null;
83
+ [key: string]: unknown;
84
+ } | null;
85
+ _meta?: Record<string, unknown> | null;
75
86
  [key: string]: unknown;
76
- };
87
+ } | null;
88
+ _meta?: Record<string, unknown> | null;
77
89
  }
78
90
 
79
91
  export interface SessionRpcRequest {
@@ -100,8 +112,11 @@ function isOfficialAgentAtLeast(initialize: InitializeMetadata | undefined, mino
100
112
  }
101
113
 
102
114
  export function supportsSessionRouting(initialize: InitializeMetadata | undefined): boolean {
103
- return isOfficialAgentAtLeast(initialize, 4, 1) &&
104
- initialize?.agentCapabilities?._meta?.antigravity?.systemPrompt?.append === true;
115
+ if (!isOfficialAgentAtLeast(initialize, 4, 1)) return false;
116
+ const meta = initialize?.agentCapabilities?._meta;
117
+ const antigravity = meta && typeof meta === "object" ? Reflect.get(meta, "antigravity") : undefined;
118
+ const systemPrompt = antigravity && typeof antigravity === "object" ? Reflect.get(antigravity, "systemPrompt") : undefined;
119
+ return Boolean(systemPrompt && typeof systemPrompt === "object" && Reflect.get(systemPrompt, "append") === true);
105
120
  }
106
121
 
107
122
  // The runtime only starts the pi-bridge when the agent advertises HTTP MCP.
@@ -129,7 +144,7 @@ export function ompToolGuidance(
129
144
  return [guidance, contextGuidance, ...(mode === "disabled" ? [NATIVE_TOOLS_DISABLED] : [])].filter(Boolean).join("\n\n");
130
145
  }
131
146
 
132
- // Composes the session append: optional ACP override, the unchanged complete
147
+ // Composes the session append: optional Antigravity override, the unchanged complete
133
148
  // OMP instruction, then the existing tool guidance. `hasOmpTools` is only
134
149
  // needed when the bridge is registered without ordinary tools.
135
150
  export function sessionSystemAppend(
@@ -143,13 +158,15 @@ export function sessionSystemAppend(
143
158
  ): string {
144
159
  const bridgeActive = bridgeConfigured && hasOmpTools !== false && mcpHttpAvailable(initialize);
145
160
  return [
146
- acpOverride(mode, sessionKind, bridgeActive),
161
+ antigravityOverride(mode, sessionKind, bridgeActive),
147
162
  instructions.trim(),
148
163
  ompToolGuidance(initialize, mode, bridgeActive, sessionKind, projectedToolNames),
149
164
  ].filter(Boolean).join("\n\n");
150
165
  }
151
166
 
152
- export function normalizeInitializeResponse<T extends InitializeMetadata>(initialize: T): T {
167
+ export function normalizeInitializeResponse(initialize: InitializeResponse): InitializeResponse;
168
+ export function normalizeInitializeResponse(initialize: InitializeMetadata): InitializeMetadata;
169
+ export function normalizeInitializeResponse(initialize: InitializeMetadata): InitializeMetadata {
153
170
  if (!isOfficialAgentAtLeast(initialize, 5, 3) || initialize.agentCapabilities?.mcpCapabilities?.http !== undefined) {
154
171
  return initialize;
155
172
  }
@@ -301,11 +301,24 @@ export class TranscriptRouting {
301
301
  forget(transcriptId: string, file?: string): string {
302
302
  const routingId = this.take(transcriptId, file);
303
303
  const route = this.byTranscript.get(transcriptId);
304
+ this.byTranscript.delete(transcriptId);
304
305
  if (route?.owner) {
305
- const current = this.currentSources.get(route.owner);
306
- if (current?.transcriptId === transcriptId) this.currentSources.delete(route.owner);
306
+ const owner = route.owner;
307
+ const current = this.currentSources.get(owner);
308
+ if (current?.transcriptId === transcriptId) {
309
+ let stillReferenced = false;
310
+ for (const other of this.byTranscript.values()) {
311
+ if (other.owner === owner) { stillReferenced = true; break; }
312
+ }
313
+ if (!stillReferenced) {
314
+ this.invalidateOwnerSource(owner);
315
+ const ownedReplacement = this.replacements.get(owner);
316
+ if (ownedReplacement) this.invalidateAttempt(ownedReplacement.attempt, ownedReplacement.source);
317
+ } else {
318
+ this.currentSources.delete(owner);
319
+ }
320
+ }
307
321
  }
308
- this.byTranscript.delete(transcriptId);
309
322
  const transcriptAttempt = this.pending.get(transcriptId);
310
323
  if (transcriptAttempt) this.removePending(transcriptAttempt);
311
324
  const routingAttempt = this.pending.get(routingId);
@@ -124,7 +124,7 @@ export function deferredAbortSignal(
124
124
  controller.abort(signal.reason);
125
125
  return;
126
126
  }
127
- giveup = armSteerGiveup(activity?.source, activity?.sessionId, timings, () => controller.abort(signal.reason));
127
+ giveup = armSteerGiveup(activity?.source, activity?.sessionId ?? "", timings, () => controller.abort(signal.reason));
128
128
  };
129
129
 
130
130
  signal.addEventListener("abort", onAbort, { once: true });
@@ -67,13 +67,17 @@ function nativeUsageSqliteRuntime(): UsageSqliteRuntime {
67
67
  function bunOpener(Database: BunDatabaseConstructor): UsageDatabaseOpener {
68
68
  return dbPath => {
69
69
  const db = new Database(dbPath, { readonly: true });
70
- try { db.exec?.("PRAGMA busy_timeout = 100;"); } catch { /* Best-effort lock timeout. */ }
70
+ try { db.exec?.("PRAGMA busy_timeout = 100; PRAGMA cache_size = -256; PRAGMA mmap_size = 0;"); } catch { /* Best-effort lock timeout and cache cap. */ }
71
71
  return db;
72
72
  };
73
73
  }
74
74
 
75
75
  function nodeOpener(Database: NodeDatabaseConstructor): UsageDatabaseOpener {
76
- return dbPath => new Database(dbPath, { readOnly: true, timeout: 100 });
76
+ return dbPath => {
77
+ const db = new Database(dbPath, { readOnly: true, timeout: 100 });
78
+ try { db.exec?.("PRAGMA cache_size = -256; PRAGMA mmap_size = 0;"); } catch { /* Best-effort cache cap. */ }
79
+ return db;
80
+ };
77
81
  }
78
82
 
79
83
  export function selectUsageDatabaseOpener(runtime: UsageSqliteRuntime): UsageDatabaseOpener | undefined {
@@ -236,29 +240,45 @@ export function readModelStepsAfter(dbPath: string, afterIdx: number): StepUsage
236
240
  try {
237
241
  const db = openDb(dbPath);
238
242
  try {
239
- const rows = db.prepare("SELECT idx, metadata FROM steps WHERE step_type = 15 AND status = 3 AND idx > ? ORDER BY idx ASC").all(afterIdx);
243
+ const batchSize = 256;
244
+ const stmt = db.prepare("SELECT idx, metadata FROM steps WHERE step_type = 15 AND status = 3 AND idx > ? ORDER BY idx ASC LIMIT ? OFFSET ?");
245
+ let cursor = afterIdx;
246
+ let offset = 0;
240
247
  let maxIdx = afterIdx;
241
248
  let calls = 0;
242
249
  const usage: StepUsage = { inputTokens: 0, outputTokens: 0, cachedWriteTokens: 0, cachedReadTokens: 0, thoughtTokens: 0 };
243
- for (const row of rows) {
244
- const rawIdx = row.idx;
245
- const idx = typeof rawIdx === "number" && Number.isFinite(rawIdx) ? rawIdx : typeof rawIdx === "bigint" ? Number(rawIdx) : undefined;
246
- const rawMetadata = row.metadata;
247
- const metadata = rawMetadata instanceof Uint8Array
248
- ? rawMetadata
249
- : ArrayBuffer.isView(rawMetadata)
250
- ? new Uint8Array(rawMetadata.buffer, rawMetadata.byteOffset, rawMetadata.byteLength)
251
- : undefined;
252
- if (idx === undefined || metadata === undefined) continue;
253
- const decoded = decodeModelUsageStats(metadata);
254
- if (decoded === undefined) continue;
255
- if (idx > maxIdx) maxIdx = idx;
256
- calls++;
257
- usage.inputTokens += decoded.inputTokens;
258
- usage.outputTokens += decoded.outputTokens;
259
- usage.cachedWriteTokens += decoded.cachedWriteTokens;
260
- usage.cachedReadTokens += decoded.cachedReadTokens;
261
- usage.thoughtTokens += decoded.thoughtTokens;
250
+ for (;;) {
251
+ const rows = stmt.all(cursor, batchSize, offset);
252
+ if (rows.length === 0) break;
253
+ let lastRowIdx = cursor;
254
+ for (const row of rows) {
255
+ const rawIdx = row.idx;
256
+ const idx = typeof rawIdx === "number" && Number.isFinite(rawIdx) ? rawIdx : typeof rawIdx === "bigint" ? Number(rawIdx) : undefined;
257
+ if (idx !== undefined && idx > lastRowIdx) lastRowIdx = idx;
258
+ const rawMetadata = row.metadata;
259
+ const metadata = rawMetadata instanceof Uint8Array
260
+ ? rawMetadata
261
+ : ArrayBuffer.isView(rawMetadata)
262
+ ? new Uint8Array(rawMetadata.buffer, rawMetadata.byteOffset, rawMetadata.byteLength)
263
+ : undefined;
264
+ if (idx === undefined || metadata === undefined) continue;
265
+ const decoded = decodeModelUsageStats(metadata);
266
+ if (decoded === undefined) continue;
267
+ if (idx > maxIdx) maxIdx = idx;
268
+ calls++;
269
+ usage.inputTokens += decoded.inputTokens;
270
+ usage.outputTokens += decoded.outputTokens;
271
+ usage.cachedWriteTokens += decoded.cachedWriteTokens;
272
+ usage.cachedReadTokens += decoded.cachedReadTokens;
273
+ usage.thoughtTokens += decoded.thoughtTokens;
274
+ }
275
+ if (rows.length < batchSize) break;
276
+ if (lastRowIdx > cursor) {
277
+ cursor = lastRowIdx;
278
+ offset = 0;
279
+ } else {
280
+ offset += rows.length;
281
+ }
262
282
  }
263
283
  if (calls === 0) return undefined;
264
284
  return {
@@ -16,7 +16,7 @@ export interface PromptUsageResult {
16
16
  }
17
17
 
18
18
  export function usageFromPrompt(
19
- response: Parameters<typeof upstreamUsage>[0] & { _meta?: { ompContextTokens?: unknown } },
19
+ response: Parameters<typeof upstreamUsage>[0] & { _meta?: { ompContextTokens?: unknown } | null },
20
20
  fallbackContextTokens?: number,
21
21
  ): PromptUsageResult {
22
22
  const usage: PromptUsageResult = upstreamUsage(response);
@@ -1,6 +1,5 @@
1
1
  Source: https://github.com/earendil-works/pi/blob/main/LICENSE
2
- Package: @earendil-works/pi-ai@1.3.0 (declares MIT; npm archive omits LICENSE)
3
- Retrieved: 2026-10-19
2
+ Retrieved: 2026-11-14
4
3
 
5
4
  MIT License
6
5
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-antigravity-acp-provider",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "ompAcpBundle": 1,
5
5
  "description": "Google Antigravity ACP provider for Oh My Pi (OMP), with tool bridging and per-model thinking; derived from zacbemis/pi-antigravity-acp-provider",
6
6
  "type": "module",
@@ -51,7 +51,9 @@
51
51
  "check:versions": "node scripts/check-release-versions.mjs",
52
52
  "typecheck": "tsc -p tsconfig.contracts.json",
53
53
  "release:bump": "node scripts/bump-release.mjs",
54
- "check": "npm run typecheck && npm run build && npm test && npm run test:cleanup && npm run test:continuity && npm run test:tools && npm run test:wire && npm run test:wire-tools && npm run test:wire-relay && npm run test:wire-tools-list && npm run test:graph && npm run test:commands && npm run test:auth && npm run test:runtime-source && npm run test:managed && npm run test:close-session && npm run test:omp-sessions && npm run test:omp-rollover && npm run test:omp-builtin-usage && npm run test:managed-context && npm run test:packed",
54
+ "check:portable": "npm run typecheck && npm run check:versions && node --test scripts/test-check-release-versions.mjs && node --test scripts/test-bump-release.mjs && node --test scripts/test-verify-release-tarball.mjs && npm run build && node scripts/test.mjs && npm run test:managed-context && node scripts/test-packed.mjs",
55
+ "check:posix": "node scripts/test-cleanup-runtime.ts && node scripts/test-request-continuity.ts && node scripts/test-graceful-cancellation.ts && npm run test:tools && npm run test:wire && npm run test:wire-tools && npm run test:wire-relay && npm run test:wire-tools-list && npm run test:graph && npm run test:commands && npm run test:auth && npm run test:runtime-source && npm run test:managed && npm run test:close-session && node scripts/test-omp-session-switch.ts && node scripts/test-context-rollover.ts && node scripts/test-omp-builtin-usage.mjs",
56
+ "check": "npm run check:portable && npm run check:posix",
55
57
  "prepack": "npm run build",
56
58
  "prepublishOnly": "npm run check",
57
59
  "test:graph": "bun scripts/test-load-graph.ts",
@@ -67,14 +69,14 @@
67
69
  },
68
70
  "devDependencies": {
69
71
  "@agentclientprotocol/sdk": "1.8.0",
70
- "@earendil-works/pi-ai": "1.3.0",
71
- "@modelcontextprotocol/sdk": "1.32.1",
72
+ "@earendil-works/pi-ai": "1.5.2",
73
+ "@modelcontextprotocol/sdk": "1.32.2",
72
74
  "esbuild": "0.28.2",
73
75
  "proper-lockfile": "4.1.2",
74
- "typebox": "1.3.36",
75
- "typescript": "^5.9.3",
76
+ "typebox": "1.4.6",
77
+ "typescript": "^7.0.2",
76
78
  "unzipper": "0.12.5",
77
- "zod": "4.6.5"
79
+ "zod": "4.6.7"
78
80
  },
79
81
  "keywords": [
80
82
  "pi-package",
@@ -86,5 +88,5 @@
86
88
  "acp",
87
89
  "gemini"
88
90
  ],
89
- "gitHead": "7dcaa0d783ed834a5f313018923ffc22cb0eab5f"
91
+ "gitHead": "aabe7f01e331ebd1e51ae816593990f09227ffd6"
90
92
  }