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
@@ -0,0 +1,428 @@
1
+ import { Position, SequenceNumber } from "./types/core.js";
2
+ import { V as EDADurableEvent, cr as EventEnvelope, mr as PositionedEvent, yr as UnixEpochMillis } from "./durable-DsV9PxZC.js";
3
+ import { EDAEphemeralEvent } from "./types/events.js";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Schema from "effect/Schema";
6
+ //#region src/websocket/protocol.ts
7
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
8
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
9
+ /** Current EDA live-event WebSocket wire protocol version. */
10
+ const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1;
11
+ /** Flow-control policy announced by the server in the hello frame. */
12
+ const EDAWebSocketWireFlowControl = Schema.Struct({
13
+ ackTimeoutMs: PositiveInt,
14
+ /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */
15
+ heartbeatIntervalMs: PositiveInt,
16
+ maxFrameBytes: PositiveInt,
17
+ maxFrameEvents: PositiveInt,
18
+ maxInFlightFrames: PositiveInt,
19
+ /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */
20
+ pingIntervalMs: Schema.optionalKey(PositiveInt),
21
+ subscriberBufferCapacityEvents: PositiveInt
22
+ });
23
+ /**
24
+ * Canonical client liveness ping message.
25
+ *
26
+ * The exact string matters: hibernation-capable hosts register it with
27
+ * WebSocket auto-response so the runtime answers without waking the object.
28
+ */
29
+ const EDA_WEB_SOCKET_PING_MESSAGE = "{\"_tag\":\"ping\"}";
30
+ /** Canonical server pong message paired with {@link EDA_WEB_SOCKET_PING_MESSAGE}. */
31
+ const EDA_WEB_SOCKET_PONG_MESSAGE = "{\"_tag\":\"pong\"}";
32
+ /** Client liveness ping; hosts answer with a pong and never ACK-track it. */
33
+ const EDAWebSocketWirePingFrame = Schema.Struct({ _tag: Schema.Literal("ping") });
34
+ /** Server liveness pong; clients may ignore it and must not ACK it. */
35
+ const EDAWebSocketWirePongFrame = Schema.Struct({ _tag: Schema.Literal("pong") });
36
+ const EDAWebSocketWireHelloFrame = Schema.Struct({
37
+ _tag: Schema.Literal("hello"),
38
+ protocolVersion: Schema.Literal(1),
39
+ subscriberId: Schema.NonEmptyString,
40
+ resumeSeq: NonNegativeInt,
41
+ flowControl: EDAWebSocketWireFlowControl
42
+ });
43
+ const EDAWebSocketWireHeartbeatFrame = Schema.Struct({
44
+ _tag: Schema.Literal("heartbeat"),
45
+ serverTimeMs: NonNegativeInt,
46
+ durableThroughSeq: NonNegativeInt
47
+ });
48
+ const EDAWebSocketWireLaggedFrame = Schema.Struct({
49
+ _tag: Schema.Literal("lagged"),
50
+ resumeSeq: NonNegativeInt,
51
+ reason: Schema.Literals(["buffer-overflow", "ack-timeout"])
52
+ });
53
+ const EDAWebSocketWireErrorFrame = Schema.Struct({
54
+ _tag: Schema.Literal("error"),
55
+ message: Schema.String
56
+ });
57
+ const EDAWebSocketWireAckFrame = Schema.Struct({
58
+ _tag: Schema.Literal("ack"),
59
+ frameId: PositiveInt,
60
+ durableThroughSeq: NonNegativeInt
61
+ });
62
+ const EDAWebSocketWireClientFrame = Schema.Union([EDAWebSocketWireAckFrame, EDAWebSocketWirePingFrame]);
63
+ /** Complete framework-owned event union present on every EDA WebSocket. */
64
+ const EDAFrameworkWebSocketEvent = Schema.Union([EDADurableEvent, EDAEphemeralEvent]);
65
+ const makeEDAWebSocketDomainSchemas = (event) => {
66
+ const positionedEvent = Schema.Struct({
67
+ position: Position,
68
+ event
69
+ });
70
+ const eventsFrame = Schema.Struct({
71
+ _tag: Schema.Literal("events"),
72
+ frameId: PositiveInt,
73
+ events: Schema.NonEmptyArray(positionedEvent),
74
+ durableThroughSeq: NonNegativeInt
75
+ });
76
+ return {
77
+ event,
78
+ positionedEvent,
79
+ eventsFrame,
80
+ serverFrame: Schema.Union([
81
+ EDAWebSocketWireHelloFrame,
82
+ eventsFrame,
83
+ EDAWebSocketWireHeartbeatFrame,
84
+ EDAWebSocketWirePongFrame,
85
+ EDAWebSocketWireLaggedFrame,
86
+ EDAWebSocketWireErrorFrame
87
+ ])
88
+ };
89
+ };
90
+ makeEDAWebSocketDomainSchemas(EventEnvelope);
91
+ const makeEDAWebSocketWireProtocolFromEventSchema = (event) => {
92
+ const domain = makeEDAWebSocketDomainSchemas(event);
93
+ const encodeDomainServerFrame = Schema.encodeSync(domain.serverFrame);
94
+ const encodeUnknownDomainServerFrame = Schema.encodeUnknownSync(domain.serverFrame);
95
+ const encodeServerFrame = (frame) => JSON.stringify(encodeDomainServerFrame(frame));
96
+ return {
97
+ domain,
98
+ wire: {
99
+ event: Schema.toEncoded(domain.event),
100
+ positionedEvent: Schema.toEncoded(domain.positionedEvent),
101
+ eventsFrame: Schema.toEncoded(domain.eventsFrame),
102
+ serverFrame: Schema.toEncoded(domain.serverFrame),
103
+ clientFrame: EDAWebSocketWireClientFrame
104
+ },
105
+ encodeServerFrame,
106
+ host: { encodeServerFrame: (frame) => JSON.stringify(encodeUnknownDomainServerFrame(frame)) }
107
+ };
108
+ };
109
+ /** Strict framework-only protocol used when an app registers no custom events. */
110
+ const edaFrameworkWebSocketWireProtocol = makeEDAWebSocketWireProtocolFromEventSchema(EDAFrameworkWebSocketEvent);
111
+ /**
112
+ * Bind the generic EDA WebSocket transport to one app's custom event schema.
113
+ *
114
+ * Framework durable and ephemeral events are included automatically. Future EDA
115
+ * apps register only their custom events. Servers use the returned domain schemas
116
+ * and typed encoder; external consumers decode with the wire schemas. Pass the
117
+ * returned `host` adapter to the selected host package.
118
+ */
119
+ const makeEDAWebSocketWireProtocol = (options) => makeEDAWebSocketWireProtocolFromEventSchema(Schema.Union([EDAFrameworkWebSocketEvent, options.appEvents]));
120
+ //#endregion
121
+ //#region src/websocket/messages.ts
122
+ /** Current EDA live-event WebSocket protocol version. */
123
+ const EDA_WEB_SOCKET_PROTOCOL_VERSION = 1;
124
+ /** WebSocket close code used when a subscriber cannot keep up with live delivery. */
125
+ const EDA_WS_CLOSE_LAGGED = 4008;
126
+ /** WebSocket close code used for normal host-driven shutdown. */
127
+ const EDA_WS_CLOSE_GOING_AWAY = 1001;
128
+ /** WebSocket close code used for malformed client protocol messages. */
129
+ const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;
130
+ /** WebSocket close code used when the host cannot send a frame. */
131
+ const EDA_WS_CLOSE_SEND_FAILED = 1011;
132
+ /** WebSocket close code used for unsupported binary messages. */
133
+ const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;
134
+ /** Live subscriber identity persisted in WebSocket attachments. */
135
+ const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand("SubscriberId"));
136
+ /** Per-connection monotonically increasing server frame id. */
137
+ const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(Schema.brand("FrameId"));
138
+ /** Flow-control policy announced by the server in the hello frame. */
139
+ const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;
140
+ /** Default bounded policy sized for fast model deltas and large durable tool/message events. */
141
+ const defaultEDAWebSocketFlowControl = {
142
+ ackTimeoutMs: 3e4,
143
+ heartbeatIntervalMs: 1e4,
144
+ maxFrameBytes: 256 * 1024,
145
+ maxFrameEvents: 1,
146
+ maxInFlightFrames: 16,
147
+ pingIntervalMs: 3e4,
148
+ subscriberBufferCapacityEvents: 2048
149
+ };
150
+ /** First server frame; announces protocol and flow-control policy. */
151
+ const EDAWebSocketHelloFrame = Schema.Struct({
152
+ ...EDAWebSocketWireHelloFrame.fields,
153
+ subscriberId: SubscriberId,
154
+ resumeSeq: SequenceNumber
155
+ });
156
+ /** Ordered positioned events delivered to the client. */
157
+ const EDAWebSocketEventsFrame = Schema.Struct({
158
+ _tag: Schema.Literal("events"),
159
+ frameId: FrameId,
160
+ events: Schema.NonEmptyArray(PositionedEvent),
161
+ durableThroughSeq: SequenceNumber
162
+ });
163
+ /**
164
+ * Deprecated idle server keepalive frame.
165
+ *
166
+ * Servers no longer send heartbeats; the schema remains so deployed clients
167
+ * keep decoding the server frame union. Liveness is client-originated via
168
+ * {@link EDAWebSocketPingFrame} and the host-level auto-response pong.
169
+ */
170
+ const EDAWebSocketHeartbeatFrame = Schema.Struct({
171
+ ...EDAWebSocketWireHeartbeatFrame.fields,
172
+ serverTimeMs: UnixEpochMillis,
173
+ durableThroughSeq: SequenceNumber
174
+ });
175
+ /** Client liveness ping; hosts answer with a pong and never ACK-track it. */
176
+ const EDAWebSocketPingFrame = EDAWebSocketWirePingFrame;
177
+ /** Server liveness pong; clients may ignore it and must not ACK it. */
178
+ const EDAWebSocketPongFrame = EDAWebSocketWirePongFrame;
179
+ /** Optional final frame sent before a lag-close. */
180
+ const EDAWebSocketLaggedFrame = Schema.Struct({
181
+ ...EDAWebSocketWireLaggedFrame.fields,
182
+ resumeSeq: SequenceNumber
183
+ });
184
+ /** Optional final frame sent before a protocol/internal close. */
185
+ const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;
186
+ /** Server-to-client application frame union. */
187
+ const EDAWebSocketServerFrame = Schema.Union([
188
+ EDAWebSocketHelloFrame,
189
+ EDAWebSocketEventsFrame,
190
+ EDAWebSocketHeartbeatFrame,
191
+ EDAWebSocketPongFrame,
192
+ EDAWebSocketLaggedFrame,
193
+ EDAWebSocketErrorFrame
194
+ ]);
195
+ /** Client acknowledgement after applying a server frame. */
196
+ const EDAWebSocketAckFrame = Schema.Struct({
197
+ ...EDAWebSocketWireAckFrame.fields,
198
+ frameId: FrameId,
199
+ durableThroughSeq: SequenceNumber
200
+ });
201
+ /** Client-to-server application frame union. */
202
+ const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame, EDAWebSocketPingFrame]);
203
+ /** Serialize a server frame for a text WebSocket message. */
204
+ const encodeEDAWebSocketServerFrame = (frame, protocol) => (protocol ?? edaFrameworkWebSocketWireProtocol.host).encodeServerFrame(frame);
205
+ /** Decode an inbound text WebSocket message at the host boundary. */
206
+ const decodeEDAWebSocketClientMessage = (input) => Effect.try({
207
+ try: () => JSON.parse(input),
208
+ catch: (error) => error
209
+ }).pipe(Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)), Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)));
210
+ /** Short close reason that fits the WebSocket protocol reason limit. */
211
+ const laggedCloseReason = (seq) => `lag;seq=${seq}`;
212
+ //#endregion
213
+ //#region src/websocket/delivery.ts
214
+ /** Slow subscriber reasons that intentionally close only the lagging socket. */
215
+ const SubscriberLagReason = Schema.Literals(["buffer-overflow", "ack-timeout"]);
216
+ /** One sent-but-unacknowledged events frame. */
217
+ const EDAWebSocketInFlightFrame = Schema.Struct({
218
+ frameId: FrameId,
219
+ durableThroughSeq: SequenceNumber,
220
+ sentAtMs: Schema.Number
221
+ });
222
+ /** Complete delivery bookkeeping persisted in the WebSocket attachment. */
223
+ const EDAWebSocketDeliveryCheckpoint = Schema.Struct({
224
+ lastAckedSeq: SequenceNumber,
225
+ lastAckedFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
226
+ lastSentFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
227
+ nextFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
228
+ sentDurableThroughSeq: SequenceNumber,
229
+ inFlight: Schema.Array(EDAWebSocketInFlightFrame)
230
+ });
231
+ /** Build delivery state for a newly accepted connection. */
232
+ const makeWebSocketDeliveryState = (input) => ({
233
+ subscriberId: input.subscriberId,
234
+ policy: input.policy,
235
+ lastAckedSeq: input.resumeSeq,
236
+ lastAckedFrameId: 0,
237
+ lastSentFrameId: 0,
238
+ nextFrameId: 1,
239
+ sentDurableThroughSeq: input.resumeSeq,
240
+ inFlight: [],
241
+ pendingEphemeral: []
242
+ });
243
+ /** Rebuild exact ACK bookkeeping from a hibernating WebSocket attachment. */
244
+ const restoreWebSocketDeliveryState = (input) => ({
245
+ subscriberId: input.subscriberId,
246
+ policy: input.policy,
247
+ ...input.checkpoint,
248
+ pendingEphemeral: []
249
+ });
250
+ /** Project in-memory delivery state into the attachment-safe checkpoint. */
251
+ const checkpointWebSocketDeliveryState = (state) => ({
252
+ lastAckedSeq: state.lastAckedSeq,
253
+ lastAckedFrameId: state.lastAckedFrameId,
254
+ lastSentFrameId: state.lastSentFrameId,
255
+ nextFrameId: state.nextFrameId,
256
+ sentDurableThroughSeq: state.sentDurableThroughSeq,
257
+ inFlight: state.inFlight
258
+ });
259
+ /** First frame for a freshly accepted connection. Restores never re-send hello. */
260
+ const deliveryHelloFrame = (state) => EDAWebSocketHelloFrame.make({
261
+ _tag: "hello",
262
+ protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
263
+ subscriberId: state.subscriberId,
264
+ resumeSeq: state.lastAckedSeq,
265
+ flowControl: state.policy
266
+ });
267
+ /** Deliver committed durable events read from the store. */
268
+ const onDurableEvents = (state, events, head, nowMs) => {
269
+ const stale = staleAckResult(state, nowMs);
270
+ if (stale !== void 0) return stale;
271
+ let next = state;
272
+ const frames = [];
273
+ let batch = [];
274
+ const flushBatch = () => {
275
+ if (batch.length === 0) return;
276
+ const sent = sendEventsFrame(next, batch, nowMs);
277
+ next = sent.state;
278
+ frames.push(sent.frame);
279
+ batch = [];
280
+ };
281
+ for (const event of events) {
282
+ if (event.event.durability === "durable" && event.position.seq <= next.sentDurableThroughSeq) continue;
283
+ if (batch.length === 0 && windowCapacity(next) <= 0) break;
284
+ batch.push(event);
285
+ if (batch.length >= next.policy.maxFrameEvents) flushBatch();
286
+ }
287
+ flushBatch();
288
+ return sentResult(next, frames, windowCapacity(next) > 0 && next.sentDurableThroughSeq < head ? next.sentDurableThroughSeq : void 0);
289
+ };
290
+ /** Deliver one live ephemeral event, buffering only while this isolate is active. */
291
+ const onEphemeralEvent = (state, event, nowMs) => {
292
+ const stale = staleAckResult(state, nowMs);
293
+ if (stale !== void 0) return stale;
294
+ if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {
295
+ const sent = sendEventsFrame(state, [event], nowMs);
296
+ return sentResult(sent.state, [sent.frame]);
297
+ }
298
+ const pendingEphemeral = [...state.pendingEphemeral, event];
299
+ if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) return laggedResult(state, "buffer-overflow");
300
+ return {
301
+ state: {
302
+ ...state,
303
+ pendingEphemeral
304
+ },
305
+ actions: []
306
+ };
307
+ };
308
+ /** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */
309
+ const onClientAck = (state, ack, nowMs) => {
310
+ const validated = applyAck(state, ack);
311
+ if (validated._tag === "close") return validated.result;
312
+ if (validated._tag === "ignore") return {
313
+ state,
314
+ actions: []
315
+ };
316
+ let next = validated.state;
317
+ const frames = [];
318
+ while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {
319
+ const [head, ...rest] = next.pendingEphemeral;
320
+ if (head === void 0) break;
321
+ const sent = sendEventsFrame({
322
+ ...next,
323
+ pendingEphemeral: rest
324
+ }, [head], nowMs);
325
+ next = sent.state;
326
+ frames.push(sent.frame);
327
+ }
328
+ const stale = staleAckResult(next, nowMs);
329
+ if (stale !== void 0) return stale;
330
+ return sentResult(next, frames, windowCapacity(next) > 0 && next.pendingEphemeral.length === 0 ? next.sentDurableThroughSeq : void 0, true);
331
+ };
332
+ const applyAck = (state, ack) => {
333
+ if (ack.frameId <= state.lastAckedFrameId) return ack.durableThroughSeq > state.lastAckedSeq ? protocolClose(state, "Duplicate ACK attempted to advance durable seq") : { _tag: "ignore" };
334
+ if (ack.frameId > state.lastSentFrameId) return protocolClose(state, "ACK referenced an unsent frame");
335
+ if (ack.durableThroughSeq < state.lastAckedSeq) return protocolClose(state, "ACK durable seq moved backwards");
336
+ const acknowledged = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);
337
+ if (acknowledged.length === 0) return protocolClose(state, "ACK referenced no in-flight frames");
338
+ const allowedDurableSeq = SequenceNumber.make(acknowledged.reduce((max, frame) => Math.max(max, frame.durableThroughSeq), state.lastAckedSeq));
339
+ if (ack.durableThroughSeq > allowedDurableSeq) return protocolClose(state, "ACK durable seq exceeded sent frame boundary");
340
+ return {
341
+ _tag: "apply",
342
+ state: {
343
+ ...state,
344
+ inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
345
+ lastAckedFrameId: ack.frameId,
346
+ lastAckedSeq: ack.durableThroughSeq
347
+ }
348
+ };
349
+ };
350
+ const windowCapacity = (state) => state.policy.maxInFlightFrames - state.inFlight.length;
351
+ const sendEventsFrame = (state, events, nowMs) => {
352
+ const [first, ...rest] = events;
353
+ if (first === void 0) throw new Error("Cannot send an empty events frame");
354
+ const frameId = FrameId.make(state.nextFrameId);
355
+ const durableThroughSeq = SequenceNumber.make(events.reduce((max, event) => event.event.durability === "durable" ? Math.max(max, event.position.seq) : max, state.sentDurableThroughSeq));
356
+ const frame = EDAWebSocketEventsFrame.make({
357
+ _tag: "events",
358
+ frameId,
359
+ events: [first, ...rest],
360
+ durableThroughSeq
361
+ });
362
+ return {
363
+ state: {
364
+ ...state,
365
+ inFlight: [...state.inFlight, {
366
+ frameId,
367
+ durableThroughSeq,
368
+ sentAtMs: nowMs
369
+ }],
370
+ lastSentFrameId: frameId,
371
+ nextFrameId: frameId + 1,
372
+ sentDurableThroughSeq: durableThroughSeq
373
+ },
374
+ frame
375
+ };
376
+ };
377
+ const sentResult = (state, frames, catchUpAfterSeq, stateChanged = frames.length > 0) => ({
378
+ state,
379
+ actions: [
380
+ ...stateChanged ? [{ _tag: "Persist" }] : [],
381
+ ...frames.length > 0 ? [{
382
+ _tag: "Send",
383
+ frames
384
+ }] : [],
385
+ ...catchUpAfterSeq === void 0 ? [] : [{
386
+ _tag: "ReadEventPage",
387
+ afterSeq: catchUpAfterSeq
388
+ }]
389
+ ]
390
+ });
391
+ /** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */
392
+ const staleAckResult = (state, nowMs) => state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs) ? laggedResult(state, "ack-timeout") : void 0;
393
+ const laggedResult = (state, reason) => ({
394
+ state,
395
+ actions: [{
396
+ _tag: "Send",
397
+ frames: [EDAWebSocketLaggedFrame.make({
398
+ _tag: "lagged",
399
+ resumeSeq: state.lastAckedSeq,
400
+ reason
401
+ })]
402
+ }, {
403
+ _tag: "Close",
404
+ code: EDA_WS_CLOSE_LAGGED,
405
+ reason: laggedCloseReason(state.lastAckedSeq)
406
+ }]
407
+ });
408
+ const protocolClose = (state, message) => ({
409
+ _tag: "close",
410
+ result: {
411
+ state,
412
+ actions: [{
413
+ _tag: "Send",
414
+ frames: [EDAWebSocketErrorFrame.make({
415
+ _tag: "error",
416
+ message: message.slice(0, 120)
417
+ })]
418
+ }, {
419
+ _tag: "Close",
420
+ code: EDA_WS_CLOSE_PROTOCOL_ERROR,
421
+ reason: "protocol"
422
+ }]
423
+ }
424
+ });
425
+ //#endregion
426
+ export { EDAFrameworkWebSocketEvent, EDAWebSocketAckFrame, EDAWebSocketClientFrame, EDAWebSocketDeliveryCheckpoint, EDAWebSocketErrorFrame, EDAWebSocketEventsFrame, EDAWebSocketFlowControl, EDAWebSocketHeartbeatFrame, EDAWebSocketHelloFrame, EDAWebSocketInFlightFrame, EDAWebSocketLaggedFrame, EDAWebSocketPingFrame, EDAWebSocketPongFrame, EDAWebSocketServerFrame, EDAWebSocketWireAckFrame, EDAWebSocketWireClientFrame, EDAWebSocketWireErrorFrame, EDAWebSocketWireFlowControl, EDAWebSocketWireHeartbeatFrame, EDAWebSocketWireHelloFrame, EDAWebSocketWireLaggedFrame, EDAWebSocketWirePingFrame, EDAWebSocketWirePongFrame, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, EDA_WS_CLOSE_GOING_AWAY, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, EDA_WS_CLOSE_UNSUPPORTED_DATA, FrameId, SubscriberId, SubscriberLagReason, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDAWebSocketFlowControl, deliveryHelloFrame, edaFrameworkWebSocketWireProtocol, encodeEDAWebSocketServerFrame, laggedCloseReason, makeEDAWebSocketWireProtocol, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent, restoreWebSocketDeliveryState };
427
+
428
+ //# sourceMappingURL=websocket.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.js","names":[],"sources":["../src/websocket/protocol.ts","../src/websocket/messages.ts","../src/websocket/delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { Position } from \"../types/core\";\nimport { EDADurableEvent, EDAEphemeralEvent, EventEnvelope } from \"../types/events\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** Current EDA live-event WebSocket wire protocol version. */\nexport const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1 as const;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketWireFlowControl = Schema.Struct({\n ackTimeoutMs: PositiveInt,\n /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */\n heartbeatIntervalMs: PositiveInt,\n maxFrameBytes: PositiveInt,\n maxFrameEvents: PositiveInt,\n maxInFlightFrames: PositiveInt,\n /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */\n pingIntervalMs: Schema.optionalKey(PositiveInt),\n subscriberBufferCapacityEvents: PositiveInt,\n});\nexport type EDAWebSocketWireFlowControl = typeof EDAWebSocketWireFlowControl.Type;\n\n/**\n * Canonical client liveness ping message.\n *\n * The exact string matters: hibernation-capable hosts register it with\n * WebSocket auto-response so the runtime answers without waking the object.\n */\nexport const EDA_WEB_SOCKET_PING_MESSAGE = '{\"_tag\":\"ping\"}';\n\n/** Canonical server pong message paired with {@link EDA_WEB_SOCKET_PING_MESSAGE}. */\nexport const EDA_WEB_SOCKET_PONG_MESSAGE = '{\"_tag\":\"pong\"}';\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketWirePingFrame = Schema.Struct({\n _tag: Schema.Literal(\"ping\"),\n});\nexport type EDAWebSocketWirePingFrame = typeof EDAWebSocketWirePingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketWirePongFrame = Schema.Struct({\n _tag: Schema.Literal(\"pong\"),\n});\nexport type EDAWebSocketWirePongFrame = typeof EDAWebSocketWirePongFrame.Type;\n\nexport const EDAWebSocketWireHelloFrame = Schema.Struct({\n _tag: Schema.Literal(\"hello\"),\n protocolVersion: Schema.Literal(EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION),\n subscriberId: Schema.NonEmptyString,\n resumeSeq: NonNegativeInt,\n flowControl: EDAWebSocketWireFlowControl,\n});\nexport type EDAWebSocketWireHelloFrame = typeof EDAWebSocketWireHelloFrame.Type;\n\nexport const EDAWebSocketWireHeartbeatFrame = Schema.Struct({\n _tag: Schema.Literal(\"heartbeat\"),\n serverTimeMs: NonNegativeInt,\n durableThroughSeq: NonNegativeInt,\n});\nexport type EDAWebSocketWireHeartbeatFrame = typeof EDAWebSocketWireHeartbeatFrame.Type;\n\nexport const EDAWebSocketWireLaggedFrame = Schema.Struct({\n _tag: Schema.Literal(\"lagged\"),\n resumeSeq: NonNegativeInt,\n reason: Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]),\n});\nexport type EDAWebSocketWireLaggedFrame = typeof EDAWebSocketWireLaggedFrame.Type;\n\nexport const EDAWebSocketWireErrorFrame = Schema.Struct({\n _tag: Schema.Literal(\"error\"),\n message: Schema.String,\n});\nexport type EDAWebSocketWireErrorFrame = typeof EDAWebSocketWireErrorFrame.Type;\n\nexport const EDAWebSocketWireAckFrame = Schema.Struct({\n _tag: Schema.Literal(\"ack\"),\n frameId: PositiveInt,\n durableThroughSeq: NonNegativeInt,\n});\nexport type EDAWebSocketWireAckFrame = typeof EDAWebSocketWireAckFrame.Type;\n\nexport const EDAWebSocketWireClientFrame = Schema.Union([\n EDAWebSocketWireAckFrame,\n EDAWebSocketWirePingFrame,\n]);\nexport type EDAWebSocketWireClientFrame = typeof EDAWebSocketWireClientFrame.Type;\n\n/** Exhaustive decision table for a concrete WebSocket event union. */\nexport type EDAWebSocketEventConsumerPolicy<\n Event extends { readonly type: string },\n Disposition,\n> = Readonly<Record<Event[\"type\"], Disposition>>;\n\n/** Complete framework-owned event union present on every EDA WebSocket. */\nexport const EDAFrameworkWebSocketEvent = Schema.Union([EDADurableEvent, EDAEphemeralEvent]);\nexport type EDAFrameworkWebSocketEvent = typeof EDAFrameworkWebSocketEvent.Type;\n\nconst makeEDAWebSocketDomainSchemas = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n) => {\n const positionedEvent = Schema.Struct({\n position: Position,\n event,\n });\n const eventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: PositiveInt,\n events: Schema.NonEmptyArray(positionedEvent),\n durableThroughSeq: NonNegativeInt,\n });\n const serverFrame = Schema.Union([\n EDAWebSocketWireHelloFrame,\n eventsFrame,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWirePongFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWireErrorFrame,\n ]);\n return { event, positionedEvent, eventsFrame, serverFrame };\n};\n\ntype EDAWebSocketDomainSchemas<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> = ReturnType<typeof makeEDAWebSocketDomainSchemas<EventSchema>>;\n\nconst EDAWebSocketHostDomain = makeEDAWebSocketDomainSchemas(EventEnvelope);\n\n/** Domain frame shape accepted by an app-bound encoder at the EDA host boundary. */\nexport type EDAWebSocketServerFrameInput = typeof EDAWebSocketHostDomain.serverFrame.Type;\n\n/** Minimal typed encoder surface consumed by an EDA host. */\nexport interface EDAWebSocketServerFrameEncoder {\n readonly encodeServerFrame: (frame: EDAWebSocketServerFrameInput) => string;\n}\n\n/** App-bound domain schemas, wire schemas, and encoders for protocol version 1. */\nexport interface EDAWebSocketWireProtocol<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> {\n /** Exact app-bound schemas whose `Type` values are used inside the server. */\n readonly domain: EDAWebSocketDomainSchemas<EventSchema>;\n /** Exact app-bound schemas whose `Type` values are the serialized JSON representation. */\n readonly wire: {\n readonly event: Schema.toEncoded<EventSchema>;\n readonly positionedEvent: Schema.toEncoded<\n EDAWebSocketDomainSchemas<EventSchema>[\"positionedEvent\"]\n >;\n readonly eventsFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"eventsFrame\"]>;\n readonly serverFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>;\n readonly clientFrame: typeof EDAWebSocketWireClientFrame;\n };\n /** Serialize one exact app-bound domain frame to a JSON text message. */\n readonly encodeServerFrame: (\n frame: Schema.Schema.Type<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>,\n ) => string;\n /** Validate broad host frames against the app event union before serialization. */\n readonly host: EDAWebSocketServerFrameEncoder;\n}\n\nconst makeEDAWebSocketWireProtocolFromEventSchema = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n): EDAWebSocketWireProtocol<EventSchema> => {\n const domain = makeEDAWebSocketDomainSchemas(event);\n const encodeDomainServerFrame = Schema.encodeSync(domain.serverFrame);\n const encodeUnknownDomainServerFrame = Schema.encodeUnknownSync(domain.serverFrame);\n const encodeServerFrame = (frame: typeof domain.serverFrame.Type): string =>\n JSON.stringify(encodeDomainServerFrame(frame));\n const host: EDAWebSocketServerFrameEncoder = {\n encodeServerFrame: (frame) => JSON.stringify(encodeUnknownDomainServerFrame(frame)),\n };\n\n return {\n domain,\n wire: {\n event: Schema.toEncoded(domain.event),\n positionedEvent: Schema.toEncoded(domain.positionedEvent),\n eventsFrame: Schema.toEncoded(domain.eventsFrame),\n serverFrame: Schema.toEncoded(domain.serverFrame),\n clientFrame: EDAWebSocketWireClientFrame,\n },\n encodeServerFrame,\n host,\n };\n};\n\n/** Strict framework-only protocol used when an app registers no custom events. */\nexport const edaFrameworkWebSocketWireProtocol: EDAWebSocketWireProtocol<\n typeof EDAFrameworkWebSocketEvent\n> = makeEDAWebSocketWireProtocolFromEventSchema(EDAFrameworkWebSocketEvent);\n\n/**\n * Bind the generic EDA WebSocket transport to one app's custom event schema.\n *\n * Framework durable and ephemeral events are included automatically. Future EDA\n * apps register only their custom events. Servers use the returned domain schemas\n * and typed encoder; external consumers decode with the wire schemas. Pass the\n * returned `host` adapter to the selected host package.\n */\nexport const makeEDAWebSocketWireProtocol = <\n AppEventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(options: {\n readonly appEvents: AppEventSchema;\n}): EDAWebSocketWireProtocol<\n Schema.Union<readonly [typeof EDAFrameworkWebSocketEvent, AppEventSchema]>\n> =>\n makeEDAWebSocketWireProtocolFromEventSchema(\n Schema.Union([EDAFrameworkWebSocketEvent, options.appEvents]),\n );\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport {\n EDA_WEB_SOCKET_PING_MESSAGE,\n EDA_WEB_SOCKET_PONG_MESSAGE,\n EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION,\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireClientFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireFlowControl,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWirePingFrame,\n EDAWebSocketWirePongFrame,\n edaFrameworkWebSocketWireProtocol,\n type EDAWebSocketServerFrameEncoder,\n} from \"./protocol\";\n\nexport { EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE };\n\nimport { SequenceNumber } from \"../types/core\";\nimport { PositionedEvent, UnixEpochMillis } from \"../types/events\";\n\n/** Current EDA live-event WebSocket protocol version. */\nexport const EDA_WEB_SOCKET_PROTOCOL_VERSION = EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION;\n\n/** WebSocket close code used when a subscriber cannot keep up with live delivery. */\nexport const EDA_WS_CLOSE_LAGGED = 4008;\n\n/** WebSocket close code used for normal host-driven shutdown. */\nexport const EDA_WS_CLOSE_GOING_AWAY = 1001;\n\n/** WebSocket close code used for malformed client protocol messages. */\nexport const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;\n\n/** WebSocket close code used when the host cannot send a frame. */\nexport const EDA_WS_CLOSE_SEND_FAILED = 1011;\n\n/** WebSocket close code used for unsupported binary messages. */\nexport const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;\n\n/** Live subscriber identity persisted in WebSocket attachments. */\nexport const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand(\"SubscriberId\"));\nexport type SubscriberId = typeof SubscriberId.Type;\n\n/** Per-connection monotonically increasing server frame id. */\nexport const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(\n Schema.brand(\"FrameId\"),\n);\nexport type FrameId = typeof FrameId.Type;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;\nexport type EDAWebSocketFlowControl = typeof EDAWebSocketFlowControl.Type;\n\n/** Default bounded policy sized for fast model deltas and large durable tool/message events. */\nexport const defaultEDAWebSocketFlowControl: EDAWebSocketFlowControl = {\n ackTimeoutMs: 30_000,\n // Deprecated wire-compat field: servers no longer schedule or send heartbeats.\n heartbeatIntervalMs: 10_000,\n maxFrameBytes: 256 * 1024,\n maxFrameEvents: 1,\n maxInFlightFrames: 16,\n pingIntervalMs: 30_000,\n subscriberBufferCapacityEvents: 2_048,\n};\n\n/** First server frame; announces protocol and flow-control policy. */\nexport const EDAWebSocketHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n subscriberId: SubscriberId,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketHelloFrame = typeof EDAWebSocketHelloFrame.Type;\n\n/** Ordered positioned events delivered to the client. */\nexport const EDAWebSocketEventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: FrameId,\n events: Schema.NonEmptyArray(PositionedEvent),\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketEventsFrame = typeof EDAWebSocketEventsFrame.Type;\n\n/**\n * Deprecated idle server keepalive frame.\n *\n * Servers no longer send heartbeats; the schema remains so deployed clients\n * keep decoding the server frame union. Liveness is client-originated via\n * {@link EDAWebSocketPingFrame} and the host-level auto-response pong.\n */\nexport const EDAWebSocketHeartbeatFrame = Schema.Struct({\n ...EDAWebSocketWireHeartbeatFrame.fields,\n serverTimeMs: UnixEpochMillis,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketHeartbeatFrame = typeof EDAWebSocketHeartbeatFrame.Type;\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketPingFrame = EDAWebSocketWirePingFrame;\nexport type EDAWebSocketPingFrame = typeof EDAWebSocketPingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketPongFrame = EDAWebSocketWirePongFrame;\nexport type EDAWebSocketPongFrame = typeof EDAWebSocketPongFrame.Type;\n\n/** Optional final frame sent before a lag-close. */\nexport const EDAWebSocketLaggedFrame = Schema.Struct({\n ...EDAWebSocketWireLaggedFrame.fields,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketLaggedFrame = typeof EDAWebSocketLaggedFrame.Type;\n\n/** Optional final frame sent before a protocol/internal close. */\nexport const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;\nexport type EDAWebSocketErrorFrame = typeof EDAWebSocketErrorFrame.Type;\n\n/** Server-to-client application frame union. */\nexport const EDAWebSocketServerFrame = Schema.Union([\n EDAWebSocketHelloFrame,\n EDAWebSocketEventsFrame,\n EDAWebSocketHeartbeatFrame,\n EDAWebSocketPongFrame,\n EDAWebSocketLaggedFrame,\n EDAWebSocketErrorFrame,\n]);\nexport type EDAWebSocketServerFrame = typeof EDAWebSocketServerFrame.Type;\n\n/** Client acknowledgement after applying a server frame. */\nexport const EDAWebSocketAckFrame = Schema.Struct({\n ...EDAWebSocketWireAckFrame.fields,\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketAckFrame = typeof EDAWebSocketAckFrame.Type;\n\n/** Client-to-server application frame union. */\nexport const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame, EDAWebSocketPingFrame]);\nexport type EDAWebSocketClientFrame = typeof EDAWebSocketClientFrame.Type;\n\n/** Serialize a server frame for a text WebSocket message. */\nexport const encodeEDAWebSocketServerFrame = (\n frame: EDAWebSocketServerFrame,\n protocol?: EDAWebSocketServerFrameEncoder,\n): string => (protocol ?? edaFrameworkWebSocketWireProtocol.host).encodeServerFrame(frame);\n\n/** Decode an inbound text WebSocket message at the host boundary. */\nexport const decodeEDAWebSocketClientMessage = (\n input: string,\n): Effect.Effect<EDAWebSocketClientFrame, unknown> =>\n Effect.try({\n try: () => JSON.parse(input) as unknown,\n catch: (error) => error,\n }).pipe(\n Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)),\n Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)),\n );\n\n/** Short close reason that fits the WebSocket protocol reason limit. */\nexport const laggedCloseReason = (seq: SequenceNumber): string => `lag;seq=${seq}`;\n","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDA_WS_CLOSE_LAGGED,\n EDA_WS_CLOSE_PROTOCOL_ERROR,\n EDAWebSocketEventsFrame,\n EDAWebSocketErrorFrame,\n EDAWebSocketHelloFrame,\n EDAWebSocketLaggedFrame,\n FrameId,\n SubscriberId,\n laggedCloseReason,\n type EDAWebSocketAckFrame,\n type EDAWebSocketFlowControl,\n type EDAWebSocketServerFrame,\n} from \"./messages\";\n\n/** Slow subscriber reasons that intentionally close only the lagging socket. */\nexport const SubscriberLagReason = Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]);\nexport type SubscriberLagReason = typeof SubscriberLagReason.Type;\n\n/** One sent-but-unacknowledged events frame. */\nexport const EDAWebSocketInFlightFrame = Schema.Struct({\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n sentAtMs: Schema.Number,\n});\nexport type EDAWebSocketInFlightFrame = typeof EDAWebSocketInFlightFrame.Type;\n\n/** Complete delivery bookkeeping persisted in the WebSocket attachment. */\nexport const EDAWebSocketDeliveryCheckpoint = Schema.Struct({\n lastAckedSeq: SequenceNumber,\n lastAckedFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lastSentFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n nextFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n sentDurableThroughSeq: SequenceNumber,\n inFlight: Schema.Array(EDAWebSocketInFlightFrame),\n});\nexport type EDAWebSocketDeliveryCheckpoint = typeof EDAWebSocketDeliveryCheckpoint.Type;\n\n/** In-memory delivery state for one accepted event WebSocket. */\nexport interface EDAWebSocketDeliveryState extends EDAWebSocketDeliveryCheckpoint {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n /** Ephemeral events are live-only and intentionally absent from the attachment. */\n readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;\n}\n\n/** Explicit instructions emitted by the pure delivery state machine. */\nexport type EDAWebSocketDeliveryAction =\n | { readonly _tag: \"Persist\" }\n | { readonly _tag: \"Send\"; readonly frames: ReadonlyArray<EDAWebSocketServerFrame> }\n | { readonly _tag: \"ReadEventPage\"; readonly afterSeq: SequenceNumber }\n | { readonly _tag: \"Close\"; readonly code: number; readonly reason: string };\n\n/** Result of one pure delivery transition. */\nexport interface EDAWebSocketDeliveryResult {\n readonly state: EDAWebSocketDeliveryState;\n readonly actions: ReadonlyArray<EDAWebSocketDeliveryAction>;\n}\n\nexport interface MakeDeliveryStateInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n}\n\n/** Build delivery state for a newly accepted connection. */\nexport const makeWebSocketDeliveryState = (\n input: MakeDeliveryStateInput,\n): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n lastAckedSeq: input.resumeSeq,\n lastAckedFrameId: 0,\n lastSentFrameId: 0,\n nextFrameId: 1,\n sentDurableThroughSeq: input.resumeSeq,\n inFlight: [],\n pendingEphemeral: [],\n});\n\n/** Rebuild exact ACK bookkeeping from a hibernating WebSocket attachment. */\nexport const restoreWebSocketDeliveryState = (input: {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n readonly checkpoint: EDAWebSocketDeliveryCheckpoint;\n}): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n ...input.checkpoint,\n pendingEphemeral: [],\n});\n\n/** Project in-memory delivery state into the attachment-safe checkpoint. */\nexport const checkpointWebSocketDeliveryState = (\n state: EDAWebSocketDeliveryState,\n): EDAWebSocketDeliveryCheckpoint => ({\n lastAckedSeq: state.lastAckedSeq,\n lastAckedFrameId: state.lastAckedFrameId,\n lastSentFrameId: state.lastSentFrameId,\n nextFrameId: state.nextFrameId,\n sentDurableThroughSeq: state.sentDurableThroughSeq,\n inFlight: state.inFlight,\n});\n\n/** First frame for a freshly accepted connection. Restores never re-send hello. */\nexport const deliveryHelloFrame = (state: EDAWebSocketDeliveryState): EDAWebSocketHelloFrame =>\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: state.subscriberId,\n resumeSeq: state.lastAckedSeq,\n flowControl: state.policy,\n });\n\n/** Deliver committed durable events read from the store. */\nexport const onDurableEvents = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n head: SequenceNumber,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n let batch: PositionedEvent[] = [];\n\n const flushBatch = (): void => {\n if (batch.length === 0) return;\n const sent = sendEventsFrame(next, batch, nowMs);\n next = sent.state;\n frames.push(sent.frame);\n batch = [];\n };\n\n for (const event of events) {\n if (event.event.durability === \"durable\" && event.position.seq <= next.sentDurableThroughSeq) {\n continue;\n }\n if (batch.length === 0 && windowCapacity(next) <= 0) break;\n batch.push(event);\n if (batch.length >= next.policy.maxFrameEvents) flushBatch();\n }\n flushBatch();\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.sentDurableThroughSeq < head\n ? next.sentDurableThroughSeq\n : undefined,\n );\n};\n\n/** Deliver one live ephemeral event, buffering only while this isolate is active. */\nexport const onEphemeralEvent = (\n state: EDAWebSocketDeliveryState,\n event: PositionedEvent,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {\n const sent = sendEventsFrame(state, [event], nowMs);\n return sentResult(sent.state, [sent.frame]);\n }\n\n const pendingEphemeral = [...state.pendingEphemeral, event];\n if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) {\n return laggedResult(state, \"buffer-overflow\");\n }\n return { state: { ...state, pendingEphemeral }, actions: [] };\n};\n\n/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */\nexport const onClientAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const validated = applyAck(state, ack);\n if (validated._tag === \"close\") return validated.result;\n if (validated._tag === \"ignore\") return { state, actions: [] };\n\n let next = validated.state;\n const frames: EDAWebSocketServerFrame[] = [];\n while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {\n const [head, ...rest] = next.pendingEphemeral;\n if (head === undefined) break;\n const sent = sendEventsFrame({ ...next, pendingEphemeral: rest }, [head], nowMs);\n next = sent.state;\n frames.push(sent.frame);\n }\n\n const stale = staleAckResult(next, nowMs);\n if (stale !== undefined) return stale;\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.pendingEphemeral.length === 0\n ? next.sentDurableThroughSeq\n : undefined,\n true,\n );\n};\n\ntype AckValidation =\n | { readonly _tag: \"ignore\" }\n | { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult }\n | { readonly _tag: \"apply\"; readonly state: EDAWebSocketDeliveryState };\n\nconst applyAck = (state: EDAWebSocketDeliveryState, ack: EDAWebSocketAckFrame): AckValidation => {\n if (ack.frameId <= state.lastAckedFrameId) {\n return ack.durableThroughSeq > state.lastAckedSeq\n ? protocolClose(state, \"Duplicate ACK attempted to advance durable seq\")\n : { _tag: \"ignore\" };\n }\n if (ack.frameId > state.lastSentFrameId) {\n return protocolClose(state, \"ACK referenced an unsent frame\");\n }\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return protocolClose(state, \"ACK durable seq moved backwards\");\n }\n const acknowledged = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledged.length === 0) {\n return protocolClose(state, \"ACK referenced no in-flight frames\");\n }\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, frame) => Math.max(max, frame.durableThroughSeq),\n state.lastAckedSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n return protocolClose(state, \"ACK durable seq exceeded sent frame boundary\");\n }\n return {\n _tag: \"apply\",\n state: {\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: ack.frameId,\n lastAckedSeq: ack.durableThroughSeq,\n },\n };\n};\n\nconst windowCapacity = (state: EDAWebSocketDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\nconst sendEventsFrame = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n nowMs: number,\n): { readonly state: EDAWebSocketDeliveryState; readonly frame: EDAWebSocketEventsFrame } => {\n const [first, ...rest] = events;\n if (first === undefined) throw new Error(\"Cannot send an empty events frame\");\n const frameId = FrameId.make(state.nextFrameId);\n const durableThroughSeq = SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n state.sentDurableThroughSeq,\n ),\n );\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: [first, ...rest],\n durableThroughSeq,\n });\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, { frameId, durableThroughSeq, sentAtMs: nowMs }],\n lastSentFrameId: frameId,\n nextFrameId: frameId + 1,\n sentDurableThroughSeq: durableThroughSeq,\n },\n frame,\n };\n};\n\nconst sentResult = (\n state: EDAWebSocketDeliveryState,\n frames: ReadonlyArray<EDAWebSocketServerFrame>,\n catchUpAfterSeq?: SequenceNumber,\n stateChanged = frames.length > 0,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n ...(stateChanged ? ([{ _tag: \"Persist\" }] as const) : []),\n ...(frames.length > 0 ? ([{ _tag: \"Send\", frames }] as const) : []),\n ...(catchUpAfterSeq === undefined\n ? []\n : ([{ _tag: \"ReadEventPage\", afterSeq: catchUpAfterSeq }] as const)),\n ],\n});\n\n/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */\nconst staleAckResult = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult | undefined =>\n state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs)\n ? laggedResult(state, \"ack-timeout\")\n : undefined;\n\nconst laggedResult = (\n state: EDAWebSocketDeliveryState,\n reason: SubscriberLagReason,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [\n EDAWebSocketLaggedFrame.make({\n _tag: \"lagged\",\n resumeSeq: state.lastAckedSeq,\n reason,\n }),\n ],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_LAGGED, reason: laggedCloseReason(state.lastAckedSeq) },\n ],\n});\n\nconst protocolClose = (\n state: EDAWebSocketDeliveryState,\n message: string,\n): { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult } => ({\n _tag: \"close\",\n result: {\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [EDAWebSocketErrorFrame.make({ _tag: \"error\", message: message.slice(0, 120) })],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_PROTOCOL_ERROR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AC,CACH;CACF,GACA;EAAE,MAAM;EAAS,MAAM;EAAqB,QAAQ,kBAAkB,MAAM,YAAY;CAAE,CAC5F;AACF;AAEA,MAAM,iBACJ,OACA,aAC6E;CAC7E,MAAM;CACN,QAAQ;EACN;EACA,SAAS,CACP;GACE,MAAM;GACN,QAAQ,CAAC,uBAAuB,KAAK;IAAE,MAAM;IAAS,SAAS,QAAQ,MAAM,GAAG,GAAG;GAAE,CAAC,CAAC;EACzF,GACA;GAAE,MAAM;GAAS,MAAM;GAA6B,QAAQ;EAAW,CACzE;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-durable-agent",
3
- "version": "0.1.0-alpha.4",
3
+ "version": "0.1.0-alpha.6",
4
4
  "description": "A host-independent, event-sourced durable state-management and execution layer for agentic applications.",
