effect-durable-agent-cloudflare 0.1.0-alpha.8 → 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 (38) hide show
  1. package/README.md +5 -2
  2. package/dist/anthropic.d.ts +44 -0
  3. package/dist/anthropic.js +66 -0
  4. package/dist/anthropic.js.map +1 -0
  5. package/dist/durable-object-DAQzdio7.js +622 -0
  6. package/dist/durable-object-DAQzdio7.js.map +1 -0
  7. package/dist/durable-object-storage-Dec6HWQ9.d.ts +136 -0
  8. package/dist/durable-object-store-yY_KaFtw.js +1231 -0
  9. package/dist/durable-object-store-yY_KaFtw.js.map +1 -0
  10. package/dist/durable-object.d.ts +2352 -55
  11. package/dist/durable-object.js +2 -193
  12. package/dist/index.d.ts +227 -6
  13. package/dist/index.js +6 -5
  14. package/dist/openai.d.ts +10 -5
  15. package/dist/openai.js +20 -48
  16. package/dist/openai.js.map +1 -1
  17. package/dist/providers.d.ts +53 -0
  18. package/dist/providers.js +221 -0
  19. package/dist/providers.js.map +1 -0
  20. package/dist/rpc-codec-B2aLiNqt.d.ts +44 -0
  21. package/dist/rpc-spec-BRNFIsY1.js +407 -0
  22. package/dist/rpc-spec-BRNFIsY1.js.map +1 -0
  23. package/dist/rpc-spec-O5conxmN.d.ts +8888 -0
  24. package/dist/rpc.d.ts +3 -16
  25. package/dist/rpc.js +2 -26
  26. package/dist/{session-controller-BRsC0px6.js → session-controller-BCtnyAEw.js} +691 -657
  27. package/dist/session-controller-BCtnyAEw.js.map +1 -0
  28. package/dist/{session-controller-D1Is2mSw.d.ts → session-controller-BZaYmBLr.d.ts} +110 -31
  29. package/dist/session-controller.d.ts +1 -1
  30. package/dist/session-controller.js +1 -1
  31. package/dist/storage.d.ts +1 -1
  32. package/dist/transport-BzgK07l4.js +205 -0
  33. package/dist/transport-BzgK07l4.js.map +1 -0
  34. package/package.json +29 -11
  35. package/dist/durable-object-storage-DCL2IyUe.d.ts +0 -41
  36. package/dist/durable-object.js.map +0 -1
  37. package/dist/rpc.js.map +0 -1
  38. package/dist/session-controller-BRsC0px6.js.map +0 -1
