omp-antigravity-acp-provider 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,7 +19,7 @@ The repository keeps the OMP adapter sources separately and installs upstream ve
19
19
 
20
20
  ## Status
21
21
 
22
- Version 0.1.15 supports all models advertised by the official ACP server. Tested with macOS, OMP 18.12.3, upstream provider 0.1.15 and official ACP runtime 1.4.1. Other platforms and OMP versions are not yet verified.
22
+ Version 0.1.17 supports all models advertised by the official ACP server. Tested with macOS, OMP 18.12.3, upstream provider 0.1.15 and official ACP runtime 1.4.1. Other platforms and OMP versions are not yet verified.
23
23
 
24
24
  Google's consumer-plan policies can restrict third-party agent access even through the official CLI or ACP executable. An official transport does not establish permission to use a subscription in OMP. Check the current [Antigravity FAQ](https://www.antigravity.google/docs/faq/) and [terms](https://antigravity.google/terms) for your account.
25
25
 
@@ -56,7 +56,7 @@ Or, inside OMP:
56
56
 
57
57
  Select **omp-antigravity-acp-provider** in the browser, install it, and restart OMP to load the provider.
58
58
 
59
- OMP's marketplace installer currently copies Git content without installing npm dependencies. This marketplace therefore ships a small source launcher that retrieves the exact published **0.1.15** prebuilt npm adapter and production dependencies on first load. It disables npm install scripts, skips Pi CLI peer installation, and performs no local compilation. Node.js 22.19+ and npm must be on PATH. First preparation needs internet access and roughly **150 MiB** of disk space; later loads reuse the installed cache without npm network access.
59
+ OMP's marketplace installer currently copies Git content without installing npm dependencies. This marketplace therefore ships a small source launcher that retrieves the exact published **0.1.17** prebuilt npm adapter and production dependencies on first load. It disables npm install scripts, skips Pi CLI peer installation, and performs no local compilation. Node.js 22.19+ and npm must be on PATH. First preparation needs internet access and roughly **150 MiB** of disk space; later loads reuse the installed cache without npm network access.
60
60
 
61
61
  The launcher stores its versioned dependencies in `.runtime/` inside the installed marketplace plugin's cache directory. Uninstalling the marketplace plugin removes that cache when it is no longer referenced by another scope. Google credentials and the separately downloaded official ACP runtime are unaffected.
62
62
 
@@ -80,7 +80,7 @@ omp plugin install npm:omp-antigravity-acp-provider
80
80
  To pin a specific release:
81
81
 
82
82
  ```sh
83
- omp plugin install npm:omp-antigravity-acp-provider@0.1.15
83
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.17
84
84
  ```
85
85
 
86
86
  Restart OMP after installation. The npm package includes the built adapter; users do not need esbuild or a manual build step. Disable any older ACP adapter for the same provider before loading this package.
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from "node:child_process";
2
+ import { setTimeout as delay } from "node:timers/promises";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
5
  import { clearAntigravityCredentials, hasAntigravityAuth, resolveAntigravityAcpDirectory } from "./runtime.mjs";
