@zvada/agent-server 0.3.17 → 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 (44) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +30 -2
  3. package/docs/consuming.md +9 -2
  4. package/docs/harnesses.md +11 -3
  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/index.ts +2 -0
  14. package/src/core/provision/pins.ts +2 -1
  15. package/src/core/runtime/agent-runtime.ts +53 -23
  16. package/src/core/runtime/event-processor.ts +10 -5
  17. package/src/core/runtime/event-sink.ts +45 -2
  18. package/src/core/runtime/model-lists.ts +24 -9
  19. package/src/protocol/history.ts +267 -0
  20. package/src/protocol/ids.ts +4 -5
  21. package/src/protocol/index.ts +1 -0
  22. package/src/protocol/wire.ts +82 -1
  23. package/src/server/agent-server.ts +167 -94
  24. package/src/server/bin.ts +22 -1
  25. package/src/server/history.ts +166 -0
  26. package/src/server/index.ts +1 -0
  27. package/src/server/session-store.ts +225 -0
  28. package/src/server/wire-error.ts +52 -0
  29. package/src/sync/event-log.ts +132 -0
  30. package/src/sync/fit.ts +124 -0
  31. package/src/sync/history-reader.ts +52 -0
  32. package/src/sync/history-sqlite.ts +344 -0
  33. package/src/sync/history.ts +226 -0
  34. package/src/sync/index.ts +6 -0
  35. package/src/sync/journal-sqlite.ts +353 -0
  36. package/src/sync/journal.ts +73 -0
  37. package/src/sync/node-sqlite.ts +20 -0
  38. package/src/sync/recovery.ts +112 -0
  39. package/src/sync/retry.ts +49 -0
  40. package/src/sync/schema.ts +56 -0
  41. package/src/sync/sql.ts +106 -0
  42. package/src/sync/sqlite-file.ts +38 -0
  43. package/src/sync/sqlite.ts +21 -0
  44. package/src/sync/worker.ts +259 -0
