omp-antigravity-acp-provider 0.1.7 → 0.1.9

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.7 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.9 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.7** 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.9** 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.7
83
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.9
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.
@@ -149,6 +149,15 @@ After upgrading from an older adapter, run `/antigravity-acp refresh` once to re
149
149
  | --- | --- |
150
150
  | `/antigravity-acp status` | Runtime, confirmed thinking and usage information |
151
151
  | `/antigravity-acp usage` | Current ACP context occupancy, accounting source and cache-data availability |
152
+ | `/antigravity-acp usage auto` | Enable supplemental usage queries |
153
+ | `/antigravity-acp usage off` | Skip supplemental queries; preserve context occupancy updates |
154
+ | `/antigravity-acp context` | Show saved settings and effective per-model budgets |
155
+ | `/antigravity-acp context set default KEY NUMBER` | Set a default token or payload setting |
156
+ | `/antigravity-acp context set MODEL KEY NUMBER` | Override one advertised model ID |
157
+ | `/antigravity-acp cleanup` | Show cleanup mode/deadline and check eligible local sessions |
158
+ | `/antigravity-acp cleanup off` | Disable automatic session-file deletion |
159
+ | `/antigravity-acp cleanup conservative` | Delete confirmed replaced/disposable sessions only (default) |
160
+ | `/antigravity-acp cleanup timeout DAYS` | Also delete inactive owned sessions after DAYS (default 7) |
152
161
  | `/antigravity-acp tools` | Available and omitted OMP tool schemas after a request |
153
162
  | `/antigravity-acp refresh` | Explicit network discovery and local catalog refresh |
154
163
  | `/antigravity-acp native-tools prefer` | Prefer OMP tools; retain native built-ins (default) |
@@ -189,31 +198,98 @@ Never include those user data directories, OAuth callback URLs, account identifi
189
198
 
190
199
  ## Context continuity and local performance
191
200
 
192
- The adapter now transfers complete replay history within a bounded budget, including historical image attachments. It no longer silently keeps only a 32,000-character history tail. If a transfer does not fit, it stops with an explicit error requesting OMP `/compact` or smaller attachments. This is a local transfer limit, not Antigravity's model context window or its internal compaction threshold. Active requests, history text and system instructions share the text budget; images have a conservative allowance and a separate total payload ceiling of 8 MiB. No automatic summarization or extra inference is added by the transfer layer.
201
+ The adapter now transfers complete replay history within a bounded budget, including historical image attachments. It no longer silently keeps only a 32,000-character history tail. If a transfer does not fit, it stops with an explicit error requesting OMP `/compact` or smaller attachments. This is a local transfer limit, not Antigravity's model context window or its internal compaction threshold. Active requests, history text and system instructions share the token and wire budgets; images also have a separate decoded-data limit. No automatic summarization or extra inference is added by the transfer layer.
193
202
 
