dsh-live-compact 1.1.11 → 1.1.12
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/CHANGELOG.md +17 -0
- package/README.md +8 -8
- package/client.js +32 -13
- package/cordis.patch.yml +1 -0
- package/gate.js +55 -5
- package/index.js +706 -216
- package/package.json +2 -2
- package/raw.js +2 -2
- package/settings.js +2 -2
- package/shadow.js +220 -15
- package/shell.js +57 -2
package/index.js
CHANGED
|
@@ -17,16 +17,18 @@ import { closeSync, existsSync, openSync, readFileSync, renameSync, unlinkSync,
|
|
|
17
17
|
import { createRequire } from "node:module";
|
|
18
18
|
import { setImmediate as scheduleImmediate } from "node:timers";
|
|
19
19
|
import { Worker } from "node:worker_threads";
|
|
20
|
-
import { dirname, join } from "node:path";
|
|
21
|
-
import { pathToFileURL } from "node:url";
|
|
20
|
+
import { basename, dirname, join, resolve as resolvePath } from "node:path";
|
|
21
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
22
22
|
import { loadBase, loadCompaction, loadLlm } from "./adapter.js";
|
|
23
23
|
import { DEFAULTS, engineConfig, readSettings } from "./settings.js";
|
|
24
24
|
import { attachBackupHint, backgroundJobId, backupClaimOk, buildCard, collectJobs, cutLongReadRound, finishedToolRounds, indexToolCalls, isToolFailure, jobCutDecision, keptToolRounds, messageText, planMessages, pointerOnlyText, pointerSpanAllowed, RAIL_TOKENS, readResultLabel, reservedCutEnd, resolveEngine, resolveProviderBaseURL, roundHasLongRead, selectCutIndexes, shadowSections, takeLocalCut, withoutFullBackupClaim } from "./plan.js";
|
|
25
25
|
import { captureOwnedToolResult, contentHash, PRUNE_MARKER, rawExcerptText, rawName, readRawToolResult, restoreToolText, runPruneAfterCapture, verifiedRaw } from "./raw.js";
|
|
26
26
|
import {
|
|
27
27
|
ensureShadowDir,
|
|
28
|
+
appendDecision,
|
|
28
29
|
flushDrainStats,
|
|
29
30
|
noteShadowWarning,
|
|
31
|
+
recoverTimedOutShadowWorker,
|
|
30
32
|
saveShadowTransaction,
|
|
31
33
|
shadowDirectory,
|
|
32
34
|
shadowFileBody,
|
|
@@ -41,6 +43,92 @@ import { buildSendLess, decideThunder } from "./thunder.js";
|
|
|
41
43
|
import { inCooldown, skipLiveOfficialCompaction } from "./cooldown.js";
|
|
42
44
|
import { activeCompactionPeers, warnCompactionStandDown } from "./gate.js";
|
|
43
45
|
|
|
46
|
+
const PI_AI_CATALOG = "@earendil-works/pi-ai/providers/all";
|
|
47
|
+
const PI_AI_PACKAGE = "@earendil-works/pi-ai";
|
|
48
|
+
|
|
49
|
+
function catalogExportTarget(value) {
|
|
50
|
+
if (typeof value === "string") return value;
|
|
51
|
+
if (!value || typeof value !== "object") return "";
|
|
52
|
+
return value.import || value.node || value.default || value.require || "";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function catalogPackageRoots(anchor) {
|
|
56
|
+
let dir;
|
|
57
|
+
try { dir = anchor.startsWith("file:") ? dirname(fileURLToPath(anchor)) : dirname(anchor); } catch { return []; }
|
|
58
|
+
const roots = [];
|
|
59
|
+
for (let count = 0; count < 12; count += 1) {
|
|
60
|
+
roots.push(join(dir, "node_modules", PI_AI_PACKAGE));
|
|
61
|
+
const parent = dirname(dir);
|
|
62
|
+
if (parent === dir) break;
|
|
63
|
+
dir = parent;
|
|
64
|
+
}
|
|
65
|
+
return roots;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function importCatalogFromPackage(root) {
|
|
69
|
+
const packageFile = join(root, "package.json");
|
|
70
|
+
if (!existsSync(packageFile)) return [];
|
|
71
|
+
let packageJson;
|
|
72
|
+
try { packageJson = JSON.parse(readFileSync(packageFile, "utf8")); } catch { return []; }
|
|
73
|
+
const target = catalogExportTarget(packageJson.exports?.["./providers/all"]);
|
|
74
|
+
const candidates = target
|
|
75
|
+
? [resolvePath(root, target)]
|
|
76
|
+
: [join(root, "providers", "all.js"), join(root, "providers", "all.mjs"), join(root, "providers", "all", "index.js")];
|
|
77
|
+
for (const candidate of candidates) {
|
|
78
|
+
try {
|
|
79
|
+
const normalized = normalizeCatalogModule(await import(pathToFileURL(candidate).href));
|
|
80
|
+
if (normalized.length) return normalized;
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
return [];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function normalizeCatalogModule(loaded) {
|
|
87
|
+
const source = loaded?.builtinProviders ? loaded : loaded?.default;
|
|
88
|
+
const list = typeof source?.builtinProviders === "function" ? source.builtinProviders() : [];
|
|
89
|
+
return list.map((entry) => {
|
|
90
|
+
let models = [];
|
|
91
|
+
try {
|
|
92
|
+
const declared = typeof entry?.getModels === "function" ? entry.getModels() : entry?.models || [];
|
|
93
|
+
models = (Array.isArray(declared) ? declared : []).map((model) => ({
|
|
94
|
+
id: model?.id || "",
|
|
95
|
+
baseURL: model?.baseUrl || model?.baseURL || "",
|
|
96
|
+
})).filter((model) => model.id && model.baseURL);
|
|
97
|
+
} catch {}
|
|
98
|
+
return {
|
|
99
|
+
id: entry?.id || "",
|
|
100
|
+
baseURL: entry?.baseUrl || entry?.baseURL || "",
|
|
101
|
+
models,
|
|
102
|
+
};
|
|
103
|
+
}).filter((entry) => entry.id && (entry.baseURL || entry.models.length));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function loadPiAiCatalog() {
|
|
107
|
+
try {
|
|
108
|
+
return normalizeCatalogModule(await import(PI_AI_CATALOG));
|
|
109
|
+
} catch {}
|
|
110
|
+
try {
|
|
111
|
+
const resolved = typeof import.meta.resolve === "function" ? import.meta.resolve(PI_AI_CATALOG) : null;
|
|
112
|
+
if (resolved) return normalizeCatalogModule(await import(resolved));
|
|
113
|
+
} catch {}
|
|
114
|
+
const anchors = [import.meta.url];
|
|
115
|
+
try {
|
|
116
|
+
if (process.argv[1]) anchors.push(pathToFileURL(process.argv[1]).href);
|
|
117
|
+
} catch {}
|
|
118
|
+
for (const anchor of anchors) {
|
|
119
|
+
for (const root of catalogPackageRoots(anchor)) {
|
|
120
|
+
const normalized = await importCatalogFromPackage(root);
|
|
121
|
+
if (normalized.length) return normalized;
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const loaded = createRequire(anchor)(PI_AI_CATALOG);
|
|
125
|
+
const normalized = normalizeCatalogModule(loaded);
|
|
126
|
+
if (normalized.length) return normalized;
|
|
127
|
+
} catch {}
|
|
128
|
+
}
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
|
|
44
132
|
const { BasicCompactionEngine } = await loadBase();
|
|
45
133
|
const { CompactionId, toolPairingBalancedAfter, toolPairingBalancedBefore } = await loadCompaction();
|
|
46
134
|
const { createUserMessage } = await loadLlm();
|
|
@@ -58,6 +146,9 @@ const RECOVER_RAW_BATCH = 1;
|
|
|
58
146
|
const CAPTURE_RETRY_LIMIT = 8;
|
|
59
147
|
const RECOVERY_ACL_REAUTH_LIMIT = 32;
|
|
60
148
|
const SHADOW_WORKER_TIMEOUT_MS = 30000;
|
|
149
|
+
const SHADOW_WORKER_RECOVERY_MS = 60000;
|
|
150
|
+
const PRESTEP_WAIT_TIMEOUT_MS = 3000;
|
|
151
|
+
const SHADOW_WORKER_IDLE_MS = process.platform === "win32" ? 60000 : 500;
|
|
61
152
|
|
|
62
153
|
const shadowWorkers = new Map();
|
|
63
154
|
|
|
@@ -65,17 +156,23 @@ function shadowWorkerFor(root) {
|
|
|
65
156
|
const key = String(root);
|
|
66
157
|
let entry = shadowWorkers.get(key);
|
|
67
158
|
if (entry) return entry;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
159
|
+
// DSH Tauri starts the host with --input-type=module --eval. Passing a
|
|
160
|
+
// filtered execArgv array makes Node re-parse host-only V8 flags such as
|
|
161
|
+
// --max-old-space-size and can throw ERR_WORKER_INVALID_EXEC_ARGV. An eval
|
|
162
|
+
// bootstrap keeps the worker's native argv inheritance and dynamically
|
|
163
|
+
// imports the module URL without re-running the host's eval script.
|
|
164
|
+
const workerURL = new URL("./shadow-save-worker.mjs", import.meta.url).href;
|
|
165
|
+
const workerBootstrap = `import(${JSON.stringify(workerURL)}).catch((error) => { setImmediate(() => { throw error; }); });`;
|
|
166
|
+
const ownerToken = randomBytes(24).toString("hex");
|
|
167
|
+
const worker = new Worker(workerBootstrap, {
|
|
168
|
+
eval: true,
|
|
169
|
+
workerData: { spineWorker: 1, spineOwner: ownerToken, accessFuse: shadowAccessFuseBuffer() },
|
|
74
170
|
});
|
|
75
|
-
entry = { worker, nextId: 1, pending: new Map(), idleTimer: null, retired: false, timedOut: false };
|
|
171
|
+
entry = { worker, root: key, ownerToken, nextId: 1, pending: new Map(), idleTimer: null, recoveryTimer: null, retired: false, timedOut: false };
|
|
76
172
|
const removeEntry = () => {
|
|
77
173
|
if (shadowWorkers.get(key) === entry) shadowWorkers.delete(key);
|
|
78
174
|
};
|
|
175
|
+
entry.removeEntry = removeEntry;
|
|
79
176
|
const scheduleIdleExit = () => {
|
|
80
177
|
if (entry.retired || entry.pending.size || entry.idleTimer) return;
|
|
81
178
|
entry.idleTimer = setTimeout(() => {
|
|
@@ -84,8 +181,9 @@ function shadowWorkerFor(root) {
|
|
|
84
181
|
entry.retired = true;
|
|
85
182
|
removeEntry();
|
|
86
183
|
worker.terminate().catch(() => {});
|
|
87
|
-
},
|
|
184
|
+
}, SHADOW_WORKER_IDLE_MS);
|
|
88
185
|
entry.idleTimer.unref?.();
|
|
186
|
+
worker.unref?.();
|
|
89
187
|
};
|
|
90
188
|
entry.scheduleIdleExit = scheduleIdleExit;
|
|
91
189
|
const fail = (error) => {
|
|
@@ -94,20 +192,32 @@ function shadowWorkerFor(root) {
|
|
|
94
192
|
clearTimeout(entry.idleTimer);
|
|
95
193
|
entry.idleTimer = null;
|
|
96
194
|
}
|
|
195
|
+
if (entry.recoveryTimer) {
|
|
196
|
+
clearTimeout(entry.recoveryTimer);
|
|
197
|
+
entry.recoveryTimer = null;
|
|
198
|
+
}
|
|
97
199
|
for (const { reject, timer } of entry.pending.values()) {
|
|
98
200
|
if (timer) clearTimeout(timer);
|
|
99
201
|
reject(error);
|
|
100
202
|
}
|
|
101
203
|
entry.pending.clear();
|
|
102
204
|
removeEntry();
|
|
103
|
-
worker.terminate()
|
|
205
|
+
worker.terminate()
|
|
206
|
+
.then(() => recoverTimedOutShadowWorker(entry.root, entry.ownerToken))
|
|
207
|
+
.catch(() => {});
|
|
104
208
|
};
|
|
105
209
|
worker.on("message", (message) => {
|
|
106
210
|
const task = entry.pending.get(message?.id);
|
|
107
211
|
if (!task) return;
|
|
108
212
|
if (task.timer) clearTimeout(task.timer);
|
|
109
213
|
entry.pending.delete(message.id);
|
|
110
|
-
if (entry.timedOut && entry.pending.size === 0)
|
|
214
|
+
if (entry.timedOut && entry.pending.size === 0) {
|
|
215
|
+
entry.timedOut = false;
|
|
216
|
+
if (entry.recoveryTimer) {
|
|
217
|
+
clearTimeout(entry.recoveryTimer);
|
|
218
|
+
entry.recoveryTimer = null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
111
221
|
if (message?.ok) {
|
|
112
222
|
task.resolve(message.result);
|
|
113
223
|
scheduleIdleExit();
|
|
@@ -141,6 +251,7 @@ function runShadowWorker(payload) {
|
|
|
141
251
|
if (entry.idleTimer) {
|
|
142
252
|
clearTimeout(entry.idleTimer);
|
|
143
253
|
entry.idleTimer = null;
|
|
254
|
+
entry.worker.ref?.();
|
|
144
255
|
}
|
|
145
256
|
const id = entry.nextId++;
|
|
146
257
|
return new Promise((resolve, reject) => {
|
|
@@ -153,6 +264,27 @@ function runShadowWorker(payload) {
|
|
|
153
264
|
// keep the pending task until the worker naturally releases its lock.
|
|
154
265
|
task.timedOut = true;
|
|
155
266
|
entry.timedOut = true;
|
|
267
|
+
// Let the host exit while a blocked filesystem call drains. A bounded
|
|
268
|
+
// recovery removes the poisoned entry later without killing a worker
|
|
269
|
+
// that may still own a rotation lock.
|
|
270
|
+
if ([...entry.pending.values()].every((pending) => pending.timedOut)) entry.worker.unref?.();
|
|
271
|
+
if (!entry.recoveryTimer) {
|
|
272
|
+
entry.recoveryTimer = setTimeout(() => {
|
|
273
|
+
if (entry.retired) return;
|
|
274
|
+
entry.retired = true;
|
|
275
|
+
entry.timedOut = false;
|
|
276
|
+
for (const pending of entry.pending.values()) {
|
|
277
|
+
if (pending.timer) clearTimeout(pending.timer);
|
|
278
|
+
pending.reject(Object.assign(new Error("spine: shadow worker recovery expired"), { code: "ESHADOWWORKER" }));
|
|
279
|
+
}
|
|
280
|
+
entry.pending.clear();
|
|
281
|
+
entry.removeEntry?.();
|
|
282
|
+
entry.worker.terminate()
|
|
283
|
+
.then(() => recoverTimedOutShadowWorker(entry.root, entry.ownerToken))
|
|
284
|
+
.catch(() => {});
|
|
285
|
+
}, SHADOW_WORKER_RECOVERY_MS);
|
|
286
|
+
entry.recoveryTimer.unref?.();
|
|
287
|
+
}
|
|
156
288
|
reject(error);
|
|
157
289
|
}, SHADOW_WORKER_TIMEOUT_MS);
|
|
158
290
|
timer.unref?.();
|
|
@@ -184,7 +316,9 @@ function failShadowWorker(entry, error) {
|
|
|
184
316
|
for (const [key, value] of shadowWorkers) {
|
|
185
317
|
if (value === entry) shadowWorkers.delete(key);
|
|
186
318
|
}
|
|
187
|
-
entry.worker.terminate()
|
|
319
|
+
entry.worker.terminate()
|
|
320
|
+
.then(() => recoverTimedOutShadowWorker(entry.root, entry.ownerToken))
|
|
321
|
+
.catch(() => {});
|
|
188
322
|
}
|
|
189
323
|
|
|
190
324
|
function recoveryRetryable(record, dir, toolCallId) {
|
|
@@ -262,6 +396,31 @@ function latestCompletedTurnEnd(events) {
|
|
|
262
396
|
return found;
|
|
263
397
|
}
|
|
264
398
|
|
|
399
|
+
function latestTurnStart(events) {
|
|
400
|
+
let found = null;
|
|
401
|
+
for (const event of events || []) {
|
|
402
|
+
if (event?.type === "turn/start") found = event;
|
|
403
|
+
}
|
|
404
|
+
return found;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function turnStartForBoundary(events, boundary) {
|
|
408
|
+
const list = events || [];
|
|
409
|
+
const boundaryTurn = boundary?.data?.turn;
|
|
410
|
+
const boundaryIndex = boundary?.seq == null
|
|
411
|
+
? -1
|
|
412
|
+
: list.findIndex((event) => event?.seq === boundary.seq);
|
|
413
|
+
let found = null;
|
|
414
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
415
|
+
if (boundaryIndex >= 0 && index >= boundaryIndex) break;
|
|
416
|
+
const event = list[index];
|
|
417
|
+
if (event?.type !== "turn/start") continue;
|
|
418
|
+
if (boundaryTurn !== undefined && event?.data?.turn !== boundaryTurn) continue;
|
|
419
|
+
found = event;
|
|
420
|
+
}
|
|
421
|
+
return found;
|
|
422
|
+
}
|
|
423
|
+
|
|
265
424
|
function maintenanceOperationSignal(agentSignal, timeoutSignal) {
|
|
266
425
|
const controller = new AbortController();
|
|
267
426
|
const forwardAgent = () => {
|
|
@@ -286,10 +445,16 @@ function maintenanceOperationSignal(agentSignal, timeoutSignal) {
|
|
|
286
445
|
return controller.signal;
|
|
287
446
|
}
|
|
288
447
|
|
|
289
|
-
function spineCheckpointSource(compactionId) {
|
|
448
|
+
function spineCheckpointSource(compactionId, rawPaths = []) {
|
|
290
449
|
// 不用 compact-checkpoint。官方压缩会把那种节点当成上一版摘要再摘一次。
|
|
291
450
|
// Do not use compact-checkpoint. Official compaction treats that kind as a prior summary and shrinks it again.
|
|
292
|
-
|
|
451
|
+
const rawNames = [...new Set((rawPaths || []).map((path) => basename(String(path || "")))
|
|
452
|
+
.filter((name) => name && name !== "." && name !== ".."))];
|
|
453
|
+
return Object.freeze({
|
|
454
|
+
kind: SPINE_SOURCE_KIND,
|
|
455
|
+
compactionId,
|
|
456
|
+
...(rawNames.length ? { rawNames } : {}),
|
|
457
|
+
});
|
|
293
458
|
}
|
|
294
459
|
|
|
295
460
|
function eventRole(session, seq) {
|
|
@@ -441,7 +606,7 @@ export { saveShadowImpl as saveShadow };
|
|
|
441
606
|
// Pick one span from the tail, as in 1.0.6. Do not cross a genuine user message.
|
|
442
607
|
// Tool pairs stay balanced. The newest settings.keepRounds finished rounds stay verbatim.
|
|
443
608
|
// Under settings.chunkMin, return null.
|
|
444
|
-
function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}) {
|
|
609
|
+
export function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}) {
|
|
445
610
|
const settings = context.settings ?? readSettings();
|
|
446
611
|
const decision = jobCutDecision(context.jobs || []);
|
|
447
612
|
if (!decision.cut) return null;
|
|
@@ -464,7 +629,6 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
|
|
|
464
629
|
}
|
|
465
630
|
if (floorCard >= 0 && end <= floorCard) return null;
|
|
466
631
|
while (end >= first && !cutOk(toolPairingBalancedAfter, session, nodes[end])) end -= 1;
|
|
467
|
-
let keptTokens = 0;
|
|
468
632
|
const visible = [];
|
|
469
633
|
for (let index = first; index <= end; index += 1) {
|
|
470
634
|
const event = session.eventAt(nodes[index]);
|
|
@@ -573,13 +737,8 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
|
|
|
573
737
|
drain: context.drain === true,
|
|
574
738
|
urgentTokens: URGENT_TOKENS,
|
|
575
739
|
};
|
|
576
|
-
let usedLongCut = false;
|
|
577
|
-
let picked = null;
|
|
578
740
|
let longPicked = null;
|
|
579
741
|
const forceLongRead = context.forceLongRead === true;
|
|
580
|
-
const fallbackWithoutLongRead = () => context.disableLongRead
|
|
581
|
-
? null
|
|
582
|
-
: selectNewestChunk(session, measurement, key, { ...context, disableLongRead: true });
|
|
583
742
|
if (longSpan) {
|
|
584
743
|
const candidate = cutLongReadRound(items, longSpan.start, longSpan.end, cutOptions);
|
|
585
744
|
if (candidate && candidate.start >= longSpan.start && candidate.end <= longSpan.end) {
|
|
@@ -590,118 +749,122 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
|
|
|
590
749
|
if (end >= first && !isCheckpoint(session, nodes[end])) {
|
|
591
750
|
ordinaryPicked = selectCutIndexes(items, cutOptions);
|
|
592
751
|
}
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
752
|
+
const candidates = [];
|
|
753
|
+
const addCandidate = (candidate, usedLongCut) => {
|
|
754
|
+
if (!candidate || candidates.some((item) => item.candidate === candidate)) return;
|
|
755
|
+
candidates.push({ candidate, usedLongCut });
|
|
756
|
+
};
|
|
757
|
+
if (forceLongRead) {
|
|
758
|
+
addCandidate(longPicked, true);
|
|
596
759
|
} else if (longPicked && ordinaryPicked) {
|
|
597
760
|
const longTokens = longPicked.tokens || 0;
|
|
598
761
|
const ordinaryTokens = ordinaryPicked.tokens || 0;
|
|
599
762
|
if (ordinaryTokens >= longTokens) {
|
|
600
|
-
|
|
763
|
+
addCandidate(ordinaryPicked, false);
|
|
764
|
+
addCandidate(longPicked, true);
|
|
601
765
|
} else {
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
}
|
|
605
|
-
} else
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
766
|
+
addCandidate(longPicked, true);
|
|
767
|
+
addCandidate(ordinaryPicked, false);
|
|
768
|
+
}
|
|
769
|
+
} else {
|
|
770
|
+
addCandidate(ordinaryPicked, false);
|
|
771
|
+
addCandidate(longPicked, true);
|
|
772
|
+
}
|
|
773
|
+
if (!candidates.length) return null;
|
|
774
|
+
|
|
775
|
+
const evaluateCandidate = ({ candidate, usedLongCut }) => {
|
|
776
|
+
const picked = { ...candidate };
|
|
777
|
+
if (picked.pointerOnly) {
|
|
778
|
+
const result = session.eventAt(nodes[picked.end]);
|
|
779
|
+
const id = result?.data?.message?.toolCallId;
|
|
780
|
+
let pairStart = -1;
|
|
781
|
+
if (id) {
|
|
782
|
+
for (let index = picked.end - 1; index >= 0; index -= 1) {
|
|
783
|
+
const blocks = session.eventAt(nodes[index])?.data?.message?.content || [];
|
|
784
|
+
if (blocks.some((block) => block?.type === "tool-call" && block.id === id)) {
|
|
785
|
+
pairStart = index;
|
|
786
|
+
break;
|
|
787
|
+
}
|
|
622
788
|
}
|
|
623
789
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
//
|
|
680
|
-
//
|
|
681
|
-
//
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
const
|
|
699
|
-
if (
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
let prefix = 0;
|
|
703
|
-
for (let index = 0; index < start; index += 1) prefix += priced[index].tokens;
|
|
704
|
-
return { start: nodes[start], end: nodes[end], tokens, after, keptTokens, card, prefix };
|
|
790
|
+
if (pairStart < 0) return null;
|
|
791
|
+
if (usedLongCut && pairStart < longSpan.start) return null;
|
|
792
|
+
if (!pointerSpanAllowed(items, pairStart, picked.end, context.engine || "cloud")) return null;
|
|
793
|
+
if (!cutOk(toolPairingBalancedBefore, session, nodes[pairStart])) return null;
|
|
794
|
+
picked.start = pairStart;
|
|
795
|
+
}
|
|
796
|
+
if (usedLongCut && (picked.start < longSpan.start || picked.end > longSpan.end)) return null;
|
|
797
|
+
|
|
798
|
+
// 1.0.6 selected the newest legal end, then grew the cut left until the
|
|
799
|
+
// 32K rail, a user/checkpoint, an unbalanced tool pair, or an incomplete
|
|
800
|
+
// card stopped it. Returning the first >= CHUNK_MIN phase leaves a tiny
|
|
801
|
+
// 1.9K tail in a long drain and defeats the low-water goal. Restore that
|
|
802
|
+
// core selection rule while keeping the newer source and checkpoint guards.
|
|
803
|
+
if (!picked.pointerOnly) {
|
|
804
|
+
let expandedStart = picked.start;
|
|
805
|
+
let expandedTokens = items.slice(expandedStart, picked.end + 1)
|
|
806
|
+
.reduce((sum, item) => sum + (item.tokens || 0), 0);
|
|
807
|
+
while (expandedStart > first) {
|
|
808
|
+
const previous = expandedStart - 1;
|
|
809
|
+
if (isCheckpoint(session, nodes[previous])) break;
|
|
810
|
+
if (classifications[previous].isGenuineUserBoundary) break;
|
|
811
|
+
if (usedLongCut && previous < longSpan.start) break;
|
|
812
|
+
const nextTokens = expandedTokens + (priced[previous].tokens || 0);
|
|
813
|
+
if (nextTokens > settings.chunkMax) break;
|
|
814
|
+
const trialPieces = spanPieces(previous, picked.end);
|
|
815
|
+
const trialCard = buildCard(
|
|
816
|
+
trialPieces.map((piece) => piece.text).join("\n"),
|
|
817
|
+
liveText(previous, picked.end),
|
|
818
|
+
trialPieces,
|
|
819
|
+
extras,
|
|
820
|
+
);
|
|
821
|
+
if (trialCard.ok !== true) break;
|
|
822
|
+
expandedStart = previous;
|
|
823
|
+
expandedTokens = nextTokens;
|
|
824
|
+
}
|
|
825
|
+
while (expandedStart <= picked.end &&
|
|
826
|
+
!cutOk(toolPairingBalancedBefore, session, nodes[expandedStart])) {
|
|
827
|
+
expandedTokens -= priced[expandedStart].tokens || 0;
|
|
828
|
+
expandedStart += 1;
|
|
829
|
+
}
|
|
830
|
+
if (expandedStart > picked.end) return null;
|
|
831
|
+
picked.start = expandedStart;
|
|
832
|
+
}
|
|
833
|
+
const start = picked.start;
|
|
834
|
+
const candidateEnd = picked.end;
|
|
835
|
+
const tokens = items.slice(start, candidateEnd + 1).reduce((sum, item) => sum + item.tokens, 0);
|
|
836
|
+
const pieces = spanPieces(start, candidateEnd);
|
|
837
|
+
if (picked.pointerOnly && pieces.some((piece) => piece.role === "tool" && isToolFailure(piece.text, piece.isError))) return null;
|
|
838
|
+
let card = picked.pointerOnly
|
|
839
|
+
? { ok: true, text: pointerOnlyText(pieces), hardLines: [], missing: [], needsBackup: false, rawPaths: [] }
|
|
840
|
+
: buildCard(pieces.map((piece) => piece.text).join("\n"), liveText(start, candidateEnd), pieces, extras);
|
|
841
|
+
if (card.ok !== true) return null;
|
|
842
|
+
if (!cutOk(toolPairingBalancedAfter, session, nodes[candidateEnd])) return null;
|
|
843
|
+
let after = 0;
|
|
844
|
+
for (let index = candidateEnd + 1; index < priced.length; index += 1) after += priced[index].tokens;
|
|
845
|
+
// `keptTokens` must describe retained rounds to the right of the actual
|
|
846
|
+
// cut. A long-read cut can be newer than the ordinary rounds selected above;
|
|
847
|
+
// counting those older rounds made `tailBeyondKept` negative and disabled
|
|
848
|
+
// the tail guard.
|
|
849
|
+
let candidateKeptTokens = 0;
|
|
850
|
+
for (const round of rounds) {
|
|
851
|
+
const roundStart = visible[round.start]?.index;
|
|
852
|
+
const roundEnd = visible[round.end]?.index;
|
|
853
|
+
if (!Number.isInteger(roundStart) || !Number.isInteger(roundEnd) || roundStart <= candidateEnd) continue;
|
|
854
|
+
for (let index = roundStart; index <= roundEnd; index += 1) candidateKeptTokens += priced[index].tokens;
|
|
855
|
+
}
|
|
856
|
+
let prefix = 0;
|
|
857
|
+
for (let index = 0; index < start; index += 1) prefix += priced[index].tokens;
|
|
858
|
+
if (!card.text.includes("不是备份文件路径")) card = { ...card, text: `${card.text}\n序号是本会话日志里的事件号,不是备份文件路径。` };
|
|
859
|
+
card = attachBackupHint(card, freshShadowFile("cut", key));
|
|
860
|
+
return { start: nodes[start], end: nodes[candidateEnd], tokens, after, keptTokens: candidateKeptTokens, card, prefix };
|
|
861
|
+
};
|
|
862
|
+
|
|
863
|
+
for (const candidate of candidates) {
|
|
864
|
+
const result = evaluateCandidate(candidate);
|
|
865
|
+
if (result) return result;
|
|
866
|
+
}
|
|
867
|
+
return null;
|
|
705
868
|
}
|
|
706
869
|
|
|
707
870
|
export const BIG_GATE = DEFAULTS.bigGate;
|
|
@@ -728,11 +891,21 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
728
891
|
retryableCaptureSeeded = new Set();
|
|
729
892
|
captureRecoveryHolds = new Map();
|
|
730
893
|
pruneGuarded = false;
|
|
894
|
+
catalogCache = [];
|
|
895
|
+
catalogPromise = null;
|
|
731
896
|
|
|
732
897
|
constructor(ctx, config, resolvedConfig) {
|
|
733
898
|
if (process.env.SPINE_ENGINE_FAIL === "construct") throw new Error("spine: constructor refused");
|
|
734
899
|
super(ctx, resolvedConfig ?? engineConfig(config));
|
|
735
900
|
this.persistCapture = true;
|
|
901
|
+
this.catalogPromise = loadPiAiCatalog().then((catalog) => {
|
|
902
|
+
this.catalogCache = catalog;
|
|
903
|
+
if (!catalog.length) this.catalogPromise = null;
|
|
904
|
+
return catalog;
|
|
905
|
+
}).catch(() => {
|
|
906
|
+
this.catalogPromise = null;
|
|
907
|
+
return [];
|
|
908
|
+
});
|
|
736
909
|
if (process.env.SPINE_ENGINE_FAIL === "after-super") throw new Error("spine: after super");
|
|
737
910
|
this.liveConfig = config;
|
|
738
911
|
try {
|
|
@@ -806,7 +979,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
806
979
|
ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
|
|
807
980
|
await this.waitForMaintenance(agent, signal);
|
|
808
981
|
return typeof next === "function" ? next() : undefined;
|
|
809
|
-
});
|
|
982
|
+
}, { prepend: true });
|
|
810
983
|
ctx.on("agent/turn-stopping", async ({ agent, signal }) => {
|
|
811
984
|
await this.runTurnStoppingMaintenance(agent, signal);
|
|
812
985
|
});
|
|
@@ -822,6 +995,53 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
822
995
|
return peers.length > 0;
|
|
823
996
|
}
|
|
824
997
|
|
|
998
|
+
recordDecision(state, record = {}) {
|
|
999
|
+
const key = state?.key || DEFAULT_KEY;
|
|
1000
|
+
const prefix = `${key}\0`;
|
|
1001
|
+
const session = state?.liveAgent?.session;
|
|
1002
|
+
this.reconcileCardRawPaths(state, session);
|
|
1003
|
+
const protectPaths = [];
|
|
1004
|
+
if (state?.lastCardPath) protectPaths.push(state.lastCardPath);
|
|
1005
|
+
for (const rawPath of state?.cardRawPaths || []) {
|
|
1006
|
+
if (!rawPath) continue;
|
|
1007
|
+
protectPaths.push(rawPath, `${rawPath}.meta.json`);
|
|
1008
|
+
}
|
|
1009
|
+
const liveIds = new Set();
|
|
1010
|
+
for (const seq of session?.surface?.nodes || []) {
|
|
1011
|
+
const event = session.eventAt?.(seq);
|
|
1012
|
+
const id = event?.type === "tool/result" ? event.data?.message?.toolCallId : "";
|
|
1013
|
+
if (id) liveIds.add(id);
|
|
1014
|
+
}
|
|
1015
|
+
for (const [rawKey, raw] of this.rawSeen || []) {
|
|
1016
|
+
if (!rawKey.startsWith(prefix) || !raw?.path || !liveIds.has(rawKey.slice(prefix.length))) continue;
|
|
1017
|
+
protectPaths.push(raw.path, `${raw.path}.meta.json`);
|
|
1018
|
+
}
|
|
1019
|
+
appendDecision(shadowDirectory(), { sid: key, ...record }, { protectPaths });
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
reconcileCardRawPaths(state, session) {
|
|
1023
|
+
if (!state || !session?.surface?.nodes) return;
|
|
1024
|
+
const root = sessionDir(shadowDirectory(), state.key || DEFAULT_KEY);
|
|
1025
|
+
const paths = [];
|
|
1026
|
+
let sawSpineCard = false;
|
|
1027
|
+
for (const seq of session.surface.nodes) {
|
|
1028
|
+
const event = session.eventAt?.(seq);
|
|
1029
|
+
const source = event?.type === "user/message" ? event.data?.source : null;
|
|
1030
|
+
if (source?.kind !== SPINE_SOURCE_KIND) continue;
|
|
1031
|
+
sawSpineCard = true;
|
|
1032
|
+
for (const name of Array.isArray(source.rawNames) ? source.rawNames : []) {
|
|
1033
|
+
if (typeof name !== "string" || !name || name !== basename(name)) continue;
|
|
1034
|
+
paths.push(join(root, name));
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
if (sawSpineCard) {
|
|
1038
|
+
state.cardRawPaths = [...new Set(paths)];
|
|
1039
|
+
state.cardRawPathsStructured = true;
|
|
1040
|
+
} else if (state.cardRawPathsStructured) {
|
|
1041
|
+
state.cardRawPaths = [];
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
|
|
825
1045
|
ownedSignal(signal) {
|
|
826
1046
|
const controller = new AbortController();
|
|
827
1047
|
const dispose = this.ctx.on("internal/status", () => {
|
|
@@ -854,10 +1074,19 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
854
1074
|
turnBase: null,
|
|
855
1075
|
maxTurnGrowth: 0,
|
|
856
1076
|
maintenanceJob: null,
|
|
1077
|
+
retryWaitingJob: null,
|
|
1078
|
+
maintenanceAbort: null,
|
|
1079
|
+
maintenanceOwner: null,
|
|
857
1080
|
turnEndScheduled: false,
|
|
858
1081
|
turnEndPending: false,
|
|
859
1082
|
turnEndSeq: -1,
|
|
860
1083
|
lastMaintenanceTurnEndSeq: -1,
|
|
1084
|
+
lastStoppingTurnEndSeq: -1,
|
|
1085
|
+
lastStoppingTurnStartSeq: -1,
|
|
1086
|
+
rawCutRetryAttempts: 0,
|
|
1087
|
+
lastCardPath: "",
|
|
1088
|
+
cardRawPaths: [],
|
|
1089
|
+
cardRawPathsStructured: false,
|
|
861
1090
|
};
|
|
862
1091
|
this.sessionState.set(key, state);
|
|
863
1092
|
if (this.sessionState.size > MAX_TRACKED_SESSIONS) {
|
|
@@ -883,16 +1112,37 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
883
1112
|
return;
|
|
884
1113
|
}
|
|
885
1114
|
if (state.turnEndSeq <= state.lastMaintenanceTurnEndSeq) return;
|
|
1115
|
+
const boundary = state.turnEndEvent || latestCompletedTurnEnd(events);
|
|
1116
|
+
const boundaryStartSeq = turnStartForBoundary(events, boundary)?.seq;
|
|
1117
|
+
const activeStartSeq = boundaryStartSeq ?? latestTurnStart(events)?.seq;
|
|
1118
|
+
const sameStoppingTurn = Number.isInteger(state.lastStoppingTurnStartSeq) &&
|
|
1119
|
+
state.lastStoppingTurnStartSeq >= 0 && Number.isInteger(activeStartSeq)
|
|
1120
|
+
? state.lastStoppingTurnStartSeq === activeStartSeq
|
|
1121
|
+
: state.lastStoppingTurnEndSeq >= 0 && state.turnEndSeq === state.lastStoppingTurnEndSeq;
|
|
1122
|
+
if (state.lastStoppingTurnStartSeq >= 0 && Number.isInteger(activeStartSeq) && !sameStoppingTurn) {
|
|
1123
|
+
state.lastStoppingTurnStartSeq = -1;
|
|
1124
|
+
state.lastStoppingTurnEndSeq = -1;
|
|
1125
|
+
}
|
|
1126
|
+
if (sameStoppingTurn) {
|
|
1127
|
+
state.lastMaintenanceTurnEndSeq = state.turnEndSeq;
|
|
1128
|
+
state.lastStoppingTurnStartSeq = -1;
|
|
1129
|
+
state.lastStoppingTurnEndSeq = -1;
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
886
1132
|
if (state.turnEndSeq > state.lastMaintenanceTurnEndSeq) {
|
|
887
1133
|
state.lastMaintenanceTurnEndSeq = state.turnEndSeq;
|
|
888
1134
|
}
|
|
889
1135
|
state.warming = true;
|
|
890
1136
|
let job;
|
|
891
|
-
job =
|
|
1137
|
+
job = (async () => {
|
|
1138
|
+
await null;
|
|
1139
|
+
return this.finishTurn(agent, events, { deferCapture: true });
|
|
1140
|
+
})()
|
|
892
1141
|
.catch((error) => noteShadowWarning(this.ctx?.logger, error))
|
|
893
1142
|
.finally(() => {
|
|
894
1143
|
if (!state.pendingMaintenance) state.warming = false;
|
|
895
1144
|
if (state.maintenanceJob === job) state.maintenanceJob = null;
|
|
1145
|
+
if (state.maintenanceAbort) state.maintenanceAbort = null;
|
|
896
1146
|
this.pendingCuts.delete(job);
|
|
897
1147
|
if (state.turnEndPending && !state.warming) {
|
|
898
1148
|
state.turnEndPending = false;
|
|
@@ -911,25 +1161,72 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
911
1161
|
return;
|
|
912
1162
|
}
|
|
913
1163
|
state.warming = true;
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
await
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
1164
|
+
const owner = {};
|
|
1165
|
+
const maintenanceAbort = new AbortController();
|
|
1166
|
+
state.maintenanceOwner = owner;
|
|
1167
|
+
state.maintenanceAbort = maintenanceAbort;
|
|
1168
|
+
const forwardAbort = () => {
|
|
1169
|
+
if (!maintenanceAbort.signal.aborted) maintenanceAbort.abort(signal?.reason);
|
|
1170
|
+
};
|
|
1171
|
+
signal?.addEventListener("abort", forwardAbort, { once: true });
|
|
1172
|
+
if (signal?.aborted) forwardAbort();
|
|
1173
|
+
let job;
|
|
1174
|
+
job = (async () => {
|
|
1175
|
+
await null;
|
|
1176
|
+
try {
|
|
1177
|
+
const settings = readSettings(this.liveConfig);
|
|
1178
|
+
const events = agent.session.snapshotEvents();
|
|
1179
|
+
const stoppingEnd = latestCompletedTurnEnd(events);
|
|
1180
|
+
const stoppingSeq = stoppingEnd?.seq;
|
|
1181
|
+
const stoppingStartSeq = (turnStartForBoundary(events, stoppingEnd) || latestTurnStart(events))?.seq;
|
|
1182
|
+
if (Number.isInteger(stoppingSeq)) {
|
|
1183
|
+
state.turnEndSeq = Number.isInteger(state.turnEndSeq) ? Math.max(state.turnEndSeq, stoppingSeq) : stoppingSeq;
|
|
1184
|
+
state.turnEndEvent = stoppingEnd;
|
|
1185
|
+
}
|
|
1186
|
+
let catchup = { finished: true, progressed: false, retryRequested: false };
|
|
1187
|
+
if (events.length > CAPTURE_EVENT_BATCH) {
|
|
1188
|
+
catchup = this.scheduleCaptureCatchup(agent, events, settings, { freezeSnapshot: true });
|
|
1189
|
+
} else {
|
|
1190
|
+
await this.flushPendingCaptures(agent.session);
|
|
1191
|
+
this.captureNew(agent.session, events, settings);
|
|
1192
|
+
}
|
|
1193
|
+
if (catchup?.promise && !catchup.finished) await catchup.promise;
|
|
1194
|
+
if (maintenanceAbort.signal.aborted) return false;
|
|
1195
|
+
await this.flushPendingCaptures(agent.session);
|
|
1196
|
+
if (maintenanceAbort.signal.aborted) return false;
|
|
1197
|
+
const completed = await this.finishTurn(agent, events, { maintenanceRetry: true, skipCapture: true });
|
|
1198
|
+
if (completed === true && (stoppingSeq !== undefined || stoppingStartSeq !== undefined)) {
|
|
1199
|
+
state.lastStoppingTurnEndSeq = stoppingSeq ?? -1;
|
|
1200
|
+
state.lastStoppingTurnStartSeq = stoppingStartSeq ?? -1;
|
|
1201
|
+
}
|
|
1202
|
+
} finally {
|
|
1203
|
+
signal?.removeEventListener("abort", forwardAbort);
|
|
1204
|
+
this.pendingCuts.delete(job);
|
|
1205
|
+
if (state.maintenanceOwner === owner) {
|
|
1206
|
+
state.warming = false;
|
|
1207
|
+
state.pendingMaintenance = false;
|
|
1208
|
+
state.maintenanceAbort = null;
|
|
1209
|
+
state.maintenanceOwner = null;
|
|
1210
|
+
if (state.maintenanceJob === job) state.maintenanceJob = null;
|
|
1211
|
+
if (state.turnEndPending) {
|
|
1212
|
+
state.turnEndPending = false;
|
|
1213
|
+
this.scheduleTurnEndMaintenance(agent, state.turnEndSeq);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
932
1216
|
}
|
|
1217
|
+
})();
|
|
1218
|
+
state.maintenanceJob = job;
|
|
1219
|
+
this.pendingCuts.add(job);
|
|
1220
|
+
if (!signal) await job;
|
|
1221
|
+
else {
|
|
1222
|
+
let abort;
|
|
1223
|
+
const aborted = new Promise((resolve) => {
|
|
1224
|
+
abort = () => resolve();
|
|
1225
|
+
if (signal.aborted) resolve();
|
|
1226
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
1227
|
+
});
|
|
1228
|
+
try { await Promise.race([job, aborted]); }
|
|
1229
|
+
finally { signal.removeEventListener("abort", abort); }
|
|
933
1230
|
}
|
|
934
1231
|
}
|
|
935
1232
|
|
|
@@ -968,24 +1265,58 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
968
1265
|
|
|
969
1266
|
async waitForMaintenance(agent, signal) {
|
|
970
1267
|
const state = this.stateFor(agent);
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
const
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
1268
|
+
const timeoutMs = Number.isFinite(this.prestepWaitTimeoutMs)
|
|
1269
|
+
? Math.max(1, this.prestepWaitTimeoutMs)
|
|
1270
|
+
: PRESTEP_WAIT_TIMEOUT_MS;
|
|
1271
|
+
const timeoutController = new AbortController();
|
|
1272
|
+
const timeoutTimer = setTimeout(() => timeoutController.abort({ kind: "prestep-timeout" }), timeoutMs);
|
|
1273
|
+
try {
|
|
1274
|
+
const waitSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
|
1275
|
+
while (!waitSignal.aborted) {
|
|
1276
|
+
const jobs = [];
|
|
1277
|
+
if (state.maintenanceJob) jobs.push(state.maintenanceJob);
|
|
1278
|
+
const catchup = this.pendingCatchups.get(state.key);
|
|
1279
|
+
if (catchup?.promise) jobs.push(catchup.promise);
|
|
1280
|
+
if (!jobs.length) {
|
|
1281
|
+
if (!(state.pendingMaintenance || state.warming || state.retryScheduled)) break;
|
|
1282
|
+
await new Promise((resolve) => scheduleImmediate(resolve));
|
|
1283
|
+
if (timeoutController.signal.aborted && !signal?.aborted) {
|
|
1284
|
+
state.maintenanceAbort?.abort({ kind: "prestep-timeout" });
|
|
1285
|
+
if (Number.isInteger(state.turnEndSeq)) {
|
|
1286
|
+
state.lastMaintenanceTurnEndSeq = state.turnEndSeq - 1;
|
|
1287
|
+
state.turnEndPending = true;
|
|
1288
|
+
this.scheduleTurnEndMaintenance(agent, state.turnEndSeq, state.turnEndEvent);
|
|
1289
|
+
}
|
|
1290
|
+
this.recordDecision(state, { phase: "prestep", result: "timeout", timeoutMs });
|
|
1291
|
+
this.ctx.logger?.warn?.(`spine: maintenance wait exceeded ${timeoutMs}ms; letting provider request continue`);
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
continue;
|
|
1295
|
+
}
|
|
1296
|
+
const settled = Promise.allSettled(jobs);
|
|
1297
|
+
let abort;
|
|
1298
|
+
const aborted = new Promise((resolve) => {
|
|
1299
|
+
abort = () => resolve();
|
|
1300
|
+
waitSignal.addEventListener("abort", abort, { once: true });
|
|
1301
|
+
});
|
|
1302
|
+
await Promise.race([settled, aborted]);
|
|
1303
|
+
waitSignal.removeEventListener("abort", abort);
|
|
1304
|
+
if (!waitSignal.aborted) await new Promise((resolve) => scheduleImmediate(resolve));
|
|
1305
|
+
if (timeoutController.signal.aborted && !signal?.aborted) {
|
|
1306
|
+
state.maintenanceAbort?.abort({ kind: "prestep-timeout" });
|
|
1307
|
+
if (Number.isInteger(state.turnEndSeq)) {
|
|
1308
|
+
state.lastMaintenanceTurnEndSeq = state.turnEndSeq - 1;
|
|
1309
|
+
state.turnEndPending = true;
|
|
1310
|
+
this.scheduleTurnEndMaintenance(agent, state.turnEndSeq, state.turnEndEvent);
|
|
1311
|
+
}
|
|
1312
|
+
this.recordDecision(state, { phase: "prestep", result: "timeout", timeoutMs });
|
|
1313
|
+
this.ctx.logger?.warn?.(`spine: maintenance wait exceeded ${timeoutMs}ms; letting provider request continue`);
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
if (signal?.aborted) return;
|
|
981
1317
|
}
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
abort = () => resolve();
|
|
985
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
986
|
-
});
|
|
987
|
-
await Promise.race([settled, aborted]);
|
|
988
|
-
signal.removeEventListener("abort", abort);
|
|
1318
|
+
} finally {
|
|
1319
|
+
clearTimeout(timeoutTimer);
|
|
989
1320
|
}
|
|
990
1321
|
}
|
|
991
1322
|
|
|
@@ -1013,6 +1344,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1013
1344
|
task.events = events;
|
|
1014
1345
|
task.settings = settings;
|
|
1015
1346
|
task.freezeSnapshot ||= options.freezeSnapshot === true;
|
|
1347
|
+
task.maintenanceRequested ||= options.maintenanceRequested === true;
|
|
1016
1348
|
return task;
|
|
1017
1349
|
}
|
|
1018
1350
|
let resolve;
|
|
@@ -1110,7 +1442,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1110
1442
|
const previousMax = this.captureRetryStats?.get(task.key) || 0;
|
|
1111
1443
|
if (task.captureRetryAttempts > previousMax) this.captureRetryStats.set(task.key, task.captureRetryAttempts);
|
|
1112
1444
|
if (task.captureRetryAttempts >= CAPTURE_RETRY_LIMIT) {
|
|
1113
|
-
|
|
1445
|
+
task.phase = "visible";
|
|
1446
|
+
task.recoverIndex = 0;
|
|
1447
|
+
task.visibleIds = [...new Set(this.surfaceToolIds(task.session))];
|
|
1448
|
+
this.queueCaptureCatchup(task);
|
|
1114
1449
|
return;
|
|
1115
1450
|
}
|
|
1116
1451
|
this.queueCaptureRetry(task);
|
|
@@ -1119,7 +1454,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1119
1454
|
if (result.blocked) {
|
|
1120
1455
|
task.captureBlocked = true;
|
|
1121
1456
|
task.retryRequested = true;
|
|
1122
|
-
|
|
1457
|
+
task.phase = "visible";
|
|
1458
|
+
task.recoverIndex = 0;
|
|
1459
|
+
task.visibleIds = [...new Set(this.surfaceToolIds(task.session))];
|
|
1460
|
+
this.queueCaptureCatchup(task);
|
|
1123
1461
|
return;
|
|
1124
1462
|
}
|
|
1125
1463
|
if (result.progressed) task.captureRetryAttempts = 0;
|
|
@@ -1155,44 +1493,107 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1155
1493
|
task.resolve();
|
|
1156
1494
|
if (task.failed) {
|
|
1157
1495
|
const state = this.stateFor(task.agent);
|
|
1158
|
-
state.
|
|
1159
|
-
|
|
1496
|
+
if (state.maintenanceOwner) {
|
|
1497
|
+
// Keep a stopping owner's lifecycle barrier until its finally block;
|
|
1498
|
+
// otherwise a failed catch-up can overlap the next maintenance job.
|
|
1499
|
+
state.pendingMaintenance = true;
|
|
1500
|
+
state.warming = true;
|
|
1501
|
+
state.turnEndPending = true;
|
|
1502
|
+
} else {
|
|
1503
|
+
state.pendingMaintenance = false;
|
|
1504
|
+
state.warming = false;
|
|
1505
|
+
}
|
|
1160
1506
|
return;
|
|
1161
1507
|
}
|
|
1508
|
+
const state = this.stateFor(task.agent);
|
|
1162
1509
|
if (!this.standDown?.() &&
|
|
1163
1510
|
(task.captureBlocked || task.retryRequested || task.maintenanceRequested)) {
|
|
1164
|
-
const state = this.stateFor(task.agent);
|
|
1165
1511
|
// Keep the lifecycle visibly warming until the scheduled retry has
|
|
1166
1512
|
// completed. Real idle hooks use this state as their await barrier.
|
|
1167
1513
|
state.pendingMaintenance = true;
|
|
1168
1514
|
state.warming = true;
|
|
1169
|
-
|
|
1515
|
+
if (state.maintenanceOwner) {
|
|
1516
|
+
// A turn-stopping owner is already going to finish this catch-up and
|
|
1517
|
+
// run maintenance. Queue the boundary behind that owner instead of
|
|
1518
|
+
// replacing its abort controller with a concurrent retry job.
|
|
1519
|
+
state.turnEndPending = true;
|
|
1520
|
+
} else {
|
|
1521
|
+
this.scheduleMaintenanceRetry(task.agent);
|
|
1522
|
+
}
|
|
1523
|
+
} else if (this.standDown?.() || !latestTurnCompleted(task.agent.session.snapshotEvents?.() || [])) {
|
|
1524
|
+
// A catch-up can finish after the next turn has already started. Do not
|
|
1525
|
+
// leave the session permanently warming; the next persisted turn/end
|
|
1526
|
+
// must be allowed to schedule a fresh maintenance pass.
|
|
1527
|
+
if (state.maintenanceOwner) {
|
|
1528
|
+
state.turnEndPending = true;
|
|
1529
|
+
} else {
|
|
1530
|
+
state.pendingMaintenance = false;
|
|
1531
|
+
state.warming = false;
|
|
1532
|
+
}
|
|
1533
|
+
} else if (!state.maintenanceOwner) {
|
|
1534
|
+
// A reused catch-up can finish without a retry request after a newer
|
|
1535
|
+
// maintenance caller has already dropped its barrier. Do not retain a
|
|
1536
|
+
// stale warming flag in that case; an active turn-stopping owner clears
|
|
1537
|
+
// its own state in its finally block.
|
|
1538
|
+
state.pendingMaintenance = false;
|
|
1539
|
+
state.warming = false;
|
|
1170
1540
|
}
|
|
1171
1541
|
}
|
|
1172
1542
|
|
|
1173
1543
|
scheduleMaintenanceRetry(agent) {
|
|
1174
1544
|
if (this.standDown?.()) return;
|
|
1175
1545
|
const state = this.stateFor(agent);
|
|
1546
|
+
if (state.maintenanceOwner) {
|
|
1547
|
+
state.turnEndPending = true;
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1176
1550
|
if (state.retryScheduled) return;
|
|
1177
1551
|
state.retryScheduled = true;
|
|
1178
1552
|
scheduleImmediate(() => {
|
|
1179
1553
|
state.retryScheduled = false;
|
|
1180
|
-
if (this.standDown?.())
|
|
1181
|
-
|
|
1182
|
-
|
|
1554
|
+
if (this.standDown?.()) {
|
|
1555
|
+
state.pendingMaintenance = false;
|
|
1556
|
+
state.warming = false;
|
|
1557
|
+
return;
|
|
1558
|
+
}
|
|
1559
|
+
if (state.maintenanceJob) {
|
|
1560
|
+
const waitingJob = state.maintenanceJob;
|
|
1561
|
+
if (state.retryWaitingJob === waitingJob) return;
|
|
1562
|
+
state.retryWaitingJob = waitingJob;
|
|
1563
|
+
const retryAfterJob = () => {
|
|
1564
|
+
if (state.retryWaitingJob !== waitingJob) return;
|
|
1565
|
+
state.retryWaitingJob = null;
|
|
1566
|
+
if (!state.maintenanceJob && state.pendingMaintenance) {
|
|
1567
|
+
this.scheduleMaintenanceRetry(agent);
|
|
1568
|
+
}
|
|
1569
|
+
};
|
|
1570
|
+
Promise.resolve(waitingJob).then(retryAfterJob, retryAfterJob);
|
|
1183
1571
|
return;
|
|
1184
1572
|
}
|
|
1573
|
+
if (state.warming && !state.pendingMaintenance) state.warming = false;
|
|
1185
1574
|
const events = agent.session.snapshotEvents();
|
|
1186
1575
|
const done = latestTurnCompleted(events);
|
|
1187
|
-
if (!done)
|
|
1576
|
+
if (!done) {
|
|
1577
|
+
state.pendingMaintenance = false;
|
|
1578
|
+
state.warming = false;
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1188
1581
|
state.warming = true;
|
|
1582
|
+
const retryAbort = new AbortController();
|
|
1583
|
+
state.maintenanceAbort = retryAbort;
|
|
1189
1584
|
const job = this.finishTurn(agent, events, { maintenanceRetry: true, skipCapture: true })
|
|
1190
1585
|
.catch((error) => noteShadowWarning(this.ctx?.logger, error))
|
|
1191
1586
|
.finally(() => {
|
|
1587
|
+
const sameJob = state.maintenanceJob === job && state.maintenanceAbort === retryAbort;
|
|
1588
|
+
this.pendingCuts.delete(job);
|
|
1589
|
+
if (!sameJob) return;
|
|
1590
|
+
const requeueBoundary = state.turnEndPending;
|
|
1591
|
+
state.turnEndPending = false;
|
|
1192
1592
|
state.pendingMaintenance = false;
|
|
1193
1593
|
state.warming = false;
|
|
1194
|
-
|
|
1195
|
-
|
|
1594
|
+
state.maintenanceAbort = null;
|
|
1595
|
+
state.maintenanceJob = null;
|
|
1596
|
+
if (requeueBoundary) this.scheduleTurnEndMaintenance(agent, state.turnEndSeq, state.turnEndEvent);
|
|
1196
1597
|
});
|
|
1197
1598
|
state.maintenanceJob = job;
|
|
1198
1599
|
this.pendingCuts.add(job);
|
|
@@ -1203,7 +1604,12 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1203
1604
|
if (this.standDown?.()) return null;
|
|
1204
1605
|
const settings = readSettings(this.liveConfig);
|
|
1205
1606
|
const state = this.stateFor(agent);
|
|
1206
|
-
|
|
1607
|
+
if (state.maintenanceAbort?.signal.aborted) return false;
|
|
1608
|
+
if (!state.maintenanceAbort) {
|
|
1609
|
+
state.maintenanceAbort = new AbortController();
|
|
1610
|
+
}
|
|
1611
|
+
const signal = AbortSignal.any([AbortSignal.timeout(30000), state.maintenanceAbort.signal]);
|
|
1612
|
+
let maintenanceCompleted = false;
|
|
1207
1613
|
const ev = events || agent.session.snapshotEvents();
|
|
1208
1614
|
const deferCapture = options.deferCapture === true;
|
|
1209
1615
|
let catchup = { finished: true, progressed: false, retryRequested: false };
|
|
@@ -1212,12 +1618,18 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1212
1618
|
// the capture surface. Re-run maintenance without rescanning events.
|
|
1213
1619
|
} else if (deferCapture) {
|
|
1214
1620
|
state.pendingMaintenance = true;
|
|
1215
|
-
|
|
1621
|
+
try {
|
|
1622
|
+
catchup = this.scheduleCaptureCatchup(agent, ev, settings, { maintenanceRequested: true });
|
|
1623
|
+
} catch (error) {
|
|
1624
|
+
state.pendingMaintenance = false;
|
|
1625
|
+
state.warming = false;
|
|
1626
|
+
throw error;
|
|
1627
|
+
}
|
|
1216
1628
|
} else {
|
|
1217
1629
|
if (ev.length > CAPTURE_EVENT_BATCH) {
|
|
1218
1630
|
catchup = this.scheduleCaptureCatchup(agent, ev, settings, { freezeSnapshot: true });
|
|
1219
1631
|
} else {
|
|
1220
|
-
await this.flushPendingCaptures();
|
|
1632
|
+
await this.flushPendingCaptures(agent.session);
|
|
1221
1633
|
this.captureNew(agent.session, ev, settings);
|
|
1222
1634
|
}
|
|
1223
1635
|
}
|
|
@@ -1232,7 +1644,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1232
1644
|
return null;
|
|
1233
1645
|
}
|
|
1234
1646
|
}
|
|
1235
|
-
await this.flushPendingCaptures();
|
|
1647
|
+
await this.flushPendingCaptures(agent.session);
|
|
1236
1648
|
const jobs = collectJobs(ev);
|
|
1237
1649
|
const calls = indexToolCalls(ev);
|
|
1238
1650
|
try {
|
|
@@ -1243,33 +1655,58 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1243
1655
|
// started at that point, so let it finish under the bounded timeout;
|
|
1244
1656
|
// user/host cancellation reasons still abort the operation.
|
|
1245
1657
|
const op = maintenanceOperationSignal(agentSignal, signal);
|
|
1658
|
+
const markCompleted = () => {
|
|
1659
|
+
if (!op.aborted && !signal.aborted) maintenanceCompleted = true;
|
|
1660
|
+
};
|
|
1246
1661
|
let measurement = this.ctx.tokenMeter.measure(agent.session);
|
|
1247
1662
|
const settleTurnBaseline = () => {
|
|
1248
1663
|
state.turnBase = measurement.totalTokens;
|
|
1249
1664
|
state.maxTurnGrowth = 0;
|
|
1250
1665
|
};
|
|
1251
1666
|
if (measurement.totalTokens < settings.minTokens || measurement.totalTokens >= settings.bigGate) {
|
|
1667
|
+
this.recordDecision(state, {
|
|
1668
|
+
phase: "maintenance-skip",
|
|
1669
|
+
reason: measurement.totalTokens < settings.minTokens ? "below-min-tokens" : "above-big-gate",
|
|
1670
|
+
totalTokens: measurement.totalTokens,
|
|
1671
|
+
});
|
|
1252
1672
|
settleTurnBaseline();
|
|
1673
|
+
markCompleted();
|
|
1253
1674
|
return;
|
|
1254
1675
|
}
|
|
1255
1676
|
// Restored cards establish a baseline; a live card still skips once,
|
|
1256
1677
|
// even when maintenance or engine construction is delayed.
|
|
1257
|
-
if (skipLiveOfficialCompaction(agent.session)) {
|
|
1678
|
+
if (!op.aborted && skipLiveOfficialCompaction(agent.session)) {
|
|
1679
|
+
this.recordDecision(state, { phase: "maintenance-skip", reason: "official-checkpoint" });
|
|
1258
1680
|
this.ctx.logger?.info?.("spine cooldown: live official compaction seen, skip this pass");
|
|
1259
1681
|
settleTurnBaseline();
|
|
1682
|
+
markCompleted();
|
|
1260
1683
|
return;
|
|
1261
1684
|
}
|
|
1262
1685
|
if (inCooldown(agent.session, { windowMs: settings.cooldownMs })) {
|
|
1686
|
+
this.recordDecision(state, { phase: "maintenance-skip", reason: "cooldown" });
|
|
1263
1687
|
settleTurnBaseline();
|
|
1688
|
+
markCompleted();
|
|
1264
1689
|
return;
|
|
1265
1690
|
}
|
|
1266
1691
|
this.ensurePruneGuard();
|
|
1692
|
+
// The pi-ai catalog is loaded asynchronously so ESM-only providers are
|
|
1693
|
+
// discoverable. Do not classify the first request as local merely
|
|
1694
|
+
// because catalogProviders() was called before the import settled.
|
|
1695
|
+
if (this.catalogPromise) await this.catalogPromise;
|
|
1267
1696
|
const resolved = this.engineFor(agent);
|
|
1268
1697
|
if (state.engine !== resolved.engine || state.engineSource !== resolved.source) {
|
|
1269
1698
|
this.ctx.logger?.info?.(`spine engine=${resolved.engine} source=${resolved.source}`);
|
|
1270
1699
|
state.engine = resolved.engine;
|
|
1271
1700
|
state.engineSource = resolved.source;
|
|
1272
1701
|
}
|
|
1702
|
+
this.recordDecision(state, {
|
|
1703
|
+
phase: "engine",
|
|
1704
|
+
engine: resolved.engine,
|
|
1705
|
+
source: resolved.source,
|
|
1706
|
+
provider: agent?.session?.requestHeader?.()?.config?.provider || "",
|
|
1707
|
+
model: agent?.session?.requestHeader?.()?.config?.model || "",
|
|
1708
|
+
catalogReady: this.catalogCache.length > 0,
|
|
1709
|
+
});
|
|
1273
1710
|
const cloud = resolved.engine !== "local";
|
|
1274
1711
|
// 预测下一轮会过 32000 时收尾;没有增长基线时仍由已有 48000 紧急线接管。
|
|
1275
1712
|
// Drain a projected request over 32000. Without a growth baseline, the existing 48000 urgent line still takes over.
|
|
@@ -1280,6 +1717,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1280
1717
|
const projected = state.maxTurnGrowth > 0 && last + state.maxTurnGrowth > settings.keepRoundTokens;
|
|
1281
1718
|
const drain = cloud && (projected || last >= URGENT_TOKENS);
|
|
1282
1719
|
const drainNotes = [];
|
|
1720
|
+
let maintenanceFailed = false;
|
|
1283
1721
|
for (let pass = 0; pass < 8; pass += 1) {
|
|
1284
1722
|
const measured = measurement;
|
|
1285
1723
|
if (drain && measured.totalTokens <= settings.keepRoundTokens) break;
|
|
@@ -1294,8 +1732,15 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1294
1732
|
});
|
|
1295
1733
|
if (chunk === null) {
|
|
1296
1734
|
if (drain && measured.totalTokens > settings.keepRoundTokens) {
|
|
1735
|
+
this.recordDecision(state, {
|
|
1736
|
+
phase: "cut-skip",
|
|
1737
|
+
reason: "no-legal-span",
|
|
1738
|
+
totalTokens: measured.totalTokens,
|
|
1739
|
+
drain: true,
|
|
1740
|
+
});
|
|
1297
1741
|
this.ctx.logger?.warn?.(`spine drain stopped at ${measured.totalTokens}; no legal span`);
|
|
1298
1742
|
} else {
|
|
1743
|
+
this.recordDecision(state, { phase: "cut-skip", reason: "no-legal-span", totalTokens: measured.totalTokens, drain: false });
|
|
1299
1744
|
this.ctx.logger?.debug?.("spine cut skipped");
|
|
1300
1745
|
}
|
|
1301
1746
|
break;
|
|
@@ -1309,12 +1754,24 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1309
1754
|
state.localOnly = true;
|
|
1310
1755
|
state.approvedCard = chunk.card;
|
|
1311
1756
|
const committed = await this.commitSelectedSpan(agent, chunk, op, { drain });
|
|
1312
|
-
if (committed === false)
|
|
1757
|
+
if (committed === false) {
|
|
1758
|
+
maintenanceFailed = true;
|
|
1759
|
+
break;
|
|
1760
|
+
}
|
|
1313
1761
|
measurement = this.ctx.tokenMeter.measure(agent.session);
|
|
1314
1762
|
const after = measurement.totalTokens;
|
|
1315
1763
|
reduced = after < before;
|
|
1316
1764
|
const saved = before - after;
|
|
1317
1765
|
if (saved > 0) {
|
|
1766
|
+
this.recordDecision(state, {
|
|
1767
|
+
phase: "cut",
|
|
1768
|
+
result: "committed",
|
|
1769
|
+
before,
|
|
1770
|
+
after,
|
|
1771
|
+
saved,
|
|
1772
|
+
tokens: chunk.tokens,
|
|
1773
|
+
drain,
|
|
1774
|
+
});
|
|
1318
1775
|
drainNotes.push({
|
|
1319
1776
|
kind: "cut",
|
|
1320
1777
|
saved,
|
|
@@ -1329,14 +1786,20 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1329
1786
|
this.ctx.logger?.info?.(`spine cut ${Date.now() - started}ms ${before} -> ${after} chunk=${chunk.tokens} saved=${saved}`);
|
|
1330
1787
|
} catch (error) {
|
|
1331
1788
|
const message = error instanceof Error ? error.message : String(error);
|
|
1332
|
-
if (message.includes("raw backup missing before cut")) {
|
|
1789
|
+
if (message.includes("raw backup missing before cut") && error?.retryable === true) {
|
|
1333
1790
|
catchup.retryRequested = true;
|
|
1334
|
-
if (catchup.finished &&
|
|
1791
|
+
if (catchup.finished && state.rawCutRetryAttempts < CAPTURE_RETRY_LIMIT) {
|
|
1792
|
+
state.rawCutRetryAttempts += 1;
|
|
1793
|
+
this.scheduleMaintenanceRetry(agent);
|
|
1794
|
+
}
|
|
1335
1795
|
}
|
|
1796
|
+
maintenanceFailed = true;
|
|
1797
|
+
this.recordDecision(state, { phase: "cut", result: "failed", reason: message, drain });
|
|
1336
1798
|
this.ctx.logger?.warn?.(`spine cut failed: ${message}`);
|
|
1337
1799
|
break;
|
|
1338
1800
|
}
|
|
1339
1801
|
if (!reduced) {
|
|
1802
|
+
maintenanceFailed = true;
|
|
1340
1803
|
this.ctx.logger?.warn?.(`spine cut did not reduce ${before}; leaving the prefix for the gate`);
|
|
1341
1804
|
break;
|
|
1342
1805
|
}
|
|
@@ -1347,6 +1810,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1347
1810
|
state.maxTurnGrowth = 0;
|
|
1348
1811
|
await this.ctx.sessions?.flush?.(agent.session);
|
|
1349
1812
|
this.rememberPrefix(agent);
|
|
1813
|
+
if (!maintenanceFailed) {
|
|
1814
|
+
state.rawCutRetryAttempts = 0;
|
|
1815
|
+
markCompleted();
|
|
1816
|
+
}
|
|
1350
1817
|
});
|
|
1351
1818
|
} catch (error) {
|
|
1352
1819
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -1354,6 +1821,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1354
1821
|
} finally {
|
|
1355
1822
|
state.localOnly = false;
|
|
1356
1823
|
}
|
|
1824
|
+
return maintenanceCompleted;
|
|
1357
1825
|
}
|
|
1358
1826
|
|
|
1359
1827
|
async flushPendingCaptures(session = null, ids = null) {
|
|
@@ -1437,12 +1905,21 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1437
1905
|
this.rawSeen.set(this.rawKey(session, id), raw);
|
|
1438
1906
|
} catch (error) {
|
|
1439
1907
|
noteShadowWarning(this.ctx?.logger, error);
|
|
1440
|
-
raw = {
|
|
1908
|
+
raw = {
|
|
1909
|
+
...raw,
|
|
1910
|
+
ok: false,
|
|
1911
|
+
reason: "unwritable",
|
|
1912
|
+
toolCallId: id,
|
|
1913
|
+
aclVerified: false,
|
|
1914
|
+
retryable: raw?.retryable === true || captureErrorRetryable(error),
|
|
1915
|
+
};
|
|
1441
1916
|
this.rawSeen.set(this.rawKey(session, id), raw);
|
|
1442
1917
|
}
|
|
1443
1918
|
}
|
|
1444
1919
|
if (!id || !verifiedRaw(raw).ok) {
|
|
1445
|
-
|
|
1920
|
+
const missing = new Error(`spine: raw backup missing before cut: ${id || "unknown"}`);
|
|
1921
|
+
missing.retryable = raw == null || raw.retryable === true;
|
|
1922
|
+
throw missing;
|
|
1446
1923
|
}
|
|
1447
1924
|
}
|
|
1448
1925
|
messages.push({
|
|
@@ -1452,6 +1929,12 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1452
1929
|
});
|
|
1453
1930
|
}
|
|
1454
1931
|
const summarized = await this.summarize({ messages, liveCompact: { card: chunk.card } }, agent, signal);
|
|
1932
|
+
if (typeof this.stateFor === "function") {
|
|
1933
|
+
const state = this.stateFor(agent);
|
|
1934
|
+
state.lastCardPath = chunk.card?.shadowFile || "";
|
|
1935
|
+
state.cardRawPaths = [...new Set([...(state.cardRawPaths || []), ...(chunk.card?.rawPaths || [])])];
|
|
1936
|
+
state.cardRawPathsStructured = true;
|
|
1937
|
+
}
|
|
1455
1938
|
signal?.throwIfAborted();
|
|
1456
1939
|
if (this.standDown?.()) return false;
|
|
1457
1940
|
assertCurrentSpan(shadowedSeqs);
|
|
@@ -1461,7 +1944,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1461
1944
|
{ type: "text", text: `${CHECKPOINT_PREAMBLE}\n\n${MARK}` },
|
|
1462
1945
|
...summarized.summary,
|
|
1463
1946
|
],
|
|
1464
|
-
source: spineCheckpointSource(compactionId),
|
|
1947
|
+
source: spineCheckpointSource(compactionId, chunk.card?.rawPaths || []),
|
|
1465
1948
|
});
|
|
1466
1949
|
const framedTokens = typeof this.ctx.tokenMeter.estimateMessage === "function"
|
|
1467
1950
|
? this.ctx.tokenMeter.estimateMessage(checkpointMessage)
|
|
@@ -1622,32 +2105,17 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1622
2105
|
}
|
|
1623
2106
|
|
|
1624
2107
|
catalogProviders() {
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
let models = [];
|
|
1635
|
-
try {
|
|
1636
|
-
const declared = typeof entry?.getModels === "function" ? entry.getModels() : entry?.models || [];
|
|
1637
|
-
models = (Array.isArray(declared) ? declared : []).map((model) => ({
|
|
1638
|
-
id: model?.id || "",
|
|
1639
|
-
baseURL: model?.baseUrl || model?.baseURL || "",
|
|
1640
|
-
})).filter((model) => model.id && model.baseURL);
|
|
1641
|
-
} catch {}
|
|
1642
|
-
return {
|
|
1643
|
-
id: entry?.id || "",
|
|
1644
|
-
baseURL: entry?.baseUrl || entry?.baseURL || "",
|
|
1645
|
-
models,
|
|
1646
|
-
};
|
|
1647
|
-
}).filter((entry) => entry.id && (entry.baseURL || entry.models.length));
|
|
1648
|
-
} catch {}
|
|
2108
|
+
if (!this.catalogPromise) {
|
|
2109
|
+
this.catalogPromise = loadPiAiCatalog().then((catalog) => {
|
|
2110
|
+
this.catalogCache = catalog;
|
|
2111
|
+
if (!catalog.length) this.catalogPromise = null;
|
|
2112
|
+
return catalog;
|
|
2113
|
+
}).catch(() => {
|
|
2114
|
+
this.catalogPromise = null;
|
|
2115
|
+
return [];
|
|
2116
|
+
});
|
|
1649
2117
|
}
|
|
1650
|
-
return [];
|
|
2118
|
+
return this.catalogCache || [];
|
|
1651
2119
|
}
|
|
1652
2120
|
|
|
1653
2121
|
profilePatchText() {
|
|
@@ -1679,6 +2147,13 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1679
2147
|
const key = this.rawKey(session, id);
|
|
1680
2148
|
const cached = this.rawSeen.get(key);
|
|
1681
2149
|
if (!cached || cached.retryable === true) return cached || null;
|
|
2150
|
+
if (cached.unrecoverable) {
|
|
2151
|
+
const text = messageText(event.data?.message);
|
|
2152
|
+
if (String(text).includes(PRUNE_MARKER)) return cached;
|
|
2153
|
+
const refused = { ok: false, reason: "duplicate-tool-call-id", toolCallId: id, retryable: false };
|
|
2154
|
+
this.rawSeen.set(key, refused);
|
|
2155
|
+
return refused;
|
|
2156
|
+
}
|
|
1682
2157
|
if (!cached.ok || !Number.isInteger(cached.bytes) || typeof cached.sha256 !== "string") return cached;
|
|
1683
2158
|
const text = messageText(event.data?.message);
|
|
1684
2159
|
if (String(text).includes(PRUNE_MARKER)) return cached;
|
|
@@ -1844,7 +2319,12 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1844
2319
|
captures += 1;
|
|
1845
2320
|
}
|
|
1846
2321
|
this.noteCaptureResult(session, event, record);
|
|
1847
|
-
if (record?.
|
|
2322
|
+
if (record?.unrecoverable) {
|
|
2323
|
+
// The host already discarded the original body. It cannot be
|
|
2324
|
+
// reconstructed, but it must not pin the cursor forever; the
|
|
2325
|
+
// visible marker remains protected by the raw lookup path.
|
|
2326
|
+
progressed = true;
|
|
2327
|
+
} else if (record?.retryable && retry === null) {
|
|
1848
2328
|
retry = seq;
|
|
1849
2329
|
retryIndex = index;
|
|
1850
2330
|
} else if (record?.ok === false && !record.retryable && blocked === null) {
|
|
@@ -1898,7 +2378,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1898
2378
|
const cached = this.cachedCaptureFor(session, event);
|
|
1899
2379
|
const record = cached && !cached.retryable ? cached : this.captureOne(session, event);
|
|
1900
2380
|
this.noteCaptureResult(session, event, record);
|
|
1901
|
-
if (record?.
|
|
2381
|
+
if (record?.unrecoverable) {
|
|
2382
|
+
// Advance beyond an already-pruned result so later events can be
|
|
2383
|
+
// captured on the same catch-up pass.
|
|
2384
|
+
} else if (record?.retryable && retry === null) retry = seq;
|
|
1902
2385
|
else if (record?.ok === false && !record.retryable && blocked === null) blocked = seq;
|
|
1903
2386
|
}
|
|
1904
2387
|
}
|
|
@@ -2250,19 +2733,23 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2250
2733
|
const card = input?.liveCompact?.card;
|
|
2251
2734
|
if (card?.needsBackup && !card.shadowFile) throw new Error("spine: omit refused; backup path missing");
|
|
2252
2735
|
const restored = this.restoreRawMessages(input.messages, state.key);
|
|
2253
|
-
|
|
2736
|
+
const protectRawPaths = [...new Set([...(state.cardRawPaths || []), ...(card?.rawPaths || [])])];
|
|
2737
|
+
await this.saveShadowAsync(restored, true, card?.shadowFile, state.key, protectRawPaths);
|
|
2254
2738
|
if (card?.needsBackup && !existsSync(card.shadowFile)) throw new Error("spine: shadow backup was not written");
|
|
2255
2739
|
const text = backupClaimOk(restored) ? decision.text : withoutFullBackupClaim(decision.text, card?.shadowFile);
|
|
2256
2740
|
const block = { type: "text", text };
|
|
2257
2741
|
return { summary: [block], provider: "local", model: "spine-extract", rawOutput: [block] };
|
|
2258
2742
|
}
|
|
2259
2743
|
try {
|
|
2744
|
+
const officialShadowFile = freshShadowFile("official", state.key);
|
|
2260
2745
|
await this.saveShadowAsync(
|
|
2261
2746
|
this.restoreRawMessages(input.messages, state.key),
|
|
2262
2747
|
false,
|
|
2263
|
-
|
|
2748
|
+
officialShadowFile,
|
|
2264
2749
|
state.key,
|
|
2750
|
+
state.cardRawPaths || [],
|
|
2265
2751
|
);
|
|
2752
|
+
state.lastCardPath = officialShadowFile;
|
|
2266
2753
|
} catch (error) {
|
|
2267
2754
|
if (
|
|
2268
2755
|
error?.code === "ESHADOWACCESS" ||
|
|
@@ -2296,6 +2783,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2296
2783
|
}
|
|
2297
2784
|
|
|
2298
2785
|
async summarizeOfficial(input, agent, signal) {
|
|
2786
|
+
this.recordDecision(this.stateFor(agent), { phase: "official-summary", result: "started" });
|
|
2299
2787
|
const result = await super.summarize(input, agent, signal);
|
|
2300
2788
|
const blocks = Array.isArray(result?.summary) ? result.summary : [];
|
|
2301
2789
|
const usable = blocks.some((block) => {
|
|
@@ -2305,9 +2793,11 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2305
2793
|
return Array.isArray(block.content) && block.content.some((part) => typeof part?.text === "string" && part.text.trim());
|
|
2306
2794
|
});
|
|
2307
2795
|
if (!usable) {
|
|
2796
|
+
this.recordDecision(this.stateFor(agent), { phase: "official-summary", result: "empty" });
|
|
2308
2797
|
this.ctx.logger?.warn?.("spine: official summarizer returned no usable summary; leaving the span untouched");
|
|
2309
2798
|
throw new Error("spine: official summarizer returned no usable summary");
|
|
2310
2799
|
}
|
|
2800
|
+
this.recordDecision(this.stateFor(agent), { phase: "official-summary", result: "usable" });
|
|
2311
2801
|
return result;
|
|
2312
2802
|
}
|
|
2313
2803
|
}
|