omp-antigravity-acp-provider 0.1.26 → 0.1.27
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 +21 -6
- package/extension/auth-sync.ts +24 -1
- package/extension/catalog-store.ts +32 -19
- package/extension/commands.ts +8 -6
- package/extension/context-settings.ts +3 -2
- package/extension/context-transfer.ts +33 -14
- package/extension/index.ts +31 -16
- package/extension/omp-context.ts +19 -0
- package/extension/omp-session-lifecycle.ts +135 -0
- package/extension/runtime-pool.ts +26 -13
- package/extension/runtime.mjs +172 -50
- package/extension/session-cleanup.ts +75 -21
- package/extension/session-store.ts +15 -3
- package/extension/tier-connection.ts +8 -1
- package/package.json +4 -3
- package/extension/vendor/pi-antigravity-acp-provider/LICENSE +0 -21
- package/extension/vendor/pi-antigravity-acp-provider/README.upstream.md +0 -144
- package/extension/vendor/pi-antigravity-acp-provider/package.json +0 -86
- package/extension/vendor/pi-antigravity-acp-provider/runtime-manifest.json +0 -205
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/antigravity.ts +0 -170
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/bounded-stream.ts +0 -148
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/connection.ts +0 -443
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/credential-storage.ts +0 -113
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/errors.ts +0 -42
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/events.ts +0 -66
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/headless-oauth.ts +0 -196
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/index.ts +0 -8
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/integrity.ts +0 -64
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/process.ts +0 -256
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/prompt-watchdog.ts +0 -80
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/proxy.ts +0 -54
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/runtime-manifest.ts +0 -183
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/session-state.ts +0 -76
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/session-store.ts +0 -88
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/setup.ts +0 -793
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/store-lock.ts +0 -24
- package/extension/vendor/pi-antigravity-acp-provider/src/acp/supervisor.mjs +0 -101
- package/extension/vendor/pi-antigravity-acp-provider/src/config.ts +0 -114
- package/extension/vendor/pi-antigravity-acp-provider/src/constants.ts +0 -10
- package/extension/vendor/pi-antigravity-acp-provider/src/index.ts +0 -8
- package/extension/vendor/pi-antigravity-acp-provider/src/mcp/bridge.ts +0 -217
- package/extension/vendor/pi-antigravity-acp-provider/src/mcp/schema.ts +0 -223
- package/extension/vendor/pi-antigravity-acp-provider/src/models.ts +0 -192
- package/extension/vendor/pi-antigravity-acp-provider/src/provider.ts +0 -149
- package/extension/vendor/pi-antigravity-acp-provider/src/runtime.ts +0 -1116
- package/extension/vendor/pi-antigravity-acp-provider/src/status.ts +0 -77
- package/extension/vendor/pi-antigravity-acp-provider/src/stream/context.ts +0 -249
- package/extension/vendor/pi-antigravity-acp-provider/src/stream/index.ts +0 -3
- package/extension/vendor/pi-antigravity-acp-provider/src/stream/json.ts +0 -17
- package/extension/vendor/pi-antigravity-acp-provider/src/stream/pi-events.ts +0 -141
- package/extension/vendor/pi-antigravity-acp-provider/src/stream/usage.ts +0 -37
- package/extension/vendor/pi-antigravity-acp-provider/src/wizard.ts +0 -83
- package/scripts/build.mjs +0 -436
package/README.md
CHANGED
|
@@ -165,6 +165,7 @@ After upgrading from an older adapter, run `/antigravity-acp refresh` once to re
|
|
|
165
165
|
| `/antigravity-acp cleanup` | Show cleanup mode/deadline and check eligible local sessions |
|
|
166
166
|
| `/antigravity-acp cleanup off` | Disable automatic session-file deletion |
|
|
167
167
|
| `/antigravity-acp cleanup conservative` | Delete confirmed replaced/disposable sessions only (default) |
|
|
168
|
+
| `/antigravity-acp cleanup balanced [DAYS]` | Keep recovery copies for 1 day, expire unmapped data after 7 days, and set soft 50-session/512-MiB defaults |
|
|
168
169
|
| `/antigravity-acp cleanup timeout DAYS` | Also delete inactive unmapped owned sessions after DAYS (default 7) |
|
|
169
170
|
| `/antigravity-acp cleanup budget MAX_SESSIONS MAX_MIB` | Set soft session-count/size budgets; `0` disables each limit |
|
|
170
171
|
| `/antigravity-acp diagnostics [on\|off\|reset]` | Show bounded timing samples, enable/disable collection, or clear samples (default off) |
|
|
@@ -224,6 +225,8 @@ New user requests supersede an interrupted ACP turn, including pending tool call
|
|
|
224
225
|
|
|
225
226
|
The cancellation checkpoint records the accepted message boundary and the partial assistant output fingerprint, including across idle shutdown/resume. If cancellation is unacknowledged, the process fails, the history is edited/compacted, or previously emitted partial output is missing or changed in OMP, the adapter reconstructs from retained history instead. Thus Esc does not always create a new ACP session, but reuse is conditional rather than guaranteed. Cancelled turns skip supplemental `/usage` queries while retaining any ACP context-occupancy update. History is explicitly separated from the current request after official ACP text conversion; cold tool handoffs resume from completed results rather than restarting prior actions. Preserving a session avoids unnecessary replay but does not guarantee a backend cache hit. See the [Flash cancellation/cache research and implementation checks](docs/cache-cancellation-research.md).
|
|
226
227
|
|
|
228
|
+
Routing uses the provider request's `sessionId`, independently of shared prompt-cache keys and the UI transcript ID. OMP's provider-state close/release hooks cover `/fresh`, reset and side-request lifetimes; old deferred requests cannot dispatch after closure, and replacement requests wait for teardown. Duplicate/ambiguous mappings are rebuilt, and a fresh Google login clears previous-account mappings. Concurrent identical input snapshots are rejected instead of dispatched twice; the same text in a distinct later user turn remains valid. Only tool names, descriptions and schemas enter ACP history fingerprints, excluding mutable OMP host objects. See the [source review and transition coverage](docs/session-transition-audit-2026-10-30.md). Run `npm run test:omp-sessions` for an isolated offline integration with the installed OMP CLI and a fake ACP transport; it creates no Google sessions and performs no inference.
|
|
229
|
+
|
|
227
230
|
The adapter transfers complete replay history within bounded budgets, including historical image attachments. It does not silently keep only a history tail. The official harness also has a per-step text conversion limit independent of its model window: the inspected configuration limits a step to 64,000 tokens and truncates oversized text to its first 192,000 UTF-8 bytes. A large cold replay after **Refine plan** can therefore lose the latest question at the tail even when the advertised model window has room. The adapter rejects rendered prompt text above 188,000 bytes before `session/prompt`, leaving 4,000 bytes for official wrapping/metadata. The context-overflow error lets OMP use its existing compaction/retry flow; OMP's adaptive summary windows can split oversized summary input too. If compaction is disabled or cannot reduce the request, use `/compact` or reduce the input before retrying. The adapter itself neither summarizes nor adds inference. See [step-limit behavior and offline validation](docs/plan-refinement-step-limit.md).
|
|
228
231
|
|
|
229
232
|
Token budgets, wire payload size and the per-step text limit are independent. The default wire payload limit is 16 MiB, configurable up to 128 MiB; raising it or `contextWindow` does not bypass the per-step text guard. Image data additionally defaults to an 8 MiB decoded payload limit and is not counted as rendered text. 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.
|
|
@@ -266,18 +269,20 @@ Active sessions are reused. After five idle minutes, the adapter closes its ACP
|
|
|
266
269
|
|
|
267
270
|
### Local ACP session cleanup
|
|
268
271
|
|
|
269
|
-
Session-file deletion is separate from the five-minute idle process shutdown. Configure one of
|
|
272
|
+
Session-file deletion is separate from the five-minute idle process shutdown. Configure one of four modes:
|
|
270
273
|
|
|
271
274
|
| Mode | Behavior |
|
|
272
275
|
| --- | --- |
|
|
273
276
|
| `off` | Keep session files, including replaced sessions. Ownership/lease bookkeeping remains enabled so cleanup can be enabled later. |
|
|
274
|
-
| `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. |
|
|
277
|
+
| `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 and explicitly released one-shot side requests are also removed after their connection exits. Ordinary shutdown and idle eviction preserve resumable sessions. |
|
|
278
|
+
| `balanced` | Keep unmapped replacement/one-shot copies for at least `recoveryDays` (default 1 day), including under quota pressure. Expire other unmapped owned data after `idleDays` (default 7 days) measured from the later of last use and first observation without a mapping. Above a soft budget, evict eligible unmapped data in activity order after the orphan grace (default 1 day). Saved OMP mappings, active sessions and OMP journals remain protected. |
|
|
275
279
|
| `timeout` | Conservative cleanup plus removal of unmapped owned sessions whose last activity exceeds `idleDays`, or eligible unmapped sessions above a configured soft budget after the orphan grace period. 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. Saved OMP mappings and live leases always override deletion. |
|
|
276
280
|
|
|
277
281
|
```text
|
|
278
282
|
/antigravity-acp cleanup
|
|
279
283
|
/antigravity-acp cleanup off
|
|
280
284
|
/antigravity-acp cleanup conservative
|
|
285
|
+
/antigravity-acp cleanup balanced
|
|
281
286
|
/antigravity-acp cleanup timeout 7
|
|
282
287
|
/antigravity-acp cleanup budget 50 512
|
|
283
288
|
```
|
|
@@ -288,15 +293,25 @@ Settings persist in `~/.omp/agent/antigravity-acp-provider/cleanup.json`:
|
|
|
288
293
|
{ "mode": "conservative", "idleDays": 7, "maxSessions": 0, "maxBytes": 0, "orphanGraceDays": 1, "batchSize": 8 }
|
|
289
294
|
```
|
|
290
295
|
|
|
291
|
-
The optional budgets default to disabled (`0`); the command accepts MiB and saves bytes.
|
|
296
|
+
The optional budgets default to disabled (`0`); the command accepts MiB and saves bytes. `cleanup balanced` sets missing budgets to 50 sessions and 512 MiB, resets ordinary orphan retention to 7 days (or the supplied DAYS), and supplies a 1-day orphan grace and recovery window. Existing explicit budgets, including disabled (`0`) limits, are preserved. The default remains `conservative`; installing an update does not switch an existing policy.
|
|
297
|
+
|
|
298
|
+
For example, the balanced preset without prior overrides saves:
|
|
299
|
+
|
|
300
|
+
```json
|
|
301
|
+
{ "mode": "balanced", "idleDays": 7, "maxSessions": 50, "maxBytes": 536870912, "orphanGraceDays": 1, "recoveryDays": 1 }
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Size accounting uses logical file sizes rather than allocated APFS space. In `off` and `conservative`, exceeding a budget only produces a status warning. In `timeout` and `balanced`, budget eviction uses least-recent activity among unmapped, unleased owned sessions after `orphanGraceDays` (default 1 day, range 1 hour–3650 days). Mapped and active sessions can keep usage above the budget. The balanced recovery window cannot be bypassed by either quota pressure or ordinary idle expiry; `recoveryDays` accepts 1 hour–3650 days. Explicitly deleted OMP journals retain their separate deletion-confirmation rules.
|
|
292
305
|
|
|
293
306
|
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. Replacement/release persists bookkeeping before scheduling file cleanup in the background. Each batch removes at most `batchSize` sessions (default 8, range 1–100); eligible overflow schedules another batch after one second. 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.
|
|
294
307
|
|
|
295
|
-
Only sessions created and registered by this adapter version onward are eligible. Pre-existing/unidentified ACP sessions are preserved. All cleanup modes protect IDs in saved `sessions.json` mappings. 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; the cross-process lease lock remains held during asynchronous deletion. Busy/corrupt registries, malformed mappings and unsafe paths defer deletion. Failed lifecycle updates remain in a bounded in-memory retry queue (1024 entries) until the next successful transaction; a process crash can lose queued intentions, so deletion is never guaranteed. The status shows mapped/unmapped/active counts, logical bytes, deferred work, failures and pending updates. 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.
|
|
308
|
+
Only sessions created and registered by this adapter version onward are eligible. Pre-existing/unidentified ACP sessions are preserved. All cleanup modes protect IDs in saved `sessions.json` mappings. 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; the cross-process lease lock remains held during asynchronous deletion. Busy/corrupt registries, malformed mappings and unsafe paths defer deletion. Failed lifecycle updates remain in a bounded in-memory retry queue (1024 entries) until the next successful transaction; a process crash can lose queued intentions, so deletion is never guaranteed. The status shows mapped/unmapped/active counts, logical bytes, bytes reclaimed in the latest batch, copies retained for recovery, deferred work, failures and pending updates. 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.
|
|
309
|
+
|
|
310
|
+
OMP explicitly releases routing IDs for final one-shot side requests. After runtime teardown, the adapter persists a disposable marker and conditionally removes only that request's matching owned mapping; newer, duplicated or shared mappings are preserved. A reused routing ID waits for this cleanup before dispatch. This also works after idle runtime eviction. If a process exits between marking and unmapping, later collection repairs the interruption; restoration refuses a finally released ACP ID. Generic provider close, process shutdown, switching sessions, and reusable side conversations do not mark their mappings disposable. Balanced mode retains the released ACP files as a temporary recovery copy; it does not add them to OMP history or expose a recovery UI.
|
|
296
311
|
|
|
297
312
|
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.
|
|
298
313
|
|
|
299
|
-
Timeout cleanup
|
|
314
|
+
Timeout and balanced cleanup sacrifice ACP-only reasoning/checkpoint state for eligible unmapped sessions. If that session is later requested through another history source, the adapter reconstructs it from OMP's retained history and can incur replay latency and a different token count. Cache expiry is not assumed or guaranteed. Ordinary mapped conversations remain resumable in every mode; budgets cannot bound the number of mapped OMP conversations you keep.
|
|
300
315
|
|
|
301
316
|
### Deleting an OMP conversation
|
|
302
317
|
|
|
@@ -317,7 +332,7 @@ Optional environment settings, applied when OMP starts:
|
|
|
317
332
|
| Setting | Default | Effect |
|
|
318
333
|
| --- | --- | --- |
|
|
319
334
|
| `OMP_ACP_HISTORY_BYTES` | context.json or 16 MiB | Optional byte-limit override, 64 KiB–128 MiB; independent of token window |
|
|
320
|
-
| `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it,
|
|
335
|
+
| `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it, otherwise `1000`–`2147483647` (Node timer range) |
|
|
321
336
|
| `OMP_ACP_MAX_IDLE_RUNTIMES` | `2` | Per-process idle runtime LRU limit; `0` disables the limit. Busy/leased runtimes remain protected |
|
|
322
337
|
| `OMP_ACP_USAGE` | context.json or auto | `off` forces supplemental queries off, including when the saved option is auto |
|
|
323
338
|
|
package/extension/auth-sync.ts
CHANGED
|
@@ -178,19 +178,42 @@ export class OmpAuthCoordinator {
|
|
|
178
178
|
// /login must mean a fresh Google sign-in: drop stored credentials (and this
|
|
179
179
|
// process's old-account servers) so a new server cannot silently reuse the
|
|
180
180
|
// saved login and keep the previous account.
|
|
181
|
+
noteLoginSucceeded(): void {
|
|
182
|
+
clearTimeout(this.followTimer);
|
|
183
|
+
this.followTimer = undefined;
|
|
184
|
+
clearTimeout(this.followRetry);
|
|
185
|
+
this.followRetry = undefined;
|
|
186
|
+
this.suppressFollow = false;
|
|
187
|
+
if (!this.apiKeyFallback) {
|
|
188
|
+
this.apiKeyFallback = true;
|
|
189
|
+
this.deps.onSyncProvider();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
181
193
|
async beginFreshGoogleLogin(): Promise<void> {
|
|
182
194
|
if (this.deps.isPoolBusy()) {
|
|
183
195
|
throw new Error("Wait for active Antigravity requests to finish before logging in.");
|
|
184
196
|
}
|
|
197
|
+
clearTimeout(this.followTimer);
|
|
198
|
+
this.followTimer = undefined;
|
|
199
|
+
clearTimeout(this.followRetry);
|
|
200
|
+
this.followRetry = undefined;
|
|
185
201
|
await this.deps.closeAllRuntimes();
|
|
202
|
+
// A different Google login must not restore the previous account's ACP
|
|
203
|
+
// mappings. OMP retains its transcript for a fresh backend reconstruction.
|
|
204
|
+
await this.deps.logoutAllRuntimes();
|
|
186
205
|
clearAntigravityCredentials();
|
|
187
|
-
|
|
206
|
+
await this.removeKeychainCredentialDurably();
|
|
188
207
|
}
|
|
189
208
|
|
|
190
209
|
async performCommandLogout(ctx: OmpCommandContext): Promise<{ keychainRemoved: boolean | undefined; ompMarker: "removed" | "absent" | "unavailable" }> {
|
|
191
210
|
if (this.deps.isPoolBusy()) {
|
|
192
211
|
throw new Error("Wait for active Antigravity requests to finish before logging out.");
|
|
193
212
|
}
|
|
213
|
+
clearTimeout(this.followTimer);
|
|
214
|
+
this.followTimer = undefined;
|
|
215
|
+
clearTimeout(this.followRetry);
|
|
216
|
+
this.followRetry = undefined;
|
|
194
217
|
await this.deps.logoutAllRuntimes();
|
|
195
218
|
await this.deps.closeAllRuntimes();
|
|
196
219
|
const keychainRemoved = await this.removeKeychainCredentialDurably();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import { writeJsonAtomic } from "./fs-atomic.ts";
|
|
3
|
-
import { resolveContextOptions, type
|
|
3
|
+
import { resolveContextOptions, type ContextSettings, type ResolvedContextOptions } from "./context-settings.ts";
|
|
4
4
|
import { EFFORTS, projectCatalog, readModels, type AdvertisedModel, type PublicCatalogModel } from "./model-catalog.ts";
|
|
5
5
|
import { officialApiCost } from "./pricing.ts";
|
|
6
6
|
import { advertisedRecord, choices, selector } from "./selectors.ts";
|
|
@@ -14,7 +14,8 @@ export interface ConfiguredCatalogModel extends PublicCatalogModel {
|
|
|
14
14
|
export class CatalogStore {
|
|
15
15
|
readonly upstreamModels = new Map<string, ConfiguredCatalogModel>();
|
|
16
16
|
currentModels: ConfiguredCatalogModel[] = [];
|
|
17
|
-
private
|
|
17
|
+
private sourceModels: PublicCatalogModel[] = [];
|
|
18
|
+
private dynamicCache?: { stamp?: string; settings: string; models: ConfiguredCatalogModel[] };
|
|
18
19
|
private discovery?: Promise<AdvertisedModel[]>;
|
|
19
20
|
private refreshing?: Promise<ConfiguredCatalogModel[]>;
|
|
20
21
|
private latestSettings?: ContextSettings;
|
|
@@ -27,8 +28,12 @@ export class CatalogStore {
|
|
|
27
28
|
) {}
|
|
28
29
|
|
|
29
30
|
projectWithSettings(models: PublicCatalogModel[], settings: ContextSettings): ConfiguredCatalogModel[] {
|
|
30
|
-
this.
|
|
31
|
-
this.
|
|
31
|
+
const projected = this.project(models, settings);
|
|
32
|
+
this.install(projected, models, settings);
|
|
33
|
+
return projected;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private project(models: PublicCatalogModel[], settings: ContextSettings): ConfiguredCatalogModel[] {
|
|
32
37
|
return models.map(source => {
|
|
33
38
|
const limits = resolveContextOptions(source, settings);
|
|
34
39
|
const model: ConfiguredCatalogModel = {
|
|
@@ -42,11 +47,21 @@ export class CatalogStore {
|
|
|
42
47
|
if (efforts.length && !model.thinking) {
|
|
43
48
|
model.thinking = { mode: "effort", efforts, defaultLevel: efforts.includes("high") ? "high" : efforts[0]! };
|
|
44
49
|
}
|
|
45
|
-
this.upstreamModels.set(model.id, model);
|
|
46
50
|
return model;
|
|
47
51
|
});
|
|
48
52
|
}
|
|
49
53
|
|
|
54
|
+
private install(models: ConfiguredCatalogModel[], sources: PublicCatalogModel[], settings: ContextSettings) {
|
|
55
|
+
// Publish only after every model validates. Preserve source limits so a
|
|
56
|
+
// removed override does not inherit the previous projected values.
|
|
57
|
+
this.sourceModels = sources;
|
|
58
|
+
this.latestSettings = settings;
|
|
59
|
+
this.currentModels = models;
|
|
60
|
+
this.dynamicCache = undefined;
|
|
61
|
+
this.upstreamModels.clear();
|
|
62
|
+
for (const model of models) this.upstreamModels.set(model.id, model);
|
|
63
|
+
}
|
|
64
|
+
|
|
50
65
|
readCachedCatalog(): AdvertisedModel[] {
|
|
51
66
|
try {
|
|
52
67
|
const cache = JSON.parse(fs.readFileSync(this.cachePath, "utf8")) as { schemaVersion?: unknown; models?: unknown };
|
|
@@ -65,27 +80,24 @@ export class CatalogStore {
|
|
|
65
80
|
// OMP's host may call fetchDynamicModels on every startup pass; stat-based
|
|
66
81
|
// reuse avoids re-reading and re-projecting an unchanged cache file.
|
|
67
82
|
getDynamicModels(settings: ContextSettings): ConfiguredCatalogModel[] {
|
|
83
|
+
let stamp: string | undefined;
|
|
68
84
|
try {
|
|
69
85
|
const stat = fs.statSync(this.cachePath);
|
|
70
|
-
|
|
71
|
-
this.dynamicCache.mtimeMs === stat.mtimeMs && this.dynamicCache.size === stat.size &&
|
|
72
|
-
this.dynamicCache.settings === settings) {
|
|
73
|
-
return this.dynamicCache.models;
|
|
74
|
-
}
|
|
86
|
+
stamp = `${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`;
|
|
75
87
|
} catch { /* Missing or unreadable cache: fall through to a fresh read. */ }
|
|
88
|
+
const settingsKey = JSON.stringify(settings);
|
|
89
|
+
if (this.dynamicCache && this.dynamicCache.stamp === stamp && this.dynamicCache.settings === settingsKey) {
|
|
90
|
+
return this.dynamicCache.models;
|
|
91
|
+
}
|
|
76
92
|
const cached = this.readCachedCatalog();
|
|
77
93
|
const base = cached.length ? projectCatalog(cached) : this.fallbackModels();
|
|
78
94
|
const models = this.projectWithSettings(base, settings);
|
|
79
|
-
|
|
80
|
-
const stat = fs.statSync(this.cachePath);
|
|
81
|
-
this.dynamicCache = { mtimeMs: stat.mtimeMs, size: stat.size, settings, models };
|
|
82
|
-
} catch { /* No cache file yet; nothing to key reuse on. */ }
|
|
95
|
+
this.dynamicCache = { stamp, settings: settingsKey, models };
|
|
83
96
|
return models;
|
|
84
97
|
}
|
|
85
98
|
|
|
86
99
|
reconfigure(settings: ContextSettings): ConfiguredCatalogModel[] {
|
|
87
|
-
|
|
88
|
-
return this.currentModels;
|
|
100
|
+
return this.projectWithSettings(this.sourceModels, settings);
|
|
89
101
|
}
|
|
90
102
|
|
|
91
103
|
async discoverModels(): Promise<AdvertisedModel[]> {
|
|
@@ -131,14 +143,15 @@ export class CatalogStore {
|
|
|
131
143
|
}
|
|
132
144
|
private async refreshOnce(): Promise<ConfiguredCatalogModel[]> {
|
|
133
145
|
const models = await this.discoverModels();
|
|
134
|
-
|
|
135
|
-
const
|
|
136
|
-
this.
|
|
146
|
+
const sources = projectCatalog(models);
|
|
147
|
+
const settings = this.latestSettings ?? { defaults: {}, models: {} };
|
|
148
|
+
const registered = this.project(sources, settings);
|
|
137
149
|
writeJsonAtomic(this.cachePath, {
|
|
138
150
|
schemaVersion: 2,
|
|
139
151
|
discoveredAt: new Date().toISOString(),
|
|
140
152
|
models,
|
|
141
153
|
});
|
|
154
|
+
this.install(registered, sources, settings);
|
|
142
155
|
return registered;
|
|
143
156
|
}
|
|
144
157
|
}
|
package/extension/commands.ts
CHANGED
|
@@ -105,8 +105,8 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
|
|
|
105
105
|
deps.cleanup.budget(Number(parts[2]), Number(parts[3]) * 1024 * 1024);
|
|
106
106
|
} else
|
|
107
107
|
if (value) {
|
|
108
|
-
if (!["off", "conservative", "timeout"].includes(value) || parts.length > 3 || (parts[2] !== undefined &&
|
|
109
|
-
throw new Error("Usage: /antigravity-acp cleanup [off|conservative|timeout [DAYS]]");
|
|
108
|
+
if (!["off", "conservative", "timeout", "balanced"].includes(value) || parts.length > 3 || (parts[2] !== undefined && !["timeout", "balanced"].includes(value))) {
|
|
109
|
+
throw new Error("Usage: /antigravity-acp cleanup [off|conservative|timeout|balanced [DAYS]]");
|
|
110
110
|
}
|
|
111
111
|
deps.cleanup.configure(value as CleanupMode, parts[2] === undefined ? undefined : Number(parts[2]));
|
|
112
112
|
deps.cleanup.start();
|
|
@@ -150,7 +150,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
|
|
|
150
150
|
}
|
|
151
151
|
|
|
152
152
|
if (command === "usage" && value) {
|
|
153
|
-
if (value !== "auto" && value !== "off") throw new Error("Usage: /antigravity-acp usage [auto|off]");
|
|
153
|
+
if (parts.length !== 2 || (value !== "auto" && value !== "off")) throw new Error("Usage: /antigravity-acp usage [auto|off]");
|
|
154
154
|
const next = updateContextSettings(deps.getContextSettings(), "default", "usageMode", value);
|
|
155
155
|
saveContextSettings(deps.contextPath, next);
|
|
156
156
|
deps.setContextSettings(next);
|
|
@@ -160,7 +160,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
|
|
|
160
160
|
}
|
|
161
161
|
|
|
162
162
|
if (command === "debug") {
|
|
163
|
-
if (value !== "on" && value !== "off") throw new Error("Usage: /antigravity-acp debug on|off");
|
|
163
|
+
if (parts.length !== 2 || (value !== "on" && value !== "off")) throw new Error("Usage: /antigravity-acp debug on|off");
|
|
164
164
|
const enabled = value === "on";
|
|
165
165
|
const next = { ...deps.getToolPolicy(), debugToolUpdates: enabled };
|
|
166
166
|
saveToolPolicy(deps.toolPolicyPath, next);
|
|
@@ -171,10 +171,11 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
|
|
|
171
171
|
}
|
|
172
172
|
|
|
173
173
|
if (command === "native-tools") {
|
|
174
|
+
if (parts.length !== 2) throw new Error("Usage: /antigravity-acp native-tools prefer|disabled");
|
|
174
175
|
const mode: NativeToolMode = parseNativeToolMode(value);
|
|
175
|
-
await deps.closeAllRuntimes();
|
|
176
176
|
const next = { ...deps.getToolPolicy(), nativeTools: mode };
|
|
177
177
|
saveToolPolicy(deps.toolPolicyPath, next);
|
|
178
|
+
await deps.closeAllRuntimes();
|
|
178
179
|
deps.setToolPolicy(next);
|
|
179
180
|
ctx.ui.notify(`Native tools: ${mode}. ACP connections will be recreated on the next request with the new policy.`, "info");
|
|
180
181
|
return;
|
|
@@ -204,6 +205,7 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
|
|
|
204
205
|
} finally {
|
|
205
206
|
lease.release();
|
|
206
207
|
}
|
|
208
|
+
deps.auth.noteLoginSucceeded?.();
|
|
207
209
|
const auth = inspectAntigravityAuth();
|
|
208
210
|
const email = antigravityAccountEmail();
|
|
209
211
|
ctx.ui.notify(`Antigravity Google login finished${email ? ` as ${email}` : ""} — fresh sign-in; ACP auth: ${auth.status}${auth.authType ? ` (${auth.authType})` : ""}.`, "info");
|
|
@@ -276,9 +278,9 @@ export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
|
|
|
276
278
|
throw new Error("Usage: /antigravity-acp permissions default|auto-edit|yolo");
|
|
277
279
|
}
|
|
278
280
|
const mode = value.replace("-", "_");
|
|
281
|
+
savePermissionMode(mode, deps.configPath);
|
|
279
282
|
deps.setPermissionModeState(mode);
|
|
280
283
|
await Promise.all(deps.getAllRuntimes().map(bundle => bundle.runtime.setPermissionMode(mode)));
|
|
281
|
-
savePermissionMode(mode, deps.configPath);
|
|
282
284
|
}
|
|
283
285
|
const usageError = "Usage: /antigravity-acp [status|account|login|logout|tools|usage|context|cleanup|diagnostics|debug|native-tools|permissions|refresh]";
|
|
284
286
|
if (command && command !== "status" && command !== "tools" && command !== "permissions") {
|
|
@@ -23,7 +23,7 @@ function validate(options: unknown, allowUsage: boolean): void {
|
|
|
23
23
|
if (value !== "auto" && value !== "off") throw new Error("usageMode must be auto or off");
|
|
24
24
|
continue;
|
|
25
25
|
}
|
|
26
|
-
const range = ranges[key as keyof ContextOptions];
|
|
26
|
+
const range = Object.hasOwn(ranges, key) ? ranges[key as keyof ContextOptions] : undefined;
|
|
27
27
|
if (!range || !Number.isSafeInteger(value) || (value as number) < range[0] || (value as number) > range[1]) {
|
|
28
28
|
throw new Error(`Invalid context setting ${key}${range ? `; expected ${range[0]}..${range[1]}` : ""}`);
|
|
29
29
|
}
|
|
@@ -54,7 +54,8 @@ export function saveContextSettings(file: string, settings: ContextSettings) {
|
|
|
54
54
|
export function updateContextSettings(settings: ContextSettings, target: string, key: string, value: number | string): ContextSettings {
|
|
55
55
|
if (["__proto__", "constructor", "prototype"].includes(target)) throw new Error("Invalid model ID");
|
|
56
56
|
const next = structuredClone(settings);
|
|
57
|
-
const options: Record<string, unknown> = target === "default" ? next.defaults
|
|
57
|
+
const options: Record<string, unknown> = target === "default" ? next.defaults
|
|
58
|
+
: Object.hasOwn(next.models, target) ? next.models[target]! : (next.models[target] = {});
|
|
58
59
|
options[key] = value;
|
|
59
60
|
validate(options, target === "default");
|
|
60
61
|
return next;
|
|
@@ -32,12 +32,33 @@ export interface TransferContext {
|
|
|
32
32
|
// otherwise a cold replay can silently lose its newest question at the tail.
|
|
33
33
|
export const ACP_STEP_TEXT_BYTES = 188_000;
|
|
34
34
|
|
|
35
|
+
function checkStepTextBytes(bytes: number): void {
|
|
36
|
+
if (bytes > ACP_STEP_TEXT_BYTES) {
|
|
37
|
+
throw new Error(`Maximum context length exceeded: official Antigravity ACP single-step text needs at least ${bytes} bytes; safe budget is ${ACP_STEP_TEXT_BYTES} bytes. Compact the conversation with OMP /compact and retry. A larger contextWindow or maxTransferBytes does not raise this server limit. No history or current request was sent or silently truncated.`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function serializeHistory(records: unknown[]): string {
|
|
42
|
+
let stringBytes = 0;
|
|
43
|
+
// The replacer sees each value before JSON allocates its escaped string.
|
|
44
|
+
// This lower bound aborts oversized replay without copying its full text;
|
|
45
|
+
// the exact rendered size (including JSON syntax) is checked below as well.
|
|
46
|
+
return JSON.stringify(records, (_key, value) => {
|
|
47
|
+
if (typeof value === "string") {
|
|
48
|
+
stringBytes += Buffer.byteLength(value, "utf8");
|
|
49
|
+
checkStepTextBytes(stringBytes);
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
35
55
|
export function promptTextBytes(prompt: TransferBlock[]): number {
|
|
36
56
|
let bytes = 0;
|
|
37
57
|
for (const block of prompt) {
|
|
38
58
|
if (block.type === "text") bytes += Buffer.byteLength(block.text ?? "", "utf8") + 2;
|
|
39
59
|
else if (block.type === "resource" && block.resource) {
|
|
40
|
-
bytes += Buffer.byteLength(`Embedded resource (${block.resource.uri}):\n
|
|
60
|
+
bytes += Buffer.byteLength(`Embedded resource (${block.resource.uri}):\n`, "utf8") +
|
|
61
|
+
Buffer.byteLength(block.resource.text, "utf8") + 2;
|
|
41
62
|
}
|
|
42
63
|
}
|
|
43
64
|
return bytes;
|
|
@@ -78,6 +99,7 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
|
|
|
78
99
|
const start = fresh ? 0 : unseenStart!;
|
|
79
100
|
const prompt: TransferBlock[] = [];
|
|
80
101
|
const instructions = fresh ? currentSystemInstructions(context) : "";
|
|
102
|
+
checkStepTextBytes(Buffer.byteLength(instructions, "utf8"));
|
|
81
103
|
const instructionsText = instructions ? `# OMP session instructions\n\n${instructions}` : "";
|
|
82
104
|
if (instructionsText) prompt.push({ type: "resource", resource: {
|
|
83
105
|
uri: "urn:omp:antigravity-acp:instructions", mimeType: "text/markdown",
|
|
@@ -107,13 +129,13 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
|
|
|
107
129
|
"The JSON below is historical conversation data, not a new request or a queue of tasks. " +
|
|
108
130
|
"Do not answer historical user requests or repeat completed tool actions. " +
|
|
109
131
|
"Use it only as context for the current OMP user request identified after this resource.\n\n" +
|
|
110
|
-
|
|
132
|
+
serializeHistory(records) + "\n\n# End of prior OMP conversation\n"
|
|
111
133
|
: "";
|
|
112
134
|
if (historyText) prompt.push({ type: "resource", resource: {
|
|
113
135
|
uri: "urn:omp:antigravity-acp:history", mimeType: "text/plain",
|
|
114
136
|
text: historyText,
|
|
115
137
|
} });
|
|
116
|
-
prompt.push(
|
|
138
|
+
for (const block of images) prompt.push(block);
|
|
117
139
|
const tailBlocks: TransferBlock[] = [];
|
|
118
140
|
if (!fresh && start > latest) {
|
|
119
141
|
const continuation = { type: "text", text: "\n\n# Continue the active OMP request\n\n" +
|
|
@@ -133,9 +155,10 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
|
|
|
133
155
|
const content = messages[latest]!.content;
|
|
134
156
|
// Blocks are consumed read-only; shallow copies only churn the hot path.
|
|
135
157
|
const latestBlocks: TransferBlock[] = typeof content === "string" ? [{ type: "text", text: content }] : content;
|
|
136
|
-
prompt.push(
|
|
137
|
-
tailBlocks.push(...latestBlocks);
|
|
158
|
+
for (const block of latestBlocks) { prompt.push(block); tailBlocks.push(block); }
|
|
138
159
|
}
|
|
160
|
+
// Reject oversized latest text before allocating its JSON wire copy too.
|
|
161
|
+
checkStepTextBytes(promptTextBytes(prompt));
|
|
139
162
|
// Image base64 size is not a text-token estimate. Bound its actual memory
|
|
140
163
|
// footprint separately, and reserve a conservative text-equivalent allowance.
|
|
141
164
|
let imageBytes = 0;
|
|
@@ -158,17 +181,13 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
|
|
|
158
181
|
const historyBytes = historyText ? Buffer.byteLength(historyText, "utf8") + 100 : 0;
|
|
159
182
|
const tailSerialized = JSON.stringify(tailTextOnly);
|
|
160
183
|
const tailBytes = Buffer.byteLength(tailSerialized, "utf8");
|
|
161
|
-
|
|
184
|
+
// Embedded history is JSON inside a resource string: its quotes and slashes
|
|
185
|
+
// are escaped again on the wire. Count actual envelopes/escaping without
|
|
186
|
+
// copying potentially large base64 data (ASCII with no JSON escaping).
|
|
187
|
+
const wireText = JSON.stringify(prompt.map(block => block.type === "image" ? { ...block, data: "" } : block));
|
|
188
|
+
const bytes = Buffer.byteLength(wireText, "utf8") + imageWireChars;
|
|
162
189
|
const budget = historyBudget(undefined, process.env, options.maxTransferBytes);
|
|
163
190
|
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.`);
|
|
164
|
-
const textBytes = promptTextBytes(prompt);
|
|
165
|
-
if (textBytes > ACP_STEP_TEXT_BYTES) {
|
|
166
|
-
// OMP recognizes this as context overflow, including inside its adaptive
|
|
167
|
-
// summary-window loop. Reject before session/prompt rather than letting the
|
|
168
|
-
// harness truncate and answer an older request. Never put request text in
|
|
169
|
-
// this error, and never let a user wire/window override disable this guard.
|
|
170
|
-
throw new Error(`Maximum context length exceeded: official Antigravity ACP single-step text needs ${textBytes} bytes; safe budget is ${ACP_STEP_TEXT_BYTES} bytes. Compact the conversation with OMP /compact and retry. A larger contextWindow or maxTransferBytes does not raise this server limit. No history or current request was sent or silently truncated.`);
|
|
171
|
-
}
|
|
172
191
|
const estimatedTokens =
|
|
173
192
|
(instructionsText ? estimateTransferTokens(instructionsText, 0, instructionsBytes - 108) : 0) +
|
|
174
193
|
(historyText ? estimateTransferTokens(historyText, 0, historyBytes - 100) : 0) +
|
package/extension/index.ts
CHANGED
|
@@ -8,6 +8,8 @@ import { SessionRuntimePool } from "./runtime-pool.ts";
|
|
|
8
8
|
import { createStructuredFingerprintMemo } from "./structured-fingerprint.ts";
|
|
9
9
|
import { Diagnostics, instrumentRuntime } from "./diagnostics.ts";
|
|
10
10
|
import { stableTools } from "./tool-order.ts";
|
|
11
|
+
import { toolDeclarations, normalizeOmpSystemDeltas, type OmpToolDeclaration } from "./omp-context.ts";
|
|
12
|
+
import { OmpSessionLifecycle, type OmpProviderSessionState } from "./omp-session-lifecycle.ts";
|
|
11
13
|
import { loadContextSettings } from "./context-settings.ts";
|
|
12
14
|
import { selectRuntimeModel, type PublicCatalogModel } from "./model-catalog.ts";
|
|
13
15
|
import { TOOL_ROUTING } from "./tool-routing.ts";
|
|
@@ -63,7 +65,8 @@ export default async function (pi: OmpHostApi) {
|
|
|
63
65
|
}
|
|
64
66
|
|
|
65
67
|
// Explicit state injection keeps command integration tests away from user data.
|
|
66
|
-
export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string
|
|
68
|
+
export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
|
|
69
|
+
createConnection = (options: ConstructorParameters<typeof TierConnection>[0]): TierConnection => new TierConnection(options)) {
|
|
67
70
|
const configPath = path.join(stateDir, "config.json");
|
|
68
71
|
const cachePath = path.join(stateDir, "models-cache.json");
|
|
69
72
|
const toolPolicyPath = path.join(stateDir, "omp-tools.json");
|
|
@@ -98,8 +101,8 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
98
101
|
|
|
99
102
|
const connections = new Set<TierConnection>();
|
|
100
103
|
const idleTimeoutMs = Number(process.env.OMP_ACP_IDLE_TIMEOUT_MS ?? 300_000);
|
|
101
|
-
if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 0 || (idleTimeoutMs > 0 && idleTimeoutMs < 1000)) {
|
|
102
|
-
throw new Error("OMP_ACP_IDLE_TIMEOUT_MS must be 0 (disabled) or an integer
|
|
104
|
+
if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 0 || idleTimeoutMs > 2_147_483_647 || (idleTimeoutMs > 0 && idleTimeoutMs < 1000)) {
|
|
105
|
+
throw new Error("OMP_ACP_IDLE_TIMEOUT_MS must be 0 (disabled) or an integer between 1000 and 2147483647");
|
|
103
106
|
}
|
|
104
107
|
const maxIdleEntries = Number(process.env.OMP_ACP_MAX_IDLE_RUNTIMES ?? 2);
|
|
105
108
|
if (!Number.isSafeInteger(maxIdleEntries) || maxIdleEntries < 0) throw new Error("OMP_ACP_MAX_IDLE_RUNTIMES must be a nonnegative integer (0 disables the cap)");
|
|
@@ -109,15 +112,18 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
109
112
|
let lastToolAudit: ToolAuditSummary | undefined;
|
|
110
113
|
let cachedToolProjection: {
|
|
111
114
|
revision: string;
|
|
112
|
-
tools:
|
|
115
|
+
tools: OmpToolDeclaration[];
|
|
113
116
|
availableNames: string;
|
|
114
117
|
audit: ToolAuditSummary;
|
|
115
118
|
} | undefined;
|
|
116
119
|
|
|
120
|
+
const lifecycle = new OmpSessionLifecycle(id => runtimes.close(id), async id => {
|
|
121
|
+
if (id) await cleanup.releaseSession(id);
|
|
122
|
+
});
|
|
117
123
|
const runtimes = new SessionRuntimePool<RuntimeBundleView>(() => {
|
|
118
124
|
const ownedConnections = new Set<TierConnection>();
|
|
119
125
|
const runtime = new AntigravityRuntime((options: ConstructorParameters<typeof TierConnection>[0]) => {
|
|
120
|
-
const connection =
|
|
126
|
+
const connection = createConnection({
|
|
121
127
|
...options,
|
|
122
128
|
ompNativeTools: toolPolicy.nativeTools,
|
|
123
129
|
ompDebugToolUpdates: toolPolicy.debugToolUpdates,
|
|
@@ -139,15 +145,18 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
139
145
|
provider: createAntigravityProvider(runtime).provider,
|
|
140
146
|
isBusy: () => [...ownedConnections].some(connection => connection.activePrompts > 0),
|
|
141
147
|
};
|
|
142
|
-
}, bundle =>
|
|
148
|
+
}, (bundle, id) => lifecycle.disposeRuntime(id, bundle, () => bundle.runtime.close()),
|
|
149
|
+
{ timeoutMs: idleTimeoutMs, maxIdleEntries, canDispose: bundle => !bundle.isBusy() });
|
|
150
|
+
|
|
151
|
+
async function closePool() { await lifecycle.closeAll(); await runtimes.closeAll(); }
|
|
143
152
|
|
|
144
153
|
const sessionIdOf = (ctx: OmpCommandContext | undefined): string | undefined => ctx?.sessionManager?.getSessionId?.();
|
|
145
154
|
pi.on("session_shutdown", async (_event: unknown, ctx: OmpCommandContext) => {
|
|
146
155
|
const sessionId = sessionIdOf(ctx);
|
|
147
156
|
if (sessionId) {
|
|
148
|
-
await Promise.all([
|
|
157
|
+
await Promise.all([lifecycle.closeSession(sessionId), lifecycle.waitClosing(), runtimes.closeIdle()]);
|
|
149
158
|
} else {
|
|
150
|
-
await
|
|
159
|
+
await closePool();
|
|
151
160
|
}
|
|
152
161
|
await sessionStore.flush();
|
|
153
162
|
if (!runtimes.values().length) await cleanup.stop();
|
|
@@ -172,7 +181,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
172
181
|
await sessionStore.clear();
|
|
173
182
|
clearAntigravityCredentials();
|
|
174
183
|
},
|
|
175
|
-
closeAllRuntimes:
|
|
184
|
+
closeAllRuntimes: closePool,
|
|
176
185
|
onSyncProvider: syncProviderRegistration,
|
|
177
186
|
});
|
|
178
187
|
|
|
@@ -236,7 +245,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
236
245
|
getSavedSessionCount: savedSessionCount,
|
|
237
246
|
getPermissionMode: () => permissionMode,
|
|
238
247
|
getAllRuntimes: () => runtimes.values(),
|
|
239
|
-
closeAllRuntimes:
|
|
248
|
+
closeAllRuntimes: closePool,
|
|
240
249
|
onModelsUpdated: models => {
|
|
241
250
|
initialModels = models;
|
|
242
251
|
adapted.registerProvider();
|
|
@@ -266,11 +275,11 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
266
275
|
},
|
|
267
276
|
streamSimple(
|
|
268
277
|
model: { id: string },
|
|
269
|
-
context: { tools?:
|
|
270
|
-
options?: { sessionId?: string; reasoning?: string; signal?: AbortSignal },
|
|
278
|
+
context: { tools?: OmpToolDeclaration[]; systemPrompt?: string | string[]; messages: unknown[] },
|
|
279
|
+
options?: { sessionId?: string; reasoning?: string; signal?: AbortSignal; providerSessionState?: Map<string, OmpProviderSessionState> },
|
|
271
280
|
) {
|
|
272
|
-
const inputTools = context.tools ?? [];
|
|
273
|
-
let tools:
|
|
281
|
+
const inputTools = toolDeclarations(context.tools ?? []);
|
|
282
|
+
let tools: OmpToolDeclaration[];
|
|
274
283
|
let availableNames: string;
|
|
275
284
|
const cached = cachedToolProjection;
|
|
276
285
|
const revision = toolProjectionMemo(inputTools, () => String(++toolRevision));
|
|
@@ -298,7 +307,8 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
298
307
|
const routedContext = {
|
|
299
308
|
...context,
|
|
300
309
|
tools,
|
|
301
|
-
|
|
310
|
+
messages: normalizeOmpSystemDeltas(context.messages),
|
|
311
|
+
systemPrompt: `${Array.isArray(context.systemPrompt) ? context.systemPrompt.join("\n\n") : context.systemPrompt ?? ""}\n\n${TOOL_ROUTING}\nOMP tool names: ${availableNames}`,
|
|
302
312
|
};
|
|
303
313
|
if (process.env.OMP_ACP_TRACE === "1") {
|
|
304
314
|
console.error("[ACP tools]", JSON.stringify(lastToolAudit));
|
|
@@ -306,17 +316,21 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
306
316
|
// OMP needs a stream synchronously. Defer runtime setup behind it so
|
|
307
317
|
// loading/selecting/listing models performs no ACP process activity.
|
|
308
318
|
const deferred = new PiEventWriter(model);
|
|
319
|
+
const ticket = lifecycle.capture(options?.sessionId, options?.providerSessionState);
|
|
309
320
|
void (async () => {
|
|
310
321
|
try {
|
|
311
322
|
if (options?.signal?.aborted) throw new Error("ACP request cancelled before startup");
|
|
323
|
+
await lifecycle.ready(ticket);
|
|
312
324
|
await diagnostics.measure("runtime.prepare", prepareRuntime);
|
|
313
325
|
if (options?.signal?.aborted) throw new Error("ACP request cancelled during startup");
|
|
314
326
|
if (!catalogStore.upstreamModels.has(model.id)) await catalogStore.refresh(contextSettings);
|
|
315
327
|
const original = catalogStore.upstreamModels.get(model.id);
|
|
316
328
|
if (!original) throw new Error(`Antigravity model was not discovered: ${model.id}. Run /antigravity-acp refresh.`);
|
|
329
|
+
await lifecycle.ready(ticket);
|
|
317
330
|
const lease = runtimes.acquire(options?.sessionId);
|
|
318
331
|
const { runtime, provider } = lease.value;
|
|
319
332
|
try {
|
|
333
|
+
lifecycle.attach(ticket, lease.value);
|
|
320
334
|
const stream = provider.streamSimple(selectRuntimeModel(original, options?.reasoning), routedContext, options);
|
|
321
335
|
for await (const event of stream) {
|
|
322
336
|
const message = event.message ?? event.partial;
|
|
@@ -331,7 +345,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
331
345
|
} finally { lease.release(); }
|
|
332
346
|
} catch (error) {
|
|
333
347
|
deferred.fail(error, options?.signal?.aborted === true);
|
|
334
|
-
}
|
|
348
|
+
} finally { lifecycle.finish(ticket); }
|
|
335
349
|
})();
|
|
336
350
|
return deferred.stream;
|
|
337
351
|
},
|
|
@@ -358,6 +372,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string) {
|
|
|
358
372
|
},
|
|
359
373
|
prompt: (request: { message: string; placeholder?: string }) => callbacks.onPrompt({ message: request.message, placeholder: request.placeholder }),
|
|
360
374
|
});
|
|
375
|
+
auth.noteLoginSucceeded();
|
|
361
376
|
// Record the signed-in account on the marker credential so OMP's
|
|
362
377
|
// account list can label it; the email is identity data, not a secret.
|
|
363
378
|
const email = antigravityAccountEmail();
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface OmpToolDeclaration { name: string; description?: string; parameters?: unknown }
|
|
2
|
+
|
|
3
|
+
// OMP tools may be live AgentTool wrappers containing the entire session host,
|
|
4
|
+
// counters, executable closures and cycles. ACP bridges declarations only;
|
|
5
|
+
// tool execution still returns through OMP's own tool loop.
|
|
6
|
+
export function toolDeclarations(tools: readonly OmpToolDeclaration[]): OmpToolDeclaration[] {
|
|
7
|
+
return tools.map(tool => ({ name: tool.name, description: tool.description, parameters: tool.parameters }));
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function normalizeOmpSystemDeltas(messages: unknown[]): unknown[] {
|
|
11
|
+
return messages.map(message => {
|
|
12
|
+
if (!message || typeof message !== "object" || !("role" in message) || message.role !== "system") return message;
|
|
13
|
+
const system = message as { toolsAdded?: OmpToolDeclaration[]; toolsRemoved?: Array<{ name: string }> };
|
|
14
|
+
return { ...message,
|
|
15
|
+
...(system.toolsAdded ? { toolsAdded: toolDeclarations(system.toolsAdded) } : {}),
|
|
16
|
+
...(system.toolsRemoved ? { toolsRemoved: system.toolsRemoved.map(tool => ({ name: tool.name })) } : {}),
|
|
17
|
+
};
|
|
18
|
+
});
|
|
19
|
+
}
|