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

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 (221) hide show
  1. package/README.md +43 -41
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/{commands-Ce1ec6kH.d.ts → commands-3OD-p8dD.d.ts} +16 -9
  5. package/dist/compaction-63iEDHHl.js +523 -0
  6. package/dist/compaction-63iEDHHl.js.map +1 -0
  7. package/dist/context-projection-D_uRtK3r.d.ts +139 -0
  8. package/dist/{core-Hv3cFydL.d.ts → core-BcimKMIv.d.ts} +6 -4
  9. package/dist/delivery-2ZILvoRD.js +507 -0
  10. package/dist/delivery-2ZILvoRD.js.map +1 -0
  11. package/dist/{websocket-wire-D3tLrhe2.d.ts → delivery-RjM1_NAE.d.ts} +1019 -200
  12. package/dist/domain/command-queues.d.ts +81 -2
  13. package/dist/domain/command-queues.js +1 -1
  14. package/dist/domain/command-queues.js.map +1 -1
  15. package/dist/domain/context-projection.d.ts +2 -0
  16. package/dist/domain/context-projection.js +32 -0
  17. package/dist/domain/context-projection.js.map +1 -0
  18. package/dist/domain/message-transcript.d.ts +36 -2
  19. package/dist/domain/message-transcript.js +10 -2
  20. package/dist/domain/message-transcript.js.map +1 -1
  21. package/dist/domain/model-usage.d.ts +2 -0
  22. package/dist/domain/model-usage.js +59 -0
  23. package/dist/domain/model-usage.js.map +1 -0
  24. package/dist/domain/reduced-state-schema.d.ts +3 -996
  25. package/dist/domain/reduced-state-schema.js +121 -12
  26. package/dist/domain/reduced-state-schema.js.map +1 -1
  27. package/dist/domain/reduced-state.d.ts +3 -2
  28. package/dist/domain/reduced-state.js +937 -2
  29. package/dist/domain/reduced-state.js.map +1 -0
  30. package/dist/domain/run-scheduling.d.ts +2 -0
  31. package/dist/domain/run-scheduling.js +127 -0
  32. package/dist/domain/run-scheduling.js.map +1 -0
  33. package/dist/{durable-DlScwmCy.d.ts → durable-Cqv5ZRFA.d.ts} +8505 -2497
  34. package/dist/{durable-C3Rz7kg3.js → durable-D13w1Qr3.js} +253 -91
  35. package/dist/durable-D13w1Qr3.js.map +1 -0
  36. package/dist/envelope-BCzKUq_z.js +91 -0
  37. package/dist/envelope-BCzKUq_z.js.map +1 -0
  38. package/dist/envelope-Che6KatU.d.ts +254 -0
  39. package/dist/{keep-alive-p8dIcSVy.js → event-factory-_vF1bIJ7.js} +8 -10
  40. package/dist/event-factory-_vF1bIJ7.js.map +1 -0
  41. package/dist/{events-Bb9-Cu-7.d.ts → events-Dg0o5wWs.d.ts} +140 -324
  42. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
  43. package/dist/in-memory-CeODnZhE.js +150 -0
  44. package/dist/in-memory-CeODnZhE.js.map +1 -0
  45. package/dist/index.d.ts +8 -7
  46. package/dist/index.js +6 -5
  47. package/dist/interpreter-DKGJ1sSx.js +1452 -0
  48. package/dist/interpreter-DKGJ1sSx.js.map +1 -0
  49. package/dist/keep-alive-_zFCUvt3.d.ts +28 -0
  50. package/dist/model-resolver-D0vcDZsU.d.ts +24 -0
  51. package/dist/model-usage-0GeHwaaU.d.ts +54 -0
  52. package/dist/records--54mZEBx.js +675 -0
  53. package/dist/records--54mZEBx.js.map +1 -0
  54. package/dist/reduced-state-DU2ECOUp.d.ts +47821 -0
  55. package/dist/reduced-state-schema-B2t3cobf.d.ts +2187 -0
  56. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-JLU1yptN.d.ts} +24 -8
  57. package/dist/run-scheduling-wakeup-D_bGdicf.d.ts +24 -0
  58. package/dist/services/compaction.d.ts +2 -2
  59. package/dist/services/compaction.js +2 -426
  60. package/dist/services/id-generator.d.ts +1 -1
  61. package/dist/services/id-generator.js +4 -2
  62. package/dist/services/id-generator.js.map +1 -1
  63. package/dist/services/keep-alive.d.ts +2 -0
  64. package/dist/services/keep-alive.js +13 -0
  65. package/dist/services/keep-alive.js.map +1 -0
  66. package/dist/services/model-call.d.ts +15 -0
  67. package/dist/services/model-call.js +15 -0
  68. package/dist/services/model-call.js.map +1 -0
  69. package/dist/services/model-resolver.d.ts +2 -0
  70. package/dist/services/model-resolver.js +17 -0
  71. package/dist/services/model-resolver.js.map +1 -0
  72. package/dist/services/prompt-projector.d.ts +2 -2
  73. package/dist/services/prompt-projector.js +49 -5
  74. package/dist/services/prompt-projector.js.map +1 -1
  75. package/dist/services/reducer-registry.d.ts +2 -2
  76. package/dist/services/reducer-registry.js +21 -4
  77. package/dist/services/reducer-registry.js.map +1 -1
  78. package/dist/services/run-scheduler.d.ts +2 -0
  79. package/dist/services/run-scheduler.js +25 -0
  80. package/dist/services/run-scheduler.js.map +1 -0
  81. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  82. package/dist/services/run-scheduling-wakeup.js +13 -0
  83. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  84. package/dist/services/runtime-layer.d.ts +48 -0
  85. package/dist/services/runtime-layer.js +51 -0
  86. package/dist/services/runtime-layer.js.map +1 -0
  87. package/dist/services/runtime.d.ts +1 -1
  88. package/dist/services/runtime.js +34 -20
  89. package/dist/services/runtime.js.map +1 -1
  90. package/dist/services/session-event-observer.d.ts +2 -0
  91. package/dist/services/session-event-observer.js +13 -0
  92. package/dist/services/session-event-observer.js.map +1 -0
  93. package/dist/services/session-query.d.ts +2 -2
  94. package/dist/services/session-query.js +141 -2
  95. package/dist/services/session-query.js.map +1 -0
  96. package/dist/services/session-state.d.ts +2 -0
  97. package/dist/services/session-state.js +2 -0
  98. package/dist/services/session-store.d.ts +2 -2
  99. package/dist/services/session-store.js +272 -2
  100. package/dist/services/session-store.js.map +1 -0
  101. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  102. package/dist/services/sink-checkpoint-store.js +50 -0
  103. package/dist/services/sink-checkpoint-store.js.map +1 -0
  104. package/dist/services/sink-registry.d.ts +2 -2
  105. package/dist/services/sink-registry.js +1 -1
  106. package/dist/services/span-names.d.ts +1 -1
  107. package/dist/services/span-names.js +7 -1
  108. package/dist/services/span-names.js.map +1 -1
  109. package/dist/services/tool-registry.d.ts +2 -2
  110. package/dist/services/tool-registry.js +12 -3
  111. package/dist/services/tool-registry.js.map +1 -1
  112. package/dist/services/tracing.d.ts +3 -3
  113. package/dist/services/tracing.js +25 -4
  114. package/dist/services/tracing.js.map +1 -1
  115. package/dist/session-event-observer-HvrRckbC.d.ts +24 -0
  116. package/dist/{session-query-Cbf-e0rG.js → session-state-BQYsuBqi.js} +693 -251
  117. package/dist/session-state-BQYsuBqi.js.map +1 -0
  118. package/dist/session-store-CQxg9U82.d.ts +3302 -0
  119. package/dist/sink-checkpoint-store-DWGifxp0.d.ts +39 -0
  120. package/dist/sink-registry-DskRcyOS.js +345 -0
  121. package/dist/sink-registry-DskRcyOS.js.map +1 -0
  122. package/dist/subscription-DmO3BcdT.js +505 -0
  123. package/dist/subscription-DmO3BcdT.js.map +1 -0
  124. package/dist/subscription-rC35dAWn.d.ts +958 -0
  125. package/dist/testkit/layers.d.ts +34 -19
  126. package/dist/testkit/layers.js +30 -16
  127. package/dist/testkit/layers.js.map +1 -1
  128. package/dist/testkit/transcript.d.ts +226 -0
  129. package/dist/testkit/transcript.js +1475 -0
  130. package/dist/testkit/transcript.js.map +1 -0
  131. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-BzlMhwzj.d.ts} +44 -8
  132. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  133. package/dist/transcript.d.ts +101 -0
  134. package/dist/transcript.js +107 -0
  135. package/dist/transcript.js.map +1 -0
  136. package/dist/types/commands.d.ts +2 -2
  137. package/dist/types/commands.js +8 -3
  138. package/dist/types/commands.js.map +1 -1
  139. package/dist/types/core.d.ts +2 -2
  140. package/dist/types/core.js +4 -2
  141. package/dist/types/core.js.map +1 -1
  142. package/dist/types/events/durable.d.ts +2 -2
  143. package/dist/types/events/durable.js +2 -2
  144. package/dist/types/events.d.ts +5 -4
  145. package/dist/types/events.js +3 -2
  146. package/dist/types/events.js.map +1 -1
  147. package/dist/types/tracing.d.ts +1 -1
  148. package/dist/types/tracing.js.map +1 -1
  149. package/dist/websocket/events.d.ts +2 -0
  150. package/dist/websocket/events.js +2 -0
  151. package/dist/websocket.d.ts +2201 -0
  152. package/dist/websocket.js +684 -0
  153. package/dist/websocket.js.map +1 -0
  154. package/dist/window-read-CBZEJ84M.d.ts +113 -0
  155. package/dist/window-read-DPFAA1hM.js +264 -0
  156. package/dist/window-read-DPFAA1hM.js.map +1 -0
  157. package/package.json +87 -46
  158. package/testing/offline-trace/README.md +2 -1
  159. package/CHANGELOG.md +0 -25
  160. package/CONTRIBUTING.md +0 -26
  161. package/SECURITY.md +0 -7
  162. package/dist/command-queues-CQ9cwRP7.d.ts +0 -468
  163. package/dist/compaction-1LSZR944.d.ts +0 -144
  164. package/dist/durable-C3Rz7kg3.js.map +0 -1
  165. package/dist/durable-object-runtime-CiMKxGs6.d.ts +0 -257
  166. package/dist/durable-object-runtime-wKiqaAt2.js +0 -1494
  167. package/dist/durable-object-runtime-wKiqaAt2.js.map +0 -1
  168. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  169. package/dist/host/durable-object-runtime.d.ts +0 -2
  170. package/dist/host/durable-object-runtime.js +0 -2
  171. package/dist/host/durable-object-storage.d.ts +0 -2
  172. package/dist/host/durable-object-storage.js +0 -0
  173. package/dist/host/durable-object.d.ts +0 -83
  174. package/dist/host/durable-object.js +0 -191
  175. package/dist/host/durable-object.js.map +0 -1
  176. package/dist/host/websocket-wire.d.ts +0 -2
  177. package/dist/host/websocket-wire.js +0 -105
  178. package/dist/host/websocket-wire.js.map +0 -1
  179. package/dist/index-BVVgDSdq.d.ts +0 -1
  180. package/dist/keep-alive-DYDsH6qN.d.ts +0 -111
  181. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  182. package/dist/message-transcript-BCHdHAe2.d.ts +0 -32
  183. package/dist/prompt-projector-DimXJPOJ.d.ts +0 -39
  184. package/dist/reduced-state-C4nVVzz9.js +0 -910
  185. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  186. package/dist/runtime-DcdPOEuE.d.ts +0 -60
  187. package/dist/services/compaction.js.map +0 -1
  188. package/dist/session-query-Cbf-e0rG.js.map +0 -1
  189. package/dist/session-query-hxfujxUH.d.ts +0 -769
  190. package/dist/session-store-D2Ore1QC.d.ts +0 -295
  191. package/dist/session-store-pYxQW9qh.js +0 -214
  192. package/dist/session-store-pYxQW9qh.js.map +0 -1
  193. package/dist/sink-registry-BziFpxoE.d.ts +0 -158
  194. package/dist/sink-registry-CFC6xjsN.js +0 -312
  195. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  196. package/docs/assets/architecture.svg +0 -216
  197. package/docs/assets/event-sequence.svg +0 -133
  198. package/docs/assets/gcp-trace.png +0 -0
  199. package/docs/assets/hero.svg +0 -33
  200. package/docs/message-steering.md +0 -831
  201. package/docs/releasing.md +0 -96
  202. package/docs/spec.md +0 -777
  203. package/docs/subagents.md +0 -725
  204. package/docs/testing.md +0 -64
  205. package/docs/ui-projection.md +0 -742
  206. package/docs/websocket-protocol.md +0 -639
  207. package/examples/001-no-tools/README.md +0 -65
  208. package/examples/001-no-tools/worker.ts +0 -79
  209. package/examples/002-slack-bridge/README.md +0 -134
  210. package/examples/002-slack-bridge/events.ts +0 -115
  211. package/examples/002-slack-bridge/reducer.ts +0 -216
  212. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  213. package/examples/002-slack-bridge/sinks.ts +0 -109
  214. package/examples/002-slack-bridge/worker.ts +0 -140
  215. package/examples/003-sandbox-lifecycle/README.md +0 -78
  216. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  217. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  218. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  219. package/examples/_shared/event-id.ts +0 -12
  220. package/examples/_shared/http.ts +0 -27
  221. package/examples/_shared/openai.ts +0 -33