194
- The default text-equivalent budget is the smaller of 512 KiB and half the model's declared context-window number, measured in bytes rather than tokens. For the current Argon/Flash metadata this is 500,000 bytes. Byte budgeting does not replace tokenization or account for all hidden server instructions. Larger model context metadata is not a guarantee that every history can be imported. Latest requests and instructions are never silently shortened to fit.
203
+ Token budgets and wire payload size are independent; the former 500,000-byte clamp is removed. The default wire payload limit is 16 MiB, configurable up to 128 MiB. Image data additionally defaults to an 8 MiB decoded payload limit. The automatic input-token budget is `contextWindow - maxTokens - reserveTokens`, where reserve defaults to the smaller of 16,384 and 5% of the window. A lightweight Unicode-aware estimate checks serialized text plus approximately 4,096 tokens per image. This is not a Gemini tokenizer, cannot guarantee exact token counts and does not include every hidden server instruction.
204
+
205
+ Persist settings in `~/.omp/agent/antigravity-acp-provider/context.json`, or use the commands below. Defaults apply to every ACP model; entries under `models` override one advertised model ID. Model limits are client metadata and transfer budgets: they do not expand Google's server window or set an unsupported ACP generation-output parameter.
206
+
207
+ ```json
208
+ {
209
+ "defaults": {
210
+ "contextWindow": 524288,
211
+ "maxTokens": 32000,
212
+ "reserveTokens": 16384,
213
+ "maxTransferBytes": 16777216,
214
+ "maxImageBytes": 8388608,
215
+ "usageMode": "off"
216
+ },
217
+ "models": {}
218
+ }
219
+ ```
220
+
221
+ Numeric keys: `contextWindow`, `maxTokens`, `reserveTokens`, `inputTokenBudget`, `maxTransferBytes`, `maxImageBytes`. Omit `inputTokenBudget` to calculate it automatically. A custom input budget must fit alongside output and reserve. Settings load once per process, without disk reads on every streamed chunk. Direct file edits require a restart; commands persist settings and refresh registration in the current process. Restart OMP or reselect the model to refresh displayed metadata. Other OMP processes must restart.
222
+
223
+ ```text
224
+ /antigravity-acp context
225
+ /antigravity-acp context set default maxTransferBytes 33554432
226
+ /antigravity-acp context set gemini-4-argon contextWindow 1000000
227
+ /antigravity-acp usage off
228
+ /antigravity-acp usage auto
229
+ ```
230
+
231
+ For OMP-managed automatic compaction, keep `compaction.enabled`, `compaction.midTurnEnabled` and `compaction.autoContinue` enabled with a working method such as `soft`. A provider-specific threshold can be set without changing other providers:
232
+
233
+ ```sh
234
+ omp config set compaction.modelThresholds '{"antigravity-acp/*":"85%"}'
235
+ ```
236
+
237
+ Merge that map with existing model-specific entries before running the command. At the example 524,288-token window, 85% triggers at 445,644 tokens, below the automatic transfer estimate budget of 475,904 tokens. OMP can also recover from local context/payload overflow errors. Google independently controls its internal agent summaries. Plugin installation does not automatically change OMP's global compaction configuration.
195
238
 
196
239
  Active sessions are reused. After five idle minutes, the adapter closes its ACP runtime, bridge and child processes; the next request tries to restore the saved server session. Active streams, outstanding ACP prompts, tools and permission waits prevent eviction. No background model prewarming, quota polling or tokenizer model download is performed.
197
240
 
241
+ ### Local ACP session cleanup
242
+
243
+ Session-file deletion is separate from the five-minute idle process shutdown. Configure one of three modes:
244
+
245
+ | Mode | Behavior |
246
+ | --- | --- |
247
+ | `off` | Keep session files, including replaced sessions. Ownership/lease bookkeeping remains enabled so cleanup can be enabled later. |
248
+ | `conservative` (default) | Remove an old session after its OMP history is rebuilt (for example after `/compact`), a replacement successfully completes a turn, and all registered users of the old session have released it. Disposable model-discovery sessions are also removed after their connection exits. Ordinary shutdown and idle eviction preserve resumable sessions. |
249
+ | `timeout` | Conservative cleanup plus removal of owned sessions whose last activity exceeds `idleDays`. Default 7 days; accepts fractional days (for example `0.5` for 12 hours), with a minimum of one hour and a maximum of 3650 days. Live leases always override the deadline. |
250
+
251
+ ```text
252
+ /antigravity-acp cleanup
253
+ /antigravity-acp cleanup off
254
+ /antigravity-acp cleanup conservative
255
+ /antigravity-acp cleanup timeout 7
256
+ ```
257
+
258
+ Settings persist in `~/.omp/agent/antigravity-acp-provider/cleanup.json`:
259
+
260
+ ```json
261
+ { "mode": "conservative", "idleDays": 7 }
262
+ ```
263
+
264
+ Commands take effect immediately; direct file edits are read on the next cleanup check. Checks run when the cleanup service starts, after replacement/release, on the inspection command, and every 15 minutes while the service is running. OMP must be running for timed checks; the deadline is not an exact scheduled deletion time. No additional model requests, tokenizer downloads or background worker processes are used.
265
+
266
+ Only sessions created and registered by this adapter version onward are eligible. Pre-existing/unidentified ACP sessions are preserved. The registry is separated by the resolved ACP storage root, and tracks both OMP and ACP supervisor PIDs across participating processes. Resume/load acquires a lease before replay. Busy/corrupt registries and unsafe paths defer deletion. Restart older OMP instances when upgrading: clients that do not implement these leases, or external clients manually opening the same session, are outside this coordination mechanism.
267
+
268
+ Cleanup targets only the registered UUID's `.db`, SQLite journal/WAL/SHM files, `.meta`, and `brain/<UUID>` directory under the ACP storage root (normally `~/.gemini/antigravity-acp/`; respects `GEMINI_HOME`). Symlinked targets are preserved. Credentials, global settings, shared artifacts, workspace files and OMP's own conversation history are untouched. Local deletion is permanent and does not request deletion of Google's server-side logs. The current official ACP runtime does not advertise session deletion, so this uses the inspected local layout rather than an unsupported RPC.
269
+
270
+ Timeout cleanup sacrifices ACP-only reasoning/checkpoint state. The next request reconstructs a session from OMP's retained history and can incur replay latency and a different token count. Cache expiry is not assumed or guaranteed. Conservative mode avoids that tradeoff for ordinary resumable sessions; it does not bound the number of unrelated OMP conversations you keep.
271
+
198
272
  Optional environment settings, applied when OMP starts:
