effect-durable-agent 0.1.0-alpha.4 → 0.1.0-alpha.6

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 (85) hide show
  1. package/README.md +19 -18
  2. package/dist/{command-queues-CV7O-51r.d.ts → command-queues-C8muEqeQ.d.ts} +2 -2
  3. package/dist/{compaction-zbvLREI8.d.ts → compaction-F4HEWzuI.d.ts} +5 -5
  4. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-C43pyxn2.d.ts} +2 -2
  5. package/dist/domain/command-queues.d.ts +1 -1
  6. package/dist/domain/context-projection.d.ts +1 -1
  7. package/dist/domain/message-transcript.d.ts +1 -1
  8. package/dist/domain/reduced-state.d.ts +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/{message-transcript-DiOPBY3l.d.ts → message-transcript-DsKTT47f.d.ts} +3 -3
  11. package/dist/{prompt-projector-C1IbkHr0.d.ts → prompt-projector-hqPh5-NI.d.ts} +4 -4
  12. package/dist/{reducer-registry-CjSJBPKo.d.ts → reducer-registry--vQFATXb.d.ts} +16 -6
  13. package/dist/{runtime-DOgmAKsO.d.ts → runtime-BO9KJq_Y.d.ts} +7 -5
  14. package/dist/services/compaction.d.ts +1 -1
  15. package/dist/services/prompt-projector.d.ts +1 -1
  16. package/dist/services/reducer-registry.d.ts +2 -2
  17. package/dist/services/reducer-registry.js +7 -3
  18. package/dist/services/reducer-registry.js.map +1 -1
  19. package/dist/services/runtime-layer.d.ts +12 -9
  20. package/dist/services/runtime-layer.js +6 -4
  21. package/dist/services/runtime-layer.js.map +1 -1
  22. package/dist/services/runtime.d.ts +1 -1
  23. package/dist/services/runtime.js +3 -2
  24. package/dist/services/runtime.js.map +1 -1
  25. package/dist/services/session-event-observer.d.ts +2 -0
  26. package/dist/services/session-event-observer.js +13 -0
  27. package/dist/services/session-event-observer.js.map +1 -0
  28. package/dist/services/session-query.d.ts +2 -2
  29. package/dist/services/session-query.js +20 -3
  30. package/dist/services/session-query.js.map +1 -1
  31. package/dist/services/session-state.d.ts +1 -1
  32. package/dist/services/session-state.js +1 -1
  33. package/dist/services/session-store.d.ts +1 -1
  34. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  35. package/dist/services/sink-registry.d.ts +1 -1
  36. package/dist/services/sink-registry.js +1 -1
  37. package/dist/services/span-names.d.ts +1 -1
  38. package/dist/services/span-names.js +1 -0
  39. package/dist/services/span-names.js.map +1 -1
  40. package/dist/services/tool-registry.d.ts +1 -1
  41. package/dist/services/tracing.js +23 -2
  42. package/dist/services/tracing.js.map +1 -1
  43. package/dist/session-event-observer-D_aoFnQs.d.ts +24 -0
  44. package/dist/{session-query-C-C4m1eq.d.ts → session-query-_Z3Kw6jj.d.ts} +15 -8
  45. package/dist/{session-state-CjOSvWbe.d.ts → session-state-BfoXKafd.d.ts} +11 -11
  46. package/dist/{session-state-SStf0KUo.js → session-state-C4m0j6CJ.js} +2 -2
  47. package/dist/{session-state-SStf0KUo.js.map → session-state-C4m0j6CJ.js.map} +1 -1
  48. package/dist/{session-store-DZZUffUy.d.ts → session-store-ofm8FFxs.d.ts} +2 -2
  49. package/dist/{sink-checkpoint-store-BZmQFTRE.d.ts → sink-checkpoint-store-BQVbI9DQ.d.ts} +2 -2
  50. package/dist/{sink-registry-D13eUO_c.js → sink-registry-DH6uiEgP.js} +19 -21
  51. package/dist/sink-registry-DH6uiEgP.js.map +1 -0
  52. package/dist/{sink-registry-Cf79ICdW.d.ts → sink-registry-PRYbj6dp.d.ts} +18 -14
  53. package/dist/testkit/layers.d.ts +10 -10
  54. package/dist/testkit/layers.js +3 -3
  55. package/dist/testkit/layers.js.map +1 -1
  56. package/dist/{tool-registry-B7Wona6N.d.ts → tool-registry-ClHdr_G5.d.ts} +2 -2
  57. package/dist/{websocket-wire-QD2SquQE.d.ts → websocket.d.ts} +335 -12
  58. package/dist/websocket.js +428 -0
  59. package/dist/websocket.js.map +1 -0
  60. package/package.json +15 -31
  61. package/testing/offline-trace/README.md +2 -1
  62. package/CHANGELOG.md +0 -34
  63. package/CONTRIBUTING.md +0 -26
  64. package/SECURITY.md +0 -7
  65. package/dist/host/websocket-protocol.d.ts +0 -229
  66. package/dist/host/websocket-protocol.js +0 -99
  67. package/dist/host/websocket-protocol.js.map +0 -1
  68. package/dist/host/websocket-wire.d.ts +0 -2
  69. package/dist/host/websocket-wire.js +0 -105
  70. package/dist/host/websocket-wire.js.map +0 -1
  71. package/dist/services/websocket-subscriber.d.ts +0 -54
  72. package/dist/services/websocket-subscriber.js +0 -190
  73. package/dist/services/websocket-subscriber.js.map +0 -1
  74. package/dist/sink-registry-D13eUO_c.js.map +0 -1
  75. package/docs/assets/architecture.svg +0 -216
  76. package/docs/assets/event-sequence.svg +0 -133
  77. package/docs/assets/gcp-trace.png +0 -0
  78. package/docs/assets/hero.svg +0 -33
  79. package/docs/message-steering.md +0 -831
  80. package/docs/releasing.md +0 -114
  81. package/docs/spec.md +0 -777
  82. package/docs/subagents.md +0 -725
  83. package/docs/testing.md +0 -64
  84. package/docs/ui-projection.md +0 -742
  85. package/docs/websocket-protocol.md +0 -639
