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

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 (129) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +28 -27
  3. package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-CV7O-51r.d.ts} +7 -6
  4. package/dist/{compaction-1LSZR944.d.ts → compaction-zbvLREI8.d.ts} +8 -6
  5. package/dist/context-projection-n6Rdup0N.d.ts +140 -0
  6. package/dist/{core-Hv3cFydL.d.ts → core-CYT6DBaS.d.ts} +2 -2
  7. package/dist/domain/command-queues.d.ts +1 -1
  8. package/dist/domain/context-projection.d.ts +2 -0
  9. package/dist/domain/context-projection.js +32 -0
  10. package/dist/domain/context-projection.js.map +1 -0
  11. package/dist/domain/message-transcript.d.ts +1 -1
  12. package/dist/domain/reduced-state-schema.d.ts +2 -0
  13. package/dist/domain/reduced-state-schema.js +2 -1
  14. package/dist/domain/reduced-state-schema.js.map +1 -1
  15. package/dist/domain/reduced-state.d.ts +1 -1
  16. package/dist/domain/reduced-state.js +1 -1
  17. package/dist/{durable-DlScwmCy.d.ts → durable-B7M6TD_0.d.ts} +341 -2
  18. package/dist/{durable-C3Rz7kg3.js → durable-DsV9PxZC.js} +13 -2
  19. package/dist/durable-DsV9PxZC.js.map +1 -0
  20. package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-CLJcyymV.d.ts} +5 -29
  21. package/dist/{keep-alive-p8dIcSVy.js → event-factory-tcpLgdMN.js} +3 -10
  22. package/dist/event-factory-tcpLgdMN.js.map +1 -0
  23. package/dist/host/websocket-protocol.d.ts +229 -0
  24. package/dist/host/websocket-protocol.js +99 -0
  25. package/dist/host/websocket-protocol.js.map +1 -0
  26. package/dist/host/websocket-wire.d.ts +1 -1
  27. package/dist/host/websocket-wire.js +2 -2
  28. package/dist/host/websocket-wire.js.map +1 -1
  29. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-Ckl8_XWW.d.ts} +2 -2
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +2 -2
  32. package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
  33. package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-DiOPBY3l.d.ts} +3 -3
  34. package/dist/{prompt-projector-DimXJPOJ.d.ts → prompt-projector-C1IbkHr0.d.ts} +5 -5
  35. package/dist/{reduced-state-C4nVVzz9.js → reduced-state-TMi7ISla.js} +20 -4
  36. package/dist/reduced-state-TMi7ISla.js.map +1 -0
  37. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-CjSJBPKo.d.ts} +2 -2
  38. package/dist/{runtime-DcdPOEuE.d.ts → runtime-DOgmAKsO.d.ts} +7 -6
  39. package/dist/services/compaction.d.ts +1 -1
  40. package/dist/services/compaction.js +4 -3
  41. package/dist/services/compaction.js.map +1 -1
  42. package/dist/services/id-generator.d.ts +1 -1
  43. package/dist/services/keep-alive.d.ts +2 -0
  44. package/dist/services/keep-alive.js +13 -0
  45. package/dist/services/keep-alive.js.map +1 -0
  46. package/dist/services/prompt-projector.d.ts +1 -1
  47. package/dist/services/reducer-registry.d.ts +1 -1
  48. package/dist/services/runtime-layer.d.ts +58 -0
  49. package/dist/services/runtime-layer.js +42 -0
  50. package/dist/services/runtime-layer.js.map +1 -0
  51. package/dist/services/runtime.d.ts +1 -1
  52. package/dist/services/runtime.js +4 -3
  53. package/dist/services/runtime.js.map +1 -1
  54. package/dist/services/session-query.d.ts +1 -1
  55. package/dist/services/session-query.js +76 -1
  56. package/dist/services/session-query.js.map +1 -0
  57. package/dist/services/session-state.d.ts +2 -0
  58. package/dist/services/session-state.js +2 -0
  59. package/dist/services/session-store.d.ts +2 -2
  60. package/dist/services/session-store.js +181 -2
  61. package/dist/services/session-store.js.map +1 -0
  62. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  63. package/dist/services/sink-checkpoint-store.js +49 -0
  64. package/dist/services/sink-checkpoint-store.js.map +1 -0
  65. package/dist/services/sink-registry.d.ts +1 -1
  66. package/dist/services/sink-registry.js +1 -1
  67. package/dist/services/tool-registry.d.ts +1 -1
  68. package/dist/services/websocket-subscriber.d.ts +54 -0
  69. package/dist/services/websocket-subscriber.js +190 -0
  70. package/dist/services/websocket-subscriber.js.map +1 -0
  71. package/dist/session-query-C-C4m1eq.d.ts +38 -0
  72. package/dist/{session-query-hxfujxUH.d.ts → session-state-CjOSvWbe.d.ts} +134 -42
  73. package/dist/{session-query-Cbf-e0rG.js → session-state-SStf0KUo.js} +18 -77
  74. package/dist/session-state-SStf0KUo.js.map +1 -0
  75. package/dist/{session-store-D2Ore1QC.d.ts → session-store-DZZUffUy.d.ts} +5 -94
  76. package/dist/sink-checkpoint-store-BZmQFTRE.d.ts +40 -0
  77. package/dist/{sink-registry-BziFpxoE.d.ts → sink-registry-Cf79ICdW.d.ts} +11 -40
  78. package/dist/{sink-registry-CFC6xjsN.js → sink-registry-D13eUO_c.js} +9 -47
  79. package/dist/sink-registry-D13eUO_c.js.map +1 -0
  80. package/dist/testkit/layers.d.ts +14 -11
  81. package/dist/testkit/layers.js +8 -5
  82. package/dist/testkit/layers.js.map +1 -1
  83. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-B7Wona6N.d.ts} +3 -3
  84. package/dist/types/core.d.ts +1 -1
  85. package/dist/types/core.js +1 -1
  86. package/dist/types/core.js.map +1 -1
  87. package/dist/types/events/durable.d.ts +2 -2
  88. package/dist/types/events/durable.js +2 -2
  89. package/dist/types/events.d.ts +2 -2
  90. package/dist/types/events.js +2 -2
  91. package/dist/{websocket-wire-D3tLrhe2.d.ts → websocket-wire-QD2SquQE.d.ts} +74 -2
  92. package/docs/message-steering.md +1 -1
  93. package/docs/releasing.md +42 -24
  94. package/docs/spec.md +11 -11
  95. package/docs/websocket-protocol.md +4 -4
  96. package/package.json +55 -35
  97. package/dist/durable-C3Rz7kg3.js.map +0 -1
  98. package/dist/durable-object-runtime-CiMKxGs6.d.ts +0 -257
  99. package/dist/durable-object-runtime-wKiqaAt2.js +0 -1494
  100. package/dist/durable-object-runtime-wKiqaAt2.js.map +0 -1
  101. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  102. package/dist/host/durable-object-runtime.d.ts +0 -2
  103. package/dist/host/durable-object-runtime.js +0 -2
  104. package/dist/host/durable-object-storage.d.ts +0 -2
  105. package/dist/host/durable-object-storage.js +0 -0
  106. package/dist/host/durable-object.d.ts +0 -83
  107. package/dist/host/durable-object.js +0 -191
  108. package/dist/host/durable-object.js.map +0 -1
  109. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  110. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  111. package/dist/session-query-Cbf-e0rG.js.map +0 -1
  112. package/dist/session-store-pYxQW9qh.js +0 -214
  113. package/dist/session-store-pYxQW9qh.js.map +0 -1
  114. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  115. package/examples/001-no-tools/README.md +0 -65
  116. package/examples/001-no-tools/worker.ts +0 -79
  117. package/examples/002-slack-bridge/README.md +0 -134
  118. package/examples/002-slack-bridge/events.ts +0 -115
  119. package/examples/002-slack-bridge/reducer.ts +0 -216
  120. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  121. package/examples/002-slack-bridge/sinks.ts +0 -109
  122. package/examples/002-slack-bridge/worker.ts +0 -140
  123. package/examples/003-sandbox-lifecycle/README.md +0 -78
  124. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  125. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  126. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  127. package/examples/_shared/event-id.ts +0 -12
  128. package/examples/_shared/http.ts +0 -27
  129. package/examples/_shared/openai.ts +0 -33