199
273
 
200
274
  | Setting | Default | Effect |
201
275
  | --- | --- | --- |
202
- | `OMP_ACP_HISTORY_BYTES` | `524288` | Transfer budget in bytes, validated between 16 KiB and 8 MiB and capped by model metadata |
276
+ | `OMP_ACP_HISTORY_BYTES` | context.json or 16 MiB | Optional byte-limit override, 64 KiB–128 MiB; independent of token window |
203
277
  | `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it, positive values must be at least `1000` |
204
- | `OMP_ACP_USAGE` | automatic | Set to `off` to skip supplemental `/usage` queries and minimize terminal-event latency |
278
+ | `OMP_ACP_USAGE` | context.json or auto | `off` forces supplemental queries off, including when the saved option is auto |
279
+
280
+ When automatic usage is enabled and `/usage` is advertised by the official server, the adapter queries it after each completed ACP prompt and computes a difference from the previous cumulative snapshot. A restored session first establishes a baseline so its old tokens are not charged again. These are main-agent totals and can include multiple internal model calls. Thinking tokens count toward estimated output cost. Queries are bounded by a five-second deadline; unavailable/malformed usage or a counter reset does not turn a successful model answer into a billing claim. Native ACP response usage takes priority when supplied. Query failures can cancel/retire the connection; subsequent work can restore the server session.
205
281
 
206
- When `/usage` is advertised by the official server, the adapter queries it after each completed ACP prompt and computes a difference from the previous cumulative snapshot. A restored session first establishes a baseline so its old tokens are not charged again. These are main-agent totals and can include multiple internal model calls. Thinking tokens count toward estimated output cost. Queries are bounded by a five-second deadline; unavailable/malformed usage or a counter reset does not turn a successful model answer into a billing claim. Native ACP response usage takes priority when supplied. Query failures can cancel/retire the connection; subsequent work can restore the server session.
282
+ Supplemental queries default to `auto` for compatibility; the example above opts out. Use `/antigravity-acp usage off` to reduce the delay between the last text chunk and OMP regaining control, or `auto` to retain available token/cache/cost estimates. In a Flash Low test with three turns per mode, that final delay had a median of **282 ms with auto vs 21 ms with off** (261 ms less). Individual queries took 241–580 ms. This small sample does not establish a universal speedup, and total response time also varies with inference. Turning queries off preserves ACP context-occupancy updates used by OMP compaction; missing accounting data stays unavailable.
207
283
 
208
284
  ACP `usage_update.used` is passed to OMP separately as `usage.contextTokens`, rather than treating aggregate billable consumption as context occupancy. OMP 18.12.3 recognizes this field; it can still use a local stored-history estimate when deciding whether to compact. Google continues to control its own internal summaries.
209
285
 
210
286
  Stable tool ordering and stable context-resource identifiers avoid unnecessary client-side prefix changes. They do not guarantee implicit cache hits. `/antigravity-acp usage` marks cache information as `unknown` when Google omits it; zero cache fields in OMP's numeric usage structure must not be read as proof of zero backend caching. If cache counts are missing, the API-equivalent estimate prices input as uncached and cannot reflect any unreported cache discount. This is not a subscription bill or a measurement of quota deduction.
211
287
 
212
- See the [continuity and resource verification report](docs/continuity-performance-0.1.7.md) for measured Flash behavior and remaining limits.
288
+ See the [0.1.8 context/compaction and usage benchmark](docs/context-compaction-0.1.8.md) for current settings and measurements. The [0.1.7 report](docs/continuity-performance-0.1.7.md) documents the previous implementation.
213
289
 
214
290
  ## Limitations
215
291
 
216
- - Argon/Flash retain client metadata of 1,000,000 context tokens and 65,536 output tokens. Other models use conservative defaults of 32,768 context tokens and 8,192 output tokens because the model selector does not supply these limits. These are client metadata, not verified server limits or controls over Antigravity's internal compaction.
292
+ - Argon/Flash default to client metadata of 1,000,000 context tokens and 65,536 output tokens. These can be overridden in context.json. Other models use conservative defaults of 32,768 context tokens and 8,192 output tokens because the model selector does not supply these limits. These are client metadata, not verified server limits or controls over Antigravity's internal compaction.
217
293
  - API background execution and long decode controls are not exposed.
218
294
  - The bridge advertises text and image input, not the full Gemini API media surface.
219
295
  - Thought summaries appear only if the ACP server emits them. A verified Argon High request returned no `agent_thought_chunk`; plan progress and optional debug tool-status lines can appear in OMP's thinking area.
@@ -0,0 +1,82 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export interface ContextOptions {
5
+ contextWindow?: number;
6
+ maxTokens?: number;
7
+ inputTokenBudget?: number;
8
+ reserveTokens?: number;
9
+ maxTransferBytes?: number;
10
+ maxImageBytes?: number;
11
+ }
12
+ export interface ContextSettings {
13
+ defaults: ContextOptions & { usageMode?: "auto" | "off" };
14
+ models: Record<string, ContextOptions>;
15
+ }
16
+ const ranges: Record<keyof ContextOptions, [number, number]> = {
17
+ contextWindow: [4096, 16_777_216], maxTokens: [1, 1_048_576], inputTokenBudget: [1, 16_777_216],
18
+ reserveTokens: [0, 1_048_576], maxTransferBytes: [65_536, 134_217_728], maxImageBytes: [0, 100_663_296],
19
+ };
20
+ function validate(options: any, allowUsage: boolean): void {
21
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("Context settings must be an object");
22
+ for (const [key, value] of Object.entries(options)) {
23
+ if (key === "usageMode" && allowUsage) {
24
+ if (value !== "auto" && value !== "off") throw new Error("usageMode must be auto or off");
25
+ continue;
26
+ }
27
+ const range = ranges[key as keyof ContextOptions];
28
+ if (!range || !Number.isSafeInteger(value) || (value as number) < range[0] || (value as number) > range[1]) {
29
+ throw new Error(`Invalid context setting ${key}${range ? `; expected ${range[0]}..${range[1]}` : ""}`);
30
+ }
31
+ }
32
+ }
33
+ export function loadContextSettings(file: string): ContextSettings {
34
+ let settings: any;
35
+ try { settings = JSON.parse(fs.readFileSync(file, "utf8")); }
36
+ catch (error: any) { if (error.code === "ENOENT") return { defaults: {}, models: {} }; throw error; }
37
+ if (!settings || Object.keys(settings).some(key => !["defaults", "models"].includes(key))) throw new Error("Invalid context settings file");
38
+ const defaults = settings.defaults ?? {}, models = settings.models ?? {};
39
+ validate(defaults, true);
40
+ if (!models || typeof models !== "object" || Array.isArray(models)) throw new Error("models must be an object");
41
+ for (const [id, options] of Object.entries(models)) {
42
+ if (!id || ["__proto__", "constructor", "prototype"].includes(id)) throw new Error("Invalid model ID");
43
+ validate(options, false);
44
+ }
45
+ return { defaults, models };
46
+ }
47
+ export function saveContextSettings(file: string, settings: ContextSettings) {
48
+ validate(settings.defaults, true);
49
+ for (const options of Object.values(settings.models)) validate(options, false);
50
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
51
+ const temporary = `${file}.${process.pid}.tmp`;
52
+ fs.writeFileSync(temporary, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
53
+ fs.renameSync(temporary, file);
54
+ }
55
+ export function updateContextSettings(settings: ContextSettings, target: string, key: string, value: number | string): ContextSettings {
56
+ if (["__proto__", "constructor", "prototype"].includes(target)) throw new Error("Invalid model ID");
57
+ const next = structuredClone(settings);
58
+ const options: any = target === "default" ? next.defaults : (next.models[target] ??= {});
59
+ options[key] = value;
60
+ validate(options, target === "default");
61
+ return next;
62
+ }
63
+ export function resolveContextOptions(model: { id: string; contextWindow: number; maxTokens: number }, settings: ContextSettings) {
64
+ const options = { ...settings.defaults, ...settings.models[model.id] };
65
+ const contextWindow = options.contextWindow ?? model.contextWindow;
66
+ const maxTokens = options.maxTokens ?? model.maxTokens;
67
+ const reserveTokens = options.reserveTokens ?? Math.min(16_384, Math.floor(contextWindow * 0.05));
68
+ const automatic = contextWindow - maxTokens - reserveTokens;
69
+ const inputTokenBudget = options.inputTokenBudget ?? automatic;
70
+ if (automatic <= 0 || inputTokenBudget > automatic) throw new Error(`Invalid token budgets for ${model.id}: input + output + reserve must fit contextWindow`);
71
+ return { contextWindow, maxTokens, reserveTokens, inputTokenBudget,
72
+ maxTransferBytes: options.maxTransferBytes ?? 16_777_216,
73
+ maxImageBytes: options.maxImageBytes ?? 8_388_608 };
74
+ }
75
+
76
+ // Lightweight estimate, not a Gemini tokenizer. Do not download tokenizers or
77
+ // confuse payload bytes with tokens. Non-ASCII receives a larger allowance.
78
+ export function estimateTransferTokens(text: string, images = 0) {
79
+ let nonAscii = 0;
80
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) > 127) nonAscii++;
81
+ return Math.ceil((text.length - nonAscii) / 3 + nonAscii * 1.5) + images * 4096;
82
+ }
@@ -1,23 +1,24 @@
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
4
  export function currentSystemInstructions(context: any): string {
4
5
  const prompt = getCurrentSystemPrompt(context.messages) || context.systemPrompt || "";
5
- if (Buffer.byteLength(prompt, "utf8") > 262_144) throw new Error("OMP system instructions exceed 262144 bytes; reduce them rather than truncating instructions");
6
+ if (Buffer.byteLength(prompt, "utf8") > 134_217_728) throw new Error("OMP system instructions exceed the 128 MiB hard transfer ceiling; reduce them rather than truncating instructions");
6
7
  return prompt;
7
8
  }
8
9
 
9
- export function historyBudget(contextWindow = 32_768, env = process.env): number {
10
- const configured = Number(env.OMP_ACP_HISTORY_BYTES ?? 524_288);
11
- if (!Number.isSafeInteger(configured) || configured < 16_384 || configured > 8_388_608) {
12
- throw new Error("OMP_ACP_HISTORY_BYTES must be an integer between 16384 and 8388608");
10
+ export function historyBudget(_contextWindow = 32_768, env = process.env, configured = 16_777_216): number {
11
+ const bytes = Number(env.OMP_ACP_HISTORY_BYTES ?? configured);
12
+ if (!Number.isSafeInteger(bytes) || bytes < 65_536 || bytes > 134_217_728) {
13
+ throw new Error("OMP_ACP_HISTORY_BYTES must be an integer between 65536 and 134217728");
13
14
  }
14
- // A byte budget is deliberately conservative; this is not a tokenizer.
15
- const modelBudget = Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow / 2) : 16_384;
16
- return Math.min(configured, Math.max(4096, modelBudget));
15
+ return bytes;
17
16
  }
18
17
 
19
18
  export function buildPromptParts(context: any, fresh: boolean, unseenStart?: number,
20
- limits: { contextWindow?: number } = {}) {
19
+ limits: { contextWindow?: number; maxTokens?: number; policy?: ContextOptions } = {}) {
20
+ const options = resolveContextOptions({ id: "transfer", contextWindow: limits.contextWindow ?? 32_768, maxTokens: limits.maxTokens ?? 8192 },
21
+ { defaults: limits.policy ?? {}, models: {} });
21
22
  const messages = context.messages;
22
23
  let latest = messages.length - 1;
23
24
  while (latest >= 0 && messages[latest].role !== "user") latest--;
@@ -68,15 +69,20 @@ export function buildPromptParts(context: any, fresh: boolean, unseenStart?: num
68
69
  // footprint separately, and reserve a conservative text-equivalent allowance.
69
70
  let imageBytes = 0;
70
71
  let imageCount = 0;
72
+ let imageWireChars = 0;
71
73
  const textOnly = prompt.map(block => {
72
74
  if (block.type !== "image") return block;
73
75
  imageBytes += Math.ceil((block.data?.length ?? 0) * 3 / 4);
76
+ imageWireChars += block.data?.length ?? 0;
74
77
  imageCount++;
75
78
  return { type: "image", mimeType: block.mimeType };
76
79
  });
77
- if (imageBytes > 8_388_608) throw new Error("ACP image transfer exceeds the 8 MiB local payload budget; reduce attachments. No images were silently omitted.");
78
- const bytes = Buffer.byteLength(JSON.stringify(textOnly), "utf8") + imageCount * 16_384;
79
- const budget = historyBudget(limits.contextWindow);
80
- if (bytes > budget) throw new Error(`ACP context transfer needs ${bytes} bytes; budget is ${budget}. Use OMP /compact to summarize history or reduce attachments. No history was silently truncated. OMP_ACP_HISTORY_BYTES configures the byte budget, capped by client model metadata.`);
80
+ if (imageBytes > options.maxImageBytes) throw new Error(`Request payload too large (413): local ACP image budget is ${options.maxImageBytes} bytes; reduce attachments. No images were silently omitted.`);
81
+ const serialized = JSON.stringify(textOnly);
82
+ const bytes = Buffer.byteLength(serialized, "utf8") + imageWireChars + imageCount * 10;
83
+ const budget = historyBudget(undefined, process.env, options.maxTransferBytes);
84
+ if (bytes > budget) throw new Error(`Request payload too large (413): local ACP transfer needs ${bytes} bytes; budget is ${budget}. Use OMP /compact or raise maxTransferBytes. No history was silently truncated.`);
85
+ const estimatedTokens = estimateTransferTokens(serialized, imageCount);
86
+ if (estimatedTokens > options.inputTokenBudget) throw new Error(`Maximum context length exceeded: local ACP estimate is ${estimatedTokens} tokens; input budget is ${options.inputTokenBudget}. Use OMP /compact. This is a heuristic estimate, not a server token count. No history was silently truncated.`);
81
87
  return { prompt, messageCount: messages.length };
82
88
  }
@@ -7,11 +7,12 @@ import fs from "node:fs";
7
7
  import { officialApiCost, applyApiCostEstimate } from "./pricing.ts";
8
8
  import { SessionRuntimePool } from "./runtime-pool.ts";
9
9
  import { stableTools } from "./tool-order.ts";
10
+ import { loadContextSettings, saveContextSettings, resolveContextOptions, updateContextSettings } from "./context-settings.ts";
10
11
  import { EFFORTS, projectCatalog, readModels, selectRuntimeModel } from "./model-catalog.ts";
11
12
  import { advertisedRecord, choices, selector } from "./selectors.ts";
12
13
  import { TOOL_ROUTING, parseNativeToolMode } from "./tool-routing.ts";
13
14
  import { loadNativeToolMode, loadToolPolicy, saveNativeToolMode, saveDebugToolUpdates } from "./tool-policy.ts";
14
- import { Type, createAntigravityProvider, AntigravityRuntime, PERMISSION_TOOL_NAME, PERMISSION_RESULT_KIND, loadConfig, savePermissionMode, inspectAntigravityAuth, hasAntigravityAuth, AcpSessionStore, ensureAntigravityAcpReady, TierConnection, planToolProjection, PiEventWriter } from "./runtime.mjs";
15
+ import { Type, createAntigravityProvider, AntigravityRuntime, PERMISSION_TOOL_NAME, PERMISSION_RESULT_KIND, loadConfig, savePermissionMode, inspectAntigravityAuth, hasAntigravityAuth, AcpSessionStore, ensureAntigravityAcpReady, TierConnection, planToolProjection, PiEventWriter, SessionCleanup } from "./runtime.mjs";
15
16
 
16
17
  const MARKER = "pi-antigravity-acp:managed-by-antigravity";
17
18
 
@@ -34,6 +35,9 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
34
35
  const configPath = path.join(stateDir, "config.json");
35
36
  const cachePath = path.join(stateDir, "models-cache.json");
36
37
  const toolPolicyPath = path.join(stateDir, "omp-tools.json");
38
+ const contextPath = path.join(stateDir, "context.json");
39
+ let contextSettings = loadContextSettings(contextPath);
40
+ const cleanup = new SessionCleanup(stateDir);
37
41
  // Loading this global extension must not start ACP or query Google.
38
42
  let readiness: Promise<void> | undefined;
39
43
  function prepareRuntime() {
@@ -53,7 +57,8 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
53
57
  const ownedConnections = new Set<any>();
54
58
  const runtime = new AntigravityRuntime((options: any) => {
55
59
  const policy = loadToolPolicy(toolPolicyPath);
56
- const connection = new TierConnection({ ...options, ompNativeTools: policy.nativeTools, ompDebugToolUpdates: policy.debugToolUpdates });
60
+ const connection = new TierConnection({ ...options, ompNativeTools: policy.nativeTools, ompDebugToolUpdates: policy.debugToolUpdates,
61
+ ompUsageMode: contextSettings.defaults.usageMode ?? "auto", ompCleanup: cleanup });
57
62
  connections.add(connection);
58
63
  ownedConnections.add(connection);
59
64
  void connection.process.exited.finally(() => connections.delete(connection));
@@ -90,9 +95,48 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
90
95
  },
91
96
  });
92
97
  pi.registerCommand("antigravity-acp", {
93
- description: "Inspect ACP status/tools/usage, toggle debug (on|off), refresh models, set native-tools or permissions",
98
+ description: "Inspect ACP status/tools/usage/context/cleanup, configure budgets, toggle debug, refresh models or set tool policies",
94
99
  async handler(args: string, ctx: any) {
95
- const [command, value] = args.trim().split(/\s+/);
100
+ const parts = args.trim().split(/\s+/);
101
+ const [command, value] = parts;
102
+ if (command === "cleanup") {
103
+ if (value) {
104
+ if (!["off", "conservative", "timeout"].includes(value) || parts.length > 3 || (parts[2] !== undefined && value !== "timeout")) {
105
+ throw new Error("Usage: /antigravity-acp cleanup [off|conservative|timeout [DAYS]]");
106
+ }
107
+ cleanup.configure(value, parts[2] === undefined ? undefined : Number(parts[2]));
108
+ cleanup.start();
109
+ }
110
+ const removed = cleanup.collect();
111
+ ctx.ui.notify(JSON.stringify({ ...cleanup.status(), removed,
112
+ note: "Active sessions are protected. Timeout cleanup loses ACP-only state; OMP history is retained." }, null, 2), "info");
113
+ return;
114
+ }
115
+ if (command === "context") {
116
+ if (value === "set") {
117
+ const [, , target, key, raw] = parts;
118
+ if (parts.length !== 5) throw new Error("Usage: /antigravity-acp context set default|MODEL KEY NUMBER");
119
+ const next = updateContextSettings(contextSettings, target, key, key === "usageMode" ? raw : Number(raw));
120
+ for (const model of initialModels) resolveContextOptions(model, next);
121
+ saveContextSettings(contextPath, next);
122
+ contextSettings = next;
123
+ if (key === "usageMode") for (const connection of connections) connection.configureUsage(raw as "auto" | "off");
124
+ initialModels = catalog(initialModels);
125
+ adapted.registerProvider();
126
+ ctx.ui.notify("ACP context settings saved. Restart OMP or reselect the model to refresh its displayed limits.", "info");
127
+ } else if (value) throw new Error("Usage: /antigravity-acp context [set default|MODEL KEY NUMBER]");
128
+ else ctx.ui.notify(JSON.stringify({ file: contextPath, settings: contextSettings,
129
+ effective: initialModels.map((model: any) => ({ id: model.id, ...resolveContextOptions(model, contextSettings) })) }, null, 2), "info");
130
+ return;
131
+ }
132
+ if (command === "usage" && value) {
133
+ if (value !== "auto" && value !== "off") throw new Error("Usage: /antigravity-acp usage [auto|off]");
134
+ contextSettings = updateContextSettings(contextSettings, "default", "usageMode", value);
135
+ saveContextSettings(contextPath, contextSettings);
136
+ for (const connection of connections) connection.configureUsage(value);
137
+ ctx.ui.notify(`Supplemental ACP usage queries: ${value}${process.env.OMP_ACP_USAGE === "off" ? " (environment override keeps queries off)" : ""}. Context occupancy updates remain enabled.`, "info");
138
+ return;
139
+ }
96
140
  if (command === "debug") {
97
141
  if (value !== "on" && value !== "off") throw new Error("Usage: /antigravity-acp debug on|off");
98
142
  const enabled = value === "on";
@@ -110,11 +154,13 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
110
154
  }
111
155
  const { runtime } = runtimes.get(sessionIdOf(ctx));
112
156
  if (command === "usage") {
113
- ctx.ui.notify(JSON.stringify([...connections].map(connection => ({
157
+ ctx.ui.notify(JSON.stringify({ configured: contextSettings.defaults.usageMode ?? "auto",
158
+ effective: process.env.OMP_ACP_USAGE === "off" ? "off" : contextSettings.defaults.usageMode ?? "auto",
159
+ connections: [...connections].map(connection => ({
114
160
  context: [...connection.contextUsage.values()],
115
161
  accounting: [...connection.usageStatus.values()],
116
162
  activePrompts: connection.activePrompts,
117
- })), null, 2), "info");
163
+ })) }, null, 2), "info");
118
164
  return;
119
165
  }
120
166
  if (command === "refresh") {
@@ -141,7 +187,9 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
141
187
  const upstreamModels = new Map<string, any>();
142
188
  function catalog(models: any[]) {
143
189
  return models.map(source => {
144
- const model = { ...source, cost: officialApiCost(source.id) ?? source.cost };
190
+ const limits = resolveContextOptions(source, contextSettings);
191
+ const model = { ...source, contextWindow: limits.contextWindow, maxTokens: limits.maxTokens,
192
+ ompContextPolicy: limits, cost: officialApiCost(source.id) ?? source.cost };
145
193
  const efforts = EFFORTS.filter(effort => model.thinkingLevelMap?.[effort]);
146
194
  if (efforts.length && !model.thinking) {
147
195
  model.thinking = { mode: "effort", efforts, defaultLevel: efforts.includes("high") ? "high" : efforts[0] };
@@ -159,10 +207,12 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
159
207
  }
160
208
  async function discoverModels() {
161
209
  await prepareRuntime();
162
- const connection = new TierConnection({ cwd: process.cwd() });
210
+ const connection = new TierConnection({ cwd: process.cwd(), ompCleanup: cleanup });
211
+ let discoveredSession: string | undefined;
163
212
  try {
164
213
  await connection.initialize();
165
214
  const session = await connection.newSession(process.cwd());
215
+ discoveredSession = session.sessionId;
166
216
  const modern = choices(selector(session, "model"));
167
217
  if (modern.length) {
168
218
  const models = [];
@@ -178,6 +228,7 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
178
228
  if (!models.length) throw new Error("Antigravity did not advertise any models");
179
229
  return models;
180
230
  } finally {
231
+ if (discoveredSession) connection.discardSession(discoveredSession);
181
232
  await connection.close();
182
233
  }
183
234
  }