effect-durable-agent 0.1.0-alpha.1 → 0.1.0-alpha.10

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 (183) hide show
  1. package/README.md +140 -136
  2. package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-CQi4Xc7u.d.ts} +109 -21
  3. package/dist/{commands-Ce1ec6kH.d.ts → commands-p8venTWs.d.ts} +10 -2
  4. package/dist/compaction-0k8zCJgB.js +473 -0
  5. package/dist/compaction-0k8zCJgB.js.map +1 -0
  6. package/dist/{compaction-YayFKo_1.d.ts → compaction-BhLSSXJ-.d.ts} +28 -7
  7. package/dist/context-projection-mCuvcO2W.d.ts +140 -0
  8. package/dist/{core-Hv3cFydL.d.ts → core-C-6xHzRx.d.ts} +6 -3
  9. package/dist/domain/command-queues.d.ts +1 -1
  10. package/dist/domain/command-queues.js +1 -1
  11. package/dist/domain/command-queues.js.map +1 -1
  12. package/dist/domain/context-projection.d.ts +2 -0
  13. package/dist/domain/context-projection.js +32 -0
  14. package/dist/domain/context-projection.js.map +1 -0
  15. package/dist/domain/message-transcript.d.ts +1 -1
  16. package/dist/domain/model-usage.d.ts +2 -0
  17. package/dist/domain/model-usage.js +59 -0
  18. package/dist/domain/model-usage.js.map +1 -0
  19. package/dist/domain/reduced-state-schema.d.ts +14 -18
  20. package/dist/domain/reduced-state-schema.js +7 -11
  21. package/dist/domain/reduced-state-schema.js.map +1 -1
  22. package/dist/domain/reduced-state.d.ts +3 -2
  23. package/dist/domain/reduced-state.js +3 -2
  24. package/dist/domain/run-scheduling.d.ts +2 -0
  25. package/dist/domain/run-scheduling.js +127 -0
  26. package/dist/domain/run-scheduling.js.map +1 -0
  27. package/dist/{durable-C3Rz7kg3.js → durable-BPHVFVvV.js} +74 -83
  28. package/dist/durable-BPHVFVvV.js.map +1 -0
  29. package/dist/{durable-DlScwmCy.d.ts → durable-DeLCAvbw.d.ts} +1256 -104
  30. package/dist/envelope-DkZyMIgp.d.ts +191 -0
  31. package/dist/envelope-DxQzo5rN.js +82 -0
  32. package/dist/envelope-DxQzo5rN.js.map +1 -0
  33. package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-KaeDSfeP.d.ts} +11 -31
  34. package/dist/{keep-alive-p8dIcSVy.js → event-factory-QuC_UvyP.js} +8 -10
  35. package/dist/event-factory-QuC_UvyP.js.map +1 -0
  36. package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
  37. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator--x6itQZ2.d.ts} +3 -2
  38. package/dist/index.d.ts +7 -6
  39. package/dist/index.js +5 -4
  40. package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
  41. package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-6PEzaEGn.d.ts} +4 -4
  42. package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
  43. package/dist/model-usage-CdBEkTwU.d.ts +55 -0
  44. package/dist/{prompt-projector-9_02lk5-.d.ts → prompt-projector-CNhqUsEr.d.ts} +15 -16
  45. package/dist/{reduced-state-C4nVVzz9.js → reduced-state-Bz68V2H8.js} +65 -32
  46. package/dist/reduced-state-Bz68V2H8.js.map +1 -0
  47. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-CCSzc4h8.d.ts} +16 -6
  48. package/dist/run-scheduler-DcS_okUH.d.ts +43 -0
  49. package/dist/run-scheduling-wakeup-CeHrvXie.d.ts +25 -0
  50. package/dist/{runtime-C56FQxiL.d.ts → runtime-WL_gKqxn.d.ts} +16 -7
  51. package/dist/services/compaction.d.ts +1 -1
  52. package/dist/services/compaction.js +1 -425
  53. package/dist/services/id-generator.d.ts +1 -1
  54. package/dist/services/id-generator.js +2 -1
  55. package/dist/services/id-generator.js.map +1 -1
  56. package/dist/services/keep-alive.d.ts +2 -0
  57. package/dist/services/keep-alive.js +13 -0
  58. package/dist/services/keep-alive.js.map +1 -0
  59. package/dist/services/model-resolver.d.ts +2 -0
  60. package/dist/services/model-resolver.js +17 -0
  61. package/dist/services/model-resolver.js.map +1 -0
  62. package/dist/services/prompt-projector.d.ts +2 -2
  63. package/dist/services/prompt-projector.js +20 -10
  64. package/dist/services/prompt-projector.js.map +1 -1
  65. package/dist/services/reducer-registry.d.ts +2 -2
  66. package/dist/services/reducer-registry.js +7 -3
  67. package/dist/services/reducer-registry.js.map +1 -1
  68. package/dist/services/run-scheduler.d.ts +3 -0
  69. package/dist/services/run-scheduler.js +25 -0
  70. package/dist/services/run-scheduler.js.map +1 -0
  71. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  72. package/dist/services/run-scheduling-wakeup.js +13 -0
  73. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  74. package/dist/services/runtime-layer.d.ts +67 -0
  75. package/dist/services/runtime-layer.js +47 -0
  76. package/dist/services/runtime-layer.js.map +1 -0
  77. package/dist/services/runtime.d.ts +1 -1
  78. package/dist/services/runtime.js +21 -14
  79. package/dist/services/runtime.js.map +1 -1
  80. package/dist/services/session-event-observer.d.ts +2 -0
  81. package/dist/services/session-event-observer.js +13 -0
  82. package/dist/services/session-event-observer.js.map +1 -0
  83. package/dist/services/session-query.d.ts +2 -2
  84. package/dist/services/session-query.js +140 -1
  85. package/dist/services/session-query.js.map +1 -0
  86. package/dist/services/session-state.d.ts +2 -0
  87. package/dist/services/session-state.js +2 -0
  88. package/dist/services/session-store.d.ts +2 -2
  89. package/dist/services/session-store.js +182 -2
  90. package/dist/services/session-store.js.map +1 -0
  91. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  92. package/dist/services/sink-checkpoint-store.js +49 -0
  93. package/dist/services/sink-checkpoint-store.js.map +1 -0
  94. package/dist/services/sink-registry.d.ts +1 -1
  95. package/dist/services/sink-registry.js +1 -1
  96. package/dist/services/span-names.d.ts +1 -1
  97. package/dist/services/span-names.js +3 -0
  98. package/dist/services/span-names.js.map +1 -1
  99. package/dist/services/tool-registry.d.ts +1 -1
  100. package/dist/services/tracing.d.ts +1 -1
  101. package/dist/services/tracing.js +23 -2
  102. package/dist/services/tracing.js.map +1 -1
  103. package/dist/session-event-observer-DaFMKKNc.d.ts +24 -0
  104. package/dist/session-query-DfW_4KC0.d.ts +47 -0
  105. package/dist/{session-query-DOc1KanA.js → session-state-BIZ2SYaP.js} +350 -183
  106. package/dist/session-state-BIZ2SYaP.js.map +1 -0
  107. package/dist/{session-query-DlRo5Ufc.d.ts → session-state-BeR2rZRR.d.ts} +144 -46
  108. package/dist/{session-store-D2Ore1QC.d.ts → session-store-J_Un45kW.d.ts} +7 -96
  109. package/dist/sink-checkpoint-store-C9hUxfH0.d.ts +40 -0
  110. package/dist/{sink-registry-CFC6xjsN.js → sink-registry-Bbqhtdnx.js} +27 -67
  111. package/dist/sink-registry-Bbqhtdnx.js.map +1 -0
  112. package/dist/{sink-registry-CIU0LD3m.d.ts → sink-registry-DuDkNXjZ.d.ts} +24 -49
  113. package/dist/testkit/layers.d.ts +24 -14
  114. package/dist/testkit/layers.js +18 -11
  115. package/dist/testkit/layers.js.map +1 -1
  116. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-BDmJe_Wr.d.ts} +4 -4
  117. package/dist/types/commands.d.ts +2 -2
  118. package/dist/types/commands.js +7 -2
  119. package/dist/types/commands.js.map +1 -1
  120. package/dist/types/core.d.ts +2 -2
  121. package/dist/types/core.js +4 -2
  122. package/dist/types/core.js.map +1 -1
  123. package/dist/types/events/durable.d.ts +2 -2
  124. package/dist/types/events/durable.js +2 -2
  125. package/dist/types/events.d.ts +4 -3
  126. package/dist/types/events.js +3 -2
  127. package/dist/types/events.js.map +1 -1
  128. package/dist/websocket.d.ts +2776 -0
  129. package/dist/websocket.js +498 -0
  130. package/dist/websocket.js.map +1 -0
  131. package/package.json +68 -43
  132. package/testing/offline-trace/README.md +2 -1
  133. package/CHANGELOG.md +0 -10
  134. package/CONTRIBUTING.md +0 -26
  135. package/SECURITY.md +0 -8
  136. package/dist/durable-C3Rz7kg3.js.map +0 -1
  137. package/dist/durable-object-runtime-B7jwBY2R.js +0 -1494
  138. package/dist/durable-object-runtime-B7jwBY2R.js.map +0 -1
  139. package/dist/durable-object-runtime-pWv0ohlz.d.ts +0 -257
  140. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  141. package/dist/host/durable-object-runtime.d.ts +0 -2
  142. package/dist/host/durable-object-runtime.js +0 -2
  143. package/dist/host/durable-object-storage.d.ts +0 -2
  144. package/dist/host/durable-object-storage.js +0 -0
  145. package/dist/host/durable-object.d.ts +0 -83
  146. package/dist/host/durable-object.js +0 -191
  147. package/dist/host/durable-object.js.map +0 -1
  148. package/dist/host/websocket-wire.d.ts +0 -2
  149. package/dist/host/websocket-wire.js +0 -88
  150. package/dist/host/websocket-wire.js.map +0 -1
  151. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  152. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  153. package/dist/services/compaction.js.map +0 -1
  154. package/dist/session-query-DOc1KanA.js.map +0 -1
  155. package/dist/session-store-pYxQW9qh.js +0 -214
  156. package/dist/session-store-pYxQW9qh.js.map +0 -1
  157. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  158. package/dist/websocket-wire-DvOu_6BJ.d.ts +0 -16773
  159. package/docs/assets/architecture.svg +0 -106
  160. package/docs/assets/event-sequence.svg +0 -143
  161. package/docs/assets/gcp-trace.png +0 -0
  162. package/docs/message-steering.md +0 -831
  163. package/docs/releasing.md +0 -57
  164. package/docs/spec.md +0 -774
  165. package/docs/subagents.md +0 -725
  166. package/docs/testing.md +0 -64
  167. package/docs/ui-projection.md +0 -742
  168. package/docs/websocket-protocol.md +0 -613
  169. package/examples/001-no-tools/README.md +0 -65
  170. package/examples/001-no-tools/worker.ts +0 -79
  171. package/examples/002-slack-bridge/README.md +0 -134
  172. package/examples/002-slack-bridge/events.ts +0 -115
  173. package/examples/002-slack-bridge/reducer.ts +0 -216
  174. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  175. package/examples/002-slack-bridge/sinks.ts +0 -109
  176. package/examples/002-slack-bridge/worker.ts +0 -140
  177. package/examples/003-sandbox-lifecycle/README.md +0 -78
  178. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  179. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  180. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  181. package/examples/_shared/event-id.ts +0 -12
  182. package/examples/_shared/http.ts +0 -27
  183. package/examples/_shared/openai.ts +0 -33
