effect-durable-agent-cloudflare 0.1.0-alpha.9 → 0.2.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 (39) 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-DIoz2TqE.js +633 -0
  6. package/dist/durable-object-DIoz2TqE.js.map +1 -0
  7. package/dist/durable-object-storage-Dec6HWQ9.d.ts +136 -0
  8. package/dist/durable-object-store-lJkqwvIj.js +1263 -0
  9. package/dist/durable-object-store-lJkqwvIj.js.map +1 -0
  10. package/dist/durable-object.d.ts +2356 -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-Nci-sCgQ.d.ts +68 -0
  21. package/dist/rpc-spec-BU5bGUWF.js +447 -0
  22. package/dist/rpc-spec-BU5bGUWF.js.map +1 -0
  23. package/dist/rpc-spec-NAf8Yjnd.d.ts +9139 -0
  24. package/dist/rpc.d.ts +3 -16
  25. package/dist/rpc.js +2 -26
  26. package/dist/{session-controller-Dp07FnPn.d.ts → session-controller-Cfd5Zjd5.d.ts} +140 -32
  27. package/dist/session-controller-UhUFR3i_.js +1517 -0
  28. package/dist/session-controller-UhUFR3i_.js.map +1 -0
  29. package/dist/session-controller.d.ts +2 -2
  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-COHH8vA6.js +0 -1434
  39. package/dist/session-controller-COHH8vA6.js.map +0 -1
