omp-antigravity-acp-provider 0.1.28 → 0.1.29
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 +4 -2
- package/extension/efforts.ts +10 -0
- package/extension/model-catalog.ts +3 -7
- package/extension/omp-session-lifecycle.ts +5 -1
- package/extension/omp-session-source.ts +17 -4
- package/extension/pricing.ts +3 -1
- package/extension/runtime.mjs +173 -37
- package/extension/session-cleanup.ts +46 -23
- package/extension/tier-connection.ts +51 -2
- package/extension/turn-cancellation.ts +128 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -221,7 +221,7 @@ Session mappings use asynchronous file I/O and nonblocking cross-process lock re
|
|
|
221
221
|
|
|
222
222
|
History comparisons reuse SHA-256 digests for unchanged large, simple messages. Every lookup validates the selected live fields against an independent snapshot, including nested tool arguments and in-place text edits; object identity alone never establishes a match. Small messages (below 2,048 characters per text/image/thinking string), complex payloads and unsupported objects use the original algorithm. The digest format and all checks after asynchronous work remain unchanged, so saved sessions stay compatible. Weak keys allow snapshots to be reclaimed when OMP drops old messages, including after compaction. This reduces local comparison work; it does not increase Google's cache-hit rate or guarantee faster model generation. See the [offline benchmarks and memory measurements](docs/history-comparison-research.md#production-integration).
|
|
223
223
|
|
|
224
|
-
New user requests supersede an interrupted ACP turn, including pending tool calls and permission prompts. The adapter cancels old waits and sends official `session/cancel`, then waits up to the existing 1.5-second cancellation deadline for the old turn to settle. A confirmed cancellation (or a clean completion racing with cancellation) keeps the warm ACP session when the transport is alive and the retained OMP history matches. New prompts queue behind that drain and are sent as new requests, never silently treated as old tool-result continuations. Ordinary completed turns and genuine tool continuations also stay warm. Tool/permission continuations claim one owner before asynchronous work; overlapping duplicates receive an explicit error instead of stealing the response stream. Changed or missing completed assistant output forces reconstruction so the backend and OMP-visible histories agree.
|
|
224
|
+
New user requests supersede an interrupted ACP turn, including pending tool calls and permission prompts. The adapter cancels old waits and sends official `session/cancel`, then waits up to the existing 1.5-second cancellation deadline for the old turn to settle. A confirmed cancellation (or a clean completion racing with cancellation) keeps the warm ACP session when the transport is alive and the retained OMP history matches. When the server replies that `session/cancel` is not implemented (verified against `agy_acp_server` 1.4.3: `-32601`), the adapter instead holds the caller's abort and waits for the old turn to end naturally, keeping the transport open, freezing `agent_message_chunk`/thought/tool/plan updates so retained partial output stays consistent, and checkpointing the same warm session once the turn ends. This steering grace is activity-aware: every update from the draining turn — thinking chunks, output or tool activity — extends the wait, so long thinking or tool loops do not expire it; only a silent gap beyond `OMP_ACP_STEER_GRACE_MS` (default 60 seconds, `0` restores the legacy immediate rebuild) or the absolute `OMP_ACP_STEER_GRACE_MAX_MS` cap (default 5 minutes, `0` = uncapped) falls back to cold reconstruction. The vendored progress watchdog (10 minutes silent / 60 minutes busy) remains the outer safety net. New prompts queue behind that drain and are sent as new requests, never silently treated as old tool-result continuations. Ordinary completed turns and genuine tool continuations also stay warm. Tool/permission continuations claim one owner before asynchronous work; overlapping duplicates receive an explicit error instead of stealing the response stream. Changed or missing completed assistant output forces reconstruction so the backend and OMP-visible histories agree.
|
|
225
225
|
|
|
226
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).
|
|
227
227
|
|
|
@@ -275,7 +275,7 @@ Session-file deletion is separate from the five-minute idle process shutdown. Co
|
|
|
275
275
|
| --- | --- |
|
|
276
276
|
| `off` | Keep session files, including replaced sessions. Ownership/lease bookkeeping remains enabled so cleanup can be enabled later. |
|
|
277
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
|
|
278
|
+
| `balanced` | Keep unmapped replacement/one-shot copies for at least `recoveryDays` (default 1 day), including under quota pressure. Expire other unmapped owned data, and mapped conversations whose last activity exceeds `idleDays` (default 7 days), measured from the later of last use and first observation without a mapping. A reclaimed mapping is removed before its files, and the next turn rebuilds the conversation from OMP history. Above a soft budget, evict eligible unmapped data in activity order after the orphan grace (default 1 day). Active sessions, live leases, ambiguous mappings and OMP journals remain protected. |
|
|
279
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. |
|
|
280
280
|
|
|
281
281
|
```text
|
|
@@ -335,6 +335,8 @@ Optional environment settings, applied when OMP starts:
|
|
|
335
335
|
| `OMP_ACP_IDLE_TIMEOUT_MS` | `300000` | Idle runtime reclamation; `0` disables it, otherwise `1000`–`2147483647` (Node timer range) |
|
|
336
336
|
| `OMP_ACP_MAX_IDLE_RUNTIMES` | `2` | Per-process idle runtime LRU limit; `0` disables the limit. Busy/leased runtimes remain protected |
|
|
337
337
|
| `OMP_ACP_USAGE` | context.json or auto | `off` forces supplemental queries off, including when the saved option is auto |
|
|
338
|
+
| `OMP_ACP_STEER_GRACE_MS` | `60000` | Steering grace when `session/cancel` is unimplemented: max silent gap while waiting for the old turn, `0`–`600000`; `0` rebuilds immediately |
|
|
339
|
+
| `OMP_ACP_STEER_GRACE_MAX_MS` | `300000` | Absolute cap on one steering wait however active the turn; `0` = uncapped, otherwise `100`–`3600000` |
|
|
338
340
|
|
|
339
341
|
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.
|
|
340
342
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Single source for the "<base>-<effort>" advertised ID suffix. Both the
|
|
2
|
+
// catalog projection and API cost lookup must agree, or pricing silently
|
|
3
|
+
// misses the variants the catalog advertises.
|
|
4
|
+
export const EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
5
|
+
export const LEGACY_EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORTS.join("|")})$`);
|
|
6
|
+
|
|
7
|
+
export function splitLegacyEffort(modelId: string): { base: string; effort: string } | undefined {
|
|
8
|
+
const match = modelId.match(LEGACY_EFFORT_SUFFIX);
|
|
9
|
+
return match ? { base: match[1]!, effort: match[2]! } : undefined;
|
|
10
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Public OMP models are derived only from server-advertised IDs and choices.
|
|
2
|
-
|
|
2
|
+
import { EFFORTS, splitLegacyEffort } from "./efforts.ts";
|
|
3
|
+
export { EFFORTS, splitLegacyEffort };
|
|
3
4
|
export interface AdvertisedModel {
|
|
4
5
|
modelId: string;
|
|
5
6
|
name: string;
|
|
@@ -22,12 +23,7 @@ export interface PublicCatalogModel {
|
|
|
22
23
|
thinking?: { mode: "effort"; efforts: string[]; defaultLevel?: string };
|
|
23
24
|
}
|
|
24
25
|
const ROUTE_PREFIX = "__omp_acp_thought__:";
|
|
25
|
-
//
|
|
26
|
-
const LEGACY_EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORTS.join("|")})$`);
|
|
27
|
-
export function splitLegacyEffort(modelId: string): { base: string; effort: string } | undefined {
|
|
28
|
-
const match = modelId.match(LEGACY_EFFORT_SUFFIX);
|
|
29
|
-
return match ? { base: match[1]!, effort: match[2]! } : undefined;
|
|
30
|
-
}
|
|
26
|
+
// The legacy "<base>-<effort>" suffix lives in efforts.ts so pricing agrees.
|
|
31
27
|
export function validId(value: unknown): value is string {
|
|
32
28
|
return typeof value === "string" && value.length > 0 && value.length <= 256 &&
|
|
33
29
|
value === value.trim() && !/[\u0000-\u001f\u007f]/u.test(value);
|
|
@@ -115,8 +115,12 @@ export class OmpSessionLifecycle {
|
|
|
115
115
|
closeSession(id: RoutingId, released = false): Promise<void> {
|
|
116
116
|
for (const ticket of [...this.tickets.get(id) ?? []]) { ticket.closed = true; ticket.scope.retainedIds.delete(id); this.forget(ticket); }
|
|
117
117
|
const previous = this.closing.get(id), closed = this.closeRuntime(id), teardown = this.closing.get(id);
|
|
118
|
-
const pending = Promise.
|
|
118
|
+
const pending = Promise.allSettled([previous, closed, teardown]).then(async results => {
|
|
119
|
+
// Teardown failures must not skip unbinding: a leaked release keeps the
|
|
120
|
+
// one-shot mapping alive and the cleanup registry out of sync.
|
|
119
121
|
if (released) await this.releaseRuntime(id);
|
|
122
|
+
const failure = results.find((result): result is PromiseRejectedResult => result.status === "rejected");
|
|
123
|
+
if (failure) throw failure.reason;
|
|
120
124
|
});
|
|
121
125
|
// Reusing an ID must also wait for removal of its prior one-shot mapping.
|
|
122
126
|
this.closing.set(id, pending);
|
|
@@ -36,11 +36,18 @@ export async function sourceId(file: string): Promise<string> {
|
|
|
36
36
|
} finally { await handle.close(); }
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
export interface OmpSourceScan {
|
|
40
|
+
sources: Map<string, string>;
|
|
41
|
+
// False when some journal header could not be read. Absence then proves
|
|
42
|
+
// nothing: the missing session may live in a file this scan could not parse.
|
|
43
|
+
complete: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
39
46
|
// Missing files may have moved between workspace buckets. Search only the
|
|
40
47
|
// known managed root, with bounded work and no symlinks; any ambiguity preserves
|
|
41
48
|
// the ACP session. Called only after a tracked file disappears.
|
|
42
|
-
export async function findSources(root: string): Promise<
|
|
43
|
-
let entries = 0;
|
|
49
|
+
export async function findSources(root: string): Promise<OmpSourceScan> {
|
|
50
|
+
let entries = 0, complete = true;
|
|
44
51
|
const sources = new Map<string, string>();
|
|
45
52
|
async function visit(dir: string, depth: number): Promise<void> {
|
|
46
53
|
if (depth > 4) throw new Error("OMP source scan depth exceeded");
|
|
@@ -52,9 +59,15 @@ export async function findSources(root: string): Promise<Map<string, string>> {
|
|
|
52
59
|
// Only journal buckets, not the adjacent per-session artifact trees.
|
|
53
60
|
if (/^\d{4}-\d\d-\d\d.*_[\da-f-]+$/i.test(item.name)) continue;
|
|
54
61
|
await visit(file, depth + 1);
|
|
55
|
-
} else if (item.isFile() && item.name.endsWith(".jsonl"))
|
|
62
|
+
} else if (item.isFile() && item.name.endsWith(".jsonl")) {
|
|
63
|
+
// A crashed writer can leave an empty or truncated journal. That file
|
|
64
|
+
// proves nothing about its own session, but it must not blind the scan
|
|
65
|
+
// for every other one, so it only marks the scan incomplete.
|
|
66
|
+
try { sources.set(await sourceId(file), file); }
|
|
67
|
+
catch { complete = false; }
|
|
68
|
+
}
|
|
56
69
|
}
|
|
57
70
|
}
|
|
58
71
|
await visit(root, 0);
|
|
59
|
-
return sources;
|
|
72
|
+
return { sources, complete };
|
|
60
73
|
}
|
package/extension/pricing.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { splitLegacyEffort } from "./efforts.ts";
|
|
2
|
+
|
|
1
3
|
// USD per 1M tokens, Gemini Developer API Standard tier.
|
|
2
4
|
// Source: https://ai.google.dev/gemini-api/docs/pricing (checked 2026-10-19).
|
|
3
5
|
// These are API-equivalent estimates, not Antigravity subscription charges.
|
|
4
6
|
export function officialApiCost(modelId: string, at = Date.now()) {
|
|
5
|
-
const id = modelId
|
|
7
|
+
const id = splitLegacyEffort(modelId)?.base ?? modelId;
|
|
6
8
|
if (id === "gemini-4-argon") {
|
|
7
9
|
// Use the undiscounted list price, ignoring introductory rates.
|
|
8
10
|
return { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 0 };
|
package/extension/runtime.mjs
CHANGED
|
@@ -19259,22 +19259,97 @@ async function claimContinuation(binding, work, invalidate) {
|
|
|
19259
19259
|
}
|
|
19260
19260
|
|
|
19261
19261
|
// extension/turn-cancellation.ts
|
|
19262
|
-
|
|
19262
|
+
function steerTimings(env2 = process.env) {
|
|
19263
|
+
const idleMs = Number(env2.OMP_ACP_STEER_GRACE_MS ?? 6e4);
|
|
19264
|
+
if (!Number.isSafeInteger(idleMs) || idleMs < 0 || idleMs > 6e5) {
|
|
19265
|
+
throw new Error("OMP_ACP_STEER_GRACE_MS must be an integer between 0 and 600000");
|
|
19266
|
+
}
|
|
19267
|
+
const maxMs = Number(env2.OMP_ACP_STEER_GRACE_MAX_MS ?? 3e5);
|
|
19268
|
+
if (!Number.isSafeInteger(maxMs) || maxMs < 0 || maxMs > 36e5 || maxMs > 0 && maxMs < 100) {
|
|
19269
|
+
throw new Error("OMP_ACP_STEER_GRACE_MAX_MS must be 0 or an integer between 100 and 3600000");
|
|
19270
|
+
}
|
|
19271
|
+
return { idleMs, maxMs };
|
|
19272
|
+
}
|
|
19273
|
+
function isCancelUnsupported(error62) {
|
|
19274
|
+
if (!error62 || typeof error62 !== "object") return false;
|
|
19275
|
+
const code = error62.code;
|
|
19276
|
+
if (code === -32601) return true;
|
|
19277
|
+
const message = error62.message;
|
|
19278
|
+
return typeof message === "string" && /method not found/i.test(message);
|
|
19279
|
+
}
|
|
19280
|
+
function armSteerGiveup(source, sessionId, timings, fire) {
|
|
19281
|
+
const startedAt = Date.now();
|
|
19282
|
+
let lastActivity = startedAt;
|
|
19283
|
+
let timer;
|
|
19284
|
+
let done = false;
|
|
19285
|
+
const schedule = () => {
|
|
19286
|
+
if (done) return;
|
|
19287
|
+
clearTimeout(timer);
|
|
19288
|
+
const silenceDeadline = lastActivity + timings.idleMs;
|
|
19289
|
+
const hardDeadline = timings.maxMs > 0 ? startedAt + timings.maxMs : Number.POSITIVE_INFINITY;
|
|
19290
|
+
timer = setTimeout(() => {
|
|
19291
|
+
if (done) return;
|
|
19292
|
+
done = true;
|
|
19293
|
+
detach?.();
|
|
19294
|
+
fire();
|
|
19295
|
+
}, Math.max(0, Math.min(silenceDeadline, hardDeadline) - Date.now()));
|
|
19296
|
+
};
|
|
19297
|
+
const detach = source?.onSteerActivity?.(sessionId, () => {
|
|
19298
|
+
lastActivity = Date.now();
|
|
19299
|
+
schedule();
|
|
19300
|
+
});
|
|
19301
|
+
schedule();
|
|
19302
|
+
return { dispose: () => {
|
|
19303
|
+
done = true;
|
|
19304
|
+
clearTimeout(timer);
|
|
19305
|
+
detach?.();
|
|
19306
|
+
} };
|
|
19307
|
+
}
|
|
19308
|
+
function deferredAbortSignal(signal, timings, activity) {
|
|
19309
|
+
if (!(timings.idleMs > 0)) return { signal, dispose: () => void 0 };
|
|
19310
|
+
const controller = new AbortController();
|
|
19311
|
+
let giveup;
|
|
19312
|
+
const onAbort = () => {
|
|
19313
|
+
if (giveup) return;
|
|
19314
|
+
giveup = armSteerGiveup(activity?.source, activity?.sessionId, timings, () => controller.abort(signal.reason));
|
|
19315
|
+
};
|
|
19316
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
19317
|
+
if (signal.aborted) onAbort();
|
|
19318
|
+
return {
|
|
19319
|
+
signal: controller.signal,
|
|
19320
|
+
dispose: () => {
|
|
19321
|
+
giveup?.dispose();
|
|
19322
|
+
signal.removeEventListener("abort", onAbort);
|
|
19323
|
+
}
|
|
19324
|
+
};
|
|
19325
|
+
}
|
|
19326
|
+
async function drainCancelledTurn(binding, abort, signal, timeoutMs = 1500, timings = steerTimings()) {
|
|
19263
19327
|
const completion = binding.turnCompletion;
|
|
19264
19328
|
if (!completion || signal?.aborted) return false;
|
|
19265
19329
|
const deadline = Promise.withResolvers();
|
|
19266
19330
|
const cancelled = () => deadline.resolve(false);
|
|
19267
|
-
|
|
19331
|
+
let timer = setTimeout(cancelled, timeoutMs);
|
|
19332
|
+
let giveup;
|
|
19268
19333
|
signal?.addEventListener("abort", cancelled, { once: true });
|
|
19334
|
+
const extendForNaturalCompletion = () => {
|
|
19335
|
+
binding.connection.muteSteerChunks?.(binding.session.sessionId);
|
|
19336
|
+
clearTimeout(timer);
|
|
19337
|
+
giveup = armSteerGiveup(binding.connection, binding.session.sessionId, timings, cancelled);
|
|
19338
|
+
};
|
|
19269
19339
|
try {
|
|
19270
19340
|
abort();
|
|
19271
19341
|
try {
|
|
19272
|
-
void binding.connection.cancel(binding.session.sessionId).catch(() =>
|
|
19273
|
-
|
|
19274
|
-
|
|
19342
|
+
void binding.connection.cancel(binding.session.sessionId).catch((error62) => {
|
|
19343
|
+
if (timings.idleMs > 0 && isCancelUnsupported(error62)) extendForNaturalCompletion();
|
|
19344
|
+
else deadline.resolve(false);
|
|
19345
|
+
});
|
|
19346
|
+
} catch (error62) {
|
|
19347
|
+
if (timings.idleMs > 0 && isCancelUnsupported(error62)) extendForNaturalCompletion();
|
|
19348
|
+
else return false;
|
|
19275
19349
|
}
|
|
19276
19350
|
return await Promise.race([completion.then(() => true, () => false), deadline.promise]);
|
|
19277
19351
|
} finally {
|
|
19352
|
+
giveup?.dispose();
|
|
19278
19353
|
clearTimeout(timer);
|
|
19279
19354
|
signal?.removeEventListener("abort", cancelled);
|
|
19280
19355
|
}
|
|
@@ -60874,14 +60949,16 @@ function stream(runtime, model, context, options) {
|
|
|
60874
60949
|
return runtime.stream(model, context, options).stream;
|
|
60875
60950
|
}
|
|
60876
60951
|
|
|
60877
|
-
// extension/
|
|
60952
|
+
// extension/efforts.ts
|
|
60878
60953
|
var EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
60879
|
-
var ROUTE_PREFIX = "__omp_acp_thought__:";
|
|
60880
60954
|
var LEGACY_EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORTS.join("|")})$`);
|
|
60881
60955
|
function splitLegacyEffort(modelId) {
|
|
60882
60956
|
const match = modelId.match(LEGACY_EFFORT_SUFFIX);
|
|
60883
60957
|
return match ? { base: match[1], effort: match[2] } : void 0;
|
|
60884
60958
|
}
|
|
60959
|
+
|
|
60960
|
+
// extension/model-catalog.ts
|
|
60961
|
+
var ROUTE_PREFIX = "__omp_acp_thought__:";
|
|
60885
60962
|
function validId(value) {
|
|
60886
60963
|
return typeof value === "string" && value.length > 0 && value.length <= 256 && value === value.trim() && !/[\u0000-\u001f\u007f]/u.test(value);
|
|
60887
60964
|
}
|
|
@@ -61004,6 +61081,7 @@ function usageDelta(before, after) {
|
|
|
61004
61081
|
}
|
|
61005
61082
|
|
|
61006
61083
|
// extension/tier-connection.ts
|
|
61084
|
+
var STEER_FROZEN_UPDATES = /* @__PURE__ */ new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);
|
|
61007
61085
|
var TierConnection = class extends AntigravityAcpConnection {
|
|
61008
61086
|
confirmedThinking;
|
|
61009
61087
|
debugToolUpdates;
|
|
@@ -61023,6 +61101,9 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61023
61101
|
ownershipRetry;
|
|
61024
61102
|
cleanupLeases = /* @__PURE__ */ new Map();
|
|
61025
61103
|
toolRouting;
|
|
61104
|
+
steerTimings;
|
|
61105
|
+
steerMuted = /* @__PURE__ */ new Set();
|
|
61106
|
+
steerActivity = /* @__PURE__ */ new Map();
|
|
61026
61107
|
constructor(options) {
|
|
61027
61108
|
super(options);
|
|
61028
61109
|
this.cleanup = options.ompCleanup;
|
|
@@ -61032,6 +61113,7 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61032
61113
|
});
|
|
61033
61114
|
this.debugToolUpdates = options.ompDebugToolUpdates ?? false;
|
|
61034
61115
|
this.usageMode = options.ompUsageMode ?? "auto";
|
|
61116
|
+
this.steerTimings = options.ompSteerTimings ?? steerTimings();
|
|
61035
61117
|
this.setHandlers({ ...options.handlers, onUpdate: async (notification) => {
|
|
61036
61118
|
const update = notification.update;
|
|
61037
61119
|
if (update.sessionUpdate === "available_commands_update") {
|
|
@@ -61052,6 +61134,10 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61052
61134
|
this.diagnostics?.record("acp.first-output", performance.now() - this.firstOutput.get(notification.sessionId));
|
|
61053
61135
|
this.firstOutput.delete(notification.sessionId);
|
|
61054
61136
|
}
|
|
61137
|
+
if (this.steerMuted.has(notification.sessionId)) {
|
|
61138
|
+
for (const listener of [...this.steerActivity.get(notification.sessionId) ?? []]) listener();
|
|
61139
|
+
if (STEER_FROZEN_UPDATES.has(update.sessionUpdate ?? "")) return;
|
|
61140
|
+
}
|
|
61055
61141
|
if (showAcpUpdate(notification, this.debugToolUpdates)) await options.handlers?.onUpdate?.(notification);
|
|
61056
61142
|
} });
|
|
61057
61143
|
if (options.ompNativeTools) {
|
|
@@ -61065,6 +61151,23 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61065
61151
|
this.usageMode = mode;
|
|
61066
61152
|
this.usageBaselines.clear();
|
|
61067
61153
|
}
|
|
61154
|
+
// drainCancelledTurn calls this while waiting for a turn the server cannot
|
|
61155
|
+
// cancel, so retained partial output stays frozen at the steering boundary
|
|
61156
|
+
// and the checkpointed fingerprint still matches the OMP transcript.
|
|
61157
|
+
muteSteerChunks(sessionId) {
|
|
61158
|
+
this.steerMuted.add(sessionId);
|
|
61159
|
+
}
|
|
61160
|
+
// armSteerGiveup subscribes here: every update from the draining session
|
|
61161
|
+
// resets the silence window of the steering grace.
|
|
61162
|
+
onSteerActivity(sessionId, listener) {
|
|
61163
|
+
let listeners = this.steerActivity.get(sessionId);
|
|
61164
|
+
if (!listeners) this.steerActivity.set(sessionId, listeners = /* @__PURE__ */ new Set());
|
|
61165
|
+
listeners.add(listener);
|
|
61166
|
+
return () => {
|
|
61167
|
+
listeners.delete(listener);
|
|
61168
|
+
if (!listeners.size) this.steerActivity.delete(sessionId);
|
|
61169
|
+
};
|
|
61170
|
+
}
|
|
61068
61171
|
async newSession(...args) {
|
|
61069
61172
|
const session = await super.newSession(...args);
|
|
61070
61173
|
if (this.cleanup) {
|
|
@@ -61096,6 +61199,8 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61096
61199
|
this.usageStatus?.delete(id);
|
|
61097
61200
|
this.usageBaselines?.delete(id);
|
|
61098
61201
|
this.usageCommands?.delete(id);
|
|
61202
|
+
this.steerMuted?.delete(id);
|
|
61203
|
+
this.steerActivity?.delete(id);
|
|
61099
61204
|
}
|
|
61100
61205
|
async retireForReplacement(key, id) {
|
|
61101
61206
|
const unloaded = !Object.keys(this.getSessionState(id)).length;
|
|
@@ -61145,6 +61250,8 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61145
61250
|
this.usageCommands?.clear();
|
|
61146
61251
|
this.usageCaptures?.clear();
|
|
61147
61252
|
this.firstOutput?.clear();
|
|
61253
|
+
this.steerMuted?.clear();
|
|
61254
|
+
this.steerActivity?.clear();
|
|
61148
61255
|
}
|
|
61149
61256
|
async retryOwnership() {
|
|
61150
61257
|
if (this.ownershipRetry) return this.ownershipRetry;
|
|
@@ -61185,12 +61292,14 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61185
61292
|
async prompt(request, signal) {
|
|
61186
61293
|
this.activePrompts++;
|
|
61187
61294
|
const id = request.sessionId;
|
|
61295
|
+
this.steerMuted?.delete(id);
|
|
61188
61296
|
await this.retryOwnership();
|
|
61189
61297
|
let abortedAt;
|
|
61190
61298
|
const aborted2 = () => {
|
|
61191
61299
|
abortedAt = performance.now();
|
|
61192
61300
|
};
|
|
61193
61301
|
signal?.addEventListener("abort", aborted2, { once: true });
|
|
61302
|
+
const deferred = signal ? deferredAbortSignal(signal, this.steerTimings, { source: this, sessionId: id }) : void 0;
|
|
61194
61303
|
try {
|
|
61195
61304
|
await this.cleanup?.touch(id);
|
|
61196
61305
|
} catch {
|
|
@@ -61206,7 +61315,7 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61206
61315
|
}
|
|
61207
61316
|
const started = performance.now();
|
|
61208
61317
|
this.firstOutput?.set(id, started);
|
|
61209
|
-
const response = await super.prompt(request, signal);
|
|
61318
|
+
const response = await super.prompt(request, deferred?.signal ?? signal);
|
|
61210
61319
|
this.diagnostics?.record("acp.prompt", performance.now() - started);
|
|
61211
61320
|
if (abortedAt !== void 0 && ["cancelled", "end_turn"].includes(response.stopReason)) this.diagnostics?.record("acp.cancel-confirmation", performance.now() - abortedAt);
|
|
61212
61321
|
const withContext = (value) => {
|
|
@@ -61232,6 +61341,7 @@ var TierConnection = class extends AntigravityAcpConnection {
|
|
|
61232
61341
|
return withContext(response);
|
|
61233
61342
|
}
|
|
61234
61343
|
} finally {
|
|
61344
|
+
deferred?.dispose();
|
|
61235
61345
|
signal?.removeEventListener("abort", aborted2);
|
|
61236
61346
|
this.firstOutput?.delete(id);
|
|
61237
61347
|
this.activePrompts--;
|
|
@@ -61301,7 +61411,7 @@ async function sourceId(file2) {
|
|
|
61301
61411
|
}
|
|
61302
61412
|
}
|
|
61303
61413
|
async function findSources(root) {
|
|
61304
|
-
let entries = 0;
|
|
61414
|
+
let entries = 0, complete = true;
|
|
61305
61415
|
const sources = /* @__PURE__ */ new Map();
|
|
61306
61416
|
async function visit2(dir, depth) {
|
|
61307
61417
|
if (depth > 4) throw new Error("OMP source scan depth exceeded");
|
|
@@ -61312,11 +61422,17 @@ async function findSources(root) {
|
|
|
61312
61422
|
if (item.isDirectory()) {
|
|
61313
61423
|
if (/^\d{4}-\d\d-\d\d.*_[\da-f-]+$/i.test(item.name)) continue;
|
|
61314
61424
|
await visit2(file2, depth + 1);
|
|
61315
|
-
} else if (item.isFile() && item.name.endsWith(".jsonl"))
|
|
61425
|
+
} else if (item.isFile() && item.name.endsWith(".jsonl")) {
|
|
61426
|
+
try {
|
|
61427
|
+
sources.set(await sourceId(file2), file2);
|
|
61428
|
+
} catch {
|
|
61429
|
+
complete = false;
|
|
61430
|
+
}
|
|
61431
|
+
}
|
|
61316
61432
|
}
|
|
61317
61433
|
}
|
|
61318
61434
|
await visit2(root, 0);
|
|
61319
|
-
return sources;
|
|
61435
|
+
return { sources, complete };
|
|
61320
61436
|
}
|
|
61321
61437
|
|
|
61322
61438
|
// extension/session-cleanup.ts
|
|
@@ -61416,7 +61532,7 @@ var SessionCleanup = class {
|
|
|
61416
61532
|
});
|
|
61417
61533
|
}
|
|
61418
61534
|
status() {
|
|
61419
|
-
return { ...loadCleanupPolicy(this.policyPath), ...this.report, warning: this.report.overBudget ? "Soft budget exceeded;
|
|
61535
|
+
return { ...loadCleanupPolicy(this.policyPath), ...this.report, warning: this.report.overBudget ? "Soft budget exceeded; active and recently used sessions remain protected" : void 0, pendingLifecycleUpdates: this.intents.length, file: this.policyPath, scope: "adapter-owned local ACP data" };
|
|
61420
61536
|
}
|
|
61421
61537
|
start() {
|
|
61422
61538
|
if (this.timer) return;
|
|
@@ -61605,7 +61721,7 @@ var SessionCleanup = class {
|
|
|
61605
61721
|
if (registry2.sessions.some((v) => v.disposableFor)) await this.unmapReleased(registry2);
|
|
61606
61722
|
const mappings = await this.sessionStore.list();
|
|
61607
61723
|
const mapped = new Set(mappings.map((v) => v.acpSessionId));
|
|
61608
|
-
const report = { owned: 0, active: 0, mapped: 0, unmapped: 0, ownedBytes: 0, overBudget: false, removed: 0, reclaimedBytes: 0, retainedForRecovery: 0, failures: this.report.failures, deferred: 0 };
|
|
61724
|
+
const report = { owned: 0, active: 0, mapped: 0, unmapped: 0, ownedBytes: 0, overBudget: false, removed: 0, removedMapped: 0, reclaimedBytes: 0, retainedForRecovery: 0, failures: this.report.failures, deferred: 0 };
|
|
61609
61725
|
let dirs;
|
|
61610
61726
|
const owned = [];
|
|
61611
61727
|
const sourceScans = /* @__PURE__ */ new Map();
|
|
@@ -61631,28 +61747,31 @@ var SessionCleanup = class {
|
|
|
61631
61747
|
delete source.missingSince;
|
|
61632
61748
|
} else {
|
|
61633
61749
|
if (!sourceScans.has(root)) sourceScans.set(root, findSources(root));
|
|
61634
|
-
const
|
|
61750
|
+
const scan = await sourceScans.get(root);
|
|
61751
|
+
const moved = scan.sources.get(source.id);
|
|
61635
61752
|
if (moved) {
|
|
61636
61753
|
source.file = moved;
|
|
61637
61754
|
delete source.missingSince;
|
|
61638
|
-
} else if (
|
|
61639
|
-
|
|
61640
|
-
|
|
61641
|
-
|
|
61642
|
-
|
|
61643
|
-
|
|
61644
|
-
|
|
61645
|
-
|
|
61646
|
-
|
|
61647
|
-
|
|
61648
|
-
|
|
61649
|
-
|
|
61650
|
-
|
|
61651
|
-
|
|
61652
|
-
|
|
61653
|
-
|
|
61654
|
-
|
|
61655
|
-
|
|
61755
|
+
} else if (scan.complete) {
|
|
61756
|
+
if (source.missingSince === void 0) source.missingSince = this.now();
|
|
61757
|
+
else if (this.now() - source.missingSince >= 6e4) {
|
|
61758
|
+
const finalRoot = await sourceRoot(root);
|
|
61759
|
+
if (finalRoot.dev !== source.device || finalRoot.ino !== source.inode) throw new Error("OMP storage changed during scan");
|
|
61760
|
+
let restored = false;
|
|
61761
|
+
try {
|
|
61762
|
+
await afs.lstat(source.file);
|
|
61763
|
+
restored = true;
|
|
61764
|
+
delete source.missingSince;
|
|
61765
|
+
} catch (e) {
|
|
61766
|
+
if (!isMissingFileError(e)) throw e;
|
|
61767
|
+
}
|
|
61768
|
+
if (!restored) {
|
|
61769
|
+
await this.sessionStore.removeIfMatches(source.id, v.id);
|
|
61770
|
+
const latest = await this.sessionStore.list();
|
|
61771
|
+
if (!latest.some((m) => m.acpSessionId === v.id)) {
|
|
61772
|
+
mapped.delete(v.id);
|
|
61773
|
+
v.sourceDeleted = true;
|
|
61774
|
+
}
|
|
61656
61775
|
}
|
|
61657
61776
|
}
|
|
61658
61777
|
}
|
|
@@ -61683,7 +61802,10 @@ var SessionCleanup = class {
|
|
|
61683
61802
|
const over = () => Boolean(policy.maxSessions && report.owned > policy.maxSessions || policy.maxBytes && report.ownedBytes > policy.maxBytes);
|
|
61684
61803
|
report.overBudget = over();
|
|
61685
61804
|
if (policy.mode !== "off") for (const { v, size } of owned.sort((a, b) => a.v.lastUsed - b.v.lastUsed)) {
|
|
61686
|
-
if (
|
|
61805
|
+
if (v.leases.length) continue;
|
|
61806
|
+
const isMapped = mapped.has(v.id);
|
|
61807
|
+
const mappedExpired = isMapped && policy.mode === "balanced" && this.now() - v.lastUsed >= policy.idleDays * 864e5;
|
|
61808
|
+
if (isMapped && !mappedExpired) continue;
|
|
61687
61809
|
const recoverable = v.replaced || v.disposableAt !== void 0;
|
|
61688
61810
|
if (policy.mode === "balanced" && v.replaced) v.confirmedAt ??= this.now();
|
|
61689
61811
|
const recovering = policy.mode === "balanced" && recoverable && this.now() - Math.max(v.confirmedAt ?? 0, v.disposableAt ?? 0, v.lastUsed) < (policy.recoveryDays ?? 1) * 864e5;
|
|
@@ -61692,14 +61814,25 @@ var SessionCleanup = class {
|
|
|
61692
61814
|
continue;
|
|
61693
61815
|
}
|
|
61694
61816
|
const timeout = policy.mode === "timeout" || policy.mode === "balanced";
|
|
61695
|
-
const idleSince = policy.mode === "balanced" ? Math.max(v.lastUsed, v.orphanedAt) : v.lastUsed;
|
|
61696
|
-
const expired = timeout && (this.now() - idleSince >= policy.idleDays * 864e5 || over() && this.now() - v.orphanedAt >= (policy.orphanGraceDays ?? 1) * 864e5);
|
|
61697
|
-
if (!recoverable && !v.sourceDeleted && !expired) continue;
|
|
61817
|
+
const idleSince = policy.mode === "balanced" ? Math.max(v.lastUsed, v.orphanedAt ?? 0) : v.lastUsed;
|
|
61818
|
+
const expired = timeout && (this.now() - idleSince >= policy.idleDays * 864e5 || over() && v.orphanedAt !== void 0 && this.now() - v.orphanedAt >= (policy.orphanGraceDays ?? 1) * 864e5);
|
|
61819
|
+
if (!recoverable && !v.sourceDeleted && !expired && !mappedExpired) continue;
|
|
61698
61820
|
if (report.removed >= (policy.batchSize ?? 8)) {
|
|
61699
61821
|
report.deferred++;
|
|
61700
61822
|
continue;
|
|
61701
61823
|
}
|
|
61702
61824
|
try {
|
|
61825
|
+
if (isMapped) {
|
|
61826
|
+
const rows = mappings.filter((m) => m.acpSessionId === v.id);
|
|
61827
|
+
const owner = rows.length === 1 ? rows[0].piSessionId : void 0;
|
|
61828
|
+
if (owner === void 0 || mappings.filter((m) => m.piSessionId === owner).length !== 1) continue;
|
|
61829
|
+
await this.sessionStore.removeIfMatches(owner, v.id);
|
|
61830
|
+
if ((await this.sessionStore.list()).some((m) => m.acpSessionId === v.id)) {
|
|
61831
|
+
report.failures++;
|
|
61832
|
+
continue;
|
|
61833
|
+
}
|
|
61834
|
+
mapped.delete(v.id);
|
|
61835
|
+
}
|
|
61703
61836
|
dirs ??= await this.verifyRoot();
|
|
61704
61837
|
const targets = this.targets(v.id, dirs);
|
|
61705
61838
|
for (const target of targets) await this.inspect(target);
|
|
@@ -61708,9 +61841,12 @@ var SessionCleanup = class {
|
|
|
61708
61841
|
this.touched.delete(v.id);
|
|
61709
61842
|
report.removed++;
|
|
61710
61843
|
report.owned--;
|
|
61711
|
-
report.unmapped--;
|
|
61712
61844
|
report.ownedBytes -= size;
|
|
61713
61845
|
report.reclaimedBytes += size;
|
|
61846
|
+
if (isMapped) {
|
|
61847
|
+
report.mapped--;
|
|
61848
|
+
report.removedMapped++;
|
|
61849
|
+
} else report.unmapped--;
|
|
61714
61850
|
} catch {
|
|
61715
61851
|
report.failures++;
|
|
61716
61852
|
}
|
|
@@ -6,7 +6,7 @@ import { lock } from "proper-lockfile";
|
|
|
6
6
|
import { resolveAntigravityAcpDirectory } from "./vendor/pi-antigravity-acp-provider/src/acp/antigravity.ts";
|
|
7
7
|
import { isMissingFileError, writeJsonAtomic } from "./fs-atomic.ts";
|
|
8
8
|
import { AcpSessionStore } from "./session-store.ts";
|
|
9
|
-
import { sourceRoot, sourceId, findSources, type OmpSessionSource } from "./omp-session-source.ts";
|
|
9
|
+
import { sourceRoot, sourceId, findSources, type OmpSessionSource, type OmpSourceScan } from "./omp-session-source.ts";
|
|
10
10
|
export type CleanupMode = "off" | "conservative" | "timeout" | "balanced";
|
|
11
11
|
export interface CleanupPolicy { mode: CleanupMode; idleDays: number; maxSessions?: number; maxBytes?: number; orphanGraceDays?: number; recoveryDays?: number; batchSize?: number }
|
|
12
12
|
const DEFAULT: CleanupPolicy = { mode: "conservative", idleDays: 7 };
|
|
@@ -74,7 +74,7 @@ export class SessionCleanup {
|
|
|
74
74
|
}
|
|
75
75
|
});
|
|
76
76
|
}
|
|
77
|
-
status() { return { ...loadCleanupPolicy(this.policyPath), ...this.report, warning: this.report.overBudget ? "Soft budget exceeded;
|
|
77
|
+
status() { return { ...loadCleanupPolicy(this.policyPath), ...this.report, warning: this.report.overBudget ? "Soft budget exceeded; active and recently used sessions remain protected" : undefined, pendingLifecycleUpdates: this.intents.length, file: this.policyPath, scope: "adapter-owned local ACP data" }; }
|
|
78
78
|
start() { if (this.timer) return; void this.collect(); this.timer = setInterval(() => { void this.collect(); }, 15 * 60_000); this.timer.unref(); }
|
|
79
79
|
async stop() { clearInterval(this.timer); clearTimeout(this.nextBatch); this.timer = undefined; this.nextBatch = undefined; await this.collecting; await tails.get(this.registryPath)?.catch(() => {}); }
|
|
80
80
|
private transaction<T>(action: (r: Registry) => T | Promise<T>): Promise<T> {
|
|
@@ -185,10 +185,10 @@ export class SessionCleanup {
|
|
|
185
185
|
if (registry.sessions.some(v => v.disposableFor)) await this.unmapReleased(registry);
|
|
186
186
|
const mappings = await this.sessionStore.list();
|
|
187
187
|
const mapped = new Set(mappings.map(v => v.acpSessionId));
|
|
188
|
-
const report = { owned: 0, active: 0, mapped: 0, unmapped: 0, ownedBytes: 0, overBudget: false, removed: 0, reclaimedBytes: 0, retainedForRecovery: 0, failures: this.report.failures, deferred: 0 };
|
|
188
|
+
const report = { owned: 0, active: 0, mapped: 0, unmapped: 0, ownedBytes: 0, overBudget: false, removed: 0, removedMapped: 0, reclaimedBytes: 0, retainedForRecovery: 0, failures: this.report.failures, deferred: 0 };
|
|
189
189
|
let dirs: { conversations: string; brain: string } | undefined;
|
|
190
190
|
const owned = [];
|
|
191
|
-
const sourceScans = new Map<string, Promise<
|
|
191
|
+
const sourceScans = new Map<string, Promise<OmpSourceScan>>();
|
|
192
192
|
for (const v of registry.sessions) {
|
|
193
193
|
v.leases = v.leases.filter(l => this.isLive(l.pid) || this.isLive(l.serverPid)); if (!v.owned) continue;
|
|
194
194
|
if (policy.mode !== "off" && v.ompSource && !v.leases.length) {
|
|
@@ -206,21 +206,24 @@ export class SessionCleanup {
|
|
|
206
206
|
if (!missing) { delete source.missingSince; }
|
|
207
207
|
else {
|
|
208
208
|
if (!sourceScans.has(root)) sourceScans.set(root, findSources(root));
|
|
209
|
-
const
|
|
209
|
+
const scan = await sourceScans.get(root)!;
|
|
210
|
+
const moved = scan.sources.get(source.id);
|
|
210
211
|
if (moved) { source.file = moved; delete source.missingSince; }
|
|
211
|
-
else if (
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
212
|
+
else if (scan.complete) {
|
|
213
|
+
if (source.missingSince === undefined) source.missingSince = this.now();
|
|
214
|
+
else if (this.now() - source.missingSince >= 60000) {
|
|
215
|
+
const finalRoot = await sourceRoot(root);
|
|
216
|
+
if (finalRoot.dev !== source.device || finalRoot.ino !== source.inode) throw new Error("OMP storage changed during scan");
|
|
217
|
+
let restored = false;
|
|
218
|
+
try { await afs.lstat(source.file); restored = true; delete source.missingSince; }
|
|
219
|
+
catch (e) { if (!isMissingFileError(e)) throw e; }
|
|
220
|
+
if (!restored) {
|
|
221
|
+
// Recheck under the mapping store's own lock. A newer ACP
|
|
222
|
+
// binding must never be removed by an old cleanup snapshot.
|
|
223
|
+
await this.sessionStore.removeIfMatches(source.id, v.id);
|
|
224
|
+
const latest = await this.sessionStore.list();
|
|
225
|
+
if (!latest.some(m => m.acpSessionId === v.id)) { mapped.delete(v.id); v.sourceDeleted = true; }
|
|
226
|
+
}
|
|
224
227
|
}
|
|
225
228
|
}
|
|
226
229
|
}
|
|
@@ -234,7 +237,13 @@ export class SessionCleanup {
|
|
|
234
237
|
const over = () => Boolean((policy.maxSessions && report.owned > policy.maxSessions) || (policy.maxBytes && report.ownedBytes > policy.maxBytes));
|
|
235
238
|
report.overBudget = over();
|
|
236
239
|
if (policy.mode !== "off") for (const { v, size } of owned.sort((a, b) => a.v.lastUsed - b.v.lastUsed)) {
|
|
237
|
-
if (
|
|
240
|
+
if (v.leases.length) continue;
|
|
241
|
+
const isMapped = mapped.has(v.id);
|
|
242
|
+
// Balanced mode may retire a still-mapped conversation once it has been
|
|
243
|
+
// idle for the full window; the next turn rebuilds it from OMP history.
|
|
244
|
+
// Every other mode, and every shorter idle period, preserves mappings.
|
|
245
|
+
const mappedExpired = isMapped && policy.mode === "balanced" && this.now() - v.lastUsed >= policy.idleDays * 86_400_000;
|
|
246
|
+
if (isMapped && !mappedExpired) continue;
|
|
238
247
|
const recoverable = v.replaced || v.disposableAt !== undefined;
|
|
239
248
|
// Legacy replacement records start their recovery window on the first
|
|
240
249
|
// balanced sweep. Pressure never bypasses that minimum retention.
|
|
@@ -242,16 +251,30 @@ export class SessionCleanup {
|
|
|
242
251
|
const recovering = policy.mode === "balanced" && recoverable && this.now() - Math.max(v.confirmedAt ?? 0, v.disposableAt ?? 0, v.lastUsed) < (policy.recoveryDays ?? 1) * 86_400_000;
|
|
243
252
|
if (recovering && !v.sourceDeleted) { report.retainedForRecovery++; continue; }
|
|
244
253
|
const timeout = policy.mode === "timeout" || policy.mode === "balanced";
|
|
245
|
-
const idleSince = policy.mode === "balanced" ? Math.max(v.lastUsed, v.orphanedAt
|
|
246
|
-
const expired = timeout && (this.now() - idleSince >= policy.idleDays * 86_400_000 ||
|
|
247
|
-
|
|
254
|
+
const idleSince = policy.mode === "balanced" ? Math.max(v.lastUsed, v.orphanedAt ?? 0) : v.lastUsed;
|
|
255
|
+
const expired = timeout && (this.now() - idleSince >= policy.idleDays * 86_400_000 ||
|
|
256
|
+
(over() && v.orphanedAt !== undefined && this.now() - v.orphanedAt >= (policy.orphanGraceDays ?? 1) * 86_400_000));
|
|
257
|
+
if (!recoverable && !v.sourceDeleted && !expired && !mappedExpired) continue;
|
|
248
258
|
if (report.removed >= (policy.batchSize ?? 8)) { report.deferred++; continue; }
|
|
249
259
|
try {
|
|
260
|
+
if (isMapped) {
|
|
261
|
+
// Re-prove ownership under the mapping store's lock before deleting
|
|
262
|
+
// files. Ambiguous or duplicated mappings prove nothing, and a
|
|
263
|
+
// concurrent resume that re-mapped this ACP ID wins; either way the
|
|
264
|
+
// sweep leaves the session for its owner.
|
|
265
|
+
const rows = mappings.filter(m => m.acpSessionId === v.id);
|
|
266
|
+
const owner = rows.length === 1 ? rows[0]!.piSessionId : undefined;
|
|
267
|
+
if (owner === undefined || mappings.filter(m => m.piSessionId === owner).length !== 1) continue;
|
|
268
|
+
await this.sessionStore.removeIfMatches(owner, v.id);
|
|
269
|
+
if ((await this.sessionStore.list()).some(m => m.acpSessionId === v.id)) { report.failures++; continue; }
|
|
270
|
+
mapped.delete(v.id);
|
|
271
|
+
}
|
|
250
272
|
dirs ??= await this.verifyRoot(); const targets = this.targets(v.id, dirs);
|
|
251
273
|
for (const target of targets) await this.inspect(target);
|
|
252
274
|
for (const target of targets) await afs.rm(target, { recursive: true, force: true });
|
|
253
275
|
registry.sessions = registry.sessions.filter(r => r !== v); this.touched.delete(v.id);
|
|
254
|
-
report.removed++; report.owned--; report.
|
|
276
|
+
report.removed++; report.owned--; report.ownedBytes -= size; report.reclaimedBytes += size;
|
|
277
|
+
if (isMapped) { report.mapped--; report.removedMapped++; } else report.unmapped--;
|
|
255
278
|
} catch { report.failures++; }
|
|
256
279
|
}
|
|
257
280
|
registry.sessions = registry.sessions.filter(v => v.owned || v.leases.length);
|
|
@@ -7,7 +7,11 @@ import { showAcpUpdate } from "./activity-presentation.ts";
|
|
|
7
7
|
import { parseSessionUsage, usageDelta, type SessionUsage } from "./usage-accounting.ts";
|
|
8
8
|
import type { SessionCleanup } from "./session-cleanup.ts";
|
|
9
9
|
import type { Diagnostics } from "./diagnostics.ts";
|
|
10
|
+
import { deferredAbortSignal, steerTimings as resolveSteerTimings, type SteerTimings } from "./turn-cancellation.ts";
|
|
10
11
|
|
|
12
|
+
// Updates that would extend the retained turn output stay frozen while a
|
|
13
|
+
// turn the server cannot cancel drains towards its natural end.
|
|
14
|
+
const STEER_FROZEN_UPDATES = new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);
|
|
11
15
|
export class TierConnection extends AntigravityAcpConnection {
|
|
12
16
|
confirmedThinking: { model: string; effort: string } | undefined;
|
|
13
17
|
debugToolUpdates: boolean;
|
|
@@ -27,8 +31,11 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
27
31
|
private ownershipRetry?: Promise<void>;
|
|
28
32
|
private cleanupLeases = new Map<string, string>();
|
|
29
33
|
toolRouting: { nativeTools: NativeToolMode; channel: "pending" | "system-append" | "legacy-prompt" } | undefined;
|
|
34
|
+
private readonly steerTimings: SteerTimings;
|
|
35
|
+
private readonly steerMuted = new Set<string>();
|
|
36
|
+
private readonly steerActivity = new Map<string, Set<() => void>>();
|
|
30
37
|
|
|
31
|
-
constructor(options: ConstructorParameters<typeof AntigravityAcpConnection>[0] & { ompNativeTools?: NativeToolMode; ompDebugToolUpdates?: boolean; ompUsageMode?: "auto" | "off"; ompCleanup?: SessionCleanup; ompDiagnostics?: Diagnostics }) {
|
|
38
|
+
constructor(options: ConstructorParameters<typeof AntigravityAcpConnection>[0] & { ompNativeTools?: NativeToolMode; ompDebugToolUpdates?: boolean; ompUsageMode?: "auto" | "off"; ompSteerTimings?: SteerTimings; ompCleanup?: SessionCleanup; ompDiagnostics?: Diagnostics }) {
|
|
32
39
|
super(options);
|
|
33
40
|
this.cleanup = options.ompCleanup;
|
|
34
41
|
this.diagnostics = options.ompDiagnostics;
|
|
@@ -36,6 +43,7 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
36
43
|
void this.process.exited.then(() => this.releaseCleanupLeases()).catch(() => {});
|
|
37
44
|
this.debugToolUpdates = options.ompDebugToolUpdates ?? false;
|
|
38
45
|
this.usageMode = options.ompUsageMode ?? "auto";
|
|
46
|
+
this.steerTimings = options.ompSteerTimings ?? resolveSteerTimings();
|
|
39
47
|
this.setHandlers({ ...options.handlers, onUpdate: async notification => {
|
|
40
48
|
const update = notification.update as {
|
|
41
49
|
sessionUpdate?: string;
|
|
@@ -62,6 +70,14 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
62
70
|
this.diagnostics?.record("acp.first-output", performance.now() - this.firstOutput.get(notification.sessionId)!);
|
|
63
71
|
this.firstOutput.delete(notification.sessionId);
|
|
64
72
|
}
|
|
73
|
+
if (this.steerMuted.has(notification.sessionId)) {
|
|
74
|
+
// The turn cannot be cancelled and is draining towards its natural
|
|
75
|
+
// end: the update proves it is alive and extends the steering grace,
|
|
76
|
+
// while output-mutating updates stay frozen so the checkpointed
|
|
77
|
+
// fingerprint still matches what OMP retained at the boundary.
|
|
78
|
+
for (const listener of [...this.steerActivity.get(notification.sessionId) ?? []]) listener();
|
|
79
|
+
if (STEER_FROZEN_UPDATES.has(update.sessionUpdate ?? "")) return;
|
|
80
|
+
}
|
|
65
81
|
if (showAcpUpdate(notification, this.debugToolUpdates)) await options.handlers?.onUpdate?.(notification);
|
|
66
82
|
} });
|
|
67
83
|
if (options.ompNativeTools) {
|
|
@@ -77,6 +93,25 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
77
93
|
this.usageBaselines.clear();
|
|
78
94
|
}
|
|
79
95
|
|
|
96
|
+
// drainCancelledTurn calls this while waiting for a turn the server cannot
|
|
97
|
+
// cancel, so retained partial output stays frozen at the steering boundary
|
|
98
|
+
// and the checkpointed fingerprint still matches the OMP transcript.
|
|
99
|
+
muteSteerChunks(sessionId: string) {
|
|
100
|
+
this.steerMuted.add(sessionId);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// armSteerGiveup subscribes here: every update from the draining session
|
|
104
|
+
// resets the silence window of the steering grace.
|
|
105
|
+
onSteerActivity(sessionId: string, listener: () => void): () => void {
|
|
106
|
+
let listeners = this.steerActivity.get(sessionId);
|
|
107
|
+
if (!listeners) this.steerActivity.set(sessionId, (listeners = new Set()));
|
|
108
|
+
listeners.add(listener);
|
|
109
|
+
return () => {
|
|
110
|
+
listeners!.delete(listener);
|
|
111
|
+
if (!listeners!.size) this.steerActivity.delete(sessionId);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
80
115
|
override async newSession(...args: Parameters<AntigravityAcpConnection["newSession"]>) {
|
|
81
116
|
const session = await super.newSession(...args);
|
|
82
117
|
if (this.cleanup) {
|
|
@@ -106,6 +141,8 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
106
141
|
this.usageStatus?.delete(id);
|
|
107
142
|
this.usageBaselines?.delete(id);
|
|
108
143
|
this.usageCommands?.delete(id);
|
|
144
|
+
this.steerMuted?.delete(id);
|
|
145
|
+
this.steerActivity?.delete(id);
|
|
109
146
|
}
|
|
110
147
|
async retireForReplacement(key: string, id: string) {
|
|
111
148
|
const unloaded = !Object.keys(this.getSessionState(id)).length;
|
|
@@ -142,6 +179,8 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
142
179
|
this.usageCommands?.clear();
|
|
143
180
|
this.usageCaptures?.clear();
|
|
144
181
|
this.firstOutput?.clear();
|
|
182
|
+
this.steerMuted?.clear();
|
|
183
|
+
this.steerActivity?.clear();
|
|
145
184
|
}
|
|
146
185
|
private async retryOwnership() {
|
|
147
186
|
if (this.ownershipRetry) return this.ownershipRetry;
|
|
@@ -174,10 +213,19 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
174
213
|
override async prompt(request: Parameters<AntigravityAcpConnection["prompt"]>[0], signal?: AbortSignal) {
|
|
175
214
|
this.activePrompts++;
|
|
176
215
|
const id = request.sessionId;
|
|
216
|
+
// The next dispatch owns this session's stream again; updates from a
|
|
217
|
+
// drained turn must no longer be frozen once it starts.
|
|
218
|
+
this.steerMuted?.delete(id);
|
|
177
219
|
await this.retryOwnership();
|
|
178
220
|
let abortedAt: number | undefined;
|
|
179
221
|
const aborted = () => { abortedAt = performance.now(); };
|
|
180
222
|
signal?.addEventListener("abort", aborted, { once: true });
|
|
223
|
+
// The official server has no session/cancel, so a caller abort must not
|
|
224
|
+
// reach the vendored transport immediately: upstream closes the whole
|
|
225
|
+
// connection 1.5s later and would destroy the warm session that
|
|
226
|
+
// drainCancelledTurn is waiting to reuse. The hold lasts as long as the
|
|
227
|
+
// draining turn keeps producing updates, within the grace timings.
|
|
228
|
+
const deferred = signal ? deferredAbortSignal(signal, this.steerTimings, { source: this, sessionId: id }) : undefined;
|
|
181
229
|
try { await this.cleanup?.touch(id); } catch { /* Cleanup must not affect inference. */ }
|
|
182
230
|
try {
|
|
183
231
|
const queryUsage = process.env.OMP_ACP_USAGE !== "off" && this.usageMode !== "off" && this.usageCommands.has(id);
|
|
@@ -189,7 +237,7 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
189
237
|
}
|
|
190
238
|
const started = performance.now();
|
|
191
239
|
this.firstOutput?.set(id, started);
|
|
192
|
-
const response = await super.prompt(request, signal);
|
|
240
|
+
const response = await super.prompt(request, deferred?.signal ?? signal);
|
|
193
241
|
this.diagnostics?.record("acp.prompt", performance.now() - started);
|
|
194
242
|
if (abortedAt !== undefined && ["cancelled", "end_turn"].includes(response.stopReason)) this.diagnostics?.record("acp.cancel-confirmation", performance.now() - abortedAt);
|
|
195
243
|
const withContext = <T extends { _meta?: Record<string, unknown> }>(value: T): T => {
|
|
@@ -214,6 +262,7 @@ export class TierConnection extends AntigravityAcpConnection {
|
|
|
214
262
|
return withContext(response);
|
|
215
263
|
}
|
|
216
264
|
} finally {
|
|
265
|
+
deferred?.dispose();
|
|
217
266
|
signal?.removeEventListener("abort", aborted);
|
|
218
267
|
this.firstOutput?.delete(id);
|
|
219
268
|
this.activePrompts--;
|
|
@@ -1,7 +1,112 @@
|
|
|
1
|
+
export interface SteerTimings {
|
|
2
|
+
/** Longest silent stretch tolerated while waiting for a turn the server cannot cancel. */
|
|
3
|
+
idleMs: number;
|
|
4
|
+
/** Absolute cap on the whole wait; 0 keeps waiting while the turn stays alive. */
|
|
5
|
+
maxMs: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface SteerActivitySource {
|
|
9
|
+
onSteerActivity?(sessionId: string, listener: () => void): () => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
1
12
|
interface PendingTurn {
|
|
2
13
|
turnCompletion?: Promise<void>;
|
|
3
14
|
session: { sessionId: string };
|
|
4
|
-
connection: {
|
|
15
|
+
connection: {
|
|
16
|
+
cancel: (sessionId: string) => Promise<void>;
|
|
17
|
+
muteSteerChunks?: (sessionId: string) => void;
|
|
18
|
+
onSteerActivity?: (sessionId: string, listener: () => void) => () => void;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// The official ACP server still lacks session/cancel (verified against
|
|
23
|
+
// agy_acp_server 1.4.3: -32601 Method not found), so an interrupted turn
|
|
24
|
+
// cannot be stopped. The steering grace instead waits for the old turn to end
|
|
25
|
+
// naturally, letting the adapter checkpoint the warm ACP session and send the
|
|
26
|
+
// new request as a delta instead of a full cold replay. The wait extends while
|
|
27
|
+
// the old turn keeps producing updates — long thinking or tool loops do not
|
|
28
|
+
// expire it — and only a silent gap beyond idleMs, or the absolute maxMs cap,
|
|
29
|
+
// gives up. idleMs 0 restores the legacy immediate-reconstruction behavior.
|
|
30
|
+
export function steerTimings(env: NodeJS.ProcessEnv = process.env): SteerTimings {
|
|
31
|
+
const idleMs = Number(env.OMP_ACP_STEER_GRACE_MS ?? 60_000);
|
|
32
|
+
if (!Number.isSafeInteger(idleMs) || idleMs < 0 || idleMs > 600_000) {
|
|
33
|
+
throw new Error("OMP_ACP_STEER_GRACE_MS must be an integer between 0 and 600000");
|
|
34
|
+
}
|
|
35
|
+
const maxMs = Number(env.OMP_ACP_STEER_GRACE_MAX_MS ?? 300_000);
|
|
36
|
+
if (!Number.isSafeInteger(maxMs) || maxMs < 0 || maxMs > 3_600_000 || (maxMs > 0 && maxMs < 100)) {
|
|
37
|
+
throw new Error("OMP_ACP_STEER_GRACE_MAX_MS must be 0 or an integer between 100 and 3600000");
|
|
38
|
+
}
|
|
39
|
+
return { idleMs, maxMs };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isCancelUnsupported(error: unknown): boolean {
|
|
43
|
+
if (!error || typeof error !== "object") return false;
|
|
44
|
+
const code = (error as { code?: unknown }).code;
|
|
45
|
+
if (code === -32601) return true;
|
|
46
|
+
const message = (error as { message?: unknown }).message;
|
|
47
|
+
return typeof message === "string" && /method not found/i.test(message);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// One activity-aware give-up clock shared by the drain and the deferred
|
|
51
|
+
// transport abort: every notification from the draining session resets the
|
|
52
|
+
// silence window, the absolute cap never moves, and the vendored progress
|
|
53
|
+
// watchdog (10 min silent / 60 min busy) remains the outer safety net.
|
|
54
|
+
export function armSteerGiveup(
|
|
55
|
+
source: SteerActivitySource | undefined,
|
|
56
|
+
sessionId: string,
|
|
57
|
+
timings: SteerTimings,
|
|
58
|
+
fire: () => void,
|
|
59
|
+
): { dispose: () => void } {
|
|
60
|
+
const startedAt = Date.now();
|
|
61
|
+
let lastActivity = startedAt;
|
|
62
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
63
|
+
let done = false;
|
|
64
|
+
const schedule = () => {
|
|
65
|
+
if (done) return;
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
const silenceDeadline = lastActivity + timings.idleMs;
|
|
68
|
+
const hardDeadline = timings.maxMs > 0 ? startedAt + timings.maxMs : Number.POSITIVE_INFINITY;
|
|
69
|
+
timer = setTimeout(() => {
|
|
70
|
+
if (done) return;
|
|
71
|
+
done = true;
|
|
72
|
+
detach?.();
|
|
73
|
+
fire();
|
|
74
|
+
}, Math.max(0, Math.min(silenceDeadline, hardDeadline) - Date.now()));
|
|
75
|
+
};
|
|
76
|
+
const detach = source?.onSteerActivity?.(sessionId, () => {
|
|
77
|
+
lastActivity = Date.now();
|
|
78
|
+
schedule();
|
|
79
|
+
});
|
|
80
|
+
schedule();
|
|
81
|
+
return { dispose: () => { done = true; clearTimeout(timer); detach?.(); } };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Keeps the vendored prompt transport alive after the caller aborts. The
|
|
85
|
+
// upstream prompt() closes the whole connection 1.5s after an abort, which
|
|
86
|
+
// would destroy the warm session before drainCancelledTurn can reuse it. The
|
|
87
|
+
// give-up follows the same activity clock as the drain, so a turn that is
|
|
88
|
+
// still producing output never loses its transport early.
|
|
89
|
+
export function deferredAbortSignal(
|
|
90
|
+
signal: AbortSignal,
|
|
91
|
+
timings: SteerTimings,
|
|
92
|
+
activity?: { source: SteerActivitySource; sessionId: string },
|
|
93
|
+
): { signal: AbortSignal; dispose: () => void } {
|
|
94
|
+
if (!(timings.idleMs > 0)) return { signal, dispose: () => undefined };
|
|
95
|
+
const controller = new AbortController();
|
|
96
|
+
let giveup: { dispose: () => void } | undefined;
|
|
97
|
+
const onAbort = () => {
|
|
98
|
+
if (giveup) return;
|
|
99
|
+
giveup = armSteerGiveup(activity?.source, activity?.sessionId, timings, () => controller.abort(signal.reason));
|
|
100
|
+
};
|
|
101
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
102
|
+
if (signal.aborted) onAbort();
|
|
103
|
+
return {
|
|
104
|
+
signal: controller.signal,
|
|
105
|
+
dispose: () => {
|
|
106
|
+
giveup?.dispose();
|
|
107
|
+
signal.removeEventListener("abort", onAbort);
|
|
108
|
+
},
|
|
109
|
+
};
|
|
5
110
|
}
|
|
6
111
|
|
|
7
112
|
// The caller decides whether the accepted transcript still matches. This only
|
|
@@ -11,20 +116,39 @@ export async function drainCancelledTurn(
|
|
|
11
116
|
abort: () => void,
|
|
12
117
|
signal?: AbortSignal,
|
|
13
118
|
timeoutMs = 1500,
|
|
119
|
+
timings: SteerTimings = steerTimings(),
|
|
14
120
|
): Promise<boolean> {
|
|
15
121
|
const completion = binding.turnCompletion;
|
|
16
122
|
if (!completion || signal?.aborted) return false;
|
|
17
123
|
const deadline = Promise.withResolvers<boolean>();
|
|
18
124
|
const cancelled = () => deadline.resolve(false);
|
|
19
|
-
|
|
125
|
+
let timer = setTimeout(cancelled, timeoutMs);
|
|
126
|
+
let giveup: { dispose: () => void } | undefined;
|
|
20
127
|
signal?.addEventListener("abort", cancelled, { once: true });
|
|
128
|
+
// Without session/cancel the old turn keeps running. Freeze what OMP has
|
|
129
|
+
// retained so the checkpointed fingerprint still matches once it ends, and
|
|
130
|
+
// wait for natural completion: the grace extends while the turn keeps
|
|
131
|
+
// producing updates and only gives up after a silent gap or the hard cap.
|
|
132
|
+
const extendForNaturalCompletion = () => {
|
|
133
|
+
binding.connection.muteSteerChunks?.(binding.session.sessionId);
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
giveup = armSteerGiveup(binding.connection, binding.session.sessionId, timings, cancelled);
|
|
136
|
+
};
|
|
21
137
|
try {
|
|
22
138
|
abort();
|
|
23
139
|
// A blocked cancel transport must not block the fallback deadline.
|
|
24
|
-
try {
|
|
25
|
-
|
|
140
|
+
try {
|
|
141
|
+
void binding.connection.cancel(binding.session.sessionId).catch((error: unknown) => {
|
|
142
|
+
if (timings.idleMs > 0 && isCancelUnsupported(error)) extendForNaturalCompletion();
|
|
143
|
+
else deadline.resolve(false);
|
|
144
|
+
});
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (timings.idleMs > 0 && isCancelUnsupported(error)) extendForNaturalCompletion();
|
|
147
|
+
else return false;
|
|
148
|
+
}
|
|
26
149
|
return await Promise.race([completion.then(() => true, () => false), deadline.promise]);
|
|
27
150
|
} finally {
|
|
151
|
+
giveup?.dispose();
|
|
28
152
|
clearTimeout(timer);
|
|
29
153
|
signal?.removeEventListener("abort", cancelled);
|
|
30
154
|
}
|
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.29",
|
|
4
4
|
"ompAcpBundle": 1,
|
|
5
5
|
"description": "Google Antigravity ACP provider for Oh My Pi (OMP), with tool bridging and per-model thinking; derived from zacbemis/pi-antigravity-acp-provider",
|
|
6
6
|
"type": "module",
|