@@ -61,6 +62,18 @@ export function antigravityAccountEmail(): string | undefined {
61
62
  // run the delayed detection without real waits.
62
63
  export const logoutFollow = { delayMs: 500, retryMs: 15_000 };
63
64
 
65
+ // Shared wording for both logout confirmations (direct command and the
66
+ // follow-up that finishes a logout OMP started).
67
+ export function formatLogoutSummary(options: { keychainRemoved: boolean | undefined; ompMarker?: "removed" | "absent" | "unavailable"; followed?: boolean }): string {
68
+ const cleared = ["Google credentials", "saved ACP sessions"];
69
+ if (options.keychainRemoved === true) cleared.push("the macOS keychain entry");
70
+ if (options.ompMarker === "removed") cleared.push("the OMP marker record");
71
+ const list = cleared.slice(0, -1).join(", ") + " and " + cleared[cleared.length - 1];
72
+ return `${options.followed ? "Antigravity ACP: finished the logout OMP started — " : "Antigravity ACP: logged out — "}${list} cleared.` +
73
+ (options.ompMarker === "unavailable" ? " The OMP marker record could not be removed; run /logout to drop it." : "") +
74
+ (options.keychainRemoved === false ? " The macOS keychain entry was not present or not removable." : "");
75
+ }
76
+
64
77
  export function authReady(): boolean {
65
78
  return hasAntigravityAuth() || keychain.present() === true;
66
79
  }
@@ -139,8 +152,8 @@ export class OmpAuthCoordinator {
139
152
  private selfLogout = false;
140
153
  // Whether registerProvider keeps the non-secret config apiKey fallback.
141
154
  apiKeyFallback = true;
142
- private followTimer: ReturnType<typeof setTimeout> | undefined;
143
- private followRetry: ReturnType<typeof setTimeout> | undefined;
155
+ private followTimer: NodeJS.Timeout | undefined;
156
+ private followRetry: NodeJS.Timeout | undefined;
144
157
 
145
158
  constructor(private readonly deps: AuthCoordinatorDeps) {}
146
159
 
@@ -156,13 +169,13 @@ export class OmpAuthCoordinator {
156
169
  async removeKeychainCredentialDurably(): Promise<boolean | undefined> {
157
170
  const pending = [...this.deps.connections].map(connection => connection.process.exited.catch(() => undefined));
158
171
  if (pending.length > 0) {
159
- await Promise.race([Promise.allSettled(pending), new Promise(resolve => setTimeout(resolve, 10_000))]);
172
+ await Promise.race([Promise.allSettled(pending), delay(10_000)]);
160
173
  }
161
174
  for (let attempt = 0; attempt < 3; attempt++) {
162
175
  if (keychain.present() === false) return true;
163
176
  const removed = keychain.remove();
164
177
  if (removed !== true) return removed;
165
- await new Promise(resolve => setTimeout(resolve, 400));
178
+ await delay(400);
166
179
  }
167
180
  return keychain.present() === false;
168
181
  }
@@ -213,11 +226,8 @@ export class OmpAuthCoordinator {
213
226
  await this.deps.closeAllRuntimes();
214
227
  const keychainRemoved = await this.removeKeychainCredentialDurably();
215
228
  // Keep the confirmation terse; /antigravity-acp account shows the details.
216
- const cleared = ["Google credentials", "saved ACP sessions"];
217
- if (keychainRemoved === true) cleared.push("the macOS keychain entry");
218
- const list = cleared.slice(0, -1).join(", ") + " and " + cleared[cleared.length - 1];
219
229
  try {
220
- ctx?.ui?.notify?.(`Antigravity ACP: finished the logout OMP started — ${list} cleared.${keychainRemoved === false ? " The macOS keychain entry was not present or not removable." : ""}`, "info");
230
+ ctx?.ui?.notify?.(formatLogoutSummary({ keychainRemoved, followed: true }), "info");
221
231
  } catch { /* the host UI may already be gone */ }
222
232
  }
223
233
 
@@ -1,19 +1,20 @@
1
1
  import fs from "node:fs";
2
2
  import { writeJsonAtomic } from "./fs-atomic.ts";
3
- import { resolveContextOptions, type ContextOptions, type ContextSettings } from "./context-settings.ts";
3
+ import { resolveContextOptions, type ContextOptions, type ContextSettings, type ResolvedContextOptions } from "./context-settings.ts";
4
4
  import { EFFORTS, projectCatalog, readModels, type AdvertisedModel, type PublicCatalogModel } from "./model-catalog.ts";
5
5
  import { officialApiCost } from "./pricing.ts";
6
6
  import { advertisedRecord, choices, selector } from "./selectors.ts";
7
- import { TierConnection } from "./tier-connection.ts";
7
+ import { TierConnection } from "./runtime.mjs";
8
8
  import type { SessionCleanup } from "./session-cleanup.ts";
9
9
 
10
10
  export interface ConfiguredCatalogModel extends PublicCatalogModel {
11
- ompContextPolicy: ReturnType<typeof resolveContextOptions>;
11
+ ompContextPolicy: ResolvedContextOptions;
12
12
  }
13
13
 
14
14
  export class CatalogStore {
15
15
  readonly upstreamModels = new Map<string, ConfiguredCatalogModel>();
16
16
  currentModels: ConfiguredCatalogModel[] = [];
17
+ private dynamicCache?: { mtimeMs: number; size: number; settings: ContextSettings; models: ConfiguredCatalogModel[] };
17
18
 
18
19
  constructor(
19
20
  private readonly cachePath: string,
@@ -56,6 +57,27 @@ export class CatalogStore {
56
57
  return this.currentModels;
57
58
  }
58
59
 
60
+ // OMP's host may call fetchDynamicModels on every startup pass; stat-based
61
+ // reuse avoids re-reading and re-projecting an unchanged cache file.
62
+ getDynamicModels(settings: ContextSettings): ConfiguredCatalogModel[] {
63
+ try {
64
+ const stat = fs.statSync(this.cachePath);
65
+ if (this.dynamicCache && this.currentModels.length > 0 &&
66
+ this.dynamicCache.mtimeMs === stat.mtimeMs && this.dynamicCache.size === stat.size &&
67
+ this.dynamicCache.settings === settings) {
68
+ return this.dynamicCache.models;
69
+ }
70
+ } catch { /* Missing or unreadable cache: fall through to a fresh read. */ }
71
+ const cached = this.readCachedCatalog();
72
+ const base = cached.length ? projectCatalog(cached) : this.fallbackModels();
73
+ const models = this.projectWithSettings(base, settings);
74
+ try {
75
+ const stat = fs.statSync(this.cachePath);
76
+ this.dynamicCache = { mtimeMs: stat.mtimeMs, size: stat.size, settings, models };
77
+ } catch { /* No cache file yet; nothing to key reuse on. */ }
78
+ return models;
79
+ }
80
+
59
81
  reconfigure(settings: ContextSettings): ConfiguredCatalogModel[] {
60
82
  this.currentModels = this.projectWithSettings(this.currentModels, settings);
61
83
  return this.currentModels;
@@ -1,8 +1,8 @@
1
1
  import { describeCredentialStorage, inspectAntigravityAuth, savePermissionMode } from "./runtime.mjs";
2
- import { antigravityAccountEmail, authReady, ompCredentialSummary, type OmpAuthCoordinator, type OmpCommandContext } from "./auth-sync.ts";
2
+ import { antigravityAccountEmail, authReady, formatLogoutSummary, ompCredentialSummary, type OmpAuthCoordinator, type OmpCommandContext } from "./auth-sync.ts";
3
3
  import { resolveContextOptions, saveContextSettings, updateContextSettings, type ContextSettings } from "./context-settings.ts";
4
4
  import { parseNativeToolMode, type NativeToolMode } from "./tool-routing.ts";
5
- import { saveDebugToolUpdates, saveNativeToolMode, type ToolPolicy } from "./tool-policy.ts";
5
+ import { saveToolPolicy, type ToolPolicy } from "./tool-policy.ts";
6
6
  import type { CatalogStore, ConfiguredCatalogModel } from "./catalog-store.ts";
7
7
  import type { SessionCleanup, CleanupMode } from "./session-cleanup.ts";
8
8
  import type { TierConnection } from "./tier-connection.ts";
@@ -20,12 +20,20 @@ export interface RuntimeSnapshotView {
20
20
  processes: RuntimeSnapshotProcess[];
21
21
  }
22
22
 
23
+ export interface StreamUsageLike { input?: unknown; output?: unknown; cacheRead?: unknown; cost?: unknown }
24
+ export interface StreamEventLike {
25
+ message?: { usage?: StreamUsageLike; timestamp?: number };
26
+ partial?: { usage?: StreamUsageLike; timestamp?: number };
27
+ }
28
+
23
29
  export interface RuntimeBundleView {
24
30
  runtime: {
25
31
  snapshot: () => Promise<RuntimeSnapshotView>;
26
32
  setPermissionMode: (mode: string) => Promise<void>;
27
33
  logout: () => Promise<void>;
28
- sessionStore?: { read: () => unknown[] };
34
+ close: () => Promise<void>;
35
+ getPermission: (requestId: string) => { id: string; title: string; options: Array<{ id?: string; label: string }> } | undefined;
36
+ sessionStore?: { read: () => unknown[]; clear: () => void };
29
37
  };
30
38
  provider: {
31
39
  auth: {
@@ -35,8 +43,10 @@ export interface RuntimeBundleView {
35
43
  notify: (event: { message?: string; links?: Array<{ url: string }> }) => void;
36
44
  prompt: (request: { message: string; placeholder?: string }) => Promise<string>;
37
45
  }) => Promise<unknown>;
46
+ refresh: (credentials: unknown) => Promise<unknown>;
38
47
  };
39
48
  };
49
+ streamSimple: (model: { id: string }, context: unknown, options?: unknown) => AsyncIterable<StreamEventLike>;
40
50
  };
41
51
  isBusy: () => boolean;
42
52
  }
@@ -63,6 +73,9 @@ export interface CommandControllerDeps {
63
73
  setPermissionModeState: (mode: string) => void;
64
74
  getLastToolAudit: () => ToolAuditSummary | undefined;
65
75
  getRuntimeForSession: (sessionId?: string) => RuntimeBundleView;
76
+ peekRuntimeForSession: (sessionId?: string) => RuntimeBundleView | undefined;
77
+ getSavedSessionCount: () => number;
78
+ getPermissionMode: () => string;
66
79
  getAllRuntimes: () => RuntimeBundleView[];
67
80
  closeAllRuntimes: () => Promise<void>;
68
81
  onModelsUpdated: (models: ConfiguredCatalogModel[]) => void;
@@ -134,8 +147,9 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
134
147
  if (command === "debug") {
135
148
  if (value !== "on" && value !== "off") throw new Error("Usage: /antigravity-acp debug on|off");
136
149
  const enabled = value === "on";
137
- saveDebugToolUpdates(deps.toolPolicyPath, enabled);
138
- deps.setToolPolicy({ ...deps.getToolPolicy(), debugToolUpdates: enabled });
150
+ const next = { ...deps.getToolPolicy(), debugToolUpdates: enabled };
151
+ saveToolPolicy(deps.toolPolicyPath, next);
152
+ deps.setToolPolicy(next);
139
153
  for (const connection of deps.connections) connection.debugToolUpdates = enabled;
140
154
  ctx.ui.notify(`ACP tool-status debug display: ${value}. Normal OMP tool results and thought summaries are preserved.`, "info");
141
155
  return;
@@ -144,8 +158,9 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
144
158
  if (command === "native-tools") {
145
159
  const mode: NativeToolMode = parseNativeToolMode(value);
146
160
  await deps.closeAllRuntimes();
147
- saveNativeToolMode(deps.toolPolicyPath, mode);
148
- deps.setToolPolicy({ ...deps.getToolPolicy(), nativeTools: mode });
161
+ const next = { ...deps.getToolPolicy(), nativeTools: mode };
162
+ saveToolPolicy(deps.toolPolicyPath, next);
163
+ deps.setToolPolicy(next);
149
164
  ctx.ui.notify(`Native tools: ${mode}. ACP connections will be recreated on the next request with the new policy.`, "info");
150
165
  return;
151
166
  }
@@ -179,11 +194,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
179
194
  if (value) throw new Error("Usage: /antigravity-acp logout");
180
195
  const { keychainRemoved, ompMarker } = await deps.auth.performCommandLogout(ctx);
181
196
  // Keep the confirmation terse; /antigravity-acp account shows the details.
182
- const cleared = ["Google credentials", "saved ACP sessions"];
183
- if (keychainRemoved === true) cleared.push("the macOS keychain entry");
184
- if (ompMarker === "removed") cleared.push("the OMP marker record");
185
- const list = cleared.slice(0, -1).join(", ") + " and " + cleared[cleared.length - 1];
186
- ctx.ui.notify(`Antigravity ACP: logged out — ${list} cleared.${ompMarker === "unavailable" ? " The OMP marker record could not be removed; run /logout to drop it." : ""}${keychainRemoved === false ? " The macOS keychain entry was not present or not removable." : ""}`, "info");
197
+ ctx.ui.notify(formatLogoutSummary({ keychainRemoved, ompMarker }), "info");
187
198
  return;
188
199
  }
189
200
 
@@ -192,8 +203,11 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
192
203
  const auth = inspectAntigravityAuth();
193
204
  let ompSource: string | undefined;
194
205
  try { ompSource = ctx?.modelRegistry?.authStorage?.keys?.describe?.("antigravity-acp", sessionIdOf(ctx)); } catch { /* host version dependent */ }
195
- const runtime = deps.getRuntimeForSession(sessionIdOf(ctx)).runtime;
196
- const snapshot = await runtime.snapshot();
206
+ // Reading saved state needs no live runtime; show live numbers only
207
+ // when a runtime for this session already exists.
208
+ const bundle = deps.peekRuntimeForSession(sessionIdOf(ctx));
209
+ const snapshot = await bundle?.runtime.snapshot();
210
+ const permissionMode = snapshot?.permissionMode ?? deps.getPermissionMode();
197
211
  const omp = ompCredentialSummary(ctx);
198
212
  const marker = omp.present === undefined ? "unknown (host did not expose the credential store)"
199
213
  : omp.present ? `present, authorized ${omp.authorizedAt ?? "unknown time"}${omp.email ? ` as ${omp.email}` : ""} (${omp.record})`
@@ -207,15 +221,14 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
207
221
  `Credential storage (preflight): ${describeCredentialStorage()}`,
208
222
  `OMP marker record: ${marker}`,
209
223
  ompSource ? `OMP auth source: ${ompSource}` : undefined,
210
- `Saved ACP sessions: ${runtime.sessionStore?.read().length ?? 0}`,
211
- `Requested permission mode: ${snapshot.permissionMode === "auto_edit" ? "auto-edit" : snapshot.permissionMode}`,
212
- `Active bindings: ${snapshot.bindings}`,
224
+ `Saved ACP sessions: ${deps.getSavedSessionCount()}`,
225
+ `Requested permission mode: ${permissionMode === "auto_edit" ? "auto-edit" : permissionMode}`,
226
+ `Active bindings: ${snapshot?.bindings ?? 0}`,
213
227
  "Google OAuth tokens stay in Antigravity-owned storage; OMP stores only a non-secret marker. /antigravity-acp logout clears both sides; OMP /logout also finishes the Antigravity-side cleanup.",
214
228
  ].filter(Boolean).join("\n"), "info");
215
229
  return;
216
230
  }
217
231
 
218
- const { runtime } = deps.getRuntimeForSession(sessionIdOf(ctx));
219
232
  if (command === "usage") {
220
233
  const currentSettings = deps.getContextSettings();
221
234
  ctx.ui.notify(JSON.stringify({
@@ -231,19 +244,32 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
231
244
  }
232
245
 
233
246
  if (command === "refresh") {
247
+ if (value !== undefined) throw new Error("Usage: /antigravity-acp refresh");
234
248
  const refreshed = await deps.catalog.refresh(deps.getContextSettings());
235
249
  deps.onModelsUpdated(refreshed);
236
250
  ctx.ui.notify(`Refreshed ACP model cache: ${refreshed.map(model => model.id).join(", ")}`, "info");
237
251
  return;
238
252
  }
239
253
 
240
- if (command === "permissions" && value && ["default", "auto-edit", "yolo"].includes(value)) {
254
+ if (command === "permissions") {
255
+ if (!value || !["default", "auto-edit", "yolo"].includes(value) || parts.length > 2) {
256
+ throw new Error("Usage: /antigravity-acp permissions default|auto-edit|yolo");
257
+ }
241
258
  const mode = value.replace("-", "_");
242
259
  deps.setPermissionModeState(mode);
243
260
  await Promise.all(deps.getAllRuntimes().map(bundle => bundle.runtime.setPermissionMode(mode)));
244
261
  savePermissionMode(mode, deps.configPath);
245
262
  }
263
+ const usageError = "Usage: /antigravity-acp [status|account|login|logout|tools|usage|context|cleanup|debug|native-tools|permissions|refresh]";
264
+ if (command && command !== "status" && command !== "tools" && command !== "permissions") {
265
+ throw new Error(usageError);
266
+ }
267
+ if (command === "status" && value !== undefined) throw new Error(usageError);
268
+ if (command === "tools" && value !== undefined) throw new Error("Usage: /antigravity-acp tools");
246
269
 
270
+ // Only the tools inspection and the status display below need a live
271
+ // runtime; every earlier command runs without one.
272
+ const { runtime } = deps.getRuntimeForSession(sessionIdOf(ctx));
247
273
  const snapshot = await runtime.snapshot();
248
274
  if (command === "tools") {
249
275
  const lastToolAudit = deps.getLastToolAudit();
@@ -59,7 +59,17 @@ export function updateContextSettings(settings: ContextSettings, target: string,
59
59
  validate(options, target === "default");
60
60
  return next;
61
61
  }
62
- export function resolveContextOptions(model: { id: string; contextWindow: number; maxTokens: number }, settings: ContextSettings) {
62
+
63
+ export interface ResolvedContextOptions {
64
+ contextWindow: number;
65
+ maxTokens: number;
66
+ reserveTokens: number;
67
+ inputTokenBudget: number;
68
+ maxTransferBytes: number;
69
+ maxImageBytes: number;
70
+ }
71
+
72
+ export function resolveContextOptions(model: { id: string; contextWindow: number; maxTokens: number }, settings: ContextSettings): ResolvedContextOptions {
63
73
  const options = { ...settings.defaults, ...settings.models[model.id] };
64
74
  const contextWindow = options.contextWindow ?? model.contextWindow;
65
75
  const maxTokens = options.maxTokens ?? model.maxTokens;
@@ -1,6 +1,6 @@
1
1
  // Adapter-owned context transfer. The pinned upstream dependency stays intact.
2
2
  import { getCurrentSystemPrompt } from "@earendil-works/pi-ai/utils/transcript";
3
- import { estimateTransferTokens, resolveContextOptions, type ContextOptions } from "./context-settings.ts";
3
+ import { estimateTransferTokens, resolveContextOptions, type ContextOptions, type ResolvedContextOptions } from "./context-settings.ts";
4
4
  export interface TransferBlock {
5
5
  type: string;
6
6
  text?: string;
@@ -42,8 +42,14 @@ export function historyBudget(_contextWindow = 32_768, env = process.env, config
42
42
 
43
43
  export function buildPromptParts(context: TransferContext, fresh: boolean, unseenStart?: number,
44
44
  limits: { contextWindow?: number; maxTokens?: number; policy?: ContextOptions } = {}) {
45
- const options = resolveContextOptions({ id: "transfer", contextWindow: limits.contextWindow ?? 32_768, maxTokens: limits.maxTokens ?? 8192 },
46
- { defaults: limits.policy ?? {}, models: {} });
45
+ // The runtime hot path always passes a fully resolved ompContextPolicy
46
+ // (see scripts/build.mjs); re-resolution is only needed for partial input.
47
+ const policy = limits.policy;
48
+ const options: ResolvedContextOptions = policy &&
49
+ typeof policy.inputTokenBudget === "number" && typeof policy.maxTransferBytes === "number" && typeof policy.maxImageBytes === "number"
50
+ ? policy
51
+ : resolveContextOptions({ id: "transfer", contextWindow: limits.contextWindow ?? 32_768, maxTokens: limits.maxTokens ?? 8192 },
52
+ { defaults: limits.policy ?? {}, models: {} });
47
53
  const messages = context.messages;
48
54
  let latest = messages.length - 1;
49
55
  while (latest >= 0 && messages[latest]!.role !== "user") latest--;
@@ -94,7 +100,8 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
94
100
  tailBlocks.push(continuation);
95
101
  } else {
96
102
  const content = messages[latest]!.content;
97
- const latestBlocks = typeof content === "string" ? [{ type: "text", text: content }] : content.map(block => ({ ...block }));
103
+ // Blocks are consumed read-only; shallow copies only churn the hot path.
104
+ const latestBlocks: TransferBlock[] = typeof content === "string" ? [{ type: "text", text: content }] : content;
98
105
  prompt.push(...latestBlocks);
99
106
  tailBlocks.push(...latestBlocks);
100
107
  }
@@ -104,7 +111,7 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
104
111
  let imageCount = 0;
105
112
  let imageWireChars = 0;
106
113
  const tailTextOnly: TransferBlock[] = [];
107
- for (const block of [...images, ...tailBlocks]) {
114
+ for (const group of [images, tailBlocks]) for (const block of group) {
108
115
  if (block.type !== "image") {
109
116
  tailTextOnly.push(block);
110
117
  continue;
@@ -1,12 +1,13 @@
1
1
  // OMP 18.x adapter for pi-antigravity-acp-provider 0.1.15 (Pi 1.1 API).
2
2
  // Keep upstream code intact; translate only the provider registration contract.
3
+ import fs from "node:fs";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
5
6
  import { applyApiCostEstimate } from "./pricing.ts";
6
7
  import { SessionRuntimePool } from "./runtime-pool.ts";
7
8
  import { stableTools } from "./tool-order.ts";
8
9
  import { loadContextSettings } from "./context-settings.ts";
9
- import { projectCatalog, selectRuntimeModel, type PublicCatalogModel } from "./model-catalog.ts";
10
+ import { selectRuntimeModel, type PublicCatalogModel } from "./model-catalog.ts";
10
11
  import { TOOL_ROUTING } from "./tool-routing.ts";
11
12
  import { loadToolPolicy } from "./tool-policy.ts";
12
13
  import {
@@ -22,6 +23,7 @@ import { createAntigravityCommandHandler, type RuntimeBundleView, type ToolAudit
22
23
  import {
23
24
  AcpSessionStore,
24
25
  AntigravityRuntime,
26
+ clearAntigravityCredentials,
25
27
  FALLBACK_MODELS,
26
28
  PERMISSION_RESULT_KIND,
27
29
  PERMISSION_TOOL_NAME,
@@ -58,8 +60,20 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
58
60
  let contextSettings = loadContextSettings(contextPath);
59
61
  let toolPolicy = loadToolPolicy(toolPolicyPath);
60
62
  let permissionMode = loadConfig(configPath).permissions;
61
- const sessionStore = new AcpSessionStore(path.join(stateDir, "sessions.json"));
63
+ const sessionStorePath = path.join(stateDir, "sessions.json");
64
+ const sessionStore = new AcpSessionStore(sessionStorePath);
62
65
  const cleanup = new SessionCleanup(stateDir);
66
+ // AcpSessionStore.read is private upstream; count saved records from the
67
+ // file so /antigravity-acp account needs no live runtime.
68
+ const savedSessionCount = (): number => {
69
+ try {
70
+ const parsed: unknown = JSON.parse(fs.readFileSync(sessionStorePath, "utf8"));
71
+ return Array.isArray(parsed)
72
+ ? parsed.filter(record => Boolean(record) && typeof record === "object" &&
73
+ typeof (record as { piSessionId?: unknown }).piSessionId === "string").length
74
+ : 0;
75
+ } catch { return 0; }
76
+ };
63
77
 
64
78
  // Loading this global extension must not start ACP or query Google.
65
79
  let readiness: Promise<void> | undefined;
@@ -85,7 +99,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
85
99
  audit: ToolAuditSummary;
86
100
  } | undefined;
87
101
 
88
- const runtimes = new SessionRuntimePool(() => {
102
+ const runtimes = new SessionRuntimePool<RuntimeBundleView>(() => {
89
103
  const ownedConnections = new Set<TierConnection>();
90
104
  const runtime = new AntigravityRuntime((options: ConstructorParameters<typeof TierConnection>[0]) => {
91
105
  const connection = new TierConnection({
@@ -133,8 +147,11 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
133
147
  connections,
134
148
  isPoolBusy: () => runtimes.values().some(bundle => bundle.isBusy()),
135
149
  logoutAllRuntimes: async () => {
136
- runtimes.get();
137
150
  await Promise.all(runtimes.values().map(bundle => bundle.runtime.logout()));
151
+ // Finish the Antigravity-side cleanup even when the pool is empty,
152
+ // instead of instantiating a runtime just to log it out.
153
+ sessionStore.clear();
154
+ clearAntigravityCredentials();
138
155
  },
139
156
  closeAllRuntimes: () => runtimes.closeAll(),
140
157
  onSyncProvider: syncProviderRegistration,
@@ -185,8 +202,11 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
185
202
  setToolPolicy: next => { toolPolicy = next; },
186
203
  setPermissionModeState: mode => { permissionMode = mode; },
187
204
  getLastToolAudit: () => lastToolAudit,
188
- getRuntimeForSession: sessionId => runtimes.get(sessionId) as unknown as RuntimeBundleView,
189
- getAllRuntimes: () => runtimes.values() as unknown as RuntimeBundleView[],
205
+ getRuntimeForSession: sessionId => runtimes.get(sessionId),
206
+ peekRuntimeForSession: sessionId => runtimes.peek(sessionId),
207
+ getSavedSessionCount: savedSessionCount,
208
+ getPermissionMode: () => permissionMode,
209
+ getAllRuntimes: () => runtimes.values(),
190
210
  closeAllRuntimes: () => runtimes.closeAll(),
191
211
  onModelsUpdated: models => {
192
212
  initialModels = models;
@@ -213,9 +233,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
213
233
  async fetchDynamicModels() {
214
234
  // OMP may call this during startup, even for another provider.
215
235
  // Network discovery is reserved for explicit refresh or first ACP use.
216
- const cached = catalogStore.readCachedCatalog();
217
- const base = cached.length ? projectCatalog(cached) : [...(FALLBACK_MODELS as PublicCatalogModel[])];
218
- return catalogStore.projectWithSettings(base, contextSettings);
236
+ return catalogStore.getDynamicModels(contextSettings);
219
237
  },
220
238
  streamSimple(
221
239
  model: { id: string },
@@ -225,10 +243,14 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
225
243
  const inputTools = context.tools ?? [];
226
244
  let tools: Array<{ name: string }>;
227
245
  let availableNames: string;
228
- if (cachedToolProjection && cachedToolProjection.ref === inputTools) {
229
- tools = cachedToolProjection.tools;
230
- availableNames = cachedToolProjection.availableNames;
231
- lastToolAudit = cachedToolProjection.audit;
246
+ const cached = cachedToolProjection;
247
+ // Hosts may rebuild the tools array each turn; equal contents hit.
248
+ if (cached && (cached.ref === inputTools ||
249
+ (cached.ref !== undefined && cached.ref.length === inputTools.length &&
250
+ inputTools.every((tool, index) => tool === cached.ref![index])))) {
251
+ tools = cached.tools;
252
+ availableNames = cached.availableNames;
253
+ lastToolAudit = cached.audit;
232
254
  } else {
233
255
  tools = stableTools(inputTools);
234
256
  const bridged = tools.filter(tool => tool.name !== PERMISSION_TOOL_NAME);
@@ -22,6 +22,12 @@ export interface PublicCatalogModel {
22
22
  thinking?: { mode: "effort"; efforts: string[]; defaultLevel?: string };
23
23
  }
24
24
  const ROUTE_PREFIX = "__omp_acp_thought__:";
25
+ // Single source for the legacy "<base>-<effort>" advertised ID suffix.
26
+ const LEGACY_EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORTS.join("|")})$`);
27
+ export function splitLegacyEffort(modelId: string): { base: string; effort: string } | undefined {
28
+ const match = modelId.match(LEGACY_EFFORT_SUFFIX);
29
+ return match ? { base: match[1]!, effort: match[2]! } : undefined;
30
+ }
25
31
  export function validId(value: unknown): value is string {
26
32
  return typeof value === "string" && value.length > 0 && value.length <= 256 &&
27
33
  value === value.trim() && !/[\u0000-\u001f\u007f]/u.test(value);
@@ -74,13 +80,12 @@ export function projectCatalog(value: unknown): PublicCatalogModel[] {
74
80
  const groups = new Map<string, { name: string; map: Record<string, string>; count: number }>();
75
81
  for (const record of records) {
76
82
  if (record.selector) continue;
77
- const match = record.modelId.match(/^(.+)-(off|minimal|low|medium|high|xhigh|max)$/);
78
- if (!match) continue;
79
- const [, base, effort] = match;
80
- const group = groups.get(base!) ?? { name: record.name.replace(/\s*\((?:off|minimal|low|medium|high|xhigh|max)\)\s*$/i, ""), map: {}, count: 0 };
81
- group.map[effort!] = record.modelId;
83
+ const legacy = splitLegacyEffort(record.modelId);
84
+ if (!legacy) continue;
85
+ const group = groups.get(legacy.base) ?? { name: record.name.replace(/\s*\((?:off|minimal|low|medium|high|xhigh|max)\)\s*$/i, ""), map: {}, count: 0 };
86
+ group.map[legacy.effort] = record.modelId;
82
87
  group.count = Object.keys(group.map).length;
83
- groups.set(base!, group);
88
+ groups.set(legacy.base, group);
84
89
  }
85
90
  const emitted = new Set<string>();
86
91
  const models: PublicCatalogModel[] = [];
@@ -94,9 +99,9 @@ export function projectCatalog(value: unknown): PublicCatalogModel[] {
94
99
  emitted.add(record.modelId);
95
100
  continue;
96
101
  }
97
- const match = record.modelId.match(/^(.+)-(off|minimal|low|medium|high|xhigh|max)$/);
98
- const group = match ? groups.get(match[1]!) : groups.get(record.modelId);
99
- const id = group && group.count > 1 && match ? match[1]! : record.modelId;
102
+ const legacy = splitLegacyEffort(record.modelId);
103
+ const group = legacy ? groups.get(legacy.base) : groups.get(record.modelId);
104
+ const id = group && group.count > 1 && legacy ? legacy.base : record.modelId;
100
105
  if (emitted.has(id)) continue;
101
106
  models.push(publicModel(id, group?.name || record.name || id, group?.map));
102
107
  emitted.add(id);
@@ -3,7 +3,7 @@
3
3
  export class SessionRuntimePool<T> {
4
4
  private readonly entries = new Map<string | undefined, T>();
5
5
  private readonly leases = new Map<T, number>();
6
- private readonly timers = new Map<T, ReturnType<typeof setTimeout>>();
6
+ private readonly timers = new Map<T, NodeJS.Timeout>();
7
7
 
8
8
  constructor(
9
9
  private readonly create: () => T,
@@ -21,6 +21,11 @@ export class SessionRuntimePool<T> {
21
21
  return entry;
22
22
  }
23
23
 
24
+ // Inspection without instantiating: command handlers that only report
25
+ // state must not spawn an idle ACP runtime for a fresh session.
26
+ peek(sessionId?: string): T | undefined {
27
+ return this.entries.get(sessionId);
28
+ }
24
29
  acquire(sessionId?: string) {
25
30
  const value = this.get(sessionId);
26
31
  this.leases.set(value, (this.leases.get(value) ?? 0) + 1);
@@ -36,8 +41,7 @@ export class SessionRuntimePool<T> {
36
41
  }
37
42
 
38
43
  private clearTimer(entry: T) {
39
- const timer = this.timers.get(entry);
40
- if (timer) clearTimeout(timer);
44
+ clearTimeout(this.timers.get(entry));
41
45
  this.timers.delete(entry);
42
46
  }
43
47
 
@@ -59128,7 +59128,8 @@ function historyBudget(_contextWindow = 32768, env2 = process.env, configured =
59128
59128
  return bytes;
59129
59129
  }
59130
59130
  function buildPromptParts(context, fresh, unseenStart, limits = {}) {
59131
- const options = resolveContextOptions(
59131
+ const policy = limits.policy;
59132
+ const options = policy && typeof policy.inputTokenBudget === "number" && typeof policy.maxTransferBytes === "number" && typeof policy.maxImageBytes === "number" ? policy : resolveContextOptions(
59132
59133
  { id: "transfer", contextWindow: limits.contextWindow ?? 32768, maxTokens: limits.maxTokens ?? 8192 },
59133
59134
  { defaults: limits.policy ?? {}, models: {} }
59134
59135
  );
@@ -59183,7 +59184,7 @@ ${instructions}` : "";
59183
59184
  tailBlocks.push(continuation);
59184
59185
  } else {
59185
59186
  const content = messages[latest].content;
59186
- const latestBlocks = typeof content === "string" ? [{ type: "text", text: content }] : content.map((block) => ({ ...block }));
59187
+ const latestBlocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
59187
59188
  prompt.push(...latestBlocks);
59188
59189
  tailBlocks.push(...latestBlocks);
59189
59190
  }
@@ -59191,7 +59192,7 @@ ${instructions}` : "";
59191
59192
  let imageCount = 0;
59192
59193
  let imageWireChars = 0;
59193
59194
  const tailTextOnly = [];
59194
- for (const block of [...images, ...tailBlocks]) {
59195
+ for (const group2 of [images, tailBlocks]) for (const block of group2) {
59195
59196
  if (block.type !== "image") {
59196
59197
  tailTextOnly.push(block);
59197
59198
  continue;
@@ -60396,7 +60397,13 @@ function stream(runtime, model, context, options) {
60396
60397
  }
60397
60398
 
60398
60399
  // extension/model-catalog.ts
60400
+ var EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
60399
60401
  var ROUTE_PREFIX = "__omp_acp_thought__:";
60402
+ var LEGACY_EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORTS.join("|")})$`);
60403
+ function splitLegacyEffort(modelId) {
60404
+ const match = modelId.match(LEGACY_EFFORT_SUFFIX);
60405
+ return match ? { base: match[1], effort: match[2] } : void 0;
60406
+ }
60400
60407
  function validId(value) {
60401
60408
  return typeof value === "string" && value.length > 0 && value.length <= 256 && value === value.trim() && !/[\u0000-\u001f\u007f]/u.test(value);
60402
60409
  }
@@ -60425,8 +60432,8 @@ function resolveSelection(state, requested) {
60425
60432
  if (!values.includes(local.modelId)) throw new Error(`ACP no longer advertises model ${local.modelId}`);
60426
60433
  return local;
60427
60434
  }
60428
- const legacy = requested.match(/^(.+)-(off|minimal|low|medium|high|xhigh|max)$/);
60429
- if (legacy && values.includes(legacy[1])) return { modelId: legacy[1], effort: legacy[2] };
60435
+ const legacy = splitLegacyEffort(requested);
60436
+ if (legacy && values.includes(legacy.base)) return { modelId: legacy.base, effort: legacy.effort };
60430
60437
  return { modelId: requested };
60431
60438
  }
60432
60439
 
@@ -60529,7 +60536,7 @@ var TierConnection = class extends AntigravityAcpConnection {
60529
60536
  contextUsage = /* @__PURE__ */ new Map();
60530
60537
  usageStatus = /* @__PURE__ */ new Map();
60531
60538
  usageBaselines = /* @__PURE__ */ new Map();
60532
- usageCapture;
60539
+ usageCaptures = /* @__PURE__ */ new Map();
60533
60540
  usageCommands = /* @__PURE__ */ new Set();
60534
60541
  cleanup;
60535
60542
  cleanupLeases = /* @__PURE__ */ new Map();
@@ -60550,9 +60557,10 @@ var TierConnection = class extends AntigravityAcpConnection {
60550
60557
  if (update.sessionUpdate === "usage_update" && typeof update.used === "number" && Number.isSafeInteger(update.used) && typeof update.size === "number" && Number.isSafeInteger(update.size)) {
60551
60558
  this.contextUsage.set(notification.sessionId, { used: update.used, size: update.size });
60552
60559
  }
60553
- if (this.usageCapture && this.usageCapture.sessionId === notification.sessionId) {
60560
+ const capture = this.usageCaptures.get(notification.sessionId);
60561
+ if (capture) {
60554
60562
  if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text" && typeof update.content.text === "string") {
60555
- this.usageCapture.text += update.content.text;
60563
+ capture.text += update.content.text;
60556
60564
  }
60557
60565
  return;
60558
60566
  }
@@ -60634,12 +60642,13 @@ var TierConnection = class extends AntigravityAcpConnection {
60634
60642
  this.usageStatus?.clear();
60635
60643
  this.usageBaselines?.clear();
60636
60644
  this.usageCommands?.clear();
60645
+ this.usageCaptures?.clear();
60637
60646
  }
60638
60647
  async readUsage(sessionId, signal) {
60639
60648
  const started = performance.now();
60640
60649
  this.usageQueryCount++;
60641
- const capture = { sessionId, text: "" };
60642
- this.usageCapture = capture;
60650
+ const capture = { text: "" };
60651
+ this.usageCaptures.set(sessionId, capture);
60643
60652
  try {
60644
60653
  const deadline = AbortSignal.timeout(5e3);
60645
60654
  await super.prompt(
@@ -60648,7 +60657,7 @@ var TierConnection = class extends AntigravityAcpConnection {
60648
60657
  );
60649
60658
  return parseSessionUsage(capture.text);
60650
60659
  } finally {
60651
- if (this.usageCapture === capture) this.usageCapture = void 0;
60660
+ if (this.usageCaptures.get(sessionId) === capture) this.usageCaptures.delete(sessionId);
60652
60661
  this.usageQueryMs += performance.now() - started;
60653
60662
  }
60654
60663
  }
@@ -60738,14 +60747,6 @@ function validate2(policy) {
60738
60747
  }
60739
60748
  return { mode: candidate.mode, idleDays: candidate.idleDays };
60740
60749
  }
60741
- function loadCleanupPolicy(file2) {
60742
- try {
60743
- return validate2(JSON.parse(fs10.readFileSync(file2, "utf8")));
60744
- } catch (error62) {
60745
- if (isMissingFileError(error62)) return { ...DEFAULT };
60746
- throw error62;
60747
- }
60748
- }
60749
60750
  function saveCleanupPolicy(file2, policy) {
60750
60751
  writeJsonAtomic(file2, validate2(policy), false);
60751
60752
  }
@@ -60777,11 +60778,29 @@ var SessionCleanup = class {
60777
60778
  timer;
60778
60779
  lastTouched = /* @__PURE__ */ new Map();
60779
60780
  pendingTouches = /* @__PURE__ */ new Map();
60780
- configure(mode, idleDays = loadCleanupPolicy(this.policyPath).idleDays) {
60781
+ cachedPolicy;
60782
+ // Stat-based cache: release/collect/status otherwise re-read this file on
60783
+ // every call. mtime plus size covers test rewrites within the same ms.
60784
+ getPolicy() {
60785
+ try {
60786
+ const stat = fs10.statSync(this.policyPath);
60787
+ if (this.cachedPolicy && this.cachedPolicy.mtimeMs === stat.mtimeMs && this.cachedPolicy.size === stat.size) {
60788
+ return this.cachedPolicy.policy;
60789
+ }
60790
+ const policy = validate2(JSON.parse(fs10.readFileSync(this.policyPath, "utf8")));
60791
+ this.cachedPolicy = { mtimeMs: stat.mtimeMs, size: stat.size, policy };
60792
+ return policy;
60793
+ } catch (error62) {
60794
+ if (isMissingFileError(error62)) return { ...DEFAULT };
60795
+ throw error62;
60796
+ }
60797
+ }
60798
+ configure(mode, idleDays = this.getPolicy().idleDays) {
60781
60799
  saveCleanupPolicy(this.policyPath, { mode, idleDays });
60800
+ this.cachedPolicy = void 0;
60782
60801
  }
60783
60802
  status() {
60784
- return { ...loadCleanupPolicy(this.policyPath), file: this.policyPath, scope: "adapter-owned local ACP data" };
60803
+ return { ...this.getPolicy(), file: this.policyPath, scope: "adapter-owned local ACP data" };
60785
60804
  }
60786
60805
  start() {
60787
60806
  if (this.timer) return;
@@ -60874,17 +60893,19 @@ var SessionCleanup = class {
60874
60893
  }
60875
60894
  collect() {
60876
60895
  try {
60877
- const policy = loadCleanupPolicy(this.policyPath);
60896
+ const policy = this.getPolicy();
60878
60897
  if (policy.mode === "off") return 0;
60879
60898
  return this.transaction((registry2) => {
60880
60899
  let removed = 0;
60900
+ let dirs;
60881
60901
  registry2.sessions = registry2.sessions.filter((r) => {
60882
60902
  r.leases = r.leases.filter((l) => this.isLive(l.pid) || this.isLive(l.serverPid));
60883
60903
  if (!r.owned && r.leases.length === 0) return false;
60884
60904
  const eligible = r.owned && r.leases.length === 0 && (r.replaced === true || policy.mode === "timeout" && this.now() - r.lastUsed >= policy.idleDays * 864e5);
60885
60905
  if (!eligible) return true;
60886
60906
  try {
60887
- this.removeFiles(r.id);
60907
+ dirs ??= this.verifyCleanupRoot();
60908
+ this.removeFiles(r.id, dirs);
60888
60909
  this.lastTouched.delete(r.id);
60889
60910
  this.pendingTouches.delete(r.id);
60890
60911
  removed++;
@@ -60899,18 +60920,28 @@ var SessionCleanup = class {
60899
60920
  return 0;
60900
60921
  }
60901
60922
  }
60902
- removeFiles(id) {
60923
+ verifyCleanupRoot() {
60903
60924
  const root = path10.resolve(this.acpDir);
60904
60925
  if (fs10.realpathSync(root) !== root) throw new Error("Symlinked ACP root; refusing cleanup");
60905
60926
  const conversations = path10.join(root, "conversations");
60906
60927
  const brain = path10.join(root, "brain");
60928
+ for (const parent of [conversations, brain]) {
60929
+ try {
60930
+ if (fs10.realpathSync(parent) !== parent) throw new Error("Symlinked cleanup directory");
60931
+ } catch (error62) {
60932
+ if (!isMissingFileError(error62)) throw error62;
60933
+ }
60934
+ }
60935
+ return { conversations, brain };
60936
+ }
60937
+ removeFiles(id, dirs) {
60907
60938
  const targets = [
60908
- path10.join(conversations, `${id}.db`),
60909
- path10.join(conversations, `${id}.db-wal`),
60910
- path10.join(conversations, `${id}.db-shm`),
60911
- path10.join(conversations, `${id}.db-journal`),
60912
- path10.join(conversations, `${id}.meta`),
60913
- path10.join(brain, id)
60939
+ path10.join(dirs.conversations, `${id}.db`),
60940
+ path10.join(dirs.conversations, `${id}.db-wal`),
60941
+ path10.join(dirs.conversations, `${id}.db-shm`),
60942
+ path10.join(dirs.conversations, `${id}.db-journal`),
60943
+ path10.join(dirs.conversations, `${id}.meta`),
60944
+ path10.join(dirs.brain, id)
60914
60945
  ];
60915
60946
  const inspect = (file2) => {
60916
60947
  let stat;
@@ -60923,13 +60954,6 @@ var SessionCleanup = class {
60923
60954
  if (stat.isSymbolicLink() || !stat.isDirectory() && !stat.isFile()) throw new Error("Unsafe cleanup target");
60924
60955
  if (stat.isDirectory()) for (const child of fs10.readdirSync(file2)) inspect(path10.join(file2, child));
60925
60956
  };
60926
- for (const parent of [conversations, brain]) {
60927
- try {
60928
- if (fs10.realpathSync(parent) !== parent) throw new Error("Symlinked cleanup directory");
60929
- } catch (error62) {
60930
- if (!isMissingFileError(error62)) throw error62;
60931
- }
60932
- }
60933
60957
  for (const target of targets) inspect(target);
60934
60958
  for (const target of targets) fs10.rmSync(target, { recursive: true, force: true });
60935
60959
  }
@@ -1,4 +1,4 @@
1
- import { parseThoughtRoute, validId, type AdvertisedModel } from "./model-catalog.ts";
1
+ import { parseThoughtRoute, splitLegacyEffort, validId, type AdvertisedModel } from "./model-catalog.ts";
2
2
 
3
3
  export interface ConfigOptionChoice {
4
4
  value?: unknown;
@@ -46,7 +46,7 @@ export function resolveSelection(state: SelectorState | undefined, requested: st
46
46
  if (!values.includes(local.modelId)) throw new Error(`ACP no longer advertises model ${local.modelId}`);
47
47
  return local;
48
48
  }
49
- const legacy = requested.match(/^(.+)-(off|minimal|low|medium|high|xhigh|max)$/);
50
- if (legacy && values.includes(legacy[1]!)) return { modelId: legacy[1]!, effort: legacy[2]! };
49
+ const legacy = splitLegacyEffort(requested);
50
+ if (legacy && values.includes(legacy.base)) return { modelId: legacy.base, effort: legacy.effort };
51
51
  return { modelId: requested };
52
52
  }
@@ -40,9 +40,10 @@ function group(key: string) { return createHash("sha256").update(key).digest("he
40
40
  export class SessionCleanup {
41
41
  readonly policyPath: string;
42
42
  private readonly registryPath: string;
43
- private timer?: ReturnType<typeof setInterval>;
43
+ private timer?: NodeJS.Timeout;
44
44
  private readonly lastTouched = new Map<string, number>();
45
45
  private readonly pendingTouches = new Map<string, number>();
46
+ private cachedPolicy?: { mtimeMs: number; size: number; policy: CleanupPolicy };
46
47
  constructor(stateDir: string, readonly acpDir = resolveAntigravityAcpDirectory(),
47
48
  private readonly now = Date.now, private readonly isLive = live) {
48
49
  this.policyPath = path.join(stateDir, "cleanup.json");
@@ -50,10 +51,27 @@ export class SessionCleanup {
50
51
  const root = createHash("sha256").update(path.resolve(acpDir)).digest("hex").slice(0, 16);
51
52
  this.registryPath = path.join(stateDir, `cleanup-sessions-${root}.json`);
52
53
  }
53
- configure(mode: CleanupMode, idleDays = loadCleanupPolicy(this.policyPath).idleDays) {
54
+ // Stat-based cache: release/collect/status otherwise re-read this file on
55
+ // every call. mtime plus size covers test rewrites within the same ms.
56
+ private getPolicy(): CleanupPolicy {
57
+ try {
58
+ const stat = fs.statSync(this.policyPath);
59
+ if (this.cachedPolicy && this.cachedPolicy.mtimeMs === stat.mtimeMs && this.cachedPolicy.size === stat.size) {
60
+ return this.cachedPolicy.policy;
61
+ }
62
+ const policy = validate(JSON.parse(fs.readFileSync(this.policyPath, "utf8")));
63
+ this.cachedPolicy = { mtimeMs: stat.mtimeMs, size: stat.size, policy };
64
+ return policy;
65
+ } catch (error: unknown) {
66
+ if (isMissingFileError(error)) return { ...DEFAULT };
67
+ throw error;
68
+ }
69
+ }
70
+ configure(mode: CleanupMode, idleDays = this.getPolicy().idleDays) {
54
71
  saveCleanupPolicy(this.policyPath, { mode, idleDays });
72
+ this.cachedPolicy = undefined;
55
73
  }
56
- status() { return { ...loadCleanupPolicy(this.policyPath), file: this.policyPath, scope: "adapter-owned local ACP data" }; }
74
+ status() { return { ...this.getPolicy(), file: this.policyPath, scope: "adapter-owned local ACP data" }; }
57
75
  start() {
58
76
  if (this.timer) return;
59
77
  this.collect();
@@ -134,10 +152,13 @@ export class SessionCleanup {
134
152
  }
135
153
  collect(): number {
136
154
  try {
137
- const policy = loadCleanupPolicy(this.policyPath);
155
+ const policy = this.getPolicy();
138
156
  if (policy.mode === "off") return 0;
139
157
  return this.transaction(registry => {
140
158
  let removed = 0;
159
+ // Verify the cleanup root once per collect, lazily on the first
160
+ // eligible session instead of once per removed session.
161
+ let dirs: { conversations: string; brain: string } | undefined;
141
162
  registry.sessions = registry.sessions.filter(r => {
142
163
  r.leases = r.leases.filter(l => this.isLive(l.pid) || this.isLive(l.serverPid));
143
164
  if (!r.owned && r.leases.length === 0) return false;
@@ -145,7 +166,8 @@ export class SessionCleanup {
145
166
  (policy.mode === "timeout" && this.now() - r.lastUsed >= policy.idleDays * 86_400_000));
146
167
  if (!eligible) return true;
147
168
  try {
148
- this.removeFiles(r.id);
169
+ dirs ??= this.verifyCleanupRoot();
170
+ this.removeFiles(r.id, dirs);
149
171
  this.lastTouched.delete(r.id);
150
172
  this.pendingTouches.delete(r.id);
151
173
  removed++;
@@ -157,24 +179,27 @@ export class SessionCleanup {
157
179
  });
158
180
  } catch { return 0; }
159
181
  }
160
- private removeFiles(id: string) {
182
+ private verifyCleanupRoot(): { conversations: string; brain: string } {
161
183
  const root = path.resolve(this.acpDir);
162
184
  if (fs.realpathSync(root) !== root) throw new Error("Symlinked ACP root; refusing cleanup");
163
185
  const conversations = path.join(root, "conversations");
164
186
  const brain = path.join(root, "brain");
165
- const targets = [path.join(conversations, `${id}.db`), path.join(conversations, `${id}.db-wal`),
166
- path.join(conversations, `${id}.db-shm`), path.join(conversations, `${id}.db-journal`),
167
- path.join(conversations, `${id}.meta`), path.join(brain, id)];
187
+ for (const parent of [conversations, brain]) {
188
+ try { if (fs.realpathSync(parent) !== parent) throw new Error("Symlinked cleanup directory"); }
189
+ catch (error: unknown) { if (!isMissingFileError(error)) throw error; }
190
+ }
191
+ return { conversations, brain };
192
+ }
193
+ private removeFiles(id: string, dirs: { conversations: string; brain: string }) {
194
+ const targets = [path.join(dirs.conversations, `${id}.db`), path.join(dirs.conversations, `${id}.db-wal`),
195
+ path.join(dirs.conversations, `${id}.db-shm`), path.join(dirs.conversations, `${id}.db-journal`),
196
+ path.join(dirs.conversations, `${id}.meta`), path.join(dirs.brain, id)];
168
197
  const inspect = (file: string) => {
169
198
  let stat: fs.Stats;
170
199
  try { stat = fs.lstatSync(file); } catch (error: unknown) { if (isMissingFileError(error)) return; throw error; }
171
200
  if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) throw new Error("Unsafe cleanup target");
172
201
  if (stat.isDirectory()) for (const child of fs.readdirSync(file)) inspect(path.join(file, child));
173
202
  };
174
- for (const parent of [conversations, brain]) {
175
- try { if (fs.realpathSync(parent) !== parent) throw new Error("Symlinked cleanup directory"); }
176
- catch (error: unknown) { if (!isMissingFileError(error)) throw error; }
177
- }
178
203
  for (const target of targets) inspect(target);
179
204
  for (const target of targets) fs.rmSync(target, { recursive: true, force: true });
180
205
  }
@@ -17,7 +17,7 @@ export class TierConnection extends AntigravityAcpConnection {
17
17
  readonly contextUsage = new Map<string, { used: number; size: number }>();
18
18
  readonly usageStatus = new Map<string, { source: string; cache: string; error?: string }>();
19
19
  private readonly usageBaselines = new Map<string, SessionUsage>();
20
- private usageCapture: { sessionId: string; text: string } | undefined;
20
+ private readonly usageCaptures = new Map<string, { text: string }>();
21
21
  private readonly usageCommands = new Set<string>();
22
22
  private cleanup?: SessionCleanup;
23
23
  private cleanupLeases = new Map<string, string>();
@@ -45,9 +45,10 @@ export class TierConnection extends AntigravityAcpConnection {
45
45
  if (update.sessionUpdate === "usage_update" && typeof update.used === "number" && Number.isSafeInteger(update.used) && typeof update.size === "number" && Number.isSafeInteger(update.size)) {
46
46
  this.contextUsage.set(notification.sessionId, { used: update.used, size: update.size });
47
47
  }
48
- if (this.usageCapture && this.usageCapture.sessionId === notification.sessionId) {
48
+ const capture = this.usageCaptures.get(notification.sessionId);
49
+ if (capture) {
49
50
  if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text" && typeof update.content.text === "string") {
50
- this.usageCapture.text += update.content.text;
51
+ capture.text += update.content.text;
51
52
  }
52
53
  return;
53
54
  }
@@ -121,20 +122,21 @@ export class TierConnection extends AntigravityAcpConnection {
121
122
  this.usageStatus?.clear();
122
123
  this.usageBaselines?.clear();
123
124
  this.usageCommands?.clear();
125
+ this.usageCaptures?.clear();
124
126
  }
125
127
 
126
128
  private async readUsage(sessionId: string, signal?: AbortSignal) {
127
129
  const started = performance.now();
128
130
  this.usageQueryCount++;
129
- const capture = { sessionId, text: "" };
130
- this.usageCapture = capture;
131
+ const capture = { text: "" };
132
+ this.usageCaptures.set(sessionId, capture);
131
133
  try {
132
134
  const deadline = AbortSignal.timeout(5_000);
133
135
  await super.prompt({ sessionId, prompt: [{ type: "text", text: "/usage" }] },
134
136
  signal ? AbortSignal.any([signal, deadline]) : deadline);
135
137
  return parseSessionUsage(capture.text);
136
138
  } finally {
137
- if (this.usageCapture === capture) this.usageCapture = undefined;
139
+ if (this.usageCaptures.get(sessionId) === capture) this.usageCaptures.delete(sessionId);
138
140
  this.usageQueryMs += performance.now() - started;
139
141
  }
140
142
  }
@@ -35,6 +35,8 @@ export function saveDebugToolUpdates(file: string, enabled: boolean) {
35
35
  saveToolPolicy(file, { ...loadToolPolicy(file), debugToolUpdates: enabled });
36
36
  }
37
37
 
38
- function saveToolPolicy(file: string, policy: ToolPolicy) {
38
+ export function saveToolPolicy(file: string, policy: ToolPolicy) {
39
+ parseNativeToolMode(policy.nativeTools);
40
+ if (typeof policy.debugToolUpdates !== "boolean") throw new Error("debugToolUpdates must be boolean");
39
41
  writeJsonAtomic(file, policy);
40
42
  }
@@ -1,7 +1,21 @@
1
1
  import { usageFromPrompt as upstreamUsage } from "pi-antigravity-acp-provider/src/stream/usage.ts";
2
2
 
3
- export function usageFromPrompt(response: Parameters<typeof upstreamUsage>[0] & { _meta?: { ompContextTokens?: unknown } }) {
4
- const usage: ReturnType<typeof upstreamUsage> & { contextTokens?: number } = upstreamUsage(response);
3
+ // Named shape of the upstream usage projection (pi-ai Usage) plus this
4
+ // adapter's contextTokens extension, so callers never depend on
5
+ // ReturnType<typeof …>.
6
+ export interface PromptUsageResult {
7
+ input: number;
8
+ output: number;
9
+ cacheRead: number;
10
+ cacheWrite: number;
11
+ totalTokens: number;
12
+ reasoning?: number;
13
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
14
+ contextTokens?: number;
15
+ }
16
+
17
+ export function usageFromPrompt(response: Parameters<typeof upstreamUsage>[0] & { _meta?: { ompContextTokens?: unknown } }): PromptUsageResult {
18
+ const usage: PromptUsageResult = upstreamUsage(response);
5
19
  const context = response._meta?.ompContextTokens;
6
20
  // OMP accepts contextTokens independently from aggregate billable tokens.
7
21
  if (typeof context === "number" && Number.isSafeInteger(context) && context >= 0) usage.contextTokens = context;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-antigravity-acp-provider",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "Google Antigravity ACP provider for Oh My Pi (OMP), with tool bridging and per-model thinking; derived from zacbemis/pi-antigravity-acp-provider",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,9 +41,10 @@
41
41
  "test:commands": "bun scripts/test-tool-command.ts",
42
42
  "test:auth": "bun scripts/test-auth-command.ts",
43
43
  "test:cleanup": "node scripts/test-cleanup-runtime.ts",
44
- "check": "npm run build && npm test && npm run test:cleanup",
44
+ "check": "npm run build && npm test && npm run test:cleanup && npm run test:graph",
45
45
  "prepack": "npm run build",
46
- "prepublishOnly": "npm run check"
46
+ "prepublishOnly": "npm run check",
47
+ "test:graph": "bun scripts/test-load-graph.ts"
47
48
  },
48
49
  "dependencies": {
49
50
  "@earendil-works/pi-ai": "1.3.0",