@moinulmoin/eden-runtime-cloudflare 0.1.0

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/LICENSE +201 -0
  2. package/NOTICE +42 -0
  3. package/dist/artifact-runtime.d.ts +27 -0
  4. package/dist/artifact-runtime.js +14 -0
  5. package/dist/eden-eve-host-worker.mjs +1960 -0
  6. package/dist/eve-host-runtime.d.ts +46 -0
  7. package/dist/eve-host-runtime.js +127 -0
  8. package/dist/eve-host.d.ts +166 -0
  9. package/dist/eve-host.js +495 -0
  10. package/dist/http-host.d.ts +6 -0
  11. package/dist/http-host.js +419 -0
  12. package/dist/index.d.ts +21 -0
  13. package/dist/index.js +7 -0
  14. package/dist/model-adapter-internal.d.ts +12 -0
  15. package/dist/model-adapter-internal.js +172 -0
  16. package/dist/model-adapter.d.ts +9 -0
  17. package/dist/model-adapter.js +56 -0
  18. package/dist/model-contracts.d.ts +92 -0
  19. package/dist/model-contracts.js +2 -0
  20. package/dist/model-normalizers.d.ts +7 -0
  21. package/dist/model-normalizers.js +453 -0
  22. package/dist/session-checkpoint.d.ts +48 -0
  23. package/dist/session-checkpoint.js +300 -0
  24. package/dist/session-identity.d.ts +9 -0
  25. package/dist/session-identity.js +45 -0
  26. package/dist/session-jobs.d.ts +69 -0
  27. package/dist/session-jobs.js +427 -0
  28. package/dist/session-journal.d.ts +154 -0
  29. package/dist/session-journal.js +391 -0
  30. package/dist/session-schema.d.ts +21 -0
  31. package/dist/session-schema.js +247 -0
  32. package/dist/session-state.d.ts +165 -0
  33. package/dist/session-state.js +168 -0
  34. package/dist/session.d.ts +40 -0
  35. package/dist/session.js +792 -0
  36. package/dist/test-execution.d.ts +8 -0
  37. package/dist/test-execution.js +12 -0
  38. package/dist/test-worker.d.ts +12 -0
  39. package/dist/test-worker.js +214 -0
  40. package/dist/tool-harness.d.ts +31 -0
  41. package/dist/tool-harness.js +226 -0
  42. package/dist/turn-runner-storage.d.ts +28 -0
  43. package/dist/turn-runner-storage.js +583 -0
  44. package/dist/turn-runner-types.d.ts +112 -0
  45. package/dist/turn-runner-types.js +21 -0
  46. package/dist/turn-runner.d.ts +6 -0
  47. package/dist/turn-runner.js +370 -0
  48. package/package.json +51 -0