@@ -0,0 +1,2 @@
1
+ import { n as SessionEventObserverShape, t as SessionEventObserver } from "../session-event-observer-HvrRckbC.js";
2
+ export { SessionEventObserver, SessionEventObserverShape };
@@ -0,0 +1,13 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Layer from "effect/Layer";
4
+ //#region src/services/session-event-observer.ts
5
+ /** Host-provided observer for append-driven integrations such as hibernatable WebSockets. */
6
+ var SessionEventObserver = class SessionEventObserver extends Context.Service()("@effect-durable-agent/SessionEventObserver") {
7
+ static Noop = Layer.succeed(SessionEventObserver, { onEvent: () => Effect.void });
8
+ static FromHandler = (onEvent) => Layer.succeed(SessionEventObserver, { onEvent });
9
+ };
10
+ //#endregion
11
+ export { SessionEventObserver };
12
+
13
+ //# sourceMappingURL=session-event-observer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-event-observer.js","names":[],"sources":["../../src/services/session-event-observer.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport type { PositionedEvent } from \"../types/events\";\n\n/**\n * Outbound integration point notified synchronously after EDA publishes an event.\n *\n * Hosts provide this service while composing the runtime. Implementations own\n * their failures and never expose host errors to the session runtime.\n */\nexport interface SessionEventObserverShape {\n readonly onEvent: (event: PositionedEvent) => Effect.Effect<void>;\n}\n\n/** Host-provided observer for append-driven integrations such as hibernatable WebSockets. */\nexport class SessionEventObserver extends Context.Service<\n SessionEventObserver,\n SessionEventObserverShape\n>()(\"@effect-durable-agent/SessionEventObserver\") {\n static readonly Noop = Layer.succeed(SessionEventObserver, {\n onEvent: () => Effect.void,\n });\n\n static readonly FromHandler = (\n onEvent: SessionEventObserverShape[\"onEvent\"],\n ): Layer.Layer<SessionEventObserver> => Layer.succeed(SessionEventObserver, { onEvent });\n}\n"],"mappings":";;;;;AAiBA,IAAa,uBAAb,MAAa,6BAA6B,QAAQ,QAGhD,CAAC,CAAC,4CAA4C,CAAC,CAAC;CAChD,OAAgB,OAAO,MAAM,QAAQ,sBAAsB,EACzD,eAAe,OAAO,KACxB,CAAC;CAED,OAAgB,eACd,YACsC,MAAM,QAAQ,sBAAsB,EAAE,QAAQ,CAAC;AACzF"}
@@ -1,2 +1,2 @@
1
- import { n as EDASessionQueryShape, r as EDASessionSnapshot, t as EDASessionQuery } from "../session-query-hxfujxUH.js";
2
- export { EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
1
+ import { $ as EDASessionQueryShape, Q as EDASessionQuery, Z as EDASessionEventPage, et as EDASessionSnapshot } from "../reduced-state-DU2ECOUp.js";
2
+ export { EDASessionEventPage, EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
@@ -1,2 +1,141 @@
1
- import { t as EDASessionQuery } from "../session-query-Cbf-e0rG.js";
2
- export { EDASessionQuery };
1
+ import { SequenceNumber } from "../types/core.js";
2
+ import { d as PositionedEvent } from "../envelope-BCzKUq_z.js";
3
+ import { qn as durableEventEnvelope } from "../durable-D13w1Qr3.js";
4
+ import { m as LiveEventBus, u as SessionState } from "../session-state-BQYsuBqi.js";
5
+ import { ReducedStateSchema } from "../domain/reduced-state-schema.js";
6
+ import { EDASessionStore } from "./session-store.js";
7
+ import { annotateEdaSpan } from "./tracing.js";
8
+ import * as Context from "effect/Context";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Layer from "effect/Layer";
11
+ import * as Schema from "effect/Schema";
12
+ import * as Stream from "effect/Stream";
13
+ import * as PubSub from "effect/PubSub";
14
+ //#region src/services/session-query.ts
15
+ /** Authoritative live snapshot for one EDA session: reduced state plus app reducer states. */
16
+ const EDASessionSnapshot = Schema.Struct({
17
+ state: ReducedStateSchema,
18
+ reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown)
19
+ });
20
+ /** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
21
+ var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-durable-agent/EDASessionQuery") {
22
+ static Live = Layer.effect(EDASessionQuery, Effect.gen(function* () {
23
+ const store = yield* EDASessionStore;
24
+ const liveBus = yield* LiveEventBus;
25
+ const sessionState = yield* SessionState;
26
+ const snapshot = Effect.gen(function* () {
27
+ const data = yield* sessionState.snapshotData();
28
+ return {
29
+ state: data.reduced,
30
+ reducerStates: data.reducerStates
31
+ };
32
+ });
33
+ return {
34
+ runRequestOutcome: Effect.fn("agent.run.request.outcome")(function* (requestId) {
35
+ const head = (yield* sessionState.snapshot()).lastSeq;
36
+ let outcome = { _tag: "Unknown" };
37
+ yield* store.eventsAfter(SequenceNumber.make(0)).pipe(Stream.takeWhile((entry) => entry.position.seq <= head), Stream.runForEach((entry) => Effect.sync(() => {
38
+ const event = entry.event;
39
+ if (event.namespace !== "effect-durable-agent") return;
40
+ switch (event.type) {
41
+ case "RunSchedulingRequested":
42
+ if (event.payload.requestId === requestId) outcome = { _tag: "Waiting" };
43
+ break;
44
+ case "RunSchedulingInvalidated":
45
+ if (event.payload.requestId === requestId) outcome = { _tag: "Invalidated" };
46
+ break;
47
+ case "RunSchedulingGranted": {
48
+ const grant = event.payload;
49
+ if (grant.requestId === requestId) outcome = {
50
+ _tag: "Granted",
51
+ runId: grant.runId,
52
+ status: "Running"
53
+ };
54
+ break;
55
+ }
56
+ case "RunCompleted":
57
+ if (outcome._tag === "Granted" && event.payload.runId === outcome.runId) outcome = {
58
+ ...outcome,
59
+ status: "Completed"
60
+ };
61
+ break;
62
+ case "RunFailed":
63
+ if (outcome._tag === "Granted" && event.payload.runId === outcome.runId) outcome = {
64
+ ...outcome,
65
+ status: "Failed"
66
+ };
67
+ break;
68
+ case "RunInterrupted": if (outcome._tag === "Granted" && event.payload.runId === outcome.runId) outcome = {
69
+ ...outcome,
70
+ status: "Interrupted"
71
+ };
72
+ }
73
+ })));
74
+ return outcome;
75
+ }),
76
+ snapshot: () => snapshot,
77
+ eventsAfter: (afterSeq) => Effect.gen(function* () {
78
+ const live = yield* liveBus.subscribeQueue();
79
+ const replayHead = (yield* sessionState.snapshot()).lastSeq;
80
+ const replay = yield* store.eventsAfter(afterSeq).pipe(Stream.filter((entry) => entry.position.seq <= replayHead), Stream.map((entry) => PositionedEvent.make({
81
+ position: entry.position,
82
+ event: durableEventEnvelope(entry.event)
83
+ })), Stream.runCollect, Effect.map((events) => Array.from(events)));
84
+ const activeTurnReplay = yield* liveBus.activeTurnReplay();
85
+ const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter((event) => shouldEmitLiveEvent(event, replayHead));
86
+ const reconnectPrefix = Array.from(uniquePositionedEvents([
87
+ ...replay,
88
+ ...activeTurnReplay.events,
89
+ ...pendingLive
90
+ ])).sort(comparePositionedEvents);
91
+ yield* annotateEdaSpan({
92
+ "eda.seq.after": afterSeq,
93
+ "eda.seq.head": replayHead,
94
+ "eda.replay.events": replay.length,
95
+ "eda.live.active_turn_events": activeTurnReplay.events.length,
96
+ "eda.live.active_turn_overflowed": activeTurnReplay.overflowed,
97
+ "eda.live.buffered_events": pendingLive.length
98
+ });
99
+ const follow = Stream.fromEffectRepeat(PubSub.take(live)).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));
100
+ return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));
101
+ }).pipe(Effect.withSpan("agent.events.follow", { attributes: { "eda.seq.after": afterSeq } })),
102
+ readEventPage: (afterSeq, limit) => Effect.gen(function* () {
103
+ const head = (yield* sessionState.snapshot()).lastSeq;
104
+ if (limit <= 0 || afterSeq >= head) return {
105
+ events: [],
106
+ head
107
+ };
108
+ return {
109
+ events: yield* store.eventsAfter(afterSeq).pipe(Stream.filter((entry) => entry.position.seq <= head), Stream.take(limit), Stream.map((entry) => PositionedEvent.make({
110
+ position: entry.position,
111
+ event: durableEventEnvelope(entry.event)
112
+ })), Stream.runCollect, Effect.map((events) => Array.from(events))),
113
+ head
114
+ };
115
+ }).pipe(Effect.withSpan("agent.events.page", { attributes: {
116
+ "eda.seq.after": afterSeq,
117
+ "eda.page.limit": limit
118
+ } }))
119
+ };
120
+ }));
121
+ };
122
+ const shouldEmitLiveEvent = (event, replayHead) => event.event.durability === "ephemeral" || event.position.seq > replayHead;
123
+ const comparePositionedEvents = (left, right) => {
124
+ const seq = left.position.seq - right.position.seq;
125
+ return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;
126
+ };
127
+ const uniquePositionedEvents = (events) => {
128
+ const seen = /* @__PURE__ */ new Set();
129
+ const output = [];
130
+ for (const event of events) {
131
+ const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;
132
+ if (seen.has(key)) continue;
133
+ seen.add(key);
134
+ output.push(event);
135
+ }
136
+ return output;
137
+ };
138
+ //#endregion
139
+ export { EDASessionQuery, EDASessionSnapshot };
140
+
141
+ //# sourceMappingURL=session-query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport { ReducedStateSchema } from \"../domain/reduced-state-schema\";\nimport { durableEventEnvelope } from \"../types/events/durable\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { RunRequestOutcome } from \"../domain/run-scheduling\";\nimport { effectDurableAgentNamespace } from \"../types/events\";\nimport { type RunRequestId, SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Authoritative live snapshot for one EDA session: reduced state plus app reducer states. */\nexport const EDASessionSnapshot = Schema.Struct({\n state: ReducedStateSchema,\n reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown),\n});\nexport type EDASessionSnapshot = typeof EDASessionSnapshot.Type;\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Reconcile one request against committed facts, including after reducer history pruning. */\n readonly runRequestOutcome: (\n requestId: RunRequestId,\n ) => Effect.Effect<RunRequestOutcome, EDASessionStoreError>;\n /** Read the authoritative live state and app reducer states. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n } satisfies EDASessionSnapshot;\n });\n\n return {\n runRequestOutcome: Effect.fn(\"agent.run.request.outcome\")(function* (\n requestId: RunRequestId,\n ) {\n const head = (yield* sessionState.snapshot()).lastSeq;\n let outcome: RunRequestOutcome = { _tag: \"Unknown\" };\n yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((entry) => entry.position.seq <= head),\n Stream.runForEach((entry) =>\n Effect.sync(() => {\n const event = entry.event;\n if (event.namespace !== effectDurableAgentNamespace) return;\n switch (event.type) {\n case \"RunSchedulingRequested\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Waiting\" };\n break;\n case \"RunSchedulingInvalidated\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Invalidated\" };\n break;\n case \"RunSchedulingGranted\": {\n const grant = event.payload;\n if (grant.requestId === requestId)\n outcome = { _tag: \"Granted\", runId: grant.runId, status: \"Running\" };\n break;\n }\n case \"RunCompleted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Completed\" };\n break;\n case \"RunFailed\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Failed\" };\n break;\n case \"RunInterrupted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Interrupted\" };\n break;\n }\n }),\n ),\n );\n return outcome;\n }),\n snapshot: () => snapshot,\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n output.push(event);\n }\n return output;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,qBAAqB,OAAO,OAAO;CAC9C,OAAO;CACP,eAAe,OAAO,YAAY,OAAO,QAAQ,OAAO,OAAO;AACjE,CAAC;;AAiCD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,CAAC,CAC3F,uCACF,CAAC,CAAC;CACA,OAAgB,OAAO,MAAM,OAC3B,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO;EACvB,MAAM,eAAe,OAAO;EAE5B,MAAM,WAAW,OAAO,IAAI,aAAa;GACvC,MAAM,OAAO,OAAO,aAAa,aAAa;GAC9C,OAAO;IACL,OAAO,KAAK;IACZ,eAAe,KAAK;GACtB;EACF,CAAC;EAED,OAAO;GACL,mBAAmB,OAAO,GAAG,2BAA2B,CAAC,CAAC,WACxD,WACA;IACA,MAAM,QAAQ,OAAO,aAAa,SAAS,EAAA,CAAG;IAC9C,IAAI,UAA6B,EAAE,MAAM,UAAU;IACnD,OAAO,MAAM,YAAY,eAAe,KAAK,CAAC,CAAC,CAAC,CAAC,KAC/C,OAAO,WAAW,UAAU,MAAM,SAAS,OAAO,IAAI,GACtD,OAAO,YAAY,UACjB,OAAO,WAAW;KAChB,MAAM,QAAQ,MAAM;KACpB,IAAI,MAAM,cAAA,wBAA2C;KACrD,QAAQ,MAAM,MAAd;MACE,KAAK;OACH,IAAI,MAAM,QAAQ,cAAc,WAAW,UAAU,EAAE,MAAM,UAAU;OACvE;MACF,KAAK;OACH,IAAI,MAAM,QAAQ,cAAc,WAAW,UAAU,EAAE,MAAM,cAAc;OAC3E;MACF,KAAK,wBAAwB;OAC3B,MAAM,QAAQ,MAAM;OACpB,IAAI,MAAM,cAAc,WACtB,UAAU;QAA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AAM,0BACJ,WACmC;CACnC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
@@ -0,0 +1,2 @@
1
+ import { _t as SessionStateShape, at as SessionCommandCompleted, ct as SessionCommandResult, dt as SessionForkedCommand, ft as SessionNoRunnableCommand, gt as SessionStateError, ht as SessionState, it as SessionCommandCancelled, lt as SessionDrainProcessed, mt as SessionRunInput, nt as SessionCommandAdmissionConflict, ot as SessionCommandFailed, pt as SessionNoRunnableReason, rt as SessionCommandAdmissionError, st as SessionCommandOutcome, tt as EDASubmittable, ut as SessionDrainResult, vt as SessionStateSnapshotData } from "../reduced-state-DU2ECOUp.js";
2
+ export { EDASubmittable, SessionCommandAdmissionConflict, SessionCommandAdmissionError, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionCommandResult, SessionDrainProcessed, SessionDrainResult, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState, SessionStateError, SessionStateShape, SessionStateSnapshotData };
@@ -0,0 +1,2 @@
1
+ import { a as SessionCommandOutcome, c as SessionNoRunnableReason, i as SessionCommandFailed, l as SessionRunInput, n as SessionCommandCancelled, o as SessionForkedCommand, r as SessionCommandCompleted, s as SessionNoRunnableCommand, t as SessionCommandAdmissionConflict, u as SessionState } from "../session-state-BQYsuBqi.js";
2
+ export { SessionCommandAdmissionConflict, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState };
@@ -1,2 +1,2 @@
1
- import { a as EDASessionStore, c as FindCommandAdmissionInput, d as hasEDASessionStoreError, i as EDAReducerCheckpoint, l as SaveReducerCheckpointInput, n as DurableAppendBatch, o as EDASessionStoreError, r as DurableAppendEntry, s as EDASessionStoreShape, t as CommittedDurableEvent, u as durableObjectSerializedJsonHardCapBytes } from "../session-store-D2Ore1QC.js";
2
- export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, durableObjectSerializedJsonHardCapBytes, hasEDASessionStoreError };
1
+ import { a as EDAReducerCheckpoint, c as EDASessionStoreShape, d as SaveReducerCheckpointInput, f as hasEDASessionStoreError, h as selectCommittedEvent, i as EDAAppEvents, l as FindCommandAdmissionInput, m as registerAppEvents, n as DurableAppendBatch, o as EDASessionStore, p as queryCommittedEvents, r as DurableAppendEntry, s as EDASessionStoreError, t as CommittedDurableEvent, u as InMemoryStoreOptions } from "../session-store-CQxg9U82.js";
2
+ export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAAppEvents, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, InMemoryStoreOptions, SaveReducerCheckpointInput, hasEDASessionStoreError, queryCommittedEvents, registerAppEvents, selectCommittedEvent };
@@ -1,2 +1,272 @@
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 { t as DurableEventEnvelope } from "../envelope-BCzKUq_z.js";
3
+ import { H as DecodedDurableEvent, Nn as commandAdmittedEventType, Un as contextRebasedEventType, Wn as decodeDurableEventSync, kr as decodeRetainingExcess, mr as summaryCreatedEventType, qn as durableEventEnvelope } from "../durable-D13w1Qr3.js";
4
+ import { CompactionSummaryArtifact } from "../domain/context-projection.js";
5
+ import { m as makeTranscriptDefinition, p as emptyTranscriptMappings } from "../interpreter-DKGJ1sSx.js";
6
+ import { T as TranscriptLogIncarnation } from "../records--54mZEBx.js";
7
+ import { a as maintainTranscripts, i as initialTranscriptState, r as inMemoryTranscriptWindowSource } from "../in-memory-CeODnZhE.js";
8
+ import { a as EDATranscriptStore, n as inactiveTranscriptWindow, r as readTranscriptWindowFrom } from "../window-read-DPFAA1hM.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 Schema from "effect/Schema";
13
+ import * as Stream from "effect/Stream";
14
+ import * as Cause from "effect/Cause";
15
+ import * as Ref from "effect/Ref";
16
+ import * as Result from "effect/Result";
17
+ import * as SchemaGetter from "effect/SchemaGetter";
18
+ //#region src/services/session-store.ts
19
+ /** A durable event after the store has assigned its replay position. */
20
+ const CommittedDurableEvent = Schema.Struct({
21
+ position: DurablePosition,
22
+ event: DurableEventEnvelope.pipe(Schema.decodeTo(Schema.declare(Schema.is(DecodedDurableEvent)), {
23
+ decode: SchemaGetter.transform(decodeDurableEventSync),
24
+ encode: SchemaGetter.transform(durableEventEnvelope)
25
+ }))
26
+ });
27
+ /**
28
+ * Store-level failure surfaced by durable append, replay, and hydration APIs.
29
+ *
30
+ * The error intentionally stays storage-semantic rather than SQL-specific so
31
+ * framework services can treat SQL-backed hosts, in-memory tests, and future adapters
32
+ * as the same durability boundary.
33
+ */
34
+ var EDASessionStoreError = class extends Schema.TaggedError()("EDASessionStoreError", { message: Schema.String }) {};
35
+ /** True when a Cause contains an escaped durable-store failure. */
36
+ const hasEDASessionStoreError = (cause) => cause.reasons.some((reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError);
37
+ /**
38
+ * One logical event to persist in the durable session log.
39
+ *
40
+ * Store adapters may split large logical payload fields into sidecar rows after
41
+ * the event insert assigns `seq`, but callers still provide one fat event.
42
+ */
43
+ const DurableAppendEntry = Schema.Struct({ event: DurableEventEnvelope });
44
+ /**
45
+ * Ordered durable append intent. Adapters assign positions in entry order.
46
+ *
47
+ * This is the single write shape exposed to framework services. It avoids raw
48
+ * SQL and public transaction callbacks while still expressing the full atomic
49
+ * transition EDA needs for events, normalized bodies, and metadata.
50
+ */
51
+ const DurableAppendBatch = Schema.Struct({ entries: Schema.Array(DurableAppendEntry) });
52
+ /** Indexed command-admission lookup used for idempotent ingress. */
53
+ const FindCommandAdmissionInput = Schema.Struct({
54
+ commandId: Schema.optionalKey(CommandId),
55
+ idempotencyKey: Schema.optionalKey(Schema.String)
56
+ });
57
+ /**
58
+ * SQL-agnostic durable storage port for one EDA session.
59
+ *
60
+ * Framework services depend on this semantic port rather than raw SQL. Host
61
+ * adapters own physical tables and synchronous transaction mechanics; callers
62
+ * only express durable append/replay/lookup intent.
63
+ */
64
+ var EDASessionStore = class extends Context.Service()("@effect-durable-agent/EDASessionStore") {
65
+ /**
66
+ * Deterministic in-memory implementation used by runtime and recovery tests.
67
+ *
68
+ * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append
69
+ * critical section. Without `options.transcript` it maintains the definition with no host
70
+ * mappings.
71
+ */
72
+ static InMemory = (sessionId, options) => inMemoryStoreLayer(sessionId, () => [], options);
73
+ /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */
74
+ static InMemorySeeded = (sessionId, events, options) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);
75
+ };
76
+ const inMemoryStoreLayer = (sessionId, seed, options) => Layer.effectContext(Effect.gen(function* () {
77
+ const committed = seed();
78
+ const config = options?.transcript ?? { current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie) };
79
+ const data = yield* Ref.make({
80
+ committed,
81
+ summaries: summariesFromCommittedEvents(committed),
82
+ reducerCheckpoints: /* @__PURE__ */ new Map(),
83
+ transcript: initialTranscriptState(TranscriptLogIncarnation.make(`memory:${sessionId}`), config, committed)
84
+ });
85
+ return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)));
86
+ }));
87
+ const seedCommittedEvents = (sessionId, events) => {
88
+ const seen = /* @__PURE__ */ new Set();
89
+ return events.map((event, index) => {
90
+ if (event.sessionId !== sessionId) throw new Error(`EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`);
91
+ if (seen.has(event.eventId)) throw new Error(`Duplicate seed eventId ${event.eventId}`);
92
+ seen.add(event.eventId);
93
+ return {
94
+ position: durablePosition(SequenceNumber.make(index + 1)),
95
+ event: decodeDurableEventSync(DurableEventEnvelope.make(event))
96
+ };
97
+ });
98
+ };
99
+ const summariesFromCommittedEvents = (events) => {
100
+ const summaries = /* @__PURE__ */ new Map();
101
+ for (const { event } of events) {
102
+ if (event.type !== summaryCreatedEventType) continue;
103
+ const payload = event.payload;
104
+ if (payload.summary !== void 0) {
105
+ const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
106
+ summaries.set(summary.summaryId, summary);
107
+ }
108
+ }
109
+ return summaries;
110
+ };
111
+ /**
112
+ * Build an in-memory store with one `Ref.modify` append critical section.
113
+ *
114
+ * The fake models the semantic atomicity of the production adapter without
115
+ * exposing SQL, so runtime tests exercise the same store contract.
116
+ */
117
+ const makeInMemoryStore = (sessionId, data) => {
118
+ const ensureSession = (event) => Effect.gen(function* () {
119
+ if (event.sessionId === sessionId) return;
120
+ return yield* new EDASessionStoreError({ message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}` });
121
+ });
122
+ const append = (batch) => Effect.gen(function* () {
123
+ for (const entry of batch.entries) yield* ensureSession(entry.event);
124
+ return yield* Ref.modify(data, (current) => {
125
+ const nextEntries = [...current.committed];
126
+ const nextSummaries = new Map(current.summaries);
127
+ const committedEvents = [];
128
+ const appended = [];
129
+ for (const entry of batch.entries) {
130
+ const { event } = entry;
131
+ const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);
132
+ if (existing !== void 0) {
133
+ committedEvents.push(existing);
134
+ continue;
135
+ }
136
+ const committed = {
137
+ position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),
138
+ event: decodeDurableEventSync(DurableEventEnvelope.make(event))
139
+ };
140
+ nextEntries.push(committed);
141
+ committedEvents.push(committed);
142
+ appended.push(committed);
143
+ if (committed.event.type === summaryCreatedEventType) {
144
+ const payload = committed.event.payload;
145
+ if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
146
+ const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
147
+ if (payload.summaryId !== void 0 && summary.summaryId !== payload.summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
148
+ nextSummaries.set(summary.summaryId, summary);
149
+ }
150
+ if (committed.event.type === contextRebasedEventType) {
151
+ const payload = committed.event.payload;
152
+ if (payload.summaryId === void 0 || !nextSummaries.has(payload.summaryId)) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
153
+ }
154
+ }
155
+ return [committedEvents, {
156
+ committed: nextEntries,
157
+ summaries: nextSummaries,
158
+ reducerCheckpoints: current.reducerCheckpoints,
159
+ transcript: appended.length === 0 ? current.transcript : maintainTranscripts(current.transcript, appended)
160
+ }];
161
+ });
162
+ });
163
+ return {
164
+ append,
165
+ eventsAfter: (afterSeq) => Stream.fromIterableEffect(Ref.get(data).pipe(Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)))),
166
+ loadCommittedEventsBySeq: (seqs) => Ref.get(data).pipe(Effect.map(({ committed }) => {
167
+ const requested = new Set(seqs.map((seq) => Number(seq)));
168
+ return committed.filter((entry) => requested.has(Number(entry.position.seq)));
169
+ })),
170
+ findCommandAdmission: (input) => Ref.get(data).pipe(Effect.map(({ committed }) => committed.find((entry) => commandAdmissionMatches(entry, input)))),
171
+ loadSummaryArtifact: (summaryId) => Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),
172
+ loadReducerCheckpoint: (name) => Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),
173
+ saveReducerCheckpoint: (checkpoint) => Ref.update(data, (current) => ({
174
+ ...current,
175
+ reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint)
176
+ })),
177
+ saveReducerCheckpoints: (checkpoints) => Ref.update(data, (current) => {
178
+ const reducerCheckpoints = new Map(current.reducerCheckpoints);
179
+ for (const checkpoint of checkpoints) reducerCheckpoints.set(checkpoint.name, checkpoint);
180
+ return {
181
+ ...current,
182
+ reducerCheckpoints
183
+ };
184
+ })
185
+ };
186
+ };
187
+ /** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */
188
+ const makeInMemoryTranscriptStore = (data) => ({
189
+ readTranscriptWindow: (selector, limits) => Effect.gen(function* () {
190
+ const { transcript } = yield* Ref.get(data);
191
+ const source = inMemoryTranscriptWindowSource(transcript);
192
+ if (source === void 0) return inactiveTranscriptWindow(transcript.incarnation, transcript.config.current.version, transcript.versions.find((version) => version.meta.role === "building")?.meta);
193
+ const window = readTranscriptWindowFrom(source, selector, limits);
194
+ return Result.isSuccess(window) ? window.success : yield* window.failure;
195
+ }),
196
+ readTranscriptMeta: Ref.get(data).pipe(Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)))
197
+ });
198
+ const commandAdmissionMatches = (entry, input) => {
199
+ if (entry.event.type !== commandAdmittedEventType) return false;
200
+ const admitted = entry.event.payload.command;
201
+ if (admitted === void 0) return false;
202
+ if (input.idempotencyKey !== void 0 && admitted.idempotencyKey === input.idempotencyKey) return true;
203
+ return input.commandId !== void 0 && admitted.commandId === input.commandId;
204
+ };
205
+ const eventNamespaces = (ast) => {
206
+ if (ast._tag === "Union") return ast.types.flatMap(eventNamespaces);
207
+ if (ast._tag === "Objects") {
208
+ const namespace = ast.propertySignatures.find((field) => field.name === "namespace")?.type;
209
+ if (namespace?._tag === "Literal" && typeof namespace.literal === "string") return [namespace.literal];
210
+ }
211
+ throw new Error("App event schemas must be a union of structs with literal namespaces");
212
+ };
213
+ /** Attach the app decoder to every event-returning store operation without changing storage bytes. */
214
+ const registerAppEvents = (store, schema) => {
215
+ const namespaces = new Set(eventNamespaces(schema.ast));
216
+ const decode = decodeRetainingExcess(schema);
217
+ const envelopeKey = (event) => JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));
218
+ const decodeEntry = (entry, prepared) => {
219
+ if (entry.event.namespace !== "__foreign" || !namespaces.has(entry.event.envelope.namespace)) return entry;
220
+ return {
221
+ ...entry,
222
+ event: {
223
+ ...entry.event,
224
+ decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope)
225
+ }
226
+ };
227
+ };
228
+ const decodeEntryEffect = (entry) => Effect.try({
229
+ try: () => decodeEntry(entry),
230
+ catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
231
+ });
232
+ const decodeEntries = (entries) => Effect.forEach(entries, decodeEntryEffect);
233
+ return {
234
+ ...store,
235
+ append: (batch) => Effect.gen(function* () {
236
+ const prepared = yield* Effect.try({
237
+ try: () => {
238
+ const decoded = /* @__PURE__ */ new Map();
239
+ for (const { event } of batch.entries) {
240
+ if (!namespaces.has(event.namespace)) continue;
241
+ const key = envelopeKey(event);
242
+ if (!decoded.has(key)) decoded.set(key, decode(event));
243
+ }
244
+ return decoded;
245
+ },
246
+ catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
247
+ });
248
+ const committed = yield* store.append(batch);
249
+ return yield* Effect.forEach(committed, (entry) => Effect.try({
250
+ try: () => decodeEntry(entry, prepared),
251
+ catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
252
+ }));
253
+ }),
254
+ eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),
255
+ loadCommittedEventsBySeq: (seqs) => store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),
256
+ findCommandAdmission: (input) => store.findCommandAdmission(input).pipe(Effect.flatMap((entry) => entry === void 0 ? Effect.succeed(void 0) : decodeEntryEffect(entry)))
257
+ };
258
+ };
259
+ /** Narrow an already decoded fact from one schema, without decoding its payload again. */
260
+ const selectCommittedEvent = (schema, entry) => {
261
+ const event = entry.event.namespace === "__foreign" ? entry.event.decoded ?? entry.event.envelope : entry.event;
262
+ return Schema.is(schema)(event) ? {
263
+ position: entry.position,
264
+ event
265
+ } : void 0;
266
+ };
267
+ /** Typed journal read available to tools and application services without private SQL access. */
268
+ const queryCommittedEvents = (store, schema, options = {}) => store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(Stream.map((entry) => selectCommittedEvent(schema, entry)), Stream.filter((entry) => entry !== void 0), Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER), Stream.runCollect);
269
+ //#endregion
270
+ export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDASessionStore, EDASessionStoreError, FindCommandAdmissionInput, hasEDASessionStoreError, queryCommittedEvents, registerAppEvents, selectCommittedEvent };
271
+
272
+ //# 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 Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n DecodedDurableEvent,\n decodeDurableEventSync,\n durableEventEnvelope,\n} from \"../types/events/durable\";\n\nimport { type CommandIdempotencyKey } 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\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport {\n initialTranscriptState,\n inMemoryTranscriptWindowSource,\n maintainTranscripts,\n type InMemoryTranscriptState,\n} from \"../transcript/in-memory\";\nimport { emptyTranscriptMappings, makeTranscriptDefinition } from \"../transcript/mapping\";\nimport { TranscriptLogIncarnation } from \"../transcript/records\";\nimport {\n EDATranscriptStore,\n type EDATranscriptStoreShape,\n type TranscriptMaintenanceConfig,\n} from \"../transcript/store\";\nimport { inactiveTranscriptWindow, readTranscriptWindowFrom } from \"../transcript/window-read\";\n\nexport type CommittedDurableEvent<E = DecodedDurableEvent> = {\n readonly position: typeof DurablePosition.Type;\n readonly event: E;\n};\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent: Schema.Codec<\n CommittedDurableEvent,\n {\n readonly position: typeof DurablePosition.Encoded;\n readonly event: typeof DurableEventEnvelope.Encoded;\n },\n never,\n never\n> = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope.pipe(\n Schema.decodeTo(Schema.declare<DecodedDurableEvent>(Schema.is(DecodedDurableEvent)), {\n decode: SchemaGetter.transform(decodeDurableEventSync),\n encode: SchemaGetter.transform(durableEventEnvelope),\n }),\n ),\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.TaggedError<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 /**\n * Deterministic in-memory implementation used by runtime and recovery tests.\n *\n * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append\n * critical section. Without `options.transcript` it maintains the definition with no host\n * mappings.\n */\n static readonly InMemory = (sessionId: SessionId, options?: InMemoryStoreOptions) =>\n inMemoryStoreLayer(sessionId, () => [], options);\n\n /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n options?: InMemoryStoreOptions,\n ) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);\n}\n\n/** Construction options for the in-memory store. */\nexport interface InMemoryStoreOptions {\n /** Transcript definitions to maintain; defaults to the definition with no host mappings. */\n readonly transcript?: TranscriptMaintenanceConfig;\n}\n\nconst inMemoryStoreLayer = (\n sessionId: SessionId,\n seed: () => ReadonlyArray<CommittedDurableEvent>,\n options: InMemoryStoreOptions | undefined,\n) =>\n Layer.effectContext(\n Effect.gen(function* () {\n const committed = seed();\n const config = options?.transcript ?? {\n current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie),\n };\n const data = yield* Ref.make<InMemoryStoreData>({\n committed,\n summaries: summariesFromCommittedEvents(committed),\n reducerCheckpoints: new Map(),\n transcript: initialTranscriptState(\n TranscriptLogIncarnation.make(`memory:${sessionId}`),\n config,\n committed,\n ),\n });\n return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(\n Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(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 readonly transcript: InMemoryTranscriptState;\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 {\n position: durablePosition(SequenceNumber.make(index + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(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;\n if (payload.summary !== undefined) {\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\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 const appended: 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 = {\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n nextEntries.push(committed);\n committedEvents.push(committed);\n appended.push(committed);\n\n if (committed.event.type === summaryCreatedEventType) {\n const payload = committed.event.payload;\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\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 (committed.event.type === contextRebasedEventType) {\n const payload = committed.event.payload;\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 // Projection staging commits with the events; a projection failure freezes only\n // the failed version and never fails the append.\n transcript:\n appended.length === 0\n ? current.transcript\n : maintainTranscripts(current.transcript, appended),\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\n/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */\nconst makeInMemoryTranscriptStore = (\n data: Ref.Ref<InMemoryStoreData>,\n): EDATranscriptStoreShape => ({\n readTranscriptWindow: (selector, limits) =>\n Effect.gen(function* () {\n const { transcript } = yield* Ref.get(data);\n const source = inMemoryTranscriptWindowSource(transcript);\n if (source === undefined) {\n return inactiveTranscriptWindow(\n transcript.incarnation,\n transcript.config.current.version,\n transcript.versions.find((version) => version.meta.role === \"building\")?.meta,\n );\n }\n const window = readTranscriptWindowFrom(source, selector, limits);\n return Result.isSuccess(window) ? window.success : yield* window.failure;\n }),\n readTranscriptMeta: Ref.get(data).pipe(\n Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)),\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.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\n/** App schemas are registered once; known namespaces fail at the store boundary when malformed. */\nexport type EDAAppEvents = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\nconst eventNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventNamespaces);\n if (ast._tag === \"Objects\") {\n const namespace = ast.propertySignatures.find((field) => field.name === \"namespace\")?.type;\n if (namespace?._tag === \"Literal\" && typeof namespace.literal === \"string\")\n return [namespace.literal];\n }\n throw new Error(\"App event schemas must be a union of structs with literal namespaces\");\n};\n\n/** Attach the app decoder to every event-returning store operation without changing storage bytes. */\nexport const registerAppEvents = (\n store: EDASessionStoreShape,\n schema: EDAAppEvents,\n): EDASessionStoreShape => {\n const namespaces = new Set(eventNamespaces(schema.ast));\n const decode = decodeRetainingExcess(schema);\n const envelopeKey = (event: DurableEventEnvelope): string =>\n JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));\n const decodeEntry = (\n entry: CommittedDurableEvent,\n prepared?: ReadonlyMap<string, DurableEventEnvelope>,\n ): CommittedDurableEvent => {\n if (entry.event.namespace !== \"__foreign\" || !namespaces.has(entry.event.envelope.namespace))\n return entry;\n return {\n ...entry,\n event: {\n ...entry.event,\n decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope),\n },\n };\n };\n const decodeEntryEffect = (entry: CommittedDurableEvent) =>\n Effect.try({\n try: () => decodeEntry(entry),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const decodeEntries = (entries: ReadonlyArray<CommittedDurableEvent>) =>\n Effect.forEach(entries, decodeEntryEffect);\n return {\n ...store,\n append: (batch) =>\n Effect.gen(function* () {\n // Idempotent append can return different retained bytes for the same event id.\n // Reuse a prepared decode only when the complete persisted envelope matches.\n const prepared = yield* Effect.try({\n try: () => {\n const decoded = new Map<string, DurableEventEnvelope>();\n for (const { event } of batch.entries) {\n if (!namespaces.has(event.namespace)) continue;\n const key = envelopeKey(event);\n if (!decoded.has(key)) {\n decoded.set(key, decode(event));\n }\n }\n return decoded;\n },\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const committed = yield* store.append(batch);\n return yield* Effect.forEach(committed, (entry) =>\n Effect.try({\n try: () => decodeEntry(entry, prepared),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n }),\n );\n }),\n eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),\n loadCommittedEventsBySeq: (seqs) =>\n store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),\n findCommandAdmission: (input) =>\n store\n .findCommandAdmission(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): entry is CommittedDurableEvent<E> => entry !== undefined),\n Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER),\n Stream.runCollect,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,MAAa,wBAQT,OAAO,OAAO;CAChB,UAAU;CACV,OAAO,qBAAqB,KAC1B,OAAO,SAAS,OAAO,QAA6B,OAAO,GAAG,mBAAmB,CAAC,GAAG;EACnF,QAAQ,aAAa,UAAU,sBAAsB;EACrD,QAAQ,aA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yB,IAAI,CAAC,CAAC,KAAK,OAAO,QAAQ,aAAa,CAAC;EACzE,uBAAuB,UACrB,MACG,qBAAqB,KAAK,CAAC,CAC3B,KACC,OAAO,SAAS,UACd,UAAU,KAAA,IAAY,OAAO,QAAQ,KAAA,CAAS,IAAI,kBAAkB,KAAK,CAC3E,CACF;CACN;AACF;;AAGA,MAAa,wBACX,QACA,UACyC;CACzC,MAAM,QACJ,MAAM,MAAM,cAAc,cACrB,MAAM,MAAM,WAAW,MAAM,MAAM,WACpC,MAAM;CACZ,OAAO,OAAO,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI;EAAE,UAAU,MAAM;EAAU;CAAM,IAAI,KAAA;AAC1E;;AAGA,MAAa,wBACX,OACA,QACA,UAA2E,CAAC,MAE5E,MAAM,YAAY,QAAQ,YAAY,eAAe,KAAK,CAAC,CAAC,CAAC,CAAC,KAC5D,OAAO,KAAK,UAAU,qBAAqB,QAAQ,KAAK,CAAC,GACzD,OAAO,QAAQ,UAA6C,UAAU,KAAA,CAAS,GAC/E,OAAO,KAAK,QAAQ,SAAS,OAAO,gBAAgB,GACpD,OAAO,UACT"}
@@ -0,0 +1,2 @@
1
+ import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-DWGifxp0.js";
2
+ export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
@@ -0,0 +1,50 @@
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
+ const checkpoints = yield* Ref.make(/* @__PURE__ */ new Map());
21
+ return makeInMemorySinkCheckpointStore(checkpoints);
22
+ }));
23
+ };
24
+ /** Build a ref-backed checkpoint map with the same public semantics as host adapters. */
25
+ const makeInMemorySinkCheckpointStore = (checkpoints) => ({
26
+ load: (sinkName) => Ref.get(checkpoints).pipe(Effect.map((map) => map.get(sinkName) ?? {
27
+ afterSeq: SequenceNumber.make(0),
28
+ payload: void 0
29
+ })),
30
+ saveState: (sinkName, payload) => Ref.update(checkpoints, (map) => {
31
+ const next = new Map(map);
32
+ next.set(sinkName, {
33
+ afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),
34
+ payload
35
+ });
36
+ return next;
37
+ }),
38
+ commit: (sinkName, afterSeq, payload) => Ref.update(checkpoints, (map) => {
39
+ const next = new Map(map);
40
+ next.set(sinkName, {
41
+ afterSeq,
42
+ payload
43
+ });
44
+ return next;
45
+ })
46
+ });
47
+ //#endregion
48
+ export { EDASinkName, SinkCheckpointStore };
49
+
50
+ //# sourceMappingURL=sink-checkpoint-store.js.map