@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,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
+ }
@@ -0,0 +1,124 @@
1
+ import {
2
+ HISTORY_MAX_BYTES,
3
+ HistoryError,
4
+ type LifecycleEvent,
5
+ canonicalHistoryJson,
6
+ jsonBytes,
7
+ validateHistoryRecords,
8
+ } from "../protocol/index.ts";
9
+
10
+ /** The largest event a journal stores: a read page must still fit around it. */
11
+ export const MAX_EVENT_BYTES = HISTORY_MAX_BYTES - 32 * 1024;
12
+ /** Room for a page cursor's digits and `hasMore` to change while records are added. */
13
+ export const PAGE_SLACK_BYTES = 128;
14
+
15
+ const encoder = new TextEncoder();
16
+ const decoder = new TextDecoder();
17
+
18
+ /**
19
+ * `event` cut down to `maxBytes`: its longest strings (usually a tool's output)
20
+ * are truncated with a visible marker until it fits. `undefined` when only
21
+ * short strings remain. An event that already fits is returned as is.
22
+ */
23
+ export function fitEvent<T>(event: T, maxBytes = MAX_EVENT_BYTES): T | undefined {
24
+ let size = jsonBytes(event);
25
+ if (size <= maxBytes) return event;
26
+ const copy = structuredClone(event);
27
+ for (let attempt = 0; attempt < 8 && size > maxBytes; attempt++) {
28
+ let longest: { holder: Record<string, unknown>; key: string; bytes: number } | undefined;
29
+ const visit = (value: unknown) => {
30
+ if (!value || typeof value !== "object") return;
31
+ for (const [key, child] of Object.entries(value)) {
32
+ if (typeof child !== "string") visit(child);
33
+ else {
34
+ const bytes = encoder.encode(child).byteLength;
35
+ if (!longest || bytes > longest.bytes)
36
+ longest = { holder: value as Record<string, unknown>, key, bytes };
37
+ }
38
+ }
39
+ };
40
+ visit(copy);
41
+ if (!longest || longest.bytes < 1024) return undefined;
42
+ const keep = Math.max(0, longest.bytes - (size - maxBytes) - 256);
43
+ const head = decoder
44
+ .decode(encoder.encode(longest.holder[longest.key] as string).slice(0, keep))
45
+ .replace(/�$/, "");
46
+ longest.holder[longest.key] =
47
+ `${head}\n[agent-server: ${longest.bytes - keep} bytes omitted to fit the journal]`;
48
+ size = jsonBytes(copy);
49
+ }
50
+ return size <= maxBytes ? copy : undefined;
51
+ }
52
+
53
+ /**
54
+ * What a journal stores in place of an event it cannot record, so the turn and
55
+ * every other session keep going. A turn or session end keeps its meaning;
56
+ * anything else becomes a recoverable error notice naming what was lost.
57
+ */
58
+ export function unrecordedEvent(event: LifecycleEvent, reason: string): LifecycleEvent {
59
+ const message = `agent-server could not record a ${event.type} event: ${reason.slice(0, 300)}`;
60
+ const timestamp = Date.now();
61
+ if (event.type === "turn.ended")
62
+ return {
63
+ type: "turn.ended",
64
+ sessionId: event.sessionId,
65
+ turnId: event.turnId,
66
+ stopReason: "error",
67
+ error: { category: "internal", message },
68
+ timestamp,
69
+ };
70
+ if (event.type === "session.ended")
71
+ return { type: "session.ended", sessionId: event.sessionId, reason: event.reason, timestamp };
72
+ const turnId = (event as { turnId?: unknown }).turnId;
73
+ return {
74
+ type: "error",
75
+ sessionId: event.sessionId,
76
+ ...(typeof turnId === "string" && { turnId }),
77
+ category: "internal",
78
+ message,
79
+ recoverable: true,
80
+ timestamp,
81
+ };
82
+ }
83
+
84
+ type SessionEvent = LifecycleEvent & { sessionId: string };
85
+ type Recordable = { event: SessionEvent; body: string };
86
+
87
+ /** An event's canonical body, when a journal can store it as it is. */
88
+ function storable(event: SessionEvent): Recordable | { tooLarge: boolean; reason: string } {
89
+ try {
90
+ validateHistoryRecords(event.sessionId, [{ seq: 1, event }]);
91
+ } catch (error) {
92
+ if (!(error instanceof HistoryError)) throw error;
93
+ return { tooLarge: false, reason: error.message };
94
+ }
95
+ const body = canonicalHistoryJson(event);
96
+ if (encoder.encode(body).byteLength > MAX_EVENT_BYTES)
97
+ return { tooLarge: true, reason: "Event exceeds durable record byte limit" };
98
+ return { event, body };
99
+ }
100
+
101
+ /**
102
+ * What a journal stores for `event`, with its canonical body: the event, a
103
+ * copy cut down to fit (`fitEvent`), or a notice in its place
104
+ * (`unrecordedEvent`). Decided before writing: one event a journal cannot
105
+ * store must not stop its turn or any other session.
106
+ */
107
+ export function recordable(event: SessionEvent): Recordable {
108
+ const checked = storable(event);
109
+ if ("body" in checked) return checked;
110
+ if (checked.tooLarge) {
111
+ const fitted = fitEvent(event);
112
+ const refitted = fitted && storable(fitted);
113
+ if (refitted && "body" in refitted) return refitted;
114
+ // A prompt replaced by a notice could never be answered: keep it, without its input.
115
+ if (event.type === "permission.requested" && event.toolCall) {
116
+ const { rawInput: _input, ...toolCall } = event.toolCall;
117
+ const bare = storable({ ...event, toolCall });
118
+ if ("body" in bare) return bare;
119
+ }
120
+ }
121
+ const notice = storable(unrecordedEvent(event, checked.reason) as SessionEvent);
122
+ if (!("body" in notice)) throw new Error(`Unstorable notice: ${notice.reason}`);
123
+ return notice;
124
+ }
@@ -0,0 +1,52 @@
1
+ import {
2
+ type HistoryPull,
3
+ type HistoryReader,
4
+ type HistorySlice,
5
+ type HistoryVersion,
6
+ type SessionRef,
7
+ sameHistory,
8
+ sameVersion,
9
+ validateHistorySlice,
10
+ } from "../protocol/index.ts";
11
+
12
+ /** Pin the leaf once and walk immutable parent cuts. Return ancestors before
13
+ * descendants so every reader/importer uses the same ordering and depth bound. */
14
+ export async function historyPath(
15
+ source: HistoryReader,
16
+ leaf: SessionRef,
17
+ signal?: AbortSignal,
18
+ ): Promise<HistoryVersion[]> {
19
+ const versions: HistoryVersion[] = [];
20
+ const seen = new Set<string>();
21
+ let ref: SessionRef | undefined = leaf;
22
+ let pinned: HistoryVersion | undefined;
23
+ while (ref) {
24
+ signal?.throwIfAborted();
25
+ const key = JSON.stringify([ref.sourceId, ref.sessionId]);
26
+ if (seen.has(key) || seen.size >= 64) throw new Error("History ancestry cycle or depth limit");
27
+ seen.add(key);
28
+ const head = await source.head(ref);
29
+ if (!sameHistory(head.descriptor, ref) || !sameHistory(head.version, ref))
30
+ throw new Error("History head identity mismatch");
31
+ versions.push(pinned ?? head.version);
32
+ pinned = head.descriptor.parent;
33
+ ref = pinned;
34
+ }
35
+ return versions.reverse();
36
+ }
37
+
38
+ /** A valid slice is not enough: bind it to the caller's identity and requested
39
+ * range before importing, yielding or reducing it. */
40
+ export async function readHistoryPage(
41
+ source: Pick<HistoryReader, "read">,
42
+ request: HistoryPull,
43
+ ): Promise<HistorySlice> {
44
+ const page = validateHistorySlice(await source.read(request));
45
+ if (
46
+ !sameHistory(page.descriptor, request) ||
47
+ (request.through && !sameVersion(page.head, request.through)) ||
48
+ (request.after ? !sameVersion(page.base, request.after) : page.base.seq !== 0)
49
+ )
50
+ throw new Error("History page does not match the requested prefix or revision");
51
+ return page;
52
+ }