@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,344 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ CONVERSATION_CHECKPOINT_FORMAT,
4
+ ConversationStateSchema,
5
+ HISTORY_MAX_BYTES,
6
+ type HistoryCatalog,
7
+ type HistoryCheckpoint,
8
+ type HistoryCheckpointRequest,
9
+ HistoryCheckpointRequestSchema,
10
+ HistoryCheckpointSchema,
11
+ type HistoryCommit,
12
+ HistoryCommitSchema,
13
+ type HistoryDescriptor,
14
+ HistoryError,
15
+ type HistoryFork,
16
+ HistoryForkSchema,
17
+ type HistoryHead,
18
+ type HistoryList,
19
+ HistoryListSchema,
20
+ type HistoryPull,
21
+ HistoryPullSchema,
22
+ type HistorySlice,
23
+ type HistoryStore,
24
+ type HistoryVersion,
25
+ type HistoryWait,
26
+ HistoryWaitSchema,
27
+ type SessionRef,
28
+ canonicalHistoryJson as canonical,
29
+ decodeLifecycleEvent,
30
+ emptyConversation,
31
+ jsonBytes,
32
+ parseHistoryRequest,
33
+ reduceConversation,
34
+ sameHistory,
35
+ sameVersion,
36
+ validateHistoryRecords,
37
+ validateHistorySlice,
38
+ } from "../protocol/index.ts";
39
+ import type { EventLog, EventRow } from "./event-log.ts";
40
+ import { MAX_EVENT_BYTES, PAGE_SLACK_BYTES } from "./fit.ts";
41
+ import type { Db } from "./sql.ts";
42
+
43
+ const conflict = (message: string) => new HistoryError("conflict", message);
44
+ const missing = (message: string) => new HistoryError("missing", message);
45
+ const invalid = (message: string) => new HistoryError("invalid", message);
46
+ const digest = (value: unknown) => createHash("sha256").update(canonical(value)).digest("hex");
47
+ /** A record's bytes in a page, `{"seq":N,"event":BODY}`: the stored body is its canonical JSON. */
48
+ const recordBytes = (row: EventRow) => 17 + String(row.seq).length + Buffer.byteLength(row.body);
49
+
50
+ /** Every history one journal file holds: those it ran, branched or copied in.
51
+ * Each mutation is one transaction; wakeups run after it commits. */
52
+ export class SqliteHistory implements HistoryStore {
53
+ private readonly closed = new AbortController();
54
+ private readonly listeners = new Set<(ref: SessionRef) => void>();
55
+
56
+ constructor(
57
+ readonly sourceId: string,
58
+ private readonly db: Db,
59
+ private readonly log: EventLog,
60
+ ) {}
61
+
62
+ /** A fork reserves its ID from the executable session namespace. */
63
+ isBranch(sessionId: string): boolean {
64
+ return this.log.head({ sourceId: this.sourceId, sessionId })?.descriptor.kind === "branch";
65
+ }
66
+ changed(ref: SessionRef): void {
67
+ for (const listener of this.listeners) {
68
+ try {
69
+ listener(ref);
70
+ } catch {
71
+ /* wakeups cannot undo a commit */
72
+ }
73
+ }
74
+ }
75
+ onChange(listener: (ref: SessionRef) => void): () => void {
76
+ this.listeners.add(listener);
77
+ return () => {
78
+ this.listeners.delete(listener);
79
+ };
80
+ }
81
+ close(): void {
82
+ this.closed.abort(new Error("History store closed"));
83
+ this.listeners.clear();
84
+ }
85
+
86
+ head(ref: SessionRef): HistoryHead {
87
+ const head = this.log.head(ref);
88
+ if (!head) throw missing("Unknown history");
89
+ return head;
90
+ }
91
+ /** The head of a history that holds `expected` exactly. */
92
+ private holding(expected: HistoryVersion): HistoryHead {
93
+ const head = this.head(expected);
94
+ if (expected.seq > head.version.seq)
95
+ throw missing("History does not reach the requested version");
96
+ const version =
97
+ expected.seq === 0 ? this.log.root(head.descriptor) : this.log.at(expected, expected.seq);
98
+ if (version?.hash !== expected.hash)
99
+ throw conflict("History version does not match the committed prefix");
100
+ return head;
101
+ }
102
+
103
+ list(request: HistoryList = {}): HistoryCatalog {
104
+ const { after, limit } = parseHistoryRequest(HistoryListSchema, request);
105
+ if (after && after.storeId !== this.sourceId)
106
+ throw invalid("Catalog cursor belongs to another store");
107
+ const heads = this.log.heads(after?.ref, limit + 1);
108
+ const entries = heads.slice(0, limit);
109
+ const last = entries.at(-1)?.version;
110
+ return {
111
+ entries,
112
+ next:
113
+ heads.length > limit && last
114
+ ? { storeId: this.sourceId, ref: { sourceId: last.sourceId, sessionId: last.sessionId } }
115
+ : null,
116
+ };
117
+ }
118
+
119
+ read(request: HistoryPull): HistorySlice {
120
+ const params = parseHistoryRequest(HistoryPullSchema, request);
121
+ const current = this.head(params);
122
+ const { descriptor } = current;
123
+ const base = params.after ?? this.log.root(descriptor);
124
+ const head = params.through ?? current.version;
125
+ if (!sameHistory(base, descriptor) || !sameHistory(head, descriptor) || base.seq > head.seq)
126
+ throw invalid("History range belongs to another history or revision");
127
+ this.holding(base);
128
+ this.holding(head);
129
+ const page: HistorySlice = {
130
+ descriptor,
131
+ base,
132
+ head,
133
+ next: base,
134
+ records: [],
135
+ hasMore: base.seq < head.seq,
136
+ };
137
+ // Count bytes as records are added; slack covers `next` and `hasMore` changing.
138
+ let bytes = jsonBytes(page) + PAGE_SLACK_BYTES;
139
+ if (bytes > params.maxBytes) throw invalid("History metadata exceeds page budget");
140
+ for (const row of this.log.records(descriptor, base.seq, head.seq, params.limit)) {
141
+ const size = recordBytes(row) + (page.records.length ? 1 : 0);
142
+ if (bytes + size > params.maxBytes) {
143
+ if (!page.records.length)
144
+ throw invalid("Increase history page maxBytes or use blob references");
145
+ break;
146
+ }
147
+ bytes += size;
148
+ page.records.push({ seq: row.seq, event: JSON.parse(row.body) });
149
+ page.next = { ...base, seq: row.seq, hash: row.hash };
150
+ }
151
+ page.hasMore = page.next.seq < head.seq;
152
+ return page;
153
+ }
154
+
155
+ fork(value: HistoryFork): HistoryHead {
156
+ const request = parseHistoryRequest(HistoryForkSchema, value);
157
+ const ref = { sourceId: this.sourceId, sessionId: request.sessionId };
158
+ const descriptor: HistoryDescriptor = {
159
+ ...ref,
160
+ format: 1,
161
+ kind: "branch",
162
+ ...(request.from && { parent: request.from }),
163
+ };
164
+ this.db.atomic(() => {
165
+ const existing = this.log.head(ref)?.descriptor;
166
+ if (existing?.kind === "execution") throw conflict("Cannot fork over an execution session");
167
+ if (request.from) {
168
+ if (sameHistory(request.from, ref)) throw invalid("A history cannot be its own parent");
169
+ this.holding(request.from);
170
+ }
171
+ if (!existing) this.log.create(descriptor);
172
+ else if (canonical(existing) !== canonical(descriptor))
173
+ throw conflict("History descriptor cannot change");
174
+ });
175
+ this.changed(ref);
176
+ return this.head(ref);
177
+ }
178
+
179
+ commit(value: HistoryCommit): HistoryVersion {
180
+ const request = parseHistoryRequest(HistoryCommitSchema, value);
181
+ if (jsonBytes(request) > HISTORY_MAX_BYTES) throw invalid("History commit exceeds byte limit");
182
+ const ref = request.expected;
183
+ const fingerprint = digest(request);
184
+ const result = this.db.atomic(() => {
185
+ const current = this.log.head(ref);
186
+ if (ref.sourceId !== this.sourceId || current?.descriptor.kind !== "branch")
187
+ throw invalid("Only locally owned branches accept explicit commits");
188
+ const receipt = this.db.one<{ fingerprint: string; version: string }>(
189
+ "SELECT fingerprint,version FROM commits WHERE session_id=? AND commit_id=?",
190
+ ref.sessionId,
191
+ request.commitId,
192
+ );
193
+ if (receipt) {
194
+ if (receipt.fingerprint !== fingerprint)
195
+ throw conflict("Commit ID was reused with different content");
196
+ return JSON.parse(receipt.version) as HistoryVersion;
197
+ }
198
+ if (!sameVersion(current.version, request.expected))
199
+ throw conflict(
200
+ "Commit expected head is stale; pull and fork or retry from the current version",
201
+ );
202
+ const first = current.version.seq + 1;
203
+ validateHistoryRecords(
204
+ ref.sessionId,
205
+ request.events.map((event, i) => ({ seq: first + i, event })),
206
+ );
207
+ const bodies = request.events.map((event) => canonical(event));
208
+ if (bodies.some((body) => Buffer.byteLength(body) > MAX_EVENT_BYTES))
209
+ throw invalid("History event exceeds readable page size");
210
+ const next = this.log.append(current.version, bodies);
211
+ this.db.run(
212
+ "INSERT INTO commits(session_id,commit_id,fingerprint,version) VALUES (?,?,?,?)",
213
+ ref.sessionId,
214
+ request.commitId,
215
+ fingerprint,
216
+ canonical(next),
217
+ );
218
+ return next;
219
+ });
220
+ this.changed(ref);
221
+ return result;
222
+ }
223
+
224
+ import(value: HistorySlice): HistoryVersion {
225
+ // The trust boundary for every caller, in process or over the wire.
226
+ const page = validateHistorySlice(value);
227
+ const ref = page.descriptor;
228
+ if (ref.sourceId === this.sourceId)
229
+ throw conflict("Cannot import over a locally owned history");
230
+ this.db.atomic(() => {
231
+ if (ref.parent) this.holding(ref.parent);
232
+ const existing = this.log.head(ref);
233
+ if (existing && canonical(existing.descriptor) !== canonical(page.descriptor))
234
+ throw conflict("History descriptor cannot change");
235
+ let head = existing?.version ?? this.log.create(page.descriptor);
236
+ this.holding(page.base);
237
+ // Records this store already holds must be identical; the rest extend it.
238
+ const held = new Map<number, string>();
239
+ for (const row of this.log.records(ref, page.base.seq, Math.min(head.seq, page.next.seq)))
240
+ held.set(row.seq, row.body);
241
+ const suffix: string[] = [];
242
+ for (const record of page.records) {
243
+ const body = canonical(record.event);
244
+ if (record.seq > head.seq) suffix.push(body);
245
+ else if (held.get(record.seq) !== body) throw conflict("History record conflict");
246
+ }
247
+ if (suffix.length) head = this.log.append(head, suffix);
248
+ const committed = head.seq === page.next.seq ? head : this.log.at(ref, page.next.seq);
249
+ if (!committed || !sameVersion(committed, page.next))
250
+ throw conflict("History payload does not match its committed version");
251
+ });
252
+ this.changed(ref);
253
+ return page.next;
254
+ }
255
+
256
+ async wait(value: HistoryWait, signal?: AbortSignal): Promise<HistoryHead> {
257
+ const request = parseHistoryRequest(HistoryWaitSchema, value);
258
+ const stop = AbortSignal.any([this.closed.signal, ...(signal ? [signal] : [])]);
259
+ stop.throwIfAborted();
260
+ const current = this.holding(request.after);
261
+ if (!sameVersion(current.version, request.after) || !request.timeoutMs) return current;
262
+ return new Promise((resolve, reject) => {
263
+ let dispose = () => {};
264
+ const cleanup = () => {
265
+ clearTimeout(timer);
266
+ dispose();
267
+ stop.removeEventListener("abort", abort);
268
+ };
269
+ const finish = () => {
270
+ cleanup();
271
+ try {
272
+ resolve(this.head(request.after));
273
+ } catch (error) {
274
+ reject(error);
275
+ }
276
+ };
277
+ const abort = () => {
278
+ cleanup();
279
+ reject(stop.reason);
280
+ };
281
+ const timer = setTimeout(finish, request.timeoutMs);
282
+ dispose = this.onChange((ref) => {
283
+ if (sameHistory(ref, request.after)) finish();
284
+ });
285
+ stop.addEventListener("abort", abort, { once: true });
286
+ if (stop.aborted) abort();
287
+ else if (!sameVersion(this.head(request.after).version, request.after)) finish();
288
+ });
289
+ }
290
+
291
+ /** Return only a compatible, previously built cache. Older pinned forks fall
292
+ * back to canonical replay when the single retained cache is beyond their cut. */
293
+ checkpoint(request: HistoryCheckpointRequest): HistoryCheckpoint | null {
294
+ const { through } = parseHistoryRequest(HistoryCheckpointRequestSchema, request);
295
+ this.holding(through);
296
+ const row = this.db.one<{ body: string }>(
297
+ "SELECT body FROM checkpoints WHERE source_id=? AND session_id=? AND seq<=? AND format=?",
298
+ through.sourceId,
299
+ through.sessionId,
300
+ through.seq,
301
+ CONVERSATION_CHECKPOINT_FORMAT,
302
+ );
303
+ if (!row) return null;
304
+ const checkpoint = HistoryCheckpointSchema.parse(JSON.parse(row.body));
305
+ this.holding(checkpoint.version);
306
+ return checkpoint;
307
+ }
308
+ /** Host-only bounded cache construction. No RPC accepts uploaded projections.
309
+ * Advance incrementally (e.g. every 1000 events); keep all original events. */
310
+ createCheckpoint(
311
+ ref: SessionRef,
312
+ options: { through?: HistoryVersion; maxRecords?: number } = {},
313
+ ): HistoryCheckpoint {
314
+ const target = options.through ?? this.head(ref).version;
315
+ if (!sameHistory(target, ref)) throw invalid("Checkpoint belongs to another history");
316
+ this.holding(target);
317
+ const prior = this.checkpoint({ through: target });
318
+ let conversation = prior
319
+ ? ConversationStateSchema.parse(prior.conversation)
320
+ : emptyConversation();
321
+ const limit = options.maxRecords ?? 100_000;
322
+ if (!Number.isSafeInteger(limit) || limit < 0)
323
+ throw new Error("Invalid checkpoint record limit");
324
+ let count = 0;
325
+ for (const row of this.log.records(ref, prior?.version.seq ?? 0, target.seq)) {
326
+ if (++count > limit) throw new Error("Checkpoint replay limit exceeded");
327
+ conversation = reduceConversation(conversation, decodeLifecycleEvent(JSON.parse(row.body)));
328
+ }
329
+ const checkpoint = { version: target, format: CONVERSATION_CHECKPOINT_FORMAT, conversation };
330
+ if (jsonBytes(checkpoint) > HISTORY_MAX_BYTES)
331
+ throw new Error("Checkpoint exceeds byte limit; use paged history");
332
+ this.db.atomic(() =>
333
+ this.db.run(
334
+ "INSERT INTO checkpoints(source_id,session_id,format,seq,body) VALUES (?,?,?,?,?) ON CONFLICT(source_id,session_id,format) DO UPDATE SET seq=excluded.seq,body=excluded.body WHERE excluded.seq>=checkpoints.seq",
335
+ ref.sourceId,
336
+ ref.sessionId,
337
+ CONVERSATION_CHECKPOINT_FORMAT,
338
+ target.seq,
339
+ canonical(checkpoint),
340
+ ),
341
+ );
342
+ return checkpoint;
343
+ }
344
+ }
@@ -0,0 +1,226 @@
1
+ import {
2
+ CONVERSATION_CHECKPOINT_FORMAT,
3
+ type ConversationState,
4
+ ConversationStateSchema,
5
+ HISTORY_MAX_BYTES,
6
+ type HistoryApi,
7
+ type HistoryArchive,
8
+ HistoryCheckpointSchema,
9
+ HistoryError,
10
+ type HistoryReader,
11
+ type HistorySlice,
12
+ type HistoryVersion,
13
+ type SessionRef,
14
+ decodeLifecycleEvent,
15
+ emptyConversation,
16
+ jsonBytes,
17
+ reduceConversation,
18
+ sameHistory,
19
+ sameVersion,
20
+ } from "../protocol/index.ts";
21
+ import { historyPath, readHistoryPage } from "./history-reader.ts";
22
+ import { RetryBudget, type RetryPolicy, idleAfter, pause } from "./retry.ts";
23
+
24
+ export interface HistoryTransferOptions {
25
+ signal?: AbortSignal;
26
+ pageSize?: number;
27
+ pageBytes?: number;
28
+ /** Imported page JSON budget (including ancestors). A candidate page may already be fetched. */
29
+ maxBytes?: number;
30
+ maxPages?: number;
31
+ /** Each imported page, with its JSON bytes. */
32
+ onPage?: (page: HistorySlice, bytes: number) => void;
33
+ }
34
+ /** A complete transfer leaves the destination holding the source's head. One
35
+ * stopped by `maxPages`/`maxBytes` reports the leaf version it reached, if any. */
36
+ export type HistoryTransfer = { pages: number; bytes: number; records: number } & (
37
+ | { complete: true; version: HistoryVersion }
38
+ | { complete: false; version: HistoryVersion | undefined }
39
+ );
40
+ function checkBudget(name: string, value: number | undefined) {
41
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0))
42
+ throw new Error(`${name} must be a nonnegative safe integer`);
43
+ }
44
+ const missing = (error: unknown) => error instanceof HistoryError && error.reason === "missing";
45
+ /** Pull from source into a durable destination, or push by passing a remote
46
+ * destination. The destination's committed prefix is authoritative after lost ACKs.
47
+ * Ancestors are copied only through the fork's pinned version. A destination
48
+ * already beyond the source is complete: it holds everything the source has
49
+ * (a source restored from an older copy conflicts when it next appends). */
50
+ export function transferHistory(
51
+ source: HistoryReader,
52
+ destination: HistoryArchive,
53
+ ref: SessionRef,
54
+ options?: HistoryTransferOptions & { maxPages?: undefined; maxBytes?: undefined },
55
+ ): Promise<Extract<HistoryTransfer, { complete: true }>>;
56
+ export function transferHistory(
57
+ source: HistoryReader,
58
+ destination: HistoryArchive,
59
+ ref: SessionRef,
60
+ options?: HistoryTransferOptions,
61
+ ): Promise<HistoryTransfer>;
62
+ export async function transferHistory(
63
+ source: HistoryReader,
64
+ destination: HistoryArchive,
65
+ ref: SessionRef,
66
+ options: HistoryTransferOptions = {},
67
+ ): Promise<HistoryTransfer> {
68
+ checkBudget("maxPages", options.maxPages);
69
+ checkBudget("maxBytes", options.maxBytes);
70
+ const stats = { pages: 0, bytes: 0, records: 0 };
71
+ let version: HistoryVersion | undefined;
72
+ for (const target of await historyPath(source, ref, options.signal)) {
73
+ const leaf = sameHistory(target, ref);
74
+ let after: HistoryVersion | undefined;
75
+ try {
76
+ after = (await destination.head(target)).version;
77
+ } catch (error) {
78
+ if (!missing(error)) throw error;
79
+ }
80
+ if (leaf) version = after;
81
+ // A destination may already hold later parent history; verify the pinned cut.
82
+ if (after && after.seq >= target.seq) {
83
+ await source.read({ ...target, after: target, through: target });
84
+ await destination.read({ ...target, after: target, through: target });
85
+ if (leaf) version = target;
86
+ continue;
87
+ }
88
+ for (;;) {
89
+ options.signal?.throwIfAborted();
90
+ if (stats.pages >= (options.maxPages ?? Number.POSITIVE_INFINITY))
91
+ return { version, complete: false, ...stats };
92
+ const page = await readHistoryPage(source, {
93
+ ...target,
94
+ after,
95
+ through: target,
96
+ limit: options.pageSize,
97
+ maxBytes: options.pageBytes,
98
+ });
99
+ const bytes = jsonBytes(page);
100
+ if (stats.bytes + bytes > (options.maxBytes ?? Number.POSITIVE_INFINITY))
101
+ return { version, complete: false, ...stats };
102
+ options.signal?.throwIfAborted();
103
+ const receipt = await destination.import(page);
104
+ if (!sameVersion(receipt, page.next)) throw new Error("History receipt mismatch");
105
+ stats.pages++;
106
+ stats.bytes += bytes;
107
+ stats.records += page.records.length;
108
+ after = page.next;
109
+ if (leaf) version = after;
110
+ options.onPage?.(page, bytes);
111
+ if (!page.hasMore) break;
112
+ }
113
+ }
114
+ // The leaf comes last on the path, and every way through it sets its version.
115
+ if (!version) throw new Error("History transfer ended before its leaf");
116
+ return { version, complete: true, ...stats };
117
+ }
118
+
119
+ export interface FollowHistoryOptions {
120
+ after?: HistoryVersion;
121
+ signal?: AbortSignal;
122
+ pageSize?: number;
123
+ pageBytes?: number;
124
+ waitMs?: number;
125
+ retry?: RetryPolicy;
126
+ /** Changes between following and reconnecting; every retry reports its error. */
127
+ onState?: (state: "following" | "reconnecting", error?: unknown) => void;
128
+ }
129
+ /** Snapshot pages, then live suffixes. A wakeup is only a hint: the next pull
130
+ * starts at the last yielded version, covering changes between read and wait.
131
+ * Sequential consumption provides backpressure without an unbounded event queue. */
132
+ export async function* followHistory(
133
+ source: Pick<HistoryApi, "read" | "wait">,
134
+ ref: SessionRef,
135
+ options: FollowHistoryOptions = {},
136
+ ): AsyncGenerator<HistorySlice> {
137
+ let after = options.after;
138
+ if (after && !sameHistory(after, ref))
139
+ throw new Error("Follow cursor belongs to another history");
140
+ const budget = new RetryBudget(options.retry);
141
+ let following = false;
142
+ const retry = async (error: unknown) => {
143
+ const ms = budget.fail(error);
144
+ following = false;
145
+ options.onState?.("reconnecting", error);
146
+ await pause(ms, options.signal);
147
+ };
148
+ while (!options.signal?.aborted) {
149
+ let page: HistorySlice;
150
+ try {
151
+ page = await readHistoryPage(source, {
152
+ ...ref,
153
+ after,
154
+ limit: options.pageSize,
155
+ maxBytes: options.pageBytes,
156
+ });
157
+ if (options.signal?.aborted) return;
158
+ // A successful empty read does not repair a persistently failing wait RPC.
159
+ if (page.records.length) budget.progressed();
160
+ if (!following) options.onState?.("following");
161
+ following = true;
162
+ } catch (error) {
163
+ if (options.signal?.aborted) return;
164
+ await retry(error);
165
+ continue;
166
+ }
167
+ const initial = !after;
168
+ after = page.next;
169
+ if (initial || page.records.length) yield page;
170
+ if (page.hasMore) continue;
171
+ try {
172
+ const waited = Date.now();
173
+ const head = await source.wait({ after, timeoutMs: options.waitMs }, options.signal);
174
+ budget.progressed();
175
+ if (sameVersion(head.version, after)) await idleAfter(waited, options.signal);
176
+ } catch (error) {
177
+ if (options.signal?.aborted) return;
178
+ await retry(error);
179
+ }
180
+ }
181
+ }
182
+
183
+ /** Ancestors remain separate, namespaced segments so provider-local turn/message
184
+ * IDs cannot collide. Render segments in order; only the leaf is followed live. */
185
+ export async function openHistory(
186
+ source: HistoryReader,
187
+ ref: SessionRef,
188
+ options: { signal?: AbortSignal; maxRecords?: number; checkpoints?: boolean } = {},
189
+ ) {
190
+ checkBudget("maxRecords", options.maxRecords);
191
+ const segments: { version: HistoryVersion; conversation: ConversationState }[] = [];
192
+ let records = 0;
193
+ for (const target of await historyPath(source, ref, options.signal)) {
194
+ let after: HistoryVersion | undefined;
195
+ let conversation = emptyConversation();
196
+ if (options.checkpoints !== false && source.checkpoint) {
197
+ const value = await source.checkpoint({ through: target });
198
+ if (value) {
199
+ const checkpoint = HistoryCheckpointSchema.parse(value);
200
+ if (jsonBytes(checkpoint) > HISTORY_MAX_BYTES)
201
+ throw new Error("Checkpoint exceeds byte limit");
202
+ if (!sameHistory(checkpoint.version, target) || checkpoint.version.seq > target.seq)
203
+ throw new Error("Checkpoint is outside the requested history");
204
+ if (checkpoint.format === CONVERSATION_CHECKPOINT_FORMAT) {
205
+ // Bind the cached state to an available prefix before applying its tail.
206
+ await source.read({ ...target, after: checkpoint.version, through: checkpoint.version });
207
+ conversation = ConversationStateSchema.parse(checkpoint.conversation);
208
+ after = checkpoint.version;
209
+ }
210
+ }
211
+ }
212
+ for (;;) {
213
+ options.signal?.throwIfAborted();
214
+ const page = await readHistoryPage(source, { ...target, after, through: target });
215
+ records += page.records.length;
216
+ if (records > (options.maxRecords ?? 100_000))
217
+ throw new Error("History projection limit exceeded; use paged reads");
218
+ for (const record of page.records)
219
+ conversation = reduceConversation(conversation, decodeLifecycleEvent(record.event));
220
+ after = page.next;
221
+ if (!page.hasMore) break;
222
+ }
223
+ segments.push({ version: after, conversation });
224
+ }
225
+ return { segments, version: segments.at(-1)!.version };
226
+ }
@@ -0,0 +1,6 @@
1
+ // Storage/transport-neutral host contracts. SQLite is an optional subpath.
2
+ export * from "./journal.ts";
3
+ export * from "./recovery.ts";
4
+ export * from "./fit.ts";
5
+ export * from "./history.ts";
6
+ export * from "./worker.ts";