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
@@ -0,0 +1,1517 @@
1
+ import { t as DurableObjectSessionStore } from "./durable-object-store-lJkqwvIj.js";
2
+ import "effect-durable-agent/services/prompt-projector";
3
+ import * as Layer from "effect/Layer";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Exit from "effect/Exit";
6
+ import * as Schema from "effect/Schema";
7
+ import { SequenceNumber, SessionId } from "effect-durable-agent/types/core";
8
+ import { EDATraceMetadata, makeRootEDATraceMetadata } from "effect-durable-agent/types/tracing";
9
+ import { EDASessionStoreError } from "effect-durable-agent/services/session-store";
10
+ import { EDARuntime } from "effect-durable-agent/services/runtime";
11
+ import { defaultTranscriptSubscriptionPolicy, emptyTranscriptActiveContentState, foldTranscriptActiveContent, planTranscriptUpdate, readTranscriptSubscription, transcriptActiveContentOf, transcriptSubscriptionBaseOf } from "effect-durable-agent/transcript";
12
+ import * as Result from "effect/Result";
13
+ import { compactSpanAttributes, toEdaExternalSpan } from "effect-durable-agent/services/tracing";
14
+ import { EDADeciderError, encodeDeciderJson, makeEDADeciderRegistry } from "effect-durable-agent/services/decider";
15
+ import * as ManagedRuntime from "effect/ManagedRuntime";
16
+ import { SinkCheckpointStore } from "effect-durable-agent/services/sink-checkpoint-store";
17
+ import { RunSchedulingWakeup } from "effect-durable-agent/services/run-scheduling-wakeup";
18
+ import "effect-durable-agent/services/compaction";
19
+ import { EDAKeepAlive } from "effect-durable-agent/services/keep-alive";
20
+ import { EDAReducerRegistry } from "effect-durable-agent/services/reducer-registry";
21
+ import { makeEDARuntimeLayer } from "effect-durable-agent/services/runtime-layer";
22
+ import { SessionEventObserver } from "effect-durable-agent/services/session-event-observer";
23
+ import { EDATranscriptClientFrame, EDATranscriptDeliveryCheckpoint, EDAWebSocketDeliveryCheckpoint, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, SubscriberId, checkpointTranscriptDelivery, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDATranscriptDeliveryLimits, defaultEDAWebSocketFlowControl, deliveryHelloFrame, edaTranscriptNegotiation, edaTranscriptUpdateFrameText, encodeEDATranscriptServerFrame, encodeEDATranscriptUpdate, encodeEDAWebSocketServerFrame, enqueueTranscriptRequest, laggedCloseReason, makeTranscriptDeliveryState, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent, onHostSuppressedFrame, onTranscriptAck, pumpTranscriptTransfer, restoreTranscriptDeliveryState, restoreWebSocketDeliveryState, startTranscriptUpdate, transcriptAckTimedOut, transcriptDeliveryCapacity, utf8ByteLength } from "effect-durable-agent/websocket";
24
+ /**
25
+ * Alarm-backed in-memory keepalive for a raw Durable Object host.
26
+ *
27
+ * Inbound events (requests, alarms) are what reliably keep an object resident: sessions streaming
28
+ * model responses and sandbox output were evicted 70-140 seconds after their last inbound event.
29
+ * The heartbeat therefore has to be delivered, not just scheduled: an armed alarm is never
30
+ * deleted or postponed when work is released, because finite work (model turns, sink catch-up)
31
+ * releases and re-acquires between steps, and moving the alarm on every step would keep it from
32
+ * ever firing. Only the alarm handler, finding no work left, or {@link shutdown} clears it, so a
33
+ * session that goes idle receives one final heartbeat.
34
+ *
35
+ * The active lease count is intentionally not durable: if the object is evicted
36
+ * or crashes, the fibers the leases represented are gone too, and normal EDA
37
+ * durable recovery must explain any escaped lifecycle boundaries.
38
+ */
39
+ var DurableObjectKeepAlive = class {
40
+ storage;
41
+ background;
42
+ intervalMs;
43
+ now;
44
+ onBackgroundError;
45
+ activeLeases = 0;
46
+ runSchedulingPending = false;
47
+ generation = 0;
48
+ scheduleTail = Promise.resolve();
49
+ shutdownRequested = false;
50
+ constructor(storage, background = void 0, options = {}) {
51
+ this.storage = storage;
52
+ this.background = background;
53
+ this.intervalMs = options.intervalMs ?? 3e4;
54
+ this.now = options.now ?? (() => Date.now());
55
+ this.onBackgroundError = options.onBackgroundError ?? (() => void 0);
56
+ }
57
+ /** Number of active unsettled host roots currently holding the heartbeat. */
58
+ get activeLeaseCount() {
59
+ return this.activeLeases;
60
+ }
61
+ /** Durable delivery work survives the release of every in-memory active lease. */
62
+ setRunSchedulingPending(pending) {
63
+ this.runSchedulingPending = pending;
64
+ return this.reschedule();
65
+ }
66
+ /** Acquire one active-work lease and arm the heartbeat if this is the first lease. */
67
+ acquire() {
68
+ if (this.shutdownRequested) return Promise.reject(/* @__PURE__ */ new Error("DurableObjectKeepAlive is shut down"));
69
+ this.activeLeases += 1;
70
+ const generation = this.generation;
71
+ let released = false;
72
+ return this.reschedule().then(() => ({ release: async () => {
73
+ if (released) return;
74
+ released = true;
75
+ if (generation !== this.generation) return;
76
+ this.activeLeases = Math.max(0, this.activeLeases - 1);
77
+ await this.reschedule();
78
+ } }), async (error) => {
79
+ released = true;
80
+ if (generation !== this.generation) throw error;
81
+ this.activeLeases = Math.max(0, this.activeLeases - 1);
82
+ await this.reschedule().catch(this.onBackgroundError);
83
+ throw error;
84
+ });
85
+ }
86
+ /** Run a promise while holding a lease. Intended for host adapters, not EDA internals. */
87
+ async runWhileActive(fn) {
88
+ const lease = await this.acquire();
89
+ try {
90
+ return await fn();
91
+ } finally {
92
+ await lease.release();
93
+ }
94
+ }
95
+ /**
96
+ * Track an already-forked Effect fiber as active host work until it settles.
97
+ *
98
+ * Use this with `ManagedRuntime.runFork(...)` when the fiber needs an already
99
+ * built runtime context. The returned lease can be released manually, but it
100
+ * is normally released by the fiber observer.
101
+ */
102
+ async trackFiber(fiber) {
103
+ const lease = await this.acquire();
104
+ fiber.addObserver(() => {
105
+ this.waitUntil(lease.release().catch((error) => {
106
+ this.onBackgroundError(error);
107
+ }));
108
+ });
109
+ if (fiber.pollUnsafe() !== void 0) await lease.release();
110
+ return lease;
111
+ }
112
+ /**
113
+ * Fork an Effect as host-tracked active work.
114
+ *
115
+ * This mirrors Effect's host-runner pattern: observe the root fiber and release
116
+ * the alarm lease when it settles. It deliberately does not patch Effect
117
+ * internals or try to classify runnable vs suspended fibers.
118
+ */
119
+ async fork(effect) {
120
+ const fiber = Effect.runFork(effect);
121
+ await this.trackFiber(fiber);
122
+ return fiber;
123
+ }
124
+ /** Handle the Durable Object `alarm()` callback: re-arm while work remains, else clear. */
125
+ alarm() {
126
+ return this.reschedule(true);
127
+ }
128
+ /** Permanently stop the heartbeat and prevent later lease releases from re-arming it. */
129
+ shutdown() {
130
+ this.shutdownRequested = true;
131
+ this.generation += 1;
132
+ this.activeLeases = 0;
133
+ this.runSchedulingPending = false;
134
+ return this.reschedule(true);
135
+ }
136
+ /** Start a fresh lease generation after the host intentionally resets its durable state. */
137
+ restart() {
138
+ this.shutdownRequested = false;
139
+ }
140
+ waitUntil(promise) {
141
+ if (this.background !== void 0) {
142
+ this.background.waitUntil(promise);
143
+ return;
144
+ }
145
+ }
146
+ /** `clearWhenIdle`: only the alarm handler and shutdown may remove an idle object's alarm. */
147
+ reschedule(clearWhenIdle = false) {
148
+ this.scheduleTail = this.scheduleTail.catch(() => void 0).then(() => this.syncAlarm(clearWhenIdle));
149
+ return this.scheduleTail;
150
+ }
151
+ async syncAlarm(clearWhenIdle) {
152
+ if (this.shutdownRequested || this.activeLeases === 0 && !this.runSchedulingPending) {
153
+ if (clearWhenIdle || this.shutdownRequested) await this.storage.deleteAlarm();
154
+ return;
155
+ }
156
+ const desiredAt = this.now() + this.intervalMs;
157
+ const currentAt = await this.storage.getAlarm();
158
+ if (currentAt === null || currentAt > desiredAt) await this.storage.setAlarm(desiredAt);
159
+ }
160
+ };
161
+ //#endregion
162
+ //#region src/durable-object-sink-checkpoints.ts
163
+ /**
164
+ * Durable Object SQLite adapter for EDA sink checkpoints.
165
+ *
166
+ * Checkpoint SQL stays in the host layer for the same reason session storage SQL
167
+ * does: framework sink code should depend on checkpoint semantics, not table access.
168
+ */
169
+ var DurableObjectSinkCheckpointStore = class DurableObjectSinkCheckpointStore {
170
+ /** Ensure the fixed `_eda_sink_cursors` table exists during host startup. */
171
+ static migrate = (storage) => migrateSinkCheckpointStore(storage);
172
+ /** Build the semantic checkpoint store over native DO SQLite. */
173
+ static make = (storage) => makeDurableObjectSinkCheckpointStore(storage);
174
+ static layer = (storage) => Layer.effect(SinkCheckpointStore, DurableObjectSinkCheckpointStore.make(storage));
175
+ };
176
+ /** Create the sink checkpoint table inside the current EDA storage schema. */
177
+ const migrateSinkCheckpointStore = (storage) => Effect.try({
178
+ try: () => {
179
+ storage.sql.exec(`
180
+ CREATE TABLE IF NOT EXISTS _eda_sink_cursors (
181
+ sink_name TEXT PRIMARY KEY,
182
+ after_seq INTEGER NOT NULL,
183
+ payload_json TEXT NOT NULL
184
+ )
185
+ `);
186
+ },
187
+ catch: (error) => sinkCheckpointError("migrating SinkCheckpointStore", error)
188
+ });
189
+ /** Interpret checkpoint load/save/commit with idempotent upserts. */
190
+ const makeDurableObjectSinkCheckpointStore = (storage) => Effect.gen(function* () {
191
+ yield* DurableObjectSinkCheckpointStore.migrate(storage);
192
+ const { sql } = storage;
193
+ return {
194
+ load: (sinkName) => Effect.try({
195
+ try: () => {
196
+ const row = sql.exec(`SELECT after_seq, payload_json FROM _eda_sink_cursors WHERE sink_name = ?`, sinkName).toArray()[0];
197
+ return row === void 0 ? {
198
+ afterSeq: SequenceNumber.make(0),
199
+ payload: void 0
200
+ } : {
201
+ afterSeq: SequenceNumber.make(row.after_seq),
202
+ payload: JSON.parse(row.payload_json)
203
+ };
204
+ },
205
+ catch: (error) => sinkCheckpointError("reading sink checkpoint", error)
206
+ }),
207
+ saveState: (sinkName, payload) => Effect.try({
208
+ try: () => {
209
+ sql.exec(`
210
+ INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)
211
+ VALUES (?, 0, ?)
212
+ ON CONFLICT(sink_name) DO UPDATE SET
213
+ payload_json = excluded.payload_json
214
+ `, sinkName, JSON.stringify(payload));
215
+ },
216
+ catch: (error) => sinkCheckpointError("saving sink checkpoint state", error)
217
+ }),
218
+ commit: (sinkName, afterSeq, payload) => Effect.try({
219
+ try: () => {
220
+ sql.exec(`
221
+ INSERT INTO _eda_sink_cursors (sink_name, after_seq, payload_json)
222
+ VALUES (?, ?, ?)
223
+ ON CONFLICT(sink_name) DO UPDATE SET
224
+ after_seq = excluded.after_seq,
225
+ payload_json = excluded.payload_json
226
+ `, sinkName, afterSeq, JSON.stringify(payload ?? { updatedAtMs: Date.now() }));
227
+ },
228
+ catch: (error) => sinkCheckpointError("committing sink checkpoint", error)
229
+ })
230
+ };
231
+ });
232
+ const sinkCheckpointError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
233
+ //#endregion
234
+ //#region src/runtime/runtime-layer.ts
235
+ /** Compose the platform-neutral runtime with Cloudflare persistence and lifecycle adapters. */
236
+ const makeEDADurableObjectRuntimeLayer = ({ appEvents, config, deciders, idGeneratorLayer, compactionExecutorLayer, compactionPolicyLayer, keepAlive, modelResolverLayer, promptProjectorLayer, reducers, runSchedulerLayer, sessionEventObserverLayer, sessionId, sinks, storage, toolkit, toolRegistry, tracer, transcript }) => {
237
+ const lifecycle = keepAlive ?? new DurableObjectKeepAlive(storage);
238
+ const keepAliveLayer = EDAKeepAlive.FromAcquire(() => lifecycle.acquire());
239
+ return makeEDARuntimeLayer({
240
+ appEvents,
241
+ config,
242
+ deciders,
243
+ idGeneratorLayer,
244
+ compactionExecutorLayer,
245
+ compactionPolicyLayer,
246
+ keepAliveLayer,
247
+ modelResolverLayer,
248
+ promptProjectorLayer,
249
+ runSchedulerLayer,
250
+ runSchedulingWakeupLayer: Layer.succeed(RunSchedulingWakeup, { setPending: (pending) => Effect.tryPromise({
251
+ try: () => lifecycle.setRunSchedulingPending(pending),
252
+ catch: (error) => new EDASessionStoreError({ message: `Persisting run scheduling wakeup: ${String(error)}` })
253
+ }) }),
254
+ reducerRegistryLayer: EDAReducerRegistry.Live(reducers ?? []),
255
+ sessionEventObserverLayer,
256
+ sessionId,
257
+ sessionStoreLayer: DurableObjectSessionStore.layer({
258
+ sessionId,
259
+ storage,
260
+ ...transcript === void 0 ? {} : { transcript }
261
+ }),
262
+ sinkCheckpointStoreLayer: DurableObjectSinkCheckpointStore.layer(storage),
263
+ sinks,
264
+ toolkit,
265
+ toolRegistry,
266
+ tracer
267
+ });
268
+ };
269
+ //#endregion
270
+ //#region src/runtime/session-runtime.ts
271
+ /** Owns the disposable ManagedRuntime and nothing about WebSocket transport. */
272
+ var EDASessionRuntime = class {
273
+ options;
274
+ keepAlive;
275
+ state;
276
+ building;
277
+ constructor(options) {
278
+ this.options = options;
279
+ this.keepAlive = options.keepAlive ?? new DurableObjectKeepAlive(options.alarmStorage ?? options.storage, options.background);
280
+ }
281
+ static migrate = (storage) => Effect.gen(function* () {
282
+ yield* DurableObjectSessionStore.migrate(storage);
283
+ yield* DurableObjectSinkCheckpointStore.migrate(storage);
284
+ });
285
+ isReady(sessionId) {
286
+ return this.state?.sessionId === sessionId;
287
+ }
288
+ async prepare(sessionId) {
289
+ await this.get(sessionId);
290
+ }
291
+ async run(sessionId, operation) {
292
+ return await (await this.get(sessionId)).runtime.runPromise(Effect.gen(function* () {
293
+ return yield* operation(yield* EDARuntime);
294
+ }));
295
+ }
296
+ async alarm(sessionId) {
297
+ const resolved = sessionId ?? this.state?.sessionId;
298
+ if (resolved !== void 0) await this.run(resolved, (runtime) => runtime.retryRunSchedulingDelivery());
299
+ await this.keepAlive.alarm();
300
+ }
301
+ async destroy() {
302
+ await this.keepAlive.shutdown();
303
+ await this.dispose();
304
+ this.state = void 0;
305
+ this.building = void 0;
306
+ }
307
+ async dispose() {
308
+ await this.state?.runtime.dispose();
309
+ }
310
+ async get(sessionId) {
311
+ if (this.state !== void 0) {
312
+ if (this.state.sessionId !== sessionId) throw new Error(`EDA session runtime is scoped to session ${this.state.sessionId}; received ${sessionId}`);
313
+ return this.state;
314
+ }
315
+ this.keepAlive.restart();
316
+ const building = this.building ?? this.build(sessionId);
317
+ this.building = building;
318
+ try {
319
+ return await building;
320
+ } catch (error) {
321
+ if (this.building === building) this.building = void 0;
322
+ throw error;
323
+ }
324
+ }
325
+ async build(sessionId) {
326
+ const runtime = ManagedRuntime.make(makeEDADurableObjectRuntimeLayer({
327
+ appEvents: this.options.appEvents,
328
+ config: this.options.config,
329
+ deciders: this.options.deciders,
330
+ idGeneratorLayer: this.options.idGeneratorLayer,
331
+ compactionExecutorLayer: this.options.compactionExecutorLayer,
332
+ compactionPolicyLayer: this.options.compactionPolicyLayer,
333
+ keepAlive: this.keepAlive,
334
+ modelResolverLayer: this.options.modelResolverLayer,
335
+ promptProjectorLayer: this.options.promptProjectorLayer,
336
+ reducers: this.options.reducers,
337
+ runSchedulerLayer: this.options.runSchedulerLayer,
338
+ sessionEventObserverLayer: this.options.sessionEventObserverLayer,
339
+ sessionId,
340
+ sinks: this.options.sinks,
341
+ storage: this.options.storage,
342
+ toolkit: resolveFactory(this.options.toolkit, sessionId),
343
+ toolRegistry: resolveFactory(this.options.toolRegistry, sessionId),
344
+ tracer: resolveFactory(this.options.tracer, sessionId),
345
+ transcript: resolveFactory(this.options.transcript, sessionId)
346
+ }));
347
+ const state = {
348
+ runtime,
349
+ sessionId
350
+ };
351
+ try {
352
+ await runtime.context();
353
+ this.state = state;
354
+ return state;
355
+ } catch (error) {
356
+ await runtime.dispose().catch(() => void 0);
357
+ throw error;
358
+ }
359
+ }
360
+ };
361
+ const resolveFactory = (value, sessionId) => typeof value === "function" ? value({ sessionId }) : value;
362
+ //#endregion
363
+ //#region src/websocket/projection.ts
364
+ /** Stable non-empty identity persisted with an app WebSocket projection. */
365
+ const EDAWebSocketProjectionId = Schema.NonEmptyString.pipe(Schema.brand("EDAWebSocketProjectionId"));
366
+ //#endregion
367
+ //#region src/websocket/attachment.ts
368
+ /** Versioned state required to resume strict delivery after Durable Object hibernation. */
369
+ const EDAWebSocketAttachment = Schema.Struct({
370
+ kind: Schema.Literal("eda-events-v2"),
371
+ sessionId: SessionId,
372
+ subscriberId: SubscriberId,
373
+ trace: EDATraceMetadata,
374
+ delivery: EDAWebSocketDeliveryCheckpoint,
375
+ projection: Schema.optionalKey(Schema.Struct({
376
+ id: EDAWebSocketProjectionId,
377
+ state: Schema.Unknown
378
+ }))
379
+ });
380
+ /**
381
+ * State required to resume a transcript-window socket after hibernation: the transport receipts,
382
+ * the applied cut, the subscription base and unanswered requests. Staged chunk data is never
383
+ * persisted; a checkpoint that names a transfer cannot resume it.
384
+ */
385
+ const EDATranscriptWebSocketAttachment = Schema.Struct({
386
+ kind: Schema.Literal("eda-transcript-v1"),
387
+ sessionId: SessionId,
388
+ subscriberId: SubscriberId,
389
+ trace: EDATraceMetadata,
390
+ delivery: EDATranscriptDeliveryCheckpoint
391
+ });
392
+ /** Either socket kind an EDA Durable Object accepts. */
393
+ const EDAAnyWebSocketAttachment = Schema.Union([EDAWebSocketAttachment, EDATranscriptWebSocketAttachment]);
394
+ /** Decode and classify an attachment read from Cloudflare's structured-clone boundary. */
395
+ const decodeWebSocketAttachment = async (input) => {
396
+ if (input === null || input === void 0) return { _tag: "Missing" };
397
+ try {
398
+ return {
399
+ _tag: "Decoded",
400
+ attachment: await Effect.runPromise(Schema.decodeUnknownEffect(EDAAnyWebSocketAttachment)(input))
401
+ };
402
+ } catch {
403
+ return { _tag: "Malformed" };
404
+ }
405
+ };
406
+ /** Encode before serialization so schema transformations cannot leak into attachments. */
407
+ const encodeWebSocketAttachment = (attachment) => Schema.encodeSync(EDAWebSocketAttachment)(attachment);
408
+ /** Encode a transcript socket attachment for Cloudflare's structured-clone boundary. */
409
+ const encodeTranscriptWebSocketAttachment = (attachment) => Schema.encodeSync(EDATranscriptWebSocketAttachment)(attachment);
410
+ //#endregion
411
+ //#region src/websocket/transcript-sockets.ts
412
+ const defaultActiveContentCadenceMs = 50;
413
+ /** Largest client frame accepted, in UTF-8 bytes; requests are persisted, so this bounds the attachment too. */
414
+ const maxClientFrameBytes = 2048;
415
+ const decodeClientFrame = Schema.decodeUnknownExit(EDATranscriptClientFrame);
416
+ /**
417
+ * Owns transcript-window sockets: the window data source beneath the frame encoder.
418
+ *
419
+ * Every subscriber is served strictly in order. Committed changes are coalesced to the complete
420
+ * boundary a store read returns; a request is answered by one read at one cut; and each update is
421
+ * sent from its own captured snapshot before the next is planned.
422
+ *
423
+ * **Publication fence.** Append publication, ephemeral publication and window capture share one
424
+ * fence: the active-content accumulator folds every published event in order, and a capture is
425
+ * served with live content only when the accumulator has folded exactly the window's cut. Durable
426
+ * commit precedes live publication, so a window read between the two would otherwise pair a
427
+ * committed inference with its stale live parts. A capture that would cross the fence waits for
428
+ * publication to catch up.
429
+ */
430
+ var EDATranscriptSockets = class {
431
+ options;
432
+ sockets = /* @__PURE__ */ new Map();
433
+ active = emptyTranscriptActiveContentState;
434
+ timerArmed = false;
435
+ background = /* @__PURE__ */ new Set();
436
+ flowControl;
437
+ policy;
438
+ limits;
439
+ cadenceMs;
440
+ fenceWaitMs;
441
+ maxTotalStagedBytes;
442
+ schedule;
443
+ now;
444
+ constructor(options) {
445
+ this.options = options;
446
+ this.flowControl = options.flowControl ?? defaultEDAWebSocketFlowControl;
447
+ this.policy = options.subscriptionPolicy ?? defaultTranscriptSubscriptionPolicy;
448
+ this.limits = options.deliveryLimits ?? defaultEDATranscriptDeliveryLimits;
449
+ this.cadenceMs = options.activeContentCadenceMs ?? 50;
450
+ this.fenceWaitMs = options.fenceWaitMs ?? 1e3;
451
+ this.maxTotalStagedBytes = options.maxTotalStagedBytes ?? 33554432;
452
+ this.schedule = options.schedule ?? ((delayMs, run) => {
453
+ setTimeout(run, delayMs);
454
+ });
455
+ this.now = options.now ?? Date.now;
456
+ }
457
+ has(webSocket) {
458
+ return this.sockets.has(webSocket);
459
+ }
460
+ /** Transcript sockets this isolate holds, for hosts that cannot enumerate accepted sockets. */
461
+ webSockets() {
462
+ return [...this.sockets.keys()];
463
+ }
464
+ /**
465
+ * Register a freshly accepted socket and greet it. Synchronous so the attachment exists before
466
+ * any platform callback can observe the socket.
467
+ */
468
+ accept(input) {
469
+ const socket = {
470
+ sessionId: input.sessionId,
471
+ subscriberId: SubscriberId.make(crypto.randomUUID()),
472
+ trace: input.trace,
473
+ delivery: makeTranscriptDeliveryState(this.flowControl),
474
+ queue: Promise.resolve(),
475
+ dirty: false,
476
+ sentActiveRevision: void 0,
477
+ last: void 0,
478
+ fenceWaitingSinceMs: void 0,
479
+ scheduledDrain: void 0,
480
+ stagedBytes: 0,
481
+ activeSentAtMs: void 0,
482
+ cadenceDue: false
483
+ };
484
+ this.sockets.set(input.webSocket, socket);
485
+ if (!this.persist(input.webSocket, socket)) return;
486
+ this.sendText(input.webSocket, encodeEDATranscriptServerFrame({
487
+ _tag: "hello",
488
+ protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
489
+ subscriberId: socket.subscriberId,
490
+ resumeSeq: 0,
491
+ flowControl: this.flowControl,
492
+ negotiation: edaTranscriptNegotiation
493
+ }));
494
+ }
495
+ /**
496
+ * Adopt a socket that survived hibernation. A socket that was mid-transfer lost its staged
497
+ * chunks with the isolate: it is closed, and the client reconnects and resubscribes.
498
+ */
499
+ restore(webSocket, attachment) {
500
+ const restored = restoreTranscriptDeliveryState(this.flowControl, attachment.delivery);
501
+ if (restored._tag === "TransferLost") {
502
+ this.close(webSocket, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, "transfer-lost");
503
+ return false;
504
+ }
505
+ this.sockets.set(webSocket, {
506
+ sessionId: attachment.sessionId,
507
+ subscriberId: attachment.subscriberId,
508
+ trace: attachment.trace,
509
+ delivery: restored.state,
510
+ queue: Promise.resolve(),
511
+ dirty: true,
512
+ sentActiveRevision: void 0,
513
+ last: void 0,
514
+ fenceWaitingSinceMs: void 0,
515
+ scheduledDrain: void 0,
516
+ stagedBytes: 0,
517
+ activeSentAtMs: void 0,
518
+ cadenceDue: false
519
+ });
520
+ return true;
521
+ }
522
+ closed(webSocket) {
523
+ this.sockets.delete(webSocket);
524
+ }
525
+ /**
526
+ * Observe one published event, in publication order. Folds it into the active-content
527
+ * accumulator synchronously, then lets each listed subscriber act on it: a durable event
528
+ * schedules a read at the new boundary; changed live content is coalesced to the display
529
+ * cadence.
530
+ *
531
+ * Reads are scheduled, not awaited, so subscribers never hold the session's append gate. The
532
+ * fence does not need the gate: every capture is checked against the accumulator's folded head
533
+ * when its read resolves.
534
+ */
535
+ onPublished(event, webSockets) {
536
+ const revision = this.active.revision;
537
+ this.active = foldTranscriptActiveContent(this.active, event);
538
+ if (event.event.durability !== "durable") {
539
+ if (this.active.revision !== revision) this.armCadence();
540
+ return;
541
+ }
542
+ for (const webSocket of webSockets) {
543
+ const socket = this.sockets.get(webSocket);
544
+ if (socket === void 0) continue;
545
+ socket.dirty = true;
546
+ this.track(this.drain(webSocket, socket));
547
+ }
548
+ }
549
+ /** Serve sockets restored from hibernation after a publication was folded. */
550
+ serveRestored(webSockets) {
551
+ for (const webSocket of webSockets) {
552
+ const socket = this.sockets.get(webSocket);
553
+ if (socket === void 0) continue;
554
+ socket.dirty = true;
555
+ this.track(this.drain(webSocket, socket));
556
+ }
557
+ }
558
+ /**
559
+ * The session's log was destroyed: live content belongs to a log that no longer exists and
560
+ * every subscription names its incarnation. Close the transcript sockets this isolate holds,
561
+ * and any listed still-hibernated socket, so clients resubscribe.
562
+ */
563
+ reset(hibernated = []) {
564
+ this.active = emptyTranscriptActiveContentState;
565
+ for (const webSocket of /* @__PURE__ */ new Set([...this.sockets.keys(), ...hibernated])) this.close(webSocket, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, "session-reset");
566
+ }
567
+ async message(webSocket, message) {
568
+ const socket = this.sockets.get(webSocket);
569
+ if (socket === void 0) {
570
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
571
+ return;
572
+ }
573
+ if (message === EDA_WEB_SOCKET_PING_MESSAGE) {
574
+ this.sendText(webSocket, EDA_WEB_SOCKET_PONG_MESSAGE);
575
+ return;
576
+ }
577
+ if (message.length > maxClientFrameBytes || utf8ByteLength(message) > maxClientFrameBytes) {
578
+ this.protocolError(webSocket, "Client frame too large");
579
+ return;
580
+ }
581
+ let json;
582
+ try {
583
+ json = JSON.parse(message);
584
+ } catch {
585
+ this.protocolError(webSocket, "Malformed client frame");
586
+ return;
587
+ }
588
+ const decoded = decodeClientFrame(json);
589
+ if (Exit.isFailure(decoded)) {
590
+ this.protocolError(webSocket, "Unknown client frame");
591
+ return;
592
+ }
593
+ const frame = decoded.value;
594
+ if (frame._tag === "ping") return;
595
+ await this.enqueue(webSocket, socket, async () => {
596
+ if (frame._tag === "ack") {
597
+ const acked = onTranscriptAck(socket.delivery, frame);
598
+ if (acked._tag === "ProtocolError") {
599
+ this.protocolError(webSocket, acked.message);
600
+ return;
601
+ }
602
+ if (acked._tag === "Ignored") return;
603
+ socket.delivery = acked.state;
604
+ if (!this.persist(webSocket, socket)) return;
605
+ } else {
606
+ const queued = enqueueTranscriptRequest(socket.delivery, frame, this.limits);
607
+ if (queued === void 0) {
608
+ this.protocolError(webSocket, "Too many unanswered transcript requests");
609
+ return;
610
+ }
611
+ socket.delivery = queued;
612
+ if (!this.persist(webSocket, socket)) return;
613
+ }
614
+ await this.drainNow(webSocket, socket);
615
+ });
616
+ }
617
+ /** Wait for scheduled reads and cadence flushes; for orderly shutdown and tests. */
618
+ async settled() {
619
+ while (this.background.size > 0) await Promise.all([...this.background]);
620
+ }
621
+ /**
622
+ * Own scheduled subscriber work until it settles. Drains never reject: `enqueue` contains every
623
+ * failure and closes the socket.
624
+ */
625
+ track(work) {
626
+ const tracked = work.finally(() => {
627
+ this.background.delete(tracked);
628
+ });
629
+ this.background.add(tracked);
630
+ }
631
+ armCadence() {
632
+ if (this.timerArmed) return;
633
+ this.timerArmed = true;
634
+ this.schedule(this.cadenceMs, () => {
635
+ this.timerArmed = false;
636
+ for (const [webSocket, socket] of this.sockets) {
637
+ socket.cadenceDue = true;
638
+ this.track(this.drain(webSocket, socket));
639
+ }
640
+ });
641
+ }
642
+ /**
643
+ * Schedule one drain, coalescing with a drain that is scheduled but not yet running. A drain
644
+ * that is already running re-checks `dirty` before it returns, so nothing is missed.
645
+ */
646
+ drain(webSocket, socket) {
647
+ if (socket.scheduledDrain !== void 0) return socket.scheduledDrain;
648
+ const scheduled = this.enqueue(webSocket, socket, () => {
649
+ socket.scheduledDrain = void 0;
650
+ return this.drainNow(webSocket, socket);
651
+ });
652
+ socket.scheduledDrain = scheduled;
653
+ return scheduled;
654
+ }
655
+ /** Send everything this subscriber is owed, one complete update at a time. */
656
+ async drainNow(webSocket, socket) {
657
+ for (;;) {
658
+ if (this.sockets.get(webSocket) !== socket) return;
659
+ const nowMs = this.now();
660
+ if (transcriptAckTimedOut(socket.delivery, nowMs)) {
661
+ this.sendText(webSocket, encodeEDATranscriptServerFrame({
662
+ _tag: "lagged",
663
+ resumeSeq: socket.delivery.appliedThroughSeq,
664
+ reason: "ack-timeout"
665
+ }));
666
+ this.close(webSocket, EDA_WS_CLOSE_LAGGED, laggedCloseReason(socket.delivery.appliedThroughSeq));
667
+ return;
668
+ }
669
+ if (socket.delivery.transfer !== void 0) {
670
+ const pumped = pumpTranscriptTransfer(socket.delivery, nowMs);
671
+ if (pumped.frames.length === 0) return;
672
+ socket.delivery = pumped.state;
673
+ if (pumped.state.transfer === void 0) socket.stagedBytes = 0;
674
+ if (!this.persistAndSend(webSocket, socket, pumped.frames)) return;
675
+ continue;
676
+ }
677
+ if (transcriptDeliveryCapacity(socket.delivery) <= 0) return;
678
+ const request = socket.delivery.requests[0];
679
+ const base = socket.delivery.subscription;
680
+ if (request === void 0) {
681
+ if (base === void 0) return;
682
+ if (!socket.dirty) {
683
+ if (socket.sentActiveRevision === this.active.revision) {
684
+ socket.cadenceDue = false;
685
+ return;
686
+ }
687
+ if (!(socket.cadenceDue || socket.activeSentAtMs === void 0 || nowMs - socket.activeSentAtMs >= this.cadenceMs)) {
688
+ this.armCadence();
689
+ return;
690
+ }
691
+ const sent = await this.sendActiveOnly(webSocket, socket);
692
+ if (sent === "NeedsRead") {
693
+ socket.dirty = true;
694
+ continue;
695
+ }
696
+ if (sent === "Failed") return;
697
+ continue;
698
+ }
699
+ }
700
+ const subscriptionRequest = request === void 0 ? { _tag: "Refresh" } : toSubscriptionRequest(request);
701
+ socket.dirty = false;
702
+ const read = await Effect.runPromiseExit(readTranscriptSubscription(this.options.transcriptStore, base, subscriptionRequest, this.policy));
703
+ if (this.sockets.get(webSocket) !== socket) return;
704
+ if (Exit.isFailure(read)) {
705
+ await Effect.runPromise(Effect.logError("EDA transcript window read failed", {
706
+ cause: read.cause,
707
+ subscriberId: socket.subscriberId
708
+ }));
709
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "read-failed");
710
+ return;
711
+ }
712
+ const { window, patchBase } = read.value;
713
+ const active = this.active;
714
+ const fenced = !(window.readiness._tag === "Ready") || window.throughSeq === active.publishedThroughSeq || window.throughSeq > active.publishedThroughSeq && active.inference === void 0;
715
+ if (!fenced) {
716
+ socket.fenceWaitingSinceMs ??= nowMs;
717
+ if (nowMs - socket.fenceWaitingSinceMs < this.fenceWaitMs) {
718
+ socket.dirty = true;
719
+ this.armCadence();
720
+ return;
721
+ }
722
+ }
723
+ socket.fenceWaitingSinceMs = void 0;
724
+ const update = planTranscriptUpdate({
725
+ patchBase,
726
+ window,
727
+ updateSeq: socket.delivery.nextUpdateSeq,
728
+ activeContent: fenced ? transcriptActiveContentOf(active) : [],
729
+ includeActiveContent: !fenced || socket.sentActiveRevision !== active.revision || window.readiness._tag === "Ready" && socket.last !== void 0 && socket.last.readiness._tag !== "Ready",
730
+ ...request?.requestId === void 0 ? {} : { requestId: request.requestId }
731
+ });
732
+ const remaining = request === void 0 ? socket.delivery.requests : socket.delivery.requests.slice(1);
733
+ if (request === void 0 && this.isNoop(socket, update)) continue;
734
+ if (!await this.start(webSocket, socket, update, transcriptSubscriptionBaseOf(window), remaining)) return;
735
+ socket.sentActiveRevision = active.revision;
736
+ if (update.activeContent !== void 0) {
737
+ socket.cadenceDue = false;
738
+ socket.activeSentAtMs = this.now();
739
+ }
740
+ socket.last = {
741
+ readiness: window.readiness,
742
+ hasOlder: window.hasOlder,
743
+ hasNewer: window.hasNewer,
744
+ dependencyIds: update.dependencyIds
745
+ };
746
+ }
747
+ }
748
+ /**
749
+ * Publish changed live content without a store read. Valid only while the accumulator has
750
+ * folded exactly the subscriber's last cut; otherwise a commit is pending and a read is needed.
751
+ */
752
+ async sendActiveOnly(webSocket, socket) {
753
+ const base = socket.delivery.subscription;
754
+ const last = socket.last;
755
+ const active = this.active;
756
+ if (last !== void 0 && last.readiness._tag !== "Ready") {
757
+ socket.sentActiveRevision = active.revision;
758
+ return "Sent";
759
+ }
760
+ if (base === void 0 || last === void 0 || active.publishedThroughSeq !== base.throughSeq) return "NeedsRead";
761
+ const update = {
762
+ updateSeq: socket.delivery.nextUpdateSeq,
763
+ mode: "patch",
764
+ incarnation: base.incarnation,
765
+ version: base.version,
766
+ throughSeq: base.throughSeq,
767
+ ...base.coverage === void 0 ? {} : { coverage: base.coverage },
768
+ hasOlder: last.hasOlder,
769
+ hasNewer: last.hasNewer,
770
+ readiness: last.readiness,
771
+ records: [],
772
+ dependencies: [],
773
+ dependencyIds: last.dependencyIds,
774
+ activeContent: transcriptActiveContentOf(active)
775
+ };
776
+ if (!await this.start(webSocket, socket, update, base, socket.delivery.requests)) return "Failed";
777
+ socket.sentActiveRevision = active.revision;
778
+ socket.cadenceDue = false;
779
+ socket.activeSentAtMs = this.now();
780
+ return "Sent";
781
+ }
782
+ /** A refresh that changes nothing the client holds is not sent. */
783
+ isNoop(socket, update) {
784
+ const base = socket.delivery.subscription;
785
+ const last = socket.last;
786
+ return base !== void 0 && last !== void 0 && update.mode === "patch" && update.records.length === 0 && update.dependencies.length === 0 && update.activeContent === void 0 && update.throughSeq === base.throughSeq && update.hasOlder === last.hasOlder && update.hasNewer === last.hasNewer && JSON.stringify(update.coverage) === JSON.stringify(base.coverage) && JSON.stringify(update.readiness) === JSON.stringify(last.readiness);
787
+ }
788
+ async start(webSocket, socket, update, subscription, requests) {
789
+ const encodedUpdate = encodeEDATranscriptUpdate(update);
790
+ const bytes = utf8ByteLength(encodedUpdate);
791
+ if (utf8ByteLength(edaTranscriptUpdateFrameText(socket.delivery.nextFrameId, encodedUpdate)) > this.flowControl.maxFrameBytes && this.stagedBytes() + bytes > this.maxTotalStagedBytes) {
792
+ this.close(webSocket, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, "staging-budget");
793
+ return false;
794
+ }
795
+ const started = startTranscriptUpdate({
796
+ ...socket.delivery,
797
+ requests
798
+ }, {
799
+ update,
800
+ encodedUpdate,
801
+ subscription
802
+ }, this.limits, this.now());
803
+ if (started._tag === "TooLarge") {
804
+ await Effect.runPromise(Effect.logError("EDA transcript update exceeds the staging bound", {
805
+ bytes: started.bytes,
806
+ subscriberId: socket.subscriberId
807
+ }));
808
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "update-too-large");
809
+ return false;
810
+ }
811
+ socket.delivery = started.state;
812
+ socket.stagedBytes = started.state.transfer === void 0 ? 0 : bytes;
813
+ return this.persistAndSend(webSocket, socket, started.frames);
814
+ }
815
+ /** Bytes of chunked updates still being transferred, across every socket of this object. */
816
+ stagedBytes() {
817
+ let total = 0;
818
+ for (const socket of this.sockets.values()) total += socket.stagedBytes;
819
+ return total;
820
+ }
821
+ /** Persist the checkpoint before any frame it accounts for becomes client-visible. */
822
+ persistAndSend(webSocket, socket, frames) {
823
+ if (!this.persist(webSocket, socket)) return false;
824
+ for (const frame of frames) if (!this.sendText(webSocket, frame)) return false;
825
+ return true;
826
+ }
827
+ persist(webSocket, socket) {
828
+ try {
829
+ webSocket.serializeAttachment(encodeTranscriptWebSocketAttachment(EDATranscriptWebSocketAttachment.make({
830
+ kind: "eda-transcript-v1",
831
+ sessionId: socket.sessionId,
832
+ subscriberId: socket.subscriberId,
833
+ trace: socket.trace,
834
+ delivery: checkpointTranscriptDelivery(socket.delivery)
835
+ })));
836
+ return true;
837
+ } catch (error) {
838
+ Effect.runSync(Effect.logError("EDA transcript socket attachment failed", {
839
+ error,
840
+ subscriberId: socket.subscriberId
841
+ }));
842
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "attachment-failed");
843
+ return false;
844
+ }
845
+ }
846
+ sendText(webSocket, text) {
847
+ try {
848
+ webSocket.send(text);
849
+ return true;
850
+ } catch (error) {
851
+ Effect.runSync(Effect.logWarning("EDA transcript socket send failed", { error }));
852
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "send-failed");
853
+ return false;
854
+ }
855
+ }
856
+ protocolError(webSocket, message) {
857
+ this.sendText(webSocket, encodeEDATranscriptServerFrame({
858
+ _tag: "error",
859
+ message: message.slice(0, 120)
860
+ }));
861
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
862
+ }
863
+ enqueue(webSocket, socket, operation) {
864
+ const run = async () => {
865
+ try {
866
+ await operation();
867
+ } catch (error) {
868
+ await Effect.runPromise(Effect.logError("EDA transcript socket operation failed", {
869
+ error,
870
+ subscriberId: socket.subscriberId
871
+ }));
872
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "subscriber-failed");
873
+ }
874
+ };
875
+ const next = socket.queue.then(run);
876
+ socket.queue = next;
877
+ return next;
878
+ }
879
+ close(webSocket, code, reason) {
880
+ this.sockets.delete(webSocket);
881
+ try {
882
+ webSocket.close(code, reason);
883
+ } catch {}
884
+ }
885
+ };
886
+ const toSubscriptionRequest = (frame) => {
887
+ switch (frame._tag) {
888
+ case "subscribe": return {
889
+ _tag: "Subscribe",
890
+ tail: frame.tail ?? false,
891
+ ...frame.range === void 0 ? {} : { range: frame.range },
892
+ ...frame.since === void 0 ? {} : { since: frame.since },
893
+ ...frame.count === void 0 ? {} : { count: frame.count }
894
+ };
895
+ case "page": return {
896
+ _tag: "Page",
897
+ direction: frame.direction,
898
+ cursor: frame.cursor,
899
+ count: frame.count
900
+ };
901
+ case "retain": return {
902
+ _tag: "Retain",
903
+ from: frame.from,
904
+ to: frame.to
905
+ };
906
+ }
907
+ };
908
+ //#endregion
909
+ //#region src/websocket/connection-manager.ts
910
+ /**
911
+ * Owns Cloudflare WebSockets, hibernation attachments, and interpretation of
912
+ * the platform-neutral delivery state machine.
913
+ */
914
+ var EDAWebSocketConnectionManager = class {
915
+ options;
916
+ 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 }))));
917
+ sockets = /* @__PURE__ */ new Map();
918
+ transcript;
919
+ constructor(options) {
920
+ this.options = options;
921
+ this.transcript = options.transcript === void 0 ? void 0 : new EDATranscriptSockets(options.transcript);
922
+ }
923
+ /** Whether this host serves transcript-window sockets. */
924
+ get supportsTranscript() {
925
+ return this.transcript !== void 0;
926
+ }
927
+ /**
928
+ * Accept a transcript-window socket. Reads are storage-level, so this never prepares the
929
+ * session runtime. Call immediately after `ctx.acceptWebSocket()`.
930
+ */
931
+ acceptTranscript(input) {
932
+ if (this.transcript === void 0) {
933
+ this.close(input.webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "unsupported");
934
+ return;
935
+ }
936
+ this.transcript.accept(input);
937
+ }
938
+ /**
939
+ * The session's log was destroyed: drop live content and close every transcript socket,
940
+ * including those still hibernated, which a just-woken object has not restored yet. They are
941
+ * recognised by their attachment kind without being restored.
942
+ */
943
+ /**
944
+ * Re-read every transcript socket, held or hibernated, at the current cut. The served version
945
+ * changed without a publication (a rebuilt version activated), so each subscriber receives a
946
+ * complete replacement (design §7 step 4, §9.4).
947
+ */
948
+ async refreshTranscript() {
949
+ if (this.transcript === void 0) return;
950
+ const sockets = [...this.transcript.webSockets()];
951
+ for (const webSocket of this.options.getWebSockets?.() ?? []) {
952
+ if (this.sockets.has(webSocket) || this.transcript.has(webSocket)) continue;
953
+ const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
954
+ if (decoded._tag !== "Decoded" || decoded.attachment.kind !== "eda-transcript-v1") continue;
955
+ if (this.transcript.has(webSocket) || this.transcript.restore(webSocket, decoded.attachment)) sockets.push(webSocket);
956
+ }
957
+ this.transcript.serveRestored(sockets);
958
+ }
959
+ async resetTranscript() {
960
+ if (this.transcript === void 0) return;
961
+ const hibernated = [];
962
+ for (const webSocket of this.options.getWebSockets?.() ?? []) {
963
+ if (this.sockets.has(webSocket) || this.transcript.has(webSocket)) continue;
964
+ const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
965
+ if (decoded._tag === "Decoded" && decoded.attachment.kind === "eda-transcript-v1") hibernated.push(webSocket);
966
+ }
967
+ this.transcript.reset(hibernated);
968
+ }
969
+ /** Wait for scheduled transcript flushes; for orderly shutdown and tests. */
970
+ async settled() {
971
+ await this.transcript?.settled();
972
+ }
973
+ resolveProjection(id) {
974
+ if (id === void 0) return void 0;
975
+ if (this.options.webSocketProjection?.id === id) return this.options.webSocketProjection;
976
+ }
977
+ async accept(input) {
978
+ const subscriberId = SubscriberId.make(crypto.randomUUID());
979
+ const delivery = makeWebSocketDeliveryState({
980
+ subscriberId,
981
+ resumeSeq: input.afterSeq,
982
+ policy: defaultEDAWebSocketFlowControl
983
+ });
984
+ const state = {
985
+ sessionId: input.sessionId,
986
+ subscriberId,
987
+ trace: input.trace,
988
+ delivery,
989
+ catchUpDeferred: false,
990
+ head: input.afterSeq,
991
+ queue: Promise.resolve(),
992
+ ...input.projectionState === void 0 ? {} : { projectionState: input.projectionState }
993
+ };
994
+ this.sockets.set(input.webSocket, state);
995
+ if (!this.persist(input.webSocket, state)) return;
996
+ if (!await this.send(input.webSocket, state, [deliveryHelloFrame(delivery)])) return;
997
+ if (!await this.prepare(input.webSocket, state)) return;
998
+ await this.enqueue(input.webSocket, state, async () => {
999
+ await this.readAndDeliver(input.webSocket, state, input.afterSeq);
1000
+ });
1001
+ }
1002
+ async message(webSocket, message) {
1003
+ if (typeof message !== "string") {
1004
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "binary");
1005
+ return;
1006
+ }
1007
+ if (message === EDA_WEB_SOCKET_PING_MESSAGE) {
1008
+ try {
1009
+ webSocket.send(EDA_WEB_SOCKET_PONG_MESSAGE);
1010
+ } catch {
1011
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "send-failed");
1012
+ }
1013
+ return;
1014
+ }
1015
+ const restored = await this.restore(webSocket);
1016
+ if (restored === "transcript") {
1017
+ await this.transcript?.message(webSocket, message);
1018
+ return;
1019
+ }
1020
+ if (restored === "closed") return;
1021
+ const state = restored;
1022
+ if (state === void 0) {
1023
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1024
+ return;
1025
+ }
1026
+ const frame = await Effect.runPromise(this.decodeClientMessage(message, state).pipe(Effect.option));
1027
+ if (frame._tag === "None") {
1028
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1029
+ return;
1030
+ }
1031
+ const clientFrame = frame.value;
1032
+ if (clientFrame._tag === "ping") return;
1033
+ if (!await this.prepare(webSocket, state)) return;
1034
+ await this.enqueue(webSocket, state, async () => {
1035
+ await this.interpret(webSocket, state, onClientAck(state.delivery, clientFrame, Date.now()));
1036
+ });
1037
+ }
1038
+ closed(webSocket) {
1039
+ this.sockets.delete(webSocket);
1040
+ this.transcript?.closed(webSocket);
1041
+ }
1042
+ async flushDeferredCatchUp(sessionId) {
1043
+ const deliveries = [];
1044
+ for (const [webSocket, state] of this.sockets) {
1045
+ if (state.sessionId !== sessionId || !state.catchUpDeferred) continue;
1046
+ deliveries.push(this.enqueue(webSocket, state, async () => {
1047
+ if (!state.catchUpDeferred) return;
1048
+ state.catchUpDeferred = false;
1049
+ await this.readAndDeliver(webSocket, state, state.delivery.sentDurableThroughSeq);
1050
+ }));
1051
+ }
1052
+ await Promise.all(deliveries);
1053
+ }
1054
+ async fanoutPublishedEvent(event) {
1055
+ const heldTranscriptSockets = new Set(this.transcript?.webSockets() ?? []);
1056
+ this.transcript?.onPublished(event, [...heldTranscriptSockets]);
1057
+ const webSockets = /* @__PURE__ */ new Set([
1058
+ ...this.options.getWebSockets?.() ?? [],
1059
+ ...this.sockets.keys(),
1060
+ ...this.transcript?.webSockets() ?? []
1061
+ ]);
1062
+ const deliveries = [];
1063
+ const transcriptSockets = [];
1064
+ for (const webSocket of webSockets) {
1065
+ const state = await this.restore(webSocket);
1066
+ if (state === "transcript") {
1067
+ transcriptSockets.push(webSocket);
1068
+ continue;
1069
+ }
1070
+ if (state === void 0 || state === "closed") continue;
1071
+ deliveries.push(this.enqueue(webSocket, state, async () => {
1072
+ if (event.event.durability !== "durable") {
1073
+ await this.interpret(webSocket, state, onEphemeralEvent(state.delivery, event, Date.now()));
1074
+ return;
1075
+ }
1076
+ state.head = SequenceNumber.make(Math.max(state.head, event.position.seq));
1077
+ if (event.position.seq <= state.delivery.sentDurableThroughSeq) return;
1078
+ if (event.position.seq === state.delivery.sentDurableThroughSeq + 1) {
1079
+ await this.interpret(webSocket, state, onDurableEvents(state.delivery, [event], state.head, Date.now()));
1080
+ return;
1081
+ }
1082
+ if (!this.options.isSessionReady(state.sessionId)) {
1083
+ state.catchUpDeferred = true;
1084
+ return;
1085
+ }
1086
+ await this.readAndDeliver(webSocket, state, state.delivery.sentDurableThroughSeq);
1087
+ }));
1088
+ }
1089
+ this.transcript?.serveRestored(transcriptSockets.filter((webSocket) => !heldTranscriptSockets.has(webSocket)));
1090
+ await Promise.all(deliveries);
1091
+ }
1092
+ async restore(webSocket) {
1093
+ const existing = this.sockets.get(webSocket);
1094
+ if (existing !== void 0) return existing;
1095
+ if (this.transcript?.has(webSocket) === true) return "transcript";
1096
+ const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
1097
+ if (decoded._tag !== "Decoded") {
1098
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1099
+ return;
1100
+ }
1101
+ const restoredMeanwhile = this.sockets.get(webSocket);
1102
+ if (restoredMeanwhile !== void 0) return restoredMeanwhile;
1103
+ if (this.transcript?.has(webSocket) === true) return "transcript";
1104
+ if (decoded.attachment.kind === "eda-transcript-v1") {
1105
+ if (this.transcript === void 0) {
1106
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1107
+ return;
1108
+ }
1109
+ return this.transcript.restore(webSocket, decoded.attachment) ? "transcript" : "closed";
1110
+ }
1111
+ const attachment = decoded.attachment;
1112
+ const projectionState = attachment.projection === void 0 ? void 0 : await this.decodeProjectionState(attachment.projection.id, attachment.projection.state);
1113
+ if (attachment.projection !== void 0 && projectionState === void 0) {
1114
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1115
+ return;
1116
+ }
1117
+ const state = {
1118
+ sessionId: attachment.sessionId,
1119
+ subscriberId: attachment.subscriberId,
1120
+ trace: attachment.trace,
1121
+ delivery: restoreWebSocketDeliveryState({
1122
+ subscriberId: attachment.subscriberId,
1123
+ policy: defaultEDAWebSocketFlowControl,
1124
+ checkpoint: attachment.delivery
1125
+ }),
1126
+ catchUpDeferred: false,
1127
+ head: attachment.delivery.sentDurableThroughSeq,
1128
+ queue: Promise.resolve(),
1129
+ ...projectionState === void 0 ? {} : { projectionState }
1130
+ };
1131
+ this.sockets.set(webSocket, state);
1132
+ return state;
1133
+ }
1134
+ async prepare(webSocket, state) {
1135
+ try {
1136
+ await this.options.prepareSession(state.sessionId);
1137
+ return this.sockets.get(webSocket) === state;
1138
+ } catch (error) {
1139
+ await Effect.runPromise(Effect.logError("EDA WebSocket session preparation failed", {
1140
+ error,
1141
+ subscriberId: state.subscriberId
1142
+ }));
1143
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "subscriber-failed");
1144
+ return false;
1145
+ }
1146
+ }
1147
+ async interpret(webSocket, state, result) {
1148
+ state.delivery = result.state;
1149
+ for (const action of result.actions) switch (action._tag) {
1150
+ case "Persist":
1151
+ if (!this.persist(webSocket, state)) return false;
1152
+ break;
1153
+ case "Send":
1154
+ if (!await this.send(webSocket, state, action.frames)) return false;
1155
+ break;
1156
+ case "ReadEventPage":
1157
+ if (!await this.readAndDeliver(webSocket, state, action.afterSeq)) return false;
1158
+ break;
1159
+ case "Close":
1160
+ this.close(webSocket, action.code, action.reason);
1161
+ return false;
1162
+ }
1163
+ return true;
1164
+ }
1165
+ async readAndDeliver(webSocket, state, afterSeq) {
1166
+ const page = await this.options.readEventPage({
1167
+ afterSeq,
1168
+ limit: state.delivery.policy.maxInFlightFrames * state.delivery.policy.maxFrameEvents,
1169
+ sessionId: state.sessionId,
1170
+ subscriberId: state.subscriberId,
1171
+ trace: state.trace
1172
+ });
1173
+ state.head = SequenceNumber.make(Math.max(state.head, page.head));
1174
+ if (page.events.length === 0) return true;
1175
+ return await this.interpret(webSocket, state, onDurableEvents(state.delivery, page.events, state.head, Date.now()));
1176
+ }
1177
+ persist(webSocket, state) {
1178
+ try {
1179
+ const projection = state.projectionState === void 0 ? void 0 : this.options.webSocketProjection;
1180
+ if (state.projectionState !== void 0 && projection === void 0) {
1181
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1182
+ return false;
1183
+ }
1184
+ const attachment = EDAWebSocketAttachment.make({
1185
+ kind: "eda-events-v2",
1186
+ sessionId: state.sessionId,
1187
+ subscriberId: state.subscriberId,
1188
+ trace: state.trace,
1189
+ delivery: checkpointWebSocketDeliveryState(state.delivery),
1190
+ ...state.projectionState === void 0 || projection === void 0 ? {} : { projection: {
1191
+ id: projection.id,
1192
+ state: projection.encodeState(state.projectionState)
1193
+ } }
1194
+ });
1195
+ webSocket.serializeAttachment(encodeWebSocketAttachment(attachment));
1196
+ return true;
1197
+ } catch {
1198
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "attachment-failed");
1199
+ return false;
1200
+ }
1201
+ }
1202
+ send(webSocket, state, frames) {
1203
+ return this.sendPrepared(webSocket, state, frames);
1204
+ }
1205
+ async sendPrepared(webSocket, state, frames) {
1206
+ try {
1207
+ const encodedFrames = [];
1208
+ const followUpActions = [];
1209
+ for (const frame of frames) {
1210
+ const projected = state.projectionState === void 0 ? void 0 : this.options.webSocketProjection?.encodeServerFrame(frame, state.projectionState);
1211
+ if (state.projectionState !== void 0 && projected === void 0) {
1212
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1213
+ return false;
1214
+ }
1215
+ if (projected?._tag === "SuppressAndAck") {
1216
+ if (frame._tag !== "events") {
1217
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
1218
+ return false;
1219
+ }
1220
+ state.projectionState = projected.state;
1221
+ const acknowledged = onHostSuppressedFrame(state.delivery, {
1222
+ durableThroughSeq: frame.durableThroughSeq,
1223
+ frameId: frame.frameId
1224
+ }, Date.now());
1225
+ state.delivery = acknowledged.state;
1226
+ followUpActions.push(...acknowledged.actions.filter((action) => action._tag !== "Persist"));
1227
+ continue;
1228
+ }
1229
+ if (projected !== void 0) state.projectionState = projected.state;
1230
+ const encoded = projected?._tag === "Send" ? projected.frame : encodeEDAWebSocketServerFrame(frame, this.options.webSocketProtocol);
1231
+ if (new TextEncoder().encode(encoded).byteLength > state.delivery.policy.maxFrameBytes) {
1232
+ this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "frame-too-large");
1233
+ return false;
1234
+ }
1235
+ encodedFrames.push(encoded);
1236
+ }
1237
+ if (state.projectionState !== void 0 && !this.persist(webSocket, state)) return false;
1238
+ for (const encoded of encodedFrames) webSocket.send(encoded);
1239
+ if (followUpActions.length > 0) return await this.interpret(webSocket, state, {
1240
+ state: state.delivery,
1241
+ actions: coalesceFollowUpActions(followUpActions)
1242
+ });
1243
+ return true;
1244
+ } catch {
1245
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "send-failed");
1246
+ return false;
1247
+ }
1248
+ }
1249
+ enqueue(webSocket, state, operation) {
1250
+ const run = async () => {
1251
+ try {
1252
+ await operation();
1253
+ } catch (error) {
1254
+ await Effect.runPromise(Effect.logError("EDA WebSocket operation failed", {
1255
+ error,
1256
+ subscriberId: state.subscriberId
1257
+ }));
1258
+ this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "subscriber-failed");
1259
+ }
1260
+ };
1261
+ const next = state.queue.then(run);
1262
+ state.queue = next;
1263
+ return next;
1264
+ }
1265
+ close(webSocket, code, reason) {
1266
+ this.sockets.delete(webSocket);
1267
+ try {
1268
+ webSocket.close(code, reason);
1269
+ } catch {}
1270
+ }
1271
+ decodeClientMessage(message, state) {
1272
+ return state.projectionState === void 0 ? decodeEDAWebSocketClientMessage(message) : this.options.webSocketProjection?.decodeClientMessage(message) ?? Effect.fail("protocol");
1273
+ }
1274
+ async decodeProjectionState(id, encoded) {
1275
+ const projection = this.resolveProjection(id);
1276
+ if (projection === void 0) return void 0;
1277
+ const decoded = await Effect.runPromise(projection.decodeState(encoded).pipe(Effect.option));
1278
+ return decoded._tag === "Some" ? decoded.value : void 0;
1279
+ }
1280
+ };
1281
+ const coalesceFollowUpActions = (actions) => {
1282
+ let readAfterSeq;
1283
+ const retained = [];
1284
+ for (const action of actions) {
1285
+ if (action._tag !== "ReadEventPage") {
1286
+ retained.push(action);
1287
+ continue;
1288
+ }
1289
+ readAfterSeq = SequenceNumber.make(Math.max(readAfterSeq ?? 0, action.afterSeq));
1290
+ }
1291
+ return readAfterSeq === void 0 ? retained : [...retained, {
1292
+ _tag: "ReadEventPage",
1293
+ afterSeq: readAfterSeq
1294
+ }];
1295
+ };
1296
+ //#endregion
1297
+ //#region src/session-controller.ts
1298
+ /**
1299
+ * Public application-facing use cases for one EDA session.
1300
+ *
1301
+ * Runtime lifecycle belongs to EDASessionRuntime; WebSocket transport belongs
1302
+ * to EDAWebSocketConnectionManager. This class only coordinates them.
1303
+ */
1304
+ var EDASessionController = class {
1305
+ runtime;
1306
+ webSockets;
1307
+ deciders;
1308
+ constructor(options) {
1309
+ this.deciders = makeEDADeciderRegistry(options.deciders ?? [], options.appEvents);
1310
+ this.webSockets = new EDAWebSocketConnectionManager({
1311
+ getWebSockets: options.getWebSockets,
1312
+ isSessionReady: (sessionId) => this.runtime.isReady(sessionId),
1313
+ prepareSession: (sessionId) => this.prepareSession(sessionId),
1314
+ 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, {
1315
+ "eda.session.id": sessionId,
1316
+ "eda.subscriber.id": subscriberId,
1317
+ "eda.seq.after": afterSeq
1318
+ })))),
1319
+ webSocketProjection: options.webSocketProjection,
1320
+ webSocketProtocol: options.webSocketProtocol,
1321
+ ...options.transcriptSockets === void 0 ? {} : { transcript: options.transcriptSockets }
1322
+ });
1323
+ this.runtime = new EDASessionRuntime({
1324
+ ...options,
1325
+ sessionEventObserverLayer: this.webSockets.observerLayer
1326
+ });
1327
+ }
1328
+ static migrate = EDASessionRuntime.migrate;
1329
+ /** Trusted reconciliation read; never submits or grants replacement work. */
1330
+ runRequestOutcome(input) {
1331
+ return this.run(input.sessionId, (eda) => eda.runRequestOutcome(input.requestId));
1332
+ }
1333
+ /** Trusted scheduler ingress. Hosts must authorize callers before invoking this method. */
1334
+ grantRun(input) {
1335
+ const parent = input.trace?.parent;
1336
+ return this.run(input.sessionId, (eda) => {
1337
+ const operation = eda.grantRun(input.command);
1338
+ return parent === void 0 || parent === null ? operation : operation.pipe(Effect.withParentSpan(toEdaExternalSpan(parent)));
1339
+ });
1340
+ }
1341
+ submit(input) {
1342
+ const trace = input.trace ?? makeRootEDATraceMetadata();
1343
+ return this.run(input.sessionId, (eda) => eda.submit(input.command).pipe(Effect.withSpan("agent.command.submit", hostSpanOptions(trace, {
1344
+ "eda.session.id": input.sessionId,
1345
+ "eda.command.kind": input.command._tag,
1346
+ "eda.command.id": input.command.commandId
1347
+ }))));
1348
+ }
1349
+ submitBatch(input) {
1350
+ const trace = input.trace ?? makeRootEDATraceMetadata();
1351
+ return this.run(input.sessionId, (eda) => eda.submit(input.items).pipe(Effect.withSpan("agent.command.submit", hostSpanOptions(trace, {
1352
+ "eda.session.id": input.sessionId,
1353
+ "eda.command.submittable_count": input.items.length
1354
+ }))));
1355
+ }
1356
+ /**
1357
+ * Trusted ingress, like `submitBatch`: run a registered decider by name. Decodes `input` with
1358
+ * the decider's `input` schema and encodes the outcome with its `result` or `rejection` schema.
1359
+ */
1360
+ decide(input) {
1361
+ const trace = input.trace ?? makeRootEDATraceMetadata();
1362
+ const decider = this.deciders.get(input.decider);
1363
+ return this.run(input.sessionId, (eda) => Effect.gen(function* () {
1364
+ if (decider === void 0) return yield* new EDADeciderError({
1365
+ decider: input.decider,
1366
+ reason: "unknown_decider",
1367
+ message: `EDA decider ${input.decider} is not registered`
1368
+ });
1369
+ const decoded = yield* Schema.decodeUnknownEffect(decider.input)(input.input).pipe(Effect.mapError((cause) => new EDADeciderError({
1370
+ decider: decider.name,
1371
+ reason: "invalid_input",
1372
+ message: `input does not decode: ${cause.message}`
1373
+ })));
1374
+ const outcome = yield* eda.decide(decider, decoded);
1375
+ return outcome._tag === "Accepted" ? {
1376
+ _tag: "Accepted",
1377
+ result: yield* encodeJson(decider, decider.result, outcome.result),
1378
+ acceptedSeq: outcome.acceptedSeq,
1379
+ replayed: outcome.replayed
1380
+ } : {
1381
+ _tag: "Rejected",
1382
+ rejection: yield* encodeJson(decider, decider.rejection, outcome.rejection)
1383
+ };
1384
+ }).pipe(Effect.withSpan("agent.decide", hostSpanOptions(trace, {
1385
+ "eda.session.id": input.sessionId,
1386
+ "eda.decider.name": input.decider
1387
+ }))));
1388
+ }
1389
+ submitAndBlock(input) {
1390
+ const trace = input.trace ?? makeRootEDATraceMetadata();
1391
+ return this.run(input.sessionId, (eda) => eda.submitAndBlock(input.command).pipe(Effect.withSpan("agent.command.submit.wait", hostSpanOptions(trace, {
1392
+ "eda.session.id": input.sessionId,
1393
+ "eda.command.kind": input.command._tag,
1394
+ "eda.command.id": input.command.commandId
1395
+ }))));
1396
+ }
1397
+ blockOnCommand(input) {
1398
+ const trace = input.trace ?? makeRootEDATraceMetadata();
1399
+ return this.run(input.sessionId, (eda) => eda.blockOnCommand(input.commandId, input.afterSeq ?? SequenceNumber.make(0)).pipe(Effect.withSpan("agent.command.wait", hostSpanOptions(trace, {
1400
+ "eda.session.id": input.sessionId,
1401
+ "eda.command.id": input.commandId,
1402
+ "eda.seq.after": input.afterSeq
1403
+ }))));
1404
+ }
1405
+ snapshot(input) {
1406
+ return this.query(input, (eda) => eda.snapshot(), "agent.session.snapshot");
1407
+ }
1408
+ acceptEventWebSocket(input) {
1409
+ return this.acceptEventWebSocketUnhosted(input);
1410
+ }
1411
+ async acceptEventWebSocketUnhosted(input) {
1412
+ const prepared = await this.prepareEventWebSocket(input);
1413
+ await this.acceptPreparedEventWebSocket({
1414
+ ...prepared,
1415
+ webSocket: input.webSocket
1416
+ });
1417
+ }
1418
+ async prepareEventWebSocket(input) {
1419
+ const projection = this.webSockets.resolveProjection(input.projectionId);
1420
+ if (input.projectionId !== void 0 && projection === void 0) throw new Error(`Unsupported EDA WebSocket projection: ${input.projectionId}`);
1421
+ const initialized = projection === void 0 ? void 0 : projection.initialize({
1422
+ ...input.afterSeq === void 0 ? {} : { requestedAfterSeq: input.afterSeq },
1423
+ snapshot: await this.snapshot({
1424
+ sessionId: input.sessionId,
1425
+ trace: input.trace
1426
+ })
1427
+ });
1428
+ return {
1429
+ afterSeq: initialized?.afterSeq ?? input.afterSeq ?? SequenceNumber.make(0),
1430
+ sessionId: input.sessionId,
1431
+ trace: input.trace ?? makeRootEDATraceMetadata(),
1432
+ ...initialized === void 0 ? {} : { projectionState: initialized.state }
1433
+ };
1434
+ }
1435
+ acceptPreparedEventWebSocket(input) {
1436
+ return this.webSockets.accept(input);
1437
+ }
1438
+ /** The served transcript version changed: give every transcript socket a replacement. */
1439
+ refreshTranscriptWebSockets() {
1440
+ return this.webSockets.refreshTranscript();
1441
+ }
1442
+ /** Whether transcript-window sockets are served. */
1443
+ get supportsTranscriptWebSocket() {
1444
+ return this.webSockets.supportsTranscript;
1445
+ }
1446
+ /**
1447
+ * Register a transcript-window socket right after the host accepted it. Never prepares the
1448
+ * model runtime: windows are storage-level reads.
1449
+ */
1450
+ acceptTranscriptWebSocket(input) {
1451
+ this.webSockets.acceptTranscript({
1452
+ sessionId: input.sessionId,
1453
+ trace: input.trace ?? makeRootEDATraceMetadata(),
1454
+ webSocket: input.webSocket
1455
+ });
1456
+ }
1457
+ webSocketMessage(webSocket, message) {
1458
+ return this.webSockets.message(webSocket, message);
1459
+ }
1460
+ webSocketClose(webSocket) {
1461
+ this.webSockets.closed(webSocket);
1462
+ }
1463
+ webSocketError(webSocket) {
1464
+ this.webSockets.closed(webSocket);
1465
+ }
1466
+ async destroy(_input) {
1467
+ await this.runtime.destroy();
1468
+ await this.webSockets.resetTranscript();
1469
+ }
1470
+ async alarm(input) {
1471
+ if (input !== void 0) await this.prepareSession(input.sessionId);
1472
+ await this.runtime.alarm(input?.sessionId);
1473
+ }
1474
+ dispose() {
1475
+ return this.runtime.dispose();
1476
+ }
1477
+ query(input, operation, spanName) {
1478
+ const trace = input.trace ?? makeRootEDATraceMetadata();
1479
+ return this.run(input.sessionId, (eda) => operation(eda).pipe(Effect.withSpan(spanName, hostSpanOptions(trace, { "eda.session.id": input.sessionId }))));
1480
+ }
1481
+ async prepareSession(sessionId) {
1482
+ await this.runtime.prepare(sessionId);
1483
+ await this.webSockets.flushDeferredCatchUp(sessionId);
1484
+ }
1485
+ async run(sessionId, operation) {
1486
+ await this.prepareSession(sessionId);
1487
+ return await this.runtime.run(sessionId, operation);
1488
+ }
1489
+ };
1490
+ /**
1491
+ * Encode a decider value for the wire with the policy the marker's stored result uses, so a
1492
+ * committed result always encodes; a rejection its own schema cannot encode is `invalid_output`.
1493
+ */
1494
+ const encodeJson = (decider, schema, value) => {
1495
+ const encoded = encodeDeciderJson(schema, value);
1496
+ return Result.isSuccess(encoded) ? Effect.succeed(encoded.success) : Effect.fail(new EDADeciderError({
1497
+ decider: decider.name,
1498
+ reason: "invalid_output",
1499
+ message: `outcome ${encoded.failure}`
1500
+ }));
1501
+ };
1502
+ const hostSpanOptions = (trace, attributes) => ({
1503
+ kind: "server",
1504
+ attributes: compactSpanAttributes({
1505
+ ...trace.attributes,
1506
+ ...attributes
1507
+ }),
1508
+ links: trace.links.map((link) => ({
1509
+ span: toEdaExternalSpan(link.context),
1510
+ attributes: link.attributes
1511
+ })),
1512
+ ...trace.parent === null ? {} : { parent: toEdaExternalSpan(trace.parent) }
1513
+ });
1514
+ //#endregion
1515
+ export { makeEDADurableObjectRuntimeLayer as i, defaultActiveContentCadenceMs as n, EDAWebSocketProjectionId as r, EDASessionController as t };
1516
+
1517
+ //# sourceMappingURL=session-controller-UhUFR3i_.js.map