@@ -0,0 +1,1231 @@
1
+ import * as Layer from "effect/Layer";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Schema from "effect/Schema";
4
+ import { ContextRebasedPayload, DurableEventEnvelope, SummaryCreatedPayload, assistantMessageCommittedEventType, assistantMessageImportedEventType, assistantPartialCommittedEventType, commandAdmittedEventType, commandCancelledEventType, commandCompletedEventType, commandFailedEventType, commandStartedEventType, contextRebasedEventType, decodeDurableEventSync, effectDurableAgentNamespace, steeringMessageQueuedEventType, summaryCreatedEventType, systemMessageCommittedEventType, userMessageCommittedEventType } from "effect-durable-agent/types/events";
5
+ import { SequenceNumber, SummaryId, durablePosition } from "effect-durable-agent/types/core";
6
+ import { EDASessionStore, EDASessionStoreError } from "effect-durable-agent/services/session-store";
7
+ import { TranscriptLogIncarnation, TranscriptRecordFromEnvelope, TranscriptRecordId, TranscriptVersion, isPendingTranscriptUserRecord, isTopLevelTranscriptRecord, planTranscriptBatch } from "effect-durable-agent/transcript";
8
+ import * as Cause from "effect/Cause";
9
+ import * as Option from "effect/Option";
10
+ import * as Stream from "effect/Stream";
11
+ import { CompactionSummaryArtifact } from "effect-durable-agent/domain/context-projection";
12
+ import { annotateEdaSpan, committedBatchAttributes } from "effect-durable-agent/services/tracing";
13
+ import { IdGenerator } from "effect-durable-agent/services/id-generator";
14
+ //#region src/durable-object-json.ts
15
+ /** Conservative JSON limit below the Durable Object SQLite per-value ceiling (2 MB). */
16
+ const durableObjectSerializedJsonHardCapBytes = 15e5;
17
+ const jsonEncoder = new TextEncoder();
18
+ /** Serialize and size-check one JSON column before it reaches DO SQLite. */
19
+ const stringifyJsonForColumn = (value, column) => {
20
+ const json = JSON.stringify(value);
21
+ if (json === void 0) throw new Error(`${column} value is not JSON serializable`);
22
+ const bytes = jsonEncoder.encode(json).byteLength;
23
+ if (bytes > 15e5) throw new Error(`${column} serialized JSON is ${bytes} bytes; hard cap is ${durableObjectSerializedJsonHardCapBytes} bytes`);
24
+ return json;
25
+ };
26
+ //#endregion
27
+ //#region src/durable-object-transcript-tables.ts
28
+ /**
29
+ * SQL layout of the transcript projection (design §5.1), created by the store's forward migration.
30
+ *
31
+ * Rows are keyed by a **slot**: one stored instance of one transcript version. A version is built
32
+ * in a fresh slot, so a retired slot that is still being deleted in bounded slices never collides
33
+ * with a later slot of the same version. At most one slot is `active` and at most one is
34
+ * `building`; `retired` slots are garbage awaiting cleanup and are never read.
35
+ *
36
+ * `_eda_log_incarnation` holds the identity of this physical event log (§8); `_eda_alarm_wakeups`
37
+ * holds each alarm owner's durable wakeup (see `durable-object-alarms.ts`).
38
+ */
39
+ const transcriptTableStatements = [
40
+ `CREATE TABLE IF NOT EXISTS _eda_transcript_meta (
41
+ slot INTEGER PRIMARY KEY AUTOINCREMENT,
42
+ version TEXT NOT NULL,
43
+ role TEXT NOT NULL CHECK (role IN ('active', 'building', 'retired')),
44
+ cursor INTEGER NOT NULL,
45
+ status TEXT NOT NULL CHECK (status IN ('ok', 'failed')),
46
+ failed_at_seq INTEGER,
47
+ error TEXT
48
+ )`,
49
+ `CREATE UNIQUE INDEX IF NOT EXISTS _eda_transcript_meta_role_idx
50
+ ON _eda_transcript_meta(role) WHERE role IN ('active', 'building')`,
51
+ `CREATE TABLE IF NOT EXISTS _eda_transcript_records (
52
+ slot INTEGER NOT NULL,
53
+ id TEXT NOT NULL,
54
+ kind TEXT NOT NULL,
55
+ anchor_seq INTEGER,
56
+ ordinal INTEGER,
57
+ top_level INTEGER NOT NULL,
58
+ pending INTEGER NOT NULL,
59
+ assistant_id TEXT,
60
+ updated_seq INTEGER NOT NULL,
61
+ envelope_json TEXT NOT NULL,
62
+ PRIMARY KEY (slot, id)
63
+ )`,
64
+ `CREATE INDEX IF NOT EXISTS _eda_transcript_records_order_idx
65
+ ON _eda_transcript_records(slot, top_level, anchor_seq, ordinal, id)`,
66
+ `CREATE INDEX IF NOT EXISTS _eda_transcript_records_anchor_idx
67
+ ON _eda_transcript_records(slot, anchor_seq, ordinal) WHERE anchor_seq IS NOT NULL`,
68
+ `CREATE INDEX IF NOT EXISTS _eda_transcript_records_updated_idx
69
+ ON _eda_transcript_records(slot, updated_seq)`,
70
+ `CREATE INDEX IF NOT EXISTS _eda_transcript_records_pending_idx
71
+ ON _eda_transcript_records(slot, id) WHERE pending = 1`,
72
+ `CREATE INDEX IF NOT EXISTS _eda_transcript_records_tool_idx
73
+ ON _eda_transcript_records(slot, assistant_id) WHERE assistant_id IS NOT NULL`,
74
+ `CREATE TABLE IF NOT EXISTS _eda_transcript_aliases (
75
+ slot INTEGER NOT NULL,
76
+ namespace TEXT NOT NULL,
77
+ key TEXT NOT NULL,
78
+ record_id TEXT NOT NULL,
79
+ PRIMARY KEY (slot, namespace, key)
80
+ )`,
81
+ `CREATE TABLE IF NOT EXISTS _eda_log_incarnation (
82
+ id INTEGER PRIMARY KEY CHECK (id = 1),
83
+ incarnation TEXT NOT NULL
84
+ )`,
85
+ `CREATE TABLE IF NOT EXISTS _eda_alarm_wakeups (
86
+ owner TEXT PRIMARY KEY,
87
+ at_ms INTEGER NOT NULL
88
+ )`
89
+ ];
90
+ /**
91
+ * Migration 3: consecutive failed builder slices of a slot (a build freezes after the configured
92
+ * limit), and consecutive failures of an alarm owner's work (an owner stops after the limit).
93
+ */
94
+ const builderFailureColumnStatements = ["ALTER TABLE _eda_transcript_meta ADD COLUMN slice_failures INTEGER NOT NULL DEFAULT 0", "ALTER TABLE _eda_alarm_wakeups ADD COLUMN failures INTEGER NOT NULL DEFAULT 0"];
95
+ const decodeVersion = Schema.decodeUnknownSync(TranscriptVersion);
96
+ const decodeSlot = (row) => {
97
+ if (row.role !== "active" && row.role !== "building" && row.role !== "retired") throw new Error(`transcript slot ${row.slot} has unknown role ${row.role}`);
98
+ if (row.status === "failed" && (row.failed_at_seq === null || row.error === null)) throw new Error(`failed transcript slot ${row.slot} has no failure seq or error`);
99
+ return {
100
+ slot: row.slot,
101
+ version: decodeVersion(row.version),
102
+ role: row.role,
103
+ cursor: SequenceNumber.make(row.cursor),
104
+ sliceFailures: row.slice_failures,
105
+ status: row.status === "failed" ? {
106
+ _tag: "Failed",
107
+ failedAtSeq: SequenceNumber.make(row.failed_at_seq ?? 0),
108
+ error: row.error ?? ""
109
+ } : { _tag: "Ok" }
110
+ };
111
+ };
112
+ /** Every stored slot, in creation order. */
113
+ const readTranscriptSlots = (sql) => sql.exec("SELECT slot, version, role, cursor, status, failed_at_seq, error, slice_failures FROM _eda_transcript_meta ORDER BY slot").toArray().map(decodeSlot);
114
+ /** The port's view of a slot; retired slots have none. */
115
+ const transcriptVersionMetaOf = (slot) => slot.role === "retired" ? void 0 : {
116
+ version: slot.version,
117
+ role: slot.role,
118
+ cursor: slot.cursor,
119
+ status: slot.status
120
+ };
121
+ const insertTranscriptSlot = (sql, version, role) => {
122
+ sql.exec("INSERT INTO _eda_transcript_meta (version, role, cursor, status) VALUES (?, ?, 0, 'ok')", version, role);
123
+ };
124
+ const setTranscriptSlotRole = (sql, slot, role) => {
125
+ sql.exec("UPDATE _eda_transcript_meta SET role = ? WHERE slot = ?", role, slot);
126
+ };
127
+ /** Record how many consecutive builder slices threw while targeting a slot. */
128
+ const setTranscriptSliceFailures = (sql, slot, failures) => {
129
+ sql.exec("UPDATE _eda_transcript_meta SET slice_failures = ? WHERE slot = ?", failures, slot);
130
+ };
131
+ /** Freeze a slot at its unchanged cursor. A failed slot is never written again. */
132
+ const markTranscriptSlotFailed = (sql, slot, failedAtSeq, error) => {
133
+ sql.exec("UPDATE _eda_transcript_meta SET status = 'failed', failed_at_seq = ?, error = ? WHERE slot = ?", failedAtSeq, error, slot);
134
+ };
135
+ /**
136
+ * Delete up to `limit` rows of a retired slot, records first, and the slot itself once empty.
137
+ * Returns the number of rows deleted.
138
+ */
139
+ const deleteRetiredTranscriptRows = (sql, slot, limit) => {
140
+ const records = sql.exec(`DELETE FROM _eda_transcript_records WHERE rowid IN (
141
+ SELECT rowid FROM _eda_transcript_records WHERE slot = ? LIMIT ?
142
+ ) RETURNING 1 AS deleted`, slot, limit).toArray().length;
143
+ const aliases = records >= limit ? 0 : sql.exec(`DELETE FROM _eda_transcript_aliases WHERE rowid IN (
144
+ SELECT rowid FROM _eda_transcript_aliases WHERE slot = ? LIMIT ?
145
+ ) RETURNING 1 AS deleted`, slot, limit - records).toArray().length;
146
+ if (records + aliases < limit) sql.exec("DELETE FROM _eda_transcript_meta WHERE slot = ? AND role = 'retired'", slot);
147
+ return records + aliases;
148
+ };
149
+ const encodeEnvelope = Schema.encodeSync(TranscriptRecordFromEnvelope);
150
+ const decodeEnvelope = Schema.decodeUnknownSync(TranscriptRecordFromEnvelope);
151
+ /** A stored record row this release cannot decode. */
152
+ var TranscriptRowDecodeError = class extends Error {
153
+ name = "TranscriptRowDecodeError";
154
+ };
155
+ /**
156
+ * Decode one stored row. A row this release cannot decode throws; maintenance treats that as a
157
+ * projection failure and reads as an unreadable window, never as a wrong view.
158
+ */
159
+ const decodeRecordRow = (row) => {
160
+ try {
161
+ return decodeEnvelope(JSON.parse(row.envelope_json));
162
+ } catch (cause) {
163
+ throw new TranscriptRowDecodeError(`undecodable transcript row: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
164
+ }
165
+ };
166
+ const positionOf = (record) => "position" in record ? record.position : void 0;
167
+ const encodeTranscriptPlan = (plan) => ({
168
+ records: plan.records.map((record) => {
169
+ const position = positionOf(record);
170
+ return [
171
+ record.id,
172
+ record.kind,
173
+ position?.anchorSeq ?? null,
174
+ position?.ordinal ?? null,
175
+ isTopLevelTranscriptRecord(record) ? 1 : 0,
176
+ isPendingTranscriptUserRecord(record) ? 1 : 0,
177
+ record.kind === "tool" ? record.assistantId : null,
178
+ record.updatedSeq,
179
+ stringifyJsonForColumn(encodeEnvelope(record), "_eda_transcript_records.envelope_json")
180
+ ];
181
+ }),
182
+ aliases: plan.aliases,
183
+ throughSeq: plan.throughSeq
184
+ });
185
+ /** Write an encoded plan to a slot and advance its cursor; the caller owns the transaction. */
186
+ const writeTranscriptPlan = (sql, slot, plan) => {
187
+ for (const row of plan.records) sql.exec(`INSERT INTO _eda_transcript_records (
188
+ slot, id, kind, anchor_seq, ordinal, top_level, pending, assistant_id, updated_seq, envelope_json
189
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
190
+ ON CONFLICT(slot, id) DO UPDATE SET
191
+ kind = excluded.kind,
192
+ anchor_seq = excluded.anchor_seq,
193
+ ordinal = excluded.ordinal,
194
+ top_level = excluded.top_level,
195
+ pending = excluded.pending,
196
+ assistant_id = excluded.assistant_id,
197
+ updated_seq = excluded.updated_seq,
198
+ envelope_json = excluded.envelope_json`, slot, ...row);
199
+ for (const alias of plan.aliases) sql.exec(`INSERT INTO _eda_transcript_aliases (slot, namespace, key, record_id) VALUES (?, ?, ?, ?)
200
+ ON CONFLICT(slot, namespace, key) DO NOTHING`, slot, alias.namespace, alias.key, alias.recordId);
201
+ sql.exec("UPDATE _eda_transcript_meta SET cursor = ? WHERE slot = ?", plan.throughSeq, slot);
202
+ };
203
+ const readRecord = (sql, slot, id) => {
204
+ const row = sql.exec("SELECT envelope_json FROM _eda_transcript_records WHERE slot = ? AND id = ?", slot, id).toArray()[0];
205
+ return row === void 0 ? void 0 : decodeRecordRow(row);
206
+ };
207
+ const decodeRecordId = Schema.decodeUnknownSync(TranscriptRecordId);
208
+ const readAlias = (sql, slot, namespace, key) => {
209
+ const row = sql.exec("SELECT record_id FROM _eda_transcript_aliases WHERE slot = ? AND namespace = ? AND key = ?", slot, namespace, key).toArray()[0];
210
+ return row === void 0 ? void 0 : decodeRecordId(row.record_id);
211
+ };
212
+ /** Indexed synchronous reads of one slot as committed so far in this transaction. */
213
+ const makeTranscriptLookup = (sql, slot) => ({
214
+ cursor: slot.cursor,
215
+ record: (id) => readRecord(sql, slot.slot, id),
216
+ alias: (namespace, key) => readAlias(sql, slot.slot, namespace, key),
217
+ nextOrdinal: (anchorSeq) => sql.exec(`SELECT MAX(ordinal) + 1 AS next FROM _eda_transcript_records
218
+ WHERE slot = ? AND anchor_seq = ?`, slot.slot, anchorSeq).one().next ?? 0
219
+ });
220
+ const topLevel = (record) => {
221
+ if (!isTopLevelTranscriptRecord(record)) throw new TranscriptRowDecodeError(`transcript record ${record.id} is indexed as top-level but is not`);
222
+ return record;
223
+ };
224
+ /**
225
+ * Window reads over one served slot. Every method is a synchronous indexed query, so a window
226
+ * assembled from them inside one synchronous call is one cut. Record ids are ASCII, so SQLite's
227
+ * binary text order equals `TranscriptOrder`'s code-unit order.
228
+ */
229
+ const makeTranscriptWindowSource = (sql, incarnation, slot, carried) => {
230
+ const meta = transcriptVersionMetaOf(slot);
231
+ if (meta === void 0) throw new Error(`retired transcript slot ${slot.slot} is not servable`);
232
+ const topLevelPage = (key, limit, inclusive, direction) => {
233
+ const comparison = direction === "before" ? inclusive ? "<=" : "<" : inclusive ? ">=" : ">";
234
+ const order = direction === "before" ? "DESC" : "ASC";
235
+ const keyClause = key === void 0 ? "" : `AND (anchor_seq, ordinal, id) ${comparison} (?, ?, ?)`;
236
+ const keyBindings = key === void 0 ? [] : [
237
+ key.anchorSeq,
238
+ key.ordinal,
239
+ key.recordId
240
+ ];
241
+ return sql.exec(`SELECT envelope_json FROM _eda_transcript_records
242
+ WHERE slot = ? AND top_level = 1 ${keyClause}
243
+ ORDER BY anchor_seq ${order}, ordinal ${order}, id ${order}
244
+ LIMIT ?`, slot.slot, ...keyBindings, limit).toArray().map((row) => topLevel(decodeRecordRow(row)));
245
+ };
246
+ return {
247
+ incarnation,
248
+ meta,
249
+ carried,
250
+ topLevelBefore: (key, limit, inclusive) => topLevelPage(key, limit, inclusive, "before"),
251
+ topLevelAfter: (key, limit, inclusive) => topLevelPage(key, limit, inclusive, "after"),
252
+ record: (id) => readRecord(sql, slot.slot, id),
253
+ alias: (namespace, key) => readAlias(sql, slot.slot, namespace, key),
254
+ toolsOf: (assistantId) => sql.exec("SELECT envelope_json FROM _eda_transcript_records WHERE slot = ? AND assistant_id = ?", slot.slot, assistantId).toArray().flatMap((row) => {
255
+ const record = decodeRecordRow(row);
256
+ return record.kind === "tool" ? [record] : [];
257
+ }),
258
+ pendingUsers: () => sql.exec("SELECT envelope_json FROM _eda_transcript_records WHERE slot = ? AND pending = 1", slot.slot).toArray().flatMap((row) => {
259
+ const record = decodeRecordRow(row);
260
+ return record.kind === "user" ? [record] : [];
261
+ })
262
+ };
263
+ };
264
+ const mintUuidV7 = () => Effect.runSync(Effect.gen(function* () {
265
+ return yield* (yield* IdGenerator).makeCorrelationId();
266
+ }).pipe(Effect.provide(IdGenerator.Live)));
267
+ /** Read this log's incarnation (or the host's adoptable value) without minting one. */
268
+ const readLogIncarnation = (sql, adopt) => {
269
+ const row = sql.exec("SELECT incarnation FROM _eda_log_incarnation WHERE id = 1").toArray()[0];
270
+ if (row !== void 0) return TranscriptLogIncarnation.make(row.incarnation);
271
+ const adopted = adopt?.kv.get(adopt.key);
272
+ return typeof adopted === "string" && adopted.length > 0 ? TranscriptLogIncarnation.make(adopted) : void 0;
273
+ };
274
+ /**
275
+ * Read this log's incarnation, minting one on first need. The caller runs it inside a
276
+ * `transactionSync`, so read-or-mint is atomic; storage wipes delete the row and so mint anew.
277
+ */
278
+ const readOrMintLogIncarnation = (sql, adopt) => {
279
+ const row = sql.exec("SELECT incarnation FROM _eda_log_incarnation WHERE id = 1").toArray()[0];
280
+ if (row !== void 0) return TranscriptLogIncarnation.make(row.incarnation);
281
+ const adopted = adopt?.kv.get(adopt.key);
282
+ const incarnation = typeof adopted === "string" && adopted.length > 0 ? adopted : mintUuidV7();
283
+ if (adopt !== void 0 && adopted !== incarnation) adopt.kv.put(adopt.key, incarnation);
284
+ sql.exec("INSERT INTO _eda_log_incarnation (id, incarnation) VALUES (1, ?)", incarnation);
285
+ return TranscriptLogIncarnation.make(incarnation);
286
+ };
287
+ //#endregion
288
+ //#region src/durable-object-transcript-maintenance.ts
289
+ const defaultTranscriptSliceLimits = {
290
+ maxEvents: 512,
291
+ pageEvents: 16,
292
+ maxDeletedRows: 2e3,
293
+ maxSliceFailures: 5
294
+ };
295
+ /** Merge host limits over the defaults; every limit must be a positive integer. */
296
+ const resolveTranscriptSliceLimits = (limits) => {
297
+ const resolved = {
298
+ ...defaultTranscriptSliceLimits,
299
+ ...Object.fromEntries(Object.entries(limits ?? {}).filter(([, value]) => value !== void 0))
300
+ };
301
+ for (const [name, value] of Object.entries(resolved)) if (!Number.isInteger(value) || value < 1) throw new Error(`transcript slice limit ${name} must be a positive integer; got ${value}`);
302
+ return resolved;
303
+ };
304
+ const emptyTranscriptEffects = () => ({
305
+ alerts: [],
306
+ pendingWork: false
307
+ });
308
+ /**
309
+ * Publish committed outcomes to the host. Call only after the outer transaction returns. A hook
310
+ * that throws is reported and otherwise ignored: the work it describes is already committed.
311
+ */
312
+ const publishTranscriptEffects = (observer, effects) => {
313
+ const notify = (hook) => {
314
+ try {
315
+ hook();
316
+ } catch (error) {
317
+ console.error("EDA transcript observer failed", error);
318
+ }
319
+ };
320
+ for (const alert of effects.alerts) notify(() => observer?.onAlert?.(alert));
321
+ const activated = effects.activated;
322
+ if (activated !== void 0) notify(() => observer?.onActivated?.(activated));
323
+ if (effects.servedChanged === true) notify(() => observer?.onServedChanged?.());
324
+ if (effects.pendingWork) notify(() => observer?.onPendingWork?.());
325
+ };
326
+ /** The carried definition for a stored version, if this release still carries it. */
327
+ const carriedDefinition = (config, version) => config.current.version === version ? config.current : config.previous?.version === version ? config.previous : void 0;
328
+ const liveSlots = (storage) => readTranscriptSlots(storage.sql).filter((slot) => slot.role !== "retired");
329
+ /**
330
+ * Bring the stored versions in line with this release's definitions (§7 steps 2, 3 and 5),
331
+ * writing only metadata. Rows are never touched here: building and cleanup happen in slices.
332
+ *
333
+ * - No version yet: an empty log starts `current` as active at seq 0; a log written before
334
+ * transcripts existed builds `current` from the log while nothing is served.
335
+ * - A building version that is not `current` is retired (discarded).
336
+ * - If the active version is not `current` and no build of `current` exists, one starts. A build
337
+ * of `current` that failed counts as existing, so it is never retried.
338
+ */
339
+ const reconcileTranscriptSlots = (storage, config, head, effects) => {
340
+ const { sql } = storage;
341
+ const current = config.current.version;
342
+ const slots = liveSlots(storage);
343
+ if (slots.length === 0) {
344
+ insertTranscriptSlot(sql, current, head === 0 ? "active" : "building");
345
+ if (head > 0) effects.pendingWork = true;
346
+ return;
347
+ }
348
+ for (const slot of slots) if (slot.role === "building" && slot.version !== current) {
349
+ setTranscriptSlotRole(sql, slot.slot, "retired");
350
+ effects.pendingWork = true;
351
+ }
352
+ const active = slots.find((slot) => slot.role === "active");
353
+ const buildingCurrent = slots.some((slot) => slot.role === "building" && slot.version === current);
354
+ if (active?.version !== current && !buildingCurrent) {
355
+ insertTranscriptSlot(sql, current, "building");
356
+ effects.pendingWork = true;
357
+ }
358
+ };
359
+ const nestedTransactionSupport = /* @__PURE__ */ new WeakMap();
360
+ const nestedTransactionRejection = /cannot start a transaction within a transaction/i;
361
+ /**
362
+ * Whether this storage runs a `transactionSync` nested in another as an independent inner
363
+ * transaction. workerd does; celld rejects nesting ("cannot start a transaction within a
364
+ * transaction") without disturbing the enclosing transaction. Probed once per storage object.
365
+ */
366
+ const supportsNestedTransactions = (storage) => {
367
+ const known = nestedTransactionSupport.get(storage);
368
+ if (known !== void 0) return known;
369
+ let supported;
370
+ try {
371
+ storage.transactionSync(() => storage.transactionSync(() => void 0));
372
+ supported = true;
373
+ } catch (error) {
374
+ if (!(error instanceof Error && nestedTransactionRejection.test(error.message))) throw error;
375
+ supported = false;
376
+ }
377
+ nestedTransactionSupport.set(storage, supported);
378
+ return supported;
379
+ };
380
+ /** Freeze a slot at its unchanged cursor and raise the alert. */
381
+ const freezeSlot = (storage, slot, failedAtSeq, cause, effects) => {
382
+ const error = cause instanceof Error ? cause.message : String(cause);
383
+ markTranscriptSlotFailed(storage.sql, slot.slot, failedAtSeq, error);
384
+ if (slot.role === "active" || slot.role === "building" && !readTranscriptSlots(storage.sql).some((other) => other.role === "active")) effects.servedChanged = true;
385
+ if (slot.role !== "retired") effects.alerts.push({
386
+ _tag: "ProjectionFailed",
387
+ version: slot.version,
388
+ role: slot.role,
389
+ failedAtSeq,
390
+ error
391
+ });
392
+ return {
393
+ ...slot,
394
+ status: {
395
+ _tag: "Failed",
396
+ failedAtSeq,
397
+ error
398
+ }
399
+ };
400
+ };
401
+ /**
402
+ * Project committed events into one slot, or freeze the slot (§5.2).
403
+ *
404
+ * Planning, row decoding and row encoding (serialization and the size cap) all run before any
405
+ * write, so every recoverable projection error is raised before the slot is touched. Where the
406
+ * platform nests transactions (workerd), the writes also run inside an inner `transactionSync`,
407
+ * so even a failing write rolls back only that slot. Either way the failure is recorded in the
408
+ * caller's transaction and the events the caller appended still commit. Where it does not
409
+ * (celld), a write that fails after planning succeeded is a storage failure, which fails the
410
+ * caller's whole transaction atomically, exactly as a failed event insert does.
411
+ */
412
+ const advanceSlot = (storage, slot, definition, events, effects) => {
413
+ const first = events.find((entry) => entry.position.seq > slot.cursor);
414
+ if (first === void 0 || slot.status._tag === "Failed" || slot.role === "retired") return slot;
415
+ const nested = supportsNestedTransactions(storage);
416
+ const project = () => {
417
+ const plan = encodeTranscriptPlan(planTranscriptBatch(makeTranscriptLookup(storage.sql, slot), events, definition));
418
+ if (nested) writeTranscriptPlan(storage.sql, slot.slot, plan);
419
+ return plan;
420
+ };
421
+ let plan;
422
+ try {
423
+ plan = nested ? storage.transactionSync(project) : project();
424
+ } catch (cause) {
425
+ return freezeSlot(storage, slot, first.position.seq, cause, effects);
426
+ }
427
+ if (!nested) writeTranscriptPlan(storage.sql, slot.slot, plan);
428
+ return {
429
+ ...slot,
430
+ cursor: plan.throughSeq
431
+ };
432
+ };
433
+ /**
434
+ * The append hook: one batch-level call inside the append transaction, after every entry has
435
+ * been inserted.
436
+ *
437
+ * A version is maintained here exactly when it is carried, healthy and caught up — its cursor is
438
+ * the head the batch started from — so the new events are precisely what it is missing. Anything
439
+ * behind (a building version) is caught up by builder slices instead, and frozen versions are
440
+ * never touched. Each version fails independently.
441
+ */
442
+ const maintainTranscriptsOnAppend = (storage, config, headBeforeBatch, appended, effects) => {
443
+ reconcileTranscriptSlots(storage, config, headBeforeBatch, effects);
444
+ if (appended.length === 0) return;
445
+ for (const slot of liveSlots(storage)) {
446
+ const definition = carriedDefinition(config, slot.version);
447
+ if (definition === void 0 || slot.status._tag === "Failed") continue;
448
+ if (slot.cursor !== headBeforeBatch) continue;
449
+ advanceSlot(storage, slot, definition, appended, effects);
450
+ }
451
+ };
452
+ /**
453
+ * The missed-session alert for a session whose active version this release no longer carries,
454
+ * raised whenever an object starts, so it does not depend on observing the build's creation.
455
+ */
456
+ const missedSessionAlert = (storage, config) => {
457
+ const active = liveSlots(storage).find((slot) => slot.role === "active");
458
+ return active === void 0 || carriedDefinition(config, active.version) !== void 0 ? void 0 : {
459
+ _tag: "MissedSession",
460
+ activeVersion: active.version,
461
+ currentVersion: config.current.version
462
+ };
463
+ };
464
+ /** The one slot a builder slice advances: the building version, else an active one behind. */
465
+ const buildTarget = (config, slots, head) => {
466
+ const healthy = (slot) => slot.status._tag === "Ok" && carriedDefinition(config, slot.version) !== void 0;
467
+ return slots.find((slot) => slot.role === "building" && healthy(slot)) ?? slots.find((slot) => slot.role === "active" && healthy(slot) && slot.cursor < head);
468
+ };
469
+ /** Whether any builder or cleanup slice has work to do. Read-only. */
470
+ const hasPendingTranscriptWork = (storage, config, head) => {
471
+ const slots = readTranscriptSlots(storage.sql);
472
+ if (slots.some((slot) => slot.role === "retired")) return true;
473
+ const live = slots.filter((slot) => slot.role !== "retired");
474
+ if (live.length === 0) return head > 0;
475
+ const current = config.current.version;
476
+ if (live.some((slot) => slot.role === "building" && slot.version !== current)) return true;
477
+ if (live.find((slot) => slot.role === "active")?.version !== current && !live.some((slot) => slot.role === "building" && slot.version === current)) return true;
478
+ return buildTarget(config, live, head) !== void 0;
479
+ };
480
+ /**
481
+ * One bounded builder slice. The caller runs it inside one outer `transactionSync`.
482
+ *
483
+ * It reconciles versions, projects at most `maxEvents` log events into the building version
484
+ * (page by page, each page's rows and cursor committed together, so an eviction resumes from the
485
+ * cursor), activates the build when its cursor equals the head re-read in this transaction, and
486
+ * deletes a bounded number of retired rows. Returns whether more work remains.
487
+ */
488
+ const runTranscriptSlice = (storage, config, log, limits, effects) => {
489
+ const { sql } = storage;
490
+ const head = log.head();
491
+ reconcileTranscriptSlots(storage, config, head, effects);
492
+ const slots = liveSlots(storage);
493
+ const target = buildTarget(config, slots, head);
494
+ if (target !== void 0) {
495
+ const definition = carriedDefinition(config, target.version);
496
+ let slot = target;
497
+ let remaining = limits.maxEvents;
498
+ try {
499
+ while (definition !== void 0 && slot.status._tag === "Ok" && slot.cursor < head && remaining > 0) {
500
+ let page;
501
+ try {
502
+ page = log.after(slot.cursor, Math.min(limits.pageEvents, remaining));
503
+ } catch (cause) {
504
+ slot = freezeSlot(storage, slot, SequenceNumber.make(slot.cursor + 1), cause, effects);
505
+ break;
506
+ }
507
+ if (page.length === 0) break;
508
+ remaining -= page.length;
509
+ slot = advanceSlot(storage, slot, definition, page, effects);
510
+ }
511
+ } catch (cause) {
512
+ throw new TranscriptBuildSliceError(cause);
513
+ }
514
+ if (target.role === "active" && target.cursor < head && slot.status._tag === "Ok" && slot.cursor === log.head()) effects.servedChanged = true;
515
+ if (target.sliceFailures > 0) setTranscriptSliceFailures(sql, target.slot, 0);
516
+ if (slot.role === "building" && slot.status._tag === "Ok" && slot.cursor === log.head()) {
517
+ const previous = slots.find((candidate) => candidate.role === "active");
518
+ if (previous !== void 0) setTranscriptSlotRole(sql, previous.slot, "retired");
519
+ setTranscriptSlotRole(sql, slot.slot, "active");
520
+ effects.activated = {
521
+ version: slot.version,
522
+ previousVersion: previous?.version
523
+ };
524
+ }
525
+ }
526
+ let deleteBudget = limits.maxDeletedRows;
527
+ for (const slot of readTranscriptSlots(sql)) {
528
+ if (deleteBudget <= 0) break;
529
+ if (slot.role === "retired") deleteBudget -= deleteRetiredTranscriptRows(sql, slot.slot, deleteBudget);
530
+ }
531
+ return hasPendingTranscriptWork(storage, config, log.head());
532
+ };
533
+ /** A builder slice threw while advancing its build target; the cause is the original error. */
534
+ var TranscriptBuildSliceError = class extends Error {
535
+ cause;
536
+ name = "TranscriptBuildSliceError";
537
+ constructor(cause) {
538
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
539
+ this.cause = cause;
540
+ }
541
+ };
542
+ /**
543
+ * Record a builder slice that threw while advancing its build target (its own transaction rolled
544
+ * back), in a new transaction.
545
+ *
546
+ * The slice's build target counts the failure; at `maxSliceFailures` consecutive failures it is
547
+ * frozen as failed at its cursor and alerted, so it is never retried, as the design requires of a
548
+ * failed build. Returns whether a version was frozen.
549
+ */
550
+ const recordTranscriptSliceFailure = (storage, config, log, limits, cause, effects) => {
551
+ const head = log.head();
552
+ reconcileTranscriptSlots(storage, config, head, effects);
553
+ const target = buildTarget(config, liveSlots(storage), head);
554
+ if (target === void 0) return false;
555
+ const failures = target.sliceFailures + 1;
556
+ if (failures < limits.maxSliceFailures) {
557
+ setTranscriptSliceFailures(storage.sql, target.slot, failures);
558
+ return false;
559
+ }
560
+ setTranscriptSliceFailures(storage.sql, target.slot, failures);
561
+ freezeSlot(storage, target, SequenceNumber.make(target.cursor + 1), cause, effects);
562
+ return true;
563
+ };
564
+ //#endregion
565
+ //#region src/durable-object-store.ts
566
+ const ProjectionPayload = Schema.Record(Schema.String, Schema.Unknown);
567
+ const AdmittedCommandProjection = Schema.Struct({
568
+ commandId: Schema.Unknown,
569
+ idempotencyKey: Schema.optionalKey(Schema.Unknown)
570
+ });
571
+ /** Squashed pre-release framework schema. */
572
+ const durableObjectSessionStoreSchemaVersion = 1;
573
+ /** Forward migration adding the transcript projection, log incarnation and alarm wakeups. */
574
+ const durableObjectTranscriptSchemaVersion = 2;
575
+ /** Forward migration adding the consecutive-failure counts that bound builder retries. */
576
+ const durableObjectBuilderFailuresSchemaVersion = 3;
577
+ /**
578
+ * Bound one synchronous DO SQLite event-log read/decode to a small CPU and memory slice.
579
+ *
580
+ * A single logical event can already approach the per-row JSON hard cap, and logical decode may
581
+ * touch sidecar rows. Sixteen rows keeps worst-case page memory materially below isolate limits
582
+ * while still amortizing SQL cursor setup for normal small framework events. Revisit with page
583
+ * duration/byte telemetry before increasing.
584
+ */
585
+ const durableObjectEventReadPageRows = 16;
586
+ /**
587
+ * Durable Object SQLite-backed implementation of the semantic `EDASessionStore`.
588
+ *
589
+ * This adapter is the only place EDA framework storage code touches DO SQL. It
590
+ * translates domain append intent into synchronous SQLite writes while keeping
591
+ * `SessionState` and runners SQL-agnostic.
592
+ */
593
+ var DurableObjectSessionStore = class DurableObjectSessionStore {
594
+ /** Run the single squashed framework migration for the current pre-release schema. */
595
+ static migrate = (storage) => migrateDurableObjectSessionStore(storage);
596
+ /** Build a session-scoped store after migrations have completed. */
597
+ static make = ({ sessionId, storage, transcript }) => Effect.gen(function* () {
598
+ yield* DurableObjectSessionStore.migrate(storage);
599
+ return makeDurableObjectSessionStore(sessionId, storage, transcript);
600
+ });
601
+ /** Layer constructor used by the Durable Object host runtime graph. */
602
+ static layer = (options) => Layer.effect(EDASessionStore, DurableObjectSessionStore.make(options));
603
+ };
604
+ /**
605
+ * Create all framework-owned tables in one idempotent startup step.
606
+ *
607
+ * The project is still pre-release, so this remains a squashed version-1 schema
608
+ * rather than a chain of compatibility migrations.
609
+ */
610
+ const migrateDurableObjectSessionStore = (storage) => Effect.try({
611
+ try: () => storage.transactionSync(() => {
612
+ const { sql } = storage;
613
+ sql.exec(`
614
+ CREATE TABLE IF NOT EXISTS _eda_schema_migrations (
615
+ id INTEGER PRIMARY KEY,
616
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
617
+ )
618
+ `);
619
+ const currentVersion = sql.exec("SELECT COALESCE(MAX(id), 0) AS version FROM _eda_schema_migrations").one().version ?? 0;
620
+ if (currentVersion < durableObjectSessionStoreSchemaVersion) {
621
+ sql.exec(`
622
+ CREATE TABLE IF NOT EXISTS _eda_event_log (
623
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
624
+ event_id TEXT NOT NULL UNIQUE,
625
+ namespace TEXT NOT NULL,
626
+ type TEXT NOT NULL,
627
+ schema_version INTEGER NOT NULL,
628
+ created_at_ms INTEGER NOT NULL,
629
+ trace_json TEXT NOT NULL,
630
+ fact_json TEXT NOT NULL
631
+ )
632
+ `);
633
+ sql.exec(`
634
+ CREATE INDEX IF NOT EXISTS _eda_event_log_namespace_type_seq_idx
635
+ ON _eda_event_log(namespace, type, seq)
636
+ `);
637
+ sql.exec(`
638
+ CREATE TABLE IF NOT EXISTS _eda_command_state (
639
+ command_id TEXT PRIMARY KEY,
640
+ admitted_seq INTEGER NOT NULL,
641
+ status TEXT NOT NULL,
642
+ idempotency_key TEXT,
643
+ payload_json TEXT NOT NULL
644
+ )
645
+ `);
646
+ sql.exec(`
647
+ CREATE TABLE IF NOT EXISTS _eda_command_inputs (
648
+ command_id TEXT PRIMARY KEY,
649
+ admitted_seq INTEGER NOT NULL UNIQUE,
650
+ payload_json TEXT NOT NULL
651
+ )
652
+ `);
653
+ sql.exec(`
654
+ CREATE INDEX IF NOT EXISTS _eda_command_state_status_seq_idx
655
+ ON _eda_command_state(status, admitted_seq)
656
+ `);
657
+ sql.exec(`
658
+ CREATE UNIQUE INDEX IF NOT EXISTS _eda_command_state_idempotency_idx
659
+ ON _eda_command_state(idempotency_key) WHERE idempotency_key IS NOT NULL
660
+ `);
661
+ sql.exec(`
662
+ CREATE TABLE IF NOT EXISTS _eda_context_messages (
663
+ message_id TEXT PRIMARY KEY,
664
+ context_seq INTEGER NOT NULL UNIQUE,
665
+ payload_json TEXT NOT NULL
666
+ )
667
+ `);
668
+ sql.exec(`
669
+ CREATE INDEX IF NOT EXISTS _eda_context_messages_context_seq_idx
670
+ ON _eda_context_messages(context_seq)
671
+ `);
672
+ sql.exec(`
673
+ CREATE TABLE IF NOT EXISTS _eda_context_summaries (
674
+ summary_id TEXT PRIMARY KEY,
675
+ created_seq INTEGER NOT NULL UNIQUE,
676
+ payload_json TEXT NOT NULL
677
+ )
678
+ `);
679
+ sql.exec(`
680
+ CREATE INDEX IF NOT EXISTS _eda_context_summaries_created_seq_idx
681
+ ON _eda_context_summaries(created_seq)
682
+ `);
683
+ sql.exec(`
684
+ CREATE TABLE IF NOT EXISTS _eda_reducer_checkpoints (
685
+ reducer_name TEXT PRIMARY KEY,
686
+ schema_version INTEGER NOT NULL,
687
+ through_seq INTEGER NOT NULL,
688
+ payload_json TEXT NOT NULL,
689
+ updated_at_ms INTEGER NOT NULL
690
+ )
691
+ `);
692
+ sql.exec(`
693
+ CREATE TABLE IF NOT EXISTS _eda_sink_cursors (
694
+ sink_name TEXT PRIMARY KEY,
695
+ after_seq INTEGER NOT NULL,
696
+ payload_json TEXT NOT NULL
697
+ )
698
+ `);
699
+ sql.exec("INSERT INTO _eda_schema_migrations (id) VALUES (?)", durableObjectSessionStoreSchemaVersion);
700
+ }
701
+ if (currentVersion < durableObjectTranscriptSchemaVersion) {
702
+ for (const statement of transcriptTableStatements) sql.exec(statement);
703
+ sql.exec("INSERT INTO _eda_schema_migrations (id) VALUES (?)", durableObjectTranscriptSchemaVersion);
704
+ }
705
+ if (currentVersion < durableObjectBuilderFailuresSchemaVersion) {
706
+ for (const statement of builderFailureColumnStatements) sql.exec(statement);
707
+ sql.exec("INSERT INTO _eda_schema_migrations (id) VALUES (?)", durableObjectBuilderFailuresSchemaVersion);
708
+ }
709
+ }),
710
+ catch: (error) => durableStoreError("migrating DurableObjectSessionStore", error)
711
+ });
712
+ /**
713
+ * Interpret the semantic store API with native DO SQLite.
714
+ *
715
+ * All writes that affect durable ordering happen inside `transactionSync`; replay
716
+ * and lookup reads stay synchronous SQL wrapped in Effect boundaries.
717
+ */
718
+ const makeDurableObjectSessionStore = (sessionId, storage, transcript) => {
719
+ const { sql } = storage;
720
+ const ensureSession = (event) => {
721
+ if (event.sessionId !== sessionId) throw new Error(`DurableObjectSessionStore is scoped to session ${sessionId}; received ${event.sessionId}`);
722
+ };
723
+ /**
724
+ * Insert one append entry or return its existing idempotent event position.
725
+ *
726
+ * The event row is the sequence allocator. Artifact/projection writes happen
727
+ * only for newly inserted events, preventing duplicate appends from advancing
728
+ * body rows or metadata; only those are collected into `inserted`.
729
+ */
730
+ const insertOrRead = (entry, inserted) => {
731
+ const { event } = entry;
732
+ ensureSession(event);
733
+ const existing = readCommittedByEventIdOptional(sql, sessionId, event.eventId);
734
+ if (existing !== void 0) return existing;
735
+ const encoded = encodeEventLogRow(event);
736
+ sql.exec(`
737
+ INSERT INTO _eda_event_log (
738
+ event_id,
739
+ namespace,
740
+ type,
741
+ schema_version,
742
+ created_at_ms,
743
+ trace_json,
744
+ fact_json
745
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
746
+ `, encoded.eventId, encoded.namespace, encoded.type, encoded.schemaVersion, encoded.createdAtMs, encoded.traceJson, encoded.factJson);
747
+ const row = readEventLogRowByEventId(sql, event.eventId);
748
+ applySynchronousProjections(sql, entry, SequenceNumber.make(row.seq), encoded.factJson);
749
+ const committed = rowToCommittedDurableEvent(sql, row, sessionId);
750
+ inserted.push(committed);
751
+ return committed;
752
+ };
753
+ /**
754
+ * Execute an entire append batch as one synchronous SQLite transaction.
755
+ *
756
+ * Transcript maintenance is one batch-level hook inside the same transaction, after every
757
+ * entry. A projection failure freezes only the failing version and never fails the append;
758
+ * its alert is published only after the transaction commits.
759
+ */
760
+ const append = (batch) => Effect.try({
761
+ try: () => {
762
+ const effects = emptyTranscriptEffects();
763
+ const committed = storage.transactionSync(() => {
764
+ const headBeforeBatch = transcript === void 0 ? void 0 : readEventLogHead(sql);
765
+ const inserted = [];
766
+ const entries = batch.entries.map((entry) => insertOrRead(entry, inserted));
767
+ if (transcript !== void 0 && headBeforeBatch !== void 0) maintainTranscriptsOnAppend(storage, transcript.definitions, headBeforeBatch, inserted, effects);
768
+ return entries;
769
+ });
770
+ publishTranscriptEffects(transcript?.observer, effects);
771
+ return committed;
772
+ },
773
+ catch: (error) => durableStoreError("appending DurableObjectSessionStore batch", error)
774
+ }).pipe(Effect.tap((committed) => annotateEdaSpan(committedBatchAttributes(committed))));
775
+ return {
776
+ append,
777
+ eventsAfter: (afterSeq) => makeCommittedEventStream(sql, sessionId, afterSeq),
778
+ loadCommittedEventsBySeq: (seqs) => Effect.try({
779
+ try: () => uniqueSequenceNumbers(seqs).sort((left, right) => left - right).map((seq) => readCommittedBySeq(sql, sessionId, seq)),
780
+ catch: (error) => durableStoreError("loading DurableObjectSessionStore events by seq", error)
781
+ }),
782
+ findCommandAdmission: (input) => Effect.try({
783
+ try: () => {
784
+ const row = findCommandAdmissionRow(sql, input.commandId, input.idempotencyKey);
785
+ return row === void 0 ? void 0 : readCommittedBySeq(sql, sessionId, row.admitted_seq);
786
+ },
787
+ catch: (error) => durableStoreError("finding command admission", error)
788
+ }),
789
+ loadSummaryArtifact: (summaryId) => Effect.try({
790
+ try: () => readSummaryPayloadOptional(sql, summaryId),
791
+ catch: (error) => durableStoreError("loading DurableObjectSessionStore summary", error)
792
+ }),
793
+ loadReducerCheckpoint: (name) => Effect.try({
794
+ try: () => readReducerCheckpoint(sql, name),
795
+ catch: (error) => durableStoreError(`loading DurableObjectSessionStore reducer checkpoint ${name}`, error)
796
+ }),
797
+ saveReducerCheckpoint: (checkpoint) => Effect.try({
798
+ try: () => writeReducerCheckpoint(sql, checkpoint),
799
+ catch: (error) => durableStoreError(`saving DurableObjectSessionStore reducer checkpoint ${checkpoint.name}`, error)
800
+ }),
801
+ saveReducerCheckpoints: (checkpoints) => Effect.try({
802
+ try: () => storage.transactionSync(() => checkpoints.forEach((checkpoint) => writeReducerCheckpoint(sql, checkpoint))),
803
+ catch: (error) => durableStoreError("saving DurableObjectSessionStore reducer checkpoints", error)
804
+ })
805
+ };
806
+ };
807
+ /** Synchronous committed-log reads for the transcript builder, decoded like every replay. */
808
+ const makeDurableObjectEventLog = (sql, sessionId) => ({
809
+ head: () => readEventLogHead(sql),
810
+ after: (afterSeq, limit) => sql.exec(`
811
+ SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
812
+ FROM _eda_event_log
813
+ WHERE seq > ?
814
+ ORDER BY seq ASC
815
+ LIMIT ?
816
+ `, afterSeq, limit).toArray().map((row) => rowToCommittedDurableEvent(sql, row, sessionId))
817
+ });
818
+ const makeCommittedEventStream = (sql, sessionId, afterSeq) => Stream.fromPull(Effect.sync(() => {
819
+ let cursor = {
820
+ afterSeq,
821
+ throughSeq: void 0
822
+ };
823
+ let done = false;
824
+ return Effect.gen(function* () {
825
+ if (done) return yield* Cause.done();
826
+ yield* Effect.yieldNow;
827
+ const page = yield* readCommittedEventPage(sql, sessionId, cursor);
828
+ if (page.events.length === 0) {
829
+ done = true;
830
+ return yield* Cause.done();
831
+ }
832
+ if (Option.isSome(page.next)) cursor = page.next.value;
833
+ else done = true;
834
+ return page.events;
835
+ });
836
+ }));
837
+ const readCommittedEventPage = (sql, sessionId, cursor) => Effect.try({
838
+ try: () => {
839
+ const throughSeq = cursor.throughSeq ?? readEventLogHead(sql);
840
+ if (cursor.afterSeq >= throughSeq) return {
841
+ events: [],
842
+ next: Option.none()
843
+ };
844
+ const events = sql.exec(`
845
+ SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
846
+ FROM _eda_event_log
847
+ WHERE seq > ? AND seq <= ?
848
+ ORDER BY seq ASC
849
+ LIMIT ?
850
+ `, cursor.afterSeq, throughSeq, durableObjectEventReadPageRows).toArray().map((row) => rowToCommittedDurableEvent(sql, row, sessionId));
851
+ const lastSeq = events.at(-1)?.position.seq ?? cursor.afterSeq;
852
+ return {
853
+ events,
854
+ next: lastSeq < throughSeq ? Option.some({
855
+ afterSeq: lastSeq,
856
+ throughSeq
857
+ }) : Option.none()
858
+ };
859
+ },
860
+ catch: (error) => durableStoreError("replaying DurableObjectSessionStore events", error)
861
+ });
862
+ const readEventLogHead = (sql) => SequenceNumber.make(sql.exec(`
863
+ SELECT COALESCE(MAX(seq), 0) AS head
864
+ FROM _eda_event_log
865
+ `).one().head ?? 0);
866
+ const uniqueSequenceNumbers = (seqs) => Array.from(new Set(seqs.map((seq) => Number(seq)))).map((seq) => SequenceNumber.make(seq));
867
+ const readEventLogRowByEventId = (sql, eventId) => sql.exec(`
868
+ SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
869
+ FROM _eda_event_log
870
+ WHERE event_id = ?
871
+ `, eventId).one();
872
+ const readCommittedByEventIdOptional = (sql, sessionId, eventId) => {
873
+ const row = sql.exec(`
874
+ SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
875
+ FROM _eda_event_log
876
+ WHERE event_id = ?
877
+ `, eventId).toArray()[0];
878
+ return row === void 0 ? void 0 : rowToCommittedDurableEvent(sql, row, sessionId);
879
+ };
880
+ const readReducerCheckpoint = (sql, name) => {
881
+ const row = sql.exec(`
882
+ SELECT reducer_name, schema_version, through_seq, payload_json, updated_at_ms
883
+ FROM _eda_reducer_checkpoints
884
+ WHERE reducer_name = ?
885
+ `, name).toArray()[0];
886
+ return row === void 0 ? void 0 : {
887
+ name: row.reducer_name,
888
+ schemaVersion: row.schema_version,
889
+ throughSeq: SequenceNumber.make(row.through_seq),
890
+ payload: JSON.parse(row.payload_json),
891
+ updatedAtMs: row.updated_at_ms
892
+ };
893
+ };
894
+ const writeReducerCheckpoint = (sql, checkpoint) => {
895
+ sql.exec(`
896
+ INSERT INTO _eda_reducer_checkpoints (
897
+ reducer_name,
898
+ schema_version,
899
+ through_seq,
900
+ payload_json,
901
+ updated_at_ms
902
+ ) VALUES (?, ?, ?, ?, ?)
903
+ ON CONFLICT(reducer_name) DO UPDATE SET
904
+ schema_version = excluded.schema_version,
905
+ through_seq = excluded.through_seq,
906
+ payload_json = excluded.payload_json,
907
+ updated_at_ms = excluded.updated_at_ms
908
+ `, checkpoint.name, checkpoint.schemaVersion, checkpoint.throughSeq, stringifyJsonForColumn(checkpoint.payload, "_eda_reducer_checkpoints.payload_json"), checkpoint.updatedAtMs);
909
+ };
910
+ const readMessagePayloadByContextSeq = (sql, contextSeq) => {
911
+ const message = sql.exec(`
912
+ SELECT context_seq, payload_json
913
+ FROM _eda_context_messages
914
+ WHERE context_seq = ?
915
+ `, contextSeq).toArray()[0];
916
+ if (message === void 0) throw new Error(`Context message at seq ${contextSeq} missing from _eda_context_messages`);
917
+ return message;
918
+ };
919
+ /**
920
+ * One committed event by seq, or `undefined` when the log has none there. Storage-only: hosts
921
+ * resolve transcript body references through it without starting the runtime.
922
+ */
923
+ const readDurableObjectCommittedEvent = (sql, sessionId, seq) => {
924
+ const row = sql.exec(`
925
+ SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
926
+ FROM _eda_event_log
927
+ WHERE seq = ?
928
+ `, seq).toArray()[0];
929
+ return row === void 0 ? void 0 : rowToCommittedDurableEvent(sql, row, sessionId);
930
+ };
931
+ /** One compaction summary artifact by id, or `undefined`. Storage-only. */
932
+ const readDurableObjectSummary = (sql, summaryId) => readSummaryPayloadOptional(sql, summaryId);
933
+ const readCommittedBySeq = (sql, sessionId, seq) => {
934
+ const committed = readDurableObjectCommittedEvent(sql, sessionId, seq);
935
+ if (committed === void 0) throw new Error(`no committed event at seq ${seq}`);
936
+ return committed;
937
+ };
938
+ const rowToCommittedDurableEvent = (sql, row, sessionId) => ({
939
+ position: durablePosition(SequenceNumber.make(row.seq)),
940
+ event: decodeDurableEventSync({
941
+ namespace: row.namespace,
942
+ type: row.type,
943
+ schemaVersion: row.schema_version,
944
+ durability: "durable",
945
+ eventId: row.event_id,
946
+ sessionId,
947
+ createdAtMs: row.created_at_ms,
948
+ trace: JSON.parse(row.trace_json),
949
+ payload: readLogicalPayload(sql, row)
950
+ })
951
+ });
952
+ const encodeEventLogRow = (event) => {
953
+ const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
954
+ return {
955
+ eventId: encoded.eventId,
956
+ namespace: encoded.namespace,
957
+ type: encoded.type,
958
+ schemaVersion: encoded.schemaVersion,
959
+ createdAtMs: encoded.createdAtMs,
960
+ traceJson: stringifyJsonForColumn(encoded.trace, "_eda_event_log.trace_json"),
961
+ factJson: stringifyJsonForColumn(eventLogFactPayload(encoded.namespace, encoded.type, encoded.payload), "_eda_event_log.fact_json")
962
+ };
963
+ };
964
+ const readLogicalPayload = (sql, row) => {
965
+ if (row.namespace !== effectDurableAgentNamespace) return JSON.parse(row.fact_json);
966
+ if (row.type === commandAdmittedEventType) {
967
+ const commandId = readCommandIdFromFact(row);
968
+ return { command: readCommandInputPayload(sql, commandId) };
969
+ }
970
+ if (contextMessageEventTypes.has(row.type)) return JSON.parse(readMessagePayloadByContextSeq(sql, row.seq).payload_json);
971
+ if (row.type === summaryCreatedEventType) return {
972
+ ...JSON.parse(row.fact_json),
973
+ summary: readSummaryPayloadFromCreatedSeq(sql, row.seq)
974
+ };
975
+ return JSON.parse(row.fact_json);
976
+ };
977
+ const eventLogFactPayload = (namespace, type, payload) => {
978
+ if (namespace !== effectDurableAgentNamespace || typeof payload !== "object" || payload === null) return payload;
979
+ const record = Schema.decodeUnknownSync(Schema.Record(Schema.String, Schema.Unknown))(payload);
980
+ switch (type) {
981
+ case commandAdmittedEventType: return { command: commandFact(record.command) };
982
+ case systemMessageCommittedEventType: return pick(record, ["messageId"]);
983
+ case userMessageCommittedEventType: return pick(record, ["commandId", "messageId"]);
984
+ case steeringMessageQueuedEventType: return pick(record, [
985
+ "commandId",
986
+ "messageId",
987
+ "runId"
988
+ ]);
989
+ case assistantMessageCommittedEventType:
990
+ case assistantMessageImportedEventType: return pick(record, [
991
+ "messageId",
992
+ "runId",
993
+ "turnId",
994
+ "inferenceId"
995
+ ]);
996
+ case assistantPartialCommittedEventType: return pick(record, [
997
+ "messageId",
998
+ "runId",
999
+ "turnId",
1000
+ "inferenceId",
1001
+ "reason"
1002
+ ]);
1003
+ case summaryCreatedEventType: return pick(record, [
1004
+ "compactionId",
1005
+ "summaryId",
1006
+ "sourceFromSeq",
1007
+ "sourceToSeq"
1008
+ ]);
1009
+ default: return payload;
1010
+ }
1011
+ };
1012
+ const commandFact = (command) => {
1013
+ if (typeof command !== "object" || command === null) return command;
1014
+ const record = command;
1015
+ return record._tag === "SubmitMessage" ? pick(record, [
1016
+ "_tag",
1017
+ "commandId",
1018
+ "disposition",
1019
+ "idempotencyKey"
1020
+ ]) : command;
1021
+ };
1022
+ const pick = (record, keys) => {
1023
+ const out = {};
1024
+ for (const key of keys) if (record[key] !== void 0) out[key] = record[key];
1025
+ return out;
1026
+ };
1027
+ const readCommandIdFromFact = (row) => {
1028
+ const { command: { commandId } } = Schema.decodeUnknownSync(Schema.Struct({ command: Schema.Struct({ commandId: Schema.String }) }))(JSON.parse(row.fact_json));
1029
+ if (typeof commandId !== "string") throw new Error(`CommandAdmitted fact at seq ${row.seq} missing command.commandId`);
1030
+ return commandId;
1031
+ };
1032
+ const readCommandInputPayload = (sql, commandId) => {
1033
+ const row = sql.exec(`
1034
+ SELECT payload_json
1035
+ FROM _eda_command_inputs
1036
+ WHERE command_id = ?
1037
+ `, commandId).toArray()[0];
1038
+ if (row === void 0) throw new Error(`Command input ${commandId} missing from _eda_command_inputs`);
1039
+ return JSON.parse(row.payload_json);
1040
+ };
1041
+ const readSummaryPayloadOptional = (sql, summaryId) => {
1042
+ const row = sql.exec(`
1043
+ SELECT payload_json
1044
+ FROM _eda_context_summaries
1045
+ WHERE summary_id = ?
1046
+ `, summaryId).toArray()[0];
1047
+ return row === void 0 ? void 0 : Schema.decodeUnknownSync(CompactionSummaryArtifact)(JSON.parse(row.payload_json));
1048
+ };
1049
+ const readSummaryPayloadFromCreatedSeq = (sql, createdSeq) => {
1050
+ const row = sql.exec(`
1051
+ SELECT payload_json
1052
+ FROM _eda_context_summaries
1053
+ WHERE created_seq = ?
1054
+ `, createdSeq).toArray()[0];
1055
+ if (row === void 0) throw new Error(`SummaryCreated at seq ${createdSeq} missing from _eda_context_summaries`);
1056
+ return JSON.parse(row.payload_json);
1057
+ };
1058
+ /**
1059
+ * Maintain bounded storage projections in the same transaction as the event.
1060
+ *
1061
+ * These rows are durability aids, not a second source of lifecycle truth: event
1062
+ * order still comes from `_eda_event_log.seq`, while projections make command
1063
+ * lookup and body-sidecar hydration bounded.
1064
+ */
1065
+ const applySynchronousProjections = (sql, entry, seq, factJson) => {
1066
+ const { event } = entry;
1067
+ if (event.namespace !== effectDurableAgentNamespace) return;
1068
+ writeCommandProjection(sql, event, seq, factJson);
1069
+ writeCommandInputProjection(sql, event, seq);
1070
+ writeMessageProjection(sql, event, seq);
1071
+ writeSummaryProjection(sql, event, seq);
1072
+ writeContextRebaseProjection(sql, event, seq);
1073
+ };
1074
+ const writeCommandProjection = (sql, event, seq, factJson) => {
1075
+ const payload = Schema.decodeUnknownSync(ProjectionPayload)(event.payload);
1076
+ switch (event.type) {
1077
+ case commandAdmittedEventType: {
1078
+ const command = Schema.decodeUnknownSync(AdmittedCommandProjection)(payload.command);
1079
+ const commandId = command.commandId;
1080
+ if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
1081
+ sql.exec(`
1082
+ INSERT INTO _eda_command_state (
1083
+ command_id,
1084
+ admitted_seq,
1085
+ status,
1086
+ idempotency_key,
1087
+ payload_json
1088
+ ) VALUES (?, ?, ?, ?, ?)
1089
+ ON CONFLICT(command_id) DO UPDATE SET
1090
+ admitted_seq = excluded.admitted_seq,
1091
+ status = excluded.status,
1092
+ idempotency_key = excluded.idempotency_key,
1093
+ payload_json = excluded.payload_json
1094
+ `, commandId, seq, "admitted", command.idempotencyKey ?? null, factJson);
1095
+ return;
1096
+ }
1097
+ case commandStartedEventType:
1098
+ writeCommandStatus(sql, payload.commandId, seq, "started", factJson);
1099
+ return;
1100
+ case commandCompletedEventType:
1101
+ writeCommandStatus(sql, payload.commandId, seq, "completed", factJson);
1102
+ return;
1103
+ case commandFailedEventType:
1104
+ writeCommandStatus(sql, payload.commandId, seq, "failed", factJson);
1105
+ return;
1106
+ case commandCancelledEventType:
1107
+ writeCommandStatus(sql, payload.commandId, seq, "cancelled", factJson);
1108
+ return;
1109
+ default: return;
1110
+ }
1111
+ };
1112
+ const writeCommandStatus = (sql, commandId, seq, status, payloadJson) => {
1113
+ if (commandId === void 0) throw new Error(`${status} command event missing commandId`);
1114
+ sql.exec(`
1115
+ INSERT INTO _eda_command_state (
1116
+ command_id,
1117
+ admitted_seq,
1118
+ status,
1119
+ idempotency_key,
1120
+ payload_json
1121
+ ) VALUES (?, ?, ?, NULL, ?)
1122
+ ON CONFLICT(command_id) DO UPDATE SET
1123
+ status = excluded.status,
1124
+ payload_json = excluded.payload_json
1125
+ `, commandId, seq, status, payloadJson);
1126
+ };
1127
+ const writeCommandInputProjection = (sql, event, seq) => {
1128
+ if (event.type !== commandAdmittedEventType) return;
1129
+ const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
1130
+ const { command } = Schema.decodeUnknownSync(Schema.Struct({ command: Schema.Record(Schema.String, Schema.Unknown) }))(encoded.payload);
1131
+ const commandId = command?.commandId;
1132
+ if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
1133
+ sql.exec(`
1134
+ INSERT INTO _eda_command_inputs (
1135
+ command_id,
1136
+ admitted_seq,
1137
+ payload_json
1138
+ ) VALUES (?, ?, ?)
1139
+ ON CONFLICT(command_id) DO UPDATE SET
1140
+ admitted_seq = excluded.admitted_seq,
1141
+ payload_json = excluded.payload_json
1142
+ `, commandId, seq, stringifyJsonForColumn(command, "_eda_command_inputs.payload_json"));
1143
+ };
1144
+ const contextMessageEventTypes = /* @__PURE__ */ new Set([
1145
+ systemMessageCommittedEventType,
1146
+ userMessageCommittedEventType,
1147
+ steeringMessageQueuedEventType,
1148
+ assistantMessageCommittedEventType,
1149
+ assistantMessageImportedEventType,
1150
+ assistantPartialCommittedEventType
1151
+ ]);
1152
+ /** Persist model-visible message bodies with the seq that exposed them to context. */
1153
+ const writeMessageProjection = (sql, event, seq) => {
1154
+ if (!contextMessageEventTypes.has(event.type)) return;
1155
+ const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
1156
+ const { messageId } = Schema.decodeUnknownSync(Schema.Struct({ messageId: Schema.Unknown }))(encoded.payload);
1157
+ if (messageId === void 0) throw new Error(`${event.type} missing messageId`);
1158
+ sql.exec(`
1159
+ INSERT INTO _eda_context_messages (
1160
+ message_id,
1161
+ context_seq,
1162
+ payload_json
1163
+ ) VALUES (?, ?, ?)
1164
+ ON CONFLICT(message_id) DO UPDATE SET
1165
+ context_seq = excluded.context_seq,
1166
+ payload_json = excluded.payload_json
1167
+ `, messageId, seq, stringifyJsonForColumn(encoded.payload, "_eda_context_messages.payload_json"));
1168
+ };
1169
+ /**
1170
+ * Persist a cumulative summary artifact without making it the active context.
1171
+ *
1172
+ * `ContextRebased` selects summaries in the framework reduced-state checkpoint;
1173
+ * failed compactions can leave orphaned summaries without changing future context.
1174
+ */
1175
+ const writeSummaryProjection = (sql, event, seq) => {
1176
+ if (event.type !== summaryCreatedEventType) return;
1177
+ const payload = Schema.decodeUnknownSync(SummaryCreatedPayload)(event.payload);
1178
+ const summaryId = payload.summaryId;
1179
+ if (summaryId === void 0) throw new Error("SummaryCreated missing summaryId");
1180
+ if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
1181
+ const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
1182
+ if (summary.summaryId !== summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
1183
+ if (summary.compactionId !== payload.compactionId) throw new Error("SummaryCreated compactionId does not match summary payload");
1184
+ sql.exec(`
1185
+ INSERT INTO _eda_context_summaries (
1186
+ summary_id,
1187
+ created_seq,
1188
+ payload_json
1189
+ ) VALUES (?, ?, ?)
1190
+ ON CONFLICT(summary_id) DO UPDATE SET
1191
+ created_seq = excluded.created_seq,
1192
+ payload_json = excluded.payload_json
1193
+ `, summaryId, seq, stringifyJsonForColumn(summary, "_eda_context_summaries.payload_json"));
1194
+ };
1195
+ /** Validate that `ContextRebased` points at a committed summary sidecar. */
1196
+ const writeContextRebaseProjection = (sql, event, _seq) => {
1197
+ if (event.type !== contextRebasedEventType) return;
1198
+ const payload = Schema.decodeUnknownSync(ContextRebasedPayload)(event.payload);
1199
+ if (payload.summaryId === void 0) throw new Error("ContextRebased missing summaryId");
1200
+ const summary = readSummaryPayloadOptional(sql, SummaryId.make(String(payload.summaryId)));
1201
+ if (summary === void 0) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
1202
+ if (summary.compactionId !== payload.compactionId) throw new Error("ContextRebased summary compactionId does not match event payload");
1203
+ if (summary.retainedFromContextSeq !== payload.retainedFromContextSeq) throw new Error("ContextRebased retained cursor does not match summary payload");
1204
+ };
1205
+ /**
1206
+ * Lookup prior command admission through `_eda_command_state` instead of genesis replay.
1207
+ *
1208
+ * Idempotency key wins over explicit command id so caller-owned retry keys remain
1209
+ * the stable dedupe surface for external ingress.
1210
+ */
1211
+ const findCommandAdmissionRow = (sql, commandId, idempotencyKey) => {
1212
+ if (idempotencyKey !== void 0) {
1213
+ const row = sql.exec(`
1214
+ SELECT admitted_seq
1215
+ FROM _eda_command_state
1216
+ WHERE idempotency_key = ?
1217
+ `, idempotencyKey).toArray()[0];
1218
+ if (row !== void 0) return row;
1219
+ }
1220
+ if (commandId === void 0) return;
1221
+ return sql.exec(`
1222
+ SELECT admitted_seq
1223
+ FROM _eda_command_state
1224
+ WHERE command_id = ?
1225
+ `, commandId).toArray()[0];
1226
+ };
1227
+ const durableStoreError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
1228
+ //#endregion
1229
+ export { makeTranscriptWindowSource as _, TranscriptBuildSliceError as a, readTranscriptSlots as b, emptyTranscriptEffects as c, publishTranscriptEffects as d, reconcileTranscriptSlots as f, TranscriptRowDecodeError as g, runTranscriptSlice as h, readDurableObjectSummary as i, hasPendingTranscriptWork as l, resolveTranscriptSliceLimits as m, makeDurableObjectEventLog as n, carriedDefinition as o, recordTranscriptSliceFailure as p, readDurableObjectCommittedEvent as r, defaultTranscriptSliceLimits as s, DurableObjectSessionStore as t, missedSessionAlert as u, readLogIncarnation as v, transcriptVersionMetaOf as x, readOrMintLogIncarnation as y };
1230
+
1231
+ //# sourceMappingURL=durable-object-store-yY_KaFtw.js.map