@@ -1,1434 +0,0 @@
1
- import * as Effect from "effect/Effect";
2
- import * as Schema from "effect/Schema";
3
- import { DurableEventEnvelope, assistantMessageCommittedEventType, assistantMessageImportedEventType, assistantPartialCommittedEventType, commandAdmittedEventType, commandCancelledEventType, commandCompletedEventType, commandFailedEventType, commandStartedEventType, contextRebasedEventType, decodeUnknownEDADurableEventSync, effectDurableAgentNamespace, steeringMessageQueuedEventType, summaryCreatedEventType, systemMessageCommittedEventType, userMessageCommittedEventType } from "effect-durable-agent/types/events";
4
- import { SequenceNumber, SessionId, SummaryId, durablePosition } from "effect-durable-agent/types/core";
5
- import { EDATraceMetadata, makeRootEDATraceMetadata } from "effect-durable-agent/types/tracing";
6
- import { annotateEdaSpan, committedBatchAttributes, compactSpanAttributes, toEdaExternalSpan } from "effect-durable-agent/services/tracing";
7
- import * as Layer from "effect/Layer";
8
- import * as ManagedRuntime from "effect/ManagedRuntime";
9
- import { EDARuntime } from "effect-durable-agent/services/runtime";
10
- import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from "effect-durable-agent/services/session-store";
11
- import { SinkCheckpointStore } from "effect-durable-agent/services/sink-checkpoint-store";
12
- import * as Cause from "effect/Cause";
13
- import * as Option from "effect/Option";
14
- import * as Stream from "effect/Stream";
15
- import { CompactionSummaryArtifact } from "effect-durable-agent/domain/context-projection";
16
- import "effect-durable-agent/services/compaction";
17
- import { EDAKeepAlive } from "effect-durable-agent/services/keep-alive";
18
- import "effect-durable-agent/services/prompt-projector";
19
- import { EDAReducerRegistry } from "effect-durable-agent/services/reducer-registry";
20
- import { makeEDARuntimeLayer } from "effect-durable-agent/services/runtime-layer";
21
- import { SessionEventObserver } from "effect-durable-agent/services/session-event-observer";
22
- import { EDAWebSocketDeliveryCheckpoint, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, SubscriberId, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDAWebSocketFlowControl, deliveryHelloFrame, encodeEDAWebSocketServerFrame, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent, onHostSuppressedFrame, restoreWebSocketDeliveryState } from "effect-durable-agent/websocket";
23
- /**
24
- * Alarm-backed in-memory keepalive for a raw Durable Object host.
25
- *
26
- * The active lease count is intentionally not durable: if the object is evicted
27
- * or crashes, the fibers the leases represented are gone too, and normal EDA
28
- * durable recovery must explain any escaped lifecycle boundaries.
29
- */
30
- var DurableObjectKeepAlive = class {
31
- storage;
32
- background;
33
- intervalMs;
34
- now;
35
- onBackgroundError;
36
- activeLeases = 0;
37
- generation = 0;
38
- scheduleTail = Promise.resolve();
39
- shutdownRequested = false;
40
- constructor(storage, background = void 0, options = {}) {
41
- this.storage = storage;
42
- this.background = background;
43
- this.intervalMs = options.intervalMs ?? 3e4;
44
- this.now = options.now ?? (() => Date.now());
45
- this.onBackgroundError = options.onBackgroundError ?? (() => void 0);
46
- }
47
- /** Number of active unsettled host roots currently holding the heartbeat. */
48
- get activeLeaseCount() {
49
- return this.activeLeases;
50
- }
51
- /** Acquire one active-work lease and arm the heartbeat if this is the first lease. */
52
- acquire() {
53
- if (this.shutdownRequested) return Promise.reject(/* @__PURE__ */ new Error("DurableObjectKeepAlive is shut down"));
54
- this.activeLeases += 1;
55
- const generation = this.generation;
56
- let released = false;
57
- return this.reschedule().then(() => ({ release: async () => {
58
- if (released) return;
59
- released = true;
60
- if (generation !== this.generation) return;
61
- this.activeLeases = Math.max(0, this.activeLeases - 1);
62
- await this.reschedule();
63
- } }), async (error) => {
64
- released = true;
65
- if (generation !== this.generation) throw error;
66
- this.activeLeases = Math.max(0, this.activeLeases - 1);
67
- await this.reschedule().catch(this.onBackgroundError);
68
- throw error;
69
- });
70
- }
71
- /** Run a promise while holding a lease. Intended for host adapters, not EDA internals. */
72
- async runWhileActive(fn) {
73
- const lease = await this.acquire();
74
- try {
75
- return await fn();
76
- } finally {
77
- await lease.release();
78
- }
79
- }
80
- /**
81
- * Track an already-forked Effect fiber as active host work until it settles.
82
- *
83
- * Use this with `ManagedRuntime.runFork(...)` when the fiber needs an already
84
- * built runtime context. The returned lease can be released manually, but it
85
- * is normally released by the fiber observer.
86
- */
87
- async trackFiber(fiber) {
88
- const lease = await this.acquire();
89
- fiber.addObserver(() => {
90
- this.waitUntil(lease.release().catch((error) => {
91
- this.onBackgroundError(error);
92
- }));
93
- });
94
- if (fiber.pollUnsafe() !== void 0) await lease.release();
95
- return lease;
96
- }
97
- /**
98
- * Fork an Effect as host-tracked active work.
99
- *
100
- * This mirrors Effect's host-runner pattern: observe the root fiber and release
101
- * the alarm lease when it settles. It deliberately does not patch Effect
102
- * internals or try to classify runnable vs suspended fibers.
103
- */
104
- async fork(effect) {
105
- const fiber = Effect.runFork(effect);
106
- await this.trackFiber(fiber);
107
- return fiber;
108
- }
109
- /** Handle the Durable Object `alarm()` callback and re-arm while work remains. */
110
- alarm() {
111
- return this.reschedule();
112
- }
113
- /** Permanently stop the heartbeat and prevent later lease releases from re-arming it. */
114
- shutdown() {
115
- this.shutdownRequested = true;
116
- this.generation += 1;
117
- this.activeLeases = 0;
118
- return this.reschedule();
119
- }
120
- /** Start a fresh lease generation after the host intentionally resets its durable state. */
121
- restart() {
122
- this.shutdownRequested = false;
123
- }
124
- waitUntil(promise) {
125
- if (this.background !== void 0) {
126
- this.background.waitUntil(promise);
127
- return;
128
- }
129
- }
130
- reschedule() {
131
- this.scheduleTail = this.scheduleTail.catch(() => void 0).then(() => this.syncAlarm());
132
- return this.scheduleTail;
133
- }
134
- async syncAlarm() {
135
- if (this.shutdownRequested || this.activeLeases === 0) {
136
- await this.storage.deleteAlarm();
137
- return;
138
- }
139
- const desiredAt = this.now() + this.intervalMs;
140
- const currentAt = await this.storage.getAlarm();
141
- if (currentAt === null || currentAt > desiredAt) await this.storage.setAlarm(desiredAt);
142
- }
143
- };
144
- //#endregion
145
- //#region src/durable-object-sink-checkpoints.ts
146
- /**
147
- * Durable Object SQLite adapter for EDA sink checkpoints.
148
- *
149
- * Checkpoint SQL stays in the host layer for the same reason session storage SQL
150
- * does: framework sink code should depend on checkpoint semantics, not table access.
151
- */
152
- var DurableObjectSinkCheckpointStore = class DurableObjectSinkCheckpointStore {
153
- /** Ensure the fixed `_eda_sink_cursors` table exists during host startup. */
154
- static migrate = (storage) => migrateSinkCheckpointStore(storage);
155
- /** Build the semantic checkpoint store over native DO SQLite. */
156
- static make = (storage) => makeDurableObjectSinkCheckpointStore(storage);
157
- static layer = (storage) => Layer.effect(SinkCheckpointStore, DurableObjectSinkCheckpointStore.make(storage));
158
- };
159
- /** Create the sink checkpoint table inside the current EDA storage schema. */
160
- const migrateSinkCheckpointStore = (storage) => Effect.try({
161
- try: () => {
162
- storage.sql.exec(`
163
- CREATE TABLE IF NOT EXISTS _eda_sink_cursors (
164
- sink_name TEXT PRIMARY KEY,
165
- after_seq INTEGER NOT NULL,
166
- payload_json TEXT NOT NULL
167
- )
168
- `);
169
- },
170
- catch: (error) => sinkCheckpointError("migrating SinkCheckpointStore", error)
171
- });
172
- /** Interpret checkpoint load/save/commit with idempotent upserts. */
173
- const makeDurableObjectSinkCheckpointStore = (storage) => Effect.gen(function* () {
174
- yield* DurableObjectSinkCheckpointStore.migrate(storage);
175
- const { sql } = storage;
176
- return {
177
- load: (sinkName) => Effect.try({
178
- try: () => {
179
- const row = sql.exec(`SELECT after_seq, payload_json FROM _eda_sink_cursors WHERE sink_name = ?`, sinkName).toArray()[0];
180
- return row === void 0 ? {
181
- afterSeq: SequenceNumber.make(0),
182
- payload: void 0
183
- } : {
184
- afterSeq: SequenceNumber.make(row.after_seq),
185
- payload: JSON.parse(row.payload_json)
186
- };
187
- },
188
- catch: (error) => sinkCheckpointError("reading sink checkpoint", error)
189
- }),
190
- saveState: (sinkName, payload) => Effect.try({
191
- try: () => {
192
- sql.exec(`
193
- INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)
194
- VALUES (?, 0, ?)
195
- ON CONFLICT(sink_name) DO UPDATE SET
196
- payload_json = excluded.payload_json
197
- `, sinkName, JSON.stringify(payload));
198
- },
199
- catch: (error) => sinkCheckpointError("saving sink checkpoint state", error)
200
- }),
201
- commit: (sinkName, afterSeq, payload) => Effect.try({
202
- try: () => {
203
- sql.exec(`
204
- INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)
205
- VALUES (?, ?, ?)
206
- ON CONFLICT(sink_name) DO UPDATE SET
207
- after_seq = excluded.after_seq,
208
- payload_json = excluded.payload_json
209
- `, sinkName, afterSeq, JSON.stringify(payload ?? { updatedAtMs: Date.now() }));
210
- },
211
- catch: (error) => sinkCheckpointError("committing sink checkpoint", error)
212
- })
213
- };
214
- });
215
- const sinkCheckpointError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
216
- //#endregion
217
- //#region src/durable-object-store.ts
218
- /** Safe payload ceiling below the Durable Object SQLite 2 MB value limit. */
219
- /** Conservative JSON limit below the Durable Object SQLite per-value ceiling. */
220
- const durableObjectSerializedJsonHardCapBytes = 15e5;
221
- const ProjectionPayload = Schema.Record(Schema.String, Schema.Unknown);
222
- const AdmittedCommandProjection = Schema.Struct({
223
- commandId: Schema.Unknown,
224
- idempotencyKey: Schema.optionalKey(Schema.Unknown)
225
- });
226
- /** Single squashed schema version for the current pre-release DO store. */
227
- const durableObjectSessionStoreSchemaVersion = 1;
228
- const jsonEncoder = new TextEncoder();
229
- /**
230
- * Bound one synchronous DO SQLite event-log read/decode to a small CPU and memory slice.
231
- *
232
- * A single logical event can already approach the per-row JSON hard cap, and logical decode may
233
- * touch sidecar rows. Sixteen rows keeps worst-case page memory materially below isolate limits
234
- * while still amortizing SQL cursor setup for normal small framework events. Revisit with page
235
- * duration/byte telemetry before increasing.
236
- */
237
- const durableObjectEventReadPageRows = 16;
238
- /**
239
- * Durable Object SQLite-backed implementation of the semantic `EDASessionStore`.
240
- *
241
- * This adapter is the only place EDA framework storage code touches DO SQL. It
242
- * translates domain append intent into synchronous SQLite writes while keeping
243
- * `SessionState` and runners SQL-agnostic.
244
- */
245
- var DurableObjectSessionStore = class DurableObjectSessionStore {
246
- /** Run the single squashed framework migration for the current pre-release schema. */
247
- static migrate = (storage) => migrateDurableObjectSessionStore(storage);
248
- /** Build a session-scoped store after migrations have completed. */
249
- static make = ({ sessionId, storage }) => Effect.gen(function* () {
250
- yield* DurableObjectSessionStore.migrate(storage);
251
- return makeDurableObjectSessionStore(sessionId, storage);
252
- });
253
- /** Layer constructor used by the Durable Object host runtime graph. */
254
- static layer = (options) => Layer.effect(EDASessionStore, DurableObjectSessionStore.make(options));
255
- };
256
- /**
257
- * Create all framework-owned tables in one idempotent startup step.
258
- *
259
- * The project is still pre-release, so this remains a squashed version-1 schema
260
- * rather than a chain of compatibility migrations.
261
- */
262
- const migrateDurableObjectSessionStore = (storage) => Effect.try({
263
- try: () => storage.transactionSync(() => {
264
- const { sql } = storage;
265
- sql.exec(`
266
- CREATE TABLE IF NOT EXISTS _eda_schema_migrations (
267
- id INTEGER PRIMARY KEY,
268
- applied_at TEXT NOT NULL DEFAULT (datetime('now'))
269
- )
270
- `);
271
- if ((sql.exec("SELECT COALESCE(MAX(id), 0) AS version FROM _eda_schema_migrations").one().version ?? 0) < durableObjectSessionStoreSchemaVersion) {
272
- sql.exec(`
273
- CREATE TABLE IF NOT EXISTS _eda_event_log (
274
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
275
- event_id TEXT NOT NULL UNIQUE,
276
- namespace TEXT NOT NULL,
277
- type TEXT NOT NULL,
278
- schema_version INTEGER NOT NULL,
279
- created_at_ms INTEGER NOT NULL,
280
- trace_json TEXT NOT NULL,
281
- fact_json TEXT NOT NULL
282
- )
283
- `);
284
- sql.exec(`
285
- CREATE INDEX IF NOT EXISTS _eda_event_log_namespace_type_seq_idx
286
- ON _eda_event_log(namespace, type, seq)
287
- `);
288
- sql.exec(`
289
- CREATE TABLE IF NOT EXISTS _eda_command_state (
290
- command_id TEXT PRIMARY KEY,
291
- admitted_seq INTEGER NOT NULL,
292
- status TEXT NOT NULL,
293
- idempotency_key TEXT,
294
- payload_json TEXT NOT NULL
295
- )
296
- `);
297
- sql.exec(`
298
- CREATE TABLE IF NOT EXISTS _eda_command_inputs (
299
- command_id TEXT PRIMARY KEY,
300
- admitted_seq INTEGER NOT NULL UNIQUE,
301
- payload_json TEXT NOT NULL
302
- )
303
- `);
304
- sql.exec(`
305
- CREATE INDEX IF NOT EXISTS _eda_command_state_status_seq_idx
306
- ON _eda_command_state(status, admitted_seq)
307
- `);
308
- sql.exec(`
309
- CREATE UNIQUE INDEX IF NOT EXISTS _eda_command_state_idempotency_idx
310
- ON _eda_command_state(idempotency_key) WHERE idempotency_key IS NOT NULL
311
- `);
312
- sql.exec(`
313
- CREATE TABLE IF NOT EXISTS _eda_context_messages (
314
- message_id TEXT PRIMARY KEY,
315
- context_seq INTEGER NOT NULL UNIQUE,
316
- payload_json TEXT NOT NULL
317
- )
318
- `);
319
- sql.exec(`
320
- CREATE INDEX IF NOT EXISTS _eda_context_messages_context_seq_idx
321
- ON _eda_context_messages(context_seq)
322
- `);
323
- sql.exec(`
324
- CREATE TABLE IF NOT EXISTS _eda_context_summaries (
325
- summary_id TEXT PRIMARY KEY,
326
- created_seq INTEGER NOT NULL UNIQUE,
327
- payload_json TEXT NOT NULL
328
- )
329
- `);
330
- sql.exec(`
331
- CREATE INDEX IF NOT EXISTS _eda_context_summaries_created_seq_idx
332
- ON _eda_context_summaries(created_seq)
333
- `);
334
- sql.exec(`
335
- CREATE TABLE IF NOT EXISTS _eda_reducer_checkpoints (
336
- reducer_name TEXT PRIMARY KEY,
337
- schema_version INTEGER NOT NULL,
338
- through_seq INTEGER NOT NULL,
339
- payload_json TEXT NOT NULL,
340
- updated_at_ms INTEGER NOT NULL
341
- )
342
- `);
343
- sql.exec(`
344
- CREATE TABLE IF NOT EXISTS _eda_sink_cursors (
345
- sink_name TEXT PRIMARY KEY,
346
- after_seq INTEGER NOT NULL,
347
- payload_json TEXT NOT NULL
348
- )
349
- `);
350
- sql.exec("INSERT INTO _eda_schema_migrations (id) VALUES (?)", durableObjectSessionStoreSchemaVersion);
351
- }
352
- }),
353
- catch: (error) => durableStoreError("migrating DurableObjectSessionStore", error)
354
- });
355
- /**
356
- * Interpret the semantic store API with native DO SQLite.
357
- *
358
- * All writes that affect durable ordering happen inside `transactionSync`; replay
359
- * and lookup reads stay synchronous SQL wrapped in Effect boundaries.
360
- */
361
- const makeDurableObjectSessionStore = (sessionId, storage) => {
362
- const { sql } = storage;
363
- const ensureSession = (event) => {
364
- if (event.sessionId !== sessionId) throw new Error(`DurableObjectSessionStore is scoped to session ${sessionId}; received ${event.sessionId}`);
365
- };
366
- /**
367
- * Insert one append entry or return its existing idempotent event position.
368
- *
369
- * The event row is the sequence allocator. Artifact/projection writes happen
370
- * only for newly inserted events, preventing duplicate appends from advancing
371
- * body rows or metadata.
372
- */
373
- const insertOrRead = (entry) => {
374
- const { event } = entry;
375
- ensureSession(event);
376
- const existing = readCommittedByEventIdOptional(sql, sessionId, event.eventId);
377
- if (existing !== void 0) return existing;
378
- const encoded = encodeEventLogRow(event);
379
- sql.exec(`
380
- INSERT INTO _eda_event_log (
381
- event_id,
382
- namespace,
383
- type,
384
- schema_version,
385
- created_at_ms,
386
- trace_json,
387
- fact_json
388
- ) VALUES (?, ?, ?, ?, ?, ?, ?)
389
- `, encoded.eventId, encoded.namespace, encoded.type, encoded.schemaVersion, encoded.createdAtMs, encoded.traceJson, encoded.factJson);
390
- const row = readEventLogRowByEventId(sql, event.eventId);
391
- applySynchronousProjections(sql, entry, SequenceNumber.make(row.seq), encoded.factJson);
392
- return rowToCommittedDurableEvent(sql, row, sessionId);
393
- };
394
- /** Execute an entire append batch as one synchronous SQLite transaction. */
395
- const append = (batch) => Effect.try({
396
- try: () => storage.transactionSync(() => batch.entries.map(insertOrRead)),
397
- catch: (error) => durableStoreError("appending DurableObjectSessionStore batch", error)
398
- }).pipe(Effect.tap((committed) => annotateEdaSpan(committedBatchAttributes(committed))));
399
- return {
400
- append,
401
- eventsAfter: (afterSeq) => makeCommittedEventStream(sql, sessionId, afterSeq),
402
- loadCommittedEventsBySeq: (seqs) => Effect.try({
403
- try: () => uniqueSequenceNumbers(seqs).sort((left, right) => left - right).map((seq) => readCommittedBySeq(sql, sessionId, seq)),
404
- catch: (error) => durableStoreError("loading DurableObjectSessionStore events by seq", error)
405
- }),
406
- findCommandAdmission: (input) => Effect.try({
407
- try: () => {
408
- const row = findCommandAdmissionRow(sql, input.commandId, input.idempotencyKey);
409
- return row === void 0 ? void 0 : readCommittedBySeq(sql, sessionId, row.admitted_seq);
410
- },
411
- catch: (error) => durableStoreError("finding command admission", error)
412
- }),
413
- loadSummaryArtifact: (summaryId) => Effect.try({
414
- try: () => readSummaryPayloadOptional(sql, summaryId),
415
- catch: (error) => durableStoreError("loading DurableObjectSessionStore summary", error)
416
- }),
417
- loadReducerCheckpoint: (name) => Effect.try({
418
- try: () => readReducerCheckpoint(sql, name),
419
- catch: (error) => durableStoreError(`loading DurableObjectSessionStore reducer checkpoint ${name}`, error)
420
- }),
421
- saveReducerCheckpoint: (checkpoint) => Effect.try({
422
- try: () => writeReducerCheckpoint(sql, checkpoint),
423
- catch: (error) => durableStoreError(`saving DurableObjectSessionStore reducer checkpoint ${checkpoint.name}`, error)
424
- }),
425
- saveReducerCheckpoints: (checkpoints) => Effect.try({
426
- try: () => storage.transactionSync(() => checkpoints.forEach((checkpoint) => writeReducerCheckpoint(sql, checkpoint))),
427
- catch: (error) => durableStoreError("saving DurableObjectSessionStore reducer checkpoints", error)
428
- })
429
- };
430
- };
431
- const makeCommittedEventStream = (sql, sessionId, afterSeq) => Stream.fromPull(Effect.sync(() => {
432
- let cursor = {
433
- afterSeq,
434
- throughSeq: void 0
435
- };
436
- let done = false;
437
- return Effect.gen(function* () {
438
- if (done) return yield* Cause.done();
439
- yield* Effect.yieldNow;
440
- const page = yield* readCommittedEventPage(sql, sessionId, cursor);
441
- if (page.events.length === 0) {
442
- done = true;
443
- return yield* Cause.done();
444
- }
445
- if (Option.isSome(page.next)) cursor = page.next.value;
446
- else done = true;
447
- return page.events;
448
- });
449
- }));
450
- const readCommittedEventPage = (sql, sessionId, cursor) => Effect.try({
451
- try: () => {
452
- const throughSeq = cursor.throughSeq ?? readEventLogHead(sql);
453
- if (cursor.afterSeq >= throughSeq) return {
454
- events: [],
455
- next: Option.none()
456
- };
457
- const events = sql.exec(`
458
- SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
459
- FROM _eda_event_log
460
- WHERE seq > ? AND seq <= ?
461
- ORDER BY seq ASC
462
- LIMIT ?
463
- `, cursor.afterSeq, throughSeq, durableObjectEventReadPageRows).toArray().map((row) => rowToCommittedDurableEvent(sql, row, sessionId));
464
- const lastSeq = events.at(-1)?.position.seq ?? cursor.afterSeq;
465
- return {
466
- events,
467
- next: lastSeq < throughSeq ? Option.some({
468
- afterSeq: lastSeq,
469
- throughSeq
470
- }) : Option.none()
471
- };
472
- },
473
- catch: (error) => durableStoreError("replaying DurableObjectSessionStore events", error)
474
- });
475
- const readEventLogHead = (sql) => SequenceNumber.make(sql.exec(`
476
- SELECT COALESCE(MAX(seq), 0) AS head
477
- FROM _eda_event_log
478
- `).one().head ?? 0);
479
- const uniqueSequenceNumbers = (seqs) => Array.from(new Set(seqs.map((seq) => Number(seq)))).map((seq) => SequenceNumber.make(seq));
480
- const readEventLogRowByEventId = (sql, eventId) => sql.exec(`
481
- SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
482
- FROM _eda_event_log
483
- WHERE event_id = ?
484
- `, eventId).one();
485
- const readCommittedByEventIdOptional = (sql, sessionId, eventId) => {
486
- const row = sql.exec(`
487
- SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
488
- FROM _eda_event_log
489
- WHERE event_id = ?
490
- `, eventId).toArray()[0];
491
- return row === void 0 ? void 0 : rowToCommittedDurableEvent(sql, row, sessionId);
492
- };
493
- const readReducerCheckpoint = (sql, name) => {
494
- const row = sql.exec(`
495
- SELECT reducer_name, schema_version, through_seq, payload_json, updated_at_ms
496
- FROM _eda_reducer_checkpoints
497
- WHERE reducer_name = ?
498
- `, name).toArray()[0];
499
- return row === void 0 ? void 0 : {
500
- name: row.reducer_name,
501
- schemaVersion: row.schema_version,
502
- throughSeq: SequenceNumber.make(row.through_seq),
503
- payload: JSON.parse(row.payload_json),
504
- updatedAtMs: row.updated_at_ms
505
- };
506
- };
507
- const writeReducerCheckpoint = (sql, checkpoint) => {
508
- sql.exec(`
509
- INSERT INTO _eda_reducer_checkpoints (
510
- reducer_name,
511
- schema_version,
512
- through_seq,
513
- payload_json,
514
- updated_at_ms
515
- ) VALUES (?, ?, ?, ?, ?)
516
- ON CONFLICT(reducer_name) DO UPDATE SET
517
- schema_version = excluded.schema_version,
518
- through_seq = excluded.through_seq,
519
- payload_json = excluded.payload_json,
520
- updated_at_ms = excluded.updated_at_ms
521
- `, checkpoint.name, checkpoint.schemaVersion, checkpoint.throughSeq, stringifyJsonForColumn(checkpoint.payload, "_eda_reducer_checkpoints.payload_json"), checkpoint.updatedAtMs);
522
- };
523
- const readMessagePayloadByContextSeq = (sql, contextSeq) => {
524
- const message = sql.exec(`
525
- SELECT context_seq, payload_json
526
- FROM _eda_context_messages
527
- WHERE context_seq = ?
528
- `, contextSeq).toArray()[0];
529
- if (message === void 0) throw new Error(`Context message at seq ${contextSeq} missing from _eda_context_messages`);
530
- return message;
531
- };
532
- const readCommittedBySeq = (sql, sessionId, seq) => {
533
- return rowToCommittedDurableEvent(sql, sql.exec(`
534
- SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
535
- FROM _eda_event_log
536
- WHERE seq = ?
537
- `, seq).one(), sessionId);
538
- };
539
- const rowToCommittedDurableEvent = (sql, row, sessionId) => CommittedDurableEvent.make({
540
- position: durablePosition(SequenceNumber.make(row.seq)),
541
- event: decodeDurableEvent({
542
- namespace: row.namespace,
543
- type: row.type,
544
- schemaVersion: row.schema_version,
545
- durability: "durable",
546
- eventId: row.event_id,
547
- sessionId,
548
- createdAtMs: row.created_at_ms,
549
- trace: JSON.parse(row.trace_json),
550
- payload: readLogicalPayload(sql, row)
551
- })
552
- });
553
- const decodeDurableEvent = (input) => {
554
- const event = Schema.decodeUnknownSync(DurableEventEnvelope)(input);
555
- return event.namespace === effectDurableAgentNamespace ? decodeUnknownEDADurableEventSync(event) : event;
556
- };
557
- const encodeEventLogRow = (event) => {
558
- const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
559
- return {
560
- eventId: encoded.eventId,
561
- namespace: encoded.namespace,
562
- type: encoded.type,
563
- schemaVersion: encoded.schemaVersion,
564
- createdAtMs: encoded.createdAtMs,
565
- traceJson: stringifyJsonForColumn(encoded.trace, "_eda_event_log.trace_json"),
566
- factJson: stringifyJsonForColumn(eventLogFactPayload(encoded.namespace, encoded.type, encoded.payload), "_eda_event_log.fact_json")
567
- };
568
- };
569
- const readLogicalPayload = (sql, row) => {
570
- if (row.namespace !== effectDurableAgentNamespace) return JSON.parse(row.fact_json);
571
- if (row.type === commandAdmittedEventType) return { command: readCommandInputPayload(sql, readCommandIdFromFact(row)) };
572
- if (contextMessageEventTypes.has(row.type)) return JSON.parse(readMessagePayloadByContextSeq(sql, row.seq).payload_json);
573
- if (row.type === summaryCreatedEventType) return {
574
- ...JSON.parse(row.fact_json),
575
- summary: readSummaryPayloadFromCreatedSeq(sql, row.seq)
576
- };
577
- return JSON.parse(row.fact_json);
578
- };
579
- const eventLogFactPayload = (namespace, type, payload) => {
580
- if (namespace !== effectDurableAgentNamespace || typeof payload !== "object" || payload === null) return payload;
581
- const record = payload;
582
- switch (type) {
583
- case commandAdmittedEventType: return { command: commandFact(record.command) };
584
- case systemMessageCommittedEventType: return pick(record, ["messageId"]);
585
- case userMessageCommittedEventType: return pick(record, ["commandId", "messageId"]);
586
- case steeringMessageQueuedEventType: return pick(record, [
587
- "commandId",
588
- "messageId",
589
- "runId"
590
- ]);
591
- case assistantMessageCommittedEventType:
592
- case assistantMessageImportedEventType: return pick(record, [
593
- "messageId",
594
- "runId",
595
- "turnId",
596
- "inferenceId"
597
- ]);
598
- case assistantPartialCommittedEventType: return pick(record, [
599
- "messageId",
600
- "runId",
601
- "turnId",
602
- "inferenceId",
603
- "reason"
604
- ]);
605
- case summaryCreatedEventType: return pick(record, [
606
- "compactionId",
607
- "summaryId",
608
- "sourceFromSeq",
609
- "sourceToSeq"
610
- ]);
611
- default: return payload;
612
- }
613
- };
614
- const commandFact = (command) => {
615
- if (typeof command !== "object" || command === null) return command;
616
- const record = command;
617
- return record._tag === "SubmitMessage" ? pick(record, [
618
- "_tag",
619
- "commandId",
620
- "disposition",
621
- "idempotencyKey"
622
- ]) : command;
623
- };
624
- const pick = (record, keys) => {
625
- const out = {};
626
- for (const key of keys) if (record[key] !== void 0) out[key] = record[key];
627
- return out;
628
- };
629
- const readCommandIdFromFact = (row) => {
630
- const commandId = JSON.parse(row.fact_json).command?.commandId;
631
- if (typeof commandId !== "string") throw new Error(`CommandAdmitted fact at seq ${row.seq} missing command.commandId`);
632
- return commandId;
633
- };
634
- const readCommandInputPayload = (sql, commandId) => {
635
- const row = sql.exec(`
636
- SELECT payload_json
637
- FROM _eda_command_inputs
638
- WHERE command_id = ?
639
- `, commandId).toArray()[0];
640
- if (row === void 0) throw new Error(`Command input ${commandId} missing from _eda_command_inputs`);
641
- return JSON.parse(row.payload_json);
642
- };
643
- const readSummaryPayloadOptional = (sql, summaryId) => {
644
- const row = sql.exec(`
645
- SELECT payload_json
646
- FROM _eda_context_summaries
647
- WHERE summary_id = ?
648
- `, summaryId).toArray()[0];
649
- return row === void 0 ? void 0 : Schema.decodeUnknownSync(CompactionSummaryArtifact)(JSON.parse(row.payload_json));
650
- };
651
- const readSummaryPayloadFromCreatedSeq = (sql, createdSeq) => {
652
- const row = sql.exec(`
653
- SELECT payload_json
654
- FROM _eda_context_summaries
655
- WHERE created_seq = ?
656
- `, createdSeq).toArray()[0];
657
- if (row === void 0) throw new Error(`SummaryCreated at seq ${createdSeq} missing from _eda_context_summaries`);
658
- return JSON.parse(row.payload_json);
659
- };
660
- /**
661
- * Maintain bounded storage projections in the same transaction as the event.
662
- *
663
- * These rows are durability aids, not a second source of lifecycle truth: event
664
- * order still comes from `_eda_event_log.seq`, while projections make command
665
- * lookup and body-sidecar hydration bounded.
666
- */
667
- const applySynchronousProjections = (sql, entry, seq, factJson) => {
668
- const { event } = entry;
669
- if (event.namespace !== effectDurableAgentNamespace) return;
670
- writeCommandProjection(sql, event, seq, factJson);
671
- writeCommandInputProjection(sql, event, seq);
672
- writeMessageProjection(sql, event, seq);
673
- writeSummaryProjection(sql, event, seq);
674
- writeContextRebaseProjection(sql, event, seq);
675
- };
676
- const writeCommandProjection = (sql, event, seq, factJson) => {
677
- const payload = Schema.decodeUnknownSync(ProjectionPayload)(event.payload);
678
- switch (event.type) {
679
- case commandAdmittedEventType: {
680
- const command = Schema.decodeUnknownSync(AdmittedCommandProjection)(payload.command);
681
- const commandId = command.commandId;
682
- if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
683
- sql.exec(`
684
- INSERT INTO _eda_command_state (
685
- command_id,
686
- admitted_seq,
687
- status,
688
- idempotency_key,
689
- payload_json
690
- ) VALUES (?, ?, ?, ?, ?)
691
- ON CONFLICT(command_id) DO UPDATE SET
692
- admitted_seq = excluded.admitted_seq,
693
- status = excluded.status,
694
- idempotency_key = excluded.idempotency_key,
695
- payload_json = excluded.payload_json
696
- `, commandId, seq, "admitted", command.idempotencyKey ?? null, factJson);
697
- return;
698
- }
699
- case commandStartedEventType:
700
- writeCommandStatus(sql, payload.commandId, seq, "started", factJson);
701
- return;
702
- case commandCompletedEventType:
703
- writeCommandStatus(sql, payload.commandId, seq, "completed", factJson);
704
- return;
705
- case commandFailedEventType:
706
- writeCommandStatus(sql, payload.commandId, seq, "failed", factJson);
707
- return;
708
- case commandCancelledEventType:
709
- writeCommandStatus(sql, payload.commandId, seq, "cancelled", factJson);
710
- return;
711
- default: return;
712
- }
713
- };
714
- const writeCommandStatus = (sql, commandId, seq, status, payloadJson) => {
715
- if (commandId === void 0) throw new Error(`${status} command event missing commandId`);
716
- sql.exec(`
717
- INSERT INTO _eda_command_state (
718
- command_id,
719
- admitted_seq,
720
- status,
721
- idempotency_key,
722
- payload_json
723
- ) VALUES (?, ?, ?, NULL, ?)
724
- ON CONFLICT(command_id) DO UPDATE SET
725
- status = excluded.status,
726
- payload_json = excluded.payload_json
727
- `, commandId, seq, status, payloadJson);
728
- };
729
- const writeCommandInputProjection = (sql, event, seq) => {
730
- if (event.type !== commandAdmittedEventType) return;
731
- const command = Schema.encodeSync(DurableEventEnvelope)(event).payload.command;
732
- const commandId = command?.commandId;
733
- if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
734
- sql.exec(`
735
- INSERT INTO _eda_command_inputs (
736
- command_id,
737
- admitted_seq,
738
- payload_json
739
- ) VALUES (?, ?, ?)
740
- ON CONFLICT(command_id) DO UPDATE SET
741
- admitted_seq = excluded.admitted_seq,
742
- payload_json = excluded.payload_json
743
- `, commandId, seq, stringifyJsonForColumn(command, "_eda_command_inputs.payload_json"));
744
- };
745
- const contextMessageEventTypes = new Set([
746
- systemMessageCommittedEventType,
747
- userMessageCommittedEventType,
748
- steeringMessageQueuedEventType,
749
- assistantMessageCommittedEventType,
750
- assistantMessageImportedEventType,
751
- assistantPartialCommittedEventType
752
- ]);
753
- /** Persist model-visible message bodies with the seq that exposed them to context. */
754
- const writeMessageProjection = (sql, event, seq) => {
755
- if (!contextMessageEventTypes.has(event.type)) return;
756
- const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
757
- const messageId = encoded.payload.messageId;
758
- if (messageId === void 0) throw new Error(`${event.type} missing messageId`);
759
- sql.exec(`
760
- INSERT INTO _eda_context_messages (
761
- message_id,
762
- context_seq,
763
- payload_json
764
- ) VALUES (?, ?, ?)
765
- ON CONFLICT(message_id) DO UPDATE SET
766
- context_seq = excluded.context_seq,
767
- payload_json = excluded.payload_json
768
- `, messageId, seq, stringifyJsonForColumn(encoded.payload, "_eda_context_messages.payload_json"));
769
- };
770
- /**
771
- * Persist a cumulative summary artifact without making it the active context.
772
- *
773
- * `ContextRebased` selects summaries in the framework reduced-state checkpoint;
774
- * failed compactions can leave orphaned summaries without changing future context.
775
- */
776
- const writeSummaryProjection = (sql, event, seq) => {
777
- if (event.type !== summaryCreatedEventType) return;
778
- const payload = event.payload;
779
- const summaryId = payload.summaryId;
780
- if (summaryId === void 0) throw new Error("SummaryCreated missing summaryId");
781
- if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
782
- const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
783
- if (summary.summaryId !== summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
784
- if (summary.compactionId !== payload.compactionId) throw new Error("SummaryCreated compactionId does not match summary payload");
785
- sql.exec(`
786
- INSERT INTO _eda_context_summaries (
787
- summary_id,
788
- created_seq,
789
- payload_json
790
- ) VALUES (?, ?, ?)
791
- ON CONFLICT(summary_id) DO UPDATE SET
792
- created_seq = excluded.created_seq,
793
- payload_json = excluded.payload_json
794
- `, summaryId, seq, stringifyJsonForColumn(summary, "_eda_context_summaries.payload_json"));
795
- };
796
- /** Validate that `ContextRebased` points at a committed summary sidecar. */
797
- const writeContextRebaseProjection = (sql, event, _seq) => {
798
- if (event.type !== contextRebasedEventType) return;
799
- const payload = event.payload;
800
- if (payload.summaryId === void 0) throw new Error("ContextRebased missing summaryId");
801
- const summary = readSummaryPayloadOptional(sql, SummaryId.make(String(payload.summaryId)));
802
- if (summary === void 0) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
803
- if (summary.compactionId !== payload.compactionId) throw new Error("ContextRebased summary compactionId does not match event payload");
804
- if (summary.retainedFromContextSeq !== payload.retainedFromContextSeq) throw new Error("ContextRebased retained cursor does not match summary payload");
805
- };
806
- /**
807
- * Lookup prior command admission through `_eda_command_state` instead of genesis replay.
808
- *
809
- * Idempotency key wins over explicit command id so caller-owned retry keys remain
810
- * the stable dedupe surface for external ingress.
811
- */
812
- const findCommandAdmissionRow = (sql, commandId, idempotencyKey) => {
813
- if (idempotencyKey !== void 0) {
814
- const row = sql.exec(`
815
- SELECT admitted_seq
816
- FROM _eda_command_state
817
- WHERE idempotency_key = ?
818
- `, idempotencyKey).toArray()[0];
819
- if (row !== void 0) return row;
820
- }
821
- if (commandId === void 0) return;
822
- return sql.exec(`
823
- SELECT admitted_seq
824
- FROM _eda_command_state
825
- WHERE command_id = ?
826
- `, commandId).toArray()[0];
827
- };
828
- /** Serialize and size-check one JSON column before it reaches DO SQLite. */
829
- const stringifyJsonForColumn = (value, column) => {
830
- const json = JSON.stringify(value);
831
- if (json === void 0) throw new Error(`${column} value is not JSON serializable`);
832
- const bytes = jsonEncoder.encode(json).byteLength;
833
- if (bytes > 15e5) throw new Error(`${column} serialized JSON is ${bytes} bytes; hard cap is ${durableObjectSerializedJsonHardCapBytes} bytes`);
834
- return json;
835
- };
836
- const durableStoreError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
837
- //#endregion
838
- //#region src/runtime/runtime-layer.ts
839
- /** Compose the platform-neutral runtime with Cloudflare persistence and lifecycle adapters. */
840
- const makeEDADurableObjectRuntimeLayer = ({ config, compactionExecutorLayer, compactionPolicyLayer, keepAlive, modelResolverLayer, promptProjectorLayer, reducers, runSchedulerLayer, sessionEventObserverLayer, sessionId, sinks, storage, toolkit, toolRegistry, tracer }) => {
841
- return makeEDARuntimeLayer({
842
- config,
843
- compactionExecutorLayer,
844
- compactionPolicyLayer,
845
- keepAliveLayer: keepAlive === void 0 ? EDAKeepAlive.Noop : EDAKeepAlive.FromAcquire(() => keepAlive.acquire()),
846
- modelResolverLayer,
847
- promptProjectorLayer,
848
- runSchedulerLayer,
849
- reducerRegistryLayer: EDAReducerRegistry.Live(reducers ?? []),
850
- sessionEventObserverLayer,
851
- sessionId,
852
- sessionStoreLayer: DurableObjectSessionStore.layer({
853
- sessionId,
854
- storage
855
- }),
856
- sinkCheckpointStoreLayer: DurableObjectSinkCheckpointStore.layer(storage),
857
- sinks,
858
- toolkit,
859
- toolRegistry,
860
- tracer
861
- });
862
- };
863
- //#endregion
864
- //#region src/runtime/session-runtime.ts
865
- /** Owns the disposable ManagedRuntime and nothing about WebSocket transport. */
866
- var EDASessionRuntime = class {
867
- options;
868
- keepAlive;
869
- state;
870
- building;
871
- constructor(options) {
872
- this.options = options;
873
- this.keepAlive = options.keepAlive ?? new DurableObjectKeepAlive(options.storage, options.background);
874
- }
875
- static migrate = (storage) => Effect.gen(function* () {
876
- yield* DurableObjectSessionStore.migrate(storage);
877
- yield* DurableObjectSinkCheckpointStore.migrate(storage);
878
- });
879
- isReady(sessionId) {
880
- return this.state?.sessionId === sessionId;
881
- }
882
- async prepare(sessionId) {
883
- await this.get(sessionId);
884
- }
885
- async run(sessionId, operation) {
886
- return await (await this.get(sessionId)).runtime.runPromise(Effect.gen(function* () {
887
- return yield* operation(yield* EDARuntime);
888
- }));
889
- }
890
- async alarm(sessionId) {
891
- const resolved = sessionId ?? this.state?.sessionId;
892
- if (resolved !== void 0) await this.get(resolved);
893
- await this.keepAlive.alarm();
894
- }
895
- async destroy() {
896
- await this.keepAlive.shutdown();
897
- await this.dispose();
898
- this.state = void 0;
899
- this.building = void 0;
900
- }
901
- async dispose() {
902
- await this.state?.runtime.dispose();
903
- }
904
- async get(sessionId) {
905
- if (this.state !== void 0) {
906
- if (this.state.sessionId !== sessionId) throw new Error(`EDA session runtime is scoped to session ${this.state.sessionId}; received ${sessionId}`);
907
- return this.state;
908
- }
909
- this.keepAlive.restart();
910
- const building = this.building ?? this.build(sessionId);
911
- this.building = building;
912
- try {
913
- return await building;
914
- } catch (error) {
915
- if (this.building === building) this.building = void 0;
916
- throw error;
917
- }
918
- }
919
- async build(sessionId) {
920
- const runtime = ManagedRuntime.make(makeEDADurableObjectRuntimeLayer({
921
- config: this.options.config,
922
- compactionExecutorLayer: this.options.compactionExecutorLayer,
923
- compactionPolicyLayer: this.options.compactionPolicyLayer,
924
- keepAlive: this.keepAlive,
925
- modelResolverLayer: this.options.modelResolverLayer,
926
- promptProjectorLayer: this.options.promptProjectorLayer,
927
- reducers: this.options.reducers,
928
- runSchedulerLayer: this.options.runSchedulerLayer,
929
- sessionEventObserverLayer: this.options.sessionEventObserverLayer,
930
- sessionId,
931
- sinks: this.options.sinks,
932
- storage: this.options.storage,
933
- toolkit: resolveFactory(this.options.toolkit, sessionId),
934
- toolRegistry: resolveFactory(this.options.toolRegistry, sessionId),
935
- tracer: resolveFactory(this.options.tracer, sessionId)
936
- }));
937
- const state = {
938
- runtime,
939
- sessionId
940
- };
941
- try {
942
- await runtime.context();
943
- this.state = state;
944
- return state;
945
- } catch (error) {
946
- await runtime.dispose().catch(() => void 0);
947
- throw error;
948
- }
949
- }
950
- };
951
- const resolveFactory = (value, sessionId) => typeof value === "function" ? value({ sessionId }) : value;
952
- //#endregion
953
- //#region src/websocket/projection.ts
954
- /** Stable non-empty identity persisted with an app WebSocket projection. */
955
- const EDAWebSocketProjectionId = Schema.NonEmptyString.pipe(Schema.brand("EDAWebSocketProjectionId"));
956
- //#endregion
957
- //#region src/websocket/attachment.ts
958
- /** Versioned state required to resume strict delivery after Durable Object hibernation. */
959
- const EDAWebSocketAttachment = Schema.Struct({
960
- kind: Schema.Literal("eda-events-v2"),
961
- sessionId: SessionId,
962
- subscriberId: SubscriberId,
963
- trace: EDATraceMetadata,
964
- delivery: EDAWebSocketDeliveryCheckpoint,
965
- projection: Schema.optionalKey(Schema.Struct({
966
- id: EDAWebSocketProjectionId,
967
- state: Schema.Unknown
968
- }))
969
- });
970
- /** Decode and classify an attachment read from Cloudflare's structured-clone boundary. */
971
- const decodeWebSocketAttachment = async (input) => {
972
- if (input === null || input === void 0) return { _tag: "Missing" };
973
- try {
974
- return {
975
- _tag: "Decoded",
976
- attachment: await Effect.runPromise(Schema.decodeUnknownEffect(EDAWebSocketAttachment)(input))
977
- };
978
- } catch {
979
- return { _tag: "Malformed" };
980
- }
981
- };
982
- /** Encode before serialization so schema transformations cannot leak into attachments. */
983
- const encodeWebSocketAttachment = (attachment) => Schema.encodeSync(EDAWebSocketAttachment)(attachment);
984
- //#endregion
985
- //#region src/websocket/connection-manager.ts
986
- /**
987
- * Owns Cloudflare WebSockets, hibernation attachments, and interpretation of
988
- * the platform-neutral delivery state machine.
989
- */
990
- var EDAWebSocketConnectionManager = class {
991
- options;
992
- observerLayer = SessionEventObserver.FromHandler((event) => Effect.tryPromise(() => this.fanoutPublishedEvent(event)).pipe(Effect.catchCause((cause) => Effect.logError("EDA WebSocket event observer recovered from a host failure", { cause }))));
993
- sockets = /* @__PURE__ */ new Map();
994
- constructor(options) {
995
- this.options = options;
996
- }
997
- resolveProjection(id) {
998
- if (id === void 0) return void 0;
999
- if (this.options.webSocketProjection?.id === id) return this.options.webSocketProjection;
1000
- }
1001
- async accept(input) {
1002
- const subscriberId = SubscriberId.make(crypto.randomUUID());
1003
- const delivery = makeWebSocketDeliveryState({
1004
- subscriberId,
1005
- resumeSeq: input.afterSeq,
1006
- policy: defaultEDAWebSocketFlowControl
1007
- });
1008
- const state = {
1009
- sessionId: input.sessionId,
1010
- subscriberId,
1011
- trace: input.trace,
1012
- delivery,
1013
- catchUpDeferred: false,
1014
- head: input.afterSeq,
1015
- queue: Promise.resolve(),
1016
- ...input.projectionState === void 0 ? {} : { projectionState: input.projectionState }
1017
- };
1018
- this.sockets.set(input.webSocket, state);
1019
- if (!this.persist(input.webSocket, state)) return;
1020
- if (!await this.send(input.webSocket, state, [deliveryHelloFrame(delivery)])) return;
1021
- if (!await this.prepare(input.webSocket, state)) return;
1022
- await this.enqueue(input.webSocket, state, async () => {
1023
- await this.readAndDeliver(input.webSocket, state, input.afterSeq);
1024
- });
1025
- }
1026
- async message(webSocket, message) {
1027
- if (typeof message !== "string") {
1028
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "binary");
1029
- return;
1030
- }
1031
- if (message === EDA_WEB_SOCKET_PING_MESSAGE) {
1032
- try {
1033
- webSocket.send(EDA_WEB_SOCKET_PONG_MESSAGE);
1034
- } catch {
1035
- this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "send-failed");
1036
- }
1037
- return;
1038
- }
1039
- const state = await this.restore(webSocket);
1040
- if (state === void 0) {
1041
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1042
- return;
1043
- }
1044
- const frame = await Effect.runPromise(this.decodeClientMessage(message, state).pipe(Effect.option));
1045
- if (frame._tag === "None") {
1046
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1047
- return;
1048
- }
1049
- const clientFrame = frame.value;
1050
- if (clientFrame._tag === "ping") return;
1051
- if (!await this.prepare(webSocket, state)) return;
1052
- await this.enqueue(webSocket, state, async () => {
1053
- await this.interpret(webSocket, state, onClientAck(state.delivery, clientFrame, Date.now()));
1054
- });
1055
- }
1056
- closed(webSocket) {
1057
- this.sockets.delete(webSocket);
1058
- }
1059
- async flushDeferredCatchUp(sessionId) {
1060
- const deliveries = [];
1061
- for (const [webSocket, state] of this.sockets) {
1062
- if (state.sessionId !== sessionId || !state.catchUpDeferred) continue;
1063
- deliveries.push(this.enqueue(webSocket, state, async () => {
1064
- if (!state.catchUpDeferred) return;
1065
- state.catchUpDeferred = false;
1066
- await this.readAndDeliver(webSocket, state, state.delivery.sentDurableThroughSeq);
1067
- }));
1068
- }
1069
- await Promise.all(deliveries);
1070
- }
1071
- async fanoutPublishedEvent(event) {
1072
- const webSockets = new Set([...this.options.getWebSockets?.() ?? [], ...this.sockets.keys()]);
1073
- const deliveries = [];
1074
- for (const webSocket of webSockets) {
1075
- const state = await this.restore(webSocket);
1076
- if (state === void 0) continue;
1077
- deliveries.push(this.enqueue(webSocket, state, async () => {
1078
- if (event.event.durability !== "durable") {
1079
- await this.interpret(webSocket, state, onEphemeralEvent(state.delivery, event, Date.now()));
1080
- return;
1081
- }
1082
- state.head = SequenceNumber.make(Math.max(state.head, event.position.seq));
1083
- if (event.position.seq <= state.delivery.sentDurableThroughSeq) return;
1084
- if (event.position.seq === state.delivery.sentDurableThroughSeq + 1) {
1085
- await this.interpret(webSocket, state, onDurableEvents(state.delivery, [event], state.head, Date.now()));
1086
- return;
1087
- }
1088
- if (!this.options.isSessionReady(state.sessionId)) {
1089
- state.catchUpDeferred = true;
1090
- return;
1091
- }
1092
- await this.readAndDeliver(webSocket, state, state.delivery.sentDurableThroughSeq);
1093
- }));
1094
- }
1095
- await Promise.all(deliveries);
1096
- }
1097
- async restore(webSocket) {
1098
- const existing = this.sockets.get(webSocket);
1099
- if (existing !== void 0) return existing;
1100
- const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
1101
- if (decoded._tag !== "Decoded") {
1102
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1103
- return;
1104
- }
1105
- const attachment = decoded.attachment;
1106
- const projectionState = attachment.projection === void 0 ? void 0 : await this.decodeProjectionState(attachment.projection.id, attachment.projection.state);
1107
- if (attachment.projection !== void 0 && projectionState === void 0) {
1108
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1109
- return;
1110
- }
1111
- const state = {
1112
- sessionId: attachment.sessionId,
1113
- subscriberId: attachment.subscriberId,
1114
- trace: attachment.trace,
1115
- delivery: restoreWebSocketDeliveryState({
1116
- subscriberId: attachment.subscriberId,
1117
- policy: defaultEDAWebSocketFlowControl,
1118
- checkpoint: attachment.delivery
1119
- }),
1120
- catchUpDeferred: false,
1121
- head: attachment.delivery.sentDurableThroughSeq,
1122
- queue: Promise.resolve(),
1123
- ...projectionState === void 0 ? {} : { projectionState }
1124
- };
1125
- this.sockets.set(webSocket, state);
1126
- return state;
1127
- }
1128
- async prepare(webSocket, state) {
1129
- try {
1130
- await this.options.prepareSession(state.sessionId);
1131
- return this.sockets.get(webSocket) === state;
1132
- } catch (error) {
1133
- await Effect.runPromise(Effect.logError("EDA WebSocket session preparation failed", {
1134
- error,
1135
- subscriberId: state.subscriberId
1136
- }));
1137
- this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "subscriber-failed");
1138
- return false;
1139
- }
1140
- }
1141
- async interpret(webSocket, state, result) {
1142
- state.delivery = result.state;
1143
- for (const action of result.actions) switch (action._tag) {
1144
- case "Persist":
1145
- if (!this.persist(webSocket, state)) return false;
1146
- break;
1147
- case "Send":
1148
- if (!await this.send(webSocket, state, action.frames)) return false;
1149
- break;
1150
- case "ReadEventPage":
1151
- if (!await this.readAndDeliver(webSocket, state, action.afterSeq)) return false;
1152
- break;
1153
- case "Close":
1154
- this.close(webSocket, action.code, action.reason);
1155
- return false;
1156
- }
1157
- return true;
1158
- }
1159
- async readAndDeliver(webSocket, state, afterSeq) {
1160
- const page = await this.options.readEventPage({
1161
- afterSeq,
1162
- limit: state.delivery.policy.maxInFlightFrames * state.delivery.policy.maxFrameEvents,
1163
- sessionId: state.sessionId,
1164
- subscriberId: state.subscriberId,
1165
- trace: state.trace
1166
- });
1167
- state.head = SequenceNumber.make(Math.max(state.head, page.head));
1168
- if (page.events.length === 0) return true;
1169
- return await this.interpret(webSocket, state, onDurableEvents(state.delivery, page.events, state.head, Date.now()));
1170
- }
1171
- persist(webSocket, state) {
1172
- try {
1173
- const projection = state.projectionState === void 0 ? void 0 : this.options.webSocketProjection;
1174
- if (state.projectionState !== void 0 && projection === void 0) {
1175
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1176
- return false;
1177
- }
1178
- const attachment = EDAWebSocketAttachment.make({
1179
- kind: "eda-events-v2",
1180
- sessionId: state.sessionId,
1181
- subscriberId: state.subscriberId,
1182
- trace: state.trace,
1183
- delivery: checkpointWebSocketDeliveryState(state.delivery),
1184
- ...state.projectionState === void 0 || projection === void 0 ? {} : { projection: {
1185
- id: projection.id,
1186
- state: projection.encodeState(state.projectionState)
1187
- } }
1188
- });
1189
- webSocket.serializeAttachment(encodeWebSocketAttachment(attachment));
1190
- return true;
1191
- } catch {
1192
- this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "attachment-failed");
1193
- return false;
1194
- }
1195
- }
1196
- send(webSocket, state, frames) {
1197
- return this.sendPrepared(webSocket, state, frames);
1198
- }
1199
- async sendPrepared(webSocket, state, frames) {
1200
- try {
1201
- const encodedFrames = [];
1202
- const followUpActions = [];
1203
- for (const frame of frames) {
1204
- const projected = state.projectionState === void 0 ? void 0 : this.options.webSocketProjection?.encodeServerFrame(frame, state.projectionState);
1205
- if (state.projectionState !== void 0 && projected === void 0) {
1206
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1207
- return false;
1208
- }
1209
- if (projected?._tag === "SuppressAndAck") {
1210
- if (frame._tag !== "events") {
1211
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1212
- return false;
1213
- }
1214
- state.projectionState = projected.state;
1215
- const acknowledged = onHostSuppressedFrame(state.delivery, {
1216
- durableThroughSeq: frame.durableThroughSeq,
1217
- frameId: frame.frameId
1218
- }, Date.now());
1219
- state.delivery = acknowledged.state;
1220
- followUpActions.push(...acknowledged.actions.filter((action) => action._tag !== "Persist"));
1221
- continue;
1222
- }
1223
- if (projected !== void 0) state.projectionState = projected.state;
1224
- const encoded = projected?._tag === "Send" ? projected.frame : encodeEDAWebSocketServerFrame(frame, this.options.webSocketProtocol);
1225
- if (new TextEncoder().encode(encoded).byteLength > state.delivery.policy.maxFrameBytes) {
1226
- this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "frame-too-large");
1227
- return false;
1228
- }
1229
- encodedFrames.push(encoded);
1230
- }
1231
- if (state.projectionState !== void 0 && !this.persist(webSocket, state)) return false;
1232
- for (const encoded of encodedFrames) webSocket.send(encoded);
1233
- if (followUpActions.length > 0) return await this.interpret(webSocket, state, {
1234
- state: state.delivery,
1235
- actions: coalesceFollowUpActions(followUpActions)
1236
- });
1237
- return true;
1238
- } catch {
1239
- this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "send-failed");
1240
- return false;
1241
- }
1242
- }
1243
- enqueue(webSocket, state, operation) {
1244
- const run = async () => {
1245
- try {
1246
- await operation();
1247
- } catch (error) {
1248
- await Effect.runPromise(Effect.logError("EDA WebSocket operation failed", {
1249
- error,
1250
- subscriberId: state.subscriberId
1251
- }));
1252
- this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "subscriber-failed");
1253
- }
1254
- };
1255
- const next = state.queue.then(run);
1256
- state.queue = next;
1257
- return next;
1258
- }
1259
- close(webSocket, code, reason) {
1260
- this.sockets.delete(webSocket);
1261
- try {
1262
- webSocket.close(code, reason);
1263
- } catch {}
1264
- }
1265
- decodeClientMessage(message, state) {
1266
- return state.projectionState === void 0 ? decodeEDAWebSocketClientMessage(message) : this.options.webSocketProjection?.decodeClientMessage(message) ?? Effect.fail("protocol");
1267
- }
1268
- async decodeProjectionState(id, encoded) {
1269
- const projection = this.resolveProjection(id);
1270
- if (projection === void 0) return void 0;
1271
- const decoded = await Effect.runPromise(projection.decodeState(encoded).pipe(Effect.option));
1272
- return decoded._tag === "Some" ? decoded.value : void 0;
1273
- }
1274
- };
1275
- const coalesceFollowUpActions = (actions) => {
1276
- let readAfterSeq;
1277
- const retained = [];
1278
- for (const action of actions) {
1279
- if (action._tag !== "ReadEventPage") {
1280
- retained.push(action);
1281
- continue;
1282
- }
1283
- readAfterSeq = SequenceNumber.make(Math.max(readAfterSeq ?? 0, action.afterSeq));
1284
- }
1285
- return readAfterSeq === void 0 ? retained : [...retained, {
1286
- _tag: "ReadEventPage",
1287
- afterSeq: readAfterSeq
1288
- }];
1289
- };
1290
- //#endregion
1291
- //#region src/session-controller.ts
1292
- /**
1293
- * Public application-facing use cases for one EDA session.
1294
- *
1295
- * Runtime lifecycle belongs to EDASessionRuntime; WebSocket transport belongs
1296
- * to EDAWebSocketConnectionManager. This class only coordinates them.
1297
- */
1298
- var EDASessionController = class {
1299
- runtime;
1300
- webSockets;
1301
- constructor(options) {
1302
- this.webSockets = new EDAWebSocketConnectionManager({
1303
- getWebSockets: options.getWebSockets,
1304
- isSessionReady: (sessionId) => this.runtime.isReady(sessionId),
1305
- prepareSession: (sessionId) => this.prepareSession(sessionId),
1306
- readEventPage: async ({ afterSeq, limit, sessionId, subscriberId, trace }) => await this.runtime.run(sessionId, (eda) => eda.readEventPage(afterSeq, limit).pipe(Effect.withSpan("agent.events.page", hostSpanOptions(trace, {
1307
- "eda.session.id": sessionId,
1308
- "eda.subscriber.id": subscriberId,
1309
- "eda.seq.after": afterSeq
1310
- })))),
1311
- webSocketProjection: options.webSocketProjection,
1312
- webSocketProtocol: options.webSocketProtocol
1313
- });
1314
- this.runtime = new EDASessionRuntime({
1315
- ...options,
1316
- sessionEventObserverLayer: this.webSockets.observerLayer
1317
- });
1318
- }
1319
- static migrate = EDASessionRuntime.migrate;
1320
- submit(input) {
1321
- const trace = input.trace ?? makeRootEDATraceMetadata();
1322
- return this.run(input.sessionId, (eda) => eda.submit(input.command).pipe(Effect.withSpan("agent.command.submit", hostSpanOptions(trace, {
1323
- "eda.session.id": input.sessionId,
1324
- "eda.command.kind": input.command._tag,
1325
- "eda.command.id": input.command.commandId
1326
- }))));
1327
- }
1328
- submitBatch(input) {
1329
- const trace = input.trace ?? makeRootEDATraceMetadata();
1330
- return this.run(input.sessionId, (eda) => eda.submit(input.items).pipe(Effect.withSpan("agent.command.submit", hostSpanOptions(trace, {
1331
- "eda.session.id": input.sessionId,
1332
- "eda.command.submittable_count": input.items.length
1333
- }))));
1334
- }
1335
- submitAndBlock(input) {
1336
- const trace = input.trace ?? makeRootEDATraceMetadata();
1337
- return this.run(input.sessionId, (eda) => eda.submitAndBlock(input.command).pipe(Effect.withSpan("agent.command.submit.wait", hostSpanOptions(trace, {
1338
- "eda.session.id": input.sessionId,
1339
- "eda.command.kind": input.command._tag,
1340
- "eda.command.id": input.command.commandId
1341
- }))));
1342
- }
1343
- blockOnCommand(input) {
1344
- const trace = input.trace ?? makeRootEDATraceMetadata();
1345
- return this.run(input.sessionId, (eda) => eda.blockOnCommand(input.commandId, input.afterSeq ?? SequenceNumber.make(0)).pipe(Effect.withSpan("agent.command.wait", hostSpanOptions(trace, {
1346
- "eda.session.id": input.sessionId,
1347
- "eda.command.id": input.commandId,
1348
- "eda.seq.after": input.afterSeq
1349
- }))));
1350
- }
1351
- snapshot(input) {
1352
- return this.query(input, (eda) => eda.snapshot(), "agent.session.snapshot");
1353
- }
1354
- messages(input) {
1355
- return this.query(input, (eda) => eda.messages(), "agent.messages.list");
1356
- }
1357
- acceptEventWebSocket(input) {
1358
- return this.acceptEventWebSocketUnhosted(input);
1359
- }
1360
- async acceptEventWebSocketUnhosted(input) {
1361
- const prepared = await this.prepareEventWebSocket(input);
1362
- await this.acceptPreparedEventWebSocket({
1363
- ...prepared,
1364
- webSocket: input.webSocket
1365
- });
1366
- }
1367
- async prepareEventWebSocket(input) {
1368
- const projection = this.webSockets.resolveProjection(input.projectionId);
1369
- if (input.projectionId !== void 0 && projection === void 0) throw new Error(`Unsupported EDA WebSocket projection: ${input.projectionId}`);
1370
- const initialized = projection === void 0 ? void 0 : projection.initialize({
1371
- ...input.afterSeq === void 0 ? {} : { requestedAfterSeq: input.afterSeq },
1372
- snapshot: await this.snapshot({
1373
- sessionId: input.sessionId,
1374
- trace: input.trace
1375
- })
1376
- });
1377
- return {
1378
- afterSeq: initialized?.afterSeq ?? input.afterSeq ?? SequenceNumber.make(0),
1379
- sessionId: input.sessionId,
1380
- trace: input.trace ?? makeRootEDATraceMetadata(),
1381
- ...initialized === void 0 ? {} : { projectionState: initialized.state }
1382
- };
1383
- }
1384
- acceptPreparedEventWebSocket(input) {
1385
- return this.webSockets.accept(input);
1386
- }
1387
- webSocketMessage(webSocket, message) {
1388
- return this.webSockets.message(webSocket, message);
1389
- }
1390
- webSocketClose(webSocket) {
1391
- this.webSockets.closed(webSocket);
1392
- }
1393
- webSocketError(webSocket) {
1394
- this.webSockets.closed(webSocket);
1395
- }
1396
- async destroy(_input) {
1397
- await this.runtime.destroy();
1398
- }
1399
- async alarm(input) {
1400
- if (input !== void 0) await this.prepareSession(input.sessionId);
1401
- await this.runtime.alarm(input?.sessionId);
1402
- }
1403
- dispose() {
1404
- return this.runtime.dispose();
1405
- }
1406
- query(input, operation, spanName) {
1407
- const trace = input.trace ?? makeRootEDATraceMetadata();
1408
- return this.run(input.sessionId, (eda) => operation(eda).pipe(Effect.withSpan(spanName, hostSpanOptions(trace, { "eda.session.id": input.sessionId }))));
1409
- }
1410
- async prepareSession(sessionId) {
1411
- await this.runtime.prepare(sessionId);
1412
- await this.webSockets.flushDeferredCatchUp(sessionId);
1413
- }
1414
- async run(sessionId, operation) {
1415
- await this.prepareSession(sessionId);
1416
- return await this.runtime.run(sessionId, operation);
1417
- }
1418
- };
1419
- const hostSpanOptions = (trace, attributes) => ({
1420
- kind: "server",
1421
- attributes: compactSpanAttributes({
1422
- ...trace.attributes,
1423
- ...attributes
1424
- }),
1425
- links: trace.links.map((link) => ({
1426
- span: toEdaExternalSpan(link.context),
1427
- attributes: link.attributes
1428
- })),
1429
- ...trace.parent === null ? {} : { parent: toEdaExternalSpan(trace.parent) }
1430
- });
1431
- //#endregion
1432
- export { EDAWebSocketProjectionId as n, makeEDADurableObjectRuntimeLayer as r, EDASessionController as t };
1433
-
1434
- //# sourceMappingURL=session-controller-COHH8vA6.js.map