opencode-live-compact 0.0.0-stage → 0.1.1
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/LICENSE +22 -0
- package/README.md +137 -3
- package/README.zh-CN.md +137 -0
- package/dist/config.d.ts +15 -0
- package/dist/config.js +33 -0
- package/dist/config.js.map +1 -0
- package/dist/engine/checkpoint.d.ts +8 -0
- package/dist/engine/checkpoint.js +50 -0
- package/dist/engine/checkpoint.js.map +1 -0
- package/dist/engine/eligibility.d.ts +30 -0
- package/dist/engine/eligibility.js +149 -0
- package/dist/engine/eligibility.js.map +1 -0
- package/dist/engine/planner.d.ts +22 -0
- package/dist/engine/planner.js +56 -0
- package/dist/engine/planner.js.map +1 -0
- package/dist/engine/reducer.d.ts +13 -0
- package/dist/engine/reducer.js +56 -0
- package/dist/engine/reducer.js.map +1 -0
- package/dist/engine/span.d.ts +19 -0
- package/dist/engine/span.js +369 -0
- package/dist/engine/span.js.map +1 -0
- package/dist/hooks/context.d.ts +8 -0
- package/dist/hooks/context.js +38 -0
- package/dist/hooks/context.js.map +1 -0
- package/dist/hooks/replacement.d.ts +11 -0
- package/dist/hooks/replacement.js +286 -0
- package/dist/hooks/replacement.js.map +1 -0
- package/dist/hooks/session.d.ts +4 -0
- package/dist/hooks/session.js +53 -0
- package/dist/hooks/session.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +64 -0
- package/dist/index.js.map +1 -0
- package/dist/metrics/collector.d.ts +41 -0
- package/dist/metrics/collector.js +17 -0
- package/dist/metrics/collector.js.map +1 -0
- package/dist/recovery/integrity.d.ts +11 -0
- package/dist/recovery/integrity.js +24 -0
- package/dist/recovery/integrity.js.map +1 -0
- package/dist/recovery/payloads.d.ts +19 -0
- package/dist/recovery/payloads.js +182 -0
- package/dist/recovery/payloads.js.map +1 -0
- package/dist/recovery/private-directory.d.ts +1 -0
- package/dist/recovery/private-directory.js +121 -0
- package/dist/recovery/private-directory.js.map +1 -0
- package/dist/recovery/restore.d.ts +12 -0
- package/dist/recovery/restore.js +32 -0
- package/dist/recovery/restore.js.map +1 -0
- package/dist/recovery/store.d.ts +51 -0
- package/dist/recovery/store.js +308 -0
- package/dist/recovery/store.js.map +1 -0
- package/dist/state/reconciliation.d.ts +32 -0
- package/dist/state/reconciliation.js +173 -0
- package/dist/state/reconciliation.js.map +1 -0
- package/docs/architecture.md +54 -0
- package/docs/assets/benchmarks-en.svg +106 -0
- package/docs/assets/benchmarks-zh-CN.svg +106 -0
- package/package.json +65 -4
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { hashText, isRecoveryReference, recoveryReference } from "./integrity.js";
|
|
3
|
+
import { privateArchivePath } from "./private-directory.js";
|
|
4
|
+
import { RecoveryPayloads } from "./payloads.js";
|
|
5
|
+
const planColumns = "session_id, reference, identity, source_hash, checkpoint, checkpoint_hash, retired_at";
|
|
6
|
+
function parse(value) {
|
|
7
|
+
if (typeof value !== "string")
|
|
8
|
+
return undefined;
|
|
9
|
+
try {
|
|
10
|
+
return JSON.parse(value);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function decodePlan(row) {
|
|
17
|
+
const identity = parse(row.identity);
|
|
18
|
+
const checkpoint = parse(row.checkpoint);
|
|
19
|
+
if (!identity || identity.sessionID !== row.session_id ||
|
|
20
|
+
typeof identity.messageID !== "string" || typeof identity.partID !== "string" ||
|
|
21
|
+
typeof identity.callID !== "string" || typeof identity.tool !== "string" ||
|
|
22
|
+
typeof row.reference !== "string" || typeof row.source_hash !== "string" || typeof checkpoint !== "string" ||
|
|
23
|
+
recoveryReference(identity, row.source_hash) !== row.reference || hashText(checkpoint) !== row.checkpoint_hash) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
version: 1,
|
|
28
|
+
identity,
|
|
29
|
+
reference: row.reference,
|
|
30
|
+
sourceHash: row.source_hash,
|
|
31
|
+
checkpoint,
|
|
32
|
+
active: row.retired_at === null,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function decodeRecord(row, payloads) {
|
|
36
|
+
if (!row)
|
|
37
|
+
return undefined;
|
|
38
|
+
const plan = decodePlan(row);
|
|
39
|
+
const original = parse(row.external === 1 && plan ? payloads.read(plan.identity.sessionID, plan.reference, Number(row.bytes)) : row.original);
|
|
40
|
+
if (!plan || typeof original !== "string" || hashText(original) !== plan.sourceHash)
|
|
41
|
+
return undefined;
|
|
42
|
+
return { ...plan, original };
|
|
43
|
+
}
|
|
44
|
+
function boundedInteger(value, label) {
|
|
45
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
46
|
+
throw new RangeError(`${label} must be a non-negative safe integer`);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function transaction(db, run) {
|
|
50
|
+
db.exec("BEGIN IMMEDIATE");
|
|
51
|
+
try {
|
|
52
|
+
const result = run();
|
|
53
|
+
db.exec("COMMIT");
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
try {
|
|
58
|
+
db.exec("ROLLBACK");
|
|
59
|
+
}
|
|
60
|
+
catch { /* Preserve the original error. */ }
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export class RecoveryStore {
|
|
65
|
+
connection;
|
|
66
|
+
payloads;
|
|
67
|
+
needsSweep = false;
|
|
68
|
+
closed = false;
|
|
69
|
+
directory;
|
|
70
|
+
maxBytes;
|
|
71
|
+
maxRecordBytes;
|
|
72
|
+
maxRecords;
|
|
73
|
+
retentionMs;
|
|
74
|
+
constructor(options) {
|
|
75
|
+
this.directory = options.directory;
|
|
76
|
+
this.maxBytes = boundedInteger(options.maxBytes ?? 256 * 1024 * 1024, "maxBytes");
|
|
77
|
+
this.maxRecordBytes = boundedInteger(options.maxRecordBytes ?? 512 * 1024, "maxRecordBytes");
|
|
78
|
+
this.maxRecords = boundedInteger(options.maxRecords ?? 2_000, "maxRecords");
|
|
79
|
+
this.retentionMs = boundedInteger(options.retentionMs ?? 7 * 24 * 60 * 60 * 1_000, "retentionMs");
|
|
80
|
+
}
|
|
81
|
+
async preserve(input) {
|
|
82
|
+
return this.preserveBatch([input]);
|
|
83
|
+
}
|
|
84
|
+
/** Preserve the complete admitted batch in one durable transaction, or preserve none. */
|
|
85
|
+
async preserveBatch(inputs) {
|
|
86
|
+
if (!inputs.length)
|
|
87
|
+
return false;
|
|
88
|
+
const unique = new Map();
|
|
89
|
+
for (const input of inputs) {
|
|
90
|
+
if (hashText(input.original) !== input.sourceHash ||
|
|
91
|
+
recoveryReference(input.identity, input.sourceHash) !== input.reference ||
|
|
92
|
+
!input.checkpoint.includes(input.reference))
|
|
93
|
+
return false;
|
|
94
|
+
const previous = unique.get(input.reference);
|
|
95
|
+
if (previous && (previous.original !== input.original || previous.checkpoint !== input.checkpoint))
|
|
96
|
+
return false;
|
|
97
|
+
unique.set(input.reference, input);
|
|
98
|
+
}
|
|
99
|
+
const db = await this.database();
|
|
100
|
+
if (this.needsSweep) {
|
|
101
|
+
transaction(db, () => this.sweep(db));
|
|
102
|
+
this.needsSweep = false;
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
return transaction(db, () => {
|
|
106
|
+
const lookup = db.prepare(`SELECT ${planColumns}, original, external, bytes FROM recovery WHERE reference = ?`);
|
|
107
|
+
const additions = [];
|
|
108
|
+
const reactivate = [];
|
|
109
|
+
let totalBytes = 0;
|
|
110
|
+
for (const input of unique.values()) {
|
|
111
|
+
const previous = lookup.get(input.reference);
|
|
112
|
+
if (previous) {
|
|
113
|
+
const valid = decodeRecord(previous, this.payloads);
|
|
114
|
+
if (!valid || valid.checkpoint !== input.checkpoint || valid.original !== input.original)
|
|
115
|
+
return false;
|
|
116
|
+
if (!valid.active)
|
|
117
|
+
reactivate.push(input.reference);
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
const bytes = Buffer.byteLength(JSON.stringify(input));
|
|
121
|
+
if (bytes > this.maxRecordBytes)
|
|
122
|
+
return false;
|
|
123
|
+
additions.push({ input, bytes });
|
|
124
|
+
totalBytes += bytes;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (totalBytes > this.maxBytes || additions.length > this.maxRecords)
|
|
128
|
+
return false;
|
|
129
|
+
// Incoming references stay pinned even if this batch reactivates a retired
|
|
130
|
+
// record. The same SQLite write lock coordinates all sessions and processes.
|
|
131
|
+
const retained = new Set(unique.keys());
|
|
132
|
+
if (!this.prune(db, Date.now(), retained, totalBytes, additions.length))
|
|
133
|
+
return false;
|
|
134
|
+
const insert = db.prepare(`INSERT INTO recovery (session_id, reference, identity, source_hash, checkpoint, checkpoint_hash, original, bytes, external)
|
|
135
|
+
VALUES (?, ?, ?, ?, ?, ?, 'null', ?, 1)`);
|
|
136
|
+
for (const { input, bytes } of additions) {
|
|
137
|
+
this.payloads.write(input.identity.sessionID, input.reference, input.original);
|
|
138
|
+
insert.run(input.identity.sessionID, input.reference, JSON.stringify(input.identity), input.sourceHash, JSON.stringify(input.checkpoint), hashText(input.checkpoint), bytes);
|
|
139
|
+
}
|
|
140
|
+
const revive = db.prepare("UPDATE recovery SET retired_at = NULL WHERE reference = ?");
|
|
141
|
+
for (const reference of reactivate)
|
|
142
|
+
revive.run(reference);
|
|
143
|
+
return true;
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
// A rolled-back batch may already have durable payloads. Reclaim only
|
|
148
|
+
// uncommitted files under the same global lock, before another admission.
|
|
149
|
+
this.needsSweep = true;
|
|
150
|
+
try {
|
|
151
|
+
transaction(db, () => this.sweep(db));
|
|
152
|
+
this.needsSweep = false;
|
|
153
|
+
}
|
|
154
|
+
catch { /* Retry before the next write. */ }
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async list(sessionID) {
|
|
159
|
+
const db = await this.database();
|
|
160
|
+
const plans = [];
|
|
161
|
+
for (const row of db.prepare(`SELECT ${planColumns} FROM recovery WHERE session_id = ? ORDER BY rowid`).all(sessionID)) {
|
|
162
|
+
const plan = decodePlan(row);
|
|
163
|
+
if (plan)
|
|
164
|
+
plans.push(plan);
|
|
165
|
+
}
|
|
166
|
+
return plans;
|
|
167
|
+
}
|
|
168
|
+
async get(sessionID, reference) {
|
|
169
|
+
return (await this.getBatch(sessionID, [reference]))[0];
|
|
170
|
+
}
|
|
171
|
+
/** Read a bounded replacement batch under one lock; validate every payload afresh. */
|
|
172
|
+
async getBatch(sessionID, references) {
|
|
173
|
+
const requested = references.map(reference => isRecoveryReference(reference) ? reference : undefined);
|
|
174
|
+
if (!requested.some(reference => reference !== undefined))
|
|
175
|
+
return requested.map(() => undefined);
|
|
176
|
+
const db = await this.database();
|
|
177
|
+
return transaction(db, () => {
|
|
178
|
+
const lookup = db.prepare(`SELECT ${planColumns}, original, external, bytes FROM recovery WHERE session_id = ? AND reference = ?`);
|
|
179
|
+
return requested.map(reference => reference === undefined ? undefined :
|
|
180
|
+
decodeRecord(lookup.get(sessionID, reference), this.payloads));
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
/** Validate the payload once before reusing a durable plan in a new runtime. */
|
|
184
|
+
async verify(plan) {
|
|
185
|
+
const record = await this.get(plan.identity.sessionID, plan.reference);
|
|
186
|
+
return record?.active === true && record.sourceHash === plan.sourceHash && record.checkpoint === plan.checkpoint;
|
|
187
|
+
}
|
|
188
|
+
/** Pass complete history and only the plans observed when that history was captured. */
|
|
189
|
+
async reconcile(sessionID, activeReferences, observedReferences) {
|
|
190
|
+
const db = await this.database();
|
|
191
|
+
const now = Date.now();
|
|
192
|
+
transaction(db, () => {
|
|
193
|
+
const reactivate = db.prepare("UPDATE recovery SET retired_at = NULL WHERE session_id = ? AND reference = ? AND retired_at IS NOT NULL");
|
|
194
|
+
const retire = db.prepare("UPDATE recovery SET retired_at = ? WHERE session_id = ? AND reference = ? AND retired_at IS NULL");
|
|
195
|
+
for (const reference of activeReferences)
|
|
196
|
+
reactivate.run(sessionID, reference);
|
|
197
|
+
for (const reference of observedReferences) {
|
|
198
|
+
if (!activeReferences.has(reference))
|
|
199
|
+
retire.run(now, sessionID, reference);
|
|
200
|
+
}
|
|
201
|
+
this.prune(db, now);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
async deleteSession(sessionID) {
|
|
205
|
+
const db = await this.database();
|
|
206
|
+
transaction(db, () => {
|
|
207
|
+
for (const row of db.prepare("SELECT reference, external FROM recovery WHERE session_id = ?").all(sessionID)) {
|
|
208
|
+
if (row.external === 1)
|
|
209
|
+
this.payloads.remove(sessionID, String(row.reference));
|
|
210
|
+
}
|
|
211
|
+
db.prepare("DELETE FROM recovery WHERE session_id = ?").run(sessionID);
|
|
212
|
+
this.sweep(db);
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
async close() {
|
|
216
|
+
this.closed = true;
|
|
217
|
+
const db = await this.connection?.catch(() => undefined);
|
|
218
|
+
db?.close();
|
|
219
|
+
this.connection = undefined;
|
|
220
|
+
}
|
|
221
|
+
prune(db, now, retained = new Set(), incomingBytes = 0, incomingCount = 0) {
|
|
222
|
+
const usage = db.prepare("SELECT COALESCE(SUM(bytes), 0) AS bytes, COUNT(*) AS count FROM recovery").get();
|
|
223
|
+
let bytes = usage.bytes + incomingBytes, count = usage.count + incomingCount;
|
|
224
|
+
const pressure = bytes > this.maxBytes || count > this.maxRecords;
|
|
225
|
+
const targetBytes = Math.floor(this.maxBytes * 0.8), targetCount = Math.floor(this.maxRecords * 0.8);
|
|
226
|
+
const remove = db.prepare("DELETE FROM recovery WHERE reference = ?");
|
|
227
|
+
// rowid records insertion age, independent of reads and retirement order.
|
|
228
|
+
for (const row of db.prepare("SELECT session_id, reference, bytes, external, retired_at FROM recovery WHERE retired_at IS NOT NULL ORDER BY rowid").all()) {
|
|
229
|
+
if (retained.has(String(row.reference)))
|
|
230
|
+
continue;
|
|
231
|
+
const expired = Number(row.retired_at) <= now - this.retentionMs;
|
|
232
|
+
const needed = pressure && (bytes > targetBytes || (count > this.maxRecords && count > targetCount));
|
|
233
|
+
if (!expired && !needed)
|
|
234
|
+
continue;
|
|
235
|
+
if (row.external === 1)
|
|
236
|
+
this.payloads.remove(String(row.session_id), String(row.reference));
|
|
237
|
+
remove.run(String(row.reference));
|
|
238
|
+
bytes -= Number(row.bytes);
|
|
239
|
+
count--;
|
|
240
|
+
}
|
|
241
|
+
return bytes <= this.maxBytes && count <= this.maxRecords;
|
|
242
|
+
}
|
|
243
|
+
sweep(db) {
|
|
244
|
+
const known = new Set(db.prepare("SELECT session_id, reference FROM recovery WHERE external = 1").all()
|
|
245
|
+
.map(row => this.payloads.key(String(row.session_id), String(row.reference))));
|
|
246
|
+
this.payloads.sweep(known);
|
|
247
|
+
}
|
|
248
|
+
database() {
|
|
249
|
+
if (this.closed)
|
|
250
|
+
return Promise.reject(new Error("Recovery store is closed"));
|
|
251
|
+
this.connection ??= this.openDatabase().catch((error) => {
|
|
252
|
+
this.connection = undefined;
|
|
253
|
+
throw error;
|
|
254
|
+
});
|
|
255
|
+
return this.connection;
|
|
256
|
+
}
|
|
257
|
+
async openDatabase() {
|
|
258
|
+
const path = await privateArchivePath(this.directory);
|
|
259
|
+
const db = new DatabaseSync(path);
|
|
260
|
+
this.payloads = new RecoveryPayloads(path);
|
|
261
|
+
try {
|
|
262
|
+
db.exec(`
|
|
263
|
+
PRAGMA busy_timeout = 25;
|
|
264
|
+
PRAGMA auto_vacuum = FULL;
|
|
265
|
+
PRAGMA secure_delete = ON;
|
|
266
|
+
PRAGMA synchronous = FULL;
|
|
267
|
+
CREATE TABLE IF NOT EXISTS recovery (
|
|
268
|
+
reference TEXT PRIMARY KEY,
|
|
269
|
+
session_id TEXT NOT NULL,
|
|
270
|
+
identity TEXT NOT NULL,
|
|
271
|
+
source_hash TEXT NOT NULL,
|
|
272
|
+
checkpoint TEXT NOT NULL,
|
|
273
|
+
checkpoint_hash TEXT NOT NULL,
|
|
274
|
+
original TEXT NOT NULL,
|
|
275
|
+
bytes INTEGER NOT NULL,
|
|
276
|
+
retired_at INTEGER,
|
|
277
|
+
external INTEGER NOT NULL DEFAULT 0
|
|
278
|
+
) STRICT;
|
|
279
|
+
CREATE INDEX IF NOT EXISTS recovery_session ON recovery (session_id);
|
|
280
|
+
CREATE INDEX IF NOT EXISTS recovery_expiry ON recovery (retired_at) WHERE retired_at IS NOT NULL;
|
|
281
|
+
`);
|
|
282
|
+
transaction(db, () => {
|
|
283
|
+
const columns = db.prepare("PRAGMA table_info(recovery)").all();
|
|
284
|
+
if (!columns.some(column => column.name === "external"))
|
|
285
|
+
db.exec("ALTER TABLE recovery ADD COLUMN external INTEGER NOT NULL DEFAULT 0");
|
|
286
|
+
// Inline rows remain authoritative after a crash during migration.
|
|
287
|
+
// Remove any partial uncommitted files before trying those writes again.
|
|
288
|
+
this.sweep(db);
|
|
289
|
+
const migrated = db.prepare("UPDATE recovery SET original = 'null', external = 1 WHERE reference = ?");
|
|
290
|
+
for (const row of db.prepare(`SELECT ${planColumns}, original, external, bytes FROM recovery WHERE external = 0 ORDER BY rowid`).all()) {
|
|
291
|
+
const record = decodeRecord(row, this.payloads);
|
|
292
|
+
if (!record)
|
|
293
|
+
continue;
|
|
294
|
+
this.payloads.write(record.identity.sessionID, record.reference, record.original);
|
|
295
|
+
migrated.run(record.reference);
|
|
296
|
+
}
|
|
297
|
+
this.sweep(db);
|
|
298
|
+
this.prune(db, Date.now());
|
|
299
|
+
});
|
|
300
|
+
return db;
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
db.close();
|
|
304
|
+
throw error;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/recovery/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CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,UAAU,CAAC;oBAAE,EAAE,CAAC,IAAI,CAAC,qEAAqE,CAAC,CAAC;gBACxI,mEAAmE;gBACnE,yEAAyE;gBACzE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACf,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,yEAAyE,CAAC,CAAC;gBACvG,KAAK,MAAM,GAAG,IAAI,EAAE,CAAC,OAAO,CAAC,UAAU,WAAW,6EAA6E,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;oBACvI,MAAM,MAAM,GAAG,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,QAAS,CAAC,CAAC;oBACjD,IAAI,CAAC,MAAM;wBAAE,SAAS;oBACtB,IAAI,CAAC,QAAS,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;oBACnF,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;gBACjC,CAAC;gBACD,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACf,IAAI,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;YAC7B,CAAC,CAAC,CAAC;YACH,OAAO,EAAE,CAAC;QACZ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,EAAE,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Context } from "@opencode/plugin/promise/plugin";
|
|
2
|
+
import type { SessionContext } from "@opencode/plugin/promise/session";
|
|
3
|
+
import type { Candidate } from "../engine/planner.ts";
|
|
4
|
+
import type { RecoveryPlan } from "../recovery/store.ts";
|
|
5
|
+
export type History = Awaited<ReturnType<Context["session"]["context"]>>;
|
|
6
|
+
export type Assistant = Extract<History[number], {
|
|
7
|
+
type: "assistant";
|
|
8
|
+
}>;
|
|
9
|
+
type Message = SessionContext["messages"][number];
|
|
10
|
+
type ToolMessage = Extract<Message, {
|
|
11
|
+
role: "tool";
|
|
12
|
+
}>;
|
|
13
|
+
type ToolResult = ToolMessage["content"][number];
|
|
14
|
+
export declare const pairKey: (messageID: string, callID: string) => string;
|
|
15
|
+
export declare function visibleResults(messages: readonly Message[]): Map<string, {
|
|
16
|
+
index: number;
|
|
17
|
+
message: ToolMessage;
|
|
18
|
+
part: ToolResult;
|
|
19
|
+
text: string;
|
|
20
|
+
}>;
|
|
21
|
+
export declare function completedRounds(history: History, sessionID: string): Candidate[][];
|
|
22
|
+
export declare function completedProse(history: History, sessionID: string, currentTurn: string): Candidate[];
|
|
23
|
+
export declare function proseCandidate(step: Assistant, sessionID: string): Candidate | undefined;
|
|
24
|
+
export declare function visibleTargets(messages: readonly Message[]): Map<string, {
|
|
25
|
+
index: number;
|
|
26
|
+
partIndex: number;
|
|
27
|
+
name: string;
|
|
28
|
+
text: string;
|
|
29
|
+
}>;
|
|
30
|
+
export declare function completedTurnTokens(history: History, end: number, request: SessionContext): number | undefined;
|
|
31
|
+
export declare function activeReferences(history: History, plans: readonly RecoveryPlan[], visible: readonly unknown[]): Set<string>;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { canRewriteToolResult } from "../engine/eligibility.js";
|
|
2
|
+
import { recoveryReferences } from "../recovery/integrity.js";
|
|
3
|
+
export const pairKey = (messageID, callID) => JSON.stringify([messageID, callID]);
|
|
4
|
+
export function visibleResults(messages) {
|
|
5
|
+
const calls = new Map();
|
|
6
|
+
const results = new Map();
|
|
7
|
+
const seenResults = new Set();
|
|
8
|
+
for (const [index, message] of messages.entries()) {
|
|
9
|
+
if (message.role === "assistant" && message.id) {
|
|
10
|
+
for (const part of message.content) {
|
|
11
|
+
if (part.type !== "tool-call")
|
|
12
|
+
continue;
|
|
13
|
+
calls.set(part.id, calls.has(part.id) || part.providerExecuted ? undefined : { messageID: message.id, name: part.name });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
if (message.role !== "tool")
|
|
17
|
+
continue;
|
|
18
|
+
for (const part of message.content) {
|
|
19
|
+
const call = calls.get(part.id);
|
|
20
|
+
if (!call)
|
|
21
|
+
continue;
|
|
22
|
+
const key = pairKey(call.messageID, part.id);
|
|
23
|
+
if (seenResults.has(key))
|
|
24
|
+
results.delete(key);
|
|
25
|
+
else if (message.content.length === 1 &&
|
|
26
|
+
part.name === call.name &&
|
|
27
|
+
canRewriteToolResult(message, part) &&
|
|
28
|
+
typeof part.result === "object" && part.result !== null &&
|
|
29
|
+
"type" in part.result && part.result.type === "text" &&
|
|
30
|
+
"value" in part.result && typeof part.result.value === "string") {
|
|
31
|
+
results.set(key, { index, message, part, text: part.result.value });
|
|
32
|
+
}
|
|
33
|
+
seenResults.add(key);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// Even an ID collision discovered later invalidates a preceding match.
|
|
37
|
+
for (const [key, result] of results) {
|
|
38
|
+
if (!calls.get(result.part.id))
|
|
39
|
+
results.delete(key);
|
|
40
|
+
}
|
|
41
|
+
return results;
|
|
42
|
+
}
|
|
43
|
+
function hasTerminalRound(tools) {
|
|
44
|
+
return tools.length > 0 && tools.every((tool) => tool.state.status === "completed" || tool.state.status === "error");
|
|
45
|
+
}
|
|
46
|
+
export function completedRounds(history, sessionID) {
|
|
47
|
+
const pending = [];
|
|
48
|
+
const rounds = [];
|
|
49
|
+
const finish = (succeeded) => {
|
|
50
|
+
const eligible = succeeded && !pending.some((step) => step.error);
|
|
51
|
+
for (const step of pending) {
|
|
52
|
+
const tools = step.content.filter((part) => part.type === "tool");
|
|
53
|
+
if (!hasTerminalRound(tools))
|
|
54
|
+
continue;
|
|
55
|
+
rounds.push(eligible && tools.every((tool) => tool.state.status === "completed") ? tools.map((tool) => ({
|
|
56
|
+
identity: { sessionID, messageID: step.id, partID: tool.id, callID: tool.id, tool: tool.name },
|
|
57
|
+
tool,
|
|
58
|
+
})) : []);
|
|
59
|
+
}
|
|
60
|
+
pending.length = 0;
|
|
61
|
+
};
|
|
62
|
+
for (const entry of history) {
|
|
63
|
+
if (entry.type === "assistant")
|
|
64
|
+
pending.push(entry);
|
|
65
|
+
if (entry.type === "idle")
|
|
66
|
+
finish(entry.outcome === "succeeded");
|
|
67
|
+
}
|
|
68
|
+
// Called only by the host's successful end-of-work hook, before idle is persisted.
|
|
69
|
+
finish(true);
|
|
70
|
+
return rounds;
|
|
71
|
+
}
|
|
72
|
+
export function completedProse(history, sessionID, currentTurn) {
|
|
73
|
+
const candidates = [];
|
|
74
|
+
let pending = [];
|
|
75
|
+
for (const entry of history) {
|
|
76
|
+
if (entry.type === "assistant")
|
|
77
|
+
pending.push(entry);
|
|
78
|
+
if (entry.type !== "idle")
|
|
79
|
+
continue;
|
|
80
|
+
if (entry.outcome === "succeeded" && !pending.some((step) => step.error)) {
|
|
81
|
+
for (const step of pending) {
|
|
82
|
+
const candidate = step.id === currentTurn ? undefined : proseCandidate(step, sessionID);
|
|
83
|
+
if (candidate)
|
|
84
|
+
candidates.push(candidate);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
pending = [];
|
|
88
|
+
}
|
|
89
|
+
return candidates;
|
|
90
|
+
}
|
|
91
|
+
export function proseCandidate(step, sessionID) {
|
|
92
|
+
if (step.error || step.content.some((part) => part.type === "tool"))
|
|
93
|
+
return;
|
|
94
|
+
const text = step.content.filter((part) => part.type === "text");
|
|
95
|
+
if (text.length !== 1 || !text[0] || text[0].native !== undefined)
|
|
96
|
+
return;
|
|
97
|
+
return {
|
|
98
|
+
identity: { sessionID, messageID: step.id, callID: "text", partID: "text", tool: "assistant_text" },
|
|
99
|
+
tool: { id: "text", name: "assistant_text", type: "tool", time: { created: 0 },
|
|
100
|
+
state: { status: "completed", input: {}, content: [{ type: "text", text: text[0].text }] } },
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
export function visibleTargets(messages) {
|
|
104
|
+
const targets = new Map();
|
|
105
|
+
for (const [key, result] of visibleResults(messages)) {
|
|
106
|
+
targets.set(key, { index: result.index, partIndex: 0, name: result.part.name, text: result.text });
|
|
107
|
+
}
|
|
108
|
+
for (const [index, message] of messages.entries()) {
|
|
109
|
+
if (message.role !== "assistant" || !message.id ||
|
|
110
|
+
("providerMetadata" in message && message.providerMetadata !== undefined) ||
|
|
111
|
+
message.content.some((part) => part.type !== "text" && part.type !== "reasoning"))
|
|
112
|
+
continue;
|
|
113
|
+
const text = message.content.filter((part) => part.type === "text");
|
|
114
|
+
if (text.length !== 1 || !text[0] || text[0].providerMetadata !== undefined)
|
|
115
|
+
continue;
|
|
116
|
+
const key = pairKey(message.id, "text");
|
|
117
|
+
if (targets.has(key)) {
|
|
118
|
+
targets.delete(key);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
targets.set(key, { index, partIndex: message.content.indexOf(text[0]), name: "assistant_text", text: text[0].text });
|
|
122
|
+
}
|
|
123
|
+
return targets;
|
|
124
|
+
}
|
|
125
|
+
export function completedTurnTokens(history, end, request) {
|
|
126
|
+
const assistant = history.slice(0, end).findLast((entry) => entry.type === "assistant" || entry.type === "idle");
|
|
127
|
+
if (assistant?.type !== "assistant" || assistant.error || !assistant.tokens ||
|
|
128
|
+
assistant.agent !== request.agent || assistant.model.providerID !== request.model.providerID ||
|
|
129
|
+
assistant.model.id !== request.model.id || assistant.model.variant !== request.model.variant)
|
|
130
|
+
return undefined;
|
|
131
|
+
const { input, cache, output, reasoning } = assistant.tokens;
|
|
132
|
+
return input + cache.read + cache.write > 0 ? input + cache.read + cache.write + output + reasoning : undefined;
|
|
133
|
+
}
|
|
134
|
+
export function activeReferences(history, plans, visible) {
|
|
135
|
+
const parts = new Set();
|
|
136
|
+
const references = new Set();
|
|
137
|
+
const scan = (value) => {
|
|
138
|
+
if (typeof value === "string") {
|
|
139
|
+
for (const reference of recoveryReferences(value))
|
|
140
|
+
references.add(reference);
|
|
141
|
+
}
|
|
142
|
+
else if (value && typeof value === "object") {
|
|
143
|
+
for (const nested of Object.values(value))
|
|
144
|
+
scan(nested);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
for (const entry of history) {
|
|
148
|
+
if (entry.type === "assistant") {
|
|
149
|
+
for (const part of entry.content) {
|
|
150
|
+
if (part.type === "tool") {
|
|
151
|
+
parts.add(pairKey(entry.id, part.id));
|
|
152
|
+
if (part.state.status === "completed")
|
|
153
|
+
scan(part.state.content);
|
|
154
|
+
}
|
|
155
|
+
else
|
|
156
|
+
scan(part.text);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
else if (entry.type === "compaction" && entry.status === "completed") {
|
|
160
|
+
scan(entry);
|
|
161
|
+
}
|
|
162
|
+
else if ("text" in entry)
|
|
163
|
+
scan(entry.text);
|
|
164
|
+
}
|
|
165
|
+
for (const plan of plans) {
|
|
166
|
+
if (parts.has(pairKey(plan.identity.messageID, plan.identity.callID)))
|
|
167
|
+
references.add(plan.reference);
|
|
168
|
+
}
|
|
169
|
+
for (const value of visible)
|
|
170
|
+
scan(value);
|
|
171
|
+
return references;
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=reconciliation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconciliation.js","sourceRoot":"","sources":["../../src/state/reconciliation.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAA;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAU7D,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,SAAiB,EAAE,MAAc,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAA;AAEjG,MAAM,UAAU,cAAc,CAAC,QAA4B;IACzD,MAAM,K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
|
4
|
+
|
|
5
|
+
## How it works
|
|
6
|
+
|
|
7
|
+
1. OpenCode's idle hook signals successful completion with no pending inputs. The plugin checks the completed tool states and skips work when background jobs are still running. The active turn and the latest three completed tool rounds stay intact by default.
|
|
8
|
+
2. The planner considers completed history after the last visible checkpoint. Eligible content includes older assistant prose, stock reads, file listings, searches, and verified successful foreground shell output. Each cut must contain at least 1,000 estimated tokens of source text selected for shortening by default; a span can combine several smaller entries. Preserved reasoning, tool-call arguments, and unchanged results do not count toward that minimum. Ordinary cuts contain at most 32,000 estimated source tokens. Every changed entry must reduce both estimated tokens and serialized size, including its checkpoint and recall reference; saving fewer than 1,000 tokens is allowed. It compares batches of up to three completed spans or individual results. Each span stays within completed work and user/checkpoint boundaries. Shortened entries share an archive reference, with their replacement text bounded by an 8,000-code-point budget per span.
|
|
9
|
+
3. The planner ranks useful batches by estimated tokens saved, discounted by the retained suffix after the earliest cut: `saved / (1 + suffix / saved)`. This favors larger reductions and shorter suffixes without rejecting a useful cut because of cache prices. It is a selection heuristic, not a cost estimate. Originals are preserved together in one durable transaction before queuing a local compaction. The compaction hook rechecks the queued item, original contents, and prefix, then constructs the replacement window by copying only changed messages. The host persists it and uses it to size later requests. [OpenCode compaction hook](https://opencode.ai/docs/build/plugins/server#hooks)
|
|
10
|
+
4. OpenCode replays the saved window on the same provider and model. On a model switch, the host falls back to the original history. Stock compaction stays enabled, and later successful turns can create new replacement windows.
|
|
11
|
+
|
|
12
|
+
Use `live_compact_recall` in the source session with the reference and an optional Unicode code point offset. Each page contains up to 2,048 code points and a continuation offset. A span reference returns the exact serialized OpenCode messages, including the original call IDs and results. A fork can inherit a checkpoint, but its reference remains scoped to the source session.
|
|
13
|
+
|
|
14
|
+
Span cuts preserve OpenCode's mixed messages in place. Reasoning, tool calls, their arguments, result IDs, and message order remain unchanged; only eligible result text or eligible older assistant text is shortened. Unsupported results in a parallel tool round stay intact. The archive stores the exact original span and a validated replacement recipe, so replay after a restart applies the same edits. Preserved reasoning and tool-call tokens are excluded from estimated savings.
|
|
15
|
+
|
|
16
|
+
OpenCode records each local replacement as a compaction event and stores the full active window for that event. The benchmark separates these events from stock compaction and records their start-to-end durations. These intervals do not directly measure user-visible waiting: planning can occur before an event, while application overlaps it. A full-context replay is local maintenance, not another cut or a native summary. Compatibility was verified with stock compaction defaults.
|
|
17
|
+
|
|
18
|
+
User messages, system instructions, provider-bound reasoning, recent assistant responses, diagnostics, and active or interrupted work stay intact. Cuts use a local byte-based token estimate. Actual prompt-cache reuse and billing depend on the provider and workload.
|
|
19
|
+
|
|
20
|
+
An otherwise eligible tool result above 32,000 estimated tokens can use a small recovery pointer instead of an excerpt. Its exact header, truncation notice, and observed status remain. This exception never applies to assistant prose. The full original must fit the archive's 512 KiB per-record limit and be stored successfully; otherwise it stays visible.
|
|
21
|
+
|
|
22
|
+
## Configuration
|
|
23
|
+
|
|
24
|
+
| Option | Default | Effect |
|
|
25
|
+
| --- | ---: | --- |
|
|
26
|
+
| `minimumContextTokens` | 20,000 | Start evaluating cuts at this completed-turn token usage. Use a local estimate when provider usage is unavailable. |
|
|
27
|
+
| `minimumSourceTokens` | 1,000 | Minimum estimated source tokens selected for shortening in one result or completed span. Every replacement must still be strictly smaller. |
|
|
28
|
+
| `protectedToolRounds` | 3 | Number of most recent completed tool rounds to keep. |
|
|
29
|
+
| `maxCutsPerCycle` | 3 | Maximum completed spans or individual results replaced in one successful-turn maintenance cycle. |
|
|
30
|
+
| `archiveDirectory` | OS-local state directory | Optional absolute directory for the private archive. |
|
|
31
|
+
| `archiveMaxBytes` | 256 MiB | Combined limit across all session archives, excluding SQLite overhead. Before a write would exceed it, remove the oldest retired records toward 80% usage. |
|
|
32
|
+
| `archiveMaxRecords` | 4,096 | Maximum number of archive records. |
|
|
33
|
+
| `archiveRetentionMs` | 7 days | Normal grace period for retired records. Capacity pressure can remove them sooner; active checkpoints stay protected. |
|
|
34
|
+
| `compactSpans` | `true` | Group adjacent eligible completed results or prose into a checkpoint without crossing a user message, protected content, or an existing checkpoint. |
|
|
35
|
+
| `dryRun` | `false` | Evaluate cuts without changing requests or saving new cuts. |
|
|
36
|
+
| `diagnostics` | `false` | Emit planning reasons, candidate counts, selected span or individual strategy, separate planning/application durations, cuts, and recall measurements without transcript content. |
|
|
37
|
+
| `metricsFile` | stderr | Optional absolute JSON Lines destination for diagnostics. |
|
|
38
|
+
|
|
39
|
+
The archive holds local copies of eligible output and uses owner-only permissions. It uses `$XDG_STATE_HOME/opencode-live-compact` when set. Otherwise it uses `%LOCALAPPDATA%/opencode-live-compact` on Windows and `~/.local/state/opencode-live-compact` elsewhere. Recovery files live under `recovery-v1/sessions/session-<session-hash>/<reference>.json`; the session hash prevents unsafe paths and name collisions. A shared SQLite catalog tracks integrity, references, and the total budget. Existing inline backups migrate without changing recall references.
|
|
40
|
+
|
|
41
|
+
Before a write would exceed the global 256 MiB cap, cleanup removes the oldest retired records first and aims to leave usage at or below 80%, including the incoming batch. Normal cleanup also removes retired records after their retention period. Active checkpoints and references being preserved in the current batch are never evicted. A stopped process alone does not make an OpenCode session's backups disposable. If protected records leave insufficient room, or preservation fails, the plugin keeps the full original context.
|
|
42
|
+
|
|
43
|
+
When handling a queued replacement, the plugin retries a failed pending-plan or history read once. If both attempts fail, OpenCode 2.2.6's compaction hook does not provide enough identity information to safely distinguish plugin maintenance from native compaction. The plugin reports `compaction-ownership-unavailable` and leaves the host in control; a model summary remains possible on this error path. Once ownership is confirmed, an unavailable archive produces a full local replay without a summary request.
|
|
44
|
+
|
|
45
|
+
The plugin measures the request once at idle instead of scanning its complete text for every context-hook diagnostic. Both planners reuse the same parsed eligible outputs within that synchronous planning cycle; the cache is cleared before asynchronous admission and is never reused across turns. Span processing checks message/call/result identities across the complete history, but parses detailed blocks only for candidate or verified archived spans. Span application also avoids building an unused individual-result index.
|
|
46
|
+
|
|
47
|
+
Queued application still rereads authoritative history and durable backups and verifies their hashes, tool pairs, and unchanged prefix. Recovery reads for a bounded cut batch share one catalog transaction; every payload is still checked afresh. A single filesystem stat validates the recovery root's type, permissions, and identity together. These optimizations do not change selection rules or skip preservation checks. Planning needs no model-price lookup. The stock host still serializes and persists each replacement window; local processing cannot have zero cost.
|
|
48
|
+
|
|
49
|
+
The span planner evaluates smaller contiguous alternatives as well as larger spans, then selects nonoverlapping cuts under the same safety and size limits. The cache-suffix estimate starts at the first edited part, excluding preserved reasoning and calls before it while including retained parts after it, even within the same message. This keeps span and individual cut ranking consistent; the estimate is not a measurement of the provider's cache. Replacement windows retain the evidence for all unchanged eligible tool rounds after the last cut, so later turns can still reduce them while preserving recent-round protection.
|
|
50
|
+
|
|
51
|
+
Individual previews normally keep up to six lines at each end. If that preview would not reduce both estimated tokens and serialized bytes, the reducer retries with up to three lines, then one line at each end. File coordinates, truncation notices, recovery references, and safety checks remain intact. If none of these previews shrinks the result, it stays unchanged.
|
|
52
|
+
|
|
53
|
+
Planning diagnostics include the context size, eligible candidate counts, source token totals, counts below or at/above the source minimum, and the number of size-valid candidates and batches evaluated. Short eligible results can still combine into a span. `insufficient-savings` means neither planning route found a useful cut; it does not mean cache profitability rejected a valid plan. Diagnostics contain counts rather than source text. Estimated savings and retained suffix size are reported for applied replacements; actual API savings still require a paired benchmark.
|
|
54
|
+
|