@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.
- package/CHANGELOG.md +56 -0
- package/README.md +30 -2
- package/docs/consuming.md +9 -2
- package/docs/harnesses.md +11 -3
- package/docs/sync-experiment.md +190 -0
- package/docs/sync-history.md +181 -0
- package/docs/sync-integration.md +133 -0
- package/package.json +14 -2
- package/src/client/client.ts +138 -33
- package/src/client/history.ts +88 -0
- package/src/client/index.ts +1 -1
- package/src/client/request.ts +19 -0
- package/src/core/index.ts +2 -0
- package/src/core/provision/pins.ts +2 -1
- package/src/core/runtime/agent-runtime.ts +53 -23
- package/src/core/runtime/event-processor.ts +10 -5
- package/src/core/runtime/event-sink.ts +45 -2
- package/src/core/runtime/model-lists.ts +24 -9
- package/src/protocol/history.ts +267 -0
- package/src/protocol/ids.ts +4 -5
- package/src/protocol/index.ts +1 -0
- package/src/protocol/wire.ts +82 -1
- package/src/server/agent-server.ts +167 -94
- package/src/server/bin.ts +22 -1
- package/src/server/history.ts +166 -0
- package/src/server/index.ts +1 -0
- package/src/server/session-store.ts +225 -0
- package/src/server/wire-error.ts +52 -0
- package/src/sync/event-log.ts +132 -0
- package/src/sync/fit.ts +124 -0
- package/src/sync/history-reader.ts +52 -0
- package/src/sync/history-sqlite.ts +344 -0
- package/src/sync/history.ts +226 -0
- package/src/sync/index.ts +6 -0
- package/src/sync/journal-sqlite.ts +353 -0
- package/src/sync/journal.ts +73 -0
- package/src/sync/node-sqlite.ts +20 -0
- package/src/sync/recovery.ts +112 -0
- package/src/sync/retry.ts +49 -0
- package/src/sync/schema.ts +56 -0
- package/src/sync/sql.ts +106 -0
- package/src/sync/sqlite-file.ts +38 -0
- package/src/sync/sqlite.ts +21 -0
- package/src/sync/worker.ts +259 -0
|
@@ -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,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
|
+
}
|