@soiljs/storage-local 0.0.0-stage → 0.2.0
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 +21 -0
- package/README.md +98 -2
- package/dist/index.d.ts +14 -0
- package/dist/index.js +1459 -0
- package/dist/index.js.map +1 -0
- package/package.json +40 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1459 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { readdir, stat, readFile, mkdir, open, rename, unlink } from 'node:fs/promises';
|
|
6
|
+
import { isTerminalTurnStatus, IdempotencyConflictError, isTerminalStepStatus, HostControlError, LeaseLostError, ConcurrencyConflictError, SessionBusyError } from '@soiljs/spi';
|
|
7
|
+
|
|
8
|
+
// src/database.ts
|
|
9
|
+
var migrationV1 = `
|
|
10
|
+
CREATE TABLE metadata (key TEXT PRIMARY KEY, value INTEGER NOT NULL);
|
|
11
|
+
INSERT INTO metadata VALUES ('seq', 0), ('queue', 0);
|
|
12
|
+
CREATE TABLE sessions (id TEXT PRIMARY KEY, data TEXT NOT NULL);
|
|
13
|
+
CREATE TABLE turns (
|
|
14
|
+
position INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
15
|
+
id TEXT NOT NULL UNIQUE,
|
|
16
|
+
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
17
|
+
status TEXT NOT NULL,
|
|
18
|
+
parent_turn_id TEXT,
|
|
19
|
+
parent_step_id TEXT,
|
|
20
|
+
data TEXT NOT NULL,
|
|
21
|
+
UNIQUE(parent_turn_id, parent_step_id)
|
|
22
|
+
);
|
|
23
|
+
CREATE UNIQUE INDEX single_active_turn ON turns(session_id)
|
|
24
|
+
WHERE status NOT IN ('queued', 'completed', 'failed', 'cancelled');
|
|
25
|
+
CREATE INDEX session_turns ON turns(session_id, position);
|
|
26
|
+
CREATE TABLE entries (
|
|
27
|
+
turn_id TEXT NOT NULL REFERENCES turns(id),
|
|
28
|
+
kind TEXT NOT NULL,
|
|
29
|
+
id TEXT NOT NULL,
|
|
30
|
+
ordinal INTEGER NOT NULL,
|
|
31
|
+
data TEXT NOT NULL,
|
|
32
|
+
input_head TEXT,
|
|
33
|
+
PRIMARY KEY(turn_id, kind, id)
|
|
34
|
+
);
|
|
35
|
+
CREATE INDEX ordered_entries ON entries(turn_id, kind, ordinal);
|
|
36
|
+
CREATE TABLE model_input_nodes (id TEXT PRIMARY KEY, previous TEXT NOT NULL, data TEXT NOT NULL);
|
|
37
|
+
CREATE TABLE epochs (id TEXT PRIMARY KEY, data TEXT NOT NULL);
|
|
38
|
+
CREATE TABLE commands (id TEXT PRIMARY KEY, data TEXT NOT NULL);
|
|
39
|
+
CREATE TABLE admissions (id TEXT PRIMARY KEY, data TEXT NOT NULL);
|
|
40
|
+
CREATE TABLE outbox (seq INTEGER PRIMARY KEY, occurred_at TEXT NOT NULL, data TEXT NOT NULL);
|
|
41
|
+
CREATE INDEX outbox_age ON outbox(occurred_at);
|
|
42
|
+
CREATE TABLE consumers (id TEXT PRIMARY KEY, seq INTEGER NOT NULL);
|
|
43
|
+
CREATE TABLE gaps (to_seq INTEGER PRIMARY KEY, reason TEXT NOT NULL);
|
|
44
|
+
CREATE TABLE artifact_refs (
|
|
45
|
+
sha256 TEXT NOT NULL,
|
|
46
|
+
owner TEXT NOT NULL,
|
|
47
|
+
PRIMARY KEY(sha256, owner)
|
|
48
|
+
);
|
|
49
|
+
PRAGMA user_version = 1;
|
|
50
|
+
`;
|
|
51
|
+
var EntityMap = class {
|
|
52
|
+
constructor(db, table) {
|
|
53
|
+
this.db = db;
|
|
54
|
+
this.table = table;
|
|
55
|
+
}
|
|
56
|
+
db;
|
|
57
|
+
table;
|
|
58
|
+
cache = /* @__PURE__ */ new Map();
|
|
59
|
+
originals = /* @__PURE__ */ new Map();
|
|
60
|
+
clear() {
|
|
61
|
+
this.cache.clear();
|
|
62
|
+
this.originals.clear();
|
|
63
|
+
}
|
|
64
|
+
get(id) {
|
|
65
|
+
if (this.db.inTransaction && this.cache.has(id)) return this.cache.get(id);
|
|
66
|
+
const row = this.db.connection.prepare(`SELECT data FROM ${this.table} WHERE id = ?`).get(id);
|
|
67
|
+
if (!row) return void 0;
|
|
68
|
+
const raw = String(row.data);
|
|
69
|
+
const value = this.table === "turns" ? this.db.loadSnapshot(JSON.parse(raw)) : JSON.parse(raw);
|
|
70
|
+
if (this.db.inTransaction) {
|
|
71
|
+
this.cache.set(id, value);
|
|
72
|
+
this.originals.set(id, JSON.stringify(value));
|
|
73
|
+
}
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
has(id) {
|
|
77
|
+
return this.get(id) !== void 0;
|
|
78
|
+
}
|
|
79
|
+
set(id, value) {
|
|
80
|
+
this.cache.set(id, value);
|
|
81
|
+
return this;
|
|
82
|
+
}
|
|
83
|
+
*values() {
|
|
84
|
+
const order = this.table === "turns" ? "position" : "rowid";
|
|
85
|
+
const ids = this.db.connection.prepare(`SELECT id FROM ${this.table} ORDER BY ${order}`).all();
|
|
86
|
+
const visited = /* @__PURE__ */ new Set();
|
|
87
|
+
for (const row of ids) {
|
|
88
|
+
const id = String(row.id);
|
|
89
|
+
visited.add(id);
|
|
90
|
+
yield this.get(id);
|
|
91
|
+
}
|
|
92
|
+
for (const [id, value] of this.cache) if (!visited.has(id)) yield value;
|
|
93
|
+
}
|
|
94
|
+
/** Targeted Turn traversal keeps queue and cascade writes independent of unrelated history. */
|
|
95
|
+
*turnsWhere(filter) {
|
|
96
|
+
const matches = (value) => {
|
|
97
|
+
const turn = value.turn;
|
|
98
|
+
return (filter.sessionId === void 0 || turn.sessionId === filter.sessionId) && (filter.parentTurnId === void 0 || turn.parentTurnId === filter.parentTurnId) && (filter.status === void 0 || turn.status === filter.status);
|
|
99
|
+
};
|
|
100
|
+
const rows = this.db.connection.prepare(
|
|
101
|
+
`SELECT id FROM turns WHERE
|
|
102
|
+
(? IS NULL OR session_id = ?) AND (? IS NULL OR parent_turn_id = ?)
|
|
103
|
+
AND (? IS NULL OR status = ?) ORDER BY position`
|
|
104
|
+
).all(
|
|
105
|
+
filter.sessionId ?? null,
|
|
106
|
+
filter.sessionId ?? null,
|
|
107
|
+
filter.parentTurnId ?? null,
|
|
108
|
+
filter.parentTurnId ?? null,
|
|
109
|
+
filter.status ?? null,
|
|
110
|
+
filter.status ?? null
|
|
111
|
+
);
|
|
112
|
+
const visited = /* @__PURE__ */ new Set();
|
|
113
|
+
for (const row of rows) {
|
|
114
|
+
const id = String(row.id);
|
|
115
|
+
visited.add(id);
|
|
116
|
+
const value = this.get(id);
|
|
117
|
+
if (matches(value)) yield value;
|
|
118
|
+
}
|
|
119
|
+
for (const [id, value] of this.cache) if (!visited.has(id) && matches(value)) yield value;
|
|
120
|
+
}
|
|
121
|
+
flush() {
|
|
122
|
+
for (const [id, value] of this.cache) {
|
|
123
|
+
const data = JSON.stringify(value);
|
|
124
|
+
if (data === this.originals.get(id)) continue;
|
|
125
|
+
if (this.table === "turns")
|
|
126
|
+
this.db.saveSnapshot(
|
|
127
|
+
value,
|
|
128
|
+
this.originals.has(id) ? JSON.parse(this.originals.get(id)) : void 0
|
|
129
|
+
);
|
|
130
|
+
else
|
|
131
|
+
this.db.connection.prepare(
|
|
132
|
+
`INSERT INTO ${this.table}(id, data) VALUES (?, ?)
|
|
133
|
+
ON CONFLICT(id) DO UPDATE SET data = excluded.data`
|
|
134
|
+
).run(id, data);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
var LocalDatabase = class {
|
|
139
|
+
constructor(dir, busyTimeoutMs) {
|
|
140
|
+
this.dir = dir;
|
|
141
|
+
this.busyTimeoutMs = busyTimeoutMs;
|
|
142
|
+
}
|
|
143
|
+
dir;
|
|
144
|
+
busyTimeoutMs;
|
|
145
|
+
handle;
|
|
146
|
+
maps = [];
|
|
147
|
+
inTransaction = false;
|
|
148
|
+
events = [];
|
|
149
|
+
get connection() {
|
|
150
|
+
if (!this.handle) throw new Error("Local storage is not open.");
|
|
151
|
+
return this.handle;
|
|
152
|
+
}
|
|
153
|
+
open() {
|
|
154
|
+
if (this.handle) return;
|
|
155
|
+
mkdirSync(this.dir, { recursive: true });
|
|
156
|
+
const handle = new DatabaseSync(join(this.dir, "ledger.sqlite"));
|
|
157
|
+
try {
|
|
158
|
+
handle.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs};
|
|
159
|
+
PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; PRAGMA foreign_keys = ON;`);
|
|
160
|
+
handle.exec("BEGIN IMMEDIATE");
|
|
161
|
+
const version = Number(handle.prepare("PRAGMA user_version").get().user_version);
|
|
162
|
+
if (version === 0) handle.exec(migrationV1);
|
|
163
|
+
else if (version !== 1)
|
|
164
|
+
throw new Error(`Unsupported local storage schema version ${version}.`);
|
|
165
|
+
handle.exec("COMMIT");
|
|
166
|
+
this.handle = handle;
|
|
167
|
+
} catch (error) {
|
|
168
|
+
handle.close();
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
close() {
|
|
173
|
+
this.handle?.close();
|
|
174
|
+
this.handle = void 0;
|
|
175
|
+
for (const map of this.maps) map.clear();
|
|
176
|
+
}
|
|
177
|
+
map(table) {
|
|
178
|
+
const map = new EntityMap(this, table);
|
|
179
|
+
this.maps.push(map);
|
|
180
|
+
return map;
|
|
181
|
+
}
|
|
182
|
+
counter(key) {
|
|
183
|
+
return Number(
|
|
184
|
+
this.connection.prepare("SELECT value FROM metadata WHERE key = ?").get(key).value
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
setCounter(key, value) {
|
|
188
|
+
this.connection.prepare("UPDATE metadata SET value = ? WHERE key = ?").run(value, key);
|
|
189
|
+
}
|
|
190
|
+
transaction(fn, beforeCommit) {
|
|
191
|
+
try {
|
|
192
|
+
return Promise.resolve(this.atomic(fn, beforeCommit));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
return Promise.reject(error);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async read(fn) {
|
|
198
|
+
const db = this.connection;
|
|
199
|
+
db.exec("BEGIN");
|
|
200
|
+
try {
|
|
201
|
+
const result = structuredClone(fn());
|
|
202
|
+
db.exec("COMMIT");
|
|
203
|
+
return result;
|
|
204
|
+
} catch (error) {
|
|
205
|
+
db.exec("ROLLBACK");
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
atomic(fn, beforeCommit) {
|
|
210
|
+
const db = this.connection;
|
|
211
|
+
db.exec("BEGIN IMMEDIATE");
|
|
212
|
+
this.inTransaction = true;
|
|
213
|
+
this.events = [];
|
|
214
|
+
try {
|
|
215
|
+
const result = structuredClone(fn());
|
|
216
|
+
for (const map of this.maps) map.flush();
|
|
217
|
+
const insert = db.prepare("INSERT INTO outbox(seq, occurred_at, data) VALUES (?, ?, ?)");
|
|
218
|
+
for (const event of this.events)
|
|
219
|
+
insert.run(event.seq, event.occurredAt, JSON.stringify(event));
|
|
220
|
+
beforeCommit?.();
|
|
221
|
+
db.exec("COMMIT");
|
|
222
|
+
return result;
|
|
223
|
+
} catch (error) {
|
|
224
|
+
db.exec("ROLLBACK");
|
|
225
|
+
throw error;
|
|
226
|
+
} finally {
|
|
227
|
+
this.inTransaction = false;
|
|
228
|
+
this.events = [];
|
|
229
|
+
for (const map of this.maps) map.clear();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
loadSnapshot(turn, afterStepId) {
|
|
233
|
+
const after = afterStepId ? this.connection.prepare("SELECT ordinal FROM entries WHERE turn_id = ? AND kind = 'steps' AND id = ?").get(turn.turnId, afterStepId)?.ordinal : void 0;
|
|
234
|
+
const entries = this.connection.prepare(
|
|
235
|
+
"SELECT kind, data, input_head FROM entries WHERE turn_id = ? AND (kind <> 'steps' OR ordinal > ?) ORDER BY ordinal"
|
|
236
|
+
).all(turn.turnId, Number(after ?? -1));
|
|
237
|
+
const result = {
|
|
238
|
+
turn,
|
|
239
|
+
steps: [],
|
|
240
|
+
attempts: [],
|
|
241
|
+
steering: [],
|
|
242
|
+
approvals: []
|
|
243
|
+
};
|
|
244
|
+
for (const row of entries) {
|
|
245
|
+
const kind = String(row.kind);
|
|
246
|
+
const entry = JSON.parse(String(row.data));
|
|
247
|
+
if (row.input_head !== null) entry.input = this.loadModelInput(String(row.input_head));
|
|
248
|
+
result[kind].push(entry);
|
|
249
|
+
}
|
|
250
|
+
return result;
|
|
251
|
+
}
|
|
252
|
+
saveSnapshot(snap, previous) {
|
|
253
|
+
const db = this.connection;
|
|
254
|
+
const turn = snap.turn;
|
|
255
|
+
db.prepare(
|
|
256
|
+
`INSERT INTO turns(id, session_id, status, parent_turn_id, parent_step_id, data)
|
|
257
|
+
VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET
|
|
258
|
+
status=excluded.status, parent_turn_id=excluded.parent_turn_id,
|
|
259
|
+
parent_step_id=excluded.parent_step_id, data=excluded.data`
|
|
260
|
+
).run(
|
|
261
|
+
turn.turnId,
|
|
262
|
+
turn.sessionId,
|
|
263
|
+
turn.status,
|
|
264
|
+
turn.parentTurnId ?? null,
|
|
265
|
+
turn.parentStepId ?? null,
|
|
266
|
+
JSON.stringify(turn)
|
|
267
|
+
);
|
|
268
|
+
this.recordReferences(`turn:${turn.turnId}`, turn.artifacts);
|
|
269
|
+
const insert = db.prepare(`INSERT INTO entries(turn_id, kind, id, ordinal, data, input_head)
|
|
270
|
+
VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(turn_id, kind, id) DO UPDATE SET
|
|
271
|
+
data=excluded.data, input_head=excluded.input_head
|
|
272
|
+
WHERE entries.data <> excluded.data OR entries.input_head IS NOT excluded.input_head`);
|
|
273
|
+
for (const kind of ["steps", "attempts", "steering", "approvals"]) {
|
|
274
|
+
for (const [index, entry] of snap[kind].entries()) {
|
|
275
|
+
if (JSON.stringify(entry) === JSON.stringify(previous?.[kind][index])) continue;
|
|
276
|
+
const id = "attemptNo" in entry ? `${entry.stepId}:${entry.attemptNo}` : "steeringId" in entry ? entry.steeringId : "approvalId" in entry && !("kind" in entry) ? entry.approvalId : entry.stepId;
|
|
277
|
+
let persisted = entry;
|
|
278
|
+
let inputHead = null;
|
|
279
|
+
if ("kind" in entry && entry.kind === "model_call" && Array.isArray(entry.input)) {
|
|
280
|
+
const { input, ...rest } = entry;
|
|
281
|
+
inputHead = this.storeModelInput(input);
|
|
282
|
+
persisted = rest;
|
|
283
|
+
}
|
|
284
|
+
insert.run(turn.turnId, kind, id, index, JSON.stringify(persisted), inputHead);
|
|
285
|
+
if ("artifacts" in entry)
|
|
286
|
+
this.recordReferences(`${turn.turnId}:${kind}:${id}`, entry.artifacts);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** A persistent prefix chain shares model context across Steps instead of O(N²) copies. */
|
|
291
|
+
storeModelInput(messages) {
|
|
292
|
+
let head = "";
|
|
293
|
+
const insert = this.connection.prepare(
|
|
294
|
+
"INSERT OR IGNORE INTO model_input_nodes(id, previous, data) VALUES (?, ?, ?)"
|
|
295
|
+
);
|
|
296
|
+
for (const message of messages) {
|
|
297
|
+
const data = JSON.stringify(message);
|
|
298
|
+
const id = createHash("sha256").update(JSON.stringify([head, data])).digest("hex");
|
|
299
|
+
insert.run(id, head, data);
|
|
300
|
+
head = id;
|
|
301
|
+
}
|
|
302
|
+
return head;
|
|
303
|
+
}
|
|
304
|
+
loadModelInput(head) {
|
|
305
|
+
const messages = [];
|
|
306
|
+
const select = this.connection.prepare(
|
|
307
|
+
"SELECT previous, data FROM model_input_nodes WHERE id = ?"
|
|
308
|
+
);
|
|
309
|
+
while (head) {
|
|
310
|
+
const node = select.get(head);
|
|
311
|
+
if (!node) throw new Error("Missing persisted model input prefix.");
|
|
312
|
+
messages.push(JSON.parse(String(node.data)));
|
|
313
|
+
head = String(node.previous);
|
|
314
|
+
}
|
|
315
|
+
return messages.reverse();
|
|
316
|
+
}
|
|
317
|
+
listTurns(sessionId) {
|
|
318
|
+
const rows = sessionId === void 0 ? this.connection.prepare(
|
|
319
|
+
"SELECT data FROM turns WHERE status NOT IN ('queued', 'completed', 'failed', 'cancelled') ORDER BY position"
|
|
320
|
+
).all() : this.connection.prepare("SELECT data FROM turns WHERE session_id = ? ORDER BY position").all(sessionId);
|
|
321
|
+
return rows.map((row) => JSON.parse(String(row.data)));
|
|
322
|
+
}
|
|
323
|
+
snapshot(id, afterStepId) {
|
|
324
|
+
const row = this.connection.prepare("SELECT data FROM turns WHERE id = ?").get(id);
|
|
325
|
+
return row ? this.loadSnapshot(JSON.parse(String(row.data)), afterStepId) : void 0;
|
|
326
|
+
}
|
|
327
|
+
recordReferences(owner, refs) {
|
|
328
|
+
if (!refs) return;
|
|
329
|
+
const insert = this.connection.prepare(
|
|
330
|
+
"INSERT OR IGNORE INTO artifact_refs(sha256, owner) VALUES (?, ?)"
|
|
331
|
+
);
|
|
332
|
+
for (const ref of refs) insert.run(ref.sha256, owner);
|
|
333
|
+
}
|
|
334
|
+
isReferenced(sha256) {
|
|
335
|
+
return !!this.connection.prepare("SELECT 1 FROM artifact_refs WHERE sha256 = ? LIMIT 1").get(sha256);
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
var digest = (data) => createHash("sha256").update(data).digest("hex");
|
|
339
|
+
async function syncDirectory(path) {
|
|
340
|
+
const handle = await open(path, "r");
|
|
341
|
+
try {
|
|
342
|
+
await handle.sync();
|
|
343
|
+
} finally {
|
|
344
|
+
await handle.close();
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function missing(error) {
|
|
348
|
+
return error.code === "ENOENT";
|
|
349
|
+
}
|
|
350
|
+
function localArtifacts(db, dir) {
|
|
351
|
+
const root = join(dir, "artifacts", "sha256");
|
|
352
|
+
function pathFor(hash) {
|
|
353
|
+
if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error("Invalid artifact SHA-256.");
|
|
354
|
+
return join(root, hash.slice(0, 2), hash);
|
|
355
|
+
}
|
|
356
|
+
return {
|
|
357
|
+
async put(input) {
|
|
358
|
+
const data = new Uint8Array(input.data);
|
|
359
|
+
const sha256 = digest(data);
|
|
360
|
+
const directory = join(root, sha256.slice(0, 2));
|
|
361
|
+
const target = pathFor(sha256);
|
|
362
|
+
await mkdir(directory, { recursive: true });
|
|
363
|
+
await syncDirectory(dir);
|
|
364
|
+
await syncDirectory(join(dir, "artifacts"));
|
|
365
|
+
await syncDirectory(root);
|
|
366
|
+
try {
|
|
367
|
+
const existing = await readFile(target);
|
|
368
|
+
if (digest(existing) !== sha256) throw new Error("Artifact integrity check failed.");
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (!missing(error)) throw error;
|
|
371
|
+
const temporary = join(directory, `.${sha256}.${randomUUID()}.tmp`);
|
|
372
|
+
try {
|
|
373
|
+
const handle = await open(temporary, "wx", 384);
|
|
374
|
+
try {
|
|
375
|
+
await handle.writeFile(data);
|
|
376
|
+
await handle.sync();
|
|
377
|
+
} finally {
|
|
378
|
+
await handle.close();
|
|
379
|
+
}
|
|
380
|
+
await rename(temporary, target);
|
|
381
|
+
await syncDirectory(directory);
|
|
382
|
+
} finally {
|
|
383
|
+
await unlink(temporary).catch((error2) => {
|
|
384
|
+
if (!missing(error2)) throw error2;
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
await syncDirectory(directory);
|
|
389
|
+
return {
|
|
390
|
+
uri: `local://sha256/${sha256}`,
|
|
391
|
+
sha256,
|
|
392
|
+
byteSize: data.byteLength,
|
|
393
|
+
contentType: input.contentType
|
|
394
|
+
};
|
|
395
|
+
},
|
|
396
|
+
async get(ref) {
|
|
397
|
+
try {
|
|
398
|
+
const data = await readFile(pathFor(ref.sha256));
|
|
399
|
+
if (digest(data) !== ref.sha256 || data.byteLength !== ref.byteSize)
|
|
400
|
+
throw new Error("Artifact integrity check failed.");
|
|
401
|
+
return new Uint8Array(data);
|
|
402
|
+
} catch (error) {
|
|
403
|
+
if (missing(error)) return null;
|
|
404
|
+
throw error;
|
|
405
|
+
}
|
|
406
|
+
},
|
|
407
|
+
async pruneUnreferenced(options) {
|
|
408
|
+
let deletedCount = 0, freedBytes = 0;
|
|
409
|
+
let prefixes;
|
|
410
|
+
try {
|
|
411
|
+
prefixes = await readdir(root);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
if (missing(error)) return { deletedCount, freedBytes };
|
|
414
|
+
throw error;
|
|
415
|
+
}
|
|
416
|
+
for (const prefix of prefixes) {
|
|
417
|
+
if (!/^[a-f0-9]{2}$/.test(prefix)) continue;
|
|
418
|
+
for (const hash of await readdir(join(root, prefix))) {
|
|
419
|
+
if (!/^[a-f0-9]{64}$/.test(hash) || !hash.startsWith(prefix)) continue;
|
|
420
|
+
if (deletedCount >= (options.limit ?? Infinity)) return { deletedCount, freedBytes };
|
|
421
|
+
const path = pathFor(hash);
|
|
422
|
+
let metadata;
|
|
423
|
+
try {
|
|
424
|
+
metadata = await stat(path);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
if (missing(error)) continue;
|
|
427
|
+
throw error;
|
|
428
|
+
}
|
|
429
|
+
if (metadata.mtimeMs >= Date.parse(options.olderThan) || await options.isReferenced(hash))
|
|
430
|
+
continue;
|
|
431
|
+
const removed = db.atomic(() => {
|
|
432
|
+
if (db.isReferenced(hash)) return false;
|
|
433
|
+
return removeOrphan(path);
|
|
434
|
+
});
|
|
435
|
+
if (removed) {
|
|
436
|
+
deletedCount++;
|
|
437
|
+
freedBytes += metadata.size;
|
|
438
|
+
await syncDirectory(join(root, prefix));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return { deletedCount, freedBytes };
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
function removeOrphan(path) {
|
|
447
|
+
try {
|
|
448
|
+
unlinkSync(path);
|
|
449
|
+
return true;
|
|
450
|
+
} catch (error) {
|
|
451
|
+
if (missing(error)) return false;
|
|
452
|
+
throw error;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// src/outbox.ts
|
|
457
|
+
function validate(value, name) {
|
|
458
|
+
if (value !== void 0 && (!Number.isFinite(value) || value < 0))
|
|
459
|
+
throw new RangeError(`${name} must be nonnegative and finite.`);
|
|
460
|
+
}
|
|
461
|
+
function localOutbox(db, retention) {
|
|
462
|
+
validate(retention?.maxRetentionDays, "maxRetentionDays");
|
|
463
|
+
validate(retention?.maxPendingEvents, "maxPendingEvents");
|
|
464
|
+
function prune(policy) {
|
|
465
|
+
validate(policy.maxRetentionMs, "maxRetentionMs");
|
|
466
|
+
validate(policy.maxPendingEvents, "maxPendingEvents");
|
|
467
|
+
const applyPrune = () => {
|
|
468
|
+
const sql = db.connection;
|
|
469
|
+
let prunedCount = 0;
|
|
470
|
+
function removeThrough(seq, reason) {
|
|
471
|
+
if (seq <= 0) return;
|
|
472
|
+
const removed = Number(sql.prepare("DELETE FROM outbox WHERE seq <= ?").run(seq).changes);
|
|
473
|
+
if (!removed) return;
|
|
474
|
+
prunedCount += removed;
|
|
475
|
+
sql.exec("DELETE FROM gaps");
|
|
476
|
+
sql.prepare("INSERT INTO gaps(to_seq, reason) VALUES (?, ?)").run(seq, reason);
|
|
477
|
+
}
|
|
478
|
+
if (policy.maxRetentionMs !== void 0) {
|
|
479
|
+
const cutoff = new Date(Date.now() - policy.maxRetentionMs).toISOString();
|
|
480
|
+
const row = sql.prepare("SELECT MAX(seq) AS seq FROM outbox WHERE occurred_at <= ?").get(cutoff);
|
|
481
|
+
removeThrough(Number(row?.seq ?? 0), "retention_ttl");
|
|
482
|
+
}
|
|
483
|
+
if (policy.maxPendingEvents !== void 0 && Number(sql.prepare("SELECT COUNT(*) AS count FROM outbox").get().count) > policy.maxPendingEvents) {
|
|
484
|
+
const row = sql.prepare("SELECT seq FROM outbox ORDER BY seq DESC LIMIT 1 OFFSET ?").get(Math.floor(policy.maxPendingEvents));
|
|
485
|
+
removeThrough(Number(row?.seq ?? 0), "max_pending_exceeded");
|
|
486
|
+
}
|
|
487
|
+
return {
|
|
488
|
+
prunedCount,
|
|
489
|
+
oldestAvailableSeq: Number(
|
|
490
|
+
sql.prepare("SELECT MIN(seq) AS seq FROM outbox").get()?.seq ?? db.counter("seq") + 1
|
|
491
|
+
)
|
|
492
|
+
};
|
|
493
|
+
};
|
|
494
|
+
return db.inTransaction ? applyPrune() : db.atomic(applyPrune);
|
|
495
|
+
}
|
|
496
|
+
return {
|
|
497
|
+
async read(options) {
|
|
498
|
+
const sql = db.connection;
|
|
499
|
+
sql.exec("BEGIN");
|
|
500
|
+
try {
|
|
501
|
+
const cursor = Math.max(
|
|
502
|
+
options.afterSeq ?? 0,
|
|
503
|
+
Number(
|
|
504
|
+
sql.prepare("SELECT seq FROM consumers WHERE id = ?").get(options.consumerId)?.seq ?? 0
|
|
505
|
+
)
|
|
506
|
+
);
|
|
507
|
+
const oldest = Number(
|
|
508
|
+
sql.prepare("SELECT MIN(seq) AS seq FROM outbox").get()?.seq ?? db.counter("seq") + 1
|
|
509
|
+
);
|
|
510
|
+
const events = sql.prepare("SELECT data FROM outbox WHERE seq > ? ORDER BY seq LIMIT ?").all(cursor, Math.max(0, Math.floor(options.limit))).map((row) => JSON.parse(String(row.data)));
|
|
511
|
+
const gap = cursor + 1 < oldest ? {
|
|
512
|
+
fromSeq: cursor + 1,
|
|
513
|
+
toSeq: oldest - 1,
|
|
514
|
+
reason: String(
|
|
515
|
+
sql.prepare("SELECT reason FROM gaps WHERE to_seq >= ? ORDER BY to_seq LIMIT 1").get(cursor + 1)?.reason ?? "retention_ttl"
|
|
516
|
+
)
|
|
517
|
+
} : void 0;
|
|
518
|
+
sql.exec("COMMIT");
|
|
519
|
+
return { events, ...gap ? { gap } : {} };
|
|
520
|
+
} catch (error) {
|
|
521
|
+
sql.exec("ROLLBACK");
|
|
522
|
+
throw error;
|
|
523
|
+
}
|
|
524
|
+
},
|
|
525
|
+
async ack(options) {
|
|
526
|
+
await db.transaction(() => {
|
|
527
|
+
const seq = Math.max(0, Math.min(options.upToSeq, db.counter("seq")));
|
|
528
|
+
db.connection.prepare(
|
|
529
|
+
`INSERT INTO consumers(id, seq) VALUES (?, ?)
|
|
530
|
+
ON CONFLICT(id) DO UPDATE SET seq = MAX(consumers.seq, excluded.seq)`
|
|
531
|
+
).run(options.consumerId, seq);
|
|
532
|
+
});
|
|
533
|
+
},
|
|
534
|
+
async prune(policy) {
|
|
535
|
+
return prune(policy);
|
|
536
|
+
},
|
|
537
|
+
enforceConfiguredRetention() {
|
|
538
|
+
if (retention?.maxRetentionDays === void 0 && retention?.maxPendingEvents === void 0)
|
|
539
|
+
return;
|
|
540
|
+
prune({
|
|
541
|
+
...retention.maxRetentionDays !== void 0 ? { maxRetentionMs: retention.maxRetentionDays * 864e5 } : {},
|
|
542
|
+
...retention.maxPendingEvents !== void 0 ? { maxPendingEvents: retention.maxPendingEvents } : {}
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function fingerprint(value) {
|
|
548
|
+
return JSON.stringify(value, (_key, item) => {
|
|
549
|
+
if (item && typeof item === "object" && !Array.isArray(item))
|
|
550
|
+
return Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)));
|
|
551
|
+
return item;
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
function sameScope(a, b) {
|
|
555
|
+
return fingerprint(a ?? {}) === fingerprint(b ?? {});
|
|
556
|
+
}
|
|
557
|
+
var now = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
558
|
+
function conflict() {
|
|
559
|
+
throw new ConcurrencyConflictError();
|
|
560
|
+
}
|
|
561
|
+
function localStorage(config) {
|
|
562
|
+
const busyTimeoutMs = config.busyTimeoutMs ?? 5e3;
|
|
563
|
+
if (!Number.isSafeInteger(busyTimeoutMs) || busyTimeoutMs < 0)
|
|
564
|
+
throw new RangeError("busyTimeoutMs must be a nonnegative safe integer.");
|
|
565
|
+
const db = new LocalDatabase(config.dir, busyTimeoutMs);
|
|
566
|
+
const state = {
|
|
567
|
+
sessions: db.map("sessions"),
|
|
568
|
+
turns: db.map("turns"),
|
|
569
|
+
epochs: db.map("epochs"),
|
|
570
|
+
commands: db.map("commands"),
|
|
571
|
+
admissions: db.map("admissions"),
|
|
572
|
+
get queue() {
|
|
573
|
+
return db.counter("queue");
|
|
574
|
+
},
|
|
575
|
+
set queue(value) {
|
|
576
|
+
db.setCounter("queue", value);
|
|
577
|
+
},
|
|
578
|
+
get seq() {
|
|
579
|
+
return db.counter("seq");
|
|
580
|
+
},
|
|
581
|
+
set seq(value) {
|
|
582
|
+
db.setCounter("seq", value);
|
|
583
|
+
},
|
|
584
|
+
get events() {
|
|
585
|
+
return db.events;
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
const outbox = localOutbox(db, {
|
|
589
|
+
maxRetentionDays: config.outbox?.maxRetentionDays ?? 7,
|
|
590
|
+
maxPendingEvents: config.outbox?.maxPendingEvents ?? 1e5
|
|
591
|
+
});
|
|
592
|
+
function transaction(fn) {
|
|
593
|
+
return db.transaction(fn, () => {
|
|
594
|
+
if (db.events.length) outbox.enforceConfiguredRetention();
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
function get(id) {
|
|
598
|
+
const value = state.turns.get(id);
|
|
599
|
+
if (!value) throw new Error(`Turn ${id} not found.`);
|
|
600
|
+
return value;
|
|
601
|
+
}
|
|
602
|
+
function session(id) {
|
|
603
|
+
const value = state.sessions.get(id);
|
|
604
|
+
if (!value) throw new Error(`Session ${id} not found.`);
|
|
605
|
+
return value;
|
|
606
|
+
}
|
|
607
|
+
function fence(input) {
|
|
608
|
+
const snap = get(input.turnId);
|
|
609
|
+
const lease = snap.turn.lease;
|
|
610
|
+
if (!lease || lease.holderId !== input.lease.holderId || lease.epoch !== input.lease.epoch || Date.parse(lease.expiresAt) <= Date.now())
|
|
611
|
+
throw new LeaseLostError();
|
|
612
|
+
return snap;
|
|
613
|
+
}
|
|
614
|
+
function event(turn, type, data, step) {
|
|
615
|
+
const seq = ++state.seq;
|
|
616
|
+
state.events.push({
|
|
617
|
+
type,
|
|
618
|
+
seq,
|
|
619
|
+
eventId: `event_${seq}`,
|
|
620
|
+
occurredAt: now(),
|
|
621
|
+
sessionId: turn.sessionId,
|
|
622
|
+
turnId: turn.turnId,
|
|
623
|
+
rootTurnId: turn.rootTurnId,
|
|
624
|
+
...turn.scope ? { scope: turn.scope } : {},
|
|
625
|
+
...turn.parentTurnId ? { parentTurnId: turn.parentTurnId } : {},
|
|
626
|
+
traceId: turn.rootTurnId,
|
|
627
|
+
spanId: step?.stepId ?? turn.turnId,
|
|
628
|
+
...step ? { stepId: step.stepId } : {},
|
|
629
|
+
data: {
|
|
630
|
+
agentId: turn.agentId,
|
|
631
|
+
agentVersion: turn.agentVersion,
|
|
632
|
+
iteration: step?.iteration ?? turn.iteration,
|
|
633
|
+
...step ? {
|
|
634
|
+
kind: step.kind,
|
|
635
|
+
status: step.status,
|
|
636
|
+
toolName: step.toolName,
|
|
637
|
+
approvalId: step.approvalId,
|
|
638
|
+
...type === "step.completed" && (step.kind === "model_call" || step.kind === "compaction") ? {
|
|
639
|
+
...step.usage ? { usage: step.usage } : {},
|
|
640
|
+
...step.protocolId ? { protocolId: step.protocolId } : {},
|
|
641
|
+
...step.modelId ? { modelId: step.modelId } : {}
|
|
642
|
+
} : {}
|
|
643
|
+
} : {},
|
|
644
|
+
...data
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
function touch(turn) {
|
|
649
|
+
turn.version++;
|
|
650
|
+
turn.updatedAt = now();
|
|
651
|
+
}
|
|
652
|
+
function claim(turn, request) {
|
|
653
|
+
if (turn.lease && Date.parse(turn.lease.expiresAt) > Date.now()) conflict();
|
|
654
|
+
if (isTerminalTurnStatus(turn.status) || turn.status === "queued") conflict();
|
|
655
|
+
const epoch = (state.epochs.get(turn.turnId) ?? 0) + 1;
|
|
656
|
+
state.epochs.set(turn.turnId, epoch);
|
|
657
|
+
const lease = {
|
|
658
|
+
holderId: request.holderId,
|
|
659
|
+
epoch,
|
|
660
|
+
expiresAt: new Date(Date.now() + request.ttlMs).toISOString()
|
|
661
|
+
};
|
|
662
|
+
turn.lease = lease;
|
|
663
|
+
turn.status = "running";
|
|
664
|
+
turn.wakeRequested = false;
|
|
665
|
+
touch(turn);
|
|
666
|
+
return lease;
|
|
667
|
+
}
|
|
668
|
+
function ordered(snap, step) {
|
|
669
|
+
if (snap.turn.completionIntent) conflict();
|
|
670
|
+
if (snap.turn.toolExecution === "sequential" && snap.steps.some((s) => s.stepSeq < step.stepSeq && !isTerminalStepStatus(s.status)))
|
|
671
|
+
conflict();
|
|
672
|
+
}
|
|
673
|
+
function terminate(snap, step) {
|
|
674
|
+
if (!step.terminatesTurn || step.status !== "completed") return;
|
|
675
|
+
if (snap.turn.toolExecution !== "sequential") conflict();
|
|
676
|
+
snap.turn.completionIntent = { stepId: step.stepId, output: step.output ?? null };
|
|
677
|
+
for (const sibling of snap.steps)
|
|
678
|
+
if (sibling.iteration === step.iteration && sibling.stepSeq > step.stepSeq && (sibling.status === "pending" || sibling.status === "awaiting_approval"))
|
|
679
|
+
terminalStep(snap, sibling, "skipped", "tool_terminated");
|
|
680
|
+
touch(snap.turn);
|
|
681
|
+
}
|
|
682
|
+
function recompute(snap) {
|
|
683
|
+
const turn = snap.turn;
|
|
684
|
+
if (isTerminalTurnStatus(turn.status) || turn.status === "queued") return;
|
|
685
|
+
const eligible = snap.turn.toolExecution === "sequential" ? snap.steps.filter((s) => !isTerminalStepStatus(s.status)).slice(0, 1) : snap.steps;
|
|
686
|
+
const local = eligible.some((s) => s.status === "pending" || s.status === "running");
|
|
687
|
+
const blocker = eligible.some((s) => s.status === "unknown") ? "waiting_resolution" : eligible.some((s) => s.status === "awaiting_approval") ? "waiting_approval" : eligible.some((s) => s.status === "waiting_child") ? "waiting_child" : void 0;
|
|
688
|
+
if (local || !blocker) {
|
|
689
|
+
turn.wakeRequested = !turn.lease;
|
|
690
|
+
touch(turn);
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const changed = turn.status !== blocker || turn.lease !== void 0;
|
|
694
|
+
turn.status = blocker;
|
|
695
|
+
delete turn.lease;
|
|
696
|
+
turn.wakeRequested = false;
|
|
697
|
+
touch(turn);
|
|
698
|
+
if (changed) event(turn, "turn.paused", { reason: blocker });
|
|
699
|
+
}
|
|
700
|
+
function admit(input) {
|
|
701
|
+
const owner = session(input.sessionId);
|
|
702
|
+
const key = fingerprint([owner.scope, input.sessionId, input.idempotencyKey]);
|
|
703
|
+
const fp = fingerprint({
|
|
704
|
+
input: input.input,
|
|
705
|
+
context: input.context,
|
|
706
|
+
limits: input.limits,
|
|
707
|
+
toolExecution: input.toolExecution,
|
|
708
|
+
mode: input.mode
|
|
709
|
+
});
|
|
710
|
+
const previous = input.idempotencyKey ? state.admissions.get(key) : void 0;
|
|
711
|
+
if (previous) {
|
|
712
|
+
if (previous.fingerprint !== fp) throw new IdempotencyConflictError();
|
|
713
|
+
return { turn: get(previous.turnId).turn, duplicate: true };
|
|
714
|
+
}
|
|
715
|
+
if (state.turns.has(input.turnId)) conflict();
|
|
716
|
+
if (owner.activeTurnId && input.mode === "reject")
|
|
717
|
+
throw new SessionBusyError(owner.activeTurnId);
|
|
718
|
+
const queued = owner.activeTurnId !== void 0;
|
|
719
|
+
const timestamp = now();
|
|
720
|
+
const turn = {
|
|
721
|
+
turnId: input.turnId,
|
|
722
|
+
sessionId: owner.sessionId,
|
|
723
|
+
agentId: owner.agentId,
|
|
724
|
+
agentVersion: owner.agentVersion,
|
|
725
|
+
...owner.scope ? { scope: owner.scope } : {},
|
|
726
|
+
input: input.input,
|
|
727
|
+
context: { ...owner.context, ...input.context },
|
|
728
|
+
status: queued ? "queued" : "running",
|
|
729
|
+
iteration: 0,
|
|
730
|
+
...queued ? { queueSeq: ++state.queue } : {},
|
|
731
|
+
...input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {},
|
|
732
|
+
...input.limits ? { limits: input.limits } : {},
|
|
733
|
+
...input.toolExecution ? { toolExecution: input.toolExecution } : {},
|
|
734
|
+
rootTurnId: input.turnId,
|
|
735
|
+
depth: 0,
|
|
736
|
+
wakeRequested: false,
|
|
737
|
+
createdAt: timestamp,
|
|
738
|
+
updatedAt: timestamp,
|
|
739
|
+
version: 1
|
|
740
|
+
};
|
|
741
|
+
state.turns.set(turn.turnId, { turn, steps: [], attempts: [], steering: [], approvals: [] });
|
|
742
|
+
const lease = queued ? void 0 : claim(turn, input.lease);
|
|
743
|
+
if (!queued) owner.activeTurnId = turn.turnId;
|
|
744
|
+
owner.version++;
|
|
745
|
+
owner.updatedAt = timestamp;
|
|
746
|
+
if (input.idempotencyKey) state.admissions.set(key, { fingerprint: fp, turnId: turn.turnId });
|
|
747
|
+
event(turn, queued ? "turn.queued" : "turn.started");
|
|
748
|
+
return { turn, ...lease ? { lease } : {}, duplicate: false };
|
|
749
|
+
}
|
|
750
|
+
function addStep(snap, input, iteration) {
|
|
751
|
+
if (snap.steps.some((s) => s.stepId === input.stepId)) conflict();
|
|
752
|
+
const step = {
|
|
753
|
+
...input,
|
|
754
|
+
turnId: snap.turn.turnId,
|
|
755
|
+
iteration,
|
|
756
|
+
stepSeq: snap.steps.length + 1,
|
|
757
|
+
status: input.status ?? "pending",
|
|
758
|
+
createdAt: now(),
|
|
759
|
+
version: 1
|
|
760
|
+
};
|
|
761
|
+
snap.steps.push(step);
|
|
762
|
+
return step;
|
|
763
|
+
}
|
|
764
|
+
function doneStep(snap, input, kind, iteration) {
|
|
765
|
+
if (input.continuationArtifact && !input.artifacts?.some((ref) => ref.sha256 === input.continuationArtifact.sha256))
|
|
766
|
+
input = { ...input, artifacts: [...input.artifacts ?? [], input.continuationArtifact] };
|
|
767
|
+
let step = snap.steps.find((s) => s.stepId === input.stepId);
|
|
768
|
+
if (step && (isTerminalStepStatus(step.status) || step.kind !== kind || step.operationKey !== input.operationKey || step.iteration !== iteration))
|
|
769
|
+
conflict();
|
|
770
|
+
step ??= addStep(
|
|
771
|
+
snap,
|
|
772
|
+
{
|
|
773
|
+
stepId: input.stepId,
|
|
774
|
+
operationKey: input.operationKey,
|
|
775
|
+
kind,
|
|
776
|
+
...input.input !== void 0 ? { input: input.input } : {}
|
|
777
|
+
},
|
|
778
|
+
iteration
|
|
779
|
+
);
|
|
780
|
+
let attempt = snap.attempts.find(
|
|
781
|
+
(a) => a.stepId === step.stepId && a.attemptNo === input.attemptNo
|
|
782
|
+
);
|
|
783
|
+
if (attempt && attempt.status !== "running") conflict();
|
|
784
|
+
if (!attempt) {
|
|
785
|
+
attempt = {
|
|
786
|
+
turnId: snap.turn.turnId,
|
|
787
|
+
stepId: step.stepId,
|
|
788
|
+
attemptNo: input.attemptNo,
|
|
789
|
+
kind: "execute",
|
|
790
|
+
status: "running",
|
|
791
|
+
holderId: snap.turn.lease.holderId,
|
|
792
|
+
leaseEpoch: snap.turn.lease.epoch,
|
|
793
|
+
startedAt: now()
|
|
794
|
+
};
|
|
795
|
+
snap.attempts.push(attempt);
|
|
796
|
+
}
|
|
797
|
+
Object.assign(
|
|
798
|
+
step,
|
|
799
|
+
{ status: "completed", output: input.output, completedAt: now(), version: step.version + 1 },
|
|
800
|
+
input.input !== void 0 ? { input: input.input } : {},
|
|
801
|
+
input.protocolId !== void 0 ? { protocolId: input.protocolId } : {},
|
|
802
|
+
input.modelId !== void 0 ? { modelId: input.modelId } : {},
|
|
803
|
+
input.continuation !== void 0 ? { continuation: input.continuation } : {},
|
|
804
|
+
input.continuationArtifact !== void 0 ? { continuationArtifact: input.continuationArtifact } : {},
|
|
805
|
+
input.usage ? { usage: input.usage } : {},
|
|
806
|
+
input.artifacts ? { artifacts: input.artifacts } : {}
|
|
807
|
+
);
|
|
808
|
+
Object.assign(
|
|
809
|
+
attempt,
|
|
810
|
+
{ status: "succeeded", output: input.output, completedAt: now() },
|
|
811
|
+
input.usage ? { usage: input.usage } : {},
|
|
812
|
+
input.artifacts ? { artifacts: input.artifacts } : {}
|
|
813
|
+
);
|
|
814
|
+
event(snap.turn, "step.completed", void 0, step);
|
|
815
|
+
return step;
|
|
816
|
+
}
|
|
817
|
+
function terminalStep(snap, step, status, reason) {
|
|
818
|
+
step.status = status;
|
|
819
|
+
step.output = { status, reason };
|
|
820
|
+
step.completedAt = now();
|
|
821
|
+
step.version++;
|
|
822
|
+
event(
|
|
823
|
+
snap.turn,
|
|
824
|
+
status === "failed" ? "step.failed" : "step.completed",
|
|
825
|
+
{ reason, error: step.error },
|
|
826
|
+
step
|
|
827
|
+
);
|
|
828
|
+
const approval = snap.approvals.find((a) => a.stepId === step.stepId && a.status === "pending");
|
|
829
|
+
if (approval) {
|
|
830
|
+
approval.status = "rejected";
|
|
831
|
+
approval.reason = reason;
|
|
832
|
+
approval.resolvedAt = now();
|
|
833
|
+
event(snap.turn, "step.approval_resolved", { reason }, step);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
function steer(input) {
|
|
837
|
+
const snap = get(input.turnId);
|
|
838
|
+
if (isTerminalTurnStatus(snap.turn.status)) {
|
|
839
|
+
if (!input.fallbackToNewTurn) return { accepted: false, reason: "turn_already_terminal" };
|
|
840
|
+
const next = admit({
|
|
841
|
+
sessionId: snap.turn.sessionId,
|
|
842
|
+
turnId: input.fallback.turnId,
|
|
843
|
+
input: input.input,
|
|
844
|
+
mode: "follow_up",
|
|
845
|
+
lease: input.fallback.lease,
|
|
846
|
+
context: { ...snap.turn.context },
|
|
847
|
+
...snap.turn.toolExecution ? { toolExecution: snap.turn.toolExecution } : {},
|
|
848
|
+
...snap.turn.limits ? { limits: { ...snap.turn.limits } } : {}
|
|
849
|
+
});
|
|
850
|
+
return { accepted: true, mode: "promoted_to_turn", turnId: next.turn.turnId };
|
|
851
|
+
}
|
|
852
|
+
if (snap.turn.status === "queued") conflict();
|
|
853
|
+
if (!snap.steering.some((s) => s.steeringId === input.steeringId)) {
|
|
854
|
+
snap.steering.push({
|
|
855
|
+
steeringId: input.steeringId,
|
|
856
|
+
turnId: input.turnId,
|
|
857
|
+
input: input.input,
|
|
858
|
+
urgency: input.urgency ?? "next_iteration",
|
|
859
|
+
supersedeApprovals: input.supersedeApprovals ?? true,
|
|
860
|
+
status: "pending",
|
|
861
|
+
createdAt: now()
|
|
862
|
+
});
|
|
863
|
+
for (const step of snap.steps) {
|
|
864
|
+
if (step.status === "pending" && (step.kind === "tool_exec" || step.kind === "sub_turn"))
|
|
865
|
+
terminalStep(snap, step, "skipped", "superseded_by_steering");
|
|
866
|
+
if (step.status === "awaiting_approval" && (input.supersedeApprovals ?? true))
|
|
867
|
+
terminalStep(snap, step, "rejected", "superseded_by_steering");
|
|
868
|
+
}
|
|
869
|
+
event(snap.turn, "steering.queued", { steeringId: input.steeringId });
|
|
870
|
+
recompute(snap);
|
|
871
|
+
}
|
|
872
|
+
return { accepted: true, mode: "steered", turnId: input.turnId };
|
|
873
|
+
}
|
|
874
|
+
function finish(input) {
|
|
875
|
+
const snap = fence(input);
|
|
876
|
+
const turn = snap.turn;
|
|
877
|
+
if (isTerminalTurnStatus(turn.status)) conflict();
|
|
878
|
+
if (input.status === "completed" && snap.steps.some((s) => !isTerminalStepStatus(s.status)))
|
|
879
|
+
conflict();
|
|
880
|
+
const previousLease = turn.lease;
|
|
881
|
+
Object.assign(
|
|
882
|
+
turn,
|
|
883
|
+
{
|
|
884
|
+
status: input.status,
|
|
885
|
+
completedAt: now(),
|
|
886
|
+
wakeRequested: false,
|
|
887
|
+
stopReason: input.stopReason ?? (input.status === "completed" ? "end_turn" : input.status === "cancelled" ? "cancelled" : "error"),
|
|
888
|
+
...input.providerFinishReason ? { providerFinishReason: input.providerFinishReason } : {},
|
|
889
|
+
...input.partial !== void 0 ? { partial: input.partial } : {}
|
|
890
|
+
},
|
|
891
|
+
input.output !== void 0 ? { output: input.output } : {},
|
|
892
|
+
input.error ? { error: input.error } : {},
|
|
893
|
+
input.artifacts ? { artifacts: input.artifacts } : {}
|
|
894
|
+
);
|
|
895
|
+
delete turn.lease;
|
|
896
|
+
touch(turn);
|
|
897
|
+
const owner = session(turn.sessionId);
|
|
898
|
+
if (owner.activeTurnId === turn.turnId) delete owner.activeTurnId;
|
|
899
|
+
event(turn, `turn.${input.status}`, {
|
|
900
|
+
stopReason: turn.stopReason,
|
|
901
|
+
providerFinishReason: turn.providerFinishReason,
|
|
902
|
+
partial: turn.partial,
|
|
903
|
+
error: turn.error
|
|
904
|
+
});
|
|
905
|
+
const queue = [...state.turns.turnsWhere({ sessionId: turn.sessionId, status: "queued" })].map((s) => s.turn).filter((t) => t.sessionId === turn.sessionId && t.status === "queued").sort((a, b) => a.queueSeq - b.queueSeq);
|
|
906
|
+
if (input.drainQueued === "cancel")
|
|
907
|
+
for (const queued of queue) cancel(get(queued.turnId), "queue_drained", false);
|
|
908
|
+
const next = input.status === "completed" && input.drainQueued !== "cancel" ? queue[0] : void 0;
|
|
909
|
+
if (next) {
|
|
910
|
+
next.status = "running";
|
|
911
|
+
const nextLease = claim(
|
|
912
|
+
next,
|
|
913
|
+
input.nextLease ?? {
|
|
914
|
+
holderId: previousLease.holderId,
|
|
915
|
+
ttlMs: Math.max(1, Date.parse(previousLease.expiresAt) - Date.now())
|
|
916
|
+
}
|
|
917
|
+
);
|
|
918
|
+
owner.activeTurnId = next.turnId;
|
|
919
|
+
event(next, "turn.started");
|
|
920
|
+
owner.version++;
|
|
921
|
+
return { turn, nextTurn: next, nextLease };
|
|
922
|
+
}
|
|
923
|
+
owner.version++;
|
|
924
|
+
return { turn };
|
|
925
|
+
}
|
|
926
|
+
function backwrite(child, modelOutput) {
|
|
927
|
+
const parent = get(child.turn.parentTurnId);
|
|
928
|
+
const step = parent.steps.find((s) => s.stepId === child.turn.parentStepId);
|
|
929
|
+
if (!isTerminalStepStatus(step.status)) {
|
|
930
|
+
step.status = child.turn.status === "completed" ? "completed" : child.turn.status === "cancelled" ? "cancelled" : "failed";
|
|
931
|
+
step.output = child.turn.output ?? { status: child.turn.status, error: child.turn.error };
|
|
932
|
+
if (modelOutput !== void 0) step.modelOutput = modelOutput;
|
|
933
|
+
step.completedAt = now();
|
|
934
|
+
step.version++;
|
|
935
|
+
const attempt = [...parent.attempts].reverse().find((a) => a.stepId === step.stepId && a.status === "running");
|
|
936
|
+
if (attempt) {
|
|
937
|
+
attempt.status = step.status === "completed" ? "succeeded" : step.status === "cancelled" ? "cancelled" : "failed";
|
|
938
|
+
attempt.output = step.output;
|
|
939
|
+
if (modelOutput !== void 0) attempt.modelOutput = modelOutput;
|
|
940
|
+
attempt.completedAt = now();
|
|
941
|
+
}
|
|
942
|
+
event(
|
|
943
|
+
parent.turn,
|
|
944
|
+
step.status === "completed" ? "step.completed" : "step.failed",
|
|
945
|
+
void 0,
|
|
946
|
+
step
|
|
947
|
+
);
|
|
948
|
+
recompute(parent);
|
|
949
|
+
}
|
|
950
|
+
return { child: child.turn, parent: parent.turn, parentStep: step };
|
|
951
|
+
}
|
|
952
|
+
function cancel(snap, reason, cascade = true) {
|
|
953
|
+
if (isTerminalTurnStatus(snap.turn.status) || snap.turn.completionIntent) return;
|
|
954
|
+
for (const step of snap.steps) {
|
|
955
|
+
if (isTerminalStepStatus(step.status) || step.status === "unknown") continue;
|
|
956
|
+
if (step.status === "running" && step.effect === "external") {
|
|
957
|
+
step.status = "unknown";
|
|
958
|
+
step.version++;
|
|
959
|
+
step.error = { code: "CANCELLED_UNCONFIRMED", message: reason };
|
|
960
|
+
event(snap.turn, "step.unknown", { reason }, step);
|
|
961
|
+
} else terminalStep(snap, step, "cancelled", reason);
|
|
962
|
+
for (const attempt of snap.attempts.filter(
|
|
963
|
+
(a) => a.stepId === step.stepId && a.status === "running"
|
|
964
|
+
)) {
|
|
965
|
+
attempt.status = step.status === "unknown" ? "unknown" : "cancelled";
|
|
966
|
+
attempt.completedAt = now();
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
snap.turn.status = "cancelled";
|
|
970
|
+
snap.turn.stopReason = "cancelled";
|
|
971
|
+
snap.turn.completedAt = now();
|
|
972
|
+
snap.turn.wakeRequested = false;
|
|
973
|
+
delete snap.turn.lease;
|
|
974
|
+
touch(snap.turn);
|
|
975
|
+
const owner = session(snap.turn.sessionId);
|
|
976
|
+
if (owner.activeTurnId === snap.turn.turnId) delete owner.activeTurnId;
|
|
977
|
+
event(snap.turn, "turn.cancelled", { reason, stopReason: "cancelled" });
|
|
978
|
+
if (cascade) {
|
|
979
|
+
for (const child of state.turns.turnsWhere({ parentTurnId: snap.turn.turnId }))
|
|
980
|
+
if (child.turn.parentTurnId === snap.turn.turnId && child.turn.propagation?.cancelWithParent !== false)
|
|
981
|
+
cancel(child, reason);
|
|
982
|
+
}
|
|
983
|
+
if (snap.turn.parentTurnId) backwrite(snap);
|
|
984
|
+
}
|
|
985
|
+
const ledger = {
|
|
986
|
+
createSession: (input) => transaction(() => {
|
|
987
|
+
if (state.sessions.has(input.sessionId)) conflict();
|
|
988
|
+
const owner = {
|
|
989
|
+
...input,
|
|
990
|
+
context: input.context ?? {},
|
|
991
|
+
createdAt: now(),
|
|
992
|
+
updatedAt: now(),
|
|
993
|
+
version: 1
|
|
994
|
+
};
|
|
995
|
+
state.sessions.set(input.sessionId, owner);
|
|
996
|
+
event(
|
|
997
|
+
{
|
|
998
|
+
sessionId: input.sessionId,
|
|
999
|
+
turnId: "",
|
|
1000
|
+
rootTurnId: "",
|
|
1001
|
+
...input.scope ? { scope: input.scope } : {}
|
|
1002
|
+
},
|
|
1003
|
+
"session.created",
|
|
1004
|
+
{ agentId: input.agentId, agentVersion: input.agentVersion }
|
|
1005
|
+
);
|
|
1006
|
+
return owner;
|
|
1007
|
+
}),
|
|
1008
|
+
getSession: (id, scope) => db.read(() => {
|
|
1009
|
+
const value = state.sessions.get(id);
|
|
1010
|
+
return value && (!scope || sameScope(value.scope, scope)) ? value : null;
|
|
1011
|
+
}),
|
|
1012
|
+
listSessionTurns: (sessionId, options) => db.read(
|
|
1013
|
+
() => db.listTurns(sessionId).filter(
|
|
1014
|
+
(turn) => turn.sessionId === sessionId && (!options?.scope || sameScope(turn.scope, options.scope))
|
|
1015
|
+
).slice(0, options?.limit ?? Infinity)
|
|
1016
|
+
),
|
|
1017
|
+
admitTurn: (input) => transaction(() => admit(input)),
|
|
1018
|
+
enqueueSteering: (input) => transaction(() => steer(input)),
|
|
1019
|
+
consumeSteeringAndRecord: (input) => transaction(() => {
|
|
1020
|
+
const snap = fence(input);
|
|
1021
|
+
const pending = snap.steering.filter((s) => s.status === "pending");
|
|
1022
|
+
if (!pending.length) return null;
|
|
1023
|
+
const step = addStep(
|
|
1024
|
+
snap,
|
|
1025
|
+
{
|
|
1026
|
+
stepId: input.stepId,
|
|
1027
|
+
operationKey: input.operationKey,
|
|
1028
|
+
kind: "steering_input",
|
|
1029
|
+
input: pending.map((s) => s.input)
|
|
1030
|
+
},
|
|
1031
|
+
input.iteration
|
|
1032
|
+
);
|
|
1033
|
+
step.status = "completed";
|
|
1034
|
+
step.output = pending.map((s) => s.input);
|
|
1035
|
+
step.completedAt = now();
|
|
1036
|
+
for (const entry of pending) {
|
|
1037
|
+
entry.status = "consumed";
|
|
1038
|
+
entry.consumedAt = now();
|
|
1039
|
+
entry.consumedByStepId = step.stepId;
|
|
1040
|
+
}
|
|
1041
|
+
event(
|
|
1042
|
+
snap.turn,
|
|
1043
|
+
"steering.applied",
|
|
1044
|
+
{ steeringIds: pending.map((s) => s.steeringId) },
|
|
1045
|
+
step
|
|
1046
|
+
);
|
|
1047
|
+
return step;
|
|
1048
|
+
}),
|
|
1049
|
+
commitCompactionStep: (input) => transaction(() => {
|
|
1050
|
+
const snap = fence(input);
|
|
1051
|
+
const step = doneStep(snap, input.step, "compaction", input.iteration);
|
|
1052
|
+
snap.turn.compactionCursorStepId = input.compactedUpToStepId;
|
|
1053
|
+
session(snap.turn.sessionId).compactionCursorStepId = input.compactedUpToStepId;
|
|
1054
|
+
event(
|
|
1055
|
+
snap.turn,
|
|
1056
|
+
"compaction.committed",
|
|
1057
|
+
{ compactedUpToStepId: input.compactedUpToStepId },
|
|
1058
|
+
step
|
|
1059
|
+
);
|
|
1060
|
+
return step;
|
|
1061
|
+
}),
|
|
1062
|
+
commitModelAndDispatchSteps: (input) => transaction(() => {
|
|
1063
|
+
const snap = fence(input);
|
|
1064
|
+
if (input.iteration <= snap.turn.iteration || snap.steps.some((s) => !isTerminalStepStatus(s.status) && s.stepId !== input.model.stepId))
|
|
1065
|
+
conflict();
|
|
1066
|
+
doneStep(snap, input.model, "model_call", input.iteration);
|
|
1067
|
+
snap.turn.iteration = input.iteration;
|
|
1068
|
+
for (const child of input.steps) {
|
|
1069
|
+
if (child.terminatesTurn && snap.turn.toolExecution !== "sequential") conflict();
|
|
1070
|
+
const step = addStep(snap, child, input.iteration);
|
|
1071
|
+
event(snap.turn, "step.dispatched", void 0, step);
|
|
1072
|
+
if (step.status === "awaiting_approval") {
|
|
1073
|
+
if (!step.approvalId) conflict();
|
|
1074
|
+
snap.approvals.push({
|
|
1075
|
+
approvalId: step.approvalId,
|
|
1076
|
+
sessionId: snap.turn.sessionId,
|
|
1077
|
+
turnId: input.turnId,
|
|
1078
|
+
rootTurnId: snap.turn.rootTurnId,
|
|
1079
|
+
...snap.turn.parentTurnId ? { parentTurnId: snap.turn.parentTurnId } : {},
|
|
1080
|
+
stepId: step.stepId,
|
|
1081
|
+
status: "pending",
|
|
1082
|
+
createdAt: now()
|
|
1083
|
+
});
|
|
1084
|
+
event(snap.turn, "step.approval_requested", { approvalId: step.approvalId }, step);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
recompute(snap);
|
|
1088
|
+
return snap;
|
|
1089
|
+
}),
|
|
1090
|
+
prepareToolStep: (input) => transaction(() => {
|
|
1091
|
+
const snap = fence(input);
|
|
1092
|
+
const step = snap.steps.find((s) => s.stepId === input.stepId);
|
|
1093
|
+
if (!step || step.status !== "pending" || step.prepared || step.version !== input.expectedStepVersion)
|
|
1094
|
+
conflict();
|
|
1095
|
+
ordered(snap, step);
|
|
1096
|
+
step.prepared = true;
|
|
1097
|
+
step.validatedInput = input.validatedInput;
|
|
1098
|
+
step.version++;
|
|
1099
|
+
if (input.error) {
|
|
1100
|
+
step.error = input.error;
|
|
1101
|
+
terminalStep(snap, step, "failed", input.error.message);
|
|
1102
|
+
} else if (input.approvalId) {
|
|
1103
|
+
step.status = "awaiting_approval";
|
|
1104
|
+
step.approvalId = input.approvalId;
|
|
1105
|
+
snap.approvals.push({
|
|
1106
|
+
approvalId: input.approvalId,
|
|
1107
|
+
sessionId: snap.turn.sessionId,
|
|
1108
|
+
rootTurnId: snap.turn.rootTurnId,
|
|
1109
|
+
...snap.turn.parentTurnId ? { parentTurnId: snap.turn.parentTurnId } : {},
|
|
1110
|
+
turnId: snap.turn.turnId,
|
|
1111
|
+
stepId: step.stepId,
|
|
1112
|
+
status: "pending",
|
|
1113
|
+
createdAt: now()
|
|
1114
|
+
});
|
|
1115
|
+
event(snap.turn, "step.approval_requested", { approvalId: input.approvalId }, step);
|
|
1116
|
+
}
|
|
1117
|
+
recompute(snap);
|
|
1118
|
+
return step;
|
|
1119
|
+
}),
|
|
1120
|
+
skipSteps: (input) => transaction(() => {
|
|
1121
|
+
const snap = fence(input);
|
|
1122
|
+
for (const step of snap.steps)
|
|
1123
|
+
if (input.stepIds.includes(step.stepId) && (step.status === "pending" || step.status === "awaiting_approval"))
|
|
1124
|
+
terminalStep(snap, step, "skipped", input.reason);
|
|
1125
|
+
recompute(snap);
|
|
1126
|
+
}),
|
|
1127
|
+
reserveModelCall: (input) => transaction(() => {
|
|
1128
|
+
const snap = fence(input);
|
|
1129
|
+
const attempt = snap.attempts.find(
|
|
1130
|
+
(a) => a.stepId === input.stepId && a.attemptNo === input.attemptNo && a.status === "running"
|
|
1131
|
+
);
|
|
1132
|
+
if (!attempt) conflict();
|
|
1133
|
+
const count = snap.attempts.reduce(
|
|
1134
|
+
(n, a) => n + (a.modelCalls ?? (snap.steps.find((s) => s.stepId === a.stepId)?.kind === "model_call" ? 1 : 0)),
|
|
1135
|
+
0
|
|
1136
|
+
);
|
|
1137
|
+
if (count >= (snap.turn.limits?.maxModelCalls ?? Infinity)) return false;
|
|
1138
|
+
attempt.modelCalls = (attempt.modelCalls ?? 0) + 1;
|
|
1139
|
+
return true;
|
|
1140
|
+
}),
|
|
1141
|
+
startStepAttempt: (input) => transaction(() => {
|
|
1142
|
+
const snap = fence(input);
|
|
1143
|
+
let step = snap.steps.find((s) => s.stepId === input.stepId);
|
|
1144
|
+
if (!step && input.newStep) step = addStep(snap, input.newStep, input.newStep.iteration);
|
|
1145
|
+
if (!step || isTerminalStepStatus(step.status) || step.status === "awaiting_approval" || step.status === "waiting_child" || input.expectedStepVersion !== void 0 && input.expectedStepVersion !== step.version)
|
|
1146
|
+
conflict();
|
|
1147
|
+
ordered(snap, step);
|
|
1148
|
+
if (input.kind === "execute" && (step.kind === "tool_exec" || step.kind === "sub_turn")) {
|
|
1149
|
+
const count = snap.attempts.filter(
|
|
1150
|
+
(a) => a.kind === "execute" && snap.steps.some(
|
|
1151
|
+
(s) => s.stepId === a.stepId && (s.kind === "tool_exec" || s.kind === "sub_turn")
|
|
1152
|
+
)
|
|
1153
|
+
).length;
|
|
1154
|
+
if (count >= (snap.turn.limits?.maxToolCalls ?? Infinity))
|
|
1155
|
+
throw new HostControlError({
|
|
1156
|
+
code: "MAX_TOOL_CALLS",
|
|
1157
|
+
message: "Tool call limit reached.",
|
|
1158
|
+
requestStage: "admission_rejected"
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
if (step.status === "unknown" && input.kind !== "reconcile") conflict();
|
|
1162
|
+
for (const previous of snap.attempts.filter(
|
|
1163
|
+
(a) => a.stepId === step.stepId && a.status === "running"
|
|
1164
|
+
)) {
|
|
1165
|
+
if (previous.leaseEpoch === input.lease.epoch) conflict();
|
|
1166
|
+
previous.status = "unknown";
|
|
1167
|
+
previous.completedAt = now();
|
|
1168
|
+
previous.error = { code: "LEASE_EXPIRED", message: "Previous lease expired." };
|
|
1169
|
+
}
|
|
1170
|
+
const attempt = {
|
|
1171
|
+
turnId: input.turnId,
|
|
1172
|
+
stepId: step.stepId,
|
|
1173
|
+
attemptNo: snap.attempts.filter((a) => a.stepId === step.stepId).length + 1,
|
|
1174
|
+
kind: input.kind,
|
|
1175
|
+
modelCalls: 0,
|
|
1176
|
+
status: "running",
|
|
1177
|
+
holderId: input.lease.holderId,
|
|
1178
|
+
leaseEpoch: input.lease.epoch,
|
|
1179
|
+
startedAt: now()
|
|
1180
|
+
};
|
|
1181
|
+
snap.attempts.push(attempt);
|
|
1182
|
+
step.status = "running";
|
|
1183
|
+
step.version++;
|
|
1184
|
+
return { step, attempt };
|
|
1185
|
+
}),
|
|
1186
|
+
completeStep: (input) => transaction(() => {
|
|
1187
|
+
const snap = fence(input);
|
|
1188
|
+
const step = snap.steps.find((s) => s.stepId === input.stepId);
|
|
1189
|
+
const attempt = snap.attempts.find(
|
|
1190
|
+
(a) => a.stepId === input.stepId && a.attemptNo === input.attemptNo
|
|
1191
|
+
);
|
|
1192
|
+
if (!step || !attempt || step.version !== input.expectedStepVersion || isTerminalStepStatus(step.status) || attempt.status !== "running" || attempt.holderId !== input.lease.holderId || attempt.leaseEpoch !== input.lease.epoch)
|
|
1193
|
+
conflict();
|
|
1194
|
+
if (input.status === "pending") {
|
|
1195
|
+
const provenNotExecuted = attempt.kind === "reconcile" && input.evidence?.status === "not_executed";
|
|
1196
|
+
const retryable = step.effect !== "external" && (step.kind === "model_call" || step.kind === "compaction" || step.kind === "tool_exec" && step.effect === "none") && ["failed", "cancelled", "unknown"].includes(input.attemptStatus);
|
|
1197
|
+
if (!provenNotExecuted && !retryable) conflict();
|
|
1198
|
+
}
|
|
1199
|
+
Object.assign(
|
|
1200
|
+
step,
|
|
1201
|
+
{ status: input.status, version: step.version + 1 },
|
|
1202
|
+
input.output !== void 0 ? { output: input.output } : {},
|
|
1203
|
+
input.modelOutput !== void 0 ? { modelOutput: input.modelOutput } : {},
|
|
1204
|
+
input.artifacts ? { artifacts: input.artifacts } : {},
|
|
1205
|
+
input.usage ? { usage: input.usage } : {},
|
|
1206
|
+
input.error ? { error: input.error } : {},
|
|
1207
|
+
isTerminalStepStatus(input.status) ? { completedAt: now() } : {}
|
|
1208
|
+
);
|
|
1209
|
+
Object.assign(
|
|
1210
|
+
attempt,
|
|
1211
|
+
{ status: input.attemptStatus, completedAt: now() },
|
|
1212
|
+
input.output !== void 0 ? { output: input.output } : {},
|
|
1213
|
+
input.modelOutput !== void 0 ? { modelOutput: input.modelOutput } : {},
|
|
1214
|
+
input.artifacts ? { artifacts: input.artifacts } : {},
|
|
1215
|
+
input.usage ? { usage: input.usage } : {},
|
|
1216
|
+
input.error ? { error: input.error } : {},
|
|
1217
|
+
input.evidence !== void 0 ? { evidence: input.evidence } : {}
|
|
1218
|
+
);
|
|
1219
|
+
if (input.status === "pending") {
|
|
1220
|
+
delete step.output;
|
|
1221
|
+
delete step.modelOutput;
|
|
1222
|
+
delete step.error;
|
|
1223
|
+
delete step.artifacts;
|
|
1224
|
+
delete step.usage;
|
|
1225
|
+
delete step.completedAt;
|
|
1226
|
+
}
|
|
1227
|
+
event(
|
|
1228
|
+
snap.turn,
|
|
1229
|
+
input.status === "pending" ? "step.dispatched" : input.status === "unknown" ? "step.unknown" : input.status === "failed" ? "step.failed" : "step.completed",
|
|
1230
|
+
{
|
|
1231
|
+
attemptNo: input.attemptNo,
|
|
1232
|
+
attemptStatus: input.attemptStatus,
|
|
1233
|
+
error: input.error,
|
|
1234
|
+
...step.terminatesTurn && input.status === "completed" ? { stopReason: "tool_terminated" } : {}
|
|
1235
|
+
},
|
|
1236
|
+
step
|
|
1237
|
+
);
|
|
1238
|
+
terminate(snap, step);
|
|
1239
|
+
recompute(snap);
|
|
1240
|
+
return step;
|
|
1241
|
+
}),
|
|
1242
|
+
dispatchSubTurn: (input) => transaction(() => {
|
|
1243
|
+
const parent = get(input.turnId);
|
|
1244
|
+
const previous = parent.steps.find((s) => s.stepId === input.parentStepId);
|
|
1245
|
+
if (previous?.childTurnId) return { turn: get(previous.childTurnId).turn, duplicate: true };
|
|
1246
|
+
fence(input);
|
|
1247
|
+
if (!previous || previous.kind !== "sub_turn" || previous.status !== "running" || input.child.sessionId === parent.turn.sessionId)
|
|
1248
|
+
conflict();
|
|
1249
|
+
const admitted = admit({
|
|
1250
|
+
sessionId: input.child.sessionId,
|
|
1251
|
+
turnId: input.child.turnId,
|
|
1252
|
+
input: input.child.input,
|
|
1253
|
+
mode: "reject",
|
|
1254
|
+
lease: input.childLease,
|
|
1255
|
+
...input.child.limits ? { limits: input.child.limits } : {},
|
|
1256
|
+
...input.child.toolExecution ? { toolExecution: input.child.toolExecution } : {}
|
|
1257
|
+
});
|
|
1258
|
+
Object.assign(admitted.turn, {
|
|
1259
|
+
parentTurnId: input.turnId,
|
|
1260
|
+
parentStepId: previous.stepId,
|
|
1261
|
+
rootTurnId: parent.turn.rootTurnId,
|
|
1262
|
+
depth: parent.turn.depth + 1,
|
|
1263
|
+
propagation: input.child.propagation ?? { cancelWithParent: true }
|
|
1264
|
+
});
|
|
1265
|
+
const childEvent = state.events.at(-1);
|
|
1266
|
+
state.events[state.events.length - 1] = {
|
|
1267
|
+
...childEvent,
|
|
1268
|
+
rootTurnId: parent.turn.rootTurnId,
|
|
1269
|
+
parentTurnId: input.turnId,
|
|
1270
|
+
traceId: parent.turn.rootTurnId
|
|
1271
|
+
};
|
|
1272
|
+
previous.childTurnId = admitted.turn.turnId;
|
|
1273
|
+
previous.status = "waiting_child";
|
|
1274
|
+
previous.version++;
|
|
1275
|
+
event(parent.turn, "sub_turn.linked", { childTurnId: admitted.turn.turnId }, previous);
|
|
1276
|
+
recompute(parent);
|
|
1277
|
+
return admitted;
|
|
1278
|
+
}),
|
|
1279
|
+
completeChildAndWakeParent: (input) => transaction(() => {
|
|
1280
|
+
const child = fence(input);
|
|
1281
|
+
if (!child.turn.parentTurnId) conflict();
|
|
1282
|
+
finish(input);
|
|
1283
|
+
return backwrite(child, input.parentModelOutput);
|
|
1284
|
+
}),
|
|
1285
|
+
applyCommand: (envelope) => transaction(() => {
|
|
1286
|
+
const key = fingerprint([envelope.scope, envelope.commandId]);
|
|
1287
|
+
const fp = fingerprint({
|
|
1288
|
+
actor: envelope.actor,
|
|
1289
|
+
payload: envelope.payload,
|
|
1290
|
+
scope: envelope.scope
|
|
1291
|
+
});
|
|
1292
|
+
const old = state.commands.get(key);
|
|
1293
|
+
if (old) {
|
|
1294
|
+
if (old.fingerprint !== fp) throw new IdempotencyConflictError();
|
|
1295
|
+
return {
|
|
1296
|
+
...old.receipt,
|
|
1297
|
+
status: old.receipt.status === "rejected" ? "rejected" : "duplicate"
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
const payload = envelope.payload;
|
|
1301
|
+
const snap = state.turns.get(payload.turnId);
|
|
1302
|
+
let reason;
|
|
1303
|
+
let resultTurnId = payload.turnId;
|
|
1304
|
+
if (!snap) reason = "not_found";
|
|
1305
|
+
else if (!sameScope(snap.turn.scope, envelope.scope)) reason = "scope_mismatch";
|
|
1306
|
+
else if (isTerminalTurnStatus(snap.turn.status) && payload.kind !== "steer")
|
|
1307
|
+
reason = "turn_already_terminal";
|
|
1308
|
+
else {
|
|
1309
|
+
switch (payload.kind) {
|
|
1310
|
+
case "steer": {
|
|
1311
|
+
const result = steer({
|
|
1312
|
+
...payload,
|
|
1313
|
+
steeringId: envelope.commandId,
|
|
1314
|
+
fallbackToNewTurn: payload.fallbackToNewTurn ?? true,
|
|
1315
|
+
fallback: {
|
|
1316
|
+
turnId: `turn_${envelope.commandId}`,
|
|
1317
|
+
lease: { holderId: "command-admission", ttlMs: 1 }
|
|
1318
|
+
}
|
|
1319
|
+
});
|
|
1320
|
+
if (result.accepted) resultTurnId = result.turnId;
|
|
1321
|
+
else reason = result.reason;
|
|
1322
|
+
break;
|
|
1323
|
+
}
|
|
1324
|
+
case "approve": {
|
|
1325
|
+
const approval = snap.approvals.find(
|
|
1326
|
+
(a) => a.approvalId === payload.approvalId && a.status === "pending"
|
|
1327
|
+
);
|
|
1328
|
+
const step = approval && snap.steps.find(
|
|
1329
|
+
(s) => s.stepId === approval.stepId && s.status === "awaiting_approval"
|
|
1330
|
+
);
|
|
1331
|
+
if (!approval || !step) {
|
|
1332
|
+
reason = "invalid_state";
|
|
1333
|
+
break;
|
|
1334
|
+
}
|
|
1335
|
+
approval.status = payload.decision;
|
|
1336
|
+
approval.actor = envelope.actor;
|
|
1337
|
+
approval.resolvedAt = now();
|
|
1338
|
+
if (payload.reason) approval.reason = payload.reason;
|
|
1339
|
+
if (payload.decision === "approved") {
|
|
1340
|
+
step.status = "pending";
|
|
1341
|
+
step.version++;
|
|
1342
|
+
} else terminalStep(snap, step, "rejected", payload.reason ?? "approval_rejected");
|
|
1343
|
+
event(snap.turn, "step.approval_resolved", { decision: payload.decision }, step);
|
|
1344
|
+
recompute(snap);
|
|
1345
|
+
break;
|
|
1346
|
+
}
|
|
1347
|
+
case "resolve_unknown": {
|
|
1348
|
+
const step = snap.steps.find(
|
|
1349
|
+
(s) => s.stepId === payload.stepId && s.status === "unknown"
|
|
1350
|
+
);
|
|
1351
|
+
if (!step) {
|
|
1352
|
+
reason = "invalid_state";
|
|
1353
|
+
break;
|
|
1354
|
+
}
|
|
1355
|
+
const resolution = payload.resolution;
|
|
1356
|
+
if (resolution.kind === "confirmed_completed") {
|
|
1357
|
+
step.status = "completed";
|
|
1358
|
+
step.output = resolution.output;
|
|
1359
|
+
if (resolution.modelOutput !== void 0) step.modelOutput = resolution.modelOutput;
|
|
1360
|
+
terminate(snap, step);
|
|
1361
|
+
} else if (resolution.kind === "confirmed_not_executed") {
|
|
1362
|
+
step.status = resolution.retry ? "pending" : "cancelled";
|
|
1363
|
+
step.output = { status: "not_executed" };
|
|
1364
|
+
} else {
|
|
1365
|
+
step.status = "failed";
|
|
1366
|
+
step.error = { code: "MANUALLY_FAILED", message: resolution.reason };
|
|
1367
|
+
}
|
|
1368
|
+
step.version++;
|
|
1369
|
+
if (isTerminalStepStatus(step.status)) step.completedAt = now();
|
|
1370
|
+
event(snap.turn, "step.resolved", { resolution }, step);
|
|
1371
|
+
recompute(snap);
|
|
1372
|
+
break;
|
|
1373
|
+
}
|
|
1374
|
+
case "cancel":
|
|
1375
|
+
cancel(snap, payload.reason ?? "cancelled_by_command");
|
|
1376
|
+
if (payload.drainQueued === "cancel") {
|
|
1377
|
+
for (const queued of state.turns.turnsWhere({
|
|
1378
|
+
sessionId: snap.turn.sessionId,
|
|
1379
|
+
status: "queued"
|
|
1380
|
+
}))
|
|
1381
|
+
if (queued.turn.sessionId === snap.turn.sessionId && queued.turn.status === "queued")
|
|
1382
|
+
cancel(queued, "queue_drained");
|
|
1383
|
+
}
|
|
1384
|
+
break;
|
|
1385
|
+
case "resume": {
|
|
1386
|
+
if (snap.turn.status === "queued") {
|
|
1387
|
+
const owner = session(snap.turn.sessionId);
|
|
1388
|
+
if (owner.activeTurnId) {
|
|
1389
|
+
reason = "invalid_state";
|
|
1390
|
+
break;
|
|
1391
|
+
}
|
|
1392
|
+
snap.turn.status = "running";
|
|
1393
|
+
snap.turn.wakeRequested = true;
|
|
1394
|
+
owner.activeTurnId = snap.turn.turnId;
|
|
1395
|
+
} else {
|
|
1396
|
+
recompute(snap);
|
|
1397
|
+
}
|
|
1398
|
+
break;
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
const receipt = {
|
|
1403
|
+
commandId: envelope.commandId,
|
|
1404
|
+
processedAt: now(),
|
|
1405
|
+
status: reason ? "rejected" : "applied",
|
|
1406
|
+
...reason ? { rejectionReason: reason } : { resultTurnId }
|
|
1407
|
+
};
|
|
1408
|
+
state.commands.set(key, { fingerprint: fp, receipt });
|
|
1409
|
+
if (!reason && snap)
|
|
1410
|
+
event(snap.turn, "command.applied", {
|
|
1411
|
+
commandId: envelope.commandId,
|
|
1412
|
+
kind: payload.kind
|
|
1413
|
+
});
|
|
1414
|
+
return receipt;
|
|
1415
|
+
}),
|
|
1416
|
+
finishTurnAndDequeue: (input) => transaction(() => finish(input)),
|
|
1417
|
+
acquireLease: (input) => transaction(() => claim(get(input.turnId).turn, input)),
|
|
1418
|
+
renewLease: (input) => transaction(() => {
|
|
1419
|
+
const snap = fence(input);
|
|
1420
|
+
const lease = {
|
|
1421
|
+
...snap.turn.lease,
|
|
1422
|
+
expiresAt: new Date(Date.now() + input.ttlMs).toISOString()
|
|
1423
|
+
};
|
|
1424
|
+
snap.turn.lease = lease;
|
|
1425
|
+
return lease;
|
|
1426
|
+
}),
|
|
1427
|
+
releaseLease: (input) => transaction(() => {
|
|
1428
|
+
const snap = fence(input);
|
|
1429
|
+
delete snap.turn.lease;
|
|
1430
|
+
touch(snap.turn);
|
|
1431
|
+
}),
|
|
1432
|
+
listRecoverableTurns: (options) => db.read(
|
|
1433
|
+
() => db.listTurns().filter(
|
|
1434
|
+
(t) => !isTerminalTurnStatus(t.status) && t.status !== "queued" && (!options.scope || sameScope(t.scope, options.scope)) && (!t.lease || Date.parse(t.lease.expiresAt) <= Date.now())
|
|
1435
|
+
).slice(0, options.limit)
|
|
1436
|
+
),
|
|
1437
|
+
getTurnSnapshot: (id, options) => db.read(() => {
|
|
1438
|
+
const snap = db.snapshot(id, options?.afterStepId);
|
|
1439
|
+
if (!snap || options?.scope && !sameScope(snap.turn.scope, options.scope)) return null;
|
|
1440
|
+
return snap;
|
|
1441
|
+
})
|
|
1442
|
+
};
|
|
1443
|
+
return {
|
|
1444
|
+
kind: "sqlite",
|
|
1445
|
+
ledger,
|
|
1446
|
+
async open() {
|
|
1447
|
+
db.open();
|
|
1448
|
+
},
|
|
1449
|
+
async close() {
|
|
1450
|
+
db.close();
|
|
1451
|
+
},
|
|
1452
|
+
artifacts: localArtifacts(db, config.dir),
|
|
1453
|
+
outbox
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
export { localStorage };
|
|
1458
|
+
//# sourceMappingURL=index.js.map
|
|
1459
|
+
//# sourceMappingURL=index.js.map
|