5
5
  "keywords": [
6
6
  "agents",
@@ -14,7 +14,8 @@
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
17
- "url": "git+https://github.com/advait/effect-durable-agent.git"
17
+ "url": "git+https://github.com/advait/effect-durable-agent.git",
18
+ "directory": "packages/effect-durable-agent"
18
19
  },
19
20
  "license": "MIT",
20
21
  "author": "Advait Shinde",
@@ -23,11 +24,7 @@
23
24
  "main": "./dist/index.js",
24
25
  "types": "./dist/index.d.ts",
25
26
  "files": [
26
- "CHANGELOG.md",
27
- "CONTRIBUTING.md",
28
- "SECURITY.md",
29
27
  "dist",
30
- "docs",
31
28
  "testing/offline-trace/README.md",
32
29
  "tooling/oxlint/index.mjs",
33
30
  "tooling/oxlint/rules/*.mjs"
@@ -53,13 +50,9 @@
53
50
  "types": "./dist/domain/reduced-state-schema.d.ts",
54
51
  "import": "./dist/domain/reduced-state-schema.js"
55
52
  },
56
- "./host/websocket-wire": {
57
- "types": "./dist/host/websocket-wire.d.ts",
58
- "import": "./dist/host/websocket-wire.js"
59
- },
60
- "./host/websocket-protocol": {
61
- "types": "./dist/host/websocket-protocol.d.ts",
62
- "import": "./dist/host/websocket-protocol.js"
53
+ "./websocket": {
54
+ "types": "./dist/websocket.d.ts",
55
+ "import": "./dist/websocket.js"
63
56
  },
64
57
  "./services/keep-alive": {
65
58
  "types": "./dist/services/keep-alive.d.ts",
@@ -93,6 +86,10 @@
93
86
  "types": "./dist/services/session-query.d.ts",
94
87
  "import": "./dist/services/session-query.js"
95
88
  },
89
+ "./services/session-event-observer": {
90
+ "types": "./dist/services/session-event-observer.d.ts",
91
+ "import": "./dist/services/session-event-observer.js"
92
+ },
96
93
  "./services/session-store": {
97
94
  "types": "./dist/services/session-store.d.ts",
98
95
  "import": "./dist/services/session-store.js"
@@ -121,10 +118,6 @@
121
118
  "types": "./dist/services/tracing.d.ts",
122
119
  "import": "./dist/services/tracing.js"
123
120
  },
124
- "./services/websocket-subscriber": {
125
- "types": "./dist/services/websocket-subscriber.d.ts",
126
- "import": "./dist/services/websocket-subscriber.js"
127
- },
128
121
  "./domain/context-projection": {
129
122
  "types": "./dist/domain/context-projection.d.ts",
130
123
  "import": "./dist/domain/context-projection.js"
@@ -182,20 +175,11 @@
182
175
  "wrangler": "^4.114.0"
183
176
  },
184
177
  "scripts": {
185
- "build": "pnpm run build:core && pnpm --filter effect-durable-agent-cloudflare run build && pnpm --filter effect-durable-agent-celld run build",
186
- "build:core": "vp pack",
187
- "check": "pnpm run lint && pnpm run typecheck && pnpm --filter effect-durable-agent-cloudflare run check && pnpm --filter effect-durable-agent-celld run check",
188
- "ci": "pnpm run build && pnpm run check && pnpm run test && pnpm run release:versions && pnpm run package:check",
189
- "lint": "vp fmt --check && vp lint --deny-warnings",
190
- "lint:fix": "vp fmt && vp lint --fix",
191
- "package:check": "node scripts/check-package.mjs",
192
- "publish:workspace": "node scripts/publish-workspace.mjs",
193
- "publish:workspace:dry-run": "node scripts/publish-workspace.mjs --dry-run",
194
- "release:versions": "node scripts/check-workspace-versions.mjs",
195
- "release:check": "pnpm run ci",
196
- "test": "pnpm run test:core && pnpm --filter effect-durable-agent-cloudflare run test && pnpm --filter effect-durable-agent-celld run test && pnpm run test:integration",
197
- "test:core": "vp test run --passWithNoTests src testing/offline-trace",
198
- "test:integration": "pnpm run build && vp test run testing/host-conformance/hosts.integration.test.ts",
178
+ "build": "vp pack",
179
+ "check": "pnpm run lint && pnpm run typecheck",
180
+ "lint": "vp fmt --check src testing tooling package.json tsconfig.json vite.config.ts && vp lint --deny-warnings src testing vite.config.ts",
181
+ "lint:fix": "vp fmt src testing tooling package.json tsconfig.json vite.config.ts && vp lint --fix src testing vite.config.ts",
182
+ "test": "vp test run --passWithNoTests src testing/offline-trace",
199
183
  "typecheck": "tsc -p tsconfig.json --noEmit"
200
184
  }
201
185
  }
