omp-antigravity-acp-provider 0.1.6 → 0.1.8
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 +74 -8
- package/extension/context-settings.ts +82 -0
- package/extension/context-transfer.ts +88 -0
- package/extension/index.ts +74 -19
- package/extension/runtime-pool.ts +40 -1
- package/extension/runtime.mjs +228 -185
- package/extension/tier-connection.ts +84 -1
- package/extension/tool-order.ts +4 -0
- package/extension/usage-accounting.ts +30 -0
- package/extension/usage.ts +9 -0
- package/package.json +2 -1
- package/scripts/build.mjs +16 -0
package/README.md
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
# omp-antigravity-acp-provider
|
|
2
2
|
|
|
3
|
-
Previously named `omp-antigravity-acp`. When migrating, uninstall the former plugin before installing the renamed package; keep only one adapter enabled. The `antigravity-acp` provider ID, `/antigravity-acp` commands, settings and session directories remain unchanged. Existing GitHub repository links redirect to the renamed repository.
|
|
4
|
-
|
|
5
3
|
[](https://www.npmjs.com/package/omp-antigravity-acp-provider)
|
|
6
4
|
[](https://www.npmjs.com/package/omp-antigravity-acp-provider)
|
|
7
5
|
|
|
@@ -21,7 +19,7 @@ The repository keeps the OMP adapter sources separately and installs upstream ve
|
|
|
21
19
|
|
|
22
20
|
## Status
|
|
23
21
|
|
|
24
|
-
Version 0.1.
|
|
22
|
+
Version 0.1.8 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.
|
|
25
23
|
|
|
26
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.
|
|
27
25
|
|
|
@@ -58,7 +56,7 @@ Or, inside OMP:
|
|
|
58
56
|
|
|
59
57
|
Select **omp-antigravity-acp-provider** in the browser, install it, and restart OMP to load the provider.
|
|
60
58
|
|
|
61
|
-
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.
|
|
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.8** 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.
|
|
62
60
|
|
|
63
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.
|
|
64
62
|
|
|
@@ -79,10 +77,10 @@ The prebuilt package is published on [npm as `omp-antigravity-acp-provider`](htt
|
|
|
79
77
|
omp plugin install npm:omp-antigravity-acp-provider
|
|
80
78
|
```
|
|
81
79
|
|
|
82
|
-
To pin
|
|
80
|
+
To pin a specific release:
|
|
83
81
|
|
|
84
82
|
```sh
|
|
85
|
-
omp plugin install npm:omp-antigravity-acp-provider@0.1.
|
|
83
|
+
omp plugin install npm:omp-antigravity-acp-provider@0.1.8
|
|
86
84
|
```
|
|
87
85
|
|
|
88
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.
|
|
@@ -112,6 +110,8 @@ Use the OMP installation target when installing from the search result. The dire
|
|
|
112
110
|
Use Node.js 22.19 or newer and OMP. Node.js is also required by the upstream process supervisor.
|
|
113
111
|
|
|
114
112
|
```sh
|
|
113
|
+
git clone https://github.com/SenCha930511/omp-antigravity-acp-provider.git
|
|
114
|
+
cd omp-antigravity-acp-provider
|
|
115
115
|
npm ci
|
|
116
116
|
npm run check
|
|
117
117
|
```
|
|
@@ -141,13 +141,19 @@ First use or login may download the official runtime. The observed macOS runtime
|
|
|
141
141
|
|
|
142
142
|
If OMP's `enabledModels` whitelist is configured, add `antigravity-acp/*` alongside your existing entries in `~/.omp/agent/config.yml` to allow newly discovered models. Use individual `antigravity-acp/<server-model-id>` entries instead if you prefer a restricted list. The adapter does not rewrite that whitelist or any model-role preset.
|
|
143
143
|
|
|
144
|
-
After upgrading from an older adapter, run `/antigravity-acp refresh` once to replace the old cached list with per-model selector choices. Startup and ordinary catalog listing remain offline, so new server models appear after an explicit refresh. Availability in the Antigravity app or CLI does not guarantee availability through ACP: on the tested account, ACP still advertised only `gemini-4-argon` and `gemini-3.8-flash` on 2026-10-
|
|
144
|
+
After upgrading from an older adapter, run `/antigravity-acp refresh` once to replace the old cached list with per-model selector choices. Startup and ordinary catalog listing remain offline, so new server models appear after an explicit refresh. Availability in the Antigravity app or CLI does not guarantee availability through ACP: on the tested account, ACP still advertised only `gemini-4-argon` and `gemini-3.8-flash` on 2026-10-20.
|
|
145
145
|
|
|
146
146
|
## Commands
|
|
147
147
|
|
|
148
148
|
| Command | Purpose |
|
|
149
149
|
| --- | --- |
|
|
150
150
|
| `/antigravity-acp status` | Runtime, confirmed thinking and usage information |
|
|
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 |
|
|
151
157
|
| `/antigravity-acp tools` | Available and omitted OMP tool schemas after a request |
|
|
152
158
|
| `/antigravity-acp refresh` | Explicit network discovery and local catalog refresh |
|
|
153
159
|
| `/antigravity-acp native-tools prefer` | Prefer OMP tools; retain native built-ins (default) |
|
|
@@ -186,9 +192,67 @@ Advanced routing requires the official `antigravity-acp` 1.x server, version 1.4
|
|
|
186
192
|
|
|
187
193
|
Never include those user data directories, OAuth callback URLs, account identifiers or downloaded runtime binaries in issues or commits. `OMP_ACP_TRACE=1` enables opt-in tool/selector diagnostics; review diagnostic output before sharing.
|
|
188
194
|
|
|
195
|
+
## Context continuity and local performance
|
|
196
|
+
|
|
197
|
+
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.
|
|
198
|
+
|
|
199
|
+
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.
|
|
200
|
+
|
|
201
|
+
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.
|
|
202
|
+
|
|
203
|
+
```json
|
|
204
|
+
{
|
|
205
|
+
"defaults": {
|
|
206
|
+
"contextWindow": 524288,
|
|
207
|
+
"maxTokens": 32000,
|
|
208
|
+
"reserveTokens": 16384,
|
|
209
|
+
"maxTransferBytes": 16777216,
|
|
210
|
+
"maxImageBytes": 8388608,
|
|
211
|
+
"usageMode": "off"
|
|
212
|
+
},
|
|
213
|
+
"models": {}
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
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.
|
|
218
|
+
|
|
219
|
+
```text
|
|
220
|
+
/antigravity-acp context
|
|
221
|
+
/antigravity-acp context set default maxTransferBytes 33554432
|
|
222
|
+
/antigravity-acp context set gemini-4-argon contextWindow 1000000
|
|
223
|
+
/antigravity-acp usage off
|
|
224
|
+
/antigravity-acp usage auto
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
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:
|
|
228
|
+
|
|
229
|
+
```sh
|
|
230
|
+
omp config set compaction.modelThresholds '{"antigravity-acp/*":"85%"}'
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
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.
|
|
234
|
+
|
|
235
|
+
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.
|
|
236
|
+
|
|
237
|
+
Optional environment settings, applied when OMP starts:
|
|
238
|
+
|
|
239
|
+
| Setting | Default | Effect |
|
|
240
|
+
| --- | --- | --- |
|
|
241
|
+
| `OMP_ACP_HISTORY_BYTES` | context.json or 16 MiB | Optional byte-limit override, 64 KiB–128 MiB; independent of token window |
|
|
242
|
+
| `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it, positive values must be at least `1000` |
|
|
243
|
+
| `OMP_ACP_USAGE` | context.json or auto | `off` forces supplemental queries off, including when the saved option is auto |
|
|
244
|
+
|
|
245
|
+
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.
|
|
246
|
+
|
|
247
|
+
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.
|
|
248
|
+
|
|
249
|
+
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.
|
|
250
|
+
|
|
251
|
+
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.
|
|
252
|
+
|
|
189
253
|
## Limitations
|
|
190
254
|
|
|
191
|
-
- Argon/Flash
|
|
255
|
+
- 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.
|
|
192
256
|
- API background execution and long decode controls are not exposed.
|
|
193
257
|
- The bridge advertises text and image input, not the full Gemini API media surface.
|
|
194
258
|
- 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.
|
|
@@ -203,6 +267,8 @@ Never include those user data directories, OAuth callback URLs, account identifi
|
|
|
203
267
|
|
|
204
268
|
`npm test` runs offline regression tests for all-vendor catalogs, per-model thinking choices, selector routing, session ownership, restart-after-shutdown, asynchronous teardown and price calculations. It performs no model inference and consumes no account quota.
|
|
205
269
|
|
|
270
|
+
`npm run test:usage` uses Bun and mocked protocol responses to verify restored-session baselines, counter resets, query failures and advertised-command gating without starting ACP. `bun scripts/verify-continuity-live.ts --live` is a separate Flash-only probe of long history, synthetic tools, usage accounting and idle process reclamation/restoration; it consumes quota. Its one-second idle setting is isolated to the test process and is not the production default.
|
|
271
|
+
|
|
206
272
|
`npm run test:packed` additionally requires OMP on PATH. It installs the exact npm tarball into a temporary consumer directory with development dependencies omitted and install scripts disabled, checks runtime assets, and loads its model catalog with ACP execution disabled. It downloads production dependencies and removes the temporary installation afterward.
|
|
207
273
|
|
|
208
274
|
`npm run test:marketplace` exercises catalog discovery, installation, automatic provider loading, offline cache reuse and uninstallation in a temporary named OMP profile. It downloads the published adapter and cleans the entire test profile afterward. Add `-- --remote` after publishing catalog changes to test the GitHub source instead of the local working tree. No model inference is performed.
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Adapter-owned context transfer. The pinned upstream dependency stays intact.
|
|
2
|
+
import { getCurrentSystemPrompt } from "@earendil-works/pi-ai/utils/transcript";
|
|
3
|
+
import { estimateTransferTokens, resolveContextOptions, type ContextOptions } from "./context-settings.ts";
|
|
4
|
+
export function currentSystemInstructions(context: any): string {
|
|
5
|
+
const prompt = getCurrentSystemPrompt(context.messages) || context.systemPrompt || "";
|
|
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");
|
|
7
|
+
return prompt;
|
|
8
|
+
}
|
|
9
|
+
|
|
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");
|
|
14
|
+
}
|
|
15
|
+
return bytes;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function buildPromptParts(context: any, fresh: boolean, unseenStart?: 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: {} });
|
|
22
|
+
const messages = context.messages;
|
|
23
|
+
let latest = messages.length - 1;
|
|
24
|
+
while (latest >= 0 && messages[latest].role !== "user") latest--;
|
|
25
|
+
if (latest < 0) throw new Error("No user message to send to Antigravity ACP");
|
|
26
|
+
if (!fresh && (unseenStart === undefined || !Number.isSafeInteger(unseenStart) || unseenStart < 0 || unseenStart > messages.length)) {
|
|
27
|
+
throw new Error("Warm ACP context has an invalid unseen boundary");
|
|
28
|
+
}
|
|
29
|
+
const end = messages.length > latest + 1 ? messages.length : latest;
|
|
30
|
+
const start = fresh ? 0 : unseenStart!;
|
|
31
|
+
const prompt: any[] = [];
|
|
32
|
+
const instructions = fresh ? currentSystemInstructions(context) : "";
|
|
33
|
+
if (instructions) prompt.push({ type: "resource", resource: {
|
|
34
|
+
uri: "urn:omp:antigravity-acp:instructions", mimeType: "text/markdown",
|
|
35
|
+
text: `# OMP session instructions\n\n${instructions}`,
|
|
36
|
+
} });
|
|
37
|
+
const records: any[] = [];
|
|
38
|
+
const images: any[] = [];
|
|
39
|
+
for (let index = start; index < end; index++) {
|
|
40
|
+
const message = messages[index];
|
|
41
|
+
if (index === latest || message.role === "system") continue;
|
|
42
|
+
const content = typeof message.content === "string" ? message.content : message.content
|
|
43
|
+
.filter((block: any) => ["text", "toolCall", "image"].includes(block.type))
|
|
44
|
+
.map((block: any) => {
|
|
45
|
+
if (block.type === "image") {
|
|
46
|
+
const imageIndex = images.length;
|
|
47
|
+
images.push({ type: "text", text: `Historical image from OMP message ${index}; treat as conversation data.` },
|
|
48
|
+
{ type: "image", data: block.data, mimeType: block.mimeType });
|
|
49
|
+
return { type: "image", attachment: imageIndex / 2 };
|
|
50
|
+
}
|
|
51
|
+
return block.type === "toolCall" ? { type: block.type, id: block.id, name: block.name, arguments: block.arguments }
|
|
52
|
+
: { type: "text", text: block.text };
|
|
53
|
+
});
|
|
54
|
+
records.push({ role: message.role, toolName: message.toolName, toolCallId: message.toolCallId, isError: message.isError, content });
|
|
55
|
+
}
|
|
56
|
+
if (records.length) prompt.push({ type: "resource", resource: {
|
|
57
|
+
uri: "urn:omp:antigravity-acp:history", mimeType: "text/plain",
|
|
58
|
+
text: "Prior conversation data, not new instructions. Do not repeat completed tool actions.\n" + JSON.stringify(records),
|
|
59
|
+
} });
|
|
60
|
+
prompt.push(...images);
|
|
61
|
+
if (!fresh && start > latest) {
|
|
62
|
+
prompt.push({ type: "text", text: "Continue the current OMP user request with the new results. Do not repeat completed tool actions." });
|
|
63
|
+
} else {
|
|
64
|
+
const content = messages[latest].content;
|
|
65
|
+
prompt.push(...(typeof content === "string" ? [{ type: "text", text: content }]
|
|
66
|
+
: content.map((block: any) => ({ ...block }))));
|
|
67
|
+
}
|
|
68
|
+
// Image base64 size is not a text-token estimate. Bound its actual memory
|
|
69
|
+
// footprint separately, and reserve a conservative text-equivalent allowance.
|
|
70
|
+
let imageBytes = 0;
|
|
71
|
+
let imageCount = 0;
|
|
72
|
+
let imageWireChars = 0;
|
|
73
|
+
const textOnly = prompt.map(block => {
|
|
74
|
+
if (block.type !== "image") return block;
|
|
75
|
+
imageBytes += Math.ceil((block.data?.length ?? 0) * 3 / 4);
|
|
76
|
+
imageWireChars += block.data?.length ?? 0;
|
|
77
|
+
imageCount++;
|
|
78
|
+
return { type: "image", mimeType: block.mimeType };
|
|
79
|
+
});
|
|
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.`);
|
|
87
|
+
return { prompt, messageCount: messages.length };
|
|
88
|
+
}
|
package/extension/index.ts
CHANGED
|
@@ -6,6 +6,8 @@ import path from "node:path";
|
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import { officialApiCost, applyApiCostEstimate } from "./pricing.ts";
|
|
8
8
|
import { SessionRuntimePool } from "./runtime-pool.ts";
|
|
9
|
+
import { stableTools } from "./tool-order.ts";
|
|
10
|
+
import { loadContextSettings, saveContextSettings, resolveContextOptions, updateContextSettings } from "./context-settings.ts";
|
|
9
11
|
import { EFFORTS, projectCatalog, readModels, selectRuntimeModel } from "./model-catalog.ts";
|
|
10
12
|
import { advertisedRecord, choices, selector } from "./selectors.ts";
|
|
11
13
|
import { TOOL_ROUTING, parseNativeToolMode } from "./tool-routing.ts";
|
|
@@ -33,6 +35,8 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
33
35
|
const configPath = path.join(stateDir, "config.json");
|
|
34
36
|
const cachePath = path.join(stateDir, "models-cache.json");
|
|
35
37
|
const toolPolicyPath = path.join(stateDir, "omp-tools.json");
|
|
38
|
+
const contextPath = path.join(stateDir, "context.json");
|
|
39
|
+
let contextSettings = loadContextSettings(contextPath);
|
|
36
40
|
// Loading this global extension must not start ACP or query Google.
|
|
37
41
|
let readiness: Promise<void> | undefined;
|
|
38
42
|
function prepareRuntime() {
|
|
@@ -43,17 +47,26 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
43
47
|
return readiness;
|
|
44
48
|
}
|
|
45
49
|
const connections = new Set<any>();
|
|
50
|
+
const idleTimeoutMs = Number(process.env.OMP_ACP_IDLE_TIMEOUT_MS ?? 300_000);
|
|
51
|
+
if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 0 || (idleTimeoutMs > 0 && idleTimeoutMs < 1000)) {
|
|
52
|
+
throw new Error("OMP_ACP_IDLE_TIMEOUT_MS must be 0 (disabled) or an integer of at least 1000");
|
|
53
|
+
}
|
|
46
54
|
let lastToolAudit: { offered: string[]; available: string[]; omitted: any[] } | undefined;
|
|
47
55
|
const runtimes = new SessionRuntimePool(() => {
|
|
56
|
+
const ownedConnections = new Set<any>();
|
|
48
57
|
const runtime = new AntigravityRuntime((options: any) => {
|
|
49
58
|
const policy = loadToolPolicy(toolPolicyPath);
|
|
50
|
-
const connection = new TierConnection({ ...options, ompNativeTools: policy.nativeTools, ompDebugToolUpdates: policy.debugToolUpdates
|
|
59
|
+
const connection = new TierConnection({ ...options, ompNativeTools: policy.nativeTools, ompDebugToolUpdates: policy.debugToolUpdates,
|
|
60
|
+
ompUsageMode: contextSettings.defaults.usageMode ?? "auto" });
|
|
51
61
|
connections.add(connection);
|
|
62
|
+
ownedConnections.add(connection);
|
|
52
63
|
void connection.process.exited.finally(() => connections.delete(connection));
|
|
64
|
+
void connection.process.exited.finally(() => ownedConnections.delete(connection));
|
|
53
65
|
return connection;
|
|
54
66
|
}, loadConfig(configPath).permissions, new AcpSessionStore(path.join(stateDir, "sessions.json")));
|
|
55
|
-
return { runtime, provider: createAntigravityProvider(runtime).provider
|
|
56
|
-
|
|
67
|
+
return { runtime, provider: createAntigravityProvider(runtime).provider,
|
|
68
|
+
isBusy: () => [...ownedConnections].some(connection => connection.activePrompts > 0) };
|
|
69
|
+
}, bundle => bundle.runtime.close(), { timeoutMs: idleTimeoutMs, canDispose: bundle => !bundle.isBusy() });
|
|
57
70
|
const sessionIdOf = (ctx: any): string | undefined => ctx?.sessionManager?.getSessionId?.();
|
|
58
71
|
pi.on("session_shutdown", async (_event: any, ctx: any) => {
|
|
59
72
|
const sessionId = sessionIdOf(ctx);
|
|
@@ -81,9 +94,35 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
81
94
|
},
|
|
82
95
|
});
|
|
83
96
|
pi.registerCommand("antigravity-acp", {
|
|
84
|
-
description: "Inspect ACP status/tools, toggle debug
|
|
97
|
+
description: "Inspect ACP status/tools/usage/context, configure budgets, toggle debug, refresh models or set tool policies",
|
|
85
98
|
async handler(args: string, ctx: any) {
|
|
86
|
-
const
|
|
99
|
+
const parts = args.trim().split(/\s+/);
|
|
100
|
+
const [command, value] = parts;
|
|
101
|
+
if (command === "context") {
|
|
102
|
+
if (value === "set") {
|
|
103
|
+
const [, , target, key, raw] = parts;
|
|
104
|
+
if (parts.length !== 5) throw new Error("Usage: /antigravity-acp context set default|MODEL KEY NUMBER");
|
|
105
|
+
const next = updateContextSettings(contextSettings, target, key, key === "usageMode" ? raw : Number(raw));
|
|
106
|
+
for (const model of initialModels) resolveContextOptions(model, next);
|
|
107
|
+
saveContextSettings(contextPath, next);
|
|
108
|
+
contextSettings = next;
|
|
109
|
+
if (key === "usageMode") for (const connection of connections) connection.configureUsage(raw as "auto" | "off");
|
|
110
|
+
initialModels = catalog(initialModels);
|
|
111
|
+
adapted.registerProvider();
|
|
112
|
+
ctx.ui.notify("ACP context settings saved. Restart OMP or reselect the model to refresh its displayed limits.", "info");
|
|
113
|
+
} else if (value) throw new Error("Usage: /antigravity-acp context [set default|MODEL KEY NUMBER]");
|
|
114
|
+
else ctx.ui.notify(JSON.stringify({ file: contextPath, settings: contextSettings,
|
|
115
|
+
effective: initialModels.map((model: any) => ({ id: model.id, ...resolveContextOptions(model, contextSettings) })) }, null, 2), "info");
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (command === "usage" && value) {
|
|
119
|
+
if (value !== "auto" && value !== "off") throw new Error("Usage: /antigravity-acp usage [auto|off]");
|
|
120
|
+
contextSettings = updateContextSettings(contextSettings, "default", "usageMode", value);
|
|
121
|
+
saveContextSettings(contextPath, contextSettings);
|
|
122
|
+
for (const connection of connections) connection.configureUsage(value);
|
|
123
|
+
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");
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
87
126
|
if (command === "debug") {
|
|
88
127
|
if (value !== "on" && value !== "off") throw new Error("Usage: /antigravity-acp debug on|off");
|
|
89
128
|
const enabled = value === "on";
|
|
@@ -100,6 +139,16 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
100
139
|
return;
|
|
101
140
|
}
|
|
102
141
|
const { runtime } = runtimes.get(sessionIdOf(ctx));
|
|
142
|
+
if (command === "usage") {
|
|
143
|
+
ctx.ui.notify(JSON.stringify({ configured: contextSettings.defaults.usageMode ?? "auto",
|
|
144
|
+
effective: process.env.OMP_ACP_USAGE === "off" ? "off" : contextSettings.defaults.usageMode ?? "auto",
|
|
145
|
+
connections: [...connections].map(connection => ({
|
|
146
|
+
context: [...connection.contextUsage.values()],
|
|
147
|
+
accounting: [...connection.usageStatus.values()],
|
|
148
|
+
activePrompts: connection.activePrompts,
|
|
149
|
+
})) }, null, 2), "info");
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
103
152
|
if (command === "refresh") {
|
|
104
153
|
initialModels = await refreshCatalog();
|
|
105
154
|
adapted.registerProvider();
|
|
@@ -124,7 +173,9 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
124
173
|
const upstreamModels = new Map<string, any>();
|
|
125
174
|
function catalog(models: any[]) {
|
|
126
175
|
return models.map(source => {
|
|
127
|
-
const
|
|
176
|
+
const limits = resolveContextOptions(source, contextSettings);
|
|
177
|
+
const model = { ...source, contextWindow: limits.contextWindow, maxTokens: limits.maxTokens,
|
|
178
|
+
ompContextPolicy: limits, cost: officialApiCost(source.id) ?? source.cost };
|
|
128
179
|
const efforts = EFFORTS.filter(effort => model.thinkingLevelMap?.[effort]);
|
|
129
180
|
if (efforts.length && !model.thinking) {
|
|
130
181
|
model.thinking = { mode: "effort", efforts, defaultLevel: efforts.includes("high") ? "high" : efforts[0] };
|
|
@@ -197,7 +248,7 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
197
248
|
return catalog(cached.length ? projectCatalog(cached) : runtimes.get().provider.getModels());
|
|
198
249
|
},
|
|
199
250
|
streamSimple(model: any, context: any, options: any) {
|
|
200
|
-
const tools = context.tools ?? [];
|
|
251
|
+
const tools = stableTools(context.tools ?? []);
|
|
201
252
|
const bridged = tools.filter((tool: any) => tool.name !== PERMISSION_TOOL_NAME);
|
|
202
253
|
const omitted = planToolProjection(tools);
|
|
203
254
|
const omittedNames = new Set(omitted.map((tool: any) => tool.name));
|
|
@@ -205,6 +256,7 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
205
256
|
lastToolAudit = { offered: bridged.map((tool: any) => tool.name), available: available.map((tool: any) => tool.name), omitted };
|
|
206
257
|
const routedContext = {
|
|
207
258
|
...context,
|
|
259
|
+
tools,
|
|
208
260
|
systemPrompt: `${context.systemPrompt ?? ""}\n\n${TOOL_ROUTING}\nOMP tool names: ${available.length ? available.map((tool: any) => `pi_${tool.name}`).join(", ") : "none currently available; report missing capabilities before proposing native operations"}`,
|
|
209
261
|
};
|
|
210
262
|
if (process.env.OMP_ACP_TRACE === "1") {
|
|
@@ -221,18 +273,21 @@ export async function registerOmpAdapter(pi: any, stateDir: string) {
|
|
|
221
273
|
if (!upstreamModels.has(model.id)) await refreshCatalog();
|
|
222
274
|
const original = upstreamModels.get(model.id);
|
|
223
275
|
if (!original) throw new Error(`Antigravity model was not discovered: ${model.id}. Run /antigravity-acp refresh.`);
|
|
224
|
-
const
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
276
|
+
const lease = runtimes.acquire(options?.sessionId);
|
|
277
|
+
const { runtime, provider } = lease.value;
|
|
278
|
+
try {
|
|
279
|
+
const stream = provider.streamSimple(selectRuntimeModel(original, options?.reasoning), routedContext, options);
|
|
280
|
+
for await (const event of stream) {
|
|
281
|
+
const message = event.message ?? event.partial;
|
|
282
|
+
if (message?.usage) applyApiCostEstimate(model.id, message.usage, message.timestamp ?? Date.now());
|
|
283
|
+
deferred.stream.push(event);
|
|
284
|
+
}
|
|
285
|
+
deferred.stream.end();
|
|
286
|
+
if (process.env.OMP_ACP_TRACE === "1") {
|
|
287
|
+
const snapshot = await runtime.snapshot();
|
|
288
|
+
console.error("[ACP bridge]", JSON.stringify(snapshot.processes.map((item: any) => ({ mcpHttp: item.mcpHttp, omittedTools: item.omittedTools }))));
|
|
289
|
+
}
|
|
290
|
+
} finally { lease.release(); }
|
|
236
291
|
} catch (error) {
|
|
237
292
|
deferred.fail(error, options?.signal?.aborted === true);
|
|
238
293
|
}
|
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
// A disposed upstream runtime is terminal, so never return it to a later request.
|
|
3
3
|
export class SessionRuntimePool<T> {
|
|
4
4
|
private readonly entries = new Map<string | undefined, T>();
|
|
5
|
+
private readonly leases = new Map<T, number>();
|
|
6
|
+
private readonly timers = new Map<T, ReturnType<typeof setTimeout>>();
|
|
5
7
|
|
|
6
8
|
constructor(
|
|
7
9
|
private readonly create: () => T,
|
|
8
10
|
private readonly dispose: (entry: T) => Promise<void>,
|
|
11
|
+
private readonly idle: { timeoutMs: number; canDispose?: (entry: T) => boolean } = { timeoutMs: 0 },
|
|
9
12
|
) {}
|
|
10
13
|
|
|
11
14
|
get(sessionId?: string): T {
|
|
@@ -14,9 +17,44 @@ export class SessionRuntimePool<T> {
|
|
|
14
17
|
entry = this.create();
|
|
15
18
|
this.entries.set(sessionId, entry);
|
|
16
19
|
}
|
|
20
|
+
this.schedule(sessionId, entry);
|
|
17
21
|
return entry;
|
|
18
22
|
}
|
|
19
23
|
|
|
24
|
+
acquire(sessionId?: string) {
|
|
25
|
+
const value = this.get(sessionId);
|
|
26
|
+
this.leases.set(value, (this.leases.get(value) ?? 0) + 1);
|
|
27
|
+
this.clearTimer(value);
|
|
28
|
+
let released = false;
|
|
29
|
+
return { value, release: () => {
|
|
30
|
+
if (released) return;
|
|
31
|
+
released = true;
|
|
32
|
+
const count = (this.leases.get(value) ?? 1) - 1;
|
|
33
|
+
if (count > 0) this.leases.set(value, count); else this.leases.delete(value);
|
|
34
|
+
if (this.entries.get(sessionId) === value) this.schedule(sessionId, value);
|
|
35
|
+
} };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private clearTimer(entry: T) {
|
|
39
|
+
const timer = this.timers.get(entry);
|
|
40
|
+
if (timer) clearTimeout(timer);
|
|
41
|
+
this.timers.delete(entry);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private schedule(key: string | undefined, entry: T) {
|
|
45
|
+
this.clearTimer(entry);
|
|
46
|
+
if (!this.idle.timeoutMs || this.leases.has(entry)) return;
|
|
47
|
+
const timer = setTimeout(() => {
|
|
48
|
+
this.timers.delete(entry);
|
|
49
|
+
if (this.entries.get(key) !== entry || this.leases.has(entry)) return;
|
|
50
|
+
// A yielded OMP tool call can still have an ACP prompt outstanding.
|
|
51
|
+
if (this.idle.canDispose?.(entry) === false) { this.schedule(key, entry); return; }
|
|
52
|
+
void this.close(key).catch(() => {});
|
|
53
|
+
}, this.idle.timeoutMs);
|
|
54
|
+
timer.unref();
|
|
55
|
+
this.timers.set(entry, timer);
|
|
56
|
+
}
|
|
57
|
+
|
|
20
58
|
values(): T[] {
|
|
21
59
|
return [...this.entries.values()];
|
|
22
60
|
}
|
|
@@ -25,12 +63,13 @@ export class SessionRuntimePool<T> {
|
|
|
25
63
|
const entry = this.entries.get(sessionId);
|
|
26
64
|
// Detach before awaiting teardown so a new turn cannot reuse a closed runtime.
|
|
27
65
|
this.entries.delete(sessionId);
|
|
28
|
-
if (entry) await this.dispose(entry);
|
|
66
|
+
if (entry) { this.clearTimer(entry); this.leases.delete(entry); await this.dispose(entry); }
|
|
29
67
|
}
|
|
30
68
|
|
|
31
69
|
async closeAll(): Promise<void> {
|
|
32
70
|
const entries = this.values();
|
|
33
71
|
this.entries.clear();
|
|
72
|
+
for (const entry of entries) { this.clearTimer(entry); this.leases.delete(entry); }
|
|
34
73
|
await Promise.allSettled(entries.map(entry => this.dispose(entry)));
|
|
35
74
|
}
|
|
36
75
|
}
|
package/extension/runtime.mjs
CHANGED
|
@@ -59055,198 +59055,114 @@ function toolError(text) {
|
|
|
59055
59055
|
return { content: [{ type: "text", text }], isError: true };
|
|
59056
59056
|
}
|
|
59057
59057
|
|
|
59058
|
-
//
|
|
59059
|
-
|
|
59060
|
-
|
|
59061
|
-
|
|
59062
|
-
|
|
59063
|
-
|
|
59064
|
-
|
|
59065
|
-
|
|
59066
|
-
|
|
59058
|
+
// extension/context-settings.ts
|
|
59059
|
+
function resolveContextOptions(model, settings2) {
|
|
59060
|
+
const options = { ...settings2.defaults, ...settings2.models[model.id] };
|
|
59061
|
+
const contextWindow = options.contextWindow ?? model.contextWindow;
|
|
59062
|
+
const maxTokens = options.maxTokens ?? model.maxTokens;
|
|
59063
|
+
const reserveTokens = options.reserveTokens ?? Math.min(16384, Math.floor(contextWindow * 0.05));
|
|
59064
|
+
const automatic = contextWindow - maxTokens - reserveTokens;
|
|
59065
|
+
const inputTokenBudget = options.inputTokenBudget ?? automatic;
|
|
59066
|
+
if (automatic <= 0 || inputTokenBudget > automatic) throw new Error(`Invalid token budgets for ${model.id}: input + output + reserve must fit contextWindow`);
|
|
59067
|
+
return {
|
|
59068
|
+
contextWindow,
|
|
59069
|
+
maxTokens,
|
|
59070
|
+
reserveTokens,
|
|
59071
|
+
inputTokenBudget,
|
|
59072
|
+
maxTransferBytes: options.maxTransferBytes ?? 16777216,
|
|
59073
|
+
maxImageBytes: options.maxImageBytes ?? 8388608
|
|
59074
|
+
};
|
|
59075
|
+
}
|
|
59076
|
+
function estimateTransferTokens(text, images = 0) {
|
|
59077
|
+
let nonAscii = 0;
|
|
59078
|
+
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) > 127) nonAscii++;
|
|
59079
|
+
return Math.ceil((text.length - nonAscii) / 3 + nonAscii * 1.5) + images * 4096;
|
|
59080
|
+
}
|
|
59081
|
+
|
|
59082
|
+
// extension/context-transfer.ts
|
|
59067
59083
|
function currentSystemInstructions(context) {
|
|
59068
59084
|
const prompt = getCurrentSystemPrompt(context.messages) || context.systemPrompt || "";
|
|
59069
|
-
if (Buffer.byteLength(prompt, "utf8") >
|
|
59070
|
-
throw new AntigravityAcpError("invalid_input", `Pi system instructions exceed ${MAX_INSTRUCTION_BYTES} bytes; reduce them rather than truncating instructions`);
|
|
59071
|
-
}
|
|
59085
|
+
if (Buffer.byteLength(prompt, "utf8") > 134217728) throw new Error("OMP system instructions exceed the 128 MiB hard transfer ceiling; reduce them rather than truncating instructions");
|
|
59072
59086
|
return prompt;
|
|
59073
59087
|
}
|
|
59074
|
-
function
|
|
59075
|
-
const
|
|
59076
|
-
if (
|
|
59077
|
-
|
|
59078
|
-
if (!latest || latest.role !== "user") {
|
|
59079
|
-
throw new AntigravityAcpError("invalid_input", "Latest Antigravity ACP input is not a user message");
|
|
59080
|
-
}
|
|
59081
|
-
const hasTrailingResults = context.messages.slice(latestIndex + 1).some((message) => message.role !== "system");
|
|
59082
|
-
if (!fresh && (hasTrailingResults && unseenStart === void 0 || unseenStart !== void 0 && (!Number.isSafeInteger(unseenStart) || unseenStart < 0 || unseenStart > context.messages.length))) {
|
|
59083
|
-
throw new AntigravityAcpError("invalid_input", "Warm Pi context has an invalid unseen boundary");
|
|
59088
|
+
function historyBudget(_contextWindow = 32768, env2 = process.env, configured = 16777216) {
|
|
59089
|
+
const bytes = Number(env2.OMP_ACP_HISTORY_BYTES ?? configured);
|
|
59090
|
+
if (!Number.isSafeInteger(bytes) || bytes < 65536 || bytes > 134217728) {
|
|
59091
|
+
throw new Error("OMP_ACP_HISTORY_BYTES must be an integer between 65536 and 134217728");
|
|
59084
59092
|
}
|
|
59085
|
-
|
|
59086
|
-
const pinStart = hasTrailingResults ? latestIndex + 1 : historyEnd;
|
|
59087
|
-
const prompt = [];
|
|
59088
|
-
if (fresh) {
|
|
59089
|
-
const sections = [];
|
|
59090
|
-
const instructions = currentSystemInstructions(context);
|
|
59091
|
-
if (instructions) sections.push(`# Pi session instructions
|
|
59092
|
-
|
|
59093
|
-
${instructions}`);
|
|
59094
|
-
const history = boundedSection(HISTORY_HEADING, historyEntries(context.messages, 0, historyEnd, latestIndex, pinStart));
|
|
59095
|
-
if (history) sections.push(history);
|
|
59096
|
-
if (sections.length) prompt.push(contextResource("context", sections.join("\n\n---\n\n")));
|
|
59097
|
-
} else if (unseenStart !== void 0 && unseenStart < historyEnd) {
|
|
59098
|
-
const delta = boundedSection(DELTA_HEADING, historyEntries(context.messages, unseenStart, historyEnd, latestIndex, pinStart));
|
|
59099
|
-
if (delta) prompt.push(contextResource("external-delta", delta));
|
|
59100
|
-
}
|
|
59101
|
-
if (!fresh && hasTrailingResults && unseenStart !== void 0 && unseenStart > latestIndex) {
|
|
59102
|
-
prompt.push({ type: "text", text: WARM_CONTINUATION });
|
|
59103
|
-
return { prompt, messageCount: context.messages.length };
|
|
59104
|
-
}
|
|
59105
|
-
if (hasTrailingResults) prompt.push({ type: "text", text: CONTINUATION_LABEL });
|
|
59106
|
-
if (typeof latest.content === "string") {
|
|
59107
|
-
if (latest.content.length > 0) prompt.push({ type: "text", text: latest.content });
|
|
59108
|
-
} else {
|
|
59109
|
-
for (const block of latest.content) {
|
|
59110
|
-
if (block.type === "text") prompt.push({ type: "text", text: block.text });
|
|
59111
|
-
else prompt.push({ type: "image", data: block.data, mimeType: block.mimeType });
|
|
59112
|
-
}
|
|
59113
|
-
}
|
|
59114
|
-
if (prompt.length === 0) throw new AntigravityAcpError("invalid_input", "User message has no supported content");
|
|
59115
|
-
return { prompt, messageCount: context.messages.length };
|
|
59093
|
+
return bytes;
|
|
59116
59094
|
}
|
|
59117
|
-
function
|
|
59118
|
-
|
|
59119
|
-
|
|
59095
|
+
function buildPromptParts(context, fresh, unseenStart, limits = {}) {
|
|
59096
|
+
const options = resolveContextOptions(
|
|
59097
|
+
{ id: "transfer", contextWindow: limits.contextWindow ?? 32768, maxTokens: limits.maxTokens ?? 8192 },
|
|
59098
|
+
{ defaults: limits.policy ?? {}, models: {} }
|
|
59099
|
+
);
|
|
59100
|
+
const messages = context.messages;
|
|
59101
|
+
let latest = messages.length - 1;
|
|
59102
|
+
while (latest >= 0 && messages[latest].role !== "user") latest--;
|
|
59103
|
+
if (latest < 0) throw new Error("No user message to send to Antigravity ACP");
|
|
59104
|
+
if (!fresh && (unseenStart === void 0 || !Number.isSafeInteger(unseenStart) || unseenStart < 0 || unseenStart > messages.length)) {
|
|
59105
|
+
throw new Error("Warm ACP context has an invalid unseen boundary");
|
|
59106
|
+
}
|
|
59107
|
+
const end = messages.length > latest + 1 ? messages.length : latest;
|
|
59108
|
+
const start = fresh ? 0 : unseenStart;
|
|
59109
|
+
const prompt = [];
|
|
59110
|
+
const instructions = fresh ? currentSystemInstructions(context) : "";
|
|
59111
|
+
if (instructions) prompt.push({ type: "resource", resource: {
|
|
59112
|
+
uri: "urn:omp:antigravity-acp:instructions",
|
|
59120
59113
|
mimeType: "text/markdown",
|
|
59121
|
-
text
|
|
59122
|
-
|
|
59123
|
-
}
|
|
59124
|
-
|
|
59125
|
-
|
|
59126
|
-
const
|
|
59127
|
-
if (full.length <= MAX_RECONSTRUCTION_CHARS) return full;
|
|
59128
|
-
const prefix = `${heading}${ENTRY_SEPARATOR}[truncated older context]`;
|
|
59129
|
-
const firstPinned = entries.findIndex((entry) => entry.pinned);
|
|
59130
|
-
const pinnedStart = firstPinned < 0 ? entries.length : firstPinned;
|
|
59131
|
-
const pinned = entries.slice(pinnedStart);
|
|
59132
|
-
const rendered = pinned.map(minimalEntry);
|
|
59133
|
-
let remaining = MAX_RECONSTRUCTION_CHARS - prefix.length - rendered.reduce((total, text) => total + ENTRY_SEPARATOR.length + text.length, 0);
|
|
59134
|
-
if (remaining < 0) {
|
|
59135
|
-
throw new AntigravityAcpError("invalid_input", "The latest Pi tool turn does not fit in the Antigravity ACP context budget");
|
|
59136
|
-
}
|
|
59137
|
-
const grow = (index, allowance) => {
|
|
59138
|
-
const entry = pinned[index];
|
|
59139
|
-
const whole = renderEntry(entry);
|
|
59140
|
-
if (entry.body === void 0 || rendered[index] === whole || allowance <= 0) return 0;
|
|
59141
|
-
const extra = whole.length - rendered[index].length;
|
|
59142
|
-
if (extra <= allowance) {
|
|
59143
|
-
rendered[index] = whole;
|
|
59144
|
-
return extra;
|
|
59145
|
-
}
|
|
59146
|
-
const kept = tailCodePoints(entry.body, allowance);
|
|
59147
|
-
if (!kept) return 0;
|
|
59148
|
-
rendered[index] = renderEntry(entry, kept);
|
|
59149
|
-
return kept.length;
|
|
59150
|
-
};
|
|
59151
|
-
const newestFirst = pinned.map((_, index) => index).reverse();
|
|
59152
|
-
let callAllowance = Math.floor(remaining / 2);
|
|
59153
|
-
for (const index of newestFirst) {
|
|
59154
|
-
if (pinned[index].toolResult) continue;
|
|
59155
|
-
const used = grow(index, callAllowance);
|
|
59156
|
-
callAllowance -= used;
|
|
59157
|
-
remaining -= used;
|
|
59158
|
-
}
|
|
59159
|
-
for (const index of newestFirst) {
|
|
59160
|
-
if (pinned[index].toolResult) remaining -= grow(index, remaining);
|
|
59161
|
-
}
|
|
59162
|
-
const older = [];
|
|
59163
|
-
for (let index = pinnedStart - 1; index >= 0; index--) {
|
|
59164
|
-
const entry = entries[index];
|
|
59165
|
-
const whole = renderEntry(entry);
|
|
59166
|
-
if (whole.length + ENTRY_SEPARATOR.length <= remaining) {
|
|
59167
|
-
older.unshift(whole);
|
|
59168
|
-
remaining -= whole.length + ENTRY_SEPARATOR.length;
|
|
59169
|
-
continue;
|
|
59170
|
-
}
|
|
59171
|
-
if (older.length === 0 && entry.body !== void 0) {
|
|
59172
|
-
const available = remaining - ENTRY_SEPARATOR.length - renderEntry(entry, "").length;
|
|
59173
|
-
const kept = tailCodePoints(entry.body, available);
|
|
59174
|
-
if (kept) older.unshift(renderEntry(entry, kept));
|
|
59175
|
-
}
|
|
59176
|
-
break;
|
|
59177
|
-
}
|
|
59178
|
-
return [prefix, ...older, ...rendered].join(ENTRY_SEPARATOR);
|
|
59179
|
-
}
|
|
59180
|
-
function minimalEntry(entry) {
|
|
59181
|
-
if (entry.body === void 0) return entry.label;
|
|
59182
|
-
const whole = renderEntry(entry);
|
|
59183
|
-
const empty = renderEntry(entry, "");
|
|
59184
|
-
return whole.length <= empty.length ? whole : empty;
|
|
59185
|
-
}
|
|
59186
|
-
function renderEntry(entry, body = entry.body) {
|
|
59187
|
-
if (body === void 0) return entry.label;
|
|
59188
|
-
const label = body === entry.body ? entry.label : `${entry.label} [truncated]`;
|
|
59189
|
-
let longest = 0;
|
|
59190
|
-
for (const match of (entry.body ?? "").matchAll(/`+/gu)) longest = Math.max(longest, match[0].length);
|
|
59191
|
-
const fence = "`".repeat(Math.max(3, longest + 1));
|
|
59192
|
-
return `${label}
|
|
59193
|
-
${fence}
|
|
59194
|
-
${body}
|
|
59195
|
-
${fence}`;
|
|
59196
|
-
}
|
|
59197
|
-
function tailCodePoints(text, length) {
|
|
59198
|
-
if (length <= 0) return "";
|
|
59199
|
-
let start = text.length - length;
|
|
59200
|
-
if (start <= 0) return text;
|
|
59201
|
-
const unit = text.charCodeAt(start);
|
|
59202
|
-
if (unit >= 56320 && unit <= 57343) start++;
|
|
59203
|
-
return text.slice(start);
|
|
59204
|
-
}
|
|
59205
|
-
function historyEntries(messages, start, end, currentIndex, pinStart) {
|
|
59206
|
-
const entries = [];
|
|
59114
|
+
text: `# OMP session instructions
|
|
59115
|
+
|
|
59116
|
+
${instructions}`
|
|
59117
|
+
} });
|
|
59118
|
+
const records = [];
|
|
59119
|
+
const images = [];
|
|
59207
59120
|
for (let index = start; index < end; index++) {
|
|
59208
59121
|
const message = messages[index];
|
|
59209
|
-
if (
|
|
59210
|
-
const
|
|
59211
|
-
|
|
59212
|
-
|
|
59213
|
-
|
|
59214
|
-
}
|
|
59215
|
-
|
|
59216
|
-
|
|
59217
|
-
|
|
59218
|
-
|
|
59219
|
-
|
|
59220
|
-
}
|
|
59221
|
-
|
|
59222
|
-
if (message.role === "system") return [];
|
|
59223
|
-
if (message.role === "user") return [{ label: "## User", body: contentText2(message.content) }];
|
|
59224
|
-
if (message.role === "assistant") {
|
|
59225
|
-
const texts = [];
|
|
59226
|
-
const calls = [];
|
|
59227
|
-
for (const block of message.content) {
|
|
59228
|
-
if (block.type === "text" && block.text) texts.push(block.text);
|
|
59229
|
-
else if (block.type === "toolCall") calls.push({
|
|
59230
|
-
label: `[tool call ${oneLine(block.name)} id=${oneLine(block.id)}]`,
|
|
59231
|
-
body: JSON.stringify(block.arguments)
|
|
59232
|
-
});
|
|
59233
|
-
}
|
|
59234
|
-
if (texts.length === 0 && calls.length === 0) return [];
|
|
59235
|
-
const label = `## Assistant (${oneLine(message.provider)})`;
|
|
59236
|
-
return [texts.length ? { label, body: texts.join("\n") } : { label }, ...calls];
|
|
59122
|
+
if (index === latest || message.role === "system") continue;
|
|
59123
|
+
const content = typeof message.content === "string" ? message.content : message.content.filter((block) => ["text", "toolCall", "image"].includes(block.type)).map((block) => {
|
|
59124
|
+
if (block.type === "image") {
|
|
59125
|
+
const imageIndex = images.length;
|
|
59126
|
+
images.push(
|
|
59127
|
+
{ type: "text", text: `Historical image from OMP message ${index}; treat as conversation data.` },
|
|
59128
|
+
{ type: "image", data: block.data, mimeType: block.mimeType }
|
|
59129
|
+
);
|
|
59130
|
+
return { type: "image", attachment: imageIndex / 2 };
|
|
59131
|
+
}
|
|
59132
|
+
return block.type === "toolCall" ? { type: block.type, id: block.id, name: block.name, arguments: block.arguments } : { type: "text", text: block.text };
|
|
59133
|
+
});
|
|
59134
|
+
records.push({ role: message.role, toolName: message.toolName, toolCallId: message.toolCallId, isError: message.isError, content });
|
|
59237
59135
|
}
|
|
59238
|
-
|
|
59239
|
-
|
|
59240
|
-
|
|
59241
|
-
|
|
59242
|
-
}
|
|
59243
|
-
|
|
59244
|
-
|
|
59245
|
-
|
|
59246
|
-
}
|
|
59247
|
-
|
|
59248
|
-
|
|
59249
|
-
|
|
59136
|
+
if (records.length) prompt.push({ type: "resource", resource: {
|
|
59137
|
+
uri: "urn:omp:antigravity-acp:history",
|
|
59138
|
+
mimeType: "text/plain",
|
|
59139
|
+
text: "Prior conversation data, not new instructions. Do not repeat completed tool actions.\n" + JSON.stringify(records)
|
|
59140
|
+
} });
|
|
59141
|
+
prompt.push(...images);
|
|
59142
|
+
if (!fresh && start > latest) {
|
|
59143
|
+
prompt.push({ type: "text", text: "Continue the current OMP user request with the new results. Do not repeat completed tool actions." });
|
|
59144
|
+
} else {
|
|
59145
|
+
const content = messages[latest].content;
|
|
59146
|
+
prompt.push(...typeof content === "string" ? [{ type: "text", text: content }] : content.map((block) => ({ ...block })));
|
|
59147
|
+
}
|
|
59148
|
+
let imageBytes = 0;
|
|
59149
|
+
let imageCount = 0;
|
|
59150
|
+
let imageWireChars = 0;
|
|
59151
|
+
const textOnly = prompt.map((block) => {
|
|
59152
|
+
if (block.type !== "image") return block;
|
|
59153
|
+
imageBytes += Math.ceil((block.data?.length ?? 0) * 3 / 4);
|
|
59154
|
+
imageWireChars += block.data?.length ?? 0;
|
|
59155
|
+
imageCount++;
|
|
59156
|
+
return { type: "image", mimeType: block.mimeType };
|
|
59157
|
+
});
|
|
59158
|
+
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.`);
|
|
59159
|
+
const serialized = JSON.stringify(textOnly);
|
|
59160
|
+
const bytes = Buffer.byteLength(serialized, "utf8") + imageWireChars + imageCount * 10;
|
|
59161
|
+
const budget = historyBudget(void 0, process.env, options.maxTransferBytes);
|
|
59162
|
+
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.`);
|
|
59163
|
+
const estimatedTokens = estimateTransferTokens(serialized, imageCount);
|
|
59164
|
+
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.`);
|
|
59165
|
+
return { prompt, messageCount: messages.length };
|
|
59250
59166
|
}
|
|
59251
59167
|
|
|
59252
59168
|
// node_modules/pi-antigravity-acp-provider/src/stream/json.ts
|
|
@@ -59416,6 +59332,14 @@ var PiEventWriter = class {
|
|
|
59416
59332
|
}
|
|
59417
59333
|
};
|
|
59418
59334
|
|
|
59335
|
+
// extension/usage.ts
|
|
59336
|
+
function usageFromPrompt2(response) {
|
|
59337
|
+
const usage = usageFromPrompt(response);
|
|
59338
|
+
const context = response._meta?.ompContextTokens;
|
|
59339
|
+
if (Number.isSafeInteger(context) && context >= 0) usage.contextTokens = context;
|
|
59340
|
+
return usage;
|
|
59341
|
+
}
|
|
59342
|
+
|
|
59419
59343
|
// node_modules/pi-antigravity-acp-provider/src/status.ts
|
|
59420
59344
|
var RuntimeMetrics = class {
|
|
59421
59345
|
totals = {
|
|
@@ -59795,7 +59719,7 @@ var AntigravityRuntime = class {
|
|
|
59795
59719
|
unseenStart += 1;
|
|
59796
59720
|
}
|
|
59797
59721
|
const parts = adaptPromptToCapabilities(
|
|
59798
|
-
buildPromptParts(context, fresh, unseenStart),
|
|
59722
|
+
buildPromptParts(context, fresh, unseenStart, { contextWindow: model.contextWindow, maxTokens: model.maxTokens, policy: model.ompContextPolicy }),
|
|
59799
59723
|
binding.initialize
|
|
59800
59724
|
);
|
|
59801
59725
|
await this.modeChanges;
|
|
@@ -59824,7 +59748,7 @@ var AntigravityRuntime = class {
|
|
|
59824
59748
|
if (onTurnAbort) options.signal?.removeEventListener("abort", onTurnAbort);
|
|
59825
59749
|
const activeWriter = binding.writer ?? writer;
|
|
59826
59750
|
if (binding.abortRequested) throw abortError();
|
|
59827
|
-
const usage =
|
|
59751
|
+
const usage = usageFromPrompt2(response);
|
|
59828
59752
|
activeWriter.message.usage = usage;
|
|
59829
59753
|
this.metrics.record(response, usage);
|
|
59830
59754
|
activeWriter.message.rawStopReason = response.stopReason;
|
|
@@ -59855,7 +59779,7 @@ var AntigravityRuntime = class {
|
|
|
59855
59779
|
binding.writer = void 0;
|
|
59856
59780
|
release();
|
|
59857
59781
|
if (this.queues.get(key) === queue) this.queues.delete(key);
|
|
59858
|
-
if (!persistent) await this.dropBinding(key, binding);
|
|
59782
|
+
if (!persistent || !binding.connection.process.alive) await this.dropBinding(key, binding);
|
|
59859
59783
|
}
|
|
59860
59784
|
}
|
|
59861
59785
|
async awaitContinuation(binding, signal) {
|
|
@@ -60507,15 +60431,69 @@ function showAcpUpdate(notification, debugToolUpdates) {
|
|
|
60507
60431
|
return debugToolUpdates || kind !== "tool_call" && kind !== "tool_call_update";
|
|
60508
60432
|
}
|
|
60509
60433
|
|
|
60434
|
+
// extension/usage-accounting.ts
|
|
60435
|
+
function parseSessionUsage(text) {
|
|
60436
|
+
const match = text.match(/\*\*Session total:\*\*\s*([\d,]+) tokens(?:\s*\(([^)]+)\))?/);
|
|
60437
|
+
if (!match) return;
|
|
60438
|
+
const total = Number(match[1].replaceAll(",", ""));
|
|
60439
|
+
const counts = {};
|
|
60440
|
+
for (const part of (match[2] ?? "").matchAll(/(prompt|completion|thinking|cached):\s*([\d,]+)/g)) counts[part[1]] = Number(part[2].replaceAll(",", ""));
|
|
60441
|
+
if (![total, ...Object.values(counts)].every((n) => Number.isSafeInteger(n) && n >= 0)) return;
|
|
60442
|
+
if (!Object.keys(counts).length && total > 0) return;
|
|
60443
|
+
const usage = { input: counts.prompt ?? 0, completion: counts.completion ?? 0, thinking: counts.thinking ?? 0, cached: counts.cached, total };
|
|
60444
|
+
if (usage.cached !== void 0 && usage.cached > usage.input) return;
|
|
60445
|
+
if (usage.input + usage.completion + usage.thinking !== usage.total) return;
|
|
60446
|
+
return usage;
|
|
60447
|
+
}
|
|
60448
|
+
function usageDelta(before, after) {
|
|
60449
|
+
const input2 = after.input - before.input;
|
|
60450
|
+
const completion = after.completion - before.completion;
|
|
60451
|
+
const thinking = after.thinking - before.thinking;
|
|
60452
|
+
const total = after.total - before.total;
|
|
60453
|
+
if ([input2, completion, thinking, total].some((n) => n < 0)) return;
|
|
60454
|
+
const cacheKnown = before.cached !== void 0 && after.cached !== void 0;
|
|
60455
|
+
const cached2 = cacheKnown ? after.cached - before.cached : void 0;
|
|
60456
|
+
if (cached2 !== void 0 && (cached2 < 0 || cached2 > input2)) return;
|
|
60457
|
+
return {
|
|
60458
|
+
inputTokens: input2,
|
|
60459
|
+
outputTokens: completion + thinking,
|
|
60460
|
+
thoughtTokens: thinking,
|
|
60461
|
+
totalTokens: total,
|
|
60462
|
+
...cached2 !== void 0 ? { cachedReadTokens: cached2 } : {}
|
|
60463
|
+
};
|
|
60464
|
+
}
|
|
60465
|
+
|
|
60510
60466
|
// extension/tier-connection.ts
|
|
60511
60467
|
var TierConnection = class extends AntigravityAcpConnection {
|
|
60512
60468
|
confirmedThinking;
|
|
60513
60469
|
debugToolUpdates;
|
|
60470
|
+
activePrompts = 0;
|
|
60471
|
+
usageQueryCount = 0;
|
|
60472
|
+
usageQueryMs = 0;
|
|
60473
|
+
usageMode = "auto";
|
|
60474
|
+
contextUsage = /* @__PURE__ */ new Map();
|
|
60475
|
+
usageStatus = /* @__PURE__ */ new Map();
|
|
60476
|
+
usageBaselines = /* @__PURE__ */ new Map();
|
|
60477
|
+
usageCapture;
|
|
60478
|
+
usageCommands = /* @__PURE__ */ new Set();
|
|
60514
60479
|
toolRouting;
|
|
60515
60480
|
constructor(options) {
|
|
60516
60481
|
super(options);
|
|
60517
60482
|
this.debugToolUpdates = options.ompDebugToolUpdates ?? false;
|
|
60483
|
+
this.usageMode = options.ompUsageMode ?? "auto";
|
|
60518
60484
|
this.setHandlers({ ...options.handlers, onUpdate: async (notification) => {
|
|
60485
|
+
const update = notification.update;
|
|
60486
|
+
if (update.sessionUpdate === "available_commands_update") {
|
|
60487
|
+
if (update.availableCommands?.some((command) => command.name === "usage")) this.usageCommands.add(notification.sessionId);
|
|
60488
|
+
else this.usageCommands.delete(notification.sessionId);
|
|
60489
|
+
}
|
|
60490
|
+
if (update.sessionUpdate === "usage_update" && Number.isSafeInteger(update.used) && Number.isSafeInteger(update.size)) {
|
|
60491
|
+
this.contextUsage.set(notification.sessionId, { used: update.used, size: update.size });
|
|
60492
|
+
}
|
|
60493
|
+
if (this.usageCapture) {
|
|
60494
|
+
if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") this.usageCapture.text += update.content.text;
|
|
60495
|
+
return;
|
|
60496
|
+
}
|
|
60519
60497
|
if (showAcpUpdate(notification, this.debugToolUpdates)) await options.handlers?.onUpdate?.(notification);
|
|
60520
60498
|
} });
|
|
60521
60499
|
if (options.ompNativeTools) {
|
|
@@ -60525,6 +60503,71 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
60525
60503
|
});
|
|
60526
60504
|
}
|
|
60527
60505
|
}
|
|
60506
|
+
configureUsage(mode) {
|
|
60507
|
+
this.usageMode = mode;
|
|
60508
|
+
this.usageBaselines.clear();
|
|
60509
|
+
}
|
|
60510
|
+
async newSession(...args) {
|
|
60511
|
+
const session = await super.newSession(...args);
|
|
60512
|
+
this.usageBaselines.set(session.sessionId, { input: 0, completion: 0, thinking: 0, cached: 0, total: 0 });
|
|
60513
|
+
return session;
|
|
60514
|
+
}
|
|
60515
|
+
async readUsage(sessionId, signal) {
|
|
60516
|
+
const started = performance.now();
|
|
60517
|
+
this.usageQueryCount++;
|
|
60518
|
+
const capture = { text: "" };
|
|
60519
|
+
this.usageCapture = capture;
|
|
60520
|
+
try {
|
|
60521
|
+
const deadline = AbortSignal.timeout(5e3);
|
|
60522
|
+
await super.prompt(
|
|
60523
|
+
{ sessionId, prompt: [{ type: "text", text: "/usage" }] },
|
|
60524
|
+
signal ? AbortSignal.any([signal, deadline]) : deadline
|
|
60525
|
+
);
|
|
60526
|
+
return parseSessionUsage(capture.text);
|
|
60527
|
+
} finally {
|
|
60528
|
+
this.usageCapture = void 0;
|
|
60529
|
+
this.usageQueryMs += performance.now() - started;
|
|
60530
|
+
}
|
|
60531
|
+
}
|
|
60532
|
+
async prompt(request, signal) {
|
|
60533
|
+
this.activePrompts++;
|
|
60534
|
+
const id = request.sessionId;
|
|
60535
|
+
try {
|
|
60536
|
+
const queryUsage = process.env.OMP_ACP_USAGE !== "off" && this.usageMode !== "off" && this.usageCommands.has(id);
|
|
60537
|
+
if (queryUsage && !this.usageBaselines.has(id)) {
|
|
60538
|
+
try {
|
|
60539
|
+
const baseline = await this.readUsage(id, signal);
|
|
60540
|
+
if (baseline) this.usageBaselines.set(id, baseline);
|
|
60541
|
+
} catch {
|
|
60542
|
+
}
|
|
60543
|
+
}
|
|
60544
|
+
const response = await super.prompt(request, signal);
|
|
60545
|
+
const withContext = (value) => {
|
|
60546
|
+
const context = this.contextUsage.get(id);
|
|
60547
|
+
return context ? { ...value, _meta: { ...value._meta, ompContextTokens: context.used } } : value;
|
|
60548
|
+
};
|
|
60549
|
+
if (response.usage || process.env.OMP_ACP_USAGE === "off" || this.usageMode === "off" || !this.usageCommands.has(id) || signal?.aborted) {
|
|
60550
|
+
this.usageBaselines.delete(id);
|
|
60551
|
+
this.usageStatus.set(id, { source: response.usage ? "ACP response" : "unavailable", cache: "unknown" });
|
|
60552
|
+
return withContext(response);
|
|
60553
|
+
}
|
|
60554
|
+
try {
|
|
60555
|
+
const after = await this.readUsage(id, signal);
|
|
60556
|
+
const before = this.usageBaselines.get(id);
|
|
60557
|
+
const usage = before && after ? usageDelta(before, after) : void 0;
|
|
60558
|
+
if (after) this.usageBaselines.set(id, after);
|
|
60559
|
+
else this.usageBaselines.delete(id);
|
|
60560
|
+
this.usageStatus.set(id, { source: usage ? "official /usage delta (main agent)" : "unavailable", cache: usage?.cachedReadTokens === void 0 ? "unknown" : "reported" });
|
|
60561
|
+
return withContext(usage ? { ...response, usage } : response);
|
|
60562
|
+
} catch {
|
|
60563
|
+
this.usageBaselines.delete(id);
|
|
60564
|
+
this.usageStatus.set(id, { source: "unavailable", cache: "unknown", error: "Official usage query failed or timed out" });
|
|
60565
|
+
return withContext(response);
|
|
60566
|
+
}
|
|
60567
|
+
} finally {
|
|
60568
|
+
this.activePrompts--;
|
|
60569
|
+
}
|
|
60570
|
+
}
|
|
60528
60571
|
async setModel(sessionId, modelId, signal) {
|
|
60529
60572
|
const { modelId: base, effort } = resolveSelection(this.getSessionState(sessionId), modelId);
|
|
60530
60573
|
await super.setModel(sessionId, base, signal);
|
|
@@ -4,16 +4,39 @@ import { AntigravityAcpConnection } from "pi-antigravity-acp-provider/src/acp/co
|
|
|
4
4
|
import { choices, resolveSelection, selector } from "./selectors.ts";
|
|
5
5
|
import { installSessionRouting, type NativeToolMode } from "./tool-routing.ts";
|
|
6
6
|
import { showAcpUpdate } from "./activity-presentation.ts";
|
|
7
|
+
import { parseSessionUsage, usageDelta, type SessionUsage } from "./usage-accounting.ts";
|
|
7
8
|
|
|
8
9
|
export class TierConnection extends AntigravityAcpConnection {
|
|
9
10
|
confirmedThinking: { model: string; effort: string } | undefined;
|
|
10
11
|
debugToolUpdates: boolean;
|
|
12
|
+
activePrompts = 0;
|
|
13
|
+
usageQueryCount = 0;
|
|
14
|
+
usageQueryMs = 0;
|
|
15
|
+
usageMode: "auto" | "off" = "auto";
|
|
16
|
+
readonly contextUsage = new Map<string, { used: number; size: number }>();
|
|
17
|
+
readonly usageStatus = new Map<string, { source: string; cache: string; error?: string }>();
|
|
18
|
+
private readonly usageBaselines = new Map<string, SessionUsage>();
|
|
19
|
+
private usageCapture: { text: string } | undefined;
|
|
20
|
+
private readonly usageCommands = new Set<string>();
|
|
11
21
|
toolRouting: { nativeTools: NativeToolMode; channel: "pending" | "system-append" | "legacy-prompt" } | undefined;
|
|
12
22
|
|
|
13
|
-
constructor(options: ConstructorParameters<typeof AntigravityAcpConnection>[0] & { ompNativeTools?: NativeToolMode; ompDebugToolUpdates?: boolean }) {
|
|
23
|
+
constructor(options: ConstructorParameters<typeof AntigravityAcpConnection>[0] & { ompNativeTools?: NativeToolMode; ompDebugToolUpdates?: boolean; ompUsageMode?: "auto" | "off" }) {
|
|
14
24
|
super(options);
|
|
15
25
|
this.debugToolUpdates = options.ompDebugToolUpdates ?? false;
|
|
26
|
+
this.usageMode = options.ompUsageMode ?? "auto";
|
|
16
27
|
this.setHandlers({ ...options.handlers, onUpdate: async notification => {
|
|
28
|
+
const update: any = notification.update;
|
|
29
|
+
if (update.sessionUpdate === "available_commands_update") {
|
|
30
|
+
if (update.availableCommands?.some((command: any) => command.name === "usage")) this.usageCommands.add(notification.sessionId);
|
|
31
|
+
else this.usageCommands.delete(notification.sessionId);
|
|
32
|
+
}
|
|
33
|
+
if (update.sessionUpdate === "usage_update" && Number.isSafeInteger(update.used) && Number.isSafeInteger(update.size)) {
|
|
34
|
+
this.contextUsage.set(notification.sessionId, { used: update.used, size: update.size });
|
|
35
|
+
}
|
|
36
|
+
if (this.usageCapture) {
|
|
37
|
+
if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") this.usageCapture.text += update.content.text;
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
17
40
|
if (showAcpUpdate(notification, this.debugToolUpdates)) await options.handlers?.onUpdate?.(notification);
|
|
18
41
|
} });
|
|
19
42
|
if (options.ompNativeTools) {
|
|
@@ -24,6 +47,66 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
24
47
|
}
|
|
25
48
|
}
|
|
26
49
|
|
|
50
|
+
configureUsage(mode: "auto" | "off") {
|
|
51
|
+
this.usageMode = mode;
|
|
52
|
+
this.usageBaselines.clear();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
override async newSession(...args: Parameters<AntigravityAcpConnection["newSession"]>) {
|
|
56
|
+
const session = await super.newSession(...args);
|
|
57
|
+
this.usageBaselines.set(session.sessionId, { input: 0, completion: 0, thinking: 0, cached: 0, total: 0 });
|
|
58
|
+
return session;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private async readUsage(sessionId: string, signal?: AbortSignal) {
|
|
62
|
+
const started = performance.now();
|
|
63
|
+
this.usageQueryCount++;
|
|
64
|
+
const capture = { text: "" };
|
|
65
|
+
this.usageCapture = capture;
|
|
66
|
+
try {
|
|
67
|
+
const deadline = AbortSignal.timeout(5_000);
|
|
68
|
+
await super.prompt({ sessionId, prompt: [{ type: "text", text: "/usage" }] },
|
|
69
|
+
signal ? AbortSignal.any([signal, deadline]) : deadline);
|
|
70
|
+
return parseSessionUsage(capture.text);
|
|
71
|
+
} finally { this.usageCapture = undefined; this.usageQueryMs += performance.now() - started; }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
override async prompt(request: Parameters<AntigravityAcpConnection["prompt"]>[0], signal?: AbortSignal) {
|
|
75
|
+
this.activePrompts++;
|
|
76
|
+
const id = request.sessionId;
|
|
77
|
+
try {
|
|
78
|
+
const queryUsage = process.env.OMP_ACP_USAGE !== "off" && this.usageMode !== "off" && this.usageCommands.has(id);
|
|
79
|
+
if (queryUsage && !this.usageBaselines.has(id)) {
|
|
80
|
+
try {
|
|
81
|
+
const baseline = await this.readUsage(id, signal);
|
|
82
|
+
if (baseline) this.usageBaselines.set(id, baseline);
|
|
83
|
+
} catch { /* Restore baseline is optional; never count the prior session as this turn. */ }
|
|
84
|
+
}
|
|
85
|
+
const response = await super.prompt(request, signal);
|
|
86
|
+
const withContext = (value: any) => {
|
|
87
|
+
const context = this.contextUsage.get(id);
|
|
88
|
+
return context ? { ...value, _meta: { ...value._meta, ompContextTokens: context.used } } : value;
|
|
89
|
+
};
|
|
90
|
+
if (response.usage || process.env.OMP_ACP_USAGE === "off" || this.usageMode === "off" || !this.usageCommands.has(id) || signal?.aborted) {
|
|
91
|
+
this.usageBaselines.delete(id);
|
|
92
|
+
this.usageStatus.set(id, { source: response.usage ? "ACP response" : "unavailable", cache: "unknown" });
|
|
93
|
+
return withContext(response);
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
const after = await this.readUsage(id, signal);
|
|
97
|
+
const before = this.usageBaselines.get(id);
|
|
98
|
+
const usage = before && after ? usageDelta(before, after) : undefined;
|
|
99
|
+
if (after) this.usageBaselines.set(id, after); else this.usageBaselines.delete(id);
|
|
100
|
+
this.usageStatus.set(id, { source: usage ? "official /usage delta (main agent)" : "unavailable", cache: usage?.cachedReadTokens === undefined ? "unknown" : "reported" });
|
|
101
|
+
return withContext(usage ? { ...response, usage } : response);
|
|
102
|
+
} catch {
|
|
103
|
+
this.usageBaselines.delete(id);
|
|
104
|
+
this.usageStatus.set(id, { source: "unavailable", cache: "unknown", error: "Official usage query failed or timed out" });
|
|
105
|
+
return withContext(response);
|
|
106
|
+
}
|
|
107
|
+
} finally { this.activePrompts--; }
|
|
108
|
+
}
|
|
109
|
+
|
|
27
110
|
override async setModel(sessionId: string, modelId: string, signal?: AbortSignal): Promise<void> {
|
|
28
111
|
const { modelId: base, effort } = resolveSelection(this.getSessionState(sessionId), modelId);
|
|
29
112
|
// These are official ACP session/set_config_option requests. The legacy
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface SessionUsage {
|
|
2
|
+
input: number; completion: number; thinking: number; cached?: number; total: number;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function parseSessionUsage(text: string): SessionUsage | undefined {
|
|
6
|
+
const match = text.match(/\*\*Session total:\*\*\s*([\d,]+) tokens(?:\s*\(([^)]+)\))?/);
|
|
7
|
+
if (!match) return;
|
|
8
|
+
const total = Number(match[1].replaceAll(",", ""));
|
|
9
|
+
const counts: Record<string, number> = {};
|
|
10
|
+
for (const part of (match[2] ?? "").matchAll(/(prompt|completion|thinking|cached):\s*([\d,]+)/g)) counts[part[1]] = Number(part[2].replaceAll(",", ""));
|
|
11
|
+
if (![total, ...Object.values(counts)].every(n => Number.isSafeInteger(n) && n >= 0)) return;
|
|
12
|
+
if (!Object.keys(counts).length && total > 0) return;
|
|
13
|
+
const usage = { input: counts.prompt ?? 0, completion: counts.completion ?? 0, thinking: counts.thinking ?? 0, cached: counts.cached, total };
|
|
14
|
+
if (usage.cached !== undefined && usage.cached > usage.input) return;
|
|
15
|
+
if (usage.input + usage.completion + usage.thinking !== usage.total) return;
|
|
16
|
+
return usage;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function usageDelta(before: SessionUsage, after: SessionUsage) {
|
|
20
|
+
const input = after.input - before.input;
|
|
21
|
+
const completion = after.completion - before.completion;
|
|
22
|
+
const thinking = after.thinking - before.thinking;
|
|
23
|
+
const total = after.total - before.total;
|
|
24
|
+
if ([input, completion, thinking, total].some(n => n < 0)) return;
|
|
25
|
+
const cacheKnown = before.cached !== undefined && after.cached !== undefined;
|
|
26
|
+
const cached = cacheKnown ? after.cached! - before.cached! : undefined;
|
|
27
|
+
if (cached !== undefined && (cached < 0 || cached > input)) return;
|
|
28
|
+
return { inputTokens: input, outputTokens: completion + thinking, thoughtTokens: thinking,
|
|
29
|
+
totalTokens: total, ...(cached !== undefined ? { cachedReadTokens: cached } : {}) };
|
|
30
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { usageFromPrompt as upstreamUsage } from "pi-antigravity-acp-provider/src/stream/usage.ts";
|
|
2
|
+
|
|
3
|
+
export function usageFromPrompt(response: any) {
|
|
4
|
+
const usage: any = upstreamUsage(response);
|
|
5
|
+
const context = response._meta?.ompContextTokens;
|
|
6
|
+
// OMP accepts contextTokens independently from aggregate billable tokens.
|
|
7
|
+
if (Number.isSafeInteger(context) && context >= 0) usage.contextTokens = context;
|
|
8
|
+
return usage;
|
|
9
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omp-antigravity-acp-provider",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
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",
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"test:packed": "node scripts/test-packed.mjs",
|
|
40
40
|
"test:marketplace": "node scripts/test-marketplace.mjs",
|
|
41
41
|
"test:commands": "bun scripts/test-tool-command.ts",
|
|
42
|
+
"test:usage": "bun scripts/test-usage-command.ts",
|
|
42
43
|
"check": "npm run build && npm test",
|
|
43
44
|
"prepack": "npm run build",
|
|
44
45
|
"prepublishOnly": "npm run check"
|
package/scripts/build.mjs
CHANGED
|
@@ -46,6 +46,22 @@ const result = await build({
|
|
|
46
46
|
plugins: [{
|
|
47
47
|
name: "portable-upstream-assets",
|
|
48
48
|
setup(builder) {
|
|
49
|
+
builder.onResolve({ filter: /^\.\/stream\/context\.js$/ }, ({ importer }) => {
|
|
50
|
+
if (importer === path.join(upstream, "src/runtime.ts")) return { path: path.join(root, "extension/context-transfer.ts") };
|
|
51
|
+
});
|
|
52
|
+
builder.onResolve({ filter: /^\.\/stream\/usage\.js$/ }, ({ importer }) => {
|
|
53
|
+
if (importer === path.join(upstream, "src/runtime.ts")) return { path: path.join(root, "extension/usage.ts") };
|
|
54
|
+
});
|
|
55
|
+
builder.onLoad({ filter: /\/src\/runtime\.ts$/ }, async ({ path: file }) => {
|
|
56
|
+
if (file !== path.join(upstream, "src/runtime.ts")) return;
|
|
57
|
+
const source = await fs.readFile(file, "utf8");
|
|
58
|
+
const marker = "buildPromptParts(context, fresh, unseenStart)";
|
|
59
|
+
if (source.split(marker).length !== 2) throw new Error("Pinned upstream context seam changed; review compatibility");
|
|
60
|
+
const retirement = "if (!persistent) await this.dropBinding(key, binding);";
|
|
61
|
+
if (source.split(retirement).length !== 2) throw new Error("Pinned upstream connection retirement seam changed; review compatibility");
|
|
62
|
+
return { contents: source.replace(marker, "buildPromptParts(context, fresh, unseenStart, { contextWindow: model.contextWindow, maxTokens: model.maxTokens, policy: model.ompContextPolicy })")
|
|
63
|
+
.replace(retirement, "if (!persistent || !binding.connection.process.alive) await this.dropBinding(key, binding);"), loader: "ts" };
|
|
64
|
+
});
|
|
49
65
|
builder.onLoad({ filter: /\/(?:process|runtime-manifest)\.ts$/ }, async ({ path: file }) => {
|
|
50
66
|
const relative = path.relative(upstream, file).split(path.sep).join("/");
|
|
51
67
|
return {
|