@zvada/agent-server 0.3.16 → 0.3.18

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +30 -2
  3. package/docs/consuming.md +9 -2
  4. package/docs/harnesses.md +19 -6
  5. package/docs/sync-experiment.md +190 -0
  6. package/docs/sync-history.md +181 -0
  7. package/docs/sync-integration.md +133 -0
  8. package/package.json +14 -2
  9. package/src/client/client.ts +138 -33
  10. package/src/client/history.ts +88 -0
  11. package/src/client/index.ts +1 -1
  12. package/src/client/request.ts +19 -0
  13. package/src/core/agents/codex-app-server/adapter.ts +31 -3
  14. package/src/core/agents/codex-sdk/adapter.ts +45 -15
  15. package/src/core/agents/codex-sdk/codex-sdk-agent.ts +25 -1
  16. package/src/core/agents/types.ts +2 -1
  17. package/src/core/index.ts +2 -0
  18. package/src/core/provision/pins.ts +2 -1
  19. package/src/core/runtime/agent-runtime.ts +53 -23
  20. package/src/core/runtime/event-processor.ts +10 -5
  21. package/src/core/runtime/event-sink.ts +45 -2
  22. package/src/core/runtime/model-lists.ts +24 -9
  23. package/src/protocol/history.ts +267 -0
  24. package/src/protocol/ids.ts +4 -5
  25. package/src/protocol/index.ts +1 -0
  26. package/src/protocol/wire.ts +82 -1
  27. package/src/server/agent-server.ts +167 -94
  28. package/src/server/bin.ts +22 -1
  29. package/src/server/history.ts +166 -0
  30. package/src/server/index.ts +1 -0
  31. package/src/server/session-store.ts +225 -0
  32. package/src/server/wire-error.ts +52 -0
  33. package/src/sync/event-log.ts +132 -0
  34. package/src/sync/fit.ts +124 -0
  35. package/src/sync/history-reader.ts +52 -0
  36. package/src/sync/history-sqlite.ts +344 -0
  37. package/src/sync/history.ts +226 -0
  38. package/src/sync/index.ts +6 -0
  39. package/src/sync/journal-sqlite.ts +353 -0
  40. package/src/sync/journal.ts +73 -0
  41. package/src/sync/node-sqlite.ts +20 -0
  42. package/src/sync/recovery.ts +112 -0
  43. package/src/sync/retry.ts +49 -0
  44. package/src/sync/schema.ts +56 -0
  45. package/src/sync/sql.ts +106 -0
  46. package/src/sync/sqlite-file.ts +38 -0
  47. package/src/sync/sqlite.ts +21 -0
  48. package/src/sync/worker.ts +259 -0