@@ -1,639 +0,0 @@
1
- # effect-durable-agent WebSocket live-event protocol
2
-
3
- Status: current
4
- Runtime: effect-durable-agent host with app-specific event bindings
5
- Last reviewed: 2026-07-16
6
-
7
- Current scope: WebSocket-only live transport. The implemented slice includes protocol schemas, Cloudflare Durable Object upgrade/restore/message/close handling, ACK-window subscriber flow control, `4008` lag close, bounded active-turn ephemeral replay in `LiveEventBus`, and reconnect-safe `EDARuntime.eventsAfter(...)`. Items called out as future hardening below are not current behavior. This document replaces the earlier SSE-oriented live-event idea.
8
-
9
- ## 0. Objectives
10
-
11
- The protocol exists to satisfy these objectives, in priority order:
12
-
13
- 1. **Durable correctness.** Durable `seq` remains the only durable resume cursor. A client that reconnects from the last acknowledged durable `seq` can recover durable facts through `eventsAfter(seq)`.
14
- 2. **Turn-scoped ephemeral continuity.** Live-only ephemerals are retained only for the currently open turn. A committed turn terminal (`TurnCompleted`, `TurnStopped`, or `TurnFailed`) is the checkpoint that makes prior ephemerals droppable because durable message/lifecycle facts now explain the visible result. A reconnecting client receives durable history through the latest checkpoint, then receives the active turn's buffered ephemerals, then follows new live events.
15
- 3. **Bounded memory per subscriber and per session.** A slow browser must not move unbounded memory from the active-turn ephemeral buffer or `LiveEventBus` into either an Effect queue or Cloudflare's opaque WebSocket send buffer. The design must state hard bounds for session-level active-turn ephemeral retention plus subscriber queue/in-flight bytes.
16
- 4. **Subscriber isolation.** Slow-client lag closes only the lagging socket. It never backpressures `SessionState`, the durable append path, `LiveEventBus`, other subscribers, model streams, tools, or sinks.
17
- 5. **Explicit failure semantics.** Expected subscriber failures are typed `Schema.TaggedErrorClass` values (`SubscriberLagged`, `SubscriberProtocolError`, etc.) and are mapped once at the host boundary to WebSocket close codes/reasons.
18
- 6. **Effect-native resource ownership.** Each subscriber is one scoped workflow made of queues, refs, streams, deferred cancellation, and forked fibers. Closing the WebSocket closes the scope; closing the scope closes the WebSocket. No detached global fibers, raw timers, or hidden promises own protocol correctness.
19
- 7. **Cloudflare Durable Object fit.** Use the Hibernation WebSocket API (`ctx.acceptWebSocket`) and small `serializeAttachment` state so an idle object can hibernate and later restore subscribers from their last acknowledged durable cursor.
20
- 8. **Operational clarity.** Observability must expose subscriber id, session id, current durable ack, in-flight frame count, queue size, close reason, lag reason, active turn id, and active-turn ephemeral buffer size.
21
- 9. **Protocol evolution.** The frame shape should be versioned and batch-capable from day one, while allowing the first implementation to send one event per frame.
22
-
23
- Non-objectives:
24
-
25
- - Provide exactly-once delivery over WebSocket. Durable events are at-least-once across reconnect and clients must de-duplicate by position/event id.
26
- - Detect kernel/TCP-level delivery. The Workers WebSocket API gives `send(...) => void` and no reliable drain signal; application-level ACKs are the durability/flow-control signal.
27
- - Preserve ephemerals indefinitely. Active-turn ephemerals are retained only until the turn terminal checkpoint commits; completed-turn ephemerals are replaced by durable facts.
28
- - Keep SSE as a supported production live transport.
29
-
30
- ## 1. Important constraints and conclusions
31
-
32
- ### 1.1 `ws.send` is an enqueue, not a backpressure boundary
33
-
34
- In Workers/Durable Objects, `WebSocket.send(...)` is synchronous and returns `void`. The installed Workers types document that it enqueues data, and they do not expose a readable `bufferedAmount` or drain effect for server-side flow control. Therefore EDA must assume that `send` can buffer below the JavaScript layer.
35
-
36
- Consequence: an Effect `Queue.dropping` before `ws.send` is necessary but insufficient. If the sender fiber drains that queue into `ws.send` without a second gate, unbounded memory can simply move into the platform's opaque socket buffer.
37
-
38
- ### 1.2 ACK-window flow control is the explicit backpressure boundary
39
-
40
- The server sends at most `maxInFlightFrames` unacknowledged frames. A frame leaves the in-flight set only when the browser sends an application ACK after applying the frame to client state. If ACKs stop, the sender stops draining the bounded subscriber queue. The eager pump continues to drain the shared live/replay source into that bounded queue. When the queue fills, `Queue.offer` returns `false`, the workflow fails with `SubscriberLagged`, and the host closes only that socket.
41
-
42
- This bounds opaque WebSocket buffering to approximately:
43
-
44
- ```text
45
- max opaque WS bytes <= maxInFlightFrames * maxFrameBytes
46
- ```
47
-
48
- and bounds Effect-side event buffering to:
49
-
50
- ```text
51
- max queued events <= subscriberBufferCapacityEvents
52
- max unsent event bytes ~= subscriberBufferCapacityEvents * average encoded event size
53
- ```
54
-
55
- ### 1.3 Batching is intentional, not delegated to TCP
56
-
57
- TCP may coalesce bytes, but it does not remove WebSocket message overhead, JavaScript `message` event overhead, JSON parsing overhead, or ACK bookkeeping. Cloudflare's WebSocket guidance recommends batching logical messages because each WebSocket message has processing overhead. EDA frames are therefore **batch-capable**.
58
-
59
- The initial implementation may set `maxFrameEvents = 1` for simplicity. The protocol still uses an `events` array so later micro-batching by count/bytes/time does not change the wire contract.
60
-
61
- ### 1.4 Turn terminals are the dynamic ephemeral-retention boundary
62
-
63
- EDA needs reconnect continuity for the active turn without retaining live deltas forever. The retention boundary is the turn terminal durable event:
64
-
65
- - While a turn is open, `LiveEventBus` keeps a **turn-scoped ephemeral replay buffer** containing positioned ephemerals emitted for that active turn.
66
- - When `TurnCompleted`, `TurnStopped`, or `TurnFailed` is published, `LiveEventBus` drops the buffer for that turn.
67
- - A later reconnect never receives pre-terminal ephemerals for completed turns; it receives the durable `AssistantMessageCommitted` / `AssistantPartialCommitted` / lifecycle terminal facts instead.
68
- - A reconnect during an open turn receives durable replay plus the active turn's buffered ephemerals, even when those ephemerals have `position.seq <= afterSeq`. `afterSeq` is durable-only and cannot prove which live-only ephemerals the client applied before disconnect.
69
-
70
- This is a natural `LiveEventBus` responsibility because the buffer is live-only transport state. `SessionState` remains the authority for durable commits, reduced state, active turn identity, and ephemeral position allocation. `LiveEventBus` consumes the already-positioned ordered stream and maintains a best-effort reconnect buffer from those facts; it does not allocate positions, mutate durable state, decide turn lifecycle, or become a correctness source after process loss.
71
-
72
- Memory safety still matters. Current behavior caps active-turn retention by event count (`activeTurnEphemeralReplayCapacity = 4096`), keeps the newest events, and records an `overflowed` flag in `LiveEventBus.activeTurnReplay()`. It does not yet emit an explicit client reset/snapshot event when overflow happens. Coalesced retention or overflow reset signaling is future hardening.
73
-
74
- ## 2. Wire protocol overview
75
-
76
- Transport: WebSocket over the authenticated session events route.
77
-
78
- Encoding: UTF-8 JSON text frames only. Binary client frames are rejected with close code `1003` (unsupported data) or `1002` (protocol error), depending on host convenience.
79
-
80
- Protocol version: `1`.
81
-
82
- Server-to-client frames:
83
-
84
- - `hello` — connection accepted and flow-control parameters announced.
85
- - `events` — one ordered frame containing one or more EDA `PositionedEvent`s.
86
- - `heartbeat` — idle keepalive/status frame emitted when no event frame has been sent for the configured heartbeat interval.
87
- - `lagged` — optional final application frame before close when the server intentionally lag-closes.
88
- - `error` — optional final application frame before close for protocol/internal errors.
89
-
90
- Client-to-server frames:
91
-
92
- - `ack` — cumulative acknowledgement for delivered/applied event frames.
93
- - `pong` — optional response to an application `ping` if one is introduced later. Protocol v1 does not require app-level ping/pong because Cloudflare handles WebSocket control ping/pong automatically.
94
-
95
- The route-level resume parameter is `afterSeq`. The server may adjust it downward to the socket attachment's `lastAckedSeq` on hibernation restore. The authoritative resume cursor is always the server-side last acknowledged durable `seq`.
96
-
97
- ### 2.1 App-specific typed event binding
98
-
99
- The transport owns the frame protocol and framework event schemas. Each app registers only its custom event union:
100
-
101
- ```ts
102
- import * as Schema from "effect/Schema";
103
-
104
- import { makeEDAWebSocketWireProtocol } from "./host/websocket-wire";
105
- import { DurableEventEnvelope } from "./types/events";
106
-
107
- const CounterIncrementedEvent = Schema.Struct({
108
- ...DurableEventEnvelope.fields,
109
- namespace: Schema.Literal("counter"),
110
- type: Schema.Literal("CounterIncremented"),
111
- schemaVersion: Schema.Literal(1),
112
- payload: Schema.Struct({ amount: Schema.Number }),
113
- });
114
-
115
- export const counterWebSocketProtocol = makeEDAWebSocketWireProtocol({
116
- appEvents: CounterIncrementedEvent,
117
- });
118
-
119
- export const CounterWebSocketServerFrame = counterWebSocketProtocol.wire.serverFrame;
120
- export type CounterWebSocketServerFrame = typeof CounterWebSocketServerFrame.Type;
121
- ```
122
-
123
- `makeEDAWebSocketWireProtocol` automatically unions the app events with all EDA durable and ephemeral events. The returned value makes the two schema directions explicit:
124
-
125
- - `domain.event`, `domain.positionedEvent`, `domain.eventsFrame`, and `domain.serverFrame`
126
- describe decoded in-memory values. Schema transformations have already run on their `Type` side.
127
- - `wire.event`, `wire.positionedEvent`, `wire.eventsFrame`, and `wire.serverFrame` describe
128
- the UTF-8 JSON representation. Browser and other external consumers decode with these schemas
129
- when they need validated wire values without hydrating domain transformations.
130
- - `wire.clientFrame` validates client-to-server ACK messages.
131
- - `encodeServerFrame` accepts only the exact app-bound domain server-frame type and serializes it to
132
- one JSON text message.
133
- - `host` is the adapter passed as `webSocketProtocol` to the EDA host. It validates and encodes the
134
- host's broad event envelope against the registered app/framework union at runtime.
135
-
136
- For example, a transformed message content field may be a prompt-part array in
137
- `domain.serverFrame.Type` and a string in `wire.serverFrame.Type`. TypeScript rejects passing the
138
- wire frame to `encodeServerFrame`; callers must decode external input through the domain schema
139
- before treating it as an in-memory value. Both surfaces are derived from the same event schemas, so
140
- there is still one logical contract rather than parallel hand-maintained models. Switching on
141
- `event.type` narrows `event.payload` to that event's exact schema on either surface.
142
-
143
- The EDA host binding is therefore explicit:
144
-
145
- ```ts
146
- const options = {
147
- // Other host options omitted.
148
- webSocketProtocol: counterWebSocketProtocol.host,
149
- };
150
- ```
151
-
152
- The app event union is the registration point: adding a custom event there changes the WebSocket union everywhere it is imported. Consumers that use an exhaustive event policy or `assertNever` then receive a TypeScript error until they explicitly apply or ignore the new event.
153
-
154
- Hosts without custom events use the strict framework-only protocol. The default host encoder does not accept an arbitrary `EventEnvelope`; an app event must be registered explicitly or outbound encoding fails. This prevents an omitted app binding from silently degrading payloads back to `unknown`.
155
-
156
- This API separation does not change protocol version `1` or any serialized frame shape. It makes the
157
- existing domain-to-wire transformation direction visible in TypeScript and tests it through a full
158
- domain frame → JSON text → wire/domain decode round trip.
159
-
160
- ## 3. Schema sketch
161
-
162
- Frame variants are plain `Schema.Struct` values with literal `_tag` fields. Client and server protocols compose those variants with `Schema.Union`. This keeps the wire contract data-only; class constructors are reserved for domain values that benefit from behavior.
163
-
164
- ```ts
165
- import * as Schema from "effect/Schema";
166
-
167
- import { SequenceNumber } from "effect-durable-agent/types/core";
168
- import { PositionedEvent } from "effect-durable-agent/types/events";
169
-
170
- export const EDA_WS_PROTOCOL_VERSION = 1 as const;
171
-
172
- export const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand("SubscriberId"));
173
- export type SubscriberId = typeof SubscriberId.Type;
174
-
175
- export const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(
176
- Schema.brand("FrameId"),
177
- );
178
- export type FrameId = typeof FrameId.Type;
179
-
180
- const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
181
-
182
- export const FlowControlConfig = Schema.Struct({
183
- ackTimeoutMs: PositiveInt,
184
- heartbeatIntervalMs: PositiveInt,
185
- maxFrameBytes: PositiveInt,
186
- maxFrameEvents: PositiveInt,
187
- maxInFlightFrames: PositiveInt,
188
- subscriberBufferCapacityEvents: PositiveInt,
189
- });
190
- export type FlowControlConfig = typeof FlowControlConfig.Type;
191
-
192
- export const HelloFrame = Schema.Struct({
193
- _tag: Schema.Literal("hello"),
194
- protocolVersion: Schema.Literal(1),
195
- subscriberId: SubscriberId,
196
- resumeSeq: SequenceNumber,
197
- flowControl: FlowControlConfig,
198
- });
199
-
200
- export const EventsFrame = Schema.Struct({
201
- _tag: Schema.Literal("events"),
202
- frameId: FrameId,
203
- // Ordered by Position. The first implementation may send one event per frame.
204
- events: Schema.NonEmptyArray(PositionedEvent),
205
- // Max durable seq included in this frame, or the previous durable seq when the frame contains only ephemerals.
206
- durableThroughSeq: SequenceNumber,
207
- });
208
-
209
- export const HeartbeatFrame = Schema.Struct({
210
- _tag: Schema.Literal("heartbeat"),
211
- serverTimeMs: UnixEpochMillis,
212
- // Latest durable seq the server has emitted on this connection. Clients may use
213
- // it for liveness/status, but heartbeats do not advance ACK frame ids.
214
- durableThroughSeq: SequenceNumber,
215
- });
216
-
217
- export const LaggedFrame = Schema.Struct({
218
- _tag: Schema.Literal("lagged"),
219
- resumeSeq: SequenceNumber,
220
- reason: Schema.Literals(["buffer-overflow", "ack-timeout"]),
221
- });
222
-
223
- export const ErrorFrame = Schema.Struct({
224
- _tag: Schema.Literal("error"),
225
- message: Schema.String,
226
- });
227
-
228
- export const ServerFrame = Schema.Union([
229
- HelloFrame,
230
- EventsFrame,
231
- HeartbeatFrame,
232
- LaggedFrame,
233
- ErrorFrame,
234
- ]);
235
- export type ServerFrame = typeof ServerFrame.Type;
236
-
237
- export const AckFrame = Schema.Struct({
238
- _tag: Schema.Literal("ack"),
239
- frameId: FrameId,
240
- // Highest durable seq the client has applied to its local state.
241
- durableThroughSeq: SequenceNumber,
242
- });
243
-
244
- export const ClientFrame = Schema.Union([AckFrame]);
245
- export type ClientFrame = typeof ClientFrame.Type;
246
- ```
247
-
248
- Notes:
249
-
250
- - `_tag` strings are intentionally short because they appear in every frame.
251
- - `events` frames are cumulative-ACKed by `frameId`: ACKing `N` acknowledges all frames with `frameId <= N`.
252
- - `heartbeat` frames are idle keepalives. They have no `frameId`, do not count against the in-flight ACK window, and must not be ACKed.
253
- - `durableThroughSeq` in an ACK must be monotonic and must not exceed the maximum durable `seq` sent through that frame. Violations are protocol errors.
254
- - Frame IDs are per-subscriber, start at `1`, and reset on reconnect.
255
-
256
- ## 4. Default policy values
257
-
258
- Current production defaults are bounded while leaving enough headroom for fast model deltas and larger durable tool/message events observed in replay:
259
-
260
- ```ts
261
- const defaultFlowControl = {
262
- subscriberBufferCapacityEvents: 2_048,
263
- maxInFlightFrames: 16,
264
- maxFrameEvents: 1,
265
- maxFrameBytes: 256 * 1024,
266
- ackTimeoutMs: 30_000,
267
- heartbeatIntervalMs: 10_000,
268
- };
269
- ```
270
-
271
- Later tuning can change only configuration:
272
-
273
- - Increase `maxFrameEvents` to `10-25` for high-frequency token deltas.
274
- - Add `maxFrameDelayMs = 25-50` if micro-batching by time is needed.
275
- - Keep `maxFrameBytes` below any practical browser/Worker frame-size concern and below the close-reason/attachment constraints.
276
-
277
- The bounded-memory invariant is the target for current and future tests:
278
-
279
- ```text
280
- Events retained by EDA subscriber workflow <= subscriberBufferCapacityEvents + maxInFlightFrames * maxFrameEvents
281
- Opaque WS bytes intentionally enqueued <= maxInFlightFrames * maxFrameBytes
282
- ```
283
-
284
- ## 5. Connection lifecycle
285
-
286
- ### 5.1 Handshake
287
-
288
- 1. HTTP route authenticates the request exactly like the former session events route.
289
- 2. Non-`Upgrade: websocket` requests return `426 Upgrade Required`.
290
- 3. Route resolves the session Durable Object by session id and forwards the upgrade request to the DO.
291
- 4. The concrete EDA DO creates a `WebSocketPair`, calls `ctx.acceptWebSocket(server)`, stores a small attachment, and returns the client socket in a `101` response.
292
- 5. The host starts or restores the subscriber workflow.
293
- 6. Server sends `hello` as the first application frame.
294
-
295
- Attachment shape:
296
-
297
- ```ts
298
- const EDAWebSocketAttachment = Schema.Struct({
299
- kind: Schema.Literal("eda-events-v1"),
300
- sessionId: SessionId,
301
- subscriberId: SubscriberId,
302
- lastAckedSeq: SequenceNumber,
303
- });
304
- ```
305
-
306
- The attachment must stay well under Cloudflare's 16 KiB attachment limit. It is updated only when ACKs advance `lastAckedSeq`.
307
-
308
- ### 5.2 Normal streaming
309
-
310
- 1. Server obtains the merged reconnect/live stream from `EDARuntime.eventsAfter(lastAckedSeq)`. That stream must include durable replay plus the active-turn ephemeral replay buffer before following new live events.
311
- 2. Eager pump subscribes/replays and offers positioned events into `Queue.dropping`.
312
- 3. Sender builds one `events` frame from the queue when the in-flight window has capacity.
313
- 4. If no event is available for `heartbeatIntervalMs`, sender emits a `heartbeat` frame with the current server time and latest sent durable seq. Heartbeats are liveness/status frames only: they do not enter `inFlight` and are not ACKed.
314
- 5. Sender calls `ws.send(JSON.stringify(frame))` inside a small transport boundary effect.
315
- 6. Sender records event-frame metadata in `inFlight` and starts/refreshes the oldest-frame ACK deadline.
316
- 7. Client validates and applies events in order.
317
- 8. Client sends `ack` after applying an `events` frame to local state.
318
- 9. Server validates ACK, frees in-flight frames through `frameId`, advances `lastAckedSeq` if durable seq advanced, and updates the socket attachment.
319
-
320
- ### 5.3 Lag close
321
-
322
- A subscriber is lagged when either:
323
-
324
- - the eager pump cannot offer a new event into the bounded queue (`buffer-overflow`), or
325
- - the oldest in-flight frame is not ACKed within `ackTimeoutMs` (`ack-timeout`).
326
-
327
- The workflow fails with `SubscriberLagged`, the host optionally sends a final `lagged` frame if the socket is still open, then closes the socket with application code `4008` and a short reason such as:
328
-
329
- ```text
330
- lag;seq=123
331
- ```
332
-
333
- Close reasons must stay short because WebSocket close reasons have a small protocol limit.
334
-
335
- ### 5.4 Cancellation / close
336
-
337
- If the client closes the socket, the host completes a `closed` signal and interrupts the subscriber scope. The Effect stream is interrupted with `Stream.interruptWhen(closed)`, which interrupts in-progress pulls. Queue resources and fibers are cleaned up by scope finalizers.
338
-
339
- If the Effect workflow completes or fails first, the finalizer closes the WebSocket unless it is already closing/closed.
340
-
341
- ### 5.5 Hibernation restore
342
-
343
- When a Durable Object hibernates, in-memory subscriber fibers disappear but accepted WebSockets and attachments remain. On any wake event (client message, new RPC, alarm), the concrete DO/runtime host must:
344
-
345
- 1. Re-run normal lightweight constructor/migration setup.
346
- 2. Inspect `ctx.getWebSockets()`.
347
- 3. For each socket with `kind: "eda-events-v1"`, ensure a subscriber workflow exists.
348
- 4. Start that workflow from `attachment.lastAckedSeq`.
349
-
350
- If durable events were committed while the subscriber workflow was absent, `eventsAfter(lastAckedSeq)` replays durable catch-up before following live events. If a turn is still open, the active-turn ephemeral replay buffer is included in the reconnect prefix. If a turn terminal committed while the subscriber workflow was absent, the old ephemeral buffer has been dropped and clients recover through durable facts only.
351
-
352
- ## 6. Effect-native runtime design
353
-
354
- ### 6.1 Boundary split
355
-
356
- Keep protocol logic out of Cloudflare callback code. The host adapter should translate platform events into small Effect queues/deferreds, while the subscriber workflow owns policy.
357
-
358
- ```ts
359
- interface EDAEventWebSocketTransport {
360
- readonly send: (frame: ServerFrame) => Effect.Effect<void, SubscriberSendFailed>;
361
- readonly incoming: Queue.Queue<ClientFrame, SubscriberProtocolError>;
362
- readonly closed: Deferred.Deferred<void>;
363
- readonly persistAck: (seq: SequenceNumber) => Effect.Effect<void>;
364
- }
365
- ```
366
-
367
- The Cloudflare adapter implementation may call `ws.send`, `ws.close`, `ws.serializeAttachment`, and signal `closed`, but it should not contain queue overflow, ACK-window, or replay policy. Active-turn ephemeral replay is likewise not transport-adapter state; it belongs in `LiveEventBus` so WebSocket subscribers, tests, and any future live transport consume the same reconnect source.
368
-
369
- ### 6.2 Typed subscriber errors
370
-
371
- Expected failures are typed and serializable:
372
-
373
- ```ts
374
- export class SubscriberLagged extends Schema.TaggedErrorClass<SubscriberLagged>()(
375
- "SubscriberLagged",
376
- {
377
- subscriberId: SubscriberId,
378
- lastAckedSeq: SequenceNumber,
379
- reason: Schema.Literals(["buffer-overflow", "ack-timeout"]),
380
- },
381
- ) {}
382
-
383
- export class SubscriberProtocolError extends Schema.TaggedErrorClass<SubscriberProtocolError>()(
384
- "SubscriberProtocolError",
385
- {
386
- subscriberId: SubscriberId,
387
- message: Schema.String,
388
- },
389
- ) {}
390
-
391
- export class SubscriberSendFailed extends Schema.TaggedErrorClass<SubscriberSendFailed>()(
392
- "SubscriberSendFailed",
393
- {
394
- subscriberId: SubscriberId,
395
- cause: Schema.Defect,
396
- },
397
- ) {}
398
- ```
399
-
400
- Mapping to close codes happens once:
401
-
402
- | Error | Code | Reason |
403
- | --- | ---: | --- |
404
- | `SubscriberLagged` | `4008` | `lag;seq=<lastAckedSeq>` |
405
- | `SubscriberProtocolError` | `1002` | `protocol` |
406
- | `SubscriberSendFailed` | `1011` | `send-failed` |
407
- | client normal close | no server override / `1000` | `normal` |
408
- | host shutdown | future use of `1001` | `going-away` |
409
-
410
- Defects are not converted into ordinary lag. They are logged as defects and close with `1011` if the socket is still open.
411
-
412
- ### 6.3 Workflow sketch
413
-
414
- Pseudo-code shape, not final API:
415
-
416
- ```ts
417
- const runWebSocketSubscriber = Effect.fn("EDAWebSocketSubscriber.run")(function* (input) {
418
- const outbound = yield* Queue.dropping<PositionedEvent>(input.policy.subscriberBufferCapacityEvents);
419
- const closed = input.transport.closed;
420
- const lastAckedSeq = yield* Ref.make(input.resumeSeq);
421
- const nextFrameId = yield* Ref.make(FrameId.make(1));
422
- const inFlight = yield* Ref.make<ReadonlyArray<SentFrame>>([]);
423
-
424
- yield* input.transport.send(new HelloFrame({
425
- protocolVersion: 1,
426
- subscriberId: input.subscriberId,
427
- resumeSeq: input.resumeSeq,
428
- flowControl: input.policy,
429
- }));
430
-
431
- const source = yield* input.runtime.eventsAfter(input.resumeSeq);
432
-
433
- const pump = source.pipe(
434
- Stream.interruptWhen(Deferred.await(closed)),
435
- Stream.runForEach((event) =>
436
- Queue.offer(outbound, event).pipe(
437
- Effect.flatMap((accepted) =>
438
- accepted
439
- ? Effect.void
440
- : Effect.gen(function* () {
441
- const seq = yield* Ref.get(lastAckedSeq);
442
- yield* new SubscriberLagged({
443
- subscriberId: input.subscriberId,
444
- lastAckedSeq: seq,
445
- reason: "buffer-overflow",
446
- });
447
- }),
448
- ),
449
- ),
450
- ),
451
- );
452
-
453
- const ackLoop = readAckFrames(input.transport.incoming, inFlight, lastAckedSeq, input.transport.persistAck);
454
- const sender = sendFrames(outbound, inFlight, nextFrameId, lastAckedSeq, input.transport, input.policy);
455
- const timeout = watchAckTimeouts(inFlight, lastAckedSeq, input.policy);
456
-
457
- yield* Effect.raceFirst(
458
- pump,
459
- Effect.raceFirst(sender, Effect.raceFirst(ackLoop, timeout)),
460
- ).pipe(
461
- Effect.ensuring(Deferred.succeed(closed, undefined).pipe(Effect.ignore)),
462
- );
463
- }).pipe(Effect.scoped);
464
- ```
465
-
466
- Design details:
467
-
468
- - The pump is eager and non-suspending at the subscriber edge because the queue is dropping. It isolates `LiveEventBus` and replay source from the client.
469
- - The sender is the only place that drains `outbound`. It waits when `inFlight.length >= maxInFlightFrames`.
470
- - ACK handling is cumulative. It removes all sent frames with `frameId <= ack.frameId`, then advances `lastAckedSeq` to `max(current, ack.durableThroughSeq)` after validation.
471
- - `watchAckTimeouts` observes only the oldest in-flight frame. No in-flight frames means no timeout.
472
- - `persistAck` updates WebSocket attachment. It is intentionally not a durable database write.
473
- - `Effect.raceFirst` is used because whichever branch fails/completes should tear down the subscriber; losers are interrupted and finalizers run.
474
-
475
- ### 6.4 Sender batching algorithm
476
-
477
- Initial algorithm with one event per frame:
478
-
479
- 1. Wait until in-flight window has capacity.
480
- 2. `Queue.take(outbound)`.
481
- 3. Encode a candidate frame.
482
- 4. If encoded bytes exceed `maxFrameBytes`, fail with `SubscriberProtocolError` or `SubscriberSendFailed` depending on whether the event is impossible to send or encoding failed unexpectedly. Large individual event payloads should be rare because durable event payloads are already size-capped.
483
- 5. Send frame.
484
- 6. Add to in-flight metadata: `{ frameId, durableThroughSeq, sentAtMs, maxDurableSeqAllowed }`.
485
-
486
- Future micro-batch algorithm:
487
-
488
- 1. Take first event immediately.
489
- 2. Pull `Queue.takeUpTo(outbound, maxFrameEvents - 1)`.
490
- 3. Keep appending while encoded size remains `<= maxFrameBytes`.
491
- 4. If time-based batching is introduced, use Effect `Clock`/`TestClock`, not raw `setTimeout`.
492
-
493
- Batch metadata:
494
-
495
- - `durableThroughSeq` is the max durable event `seq` in the frame, or current `lastAckedSeq` for ephemeral-only frames.
496
- - Frame event order must already be `Position` order. The subscriber does not sort the ongoing live stream; reconnect prefix sorting stays in `EDASessionQuery.eventsAfter`.
497
-
498
- ## 7. Client obligations
499
-
500
- The browser client must:
501
-
502
- 1. Open WebSocket with its current durable cursor: `?afterSeq=<lastDurableAppliedSeq>`.
503
- 2. Wait for `hello` and validate `protocolVersion === 1`.
504
- 3. Ignore `heartbeat` frames for state application. They only prove the socket is alive and report the server's latest emitted durable seq.
505
- 4. Process `events` frames in `frameId` order. If a frame id skips unexpectedly, close and reconnect from the last applied durable seq.
506
- 5. Apply events to local state idempotently:
507
- - Drop durable events with `position.seq <= lastDurableAppliedSeq`.
508
- - Apply ephemerals only if they are relevant to the current live turn/session view.
509
- 6. ACK only after events are validated and applied to client state:
510
-
511
- ```json
512
- { "_tag": "ack", "frameId": 42, "durableThroughSeq": 123 }
513
- ```
514
-
515
- 7. Do not ACK `heartbeat` frames; they have no `frameId` and do not affect backpressure.
516
- 8. On close `4008`, reconnect from the sequence in close reason if present, otherwise from local `lastDurableAppliedSeq`.
517
- 9. Use bounded exponential backoff for abnormal reconnects.
518
-
519
- ACK after state application, not merely after receipt, is intentional: it backpressures on a busy browser main thread as well as on network delay.
520
-
521
- ## 8. `LiveEventBus` active-turn ephemeral replay buffer
522
-
523
- The WebSocket subscriber protocol depends on a live-only reconnect source owned by `LiveEventBus` with these semantics:
524
-
525
- ```ts
526
- interface ActiveTurnEphemeralReplay {
527
- readonly turnId?: TurnId;
528
- readonly events: ReadonlyArray<PositionedEvent>; // ephemerals only, ordered by Position
529
- readonly overflowed: boolean;
530
- }
531
-
532
- interface LiveEventBusShape {
533
- readonly publish: (event: PositionedEvent) => Effect.Effect<boolean>;
534
- readonly subscribeQueue: () => Effect.Effect<PubSub.Subscription<PositionedEvent>, never, Scope.Scope>;
535
- readonly activeTurnReplay: () => Effect.Effect<ActiveTurnEphemeralReplay>;
536
- }
537
- ```
538
-
539
- Ownership rules:
540
-
541
- 1. `SessionState` still emits every durable and ephemeral event through `LiveEventBus.publish` after assigning authoritative positions and folding durable state.
542
- 2. `LiveEventBus.publish` updates its active-turn buffer from the positioned event in the same live-bus critical section as PubSub fanout, with no suspending work between buffer mutation and publish:
543
- - `TurnStarted` opens or resets the active-turn buffer for that `turnId`.
544
- - active-turn ephemerals append to the buffer in `Position` order.
545
- - `TurnCompleted`, `TurnStopped`, or `TurnFailed` publishes the terminal and closes the current turn buffer, dropping its ephemerals at that checkpoint.
546
- 3. Reconnect setup subscribes to `LiveEventBus`, captures a durable replay head, reads durable replay, reads `liveBus.activeTurnReplay()`, drains pending live events, sorts this finite prefix by `Position`, drops duplicate durable events at or below the replay head, and emits all active-turn ephemerals from the buffer regardless of `afterSeq`.
547
- 4. Clients must treat reconnect-prefix ephemerals as a reconstruction of the current open turn. They should reset or de-duplicate active-turn live accumulators before applying buffered ephemerals, because durable `afterSeq` alone cannot encode which ephemerals were previously applied.
548
- 5. Once the turn terminal durable event is observed, clients should retire live accumulators for that turn and rely on durable transcript/lifecycle state.
549
-
550
- This changes `LiveEventBus` from "only PubSub fanout" to "live delivery hub": it still is not durable authority, but it is the natural owner of live-only retention and subscriber replay state. The shared `PubSub` remains just one implementation detail inside that service.
551
-
552
- Implemented decision: raw-delta retention with a conservative event-count cap. This gives reconnecting clients the same live event sequence for the open turn while bounding process memory. Coalesced retention would bound memory more semantically but requires snapshot-shaped ephemeral schemas and client reset semantics; that belongs to a future live-state extension.
553
-
554
- ## 9. Observability
555
-
556
- Every subscriber run should have a span such as `eda.ws.subscriber` with attributes:
557
-
558
- - `sessionId`
559
- - `subscriberId`
560
- - `resumeSeq`
561
- - `lastAckedSeq`
562
- - `queueCapacityEvents`
563
- - `queueSize` where cheap/available
564
- - `inFlightFrames`
565
- - `maxInFlightFrames`
566
- - `closeCode`
567
- - `closeReason`
568
- - `lagReason`
569
-
570
- Logs:
571
-
572
- - connect/restore with resume seq
573
- - ACK advancement
574
- - lag close with queue size/in-flight details
575
- - protocol error with sanitized reason
576
- - send defect with `Schema.Defect`
577
-
578
- Metrics later:
579
-
580
- - active subscribers
581
- - lag closes by reason
582
- - ack latency histogram
583
- - frames sent
584
- - events sent
585
- - reconnect count
586
-
587
- ## 10. Security and boundary validation
588
-
589
- - Authenticate and authorize before upgrade. Do not accept a WebSocket and then authenticate inside the protocol.
590
- - Decode every inbound client frame with `Schema.decodeUnknownEffect(ClientFrame)` after JSON parse.
591
- - Reject binary frames.
592
- - Treat unknown `_tag`, malformed JSON, non-monotonic ACKs, ACKs for unsent future frames, and `durableThroughSeq` beyond sent durable max as `SubscriberProtocolError`.
593
- - Do not expose raw internal error details in `error` frames or close reasons.
594
-
595
- Future hardening: cap inbound text frame size before `JSON.parse`; ACK frames should be tiny.
596
-
597
- ## 11. Testing status and future hardening
598
-
599
- Current tests cover the implemented slice:
600
-
601
- 1. **Normal subscriber delivery:** fake runtime stream emits events; fake transport records frames; ACKs advance `lastAckedSeq` and attachment persistence is called.
602
- 2. **Overflow lag:** with no ACKs and a tiny subscriber buffer, the pump fails with `SubscriberLagged`.
603
- 3. **Active-turn ephemeral replay:** reconnect during an open turn emits buffered ephemerals even when their durable anchor `seq <= afterSeq`.
604
- 4. **Turn terminal checkpoint:** committing `TurnCompleted`/`TurnStopped`/`TurnFailed` drops prior buffered ephemerals; subsequent reconnect receives durable facts only for that completed turn.
605
- 5. **Merged reconnect ordering:** durable replay, buffered live events, and active-turn ephemerals sort into a reconnect-safe prefix.
606
- 6. **Cloudflare host flow:** fake DO WebSocket upgrade streams frames and ACK updates `serializeAttachment`.
607
- 7. **Integration flow:** fake WebSocket-style route/runtime tests exercise the WebSocket-only session event path.
608
-
609
- Future hardening tests should add:
610
-
611
- - ACK-gated send assertions that the sender stops draining `outbound` while the in-flight window is full.
612
- - ACK timeout with `TestClock.adjust(ackTimeoutMs)` producing `SubscriberLagged { reason: "ack-timeout" }`.
613
- - Protocol errors for malformed ACKs, ACKs for unsent future frames, and durable seq advancement beyond sent frame boundaries.
614
- - Oversized outbound frame behavior and inbound text-frame byte cap before JSON parse.
615
- - Explicit client reducer reset/de-duplication behavior after active-turn replay overflow.
616
-
617
- Shared conformance tests exercise this flow against real workerd and celld processes.
618
-
619
- ## 12. Implemented artifacts and remaining work
620
-
621
- Implemented artifacts:
622
-
623
- 1. `src/host/websocket-wire.ts` defines the app-event-parameterized public wire schemas and encoder.
624
- 2. `src/host/websocket-protocol.ts` defines host frame schemas, attachment schema, flow-control config, close-code constants, and encode/decode helpers.
625
- 3. `src/services/live-event-bus.ts` owns bounded active-turn ephemeral replay: open on `TurnStarted`, append active-turn ephemerals, drop on `TurnCompleted`/`TurnStopped`/`TurnFailed`, expose `activeTurnReplay()`.
626
- 4. `src/services/session-query.ts` / `EDARuntime.eventsAfter(...)` merge durable replay, active-turn ephemerals, already-buffered live events, and follow-live delivery.
627
- 5. `src/services/websocket-subscriber.ts` defines typed subscriber errors and `runWebSocketSubscriber(...)` over `EDARuntime.eventsAfter`, `Queue.dropping`, ACK refs, scoped cancellation, and ACK timeouts.
628
- 6. `packages/cloudflare/src/durable-object-runtime.ts` adapts Durable Object WebSockets to the transport, persists ACKs in `serializeAttachment`, restores accepted sockets, and maps typed errors to close codes for Cloudflare and celld.
629
- 7. `packages/cloudflare/src/durable-object.ts` and the consuming application's routes expose a WebSocket-only events endpoint with `426` for non-upgrade requests.
630
- 8. Tests cover typed custom-event bindings, normal subscriber delivery, subscriber overflow lag, active-turn replay retention/drop, reconnect ordering, and fake DO WebSocket streaming.
631
-
632
- Remaining hardening:
633
-
634
- 1. Browser/client-side protocol helper with ordered apply, ACK-after-apply, active-turn replay reset/de-dupe, duplicate durable drop, and reconnect from last durable seq.
635
- 2. Inbound text-frame byte cap before JSON parse.
636
- 3. Focused ACK-timeout and protocol-error tests.
637
- 4. Micro-batching (`maxFrameEvents > 1`, optional frame delay) once token volume needs it.
638
- 5. Explicit client-visible behavior for active-turn replay overflow.
639
- 6. Broader host conformance coverage for lag/timeout failure paths.