@@ -0,0 +1,166 @@
1
+ import {
2
+ HISTORY_METHODS,
3
+ HistoryCheckpointRequestSchema,
4
+ HistoryCommitSchema,
5
+ HistoryError,
6
+ HistoryForkSchema,
7
+ type HistoryHead,
8
+ HistoryListSchema,
9
+ HistoryPullSchema,
10
+ HistorySliceSchema,
11
+ type HistoryStore,
12
+ HistoryWaitSchema,
13
+ type JsonRpcId,
14
+ type SessionRef,
15
+ SessionRefSchema,
16
+ type WireTransport,
17
+ encodeResponse,
18
+ } from "../protocol/index.ts";
19
+ import { parseParams } from "./wire-error.ts";
20
+
21
+ export interface HistoryHost {
22
+ store: HistoryStore;
23
+ /** Undefined ref means catalog permission. Use tenant-scoped stores/catalogs.
24
+ * This protects history methods only; the host must restrict execution methods. */
25
+ authorize(
26
+ transport: WireTransport,
27
+ ref: SessionRef | undefined,
28
+ operation: "read" | "write" | "list",
29
+ ): boolean | Promise<boolean>;
30
+ }
31
+
32
+ /**
33
+ * Long-polls one connection may hold open. One more answers the oldest early:
34
+ * a wait is only a wakeup (its caller pulls next), so waits a caller abandoned
35
+ * cannot lock the connection out.
36
+ */
37
+ const MAX_WAITS = 8;
38
+ const waiting = new WeakMap<WireTransport, AbortController[]>();
39
+ const superseded = new Error("Superseded by a newer wait");
40
+
41
+ type Route = (host: HistoryHost, transport: WireTransport, params: unknown) => Promise<unknown>;
42
+
43
+ async function permit(
44
+ host: HistoryHost,
45
+ transport: WireTransport,
46
+ ref: SessionRef | undefined,
47
+ operation: "read" | "write" | "list",
48
+ ): Promise<void> {
49
+ if (!(await host.authorize(transport, ref, operation)))
50
+ throw new HistoryError("unauthorized", "History not authorized");
51
+ }
52
+
53
+ /** One route per method: a method added to HISTORY_METHODS does not compile without one. */
54
+ const ROUTES: Record<(typeof HISTORY_METHODS)[keyof typeof HISTORY_METHODS], Route> = {
55
+ [HISTORY_METHODS.list]: async (host, transport, params) => {
56
+ await permit(host, transport, undefined, "list");
57
+ const { after, limit } = parseParams(HistoryListSchema, params ?? {});
58
+ // The cursor names only an entry this caller may read, so it scans past hidden
59
+ // ones. It belongs to a catalog, not a snapshot: entries may appear between pages.
60
+ const entries: HistoryHead[] = [];
61
+ let cursor = after;
62
+ for (;;) {
63
+ const page = await host.store.list({ after: cursor, limit });
64
+ let scanned = 0;
65
+ for (const item of page.entries) {
66
+ if (entries.length === limit) break;
67
+ scanned++;
68
+ if (await host.authorize(transport, item.descriptor, "read")) entries.push(item);
69
+ }
70
+ if (!page.next || entries.length === limit) {
71
+ // More remain past this store page, or in it when the limit filled first.
72
+ const more = Boolean(page.next) || scanned < page.entries.length;
73
+ const last = entries.at(-1)?.version;
74
+ return {
75
+ entries,
76
+ next:
77
+ more && last
78
+ ? {
79
+ storeId: page.next?.storeId ?? host.store.sourceId,
80
+ ref: { sourceId: last.sourceId, sessionId: last.sessionId },
81
+ }
82
+ : null,
83
+ };
84
+ }
85
+ cursor = page.next;
86
+ }
87
+ },
88
+ [HISTORY_METHODS.head]: async (host, transport, params) => {
89
+ const ref = parseParams(SessionRefSchema, params);
90
+ await permit(host, transport, ref, "read");
91
+ return host.store.head(ref);
92
+ },
93
+ [HISTORY_METHODS.read]: async (host, transport, params) => {
94
+ const request = parseParams(HistoryPullSchema, params);
95
+ await permit(host, transport, request, "read");
96
+ return host.store.read(request);
97
+ },
98
+ [HISTORY_METHODS.checkpoint]: async (host, transport, params) => {
99
+ const request = parseParams(HistoryCheckpointRequestSchema, params);
100
+ await permit(host, transport, request.through, "read");
101
+ return host.store.checkpoint(request);
102
+ },
103
+ [HISTORY_METHODS.import]: async (host, transport, params) => {
104
+ // The store validates what it imports; authorization needs only the shape.
105
+ const page = parseParams(HistorySliceSchema, params);
106
+ await permit(host, transport, page.descriptor, "write");
107
+ if (page.descriptor.parent) await permit(host, transport, page.descriptor.parent, "read");
108
+ return host.store.import(page);
109
+ },
110
+ [HISTORY_METHODS.fork]: async (host, transport, params) => {
111
+ const request = parseParams(HistoryForkSchema, params);
112
+ await permit(
113
+ host,
114
+ transport,
115
+ { sourceId: host.store.sourceId, sessionId: request.sessionId },
116
+ "write",
117
+ );
118
+ if (request.from) await permit(host, transport, request.from, "read");
119
+ return host.store.fork(request);
120
+ },
121
+ [HISTORY_METHODS.commit]: async (host, transport, params) => {
122
+ const request = parseParams(HistoryCommitSchema, params);
123
+ await permit(host, transport, request.expected, "write");
124
+ return host.store.commit(request);
125
+ },
126
+ [HISTORY_METHODS.wait]: async (host, transport, params) => {
127
+ const request = parseParams(HistoryWaitSchema, params);
128
+ await permit(host, transport, request.after, "read");
129
+ const waits = waiting.get(transport) ?? [];
130
+ waiting.set(transport, waits);
131
+ const stop = new AbortController();
132
+ waits.push(stop);
133
+ if (waits.length > MAX_WAITS) waits.shift()?.abort(superseded);
134
+ const off = transport.onClose(() => stop.abort(new Error("Transport closed")));
135
+ let head: unknown;
136
+ try {
137
+ head = await host.store.wait(request, stop.signal);
138
+ } catch (error) {
139
+ if (stop.signal.reason !== superseded) throw error;
140
+ head = await host.store.head(request.after);
141
+ } finally {
142
+ off();
143
+ const index = waits.indexOf(stop);
144
+ if (index >= 0) waits.splice(index, 1);
145
+ }
146
+ // Membership may have changed while waiting: never answer on stale authorization.
147
+ await permit(host, transport, request.after, "read");
148
+ return head;
149
+ },
150
+ };
151
+ const routes = new Map<string, Route>(Object.entries(ROUTES));
152
+
153
+ /** Answers a `history/*` request; false for any other method. Every mutation is
154
+ * one storage transaction, and no agent is ever invoked from here. */
155
+ export async function handleHistoryRequest(
156
+ host: HistoryHost,
157
+ transport: WireTransport,
158
+ id: JsonRpcId,
159
+ method: string,
160
+ params: unknown,
161
+ ): Promise<boolean> {
162
+ const route = routes.get(method);
163
+ if (!route) return false;
164
+ transport.send(encodeResponse(id, await route(host, transport, params)));
165
+ return true;
166
+ }
@@ -3,6 +3,7 @@
3
3
  // events, bounded replay, engine-brokered permissions.