@@ -0,0 +1,391 @@
1
+ /*
2
+ * Modified derivative of portable Eve concepts. Eve 0.31.3 reference commit:
3
+ * 0b102bc90e7cf2c3e294f6ca3af86c307d449b1a. See repository NOTICE and LICENSE.
4
+ */
5
+ const MAX_EVENT_PAYLOAD_BYTES = 131_072;
6
+ const EVENT_ID_BYTES = 16;
7
+ export const MAX_JOURNAL_EVENTS_PER_PAGE = 256;
8
+ const EDEN_EVENT_TYPES = new Set([
9
+ "session.started",
10
+ "turn.started",
11
+ "message.received",
12
+ "step.started",
13
+ "actions.requested",
14
+ "action.result",
15
+ "message.completed",
16
+ "step.completed",
17
+ "turn.completed",
18
+ "session.waiting",
19
+ "step.failed",
20
+ "turn.failed",
21
+ "session.failed",
22
+ ]);
23
+ export function createOpaqueEventId() {
24
+ const bytes = new Uint8Array(EVENT_ID_BYTES);
25
+ crypto.getRandomValues(bytes);
26
+ let hex = "";
27
+ for (const byte of bytes) {
28
+ hex += byte.toString(16).padStart(2, "0");
29
+ }
30
+ return `evt_${hex}`;
31
+ }
32
+ function now() {
33
+ return new Date().toISOString();
34
+ }
35
+ function json(value) {
36
+ const serialized = JSON.stringify(value);
37
+ if (serialized === undefined) {
38
+ throw new Error("Journal values must be JSON-compatible");
39
+ }
40
+ return serialized;
41
+ }
42
+ function assertPayloadSize(payload) {
43
+ const byteLength = new TextEncoder().encode(payload).byteLength;
44
+ if (byteLength > MAX_EVENT_PAYLOAD_BYTES) {
45
+ throw new Error("Journal event payload exceeds the 128 KiB limit");
46
+ }
47
+ }
48
+ function optional(value) {
49
+ return value ?? null;
50
+ }
51
+ function requireRow(sql, query, ...bindings) {
52
+ const rows = sql
53
+ .exec(query, ...bindings)
54
+ .toArray();
55
+ if (rows[0]?.present !== 1) {
56
+ throw new Error("Journal transition referenced a missing durable row");
57
+ }
58
+ }
59
+ function requireRelatedRows(sql, sessionId, rows) {
60
+ if (rows.turnId !== undefined && rows.stepId !== undefined) {
61
+ requireRow(sql, `SELECT EXISTS (
62
+ SELECT 1
63
+ FROM turns
64
+ INNER JOIN steps
65
+ ON steps.session_id = turns.session_id
66
+ AND steps.turn_id = turns.turn_id
67
+ WHERE turns.session_id = ?
68
+ AND turns.turn_id = ?
69
+ AND steps.step_id = ?
70
+ ) AS present`, sessionId, rows.turnId, rows.stepId);
71
+ return;
72
+ }
73
+ if (rows.turnId !== undefined) {
74
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM turns WHERE turn_id = ? AND session_id = ?) AS present", rows.turnId, sessionId);
75
+ }
76
+ if (rows.stepId !== undefined) {
77
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM steps WHERE step_id = ? AND session_id = ?) AS present", rows.stepId, sessionId);
78
+ }
79
+ }
80
+ function createJournal(sql, sessionId) {
81
+ return {
82
+ appendEvent(input) {
83
+ if (!EDEN_EVENT_TYPES.has(input.type)) {
84
+ throw new Error(`Unknown Eden event type: ${String(input.type)}`);
85
+ }
86
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?) AS present", sessionId);
87
+ requireRelatedRows(sql, sessionId, input);
88
+ const payload = json(input.data);
89
+ assertPayloadSize(payload);
90
+ const eventId = createOpaqueEventId();
91
+ const committedAt = input.committedAt ?? now();
92
+ const streamIndex = readLatestJournalCursor(sql, sessionId) + 1;
93
+ const envelope = json({
94
+ streamIndex,
95
+ eventId,
96
+ type: input.type,
97
+ data: input.data,
98
+ committedAt,
99
+ });
100
+ assertPayloadSize(envelope);
101
+ sql.exec(`INSERT INTO events (
102
+ stream_index, event_id, session_id, turn_id, step_id, type,
103
+ payload_json, committed_at
104
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, streamIndex, eventId, sessionId, optional(input.turnId), optional(input.stepId), input.type, payload, committedAt);
105
+ return {
106
+ streamIndex,
107
+ eventId,
108
+ type: input.type,
109
+ data: input.data,
110
+ committedAt,
111
+ };
112
+ },
113
+ setSessionStatus(status, updatedAt = now()) {
114
+ sql.exec("UPDATE session_meta SET status = ?, updated_at = ? WHERE session_id = ?", status, updatedAt, sessionId);
115
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?) AS present", sessionId);
116
+ },
117
+ insertTurn(input) {
118
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?) AS present", sessionId);
119
+ sql.exec(`INSERT INTO turns (
120
+ turn_id, session_id, status, accepted_at, started_at,
121
+ completed_at, failed_at, error_id
122
+ ) VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL)`, input.turnId, sessionId, input.status, input.acceptedAt, optional(input.startedAt));
123
+ },
124
+ updateTurn(input) {
125
+ const assignments = ["status = ?"];
126
+ const bindings = [input.status];
127
+ if (input.startedAt !== undefined) {
128
+ assignments.push("started_at = ?");
129
+ bindings.push(input.startedAt);
130
+ }
131
+ if (input.completedAt !== undefined) {
132
+ assignments.push("completed_at = ?");
133
+ bindings.push(input.completedAt);
134
+ }
135
+ if (input.failedAt !== undefined) {
136
+ assignments.push("failed_at = ?");
137
+ bindings.push(input.failedAt);
138
+ }
139
+ if (input.errorId !== undefined) {
140
+ assignments.push("error_id = ?");
141
+ bindings.push(input.errorId);
142
+ }
143
+ sql.exec(`UPDATE turns SET ${assignments.join(", ")}
144
+ WHERE turn_id = ? AND session_id = ?`, ...bindings, input.turnId, sessionId);
145
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM turns WHERE turn_id = ? AND session_id = ?) AS present", input.turnId, sessionId);
146
+ },
147
+ insertStep(input) {
148
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM turns WHERE turn_id = ? AND session_id = ?) AS present", input.turnId, sessionId);
149
+ sql.exec(`INSERT INTO steps (
150
+ step_id, session_id, turn_id, logical_key, phase, status,
151
+ attempt_count, result_ref, error_id, created_at, updated_at, completed_at
152
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, input.stepId, sessionId, input.turnId, input.logicalKey, input.phase, input.status, input.attemptCount ?? 0, optional(input.resultRef), optional(input.errorId), input.createdAt, input.updatedAt, optional(input.completedAt));
153
+ },
154
+ updateStep(input) {
155
+ const assignments = ["status = ?", "updated_at = ?"];
156
+ const bindings = [input.status, input.updatedAt];
157
+ if (input.attemptCount !== undefined) {
158
+ assignments.push("attempt_count = ?");
159
+ bindings.push(input.attemptCount);
160
+ }
161
+ if (input.resultRef !== undefined) {
162
+ assignments.push("result_ref = ?");
163
+ bindings.push(input.resultRef);
164
+ }
165
+ if (input.errorId !== undefined) {
166
+ assignments.push("error_id = ?");
167
+ bindings.push(input.errorId);
168
+ }
169
+ if (input.completedAt !== undefined) {
170
+ assignments.push("completed_at = ?");
171
+ bindings.push(input.completedAt);
172
+ }
173
+ sql.exec(`UPDATE steps SET ${assignments.join(", ")}
174
+ WHERE step_id = ? AND session_id = ?`, ...bindings, input.stepId, sessionId);
175
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM steps WHERE step_id = ? AND session_id = ?) AS present", input.stepId, sessionId);
176
+ },
177
+ insertMessage(input) {
178
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?) AS present", sessionId);
179
+ if (input.turnId !== undefined) {
180
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM turns WHERE turn_id = ? AND session_id = ?) AS present", input.turnId, sessionId);
181
+ }
182
+ sql.exec(`INSERT INTO messages (
183
+ message_id, session_id, turn_id, role, content, created_at, completed_at
184
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`, input.messageId, sessionId, optional(input.turnId), input.role, input.content, input.createdAt, optional(input.completedAt));
185
+ },
186
+ updateMessage(input) {
187
+ const assignments = [];
188
+ const bindings = [];
189
+ if (input.content !== undefined) {
190
+ assignments.push("content = ?");
191
+ bindings.push(input.content);
192
+ }
193
+ if (input.completedAt !== undefined) {
194
+ assignments.push("completed_at = ?");
195
+ bindings.push(input.completedAt);
196
+ }
197
+ if (assignments.length === 0) {
198
+ throw new Error("Message update must change at least one field");
199
+ }
200
+ sql.exec(`UPDATE messages SET ${assignments.join(", ")}
201
+ WHERE message_id = ? AND session_id = ?`, ...bindings, input.messageId, sessionId);
202
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM messages WHERE message_id = ? AND session_id = ?) AS present", input.messageId, sessionId);
203
+ },
204
+ upsertProjection(projectionKey, value, updatedAt = now()) {
205
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?) AS present", sessionId);
206
+ const projection = json(value);
207
+ sql.exec(`INSERT INTO projections (
208
+ session_id, projection_key, projection_json, updated_at
209
+ ) VALUES (?, ?, ?, ?)
210
+ ON CONFLICT (session_id, projection_key) DO UPDATE SET
211
+ projection_json = excluded.projection_json,
212
+ updated_at = excluded.updated_at`, sessionId, projectionKey, projection, updatedAt);
213
+ },
214
+ requestEffect(input) {
215
+ requireRelatedRows(sql, sessionId, input);
216
+ const effectInput = json(input.input);
217
+ sql.exec(`INSERT INTO effects (
218
+ effect_id, session_id, turn_id, step_id, call_id, tool_name,
219
+ idempotency_key, status, input_json, output_json, error_json,
220
+ created_at, updated_at, completed_at
221
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 'requested', ?, NULL, NULL, ?, ?, NULL)`, input.effectId, sessionId, input.turnId, input.stepId, input.callId, input.toolName, input.idempotencyKey, effectInput, input.createdAt, input.createdAt);
222
+ },
223
+ startEffect(input) {
224
+ sql.exec(`UPDATE effects SET status = 'running', updated_at = ?
225
+ WHERE effect_id = ? AND session_id = ? AND status = 'requested'`, input.updatedAt, input.effectId, sessionId);
226
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM effects WHERE effect_id = ? AND session_id = ?) AS present", input.effectId, sessionId);
227
+ },
228
+ completeEffect(input) {
229
+ const output = json(input.output);
230
+ const existing = sql
231
+ .exec("SELECT status, output_json FROM effects WHERE effect_id = ? AND session_id = ?", input.effectId, sessionId)
232
+ .toArray()[0];
233
+ if (existing === undefined) {
234
+ throw new Error("Journal transition referenced a missing durable row");
235
+ }
236
+ if (existing.status === "completed") {
237
+ if (existing.output_json !== output) {
238
+ throw new Error("Journal effect is already completed with different output");
239
+ }
240
+ return;
241
+ }
242
+ if (existing.status === "failed") {
243
+ throw new Error("Journal effect is already failed");
244
+ }
245
+ sql.exec(`UPDATE effects SET
246
+ status = 'completed',
247
+ output_json = ?,
248
+ error_json = NULL,
249
+ updated_at = ?,
250
+ completed_at = ?
251
+ WHERE effect_id = ? AND session_id = ?`, output, input.completedAt, input.completedAt, input.effectId, sessionId);
252
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM effects WHERE effect_id = ? AND session_id = ?) AS present", input.effectId, sessionId);
253
+ },
254
+ failEffect(input) {
255
+ const error = json(input.error);
256
+ const existing = sql
257
+ .exec("SELECT status, error_json FROM effects WHERE effect_id = ? AND session_id = ?", input.effectId, sessionId)
258
+ .toArray()[0];
259
+ if (existing === undefined) {
260
+ throw new Error("Journal transition referenced a missing durable row");
261
+ }
262
+ if (existing.status === "failed") {
263
+ if (existing.error_json !== error) {
264
+ throw new Error("Journal effect is already failed with different error");
265
+ }
266
+ return;
267
+ }
268
+ if (existing.status === "completed") {
269
+ return;
270
+ }
271
+ sql.exec(`UPDATE effects SET
272
+ status = 'failed',
273
+ output_json = NULL,
274
+ error_json = ?,
275
+ updated_at = ?
276
+ WHERE effect_id = ? AND session_id = ?`, error, input.updatedAt, input.effectId, sessionId);
277
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM effects WHERE effect_id = ? AND session_id = ?) AS present", input.effectId, sessionId);
278
+ },
279
+ recordError(input) {
280
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?) AS present", sessionId);
281
+ requireRelatedRows(sql, sessionId, input);
282
+ sql.exec(`INSERT INTO errors (
283
+ error_id, session_id, turn_id, step_id, code, message, retryable,
284
+ status, created_at, resolved_at
285
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 'open', ?, NULL)`, input.errorId, sessionId, optional(input.turnId), optional(input.stepId), input.code, input.message, input.retryable ? 1 : 0, input.createdAt);
286
+ },
287
+ insertJob(input) {
288
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?) AS present", sessionId);
289
+ sql.exec(`INSERT INTO jobs (
290
+ job_id, session_id, kind, status, due_at, attempts, max_attempts,
291
+ last_error, recovery_action, created_at, updated_at, completed_at
292
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, input.jobId, sessionId, input.kind, input.status ?? "pending", input.dueAt, input.attempts ?? 0, input.maxAttempts ?? 3, optional(input.lastError), optional(input.recoveryAction), input.createdAt, input.updatedAt ?? input.createdAt, optional(input.completedAt));
293
+ },
294
+ updateJob(input) {
295
+ const assignments = ["status = ?", "updated_at = ?"];
296
+ const bindings = [input.status, input.updatedAt];
297
+ if (input.dueAt !== undefined) {
298
+ assignments.push("due_at = ?");
299
+ bindings.push(input.dueAt);
300
+ }
301
+ if (input.attempts !== undefined) {
302
+ assignments.push("attempts = ?");
303
+ bindings.push(input.attempts);
304
+ }
305
+ if (input.lastError !== undefined) {
306
+ assignments.push("last_error = ?");
307
+ bindings.push(input.lastError);
308
+ }
309
+ if (input.recoveryAction !== undefined) {
310
+ assignments.push("recovery_action = ?");
311
+ bindings.push(input.recoveryAction);
312
+ }
313
+ if (input.completedAt !== undefined) {
314
+ assignments.push("completed_at = ?");
315
+ bindings.push(input.completedAt);
316
+ }
317
+ sql.exec(`UPDATE jobs SET ${assignments.join(", ")}
318
+ WHERE job_id = ? AND session_id = ?`, ...bindings, input.jobId, sessionId);
319
+ requireRow(sql, "SELECT EXISTS (SELECT 1 FROM jobs WHERE job_id = ? AND session_id = ?) AS present", input.jobId, sessionId);
320
+ },
321
+ };
322
+ }
323
+ export function commitSessionTransaction(storage, sessionId, transition) {
324
+ return storage.transactionSync(() => transition(createJournal(storage.sql, sessionId)));
325
+ }
326
+ function parseEvent(row) {
327
+ return {
328
+ streamIndex: row.stream_index,
329
+ eventId: row.event_id,
330
+ type: row.type,
331
+ data: JSON.parse(row.payload_json),
332
+ committedAt: row.committed_at,
333
+ };
334
+ }
335
+ export function readJournalEventsPage(sql, sessionId, startIndex = 0, options = {}) {
336
+ if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
337
+ throw new Error("Journal start index must be a non-negative safe integer");
338
+ }
339
+ const endIndex = options.endIndex;
340
+ if (endIndex !== undefined &&
341
+ (!Number.isSafeInteger(endIndex) || endIndex < 0)) {
342
+ throw new Error("Journal end index must be a non-negative safe integer");
343
+ }
344
+ const limit = options.limit ?? MAX_JOURNAL_EVENTS_PER_PAGE;
345
+ if (!Number.isSafeInteger(limit) ||
346
+ limit < 1 ||
347
+ limit > MAX_JOURNAL_EVENTS_PER_PAGE) {
348
+ throw new Error("Journal page limit is invalid");
349
+ }
350
+ if (endIndex !== undefined && endIndex <= startIndex)
351
+ return [];
352
+ const conditions = ["session_id = ?", "stream_index > ?"];
353
+ const bindings = [sessionId, startIndex];
354
+ if (endIndex !== undefined) {
355
+ conditions.push("stream_index <= ?");
356
+ bindings.push(endIndex);
357
+ }
358
+ const rows = sql
359
+ .exec(`SELECT stream_index, event_id, type, payload_json, committed_at
360
+ FROM events
361
+ WHERE ${conditions.join(" AND ")}
362
+ ORDER BY stream_index ASC
363
+ LIMIT ?`, ...bindings, limit)
364
+ .toArray();
365
+ return rows.map((row) => parseEvent(row));
366
+ }
367
+ export function readJournalEvents(sql, sessionId, startIndex = 0) {
368
+ if (!Number.isSafeInteger(startIndex) || startIndex < 0) {
369
+ throw new Error("Journal start index must be a non-negative safe integer");
370
+ }
371
+ const highWater = readLatestJournalCursor(sql, sessionId);
372
+ const events = [];
373
+ let cursor = startIndex;
374
+ while (cursor < highWater) {
375
+ const page = readJournalEventsPage(sql, sessionId, cursor, {
376
+ endIndex: highWater,
377
+ });
378
+ if (page.length === 0)
379
+ break;
380
+ events.push(...page);
381
+ cursor = page[page.length - 1]?.streamIndex ?? cursor;
382
+ }
383
+ return events;
384
+ }
385
+ export function readLatestJournalCursor(sql, sessionId) {
386
+ const rows = sql
387
+ .exec("SELECT MAX(stream_index) AS stream_index FROM events WHERE session_id = ?", sessionId)
388
+ .toArray();
389
+ return rows[0]?.stream_index ?? 0;
390
+ }
391
+ //# sourceMappingURL=session-journal.js.map
@@ -0,0 +1,21 @@
1
+ interface SessionSchemaSql {
2
+ exec(query: string, ...bindings: (ArrayBuffer | string | number | null)[]): {
3
+ toArray(): Record<string, ArrayBuffer | string | number | null>[];
4
+ };
5
+ }
6
+ export interface SessionMigration {
7
+ readonly version: number;
8
+ readonly name: string;
9
+ readonly statements: readonly string[];
10
+ }
11
+ export declare const SESSION_SCHEMA_MIGRATIONS: readonly SessionMigration[];
12
+ export declare const SESSION_SCHEMA_VERSION: number;
13
+ export declare const SESSION_SCHEMA_TABLES: readonly ["schema_migrations", "session_meta", "turns", "steps", "events", "messages", "projections", "effects", "jobs", "errors", "stream_chunks"];
14
+ export declare function readAppliedSessionSchemaVersion(sql: SessionSchemaSql): number;
15
+ interface SessionStorage {
16
+ readonly sql: SessionSchemaSql;
17
+ transactionSync<T>(closure: () => T): T;
18
+ }
19
+ export declare function applySessionMigrations(storage: SessionStorage, migrations?: readonly SessionMigration[]): void;
20
+ export {};
21
+ //# sourceMappingURL=session-schema.d.ts.map
@@ -0,0 +1,247 @@
1
+ export const SESSION_SCHEMA_MIGRATIONS = [
2
+ {
3
+ version: 1,
4
+ name: "session-domains",
5
+ statements: [
6
+ `CREATE TABLE IF NOT EXISTS schema_migrations (
7
+ version INTEGER PRIMARY KEY,
8
+ name TEXT NOT NULL UNIQUE,
9
+ applied_at TEXT NOT NULL
10
+ )`,
11
+ `CREATE TABLE IF NOT EXISTS session_meta (
12
+ session_id TEXT PRIMARY KEY,
13
+ owner_principal TEXT NOT NULL,
14
+ status TEXT NOT NULL CHECK (status IN ('new', 'running', 'waiting', 'failed', 'completed')),
15
+ created_at TEXT NOT NULL,
16
+ updated_at TEXT NOT NULL,
17
+ runtime_version TEXT NOT NULL,
18
+ agent_bundle_version TEXT NOT NULL,
19
+ manifest_version TEXT NOT NULL,
20
+ protocol_version TEXT NOT NULL,
21
+ schema_version INTEGER NOT NULL
22
+ )`,
23
+ `CREATE TABLE IF NOT EXISTS turns (
24
+ turn_id TEXT PRIMARY KEY,
25
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
26
+ status TEXT NOT NULL CHECK (status IN ('accepted', 'running', 'completed', 'failed')),
27
+ accepted_at TEXT NOT NULL,
28
+ started_at TEXT,
29
+ completed_at TEXT,
30
+ failed_at TEXT,
31
+ error_id TEXT
32
+ )`,
33
+ `CREATE TABLE IF NOT EXISTS steps (
34
+ step_id TEXT PRIMARY KEY,
35
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
36
+ turn_id TEXT NOT NULL REFERENCES turns(turn_id),
37
+ logical_key TEXT NOT NULL,
38
+ phase TEXT NOT NULL CHECK (phase IN ('model-tool', 'final-response')),
39
+ status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'completed', 'retryable', 'failed')),
40
+ attempt_count INTEGER NOT NULL DEFAULT 0,
41
+ result_ref TEXT,
42
+ error_id TEXT,
43
+ created_at TEXT NOT NULL,
44
+ updated_at TEXT NOT NULL,
45
+ completed_at TEXT,
46
+ UNIQUE (session_id, turn_id, logical_key)
47
+ )`,
48
+ `CREATE TABLE IF NOT EXISTS events (
49
+ stream_index INTEGER PRIMARY KEY AUTOINCREMENT,
50
+ event_id TEXT NOT NULL UNIQUE,
51
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
52
+ turn_id TEXT,
53
+ step_id TEXT,
54
+ type TEXT NOT NULL,
55
+ payload_json TEXT NOT NULL,
56
+ committed_at TEXT NOT NULL,
57
+ CHECK (length(CAST(payload_json AS BLOB)) <= 131072)
58
+ )`,
59
+ `CREATE TABLE IF NOT EXISTS messages (
60
+ message_id TEXT PRIMARY KEY,
61
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
62
+ turn_id TEXT,
63
+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant', 'tool')),
64
+ content TEXT NOT NULL,
65
+ created_at TEXT NOT NULL,
66
+ completed_at TEXT
67
+ )`,
68
+ `CREATE TABLE IF NOT EXISTS projections (
69
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
70
+ projection_key TEXT NOT NULL,
71
+ projection_json TEXT NOT NULL,
72
+ updated_at TEXT NOT NULL,
73
+ PRIMARY KEY (session_id, projection_key)
74
+ )`,
75
+ `CREATE TABLE IF NOT EXISTS effects (
76
+ effect_id TEXT PRIMARY KEY,
77
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
78
+ turn_id TEXT NOT NULL REFERENCES turns(turn_id),
79
+ step_id TEXT NOT NULL REFERENCES steps(step_id),
80
+ call_id TEXT NOT NULL,
81
+ tool_name TEXT NOT NULL,
82
+ idempotency_key TEXT NOT NULL UNIQUE,
83
+ status TEXT NOT NULL CHECK (status IN ('requested', 'running', 'completed', 'failed')),
84
+ input_json TEXT NOT NULL,
85
+ output_json TEXT,
86
+ error_json TEXT,
87
+ created_at TEXT NOT NULL,
88
+ updated_at TEXT NOT NULL,
89
+ completed_at TEXT
90
+ )`,
91
+ `CREATE TABLE IF NOT EXISTS jobs (
92
+ job_id TEXT PRIMARY KEY,
93
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
94
+ kind TEXT NOT NULL,
95
+ status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'completed', 'retryable', 'dead')),
96
+ due_at INTEGER NOT NULL,
97
+ attempts INTEGER NOT NULL DEFAULT 0,
98
+ max_attempts INTEGER NOT NULL DEFAULT 3,
99
+ last_error TEXT,
100
+ recovery_action TEXT,
101
+ created_at TEXT NOT NULL,
102
+ updated_at TEXT NOT NULL,
103
+ completed_at TEXT
104
+ )`,
105
+ `CREATE TABLE IF NOT EXISTS errors (
106
+ error_id TEXT PRIMARY KEY,
107
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
108
+ turn_id TEXT,
109
+ step_id TEXT,
110
+ code TEXT NOT NULL,
111
+ message TEXT NOT NULL,
112
+ retryable INTEGER NOT NULL CHECK (retryable IN (0, 1)),
113
+ status TEXT NOT NULL CHECK (status IN ('open', 'resolved')),
114
+ created_at TEXT NOT NULL,
115
+ resolved_at TEXT
116
+ )`,
117
+ `CREATE TABLE IF NOT EXISTS stream_chunks (
118
+ chunk_id TEXT PRIMARY KEY,
119
+ session_id TEXT NOT NULL REFERENCES session_meta(session_id),
120
+ stream_index INTEGER NOT NULL,
121
+ payload_json TEXT NOT NULL,
122
+ byte_length INTEGER NOT NULL,
123
+ created_at TEXT NOT NULL,
124
+ UNIQUE (session_id, stream_index),
125
+ CHECK (
126
+ byte_length >= 0 AND
127
+ byte_length <= 131072 AND
128
+ length(CAST(payload_json AS BLOB)) <= 131072
129
+ )
130
+ )`,
131
+ ],
132
+ },
133
+ {
134
+ version: 2,
135
+ name: "session-domain-indexes",
136
+ statements: [
137
+ "CREATE INDEX IF NOT EXISTS turns_by_session ON turns (session_id, accepted_at)",
138
+ "CREATE INDEX IF NOT EXISTS steps_by_turn ON steps (session_id, turn_id, logical_key)",
139
+ "CREATE INDEX IF NOT EXISTS events_by_session_cursor ON events (session_id, stream_index)",
140
+ "CREATE INDEX IF NOT EXISTS messages_by_session_time ON messages (session_id, created_at)",
141
+ "CREATE INDEX IF NOT EXISTS effects_by_step ON effects (session_id, step_id)",
142
+ "CREATE INDEX IF NOT EXISTS jobs_due ON jobs (session_id, status, due_at)",
143
+ "CREATE INDEX IF NOT EXISTS errors_by_session_time ON errors (session_id, created_at)",
144
+ "CREATE INDEX IF NOT EXISTS stream_chunks_by_session_cursor ON stream_chunks (session_id, stream_index)",
145
+ ],
146
+ },
147
+ {
148
+ version: 3,
149
+ name: "separate-artifact-schema-version",
150
+ statements: [
151
+ "ALTER TABLE session_meta ADD COLUMN artifact_schema_version INTEGER NOT NULL DEFAULT 0",
152
+ "UPDATE session_meta SET artifact_schema_version = schema_version",
153
+ ],
154
+ },
155
+ ];
156
+ export const SESSION_SCHEMA_VERSION = SESSION_SCHEMA_MIGRATIONS[SESSION_SCHEMA_MIGRATIONS.length - 1]?.version ?? 0;
157
+ export const SESSION_SCHEMA_TABLES = [
158
+ "schema_migrations",
159
+ "session_meta",
160
+ "turns",
161
+ "steps",
162
+ "events",
163
+ "messages",
164
+ "projections",
165
+ "effects",
166
+ "jobs",
167
+ "errors",
168
+ "stream_chunks",
169
+ ];
170
+ function readAppliedMigrations(sql) {
171
+ const rows = sql
172
+ .exec("SELECT version, name FROM schema_migrations ORDER BY version ASC")
173
+ .toArray();
174
+ return new Map(rows.map((row) => [row.version, { name: row.name }]));
175
+ }
176
+ export function readAppliedSessionSchemaVersion(sql) {
177
+ if (!hasMigrationLedger(sql)) {
178
+ throw new Error("Session migration ledger is unavailable");
179
+ }
180
+ const applied = readAppliedMigrations(sql);
181
+ const appliedVersions = Array.from(applied.keys()).sort((left, right) => left - right);
182
+ const expectedVersions = SESSION_SCHEMA_MIGRATIONS.map(({ version }) => version);
183
+ if (appliedVersions.length !== expectedVersions.length ||
184
+ appliedVersions.some((version, index) => version !== expectedVersions[index])) {
185
+ throw new Error("Session migration ledger is incomplete or unexpected");
186
+ }
187
+ let latestVersion = 0;
188
+ for (const migration of SESSION_SCHEMA_MIGRATIONS) {
189
+ const recorded = applied.get(migration.version);
190
+ if (recorded === undefined) {
191
+ throw new Error(`Session migration ${migration.version} is not recorded`);
192
+ }
193
+ if (recorded.name !== migration.name) {
194
+ throw new Error(`Session migration ${migration.version} is recorded as ${recorded.name}, expected ${migration.name}`);
195
+ }
196
+ latestVersion = migration.version;
197
+ }
198
+ if (latestVersion !== SESSION_SCHEMA_VERSION) {
199
+ throw new Error(`Session schema version ${latestVersion} does not match expected ${SESSION_SCHEMA_VERSION}`);
200
+ }
201
+ return latestVersion;
202
+ }
203
+ function hasMigrationLedger(sql) {
204
+ const rows = sql
205
+ .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", "schema_migrations")
206
+ .toArray();
207
+ return rows.length > 0;
208
+ }
209
+ function assertCompleteSchema(sql) {
210
+ const expectedTables = new Set(SESSION_SCHEMA_TABLES);
211
+ const rows = sql
212
+ .exec(`SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (${SESSION_SCHEMA_TABLES.map(() => "?").join(", ")})`, ...SESSION_SCHEMA_TABLES)
213
+ .toArray();
214
+ for (const row of rows) {
215
+ expectedTables.delete(row.name);
216
+ }
217
+ if (expectedTables.size > 0) {
218
+ throw new Error(`Session schema is incomplete: missing ${Array.from(expectedTables).join(", ")}`);
219
+ }
220
+ }
221
+ export function applySessionMigrations(storage, migrations = SESSION_SCHEMA_MIGRATIONS) {
222
+ const sql = storage.sql;
223
+ const applied = hasMigrationLedger(sql)
224
+ ? readAppliedMigrations(sql)
225
+ : new Map();
226
+ for (const migration of migrations) {
227
+ const existing = applied.get(migration.version);
228
+ if (existing) {
229
+ if (existing.name !== migration.name) {
230
+ throw new Error(`Session migration ${migration.version} is recorded as ${existing.name}, expected ${migration.name}`);
231
+ }
232
+ continue;
233
+ }
234
+ const applyMigration = () => {
235
+ for (const statement of migration.statements) {
236
+ sql.exec(statement);
237
+ }
238
+ sql.exec(`INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)`, migration.version, migration.name, new Date().toISOString());
239
+ sql.exec("UPDATE session_meta SET schema_version = ?", migration.version);
240
+ assertCompleteSchema(sql);
241
+ };
242
+ storage.transactionSync(applyMigration);
243
+ applied.set(migration.version, { name: migration.name });
244
+ }
245
+ assertCompleteSchema(sql);
246
+ }
247
+ //# sourceMappingURL=session-schema.js.map