@@ -7,7 +7,8 @@ remains self-contained.
7
7
  ## Run a real OpenAI trace
8
8
 
9
9
  ```bash
10
- OPENAI_API_KEY=... pnpm exec tsx testing/offline-trace/node/run.ts \
10
+ OPENAI_API_KEY=... pnpm --filter effect-durable-agent exec tsx \
11
+ testing/offline-trace/node/run.ts \
11
12
  --scenario no-tools \
12
13
  --out .eda-traces/no-tools-001
13
14
  ```
package/CHANGELOG.md DELETED
@@ -1,34 +0,0 @@
1
- # Changelog
2
-
3
- All notable changes to Effect Durable Agent will be documented in this file.
4
-
5
- ## Unreleased
6
-
7
- ## 0.1.0-alpha.4
8
-
9
- - Let applications project instruction and data messages from current reducer state into each model prompt
10
- - Build prompts only after turn input selection is committed into durable reducer state
11
- - Split the host-neutral runtime, Cloudflare Durable Objects host, and celld host into lockstep packages
12
- - Add shared real-runtime conformance tests for workerd and celld, including RPC, persistence,
13
- hard-restart recovery, durable idempotency, WebSocket resume/ACK, and warm/cold session recreation
14
- - Encode Effect Schema values explicitly at Durable Object RPC boundaries
15
-
16
- ## 0.1.0-alpha.3
17
-
18
- - Publish the state-projected prompt context and WebSocket schema changes from the unpublished `0.1.0-alpha.2` package
19
- - Pin prerelease publication to the npm `alpha` dist-tag
20
-
21
- ## 0.1.0-alpha.2
22
-
23
- - Let applications project instruction and data messages from current reducer state into each model prompt
24
- - Build prompts only after turn input selection is committed into durable reducer state
25
- - Separate WebSocket protocol schemas into explicit domain and wire surfaces
26
- - Add a typed domain-frame encoder, a host adapter for app-event narrowing, and transformation
27
- round-trip coverage
28
-
29
- ## 0.1.0-alpha.1
30
-
31
- - Publish the first public prerelease as `effect-durable-agent`
32
- - Ship compiled ESM and TypeScript declarations for every supported subpath
33
- - Add isolated package-consumer validation for Cloudflare Workers
34
- - Add MIT licensing and trusted-publishing release automation