4
4
 
5
5
  export { AgentServer, type AgentServerOptions } from "./agent-server.ts";
6
+ export type { HistoryHost } from "./history.ts";
6
7
  export {
7
8
  type InstallOptions,
8
9
  type InstallResult,
@@ -0,0 +1,225 @@
1
+ import { EventSinkError } from "../core/index.ts";
2
+ import {
3
+ type AgentHarness,
4
+ type DurableSession,
5
+ type EventsReplayResult,
6
+ type LifecycleEvent,
7
+ type RunRequest,
8
+ type TurnEndedEvent,
9
+ type TurnReceipt,
10
+ WIRE_ERROR_CODES,
11
+ type WireEventEnvelope,
12
+ } from "../protocol/index.ts";
13
+ import { JournalError, type SessionJournal } from "../sync/journal.ts";
14
+ import { DEFAULT_BUFFER_SIZE, SessionLog } from "./session-log.ts";
15
+ import { WireError } from "./wire-error.ts";
16
+
17
+ /**
18
+ * Where the server keeps its session logs: the seam between execution and
19
+ * persistence. AgentServer picks one at construction; nothing else in its
20
+ * request path knows whether sessions outlive the process.
21
+ */
22
+ export interface SessionStore {
23
+ /** Set when the logs outlive the process: their identity (`initialize.historyId`). */
24
+ readonly historyId?: string;
25
+ /** The harness a session is bound to (its first turn's). */
26
+ harnessOf(sessionId: string): AgentHarness | undefined;
27
+ /** A retried turn this store already admitted. Refuses a turnId reused with other input. */
28
+ duplicateOf(request: RunRequest): { terminal?: TurnEndedEvent } | undefined;
29
+ /** Admit a new turn, before its quick-ack, or refuse it. */
30
+ open(request: RunRequest): void;
31
+ /**
32
+ * Sequence one of the session's events. A durable store commits it first;
33
+ * when it cannot, it throws EventSinkError and stays failed. `session.ended`
34
+ * retires the session.
35
+ */
36
+ append(sessionId: string, event: LifecycleEvent): WireEventEnvelope;
37
+ /** Events from `fromSeq`; undefined for a session without a log (unknown or closed). */
38
+ replay(sessionId: string, fromSeq: number): EventsReplayResult | undefined;
39
+ /** The harness to release before `session.ended`; undefined when there is
40
+ * nothing to close. Refuses a session that may not close yet. */
41
+ closing(sessionId: string): AgentHarness | undefined;
42
+ /** Durable stores only. */
43
+ receipt?(sessionId: string, turnId: string): TurnReceipt | undefined;
44
+ session?(sessionId: string): DurableSession | undefined;
45
+ confirmStopped?(sessionId: string, expectedHeadSeq: number): boolean;
46
+ /** Give up execution ownership when the server shuts down. */
47
+ release(): void;
48
+ }
49
+
50
+ /** A bounded replay ring per session, gone with the process. */
51
+ export class MemorySessionStore implements SessionStore {
52
+ private readonly sessions = new Map<string, SessionLog>();
53
+ /** Last assigned seq of closed sessions, so a reused id continues
54
+ * monotonically. Memory: one number per closed-and-never-reused session id —
55
+ * unbounded only across a server lifetime with unbounded distinct ids, the
56
+ * same order of growth already accepted for `sessions`. */
57
+ private readonly retiredSeqs = new Map<string, number>();
58
+
59
+ constructor(private readonly bufferSize = DEFAULT_BUFFER_SIZE) {}
60
+
61
+ harnessOf(sessionId: string): AgentHarness | undefined {
62
+ return this.sessions.get(sessionId)?.harness;
63
+ }
64
+ /** The runtime's own admission converges retries of volatile turns. */
65
+ duplicateOf(): undefined {
66
+ return undefined;
67
+ }
68
+ open({ sessionId, config }: RunRequest): void {
69
+ if (this.sessions.has(sessionId)) return;
70
+ const startSeq = (this.retiredSeqs.get(sessionId) ?? 0) + 1;
71
+ this.sessions.set(
72
+ sessionId,
73
+ new SessionLog(sessionId, config.harness, this.bufferSize, startSeq),
74
+ );
75
+ this.retiredSeqs.delete(sessionId);
76
+ }
77
+ append(sessionId: string, event: LifecycleEvent): WireEventEnvelope {
78
+ const log = this.sessions.get(sessionId);
79
+ if (!log) throw new Error(`session ${sessionId} has no log`);
80
+ const envelope = log.append(event);
81
+ // `session.ended` is deliberately NOT replayable: a subscriber detached
82
+ // during the close gets `unknownSession` from `events/replay`, and that
83
+ // answer IS its terminal signal (nothing more will ever be appended).
84
+ if (event.type === "session.ended") {
85
+ if (log.latestSeq !== null) this.retiredSeqs.set(sessionId, log.latestSeq);
86
+ this.sessions.delete(sessionId);
87
+ }
88
+ return envelope;
89
+ }
90
+ replay(sessionId: string, fromSeq: number): EventsReplayResult | undefined {
91
+ const log = this.sessions.get(sessionId);
92
+ if (!log) return undefined;
93
+ return {
94
+ events: log.replay(fromSeq),
95
+ firstAvailableSeq: log.firstAvailableSeq,
96
+ latestSeq: log.latestSeq,
97
+ };
98
+ }
99
+ closing(sessionId: string): AgentHarness | undefined {
100
+ return this.harnessOf(sessionId);
101
+ }
102
+ release(): void {}
103
+ }
104
+
105
+ /** The wire code of each journal refusal. */
106
+ const REFUSAL_CODES: Record<JournalError["code"], number> = {
107
+ turnConflict: WIRE_ERROR_CODES.turnConflict,
108
+ turnActive: WIRE_ERROR_CODES.turnActive,
109
+ sessionClosed: WIRE_ERROR_CODES.sessionClosed,
110
+ recoveryRequired: WIRE_ERROR_CODES.recoveryRequired,
111
+ resumeRequired: WIRE_ERROR_CODES.resumeRequired,
112
+ unknownSession: WIRE_ERROR_CODES.unknownSession,
113
+ staleHead: WIRE_ERROR_CODES.historyConflict,
114
+ invalidRecord: WIRE_ERROR_CODES.invalidParams,
115
+ recordTooLarge: WIRE_ERROR_CODES.invalidParams,
116
+ };
117
+ /** A journal refusal answers the request; any other error is a storage fault. */
118
+ const refusal = (error: unknown) =>
119
+ error instanceof JournalError
120
+ ? new WireError(REFUSAL_CODES[error.code], error.message, error.data)
121
+ : undefined;
122
+
123
+ /**
124
+ * Every admission and event committed to a journal before it is acknowledged
125
+ * or delivered, so sessions survive restarts. A journal that fails to write
126
+ * fails this store for good, and `onFault` stops the server: restart recovery,
127
+ * not this process, decides what the cut-off turns did.
128
+ */
129
+ export class JournalSessionStore implements SessionStore {
130
+ readonly historyId: string;
131
+ private fault: { error: unknown } | undefined;
132
+ private readonly releaseClaim: () => void;
133
+ /** After shutdown, a turn that ignored its abort must not write behind a new owner. */
134
+ private released = false;
135
+
136
+ constructor(
137
+ private readonly journal: SessionJournal,
138
+ private readonly onFault: (error: unknown) => void,
139
+ ) {
140
+ this.historyId = journal.sourceId;
141
+ this.releaseClaim = journal.claim();
142
+ }
143
+
144
+ harnessOf(sessionId: string): AgentHarness | undefined {
145
+ const session = this.journal.session(sessionId);
146
+ return session && !session.closed ? session.harness : undefined;
147
+ }
148
+ duplicateOf(request: RunRequest): { terminal?: TurnEndedEvent } | undefined {
149
+ try {
150
+ if (this.journal.admission(request) === "new") return undefined;
151
+ } catch (error) {
152
+ throw refusal(error) ?? error;
153
+ }
154
+ return { terminal: this.journal.turn(request.sessionId, request.turnId)?.terminal };
155
+ }
156
+ open(request: RunRequest): void {
157
+ this.write(() => this.journal.admit(request));
158
+ }
159
+ append(sessionId: string, event: LifecycleEvent): WireEventEnvelope {
160
+ if (this.released) throw new EventSinkError(new Error("Journal ownership was released"));
161
+ if (this.fault) throw new EventSinkError(this.fault.error);
162
+ try {
163
+ // Only a pre-session `error` may lack its session; this one has one.
164
+ return this.journal.append(event.sessionId === undefined ? { ...event, sessionId } : event);
165
+ } catch (error) {
166
+ this.failed(error);
167
+ throw new EventSinkError(error);
168
+ }
169
+ }
170
+ replay(sessionId: string, fromSeq: number): EventsReplayResult | undefined {
171
+ const session = this.journal.session(sessionId);
172
+ if (!session || session.closed) return undefined;
173
+ const page = this.journal.replay(sessionId, fromSeq);
174
+ return {
175
+ events: page.events,
176
+ firstAvailableSeq: session.headSeq ? 1 : null,
177
+ latestSeq: session.headSeq || null,
178
+ hasMore: page.hasMore,
179
+ };
180
+ }
181
+ closing(sessionId: string): AgentHarness | undefined {
182
+ const session = this.journal.session(sessionId);
183
+ if (!session || session.closed) return undefined;
184
+ if (session.recoveryRequired)
185
+ throw new WireError(
186
+ WIRE_ERROR_CODES.recoveryRequired,
187
+ "Confirm the native process stopped before closing",
188
+ { headSeq: session.headSeq },
189
+ );
190
+ return session.harness;
191
+ }
192
+ receipt(sessionId: string, turnId: string): TurnReceipt | undefined {
193
+ return this.journal.turn(sessionId, turnId);
194
+ }
195
+ session(sessionId: string): DurableSession | undefined {
196
+ return this.journal.session(sessionId);
197
+ }
198
+ confirmStopped(sessionId: string, expectedHeadSeq: number): boolean {
199
+ return this.write(() => this.journal.confirmStopped(sessionId, expectedHeadSeq));
200
+ }
201
+ release(): void {
202
+ if (this.released) return;
203
+ this.released = true;
204
+ this.releaseClaim();
205
+ }
206
+
207
+ /** A write that fails, rather than refuses, fails the store. */
208
+ private write<T>(operation: () => T): T {
209
+ if (this.released) throw new Error("Journal ownership was released");
210
+ if (this.fault) throw new Error("Journal failed; restart and recover before executing");
211
+ try {
212
+ return operation();
213
+ } catch (error) {
214
+ const refused = refusal(error);
215
+ if (refused) throw refused;
216
+ this.failed(error);
217
+ throw error;
218
+ }
219
+ }
220
+ private failed(error: unknown): void {
221
+ if (this.fault) return;
222
+ this.fault = { error };
223
+ this.onFault(error);
224
+ }
225
+ }
@@ -0,0 +1,52 @@
1
+ import { HISTORY_ERROR_CODES, HistoryError, WIRE_ERROR_CODES } from "../protocol/index.ts";
2
+
3
+ /** A refusal: the request's error response, as opposed to a server fault. */
4
+ export class WireError extends Error {
5
+ override readonly name = "WireError";
6
+ constructor(
7
+ readonly code: number,
8
+ message: string,
9
+ readonly data?: unknown,
10
+ ) {
11
+ super(message);
12
+ }
13
+ }
14
+
15
+ /** Structural slice of a ZodError — keeps zod out of this package's deps. */
16
+ export interface ValidationError {
17
+ issues: ReadonlyArray<{ path: ReadonlyArray<PropertyKey>; message: string }>;
18
+ }
19
+
20
+ export function invalidParams(error: ValidationError): WireError {
21
+ return new WireError(
22
+ WIRE_ERROR_CODES.invalidParams,
23
+ "invalid params",
24
+ error.issues.map((i) => ({ path: i.path.join("."), message: i.message })),
25
+ );
26
+ }
27
+
28
+ /** Parse a request's params, or refuse them as `invalidParams`. */
29
+ export function parseParams<T>(
30
+ schema: {
31
+ safeParse(
32
+ value: unknown,
33
+ ): { success: true; data: T } | { success: false; error: ValidationError };
34
+ },
35
+ params: unknown,
36
+ ): T {
37
+ const parsed = schema.safeParse(params);
38
+ if (!parsed.success) throw invalidParams(parsed.error);
39
+ return parsed.data;
40
+ }
41
+
42
+ /** The error response for anything a handler threw: refusals keep their code,
43
+ * everything else is an `internalError`. */
44
+ export function wireErrorOf(error: unknown): WireError {
45
+ if (error instanceof WireError) return error;
46
+ if (error instanceof HistoryError)
47
+ return new WireError(HISTORY_ERROR_CODES[error.reason], error.message);
48
+ return new WireError(
49
+ WIRE_ERROR_CODES.internalError,
50
+ error instanceof Error ? error.message : String(error),
51
+ );
52
+ }
@@ -0,0 +1,132 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ type HistoryDescriptor,
4
+ type HistoryHead,
5
+ type HistoryVersion,
6
+ type SessionRef,
7
+ canonicalHistoryJson,
8
+ historyRecordPreimage,
9
+ historyRootPreimage,
10
+ } from "../protocol/index.ts";
11
+ import type { Db } from "./sql.ts";
12
+
13
+ const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");
14
+ type HeadRow = {
15
+ source_id: string;
16
+ session_id: string;
17
+ descriptor: string;
18
+ head_seq: number;
19
+ head_hash: string;
20
+ };
21
+ export type EventRow = { seq: number; hash: string; body: string };
22
+
23
+ const toHead = (row: HeadRow): HistoryHead => ({
24
+ // Written by this store from a validated descriptor.
25
+ descriptor: JSON.parse(row.descriptor) as HistoryDescriptor,
26
+ version: {
27
+ sourceId: row.source_id,
28
+ sessionId: row.session_id,
29
+ seq: row.head_seq,
30
+ hash: row.head_hash,
31
+ },
32
+ });
33
+
34
+ /**
35
+ * Every history a store holds: its descriptor, its head, and its hash-chained
36
+ * records. The only code that touches the `histories` and `events` tables.
37
+ * Writes run inside the caller's transaction.
38
+ */
39
+ export class EventLog {
40
+ constructor(private readonly db: Db) {}
41
+
42
+ head(ref: SessionRef): HistoryHead | undefined {
43
+ const row = this.db.one<HeadRow>(
44
+ "SELECT * FROM histories WHERE source_id=? AND session_id=?",
45
+ ref.sourceId,
46
+ ref.sessionId,
47
+ );
48
+ return row && toHead(row);
49
+ }
50
+ /** Heads in (sourceId, sessionId) order, after `after` when given. */
51
+ heads(after: SessionRef | undefined, limit: number): HistoryHead[] {
52
+ const rows = after
53
+ ? this.db.all<HeadRow>(
54
+ "SELECT * FROM histories WHERE source_id>? OR (source_id=? AND session_id>?) ORDER BY source_id,session_id LIMIT ?",
55
+ after.sourceId,
56
+ after.sourceId,
57
+ after.sessionId,
58
+ limit,
59
+ )
60
+ : this.db.all<HeadRow>(
61
+ "SELECT * FROM histories ORDER BY source_id,session_id LIMIT ?",
62
+ limit,
63
+ );
64
+ return rows.map(toHead);
65
+ }
66
+ /** A new, empty history. */
67
+ create(descriptor: HistoryDescriptor): HistoryVersion {
68
+ const root = this.root(descriptor);
69
+ this.db.run(
70
+ "INSERT INTO histories(source_id,session_id,descriptor,head_seq,head_hash) VALUES (?,?,?,0,?)",
71
+ descriptor.sourceId,
72
+ descriptor.sessionId,
73
+ canonicalHistoryJson(descriptor),
74
+ root.hash,
75
+ );
76
+ return root;
77
+ }
78
+ /** A history's version 0. */
79
+ root(descriptor: HistoryDescriptor): HistoryVersion {
80
+ const { sourceId, sessionId } = descriptor;
81
+ return { sourceId, sessionId, seq: 0, hash: sha256(historyRootPreimage(descriptor)) };
82
+ }
83
+ /** Records `bodies` (canonical event JSON) after `head`, the current head; returns the new one. */
84
+ append(head: HistoryVersion, bodies: readonly string[]): HistoryVersion {
85
+ let { seq, hash } = head;
86
+ for (const body of bodies) {
87
+ seq += 1;
88
+ hash = sha256(historyRecordPreimage(hash, seq, body));
89
+ this.db.run(
90
+ "INSERT INTO events(source_id,session_id,seq,hash,body) VALUES (?,?,?,?,?)",
91
+ head.sourceId,
92
+ head.sessionId,
93
+ seq,
94
+ hash,
95
+ body,
96
+ );
97
+ }
98
+ this.db.run(
99
+ "UPDATE histories SET head_seq=?, head_hash=? WHERE source_id=? AND session_id=?",
100
+ seq,
101
+ hash,
102
+ head.sourceId,
103
+ head.sessionId,
104
+ );
105
+ return { ...head, seq, hash };
106
+ }
107
+ /** The version at `seq`, when the history reaches it. */
108
+ at(ref: SessionRef, seq: number): HistoryVersion | undefined {
109
+ if (seq === 0) {
110
+ const head = this.head(ref);
111
+ return head && this.root(head.descriptor);
112
+ }
113
+ const row = this.db.one<{ hash: string }>(
114
+ "SELECT hash FROM events WHERE source_id=? AND session_id=? AND seq=?",
115
+ ref.sourceId,
116
+ ref.sessionId,
117
+ seq,
118
+ );
119
+ return row && { sourceId: ref.sourceId, sessionId: ref.sessionId, seq, hash: row.hash };
120
+ }
121
+ /** Records after `afterSeq` through `throughSeq`, oldest first. */
122
+ records(ref: SessionRef, afterSeq: number, throughSeq: number, limit = -1): Iterable<EventRow> {
123
+ return this.db.each<EventRow>(
124
+ "SELECT seq,hash,body FROM events WHERE source_id=? AND session_id=? AND seq>? AND seq<=? ORDER BY seq LIMIT ?",
125
+ ref.sourceId,
126
+ ref.sessionId,
127
+ afterSeq,
128
+ throughSeq,
129
+ limit,
130
+ );
131
+ }
132
+ }