@@ -1,2 +1,181 @@
1
- import { a as EDASessionStoreError, c as hasEDASessionStoreError, i as EDASessionStore, n as DurableAppendBatch, o as FindCommandAdmissionInput, r as DurableAppendEntry, s as durableObjectSerializedJsonHardCapBytes, t as CommittedDurableEvent } from "../session-store-pYxQW9qh.js";
2
- export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDASessionStore, EDASessionStoreError, FindCommandAdmissionInput, durableObjectSerializedJsonHardCapBytes, hasEDASessionStoreError };
1
+ import { CommandId, DurablePosition, SequenceNumber, durablePosition } from "../types/core.js";
2
+ import { En as contextRebasedEventType, Un as summaryCreatedEventType, ar as DurableEventEnvelope, gn as commandAdmittedEventType } from "../durable-DsV9PxZC.js";
3
+ import { CompactionSummaryArtifact } from "../domain/context-projection.js";
4
+ import * as Context from "effect/Context";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Layer from "effect/Layer";
7
+ import * as Schema from "effect/Schema";
8
+ import * as Stream from "effect/Stream";
9
+ import * as Cause from "effect/Cause";
10
+ import * as Ref from "effect/Ref";
11
+ //#region src/services/session-store.ts
12
+ /** A durable event after the store has assigned its replay position. */
13
+ const CommittedDurableEvent = Schema.Struct({
14
+ position: DurablePosition,
15
+ event: DurableEventEnvelope
16
+ });
17
+ /**
18
+ * Store-level failure surfaced by durable append, replay, and hydration APIs.
19
+ *
20
+ * The error intentionally stays storage-semantic rather than SQL-specific so
21
+ * framework services can treat SQL-backed hosts, in-memory tests, and future adapters
22
+ * as the same durability boundary.
23
+ */
24
+ var EDASessionStoreError = class extends Schema.TaggedErrorClass()("EDASessionStoreError", { message: Schema.String }) {};
25
+ /** True when a Cause contains an escaped durable-store failure. */
26
+ const hasEDASessionStoreError = (cause) => cause.reasons.some((reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError);
27
+ /**
28
+ * One logical event to persist in the durable session log.
29
+ *
30
+ * Store adapters may split large logical payload fields into sidecar rows after
31
+ * the event insert assigns `seq`, but callers still provide one fat event.
32
+ */
33
+ const DurableAppendEntry = Schema.Struct({ event: DurableEventEnvelope });
34
+ /**
35
+ * Ordered durable append intent. Adapters assign positions in entry order.
36
+ *
37
+ * This is the single write shape exposed to framework services. It avoids raw
38
+ * SQL and public transaction callbacks while still expressing the full atomic
39
+ * transition EDA needs for events, normalized bodies, and metadata.
40
+ */
41
+ const DurableAppendBatch = Schema.Struct({ entries: Schema.Array(DurableAppendEntry) });
42
+ /** Indexed command-admission lookup used for idempotent ingress. */
43
+ const FindCommandAdmissionInput = Schema.Struct({
44
+ commandId: Schema.optionalKey(CommandId),
45
+ idempotencyKey: Schema.optionalKey(Schema.String)
46
+ });
47
+ /**
48
+ * SQL-agnostic durable storage port for one EDA session.
49
+ *
50
+ * Framework services depend on this semantic port rather than raw SQL. Host
51
+ * adapters own physical tables and synchronous transaction mechanics; callers
52
+ * only express durable append/replay/lookup intent.
53
+ */
54
+ var EDASessionStore = class EDASessionStore extends Context.Service()("@effect-durable-agent/EDASessionStore") {
55
+ /** Deterministic in-memory implementation used by runtime and recovery tests. */
56
+ static InMemory = (sessionId) => Layer.effect(EDASessionStore, Effect.gen(function* () {
57
+ return makeInMemoryStore(sessionId, yield* Ref.make(emptyInMemoryStoreData()));
58
+ }));
59
+ /** In-memory store seeded with a durable prefix; intended for recovery tests. */
60
+ static InMemorySeeded = (sessionId, events) => Layer.effect(EDASessionStore, Effect.gen(function* () {
61
+ const committed = seedCommittedEvents(sessionId, events);
62
+ return makeInMemoryStore(sessionId, yield* Ref.make({
63
+ ...emptyInMemoryStoreData(),
64
+ committed,
65
+ summaries: summariesFromCommittedEvents(committed)
66
+ }));
67
+ }));
68
+ };
69
+ const emptyInMemoryStoreData = () => ({
70
+ committed: [],
71
+ summaries: /* @__PURE__ */ new Map(),
72
+ reducerCheckpoints: /* @__PURE__ */ new Map()
73
+ });
74
+ const seedCommittedEvents = (sessionId, events) => {
75
+ const seen = /* @__PURE__ */ new Set();
76
+ return events.map((event, index) => {
77
+ if (event.sessionId !== sessionId) throw new Error(`EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`);
78
+ if (seen.has(event.eventId)) throw new Error(`Duplicate seed eventId ${event.eventId}`);
79
+ seen.add(event.eventId);
80
+ return CommittedDurableEvent.make({
81
+ position: durablePosition(SequenceNumber.make(index + 1)),
82
+ event
83
+ });
84
+ });
85
+ };
86
+ const summariesFromCommittedEvents = (events) => {
87
+ const summaries = /* @__PURE__ */ new Map();
88
+ for (const { event } of events) {
89
+ if (event.type !== summaryCreatedEventType) continue;
90
+ const payload = event.payload;
91
+ if (payload.summary !== void 0) {
92
+ const summary = CompactionSummaryArtifact.make(payload.summary);
93
+ summaries.set(summary.summaryId, summary);
94
+ }
95
+ }
96
+ return summaries;
97
+ };
98
+ /**
99
+ * Build an in-memory store with one `Ref.modify` append critical section.
100
+ *
101
+ * The fake models the semantic atomicity of the production adapter without
102
+ * exposing SQL, so runtime tests exercise the same store contract.
103
+ */
104
+ const makeInMemoryStore = (sessionId, data) => {
105
+ const ensureSession = (event) => Effect.gen(function* () {
106
+ if (event.sessionId === sessionId) return;
107
+ return yield* new EDASessionStoreError({ message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}` });
108
+ });
109
+ const append = (batch) => Effect.gen(function* () {
110
+ for (const entry of batch.entries) yield* ensureSession(entry.event);
111
+ return yield* Ref.modify(data, (current) => {
112
+ const nextEntries = [...current.committed];
113
+ const nextSummaries = new Map(current.summaries);
114
+ const committedEvents = [];
115
+ for (const entry of batch.entries) {
116
+ const { event } = entry;
117
+ const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);
118
+ if (existing !== void 0) {
119
+ committedEvents.push(existing);
120
+ continue;
121
+ }
122
+ const committed = CommittedDurableEvent.make({
123
+ position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),
124
+ event
125
+ });
126
+ nextEntries.push(committed);
127
+ committedEvents.push(committed);
128
+ if (event.type === summaryCreatedEventType) {
129
+ const payload = event.payload;
130
+ if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
131
+ const summary = CompactionSummaryArtifact.make(payload.summary);
132
+ if (payload.summaryId !== void 0 && summary.summaryId !== payload.summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
133
+ nextSummaries.set(summary.summaryId, summary);
134
+ }
135
+ if (event.type === contextRebasedEventType) {
136
+ const payload = event.payload;
137
+ if (payload.summaryId === void 0 || !nextSummaries.has(payload.summaryId)) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
138
+ }
139
+ }
140
+ return [committedEvents, {
141
+ committed: nextEntries,
142
+ summaries: nextSummaries,
143
+ reducerCheckpoints: current.reducerCheckpoints
144
+ }];
145
+ });
146
+ });
147
+ return {
148
+ append,
149
+ eventsAfter: (afterSeq) => Stream.fromIterableEffect(Ref.get(data).pipe(Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)))),
150
+ loadCommittedEventsBySeq: (seqs) => Ref.get(data).pipe(Effect.map(({ committed }) => {
151
+ const requested = new Set(seqs.map((seq) => Number(seq)));
152
+ return committed.filter((entry) => requested.has(Number(entry.position.seq)));
153
+ })),
154
+ findCommandAdmission: (input) => Ref.get(data).pipe(Effect.map(({ committed }) => committed.find((entry) => commandAdmissionMatches(entry, input)))),
155
+ loadSummaryArtifact: (summaryId) => Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),
156
+ loadReducerCheckpoint: (name) => Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),
157
+ saveReducerCheckpoint: (checkpoint) => Ref.update(data, (current) => ({
158
+ ...current,
159
+ reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint)
160
+ })),
161
+ saveReducerCheckpoints: (checkpoints) => Ref.update(data, (current) => {
162
+ const reducerCheckpoints = new Map(current.reducerCheckpoints);
163
+ for (const checkpoint of checkpoints) reducerCheckpoints.set(checkpoint.name, checkpoint);
164
+ return {
165
+ ...current,
166
+ reducerCheckpoints
167
+ };
168
+ })
169
+ };
170
+ };
171
+ const commandAdmissionMatches = (entry, input) => {
172
+ if (entry.event.type !== commandAdmittedEventType) return false;
173
+ const admitted = entry.event.payload.command;
174
+ if (admitted === void 0) return false;
175
+ if (input.idempotencyKey !== void 0 && admitted.idempotencyKey === input.idempotencyKey) return true;
176
+ return input.commandId !== void 0 && admitted.commandId === input.commandId;
177
+ };
178
+ //#endregion
179
+ export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDASessionStore, EDASessionStoreError, FindCommandAdmissionInput, hasEDASessionStoreError };
180
+
181
+ //# sourceMappingURL=session-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { type CommandIdempotencyKey, type EDACommand } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope,\n});\nexport type CommittedDurableEvent = typeof CommittedDurableEvent.Type;\n\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedErrorClass<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /** Deterministic in-memory implementation used by runtime and recovery tests. */\n static readonly InMemory = (sessionId: SessionId) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const data = yield* Ref.make<InMemoryStoreData>(emptyInMemoryStoreData());\n return makeInMemoryStore(sessionId, data);\n }),\n );\n\n /** In-memory store seeded with a durable prefix; intended for recovery tests. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n ) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const committed = seedCommittedEvents(sessionId, events);\n const data = yield* Ref.make<InMemoryStoreData>({\n ...emptyInMemoryStoreData(),\n committed,\n summaries: summariesFromCommittedEvents(committed),\n });\n return makeInMemoryStore(sessionId, data);\n }),\n );\n}\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n}\n\nconst emptyInMemoryStoreData = (): InMemoryStoreData => ({\n committed: [],\n summaries: new Map(),\n reducerCheckpoints: new Map(),\n});\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(index + 1)),\n event,\n });\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload as { readonly summary?: unknown };\n if (payload.summary !== undefined) {\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed = CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event,\n });\n nextEntries.push(committed);\n committedEvents.push(committed);\n\n if (event.type === summaryCreatedEventType) {\n const payload = event.payload as {\n readonly summary?: unknown;\n readonly summaryId?: CompactionSummaryArtifact[\"summaryId\"];\n };\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (event.type === contextRebasedEventType) {\n const payload = event.payload as { readonly summaryId?: SummaryId };\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = (entry.event.payload as { readonly command?: EDACommand }).command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAa,wBAAwB,OAAO,OAAO;CACjD,UAAU;CACV,OAAO;AACT,CAAC;;;;;;;;AAUD,IAAa,uBAAb,cAA0C,OA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,IAAI,IAAI,EAAE,KAAK,OAAO,KAAK,EAAE,gBAAgB,UAAU,IAAI,SAAS,CAAC,CAAC;EAC5E,wBAAwB,SACtB,IAAI,IAAI,IAAI,EAAE,KAAK,OAAO,KAAK,EAAE,yBAAyB,mBAAmB,IAAI,IAAI,CAAC,CAAC;EACzF,wBAAwB,eACtB,IAAI,OAAO,OAAO,aAAa;GAC7B,GAAG;GACH,oBAAoB,IAAI,IAAI,QAAQ,kBAAkB,EAAE,IAAI,WAAW,MAAM,UAAU;EACzF,EAAE;EACJ,yBAAyB,gBACvB,IAAI,OAAO,OAAO,YAAY;GAC5B,MAAM,qBAAqB,IAAI,IAAI,QAAQ,kBAAkB;GAC7D,KAAK,MAAM,cAAc,aACvB,mBAAmB,IAAI,WAAW,MAAM,UAAU;GAEpD,OAAO;IAAE,GAAG;IAAS;GAAmB;EAC1C,CAAC;CACL;AACF;AAEA,MAAM,2BACJ,OACA,UACY;CACZ,IAAI,MAAM,MAAM,SAAS,0BACvB,OAAO;CAET,MAAM,WAAY,MAAM,MAAM,QAA8C;CAC5E,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,mBAAmB,KAAA,KAAa,SAAS,mBAAmB,MAAM,gBAC1E,OAAO;CAET,OAAO,MAAM,cAAc,KAAA,KAAa,SAAS,cAAc,MAAM;AACvE"}
@@ -0,0 +1,2 @@
1
+ import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-BZmQFTRE.js";
2
+ export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
@@ -0,0 +1,49 @@
1
+ import { SequenceNumber } from "../types/core.js";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import * as Schema from "effect/Schema";
6
+ import * as Ref from "effect/Ref";
7
+ //#region src/services/sink-checkpoint-store.ts
8
+ /** Stable sink name used as the durable checkpoint key. */
9
+ const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand("EDASinkName"));
10
+ /**
11
+ * Semantic checkpoint store for registered EDA sinks.
12
+ *
13
+ * Checkpoints are intentionally exposed as load/save/commit operations rather
14
+ * than SQL. Sink side effects happen outside event append transactions, and the
15
+ * cursor advances only after the sink finishes its own external work.
16
+ */
17
+ var SinkCheckpointStore = class SinkCheckpointStore extends Context.Service()("@effect-durable-agent/SinkCheckpointStore") {
18
+ /** In-memory checkpoint implementation for store/runtime tests. */
19
+ static InMemory = Layer.effect(SinkCheckpointStore, Effect.gen(function* () {
20
+ return makeInMemorySinkCheckpointStore(yield* Ref.make(/* @__PURE__ */ new Map()));
21
+ }));
22
+ };
23
+ /** Build a ref-backed checkpoint map with the same public semantics as host adapters. */
24
+ const makeInMemorySinkCheckpointStore = (checkpoints) => ({
25
+ load: (sinkName) => Ref.get(checkpoints).pipe(Effect.map((map) => map.get(sinkName) ?? {
26
+ afterSeq: SequenceNumber.make(0),
27
+ payload: void 0
28
+ })),
29
+ saveState: (sinkName, payload) => Ref.update(checkpoints, (map) => {
30
+ const next = new Map(map);
31
+ next.set(sinkName, {
32
+ afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),
33
+ payload
34
+ });
35
+ return next;
36
+ }),
37
+ commit: (sinkName, afterSeq, payload) => Ref.update(checkpoints, (map) => {
38
+ const next = new Map(map);
39
+ next.set(sinkName, {
40
+ afterSeq,
41
+ payload
42
+ });
43
+ return next;
44
+ })
45
+ });
46
+ //#endregion
47
+ export { EDASinkName, SinkCheckpointStore };
48
+
49
+ //# sourceMappingURL=sink-checkpoint-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sink-checkpoint-store.js","names":[],"sources":["../../src/services/sink-checkpoint-store.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { EDASessionStoreError } from \"./session-store\";\n\n/** Stable sink name used as the durable checkpoint key. */\nexport const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand(\"EDASinkName\"));\nexport type EDASinkName = typeof EDASinkName.Type;\n\n/** Persisted cursor and sink-owned payload for one registered sink. */\nexport interface StoredSinkCheckpoint {\n readonly afterSeq: SequenceNumber;\n readonly payload: unknown | undefined;\n}\n\n/** Durable checkpoint persistence port for at-least-once sink runners. */\nexport interface SinkCheckpointStoreShape {\n /** Read the latest committed cursor and sink-owned payload. */\n readonly load: (\n sinkName: EDASinkName,\n ) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;\n /** Save sink-owned state without advancing the durable cursor. */\n readonly saveState: (\n sinkName: EDASinkName,\n payload: unknown,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Atomically commit the processed cursor together with current sink-owned state. */\n readonly commit: (\n sinkName: EDASinkName,\n afterSeq: SequenceNumber,\n payload: unknown | undefined,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * Semantic checkpoint store for registered EDA sinks.\n *\n * Checkpoints are intentionally exposed as load/save/commit operations rather\n * than SQL. Sink side effects happen outside event append transactions, and the\n * cursor advances only after the sink finishes its own external work.\n */\nexport class SinkCheckpointStore extends Context.Service<\n SinkCheckpointStore,\n SinkCheckpointStoreShape\n>()(\"@effect-durable-agent/SinkCheckpointStore\") {\n /** In-memory checkpoint implementation for store/runtime tests. */\n static readonly InMemory = Layer.effect(\n SinkCheckpointStore,\n Effect.gen(function* () {\n const checkpoints = yield* Ref.make<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>(\n new Map(),\n );\n return makeInMemorySinkCheckpointStore(checkpoints);\n }),\n );\n}\n\n/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */\nconst makeInMemorySinkCheckpointStore = (\n checkpoints: Ref.Ref<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>,\n): SinkCheckpointStoreShape => ({\n load: (sinkName) =>\n Ref.get(checkpoints).pipe(\n Effect.map(\n (map) =>\n map.get(sinkName) ?? {\n afterSeq: SequenceNumber.make(0),\n payload: undefined,\n },\n ),\n ),\n saveState: (sinkName, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, {\n afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),\n payload,\n });\n return next;\n }),\n commit: (sinkName, afterSeq, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, { afterSeq, payload });\n return next;\n }),\n});\n"],"mappings":";;;;;;;;AAUA,MAAa,cAAc,OAAO,eAAe,KAAK,OAAO,MAAM,aAAa,CAAC;;;;;;;;AAmCjF,IAAa,sBAAb,MAAa,4BAA4B,QAAQ,QAG/C,EAAE,2CAA2C,EAAE;;CAE/C,OAAgB,WAAW,MAAM,OAC/B,qBACA,OAAO,IAAI,aAAa;EAItB,OAAO,gCAAgC,OAHZ,IAAI,qBAC7B,IAAI,IAAI,CACV,CACkD;CACpD,CAAC,CACH;AACF;;AAGA,MAAM,mCACJ,iBAC8B;CAC9B,OAAO,aACL,IAAI,IAAI,WAAW,EAAE,KACnB,OAAO,KACJ,QACC,IAAI,IAAI,QAAQ,KAAK;EACnB,UAAU,eAAe,KAAK,CAAC;EAC/B,SAAS,KAAA;CACX,CACJ,CACF;CACF,YAAY,UAAU,YACpB,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GACjB,UAAU,IAAI,IAAI,QAAQ,GAAG,YAAY,eAAe,KAAK,CAAC;GAC9D;EACF,CAAC;EACD,OAAO;CACT,CAAC;CACH,SAAS,UAAU,UAAU,YAC3B,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GAAE;GAAU;EAAQ,CAAC;EACxC,OAAO;CACT,CAAC;AACL"}
@@ -1,2 +1,2 @@
1
- import { a as EDASinkContext, c as EDASinkRegistryShape, i as EDASinkCheckpoint, l as EDASinkRunnerStartInput, n as EDAEphemeralSinkDefinition, o as EDASinkDurableBatch, r as EDASink, s as EDASinkRegistry, t as EDADurableSinkDefinition } from "../sink-registry-BziFpxoE.js";
1
+ import { a as EDASinkContext, c as EDASinkRegistryShape, i as EDASinkCheckpoint, l as EDASinkRunnerStartInput, n as EDAEphemeralSinkDefinition, o as EDASinkDurableBatch, r as EDASink, s as EDASinkRegistry, t as EDADurableSinkDefinition } from "../sink-registry-Cf79ICdW.js";
2
2
  export { EDADurableSinkDefinition, EDAEphemeralSinkDefinition, EDASink, EDASinkCheckpoint, EDASinkContext, EDASinkDurableBatch, EDASinkRegistry, EDASinkRegistryShape, EDASinkRunnerStartInput };
@@ -1,2 +1,2 @@
1
- import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-CFC6xjsN.js";
1
+ import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-D13eUO_c.js";
2
2
  export { EDASink, EDASinkRegistry };
@@ -1,2 +1,2 @@
1
- import { a as ToolParamsSchema, i as EDAToolRegistryShape, n as EDAToolExecutionContext, o as makeEDAToolkit, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-CcnkAAQK.js";
1
+ import { a as ToolParamsSchema, i as EDAToolRegistryShape, n as EDAToolExecutionContext, o as makeEDAToolkit, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-B7Wona6N.js";
2
2
  export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
@@ -0,0 +1,54 @@
1
+ import { m as SequenceNumber } from "../core-CYT6DBaS.js";
2
+ import { o as EDASessionStoreError } from "../session-store-DZZUffUy.js";
3
+ import { r as EDARuntime } from "../runtime-DOgmAKsO.js";
4
+ import { EDAWebSocketClientFrame, EDAWebSocketFlowControl, EDAWebSocketServerFrame, SubscriberId } from "../host/websocket-protocol.js";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Schema from "effect/Schema";
7
+ import * as Queue from "effect/Queue";
8
+ import * as Scope from "effect/Scope";
9
+ import * as Deferred from "effect/Deferred";
10
+
11
+ //#region src/services/websocket-subscriber.d.ts
12
+ /** Slow subscriber reasons that intentionally close only the lagging socket. */
13
+ declare const SubscriberLagReason: Schema.Literals<readonly ["buffer-overflow", "ack-timeout"]>;
14
+ type SubscriberLagReason = typeof SubscriberLagReason.Type;
15
+ declare const SubscriberLagged_base: Schema.Class<SubscriberLagged, Schema.TaggedStruct<"SubscriberLagged", {
16
+ readonly subscriberId: Schema.brand<Schema.NonEmptyString, "SubscriberId">;
17
+ readonly lastAckedSeq: Schema.brand<Schema.Int, "SequenceNumber">;
18
+ readonly reason: Schema.Literals<readonly ["buffer-overflow", "ack-timeout"]>;
19
+ }>, import("effect/Cause").YieldableError>;
20
+ /** The subscriber could not keep up with the bounded live-delivery policy. */
21
+ declare class SubscriberLagged extends SubscriberLagged_base {}
22
+ declare const SubscriberProtocolError_base: Schema.Class<SubscriberProtocolError, Schema.TaggedStruct<"SubscriberProtocolError", {
23
+ readonly subscriberId: Schema.brand<Schema.NonEmptyString, "SubscriberId">;
24
+ readonly message: Schema.String;
25
+ }>, import("effect/Cause").YieldableError>;
26
+ /** The client sent a malformed or impossible protocol frame. */
27
+ declare class SubscriberProtocolError extends SubscriberProtocolError_base {}
28
+ declare const SubscriberSendFailed_base: Schema.Class<SubscriberSendFailed, Schema.TaggedStruct<"SubscriberSendFailed", {
29
+ readonly subscriberId: Schema.brand<Schema.NonEmptyString, "SubscriberId">;
30
+ readonly cause: Schema.Defect;
31
+ }>, import("effect/Cause").YieldableError>;
32
+ /** The host WebSocket boundary failed while sending a frame. */
33
+ declare class SubscriberSendFailed extends SubscriberSendFailed_base {}
34
+ /** Expected error surface for one WebSocket subscriber workflow. */
35
+ type EDAWebSocketSubscriberError = SubscriberLagged | SubscriberProtocolError | SubscriberSendFailed | EDASessionStoreError;
36
+ /** Transport boundary implemented by a host WebSocket adapter or tests. */
37
+ interface EDAWebSocketSubscriberTransport {
38
+ readonly send: (frame: EDAWebSocketServerFrame) => Effect.Effect<void, SubscriberSendFailed>;
39
+ readonly incoming: Queue.Queue<EDAWebSocketClientFrame>;
40
+ readonly closed: Deferred.Deferred<void>;
41
+ readonly persistAck: (seq: SequenceNumber) => Effect.Effect<void>;
42
+ }
43
+ /** Configuration for one scoped ACK-window subscriber workflow. */
44
+ interface EDAWebSocketSubscriberInput {
45
+ readonly subscriberId: SubscriberId;
46
+ readonly resumeSeq: SequenceNumber;
47
+ readonly policy: EDAWebSocketFlowControl;
48
+ readonly transport: EDAWebSocketSubscriberTransport;
49
+ }
50
+ /** Run one scoped, ACK-gated live-event WebSocket subscriber. */
51
+ declare const runWebSocketSubscriber: (input: EDAWebSocketSubscriberInput) => Effect.Effect<void, EDAWebSocketSubscriberError, EDARuntime | Scope.Scope>;
52
+ //#endregion
53
+ export { EDAWebSocketSubscriberError, EDAWebSocketSubscriberInput, EDAWebSocketSubscriberTransport, SubscriberLagReason, SubscriberLagged, SubscriberProtocolError, SubscriberSendFailed, runWebSocketSubscriber };
54
+ //# sourceMappingURL=websocket-subscriber.d.ts.map
@@ -0,0 +1,190 @@
1
+ import { SequenceNumber } from "../types/core.js";
2
+ import { yr as UnixEpochMillis } from "../durable-DsV9PxZC.js";
3
+ import { EDARuntime } from "./runtime.js";
4
+ import { EDAWebSocketEventsFrame, EDAWebSocketHeartbeatFrame, EDAWebSocketHelloFrame, EDA_WEB_SOCKET_PROTOCOL_VERSION, FrameId, SubscriberId } from "../host/websocket-protocol.js";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Schema from "effect/Schema";
7
+ import * as Stream from "effect/Stream";
8
+ import * as Clock from "effect/Clock";
9
+ import * as Queue from "effect/Queue";
10
+ import * as Ref from "effect/Ref";
11
+ import * as Deferred from "effect/Deferred";
12
+ //#region src/services/websocket-subscriber.ts
13
+ /** Slow subscriber reasons that intentionally close only the lagging socket. */
14
+ const SubscriberLagReason = Schema.Literals(["buffer-overflow", "ack-timeout"]);
15
+ /** The subscriber could not keep up with the bounded live-delivery policy. */
16
+ var SubscriberLagged = class extends Schema.TaggedErrorClass()("SubscriberLagged", {
17
+ subscriberId: SubscriberId,
18
+ lastAckedSeq: SequenceNumber,
19
+ reason: SubscriberLagReason
20
+ }) {};
21
+ /** The client sent a malformed or impossible protocol frame. */
22
+ var SubscriberProtocolError = class extends Schema.TaggedErrorClass()("SubscriberProtocolError", {
23
+ subscriberId: SubscriberId,
24
+ message: Schema.String
25
+ }) {};
26
+ /** The host WebSocket boundary failed while sending a frame. */
27
+ var SubscriberSendFailed = class extends Schema.TaggedErrorClass()("SubscriberSendFailed", {
28
+ subscriberId: SubscriberId,
29
+ cause: Schema.Defect()
30
+ }) {};
31
+ /** Run one scoped, ACK-gated live-event WebSocket subscriber. */
32
+ const runWebSocketSubscriber = (input) => Effect.gen(function* () {
33
+ const eda = yield* EDARuntime;
34
+ const outbound = yield* Queue.dropping(input.policy.subscriberBufferCapacityEvents);
35
+ const windowSignal = yield* Queue.sliding(1);
36
+ const timeoutFailure = yield* Deferred.make();
37
+ const lastAckedSeq = yield* Ref.make(input.resumeSeq);
38
+ const lastAckedFrameId = yield* Ref.make(0);
39
+ const lastSentFrameId = yield* Ref.make(0);
40
+ const lastSentDurableThroughSeq = yield* Ref.make(input.resumeSeq);
41
+ const nextFrameId = yield* Ref.make(FrameId.make(1));
42
+ const inFlight = yield* Ref.make([]);
43
+ yield* input.transport.send(EDAWebSocketHelloFrame.make({
44
+ _tag: "hello",
45
+ protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
46
+ subscriberId: input.subscriberId,
47
+ resumeSeq: input.resumeSeq,
48
+ flowControl: input.policy
49
+ }));
50
+ const pump = (yield* eda.eventsAfter(input.resumeSeq)).pipe(Stream.interruptWhen(Deferred.await(input.transport.closed)), Stream.runForEach((event) => Queue.offer(outbound, event).pipe(Effect.flatMap((accepted) => accepted ? Effect.void : Effect.gen(function* () {
51
+ const seq = yield* Ref.get(lastAckedSeq);
52
+ return yield* new SubscriberLagged({
53
+ subscriberId: input.subscriberId,
54
+ lastAckedSeq: seq,
55
+ reason: "buffer-overflow"
56
+ });
57
+ })))));
58
+ const sender = sendLoop({
59
+ inFlight,
60
+ input,
61
+ lastAckedSeq,
62
+ lastSentDurableThroughSeq,
63
+ lastSentFrameId,
64
+ nextFrameId,
65
+ outbound,
66
+ timeoutFailure,
67
+ windowSignal
68
+ });
69
+ const ackLoop = receiveAcks({
70
+ inFlight,
71
+ input,
72
+ lastAckedFrameId,
73
+ lastAckedSeq,
74
+ lastSentFrameId,
75
+ windowSignal
76
+ });
77
+ yield* Effect.raceFirst(Deferred.await(input.transport.closed), Effect.raceFirst(Deferred.await(timeoutFailure), Effect.raceFirst(pump, Effect.raceFirst(sender, ackLoop))));
78
+ });
79
+ const sendLoop = (input) => Effect.forever(Effect.gen(function* () {
80
+ yield* waitForWindow(input.inFlight, input.windowSignal, input.input.policy.maxInFlightFrames);
81
+ const next = yield* takeNextOutboundOrHeartbeat(input.outbound, input.input.policy.heartbeatIntervalMs);
82
+ if (next._tag === "heartbeat") {
83
+ yield* sendHeartbeat(input.input, input.lastSentDurableThroughSeq);
84
+ return;
85
+ }
86
+ const event = next.event;
87
+ const frameId = yield* Ref.get(input.nextFrameId);
88
+ yield* Ref.set(input.nextFrameId, FrameId.make(frameId + 1));
89
+ const previousSentDurableSeq = yield* Ref.get(input.lastSentDurableThroughSeq);
90
+ const durableThroughSeq = durableThroughForFrame([event], previousSentDurableSeq);
91
+ const frame = EDAWebSocketEventsFrame.make({
92
+ _tag: "events",
93
+ frameId,
94
+ events: [event],
95
+ durableThroughSeq
96
+ });
97
+ const encodedBytes = encodedFrameBytes(frame);
98
+ if (encodedBytes > input.input.policy.maxFrameBytes) return yield* new SubscriberProtocolError({
99
+ subscriberId: input.input.subscriberId,
100
+ message: `Encoded WebSocket frame exceeded maxFrameBytes (${encodedBytes} > ${input.input.policy.maxFrameBytes})`
101
+ });
102
+ const sent = {
103
+ frameId,
104
+ durableThroughSeq,
105
+ sentAtMs: yield* Clock.currentTimeMillis
106
+ };
107
+ yield* Ref.update(input.inFlight, (frames) => [...frames, sent]);
108
+ yield* Ref.set(input.lastSentFrameId, frameId);
109
+ yield* Ref.set(input.lastSentDurableThroughSeq, durableThroughSeq);
110
+ yield* input.input.transport.send(frame);
111
+ yield* startAckTimeout(input.input, input.inFlight, input.lastAckedSeq, input.timeoutFailure, sent);
112
+ }));
113
+ const takeNextOutboundOrHeartbeat = (outbound, heartbeatIntervalMs) => Effect.raceFirst(Queue.take(outbound).pipe(Effect.map((event) => ({
114
+ _tag: "event",
115
+ event
116
+ }))), Effect.sleep(`${heartbeatIntervalMs} millis`).pipe(Effect.as({ _tag: "heartbeat" })));
117
+ const sendHeartbeat = (input, lastSentDurableThroughSeq) => Effect.gen(function* () {
118
+ const durableThroughSeq = yield* Ref.get(lastSentDurableThroughSeq);
119
+ const serverTimeMs = yield* Clock.currentTimeMillis;
120
+ yield* input.transport.send(EDAWebSocketHeartbeatFrame.make({
121
+ _tag: "heartbeat",
122
+ serverTimeMs: UnixEpochMillis.make(serverTimeMs),
123
+ durableThroughSeq
124
+ }));
125
+ });
126
+ const receiveAcks = (input) => Effect.forever(Effect.gen(function* () {
127
+ const frame = yield* Queue.take(input.input.transport.incoming);
128
+ if (frame._tag !== "ack") return yield* new SubscriberProtocolError({
129
+ subscriberId: input.input.subscriberId,
130
+ message: `Unsupported client frame ${frame._tag ?? "unknown"}`
131
+ });
132
+ yield* applyAck(input, frame);
133
+ }));
134
+ const applyAck = (input, ack) => Effect.gen(function* () {
135
+ const lastAckedFrame = yield* Ref.get(input.lastAckedFrameId);
136
+ const lastSentFrame = yield* Ref.get(input.lastSentFrameId);
137
+ const currentSeq = yield* Ref.get(input.lastAckedSeq);
138
+ if (ack.frameId <= lastAckedFrame) {
139
+ if (ack.durableThroughSeq > currentSeq) return yield* new SubscriberProtocolError({
140
+ subscriberId: input.input.subscriberId,
141
+ message: "Duplicate ACK attempted to advance durable seq"
142
+ });
143
+ return;
144
+ }
145
+ if (ack.frameId > lastSentFrame) return yield* new SubscriberProtocolError({
146
+ subscriberId: input.input.subscriberId,
147
+ message: "ACK referenced an unsent frame"
148
+ });
149
+ if (ack.durableThroughSeq < currentSeq) return yield* new SubscriberProtocolError({
150
+ subscriberId: input.input.subscriberId,
151
+ message: "ACK durable seq moved backwards"
152
+ });
153
+ const acknowledged = (yield* Ref.get(input.inFlight)).filter((frame) => frame.frameId <= ack.frameId);
154
+ if (acknowledged.length === 0) return yield* new SubscriberProtocolError({
155
+ subscriberId: input.input.subscriberId,
156
+ message: "ACK referenced no in-flight frames"
157
+ });
158
+ const allowedDurableSeq = SequenceNumber.make(acknowledged.reduce((max, frame) => Math.max(max, frame.durableThroughSeq), currentSeq));
159
+ if (ack.durableThroughSeq > allowedDurableSeq) return yield* new SubscriberProtocolError({
160
+ subscriberId: input.input.subscriberId,
161
+ message: "ACK durable seq exceeded sent frame boundary"
162
+ });
163
+ yield* Ref.update(input.inFlight, (frames) => frames.filter((frame) => frame.frameId > ack.frameId));
164
+ yield* Ref.set(input.lastAckedFrameId, ack.frameId);
165
+ yield* Ref.set(input.lastAckedSeq, ack.durableThroughSeq);
166
+ yield* input.input.transport.persistAck(ack.durableThroughSeq);
167
+ yield* Queue.offer(input.windowSignal, void 0);
168
+ });
169
+ const waitForWindow = (inFlight, windowSignal, maxInFlightFrames) => Effect.gen(function* () {
170
+ while (true) {
171
+ if ((yield* Ref.get(inFlight)).length < maxInFlightFrames) return;
172
+ yield* Queue.take(windowSignal);
173
+ }
174
+ });
175
+ const startAckTimeout = (input, inFlight, lastAckedSeq, timeoutFailure, sent) => Effect.gen(function* () {
176
+ yield* Effect.sleep(`${input.policy.ackTimeoutMs} millis`);
177
+ if (!(yield* Ref.get(inFlight)).some((frame) => frame.frameId === sent.frameId)) return;
178
+ const seq = yield* Ref.get(lastAckedSeq);
179
+ yield* Deferred.fail(timeoutFailure, new SubscriberLagged({
180
+ subscriberId: input.subscriberId,
181
+ lastAckedSeq: seq,
182
+ reason: "ack-timeout"
183
+ }));
184
+ }).pipe(Effect.forkScoped, Effect.asVoid);
185
+ const durableThroughForFrame = (events, previousSentDurableSeq) => SequenceNumber.make(events.reduce((max, event) => event.event.durability === "durable" ? Math.max(max, event.position.seq) : max, previousSentDurableSeq));
186
+ const encodedFrameBytes = (frame) => new TextEncoder().encode(JSON.stringify(frame)).byteLength;
187
+ //#endregion
188
+ export { SubscriberLagReason, SubscriberLagged, SubscriberProtocolError, SubscriberSendFailed, runWebSocketSubscriber };
189
+
190
+ //# sourceMappingURL=websocket-subscriber.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket-subscriber.js","names":[],"sources":["../../src/services/websocket-subscriber.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { EDARuntime } from \"./runtime\";\nimport { EDASessionStoreError } from \"./session-store\";\nimport { SequenceNumber } from \"../types/core\";\nimport { UnixEpochMillis, type PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDAWebSocketAckFrame,\n EDAWebSocketEventsFrame,\n EDAWebSocketFlowControl,\n EDAWebSocketHeartbeatFrame,\n EDAWebSocketHelloFrame,\n FrameId,\n SubscriberId,\n type EDAWebSocketClientFrame,\n type EDAWebSocketServerFrame,\n} from \"../host/websocket-protocol\";\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/** The subscriber could not keep up with the bounded live-delivery policy. */\nexport class SubscriberLagged extends Schema.TaggedErrorClass<SubscriberLagged>()(\n \"SubscriberLagged\",\n {\n subscriberId: SubscriberId,\n lastAckedSeq: SequenceNumber,\n reason: SubscriberLagReason,\n },\n) {}\n\n/** The client sent a malformed or impossible protocol frame. */\nexport class SubscriberProtocolError extends Schema.TaggedErrorClass<SubscriberProtocolError>()(\n \"SubscriberProtocolError\",\n {\n subscriberId: SubscriberId,\n message: Schema.String,\n },\n) {}\n\n/** The host WebSocket boundary failed while sending a frame. */\nexport class SubscriberSendFailed extends Schema.TaggedErrorClass<SubscriberSendFailed>()(\n \"SubscriberSendFailed\",\n {\n subscriberId: SubscriberId,\n cause: Schema.Defect(),\n },\n) {}\n\n/** Expected error surface for one WebSocket subscriber workflow. */\nexport type EDAWebSocketSubscriberError =\n | SubscriberLagged\n | SubscriberProtocolError\n | SubscriberSendFailed\n | EDASessionStoreError;\n\n/** Transport boundary implemented by a host WebSocket adapter or tests. */\nexport interface EDAWebSocketSubscriberTransport {\n readonly send: (frame: EDAWebSocketServerFrame) => Effect.Effect<void, SubscriberSendFailed>;\n readonly incoming: Queue.Queue<EDAWebSocketClientFrame>;\n readonly closed: Deferred.Deferred<void>;\n readonly persistAck: (seq: SequenceNumber) => Effect.Effect<void>;\n}\n\n/** Configuration for one scoped ACK-window subscriber workflow. */\nexport interface EDAWebSocketSubscriberInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n readonly transport: EDAWebSocketSubscriberTransport;\n}\n\ninterface SentFrame {\n readonly frameId: FrameId;\n readonly durableThroughSeq: SequenceNumber;\n readonly sentAtMs: number;\n}\n\n/** Run one scoped, ACK-gated live-event WebSocket subscriber. */\nexport const runWebSocketSubscriber = (\n input: EDAWebSocketSubscriberInput,\n): Effect.Effect<void, EDAWebSocketSubscriberError, EDARuntime | Scope.Scope> =>\n Effect.gen(function* () {\n const eda = yield* EDARuntime;\n const outbound = yield* Queue.dropping<PositionedEvent>(\n input.policy.subscriberBufferCapacityEvents,\n );\n const windowSignal = yield* Queue.sliding<void>(1);\n const timeoutFailure = yield* Deferred.make<never, SubscriberLagged>();\n const lastAckedSeq = yield* Ref.make(input.resumeSeq);\n const lastAckedFrameId = yield* Ref.make(0);\n const lastSentFrameId = yield* Ref.make(0);\n const lastSentDurableThroughSeq = yield* Ref.make(input.resumeSeq);\n const nextFrameId = yield* Ref.make(FrameId.make(1));\n const inFlight = yield* Ref.make<ReadonlyArray<SentFrame>>([]);\n\n yield* input.transport.send(\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: input.subscriberId,\n resumeSeq: input.resumeSeq,\n flowControl: input.policy,\n }),\n );\n\n const events = yield* eda.eventsAfter(input.resumeSeq);\n // TODO(backpressure): this pump drains the replay/live stream into an intermediate queue ahead\n // of the ACK window. That bounded queue protects memory, but it still breaks end-to-end\n // backpressure from slow WebSocket clients to host-level paged durable replay.\n const pump = events.pipe(\n Stream.interruptWhen(Deferred.await(input.transport.closed)),\n Stream.runForEach((event) =>\n Queue.offer(outbound, event).pipe(\n Effect.flatMap((accepted) =>\n accepted\n ? Effect.void\n : Effect.gen(function* () {\n const seq = yield* Ref.get(lastAckedSeq);\n return yield* new SubscriberLagged({\n subscriberId: input.subscriberId,\n lastAckedSeq: seq,\n reason: \"buffer-overflow\",\n });\n }),\n ),\n ),\n ),\n );\n\n const sender = sendLoop({\n inFlight,\n input,\n lastAckedSeq,\n lastSentDurableThroughSeq,\n lastSentFrameId,\n nextFrameId,\n outbound,\n timeoutFailure,\n windowSignal,\n });\n const ackLoop = receiveAcks({\n inFlight,\n input,\n lastAckedFrameId,\n lastAckedSeq,\n lastSentFrameId,\n windowSignal,\n });\n\n yield* Effect.raceFirst(\n Deferred.await(input.transport.closed),\n Effect.raceFirst(\n Deferred.await(timeoutFailure),\n Effect.raceFirst(pump, Effect.raceFirst(sender, ackLoop)),\n ),\n );\n });\n\nconst sendLoop = (input: {\n readonly inFlight: Ref.Ref<ReadonlyArray<SentFrame>>;\n readonly input: EDAWebSocketSubscriberInput;\n readonly lastAckedSeq: Ref.Ref<SequenceNumber>;\n readonly lastSentDurableThroughSeq: Ref.Ref<SequenceNumber>;\n readonly lastSentFrameId: Ref.Ref<number>;\n readonly nextFrameId: Ref.Ref<FrameId>;\n readonly outbound: Queue.Queue<PositionedEvent>;\n readonly timeoutFailure: Deferred.Deferred<never, SubscriberLagged>;\n readonly windowSignal: Queue.Queue<void>;\n}): Effect.Effect<\n void,\n SubscriberLagged | SubscriberProtocolError | SubscriberSendFailed,\n Scope.Scope\n> =>\n Effect.forever(\n Effect.gen(function* () {\n yield* waitForWindow(\n input.inFlight,\n input.windowSignal,\n input.input.policy.maxInFlightFrames,\n );\n const next = yield* takeNextOutboundOrHeartbeat(\n input.outbound,\n input.input.policy.heartbeatIntervalMs,\n );\n if (next._tag === \"heartbeat\") {\n yield* sendHeartbeat(input.input, input.lastSentDurableThroughSeq);\n return;\n }\n\n const event = next.event;\n const frameId = yield* Ref.get(input.nextFrameId);\n yield* Ref.set(input.nextFrameId, FrameId.make(frameId + 1));\n\n const previousSentDurableSeq = yield* Ref.get(input.lastSentDurableThroughSeq);\n const durableThroughSeq = durableThroughForFrame([event], previousSentDurableSeq);\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: [event],\n durableThroughSeq,\n });\n const encodedBytes = encodedFrameBytes(frame);\n if (encodedBytes > input.input.policy.maxFrameBytes) {\n return yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: `Encoded WebSocket frame exceeded maxFrameBytes (${encodedBytes} > ${input.input.policy.maxFrameBytes})`,\n });\n }\n\n const sentAtMs = yield* Clock.currentTimeMillis;\n const sent = { frameId, durableThroughSeq, sentAtMs } satisfies SentFrame;\n // Mark the frame in-flight before the synchronous host send so an immediate\n // client ACK cannot race ahead of our bookkeeping.\n yield* Ref.update(input.inFlight, (frames) => [...frames, sent]);\n yield* Ref.set(input.lastSentFrameId, frameId);\n yield* Ref.set(input.lastSentDurableThroughSeq, durableThroughSeq);\n yield* input.input.transport.send(frame);\n yield* startAckTimeout(\n input.input,\n input.inFlight,\n input.lastAckedSeq,\n input.timeoutFailure,\n sent,\n );\n }),\n );\n\nconst takeNextOutboundOrHeartbeat = (\n outbound: Queue.Queue<PositionedEvent>,\n heartbeatIntervalMs: number,\n): Effect.Effect<\n { readonly _tag: \"event\"; readonly event: PositionedEvent } | { readonly _tag: \"heartbeat\" }\n> =>\n Effect.raceFirst(\n Queue.take(outbound).pipe(Effect.map((event) => ({ _tag: \"event\", event }) as const)),\n Effect.sleep(`${heartbeatIntervalMs} millis`).pipe(Effect.as({ _tag: \"heartbeat\" } as const)),\n );\n\nconst sendHeartbeat = (\n input: EDAWebSocketSubscriberInput,\n lastSentDurableThroughSeq: Ref.Ref<SequenceNumber>,\n): Effect.Effect<void, SubscriberSendFailed> =>\n Effect.gen(function* () {\n const durableThroughSeq = yield* Ref.get(lastSentDurableThroughSeq);\n const serverTimeMs = yield* Clock.currentTimeMillis;\n yield* input.transport.send(\n EDAWebSocketHeartbeatFrame.make({\n _tag: \"heartbeat\",\n serverTimeMs: UnixEpochMillis.make(serverTimeMs),\n durableThroughSeq,\n }),\n );\n });\n\nconst receiveAcks = (input: {\n readonly inFlight: Ref.Ref<ReadonlyArray<SentFrame>>;\n readonly input: EDAWebSocketSubscriberInput;\n readonly lastAckedFrameId: Ref.Ref<number>;\n readonly lastAckedSeq: Ref.Ref<SequenceNumber>;\n readonly lastSentFrameId: Ref.Ref<number>;\n readonly windowSignal: Queue.Queue<void>;\n}): Effect.Effect<void, SubscriberProtocolError> =>\n Effect.forever(\n Effect.gen(function* () {\n const frame = yield* Queue.take(input.input.transport.incoming);\n if (frame._tag !== \"ack\") {\n return yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: `Unsupported client frame ${\n (\n frame as {\n readonly _tag?: string;\n }\n )._tag ?? \"unknown\"\n }`,\n });\n }\n yield* applyAck(input, frame as EDAWebSocketAckFrame);\n }),\n );\n\nconst applyAck = (\n input: Parameters<typeof receiveAcks>[0],\n ack: EDAWebSocketAckFrame,\n): Effect.Effect<void, SubscriberProtocolError> =>\n Effect.gen(function* () {\n const lastAckedFrame = yield* Ref.get(input.lastAckedFrameId);\n const lastSentFrame = yield* Ref.get(input.lastSentFrameId);\n const currentSeq = yield* Ref.get(input.lastAckedSeq);\n\n if (ack.frameId <= lastAckedFrame) {\n if (ack.durableThroughSeq > currentSeq) {\n return yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"Duplicate ACK attempted to advance durable seq\",\n });\n }\n return;\n }\n\n if (ack.frameId > lastSentFrame) {\n return yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK referenced an unsent frame\",\n });\n }\n\n if (ack.durableThroughSeq < currentSeq) {\n return yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK durable seq moved backwards\",\n });\n }\n\n const frames = yield* Ref.get(input.inFlight);\n const acknowledged = frames.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledged.length === 0) {\n return yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK referenced no in-flight frames\",\n });\n }\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, frame) => Math.max(max, frame.durableThroughSeq),\n currentSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n return yield* new SubscriberProtocolError({\n subscriberId: input.input.subscriberId,\n message: \"ACK durable seq exceeded sent frame boundary\",\n });\n }\n\n yield* Ref.update(input.inFlight, (frames) =>\n frames.filter((frame) => frame.frameId > ack.frameId),\n );\n yield* Ref.set(input.lastAckedFrameId, ack.frameId);\n yield* Ref.set(input.lastAckedSeq, ack.durableThroughSeq);\n yield* input.input.transport.persistAck(ack.durableThroughSeq);\n yield* Queue.offer(input.windowSignal, undefined);\n });\n\nconst waitForWindow = (\n inFlight: Ref.Ref<ReadonlyArray<SentFrame>>,\n windowSignal: Queue.Queue<void>,\n maxInFlightFrames: number,\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n while (true) {\n const frames = yield* Ref.get(inFlight);\n if (frames.length < maxInFlightFrames) {\n return;\n }\n yield* Queue.take(windowSignal);\n }\n });\n\nconst startAckTimeout = (\n input: EDAWebSocketSubscriberInput,\n inFlight: Ref.Ref<ReadonlyArray<SentFrame>>,\n lastAckedSeq: Ref.Ref<SequenceNumber>,\n timeoutFailure: Deferred.Deferred<never, SubscriberLagged>,\n sent: SentFrame,\n): Effect.Effect<void, never, Scope.Scope> =>\n Effect.gen(function* () {\n yield* Effect.sleep(`${input.policy.ackTimeoutMs} millis`);\n const stillInFlight = (yield* Ref.get(inFlight)).some(\n (frame) => frame.frameId === sent.frameId,\n );\n if (!stillInFlight) {\n return;\n }\n const seq = yield* Ref.get(lastAckedSeq);\n yield* Deferred.fail(\n timeoutFailure,\n new SubscriberLagged({\n subscriberId: input.subscriberId,\n lastAckedSeq: seq,\n reason: \"ack-timeout\",\n }),\n );\n }).pipe(Effect.forkScoped, Effect.asVoid);\n\nconst durableThroughForFrame = (\n events: ReadonlyArray<PositionedEvent>,\n previousSentDurableSeq: SequenceNumber,\n): SequenceNumber =>\n SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n previousSentDurableSeq,\n ),\n );\n\nconst encodedFrameBytes = (frame: EDAWebSocketServerFrame): number =>\n new TextEncoder().encode(JSON.stringify(frame)).byteLength;\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAa,sBAAsB,OAAO,SAAS,CAAC,mBAAmB,aAAa,CAAC;;AAIrF,IAAa,mBAAb,cAAsC,OAAO,iBAAmC,EAC9E,oBACA;CACE,cAAc;CACd,cAAc;CACd,QAAQ;AACV,CACF,EAAE,CAAC;;AAGH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ACF,CAAC;AAEH,MAAM,mBACJ,OACA,UACA,cACA,gBACA,SAEA,OAAO,IAAI,aAAa;CACtB,OAAO,OAAO,MAAM,GAAG,MAAM,OAAO,aAAa,QAAQ;CAIzD,IAAI,EAHmB,OAAO,IAAI,IAAI,QAAQ,GAAG,MAC9C,UAAU,MAAM,YAAY,KAAK,OAEnB,GACf;CAEF,MAAM,MAAM,OAAO,IAAI,IAAI,YAAY;CACvC,OAAO,SAAS,KACd,gBACA,IAAI,iBAAiB;EACnB,cAAc,MAAM;EACpB,cAAc;EACd,QAAQ;CACV,CAAC,CACH;AACF,CAAC,EAAE,KAAK,OAAO,YAAY,OAAO,MAAM;AAE1C,MAAM,0BACJ,QACA,2BAEA,eAAe,KACb,OAAO,QACJ,KAAK,UACJ,MAAM,MAAM,eAAe,YAAY,KAAK,IAAI,KAAK,MAAM,SAAS,GAAG,IAAI,KAC7E,sBACF,CACF;AAEF,MAAM,qBAAqB,UACzB,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,KAAK,CAAC,EAAE"}
@@ -0,0 +1,38 @@
1
+ import { m as SequenceNumber } from "./core-CYT6DBaS.js";
2
+ import { L as PositionedEvent } from "./events-Bb9-Cu-7.js";
3
+ import { a as EDASessionStore, o as EDASessionStoreError } from "./session-store-DZZUffUy.js";
4
+ import { S as ReducedState } from "./command-queues-CV7O-51r.js";
5
+ import { t as DurableTranscriptMessage } from "./message-transcript-DiOPBY3l.js";
6
+ import { u as LiveEventBus } from "./sink-registry-Cf79ICdW.js";
7
+ import { i as EDAReducerStateSnapshot } from "./reducer-registry-CjSJBPKo.js";
8
+ import { h as SessionState } from "./session-state-CjOSvWbe.js";
9
+ import * as Context from "effect/Context";
10
+ import * as Effect from "effect/Effect";
11
+ import * as Layer from "effect/Layer";
12
+ import * as Stream from "effect/Stream";
13
+ import * as Scope from "effect/Scope";
14
+
15
+ //#region src/services/session-query.d.ts
16
+ /** Authoritative live snapshot for one EDA session plus its derived durable transcript. */
17
+ interface EDASessionSnapshot {
18
+ readonly state: ReducedState;
19
+ readonly reducerStates: EDAReducerStateSnapshot;
20
+ readonly messages: ReadonlyArray<DurableTranscriptMessage>;
21
+ }
22
+ /** Read-only query facade over authoritative live state and reconnect-safe event streams. */
23
+ interface EDASessionQueryShape {
24
+ /** Read the authoritative live state and derive its durable transcript. */
25
+ readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;
26
+ /** Read durable user/assistant messages in committed sequence order from the live snapshot. */
27
+ readonly messages: () => Effect.Effect<ReadonlyArray<DurableTranscriptMessage>, EDASessionStoreError>;
28
+ /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */
29
+ readonly eventsAfter: (afterSeq: SequenceNumber) => Effect.Effect<Stream.Stream<PositionedEvent, EDASessionStoreError>, EDASessionStoreError, Scope.Scope>;
30
+ }
31
+ declare const EDASessionQuery_base: Context.ServiceClass<EDASessionQuery, "@effect-durable-agent/EDASessionQuery", EDASessionQueryShape>;
32
+ /** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
33
+ declare class EDASessionQuery extends EDASessionQuery_base {
34
+ static readonly Live: Layer.Layer<EDASessionQuery, never, EDASessionStore | SessionState | LiveEventBus>;
35
+ }
36
+ //#endregion
37
+ export { EDASessionQueryShape as n, EDASessionSnapshot as r, EDASessionQuery as t };
38
+ //# sourceMappingURL=session-query-C-C4m1eq.d.ts.map