@@ -1,613 +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.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 serves both boundaries:
124
-
125
- - Pass it to the EDA host as `webSocketProtocol` so outbound frames are encoded and validated against the app's exact event union.
126
- - Share its `serverFrame`, `eventsFrame`, and `positionedEvent` schemas with browser or other WebSocket consumers for decoding and type inference.
127
-
128
- The exposed schemas describe the encoded JSON representation. Domain-only brands and transformations therefore do not leak into ordinary wire consumers, while every field is still derived from and checked by the domain event schemas. Switching on `event.type` narrows `event.payload` to that event's exact schema.
129
-
130
- 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.
131
-
132
- 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`.
133
-
134
- ## 3. Schema sketch
135
-
136
- 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.
137
-
138
- ```ts
139
- import * as Schema from "effect/Schema";
140
-
141
- import { SequenceNumber } from "effect-durable-agent/types/core";
142
- import { PositionedEvent } from "effect-durable-agent/types/events";
143
-
144
- export const EDA_WS_PROTOCOL_VERSION = 1 as const;
145
-
146
- export const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand("SubscriberId"));
147
- export type SubscriberId = typeof SubscriberId.Type;
148
-
149
- export const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(
150
- Schema.brand("FrameId"),
151
- );
152
- export type FrameId = typeof FrameId.Type;
153
-
154
- const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
155
-
156
- export const FlowControlConfig = Schema.Struct({
157
- ackTimeoutMs: PositiveInt,
158
- heartbeatIntervalMs: PositiveInt,
159
- maxFrameBytes: PositiveInt,
160
- maxFrameEvents: PositiveInt,
161
- maxInFlightFrames: PositiveInt,
162
- subscriberBufferCapacityEvents: PositiveInt,
163
- });
164
- export type FlowControlConfig = typeof FlowControlConfig.Type;
165
-
166
- export const HelloFrame = Schema.Struct({
167
- _tag: Schema.Literal("hello"),
168
- protocolVersion: Schema.Literal(1),
169
- subscriberId: SubscriberId,
170
- resumeSeq: SequenceNumber,
171
- flowControl: FlowControlConfig,
172
- });
173
-
174
- export const EventsFrame = Schema.Struct({
175
- _tag: Schema.Literal("events"),
176
- frameId: FrameId,
177
- // Ordered by Position. The first implementation may send one event per frame.
178
- events: Schema.NonEmptyArray(PositionedEvent),
179
- // Max durable seq included in this frame, or the previous durable seq when the frame contains only ephemerals.
180
- durableThroughSeq: SequenceNumber,
181
- });
182
-
183
- export const HeartbeatFrame = Schema.Struct({
184
- _tag: Schema.Literal("heartbeat"),
185
- serverTimeMs: UnixEpochMillis,
186
- // Latest durable seq the server has emitted on this connection. Clients may use
187
- // it for liveness/status, but heartbeats do not advance ACK frame ids.
188
- durableThroughSeq: SequenceNumber,
189
- });
190
-
191
- export const LaggedFrame = Schema.Struct({
192
- _tag: Schema.Literal("lagged"),
193
- resumeSeq: SequenceNumber,
194
- reason: Schema.Literals(["buffer-overflow", "ack-timeout"]),
195
- });
196
-
197
- export const ErrorFrame = Schema.Struct({
198
- _tag: Schema.Literal("error"),
199
- message: Schema.String,
200
- });
201
-
202
- export const ServerFrame = Schema.Union([
203
- HelloFrame,
204
- EventsFrame,
205
- HeartbeatFrame,
206
- LaggedFrame,
207
- ErrorFrame,
208
- ]);
209
- export type ServerFrame = typeof ServerFrame.Type;
210
-
211
- export const AckFrame = Schema.Struct({
212
- _tag: Schema.Literal("ack"),
213
- frameId: FrameId,
214
- // Highest durable seq the client has applied to its local state.
215
- durableThroughSeq: SequenceNumber,
216
- });
217
-
218
- export const ClientFrame = Schema.Union([AckFrame]);
219
- export type ClientFrame = typeof ClientFrame.Type;
220
- ```
221
-
222
- Notes:
223
-
224
- - `_tag` strings are intentionally short because they appear in every frame.
225
- - `events` frames are cumulative-ACKed by `frameId`: ACKing `N` acknowledges all frames with `frameId <= N`.
226
- - `heartbeat` frames are idle keepalives. They have no `frameId`, do not count against the in-flight ACK window, and must not be ACKed.
227
- - `durableThroughSeq` in an ACK must be monotonic and must not exceed the maximum durable `seq` sent through that frame. Violations are protocol errors.
228
- - Frame IDs are per-subscriber, start at `1`, and reset on reconnect.
229
-
230
- ## 4. Default policy values
231
-
232
- Current production defaults are bounded while leaving enough headroom for fast model deltas and larger durable tool/message events observed in replay:
233
-
234
- ```ts
235
- const defaultFlowControl = {
236
- subscriberBufferCapacityEvents: 2_048,
237
- maxInFlightFrames: 16,
238
- maxFrameEvents: 1,
239
- maxFrameBytes: 256 * 1024,
240
- ackTimeoutMs: 30_000,
241
- heartbeatIntervalMs: 10_000,
242
- };
243
- ```
244
-
245
- Later tuning can change only configuration:
246
-
247
- - Increase `maxFrameEvents` to `10-25` for high-frequency token deltas.
248
- - Add `maxFrameDelayMs = 25-50` if micro-batching by time is needed.
249
- - Keep `maxFrameBytes` below any practical browser/Worker frame-size concern and below the close-reason/attachment constraints.
250
-
251
- The bounded-memory invariant is the target for current and future tests:
252
-
253
- ```text
254
- Events retained by EDA subscriber workflow <= subscriberBufferCapacityEvents + maxInFlightFrames * maxFrameEvents
255
- Opaque WS bytes intentionally enqueued <= maxInFlightFrames * maxFrameBytes
256
- ```
257
-
258
- ## 5. Connection lifecycle
259
-
260
- ### 5.1 Handshake
261
-
262
- 1. HTTP route authenticates the request exactly like the former session events route.
263
- 2. Non-`Upgrade: websocket` requests return `426 Upgrade Required`.
264
- 3. Route resolves the session Durable Object by session id and forwards the upgrade request to the DO.
265
- 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.
266
- 5. The host starts or restores the subscriber workflow.
267
- 6. Server sends `hello` as the first application frame.
268
-
269
- Attachment shape:
270
-
271
- ```ts
272
- const EDAWebSocketAttachment = Schema.Struct({
273
- kind: Schema.Literal("eda-events-v1"),
274
- sessionId: SessionId,
275
- subscriberId: SubscriberId,
276
- lastAckedSeq: SequenceNumber,
277
- });
278
- ```
279
-
280
- The attachment must stay well under Cloudflare's 16 KiB attachment limit. It is updated only when ACKs advance `lastAckedSeq`.
281
-
282
- ### 5.2 Normal streaming
283
-
284
- 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.
285
- 2. Eager pump subscribes/replays and offers positioned events into `Queue.dropping`.
286
- 3. Sender builds one `events` frame from the queue when the in-flight window has capacity.
287
- 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.
288
- 5. Sender calls `ws.send(JSON.stringify(frame))` inside a small transport boundary effect.
289
- 6. Sender records event-frame metadata in `inFlight` and starts/refreshes the oldest-frame ACK deadline.
290
- 7. Client validates and applies events in order.
291
- 8. Client sends `ack` after applying an `events` frame to local state.
292
- 9. Server validates ACK, frees in-flight frames through `frameId`, advances `lastAckedSeq` if durable seq advanced, and updates the socket attachment.
293
-
294
- ### 5.3 Lag close
295
-
296
- A subscriber is lagged when either:
297
-
298
- - the eager pump cannot offer a new event into the bounded queue (`buffer-overflow`), or
299
- - the oldest in-flight frame is not ACKed within `ackTimeoutMs` (`ack-timeout`).
300
-
301
- 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:
302
-
303
- ```text
304
- lag;seq=123
305
- ```
306
-
307
- Close reasons must stay short because WebSocket close reasons have a small protocol limit.
308
-
309
- ### 5.4 Cancellation / close
310
-
311
- 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.
312
-
313
- If the Effect workflow completes or fails first, the finalizer closes the WebSocket unless it is already closing/closed.
314
-
315
- ### 5.5 Hibernation restore
316
-
317
- 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:
318
-
319
- 1. Re-run normal lightweight constructor/migration setup.
320
- 2. Inspect `ctx.getWebSockets()`.
321
- 3. For each socket with `kind: "eda-events-v1"`, ensure a subscriber workflow exists.
322
- 4. Start that workflow from `attachment.lastAckedSeq`.
323
-
324
- 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.
325
-
326
- ## 6. Effect-native runtime design
327
-
328
- ### 6.1 Boundary split
329
-
330
- 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.
331
-
332
- ```ts
333
- interface EDAEventWebSocketTransport {
334
- readonly send: (frame: ServerFrame) => Effect.Effect<void, SubscriberSendFailed>;
335
- readonly incoming: Queue.Queue<ClientFrame, SubscriberProtocolError>;
336
- readonly closed: Deferred.Deferred<void>;
337
- readonly persistAck: (seq: SequenceNumber) => Effect.Effect<void>;
338
- }
339
- ```
340
-
341
- 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.
342
-
343
- ### 6.2 Typed subscriber errors
344
-
345
- Expected failures are typed and serializable:
346
-
347
- ```ts
348
- export class SubscriberLagged extends Schema.TaggedErrorClass<SubscriberLagged>()(
349
- "SubscriberLagged",
350
- {
351
- subscriberId: SubscriberId,
352
- lastAckedSeq: SequenceNumber,
353
- reason: Schema.Literals(["buffer-overflow", "ack-timeout"]),
354
- },
355
- ) {}
356
-
357
- export class SubscriberProtocolError extends Schema.TaggedErrorClass<SubscriberProtocolError>()(
358
- "SubscriberProtocolError",
359
- {
360
- subscriberId: SubscriberId,
361
- message: Schema.String,
362
- },
363
- ) {}
364
-
365
- export class SubscriberSendFailed extends Schema.TaggedErrorClass<SubscriberSendFailed>()(
366
- "SubscriberSendFailed",
367
- {
368
- subscriberId: SubscriberId,
369
- cause: Schema.Defect,
370
- },
371
- ) {}
372
- ```
373
-
374
- Mapping to close codes happens once:
375
-
376
- | Error | Code | Reason |
377
- | --- | ---: | --- |
378
- | `SubscriberLagged` | `4008` | `lag;seq=<lastAckedSeq>` |
379
- | `SubscriberProtocolError` | `1002` | `protocol` |
380
- | `SubscriberSendFailed` | `1011` | `send-failed` |
381
- | client normal close | no server override / `1000` | `normal` |
382
- | host shutdown | future use of `1001` | `going-away` |
383
-
384
- Defects are not converted into ordinary lag. They are logged as defects and close with `1011` if the socket is still open.
385
-
386
- ### 6.3 Workflow sketch
387
-
388
- Pseudo-code shape, not final API:
389
-
390
- ```ts
391
- const runWebSocketSubscriber = Effect.fn("EDAWebSocketSubscriber.run")(function* (input) {
392
- const outbound = yield* Queue.dropping<PositionedEvent>(input.policy.subscriberBufferCapacityEvents);
393
- const closed = input.transport.closed;
394
- const lastAckedSeq = yield* Ref.make(input.resumeSeq);
395
- const nextFrameId = yield* Ref.make(FrameId.make(1));
396
- const inFlight = yield* Ref.make<ReadonlyArray<SentFrame>>([]);
397
-
398
- yield* input.transport.send(new HelloFrame({
399
- protocolVersion: 1,
400
- subscriberId: input.subscriberId,
401
- resumeSeq: input.resumeSeq,
402
- flowControl: input.policy,
403
- }));
404
-
405
- const source = yield* input.runtime.eventsAfter(input.resumeSeq);
406
-
407
- const pump = source.pipe(
408
- Stream.interruptWhen(Deferred.await(closed)),
409
- Stream.runForEach((event) =>
410
- Queue.offer(outbound, event).pipe(
411
- Effect.flatMap((accepted) =>
412
- accepted
413
- ? Effect.void
414
- : Effect.gen(function* () {
415
- const seq = yield* Ref.get(lastAckedSeq);
416
- yield* new SubscriberLagged({
417
- subscriberId: input.subscriberId,
418
- lastAckedSeq: seq,
419
- reason: "buffer-overflow",
420
- });
421
- }),
422
- ),
423
- ),
424
- ),
425
- );
426
-
427
- const ackLoop = readAckFrames(input.transport.incoming, inFlight, lastAckedSeq, input.transport.persistAck);
428
- const sender = sendFrames(outbound, inFlight, nextFrameId, lastAckedSeq, input.transport, input.policy);
429
- const timeout = watchAckTimeouts(inFlight, lastAckedSeq, input.policy);
430
-
431
- yield* Effect.raceFirst(
432
- pump,
433
- Effect.raceFirst(sender, Effect.raceFirst(ackLoop, timeout)),
434
- ).pipe(
435
- Effect.ensuring(Deferred.succeed(closed, undefined).pipe(Effect.ignore)),
436
- );
437
- }).pipe(Effect.scoped);
438
- ```
439
-
440
- Design details:
441
-
442
- - 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.
443
- - The sender is the only place that drains `outbound`. It waits when `inFlight.length >= maxInFlightFrames`.
444
- - ACK handling is cumulative. It removes all sent frames with `frameId <= ack.frameId`, then advances `lastAckedSeq` to `max(current, ack.durableThroughSeq)` after validation.
445
- - `watchAckTimeouts` observes only the oldest in-flight frame. No in-flight frames means no timeout.
446
- - `persistAck` updates WebSocket attachment. It is intentionally not a durable database write.
447
- - `Effect.raceFirst` is used because whichever branch fails/completes should tear down the subscriber; losers are interrupted and finalizers run.
448
-
449
- ### 6.4 Sender batching algorithm
450
-
451
- Initial algorithm with one event per frame:
452
-
453
- 1. Wait until in-flight window has capacity.
454
- 2. `Queue.take(outbound)`.
455
- 3. Encode a candidate frame.
456
- 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.
457
- 5. Send frame.
458
- 6. Add to in-flight metadata: `{ frameId, durableThroughSeq, sentAtMs, maxDurableSeqAllowed }`.
459
-
460
- Future micro-batch algorithm:
461
-
462
- 1. Take first event immediately.
463
- 2. Pull `Queue.takeUpTo(outbound, maxFrameEvents - 1)`.
464
- 3. Keep appending while encoded size remains `<= maxFrameBytes`.
465
- 4. If time-based batching is introduced, use Effect `Clock`/`TestClock`, not raw `setTimeout`.
466
-
467
- Batch metadata:
468
-
469
- - `durableThroughSeq` is the max durable event `seq` in the frame, or current `lastAckedSeq` for ephemeral-only frames.
470
- - Frame event order must already be `Position` order. The subscriber does not sort the ongoing live stream; reconnect prefix sorting stays in `EDASessionQuery.eventsAfter`.
471
-
472
- ## 7. Client obligations
473
-
474
- The browser client must:
475
-
476
- 1. Open WebSocket with its current durable cursor: `?afterSeq=<lastDurableAppliedSeq>`.
477
- 2. Wait for `hello` and validate `protocolVersion === 1`.
478
- 3. Ignore `heartbeat` frames for state application. They only prove the socket is alive and report the server's latest emitted durable seq.
479
- 4. Process `events` frames in `frameId` order. If a frame id skips unexpectedly, close and reconnect from the last applied durable seq.
480
- 5. Apply events to local state idempotently:
481
- - Drop durable events with `position.seq <= lastDurableAppliedSeq`.
482
- - Apply ephemerals only if they are relevant to the current live turn/session view.
483
- 6. ACK only after events are validated and applied to client state:
484
-
485
- ```json
486
- { "_tag": "ack", "frameId": 42, "durableThroughSeq": 123 }
487
- ```
488
-
489
- 7. Do not ACK `heartbeat` frames; they have no `frameId` and do not affect backpressure.
490
- 8. On close `4008`, reconnect from the sequence in close reason if present, otherwise from local `lastDurableAppliedSeq`.
491
- 9. Use bounded exponential backoff for abnormal reconnects.
492
-
493
- ACK after state application, not merely after receipt, is intentional: it backpressures on a busy browser main thread as well as on network delay.
494
-
495
- ## 8. `LiveEventBus` active-turn ephemeral replay buffer
496
-
497
- The WebSocket subscriber protocol depends on a live-only reconnect source owned by `LiveEventBus` with these semantics:
498
-
499
- ```ts
500
- interface ActiveTurnEphemeralReplay {
501
- readonly turnId?: TurnId;
502
- readonly events: ReadonlyArray<PositionedEvent>; // ephemerals only, ordered by Position
503
- readonly overflowed: boolean;
504
- }
505
-
506
- interface LiveEventBusShape {
507
- readonly publish: (event: PositionedEvent) => Effect.Effect<boolean>;
508
- readonly subscribeQueue: () => Effect.Effect<PubSub.Subscription<PositionedEvent>, never, Scope.Scope>;
509
- readonly activeTurnReplay: () => Effect.Effect<ActiveTurnEphemeralReplay>;
510
- }
511
- ```
512
-
513
- Ownership rules:
514
-
515
- 1. `SessionState` still emits every durable and ephemeral event through `LiveEventBus.publish` after assigning authoritative positions and folding durable state.
516
- 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:
517
- - `TurnStarted` opens or resets the active-turn buffer for that `turnId`.
518
- - active-turn ephemerals append to the buffer in `Position` order.
519
- - `TurnCompleted`, `TurnStopped`, or `TurnFailed` publishes the terminal and closes the current turn buffer, dropping its ephemerals at that checkpoint.
520
- 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`.
521
- 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.
522
- 5. Once the turn terminal durable event is observed, clients should retire live accumulators for that turn and rely on durable transcript/lifecycle state.
523
-
524
- 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.
525
-
526
- 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.
527
-
528
- ## 9. Observability
529
-
530
- Every subscriber run should have a span such as `eda.ws.subscriber` with attributes:
531
-
532
- - `sessionId`
533
- - `subscriberId`
534
- - `resumeSeq`
535
- - `lastAckedSeq`
536
- - `queueCapacityEvents`
537
- - `queueSize` where cheap/available
538
- - `inFlightFrames`
539
- - `maxInFlightFrames`
540
- - `closeCode`
541
- - `closeReason`
542
- - `lagReason`
543
-
544
- Logs:
545
-
546
- - connect/restore with resume seq
547
- - ACK advancement
548
- - lag close with queue size/in-flight details
549
- - protocol error with sanitized reason
550
- - send defect with `Schema.Defect`
551
-
552
- Metrics later:
553
-
554
- - active subscribers
555
- - lag closes by reason
556
- - ack latency histogram
557
- - frames sent
558
- - events sent
559
- - reconnect count
560
-
561
- ## 10. Security and boundary validation
562
-
563
- - Authenticate and authorize before upgrade. Do not accept a WebSocket and then authenticate inside the protocol.
564
- - Decode every inbound client frame with `Schema.decodeUnknownEffect(ClientFrame)` after JSON parse.
565
- - Reject binary frames.
566
- - Treat unknown `_tag`, malformed JSON, non-monotonic ACKs, ACKs for unsent future frames, and `durableThroughSeq` beyond sent durable max as `SubscriberProtocolError`.
567
- - Do not expose raw internal error details in `error` frames or close reasons.
568
-
569
- Future hardening: cap inbound text frame size before `JSON.parse`; ACK frames should be tiny.
570
-
571
- ## 11. Testing status and future hardening
572
-
573
- Current tests cover the implemented slice:
574
-
575
- 1. **Normal subscriber delivery:** fake runtime stream emits events; fake transport records frames; ACKs advance `lastAckedSeq` and attachment persistence is called.
576
- 2. **Overflow lag:** with no ACKs and a tiny subscriber buffer, the pump fails with `SubscriberLagged`.
577
- 3. **Active-turn ephemeral replay:** reconnect during an open turn emits buffered ephemerals even when their durable anchor `seq <= afterSeq`.
578
- 4. **Turn terminal checkpoint:** committing `TurnCompleted`/`TurnStopped`/`TurnFailed` drops prior buffered ephemerals; subsequent reconnect receives durable facts only for that completed turn.
579
- 5. **Merged reconnect ordering:** durable replay, buffered live events, and active-turn ephemerals sort into a reconnect-safe prefix.
580
- 6. **Cloudflare host flow:** fake DO WebSocket upgrade streams frames and ACK updates `serializeAttachment`.
581
- 7. **Integration flow:** fake WebSocket-style route/runtime tests exercise the WebSocket-only session event path.
582
-
583
- Future hardening tests should add:
584
-
585
- - ACK-gated send assertions that the sender stops draining `outbound` while the in-flight window is full.
586
- - ACK timeout with `TestClock.adjust(ackTimeoutMs)` producing `SubscriberLagged { reason: "ack-timeout" }`.
587
- - Protocol errors for malformed ACKs, ACKs for unsent future frames, and durable seq advancement beyond sent frame boundaries.
588
- - Oversized outbound frame behavior and inbound text-frame byte cap before JSON parse.
589
- - Explicit client reducer reset/de-duplication behavior after active-turn replay overflow.
590
-
591
- Integration tests can later use a real Cloudflare Workers test pool if available.
592
-
593
- ## 12. Implemented artifacts and remaining work
594
-
595
- Implemented artifacts:
596
-
597
- 1. `src/host/websocket-wire.ts` defines the app-event-parameterized public wire schemas and encoder.
598
- 2. `src/host/websocket-protocol.ts` defines host frame schemas, attachment schema, flow-control config, close-code constants, and encode/decode helpers.
599
- 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()`.
600
- 4. `src/services/session-query.ts` / `EDARuntime.eventsAfter(...)` merge durable replay, active-turn ephemerals, already-buffered live events, and follow-live delivery.
601
- 5. `src/services/websocket-subscriber.ts` defines typed subscriber errors and `runWebSocketSubscriber(...)` over `EDARuntime.eventsAfter`, `Queue.dropping`, ACK refs, scoped cancellation, and ACK timeouts.
602
- 6. `src/host/durable-object-runtime.ts` adapts Cloudflare WebSockets to the transport, persists ACKs in `serializeAttachment`, restores accepted sockets, and maps typed errors to close codes.
603
- 7. `src/host/durable-object.ts`, `app/routes/api.eda-agent.sessions.$sessionId.events.ts`, and `workers/eda-agent/api.ts` expose a WebSocket-only events route with `426` for non-upgrade requests.
604
- 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.
605
-
606
- Remaining hardening:
607
-
608
- 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.
609
- 2. Inbound text-frame byte cap before JSON parse.
610
- 3. Focused ACK-timeout and protocol-error tests.
611
- 4. Micro-batching (`maxFrameEvents > 1`, optional frame delay) once token volume needs it.
612
- 5. Explicit client-visible behavior for active-turn replay overflow.
613
- 6. Real Cloudflare Workers/WebSocket integration test pool if available.