@@ -0,0 +1,353 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ type AgentHarness,
4
+ type DurableSession,
5
+ HISTORY_MAX_BYTES,
6
+ HISTORY_MAX_RECORDS,
7
+ type LifecycleEvent,
8
+ type RunRequest,
9
+ type SessionRef,
10
+ type TurnEndedEvent,
11
+ type TurnReceipt,
12
+ type WireEventEnvelope,
13
+ canonicalHistoryJson as canonical,
14
+ generateUUIDv7,
15
+ } from "../protocol/index.ts";
16
+ import { EventLog } from "./event-log.ts";
17
+ import { MAX_EVENT_BYTES, recordable } from "./fit.ts";
18
+ import { SqliteHistory } from "./history-sqlite.ts";
19
+ import { JournalError, type SessionJournal } from "./journal.ts";
20
+ import { interruptionFacts } from "./recovery.ts";
21
+ import { openSchema } from "./schema.ts";
22
+ import { Db, type SqlConnection } from "./sql.ts";
23
+
24
+ const fingerprint = (request: RunRequest) =>
25
+ createHash("sha256")
26
+ .update(canonical({ input: request.input, config: request.config }))
27
+ .digest("hex");
28
+ /** Ids name histories, whose wire schema bounds them. */
29
+ const storableId = (value: string) => value.length > 0 && value.length <= 512;
30
+ type SessionRow = {
31
+ session_id: string;
32
+ harness: AgentHarness;
33
+ native_id: string | null;
34
+ closed: number;
35
+ recovery_required: number;
36
+ head_seq: number;
37
+ };
38
+ type SessionEvent = LifecycleEvent & { sessionId: string };
39
+
40
+ /** The journal over any synchronous SQLite connection: the Bun and Node
41
+ * adapters open a private, exclusively locked file for it (`openJournalFile`).
42
+ * Native agent execution is never reconstructed by replaying this database. */
43
+ export class SqliteJournal implements SessionJournal {
44
+ readonly sourceId: string;
45
+ /** Every history in this file, the executed sessions' included, read-only for those. */
46
+ readonly history: SqliteHistory;
47
+ private readonly db: Db;
48
+ private readonly log: EventLog;
49
+ private claimed = false;
50
+ /** Sessions whose native conversation this owner has started or resumed. */
51
+ private readonly live = new Set<string>();
52
+
53
+ constructor(connection: SqlConnection) {
54
+ this.db = new Db(connection);
55
+ try {
56
+ this.sourceId = openSchema(this.db, generateUUIDv7);
57
+ this.log = new EventLog(this.db);
58
+ this.history = new SqliteHistory(this.sourceId, this.db, this.log);
59
+ } catch (error) {
60
+ this.db.close();
61
+ throw error;
62
+ }
63
+ }
64
+ private ref(sessionId: string): SessionRef {
65
+ return { sourceId: this.sourceId, sessionId };
66
+ }
67
+
68
+ claim(): () => void {
69
+ if (this.claimed) throw new Error("Journal already has an executing owner");
70
+ this.recoverInterrupted();
71
+ this.claimed = true;
72
+ this.live.clear();
73
+ return () => {
74
+ this.claimed = false;
75
+ };
76
+ }
77
+ session(sessionId: string): DurableSession | undefined {
78
+ const row = this.db.one<SessionRow>(
79
+ "SELECT s.*, h.head_seq FROM sessions s JOIN histories h ON h.source_id=? AND h.session_id=s.session_id WHERE s.session_id=?",
80
+ this.sourceId,
81
+ sessionId,
82
+ );
83
+ return (
84
+ row && {
85
+ sessionId: row.session_id,
86
+ harness: row.harness,
87
+ headSeq: row.head_seq,
88
+ nativeSessionId: row.native_id,
89
+ closed: Boolean(row.closed),
90
+ recoveryRequired: Boolean(row.recovery_required),
91
+ }
92
+ );
93
+ }
94
+ turn(sessionId: string, turnId: string): TurnReceipt | undefined {
95
+ const row = this.db.one<{
96
+ state: TurnReceipt["state"];
97
+ input: string;
98
+ terminal: string | null;
99
+ }>(
100
+ "SELECT t.state, t.input, e.body AS terminal FROM turns t LEFT JOIN events e ON e.source_id=? AND e.session_id=t.session_id AND e.seq=t.terminal_seq WHERE t.session_id=? AND t.turn_id=?",
101
+ this.sourceId,
102
+ sessionId,
103
+ turnId,
104
+ );
105
+ return (
106
+ row && {
107
+ sessionId,
108
+ turnId,
109
+ state: row.state,
110
+ input: JSON.parse(row.input),
111
+ ...(row.terminal !== null && { terminal: JSON.parse(row.terminal) as TurnEndedEvent }),
112
+ }
113
+ );
114
+ }
115
+ admission(request: RunRequest): "new" | "duplicate" {
116
+ const row = this.db.one<{ fingerprint: string }>(
117
+ "SELECT fingerprint FROM turns WHERE session_id=? AND turn_id=?",
118
+ request.sessionId,
119
+ request.turnId,
120
+ );
121
+ if (!row) return "new";
122
+ if (row.fingerprint !== fingerprint(request))
123
+ throw new JournalError("turnConflict", "Turn ID already belongs to a different request", {
124
+ turnId: request.turnId,
125
+ });
126
+ return "duplicate";
127
+ }
128
+ admit(request: RunRequest): "new" | "duplicate" {
129
+ const { sessionId, turnId, config } = request;
130
+ if (!storableId(sessionId) || !storableId(turnId))
131
+ throw new JournalError("invalidRecord", "Durable session and turn IDs are 1-512 characters");
132
+ if (this.history.isBranch(sessionId))
133
+ throw new JournalError(
134
+ "invalidRecord",
135
+ "History branch is not a native execution session; prepare provider context explicitly",
136
+ );
137
+ const input = canonical(request.input);
138
+ if (Buffer.byteLength(input) > MAX_EVENT_BYTES)
139
+ throw new JournalError("recordTooLarge", "Input exceeds durable record limit");
140
+ return this.db.atomic(() => {
141
+ if (this.admission(request) === "duplicate") return "duplicate";
142
+ const state = this.session(sessionId);
143
+ if (state?.closed)
144
+ throw new JournalError("sessionClosed", "Closed durable session IDs cannot be reused");
145
+ if (state?.recoveryRequired)
146
+ throw new JournalError(
147
+ "recoveryRequired",
148
+ "Confirm the interrupted native execution stopped before starting another turn",
149
+ { headSeq: state.headSeq },
150
+ );
151
+ // Without its native conversation, a turn would silently start a new one.
152
+ if (
153
+ state?.nativeSessionId &&
154
+ !this.live.has(sessionId) &&
155
+ config.resumeSessionId !== state.nativeSessionId
156
+ )
157
+ throw new JournalError(
158
+ "resumeRequired",
159
+ "This session was restored; explicitly pass its nativeSessionId as config.resumeSessionId, or start a new session",
160
+ { nativeSessionId: state.nativeSessionId },
161
+ );
162
+ if (state && state.harness !== config.harness)
163
+ throw new JournalError("invalidRecord", "Session harness cannot change");
164
+ if (config.includeRaw)
165
+ throw new JournalError("invalidRecord", "Durable sessions require includeRaw=false");
166
+ const active = this.activeTurn(sessionId);
167
+ if (active)
168
+ throw new JournalError("turnActive", "Session already has an admitted turn", {
169
+ turnId: active,
170
+ });
171
+ if (!state) {
172
+ this.db.run(
173
+ "INSERT INTO sessions(session_id,harness) VALUES (?,?)",
174
+ sessionId,
175
+ config.harness,
176
+ );
177
+ this.log.create({ ...this.ref(sessionId), format: 1, kind: "execution" });
178
+ }
179
+ this.db.run(
180
+ "INSERT INTO turns(session_id,turn_id,fingerprint,input,state) VALUES (?,?,?,?,'admitted')",
181
+ sessionId,
182
+ turnId,
183
+ fingerprint(request),
184
+ input,
185
+ );
186
+ return "new";
187
+ });
188
+ }
189
+ private activeTurn(sessionId: string): string | undefined {
190
+ return this.db.one<{ turn_id: string }>(
191
+ "SELECT turn_id FROM turns WHERE session_id=? AND state='admitted'",
192
+ sessionId,
193
+ )?.turn_id;
194
+ }
195
+
196
+ append(event: LifecycleEvent): WireEventEnvelope {
197
+ const { sessionId } = event;
198
+ if (!sessionId) throw new JournalError("invalidRecord", "Durable events require a session ID");
199
+ const stored = recordable({ ...event, sessionId });
200
+ const envelope = this.db.atomic(() => {
201
+ const recorded = this.record(stored.event, stored.body);
202
+ this.apply(recorded.event, recorded.seq);
203
+ return recorded;
204
+ });
205
+ if (envelope.event.type === "session.created") this.live.add(sessionId);
206
+ this.history.changed(this.ref(sessionId));
207
+ return envelope;
208
+ }
209
+ /** Inside a transaction: record one storable event of an open session. */
210
+ private record(event: SessionEvent, body: string): WireEventEnvelope {
211
+ const { sessionId } = event;
212
+ const state = this.session(sessionId);
213
+ if (!state || state.closed)
214
+ throw new JournalError("sessionClosed", "Cannot append to an unknown or closed session");
215
+ if (event.type === "session.ended" && (state.recoveryRequired || this.activeTurn(sessionId)))
216
+ throw new JournalError(
217
+ "recoveryRequired",
218
+ "Cannot close a session with unconfirmed execution",
219
+ );
220
+ const head = this.log.head(this.ref(sessionId))!.version;
221
+ const { seq } = this.log.append(head, [body]);
222
+ return { sessionId, seq, event: JSON.parse(body) as LifecycleEvent };
223
+ }
224
+ /** What a recorded event changes beyond the history. */
225
+ private apply(event: LifecycleEvent, seq: number): void {
226
+ switch (event.type) {
227
+ case "session.created":
228
+ this.db.run(
229
+ "UPDATE sessions SET native_id=? WHERE session_id=?",
230
+ event.nativeSessionId,
231
+ event.sessionId,
232
+ );
233
+ break;
234
+ case "turn.ended":
235
+ this.settle(event.sessionId, event.turnId, "completed", seq);
236
+ break;
237
+ case "session.ended":
238
+ this.db.run("UPDATE sessions SET closed=1 WHERE session_id=?", event.sessionId);
239
+ break;
240
+ }
241
+ }
242
+ private settle(
243
+ sessionId: string,
244
+ turnId: string,
245
+ state: "completed" | "interrupted",
246
+ terminalSeq: number,
247
+ ): void {
248
+ this.db.run(
249
+ "UPDATE turns SET state=?, terminal_seq=? WHERE session_id=? AND turn_id=? AND state='admitted'",
250
+ state,
251
+ terminalSeq,
252
+ sessionId,
253
+ turnId,
254
+ );
255
+ }
256
+
257
+ replay(
258
+ sessionId: string,
259
+ fromSeq: number,
260
+ limit = HISTORY_MAX_RECORDS,
261
+ ): { events: WireEventEnvelope[]; hasMore: boolean } {
262
+ const ref = this.ref(sessionId);
263
+ const head = this.log.head(ref)?.version.seq ?? 0;
264
+ const events: WireEventEnvelope[] = [];
265
+ // Each envelope: {"sessionId":…,"seq":…,"event":BODY} and its comma.
266
+ const envelope = Buffer.byteLength(JSON.stringify(sessionId)) + 48;
267
+ let bytes = 0;
268
+ for (const row of this.log.records(
269
+ ref,
270
+ fromSeq - 1,
271
+ head,
272
+ Math.min(limit, HISTORY_MAX_RECORDS),
273
+ )) {
274
+ // Every event fits a page alone; a page holds as many as fit together.
275
+ bytes += Buffer.byteLength(row.body) + envelope;
276
+ if (events.length && bytes > HISTORY_MAX_BYTES - 65536) break;
277
+ events.push({ sessionId, seq: row.seq, event: JSON.parse(row.body) as LifecycleEvent });
278
+ }
279
+ return { events, hasMore: (events.at(-1)?.seq ?? fromSeq - 1) < head };
280
+ }
281
+
282
+ /** End each turn a previous owner left admitted, closing what it left open first,
283
+ * so its history stays a valid stream; fence its session until confirmed. */
284
+ private recoverInterrupted(): void {
285
+ this.db.atomic(() => {
286
+ const admitted = this.db.all<{ session_id: string; turn_id: string }>(
287
+ "SELECT session_id,turn_id FROM turns WHERE state='admitted'",
288
+ );
289
+ for (const { session_id: sessionId, turn_id: turnId } of admitted) {
290
+ const at = Date.now();
291
+ const history = [...this.log.records(this.ref(sessionId), 0, Number.MAX_SAFE_INTEGER)].map(
292
+ (row) => JSON.parse(row.body),
293
+ );
294
+ const ended: TurnEndedEvent = {
295
+ type: "turn.ended",
296
+ sessionId,
297
+ turnId,
298
+ stopReason: "error",
299
+ error: {
300
+ category: "internal",
301
+ message:
302
+ "Server restarted before the turn settled. Native execution is unconfirmed; inspect it before resuming.",
303
+ },
304
+ timestamp: at,
305
+ };
306
+ // A turn cut off before its first event still reads as started, then ended.
307
+ const started = history.some(
308
+ (event) => event?.type === "turn.started" && event.turnId === turnId,
309
+ );
310
+ const opened: LifecycleEvent[] = started
311
+ ? []
312
+ : [
313
+ {
314
+ type: "turn.started",
315
+ sessionId,
316
+ turnId,
317
+ execution: { harness: this.session(sessionId)!.harness },
318
+ timestamp: at,
319
+ },
320
+ ];
321
+ let seq = 0;
322
+ for (const fact of [
323
+ ...opened,
324
+ ...interruptionFacts(history, sessionId, turnId, at),
325
+ ended,
326
+ ]) {
327
+ const stored = recordable({ ...fact, sessionId });
328
+ seq = this.record(stored.event, stored.body).seq;
329
+ }
330
+ this.settle(sessionId, turnId, "interrupted", seq);
331
+ this.db.run("UPDATE sessions SET recovery_required=1 WHERE session_id=?", sessionId);
332
+ }
333
+ });
334
+ }
335
+ confirmStopped(sessionId: string, expectedHeadSeq: number): boolean {
336
+ return this.db.atomic(() => {
337
+ const state = this.session(sessionId);
338
+ if (!state || state.headSeq !== expectedHeadSeq)
339
+ throw new JournalError(
340
+ state ? "staleHead" : "unknownSession",
341
+ state ? "Recovery confirmation names an old history position" : "Unknown durable session",
342
+ state && { headSeq: state.headSeq },
343
+ );
344
+ if (!state.recoveryRequired) return false;
345
+ this.db.run("UPDATE sessions SET recovery_required=0 WHERE session_id=?", sessionId);
346
+ return true;
347
+ });
348
+ }
349
+ close(): void {
350
+ this.history.close();
351
+ this.db.close();
352
+ }
353
+ }
@@ -0,0 +1,73 @@
1
+ import type {
2
+ DurableSession,
3
+ LifecycleEvent,
4
+ RunRequest,
5
+ TurnReceipt,
6
+ WireEventEnvelope,
7
+ } from "../protocol/index.ts";
8
+
9
+ /**
10
+ * What a journal refuses, as opposed to failing to store: the request itself
11
+ * is the problem, nothing was written, and the journal stays usable. Any other
12
+ * error a journal throws means its storage failed.
13
+ */
14
+ export class JournalError extends Error {
15
+ override readonly name = "JournalError";
16
+ constructor(
17
+ readonly code:
18
+ | "turnConflict"
19
+ | "turnActive"
20
+ | "sessionClosed"
21
+ | "recoveryRequired"
22
+ | "resumeRequired"
23
+ | "unknownSession"
24
+ | "staleHead"
25
+ | "invalidRecord"
26
+ | "recordTooLarge",
27
+ message: string,
28
+ /** What the caller needs to act on the refusal, e.g. the `headSeq` to confirm. */
29
+ readonly data?: Record<string, unknown>,
30
+ ) {
31
+ super(message);
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Durable execution history. Synchronous and transactional: a method that
37
+ * returns has committed locally. Session histories are also served, read-only,
38
+ * through the adapter's history store under this journal's `sourceId`.
39
+ */
40
+ export interface SessionJournal {
41
+ readonly sourceId: string;
42
+ /**
43
+ * Take execution ownership: one executing owner per journal. Ends the turns
44
+ * a previous owner left running as interrupted (`interruptionFacts`), never
45
+ * rerunning them, and fences their sessions until `confirmStopped`. Returns
46
+ * the release.
47
+ */
48
+ claim(): () => void;
49
+ session(sessionId: string): DurableSession | undefined;
50
+ turn(sessionId: string, turnId: string): TurnReceipt | undefined;
51
+ /** Whether this journal already admitted the turn. Throws `turnConflict` for other input. */
52
+ admission(request: RunRequest): "new" | "duplicate";
53
+ /**
54
+ * Commit the turn's receipt and input, or refuse it, checking in order:
55
+ * duplicate (no write), closed session, unconfirmed interruption, a session
56
+ * this owner has not resumed (`resumeRequired`), harness change, raw output,
57
+ * active turn.
58
+ */
59
+ admit(request: RunRequest): "new" | "duplicate";
60
+ /** Commits `event`, or, when its content cannot be stored, a fitted copy or a
61
+ * notice in its place (`fitEvent`, `unrecordedEvent`). Deliver what it returns.
62
+ * Throws only when storage itself fails. */
63
+ append(event: LifecycleEvent): WireEventEnvelope;
64
+ /** Committed events from `fromSeq`, a bounded page at a time. */
65
+ replay(
66
+ sessionId: string,
67
+ fromSeq: number,
68
+ limit?: number,
69
+ ): { events: WireEventEnvelope[]; hasMore: boolean };
70
+ /** Lift the fence `claim` put on an interrupted session. False when there was none. */
71
+ confirmStopped(sessionId: string, expectedHeadSeq: number): boolean;
72
+ close(): void;
73
+ }
@@ -0,0 +1,20 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { SqliteJournal } from "./journal-sqlite.ts";
3
+ import { openJournalFile } from "./sqlite-file.ts";
4
+
5
+ /** Node >=22.16 adapter (node:sqlite). Same schema and guarantees as Bun.
6
+ * Transpile the package's TypeScript using the host's normal build pipeline. */
7
+ export class NodeSqliteSessionJournal extends SqliteJournal {
8
+ constructor(path: string) {
9
+ super(
10
+ openJournalFile(path, (file) => {
11
+ const db = new DatabaseSync(file);
12
+ return {
13
+ exec: (sql) => db.exec(sql),
14
+ prepare: (sql) => db.prepare(sql),
15
+ close: () => db.close(),
16
+ };
17
+ }),
18
+ );
19
+ }
20
+ }
@@ -0,0 +1,112 @@
1
+ import {
2
+ type LifecycleEvent,
3
+ PARTIAL_INPUT_META_KEY,
4
+ type Part,
5
+ decodeLifecycleEvent,
6
+ emptyConversation,
7
+ isUnknownEvent,
8
+ reduceConversation,
9
+ } from "../protocol/index.ts";
10
+
11
+ /** What a tool that was running when the process died reports. */
12
+ export const INTERRUPTED_TOOL_ERROR =
13
+ "Tool execution was interrupted when agent-server stopped. Its outcome is unknown and its effects were not undone. Check the current state before continuing or retrying.";
14
+
15
+ function closePart(part: Part, at: number): Part | undefined {
16
+ if (part.type === "tool") {
17
+ const state = part.state;
18
+ if (state.status === "pending")
19
+ return {
20
+ ...part,
21
+ state: {
22
+ status: "failed",
23
+ input: {},
24
+ error: INTERRUPTED_TOOL_ERROR,
25
+ time: { start: at, end: at },
26
+ ...(state.partialInput && {
27
+ _meta: { ...state._meta, [PARTIAL_INPUT_META_KEY]: state.partialInput },
28
+ }),
29
+ },
30
+ };
31
+ if (state.status === "in_progress")
32
+ return {
33
+ ...part,
34
+ state: {
35
+ status: "failed",
36
+ input: state.input,
37
+ error: INTERRUPTED_TOOL_ERROR,
38
+ time: { start: state.time.start, end: at },
39
+ ...(state._meta && { _meta: state._meta }),
40
+ },
41
+ };
42
+ return undefined;
43
+ }
44
+ if ((part.type === "text" || part.type === "reasoning") && part.state === "streaming")
45
+ return { ...part, state: "done" };
46
+ return undefined;
47
+ }
48
+
49
+ /**
50
+ * The facts that close what an interrupted turn left open, to commit before
51
+ * its `turn.ended`: pending permissions resolve as cancelled, running tools
52
+ * fail with an outcome-unknown error, streaming text is marked done, and open
53
+ * messages end. `events` is the turn's committed history, oldest first.
54
+ */
55
+ export function interruptionFacts(
56
+ events: Iterable<unknown>,
57
+ sessionId: string,
58
+ turnId: string,
59
+ at: number,
60
+ ): LifecycleEvent[] {
61
+ let state = emptyConversation();
62
+ const address = new Map<string, { messageId: string; outputIndex: number; partIndex: number }>();
63
+ for (const raw of events) {
64
+ const event = decodeLifecycleEvent(raw);
65
+ state = reduceConversation(state, event);
66
+ if (!isUnknownEvent(event) && event.type === "message.part" && event.turnId === turnId)
67
+ address.set(event.part.id, {
68
+ messageId: event.messageId,
69
+ outputIndex: event.outputIndex,
70
+ partIndex: event.partIndex,
71
+ });
72
+ }
73
+ const facts: LifecycleEvent[] = [];
74
+ for (const permission of state.permissions)
75
+ if (permission.turnId === turnId && permission.outcome === undefined)
76
+ facts.push({
77
+ type: "permission.resolved",
78
+ sessionId,
79
+ turnId,
80
+ requestId: permission.requestId,
81
+ outcome: { outcome: "cancelled" },
82
+ timestamp: at,
83
+ });
84
+ for (const entry of state.timeline) {
85
+ if (entry.kind !== "message" || entry.turnId !== turnId) continue;
86
+ // A tool keeps running after the model message that called it ends, and
87
+ // its later states update the part under that ended message.
88
+ for (const part of entry.parts) {
89
+ if ("raw" in part) continue;
90
+ const where = address.get(part.id);
91
+ const closed = where && closePart(part, at);
92
+ if (where && closed)
93
+ facts.push({
94
+ type: "message.part",
95
+ sessionId,
96
+ turnId,
97
+ ...where,
98
+ part: closed,
99
+ timestamp: at,
100
+ });
101
+ }
102
+ if (entry.endedAt === undefined)
103
+ facts.push({
104
+ type: "message.ended",
105
+ sessionId,
106
+ turnId,
107
+ messageId: entry.messageId,
108
+ timestamp: at,
109
+ });
110
+ }
111
+ return facts;
112
+ }
@@ -0,0 +1,49 @@
1
+ /** Resolves after `ms`, or as soon as `signal` aborts (without throwing). */
2
+ export function pause(ms: number, signal?: AbortSignal): Promise<void> {
3
+ if (signal?.aborted) return Promise.resolve();
4
+ return new Promise((resolve) => {
5
+ const done = () => {
6
+ clearTimeout(timer);
7
+ signal?.removeEventListener("abort", done);
8
+ resolve();
9
+ };
10
+ const timer = setTimeout(done, ms);
11
+ signal?.addEventListener("abort", done, { once: true });
12
+ });
13
+ }
14
+
15
+ /** The shortest time between two waits that brought nothing. */
16
+ const IDLE_FLOOR_MS = 100;
17
+ /** After a wait that brought nothing, pause what remains of the idle floor: a
18
+ * wait answered at once (a zero timeout, or one a short request timeout clamps)
19
+ * must not spin. */
20
+ export function idleAfter(waitStartedAt: number, signal?: AbortSignal): Promise<void> {
21
+ return pause(Math.max(0, IDLE_FLOOR_MS - (Date.now() - waitStartedAt)), signal);
22
+ }
23
+
24
+ /**
25
+ * The host's retry policy: the delay in ms before retrying `error` after
26
+ * `failures` consecutive failures, or undefined to give up. Retry transport
27
+ * failures (`ConnectionClosedError`); never retry a HistoryError.
28
+ */
29
+ export type RetryPolicy = (error: unknown, failures: number) => number | undefined;
30
+
31
+ /** Consecutive failures under a retry policy. Only progress puts them behind:
32
+ * a read that changes nothing does not repair a channel that keeps failing. */
33
+ export class RetryBudget {
34
+ private consecutive = 0;
35
+ constructor(private readonly policy?: RetryPolicy) {}
36
+ get failures(): number {
37
+ return this.consecutive;
38
+ }
39
+ /** The delay before retrying (at most a minute), or `error` rethrown when
40
+ * the policy gives up. */
41
+ fail(error: unknown): number {
42
+ const ms = this.policy?.(error, ++this.consecutive);
43
+ if (ms === undefined || !Number.isFinite(ms) || ms < 0) throw error;
44
+ return Math.min(ms, 60_000);
45
+ }
46
+ progressed(): void {
47
+ this.consecutive = 0;
48
+ }
49
+ }
@@ -0,0 +1,56 @@
1
+ import type { Db } from "./sql.ts";
2
+
3
+ /** Nothing has been released yet, so there are no migrations: an empty file
4
+ * gets this schema, and a released change will add ordered migrations keyed
5
+ * by `user_version`. Version 1 was an unreleased experiment's layout. */
6
+ export const SCHEMA_VERSION = 2;
7
+
8
+ const DDL = `
9
+ CREATE TABLE identity (id TEXT PRIMARY KEY);
10
+ -- Every history this store holds, run here or copied in: descriptor and head.
11
+ CREATE TABLE histories (
12
+ source_id TEXT NOT NULL, session_id TEXT NOT NULL, descriptor TEXT NOT NULL,
13
+ head_seq INTEGER NOT NULL, head_hash TEXT NOT NULL,
14
+ PRIMARY KEY (source_id, session_id));
15
+ -- Every history's records: canonical event JSON, hash-chained per history.
16
+ CREATE TABLE events (
17
+ source_id TEXT NOT NULL, session_id TEXT NOT NULL, seq INTEGER NOT NULL,
18
+ hash TEXT NOT NULL, body TEXT NOT NULL,
19
+ PRIMARY KEY (source_id, session_id, seq));
20
+ -- The sessions this store executes; their histories have its identity as source.
21
+ CREATE TABLE sessions (
22
+ session_id TEXT PRIMARY KEY, harness TEXT NOT NULL, native_id TEXT,
23
+ closed INTEGER NOT NULL DEFAULT 0, recovery_required INTEGER NOT NULL DEFAULT 0);
24
+ -- Admitted turns: the request's fingerprint and input, then how it settled.
25
+ CREATE TABLE turns (
26
+ session_id TEXT NOT NULL, turn_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
27
+ input TEXT NOT NULL, state TEXT NOT NULL, terminal_seq INTEGER,
28
+ PRIMARY KEY (session_id, turn_id));
29
+ CREATE UNIQUE INDEX one_active_turn ON turns (session_id) WHERE state = 'admitted';
30
+ -- Branch commits by id, so a retried commit returns the version it first made.
31
+ CREATE TABLE commits (
32
+ session_id TEXT NOT NULL, commit_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
33
+ version TEXT NOT NULL, PRIMARY KEY (session_id, commit_id));
34
+ -- Cached conversation projections; the events stay authoritative.
35
+ CREATE TABLE checkpoints (
36
+ source_id TEXT NOT NULL, session_id TEXT NOT NULL, format TEXT NOT NULL,
37
+ seq INTEGER NOT NULL, body TEXT NOT NULL,
38
+ PRIMARY KEY (source_id, session_id, format));
39
+ PRAGMA user_version = ${SCHEMA_VERSION};
40
+ `;
41
+
42
+ /** Create or check the schema; returns the store's identity, minting it once. */
43
+ export function openSchema(db: Db, newId: () => string): string {
44
+ const { user_version: version } = db.one<{ user_version: number }>("PRAGMA user_version")!;
45
+ if (version !== 0 && version !== SCHEMA_VERSION)
46
+ throw new Error(
47
+ `Unsupported journal schema ${version}; this build reads schema ${SCHEMA_VERSION}`,
48
+ );
49
+ return db.atomic(() => {
50
+ if (version === 0) {
51
+ db.exec(DDL);
52
+ db.run("INSERT INTO identity(id) VALUES (?)", newId());
53
+ }
54
+ return db.one<{ id: string }>("SELECT id FROM identity")!.id;
55
+ });
56
+ }