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

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 (142) hide show
  1. package/README.md +43 -41
  2. package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-Dwdf41mq.d.ts} +7 -6
  3. package/dist/{compaction-1LSZR944.d.ts → compaction-DpHOf-g7.d.ts} +8 -6
  4. package/dist/context-projection-B4DWOZgi.d.ts +140 -0
  5. package/dist/{core-Hv3cFydL.d.ts → core-CYT6DBaS.d.ts} +2 -2
  6. package/dist/domain/command-queues.d.ts +1 -1
  7. package/dist/domain/context-projection.d.ts +2 -0
  8. package/dist/domain/context-projection.js +32 -0
  9. package/dist/domain/context-projection.js.map +1 -0
  10. package/dist/domain/message-transcript.d.ts +1 -1
  11. package/dist/domain/reduced-state-schema.d.ts +2 -0
  12. package/dist/domain/reduced-state-schema.js +2 -1
  13. package/dist/domain/reduced-state-schema.js.map +1 -1
  14. package/dist/domain/reduced-state.d.ts +1 -1
  15. package/dist/domain/reduced-state.js +1 -1
  16. package/dist/{durable-DlScwmCy.d.ts → durable-B7M6TD_0.d.ts} +341 -2
  17. package/dist/{durable-C3Rz7kg3.js → durable-DsV9PxZC.js} +13 -2
  18. package/dist/durable-DsV9PxZC.js.map +1 -0
  19. package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-CLJcyymV.d.ts} +5 -29
  20. package/dist/{keep-alive-p8dIcSVy.js → event-factory-tcpLgdMN.js} +3 -10
  21. package/dist/event-factory-tcpLgdMN.js.map +1 -0
  22. package/dist/host/websocket-protocol.d.ts +252 -0
  23. package/dist/host/websocket-protocol.js +111 -0
  24. package/dist/host/websocket-protocol.js.map +1 -0
  25. package/dist/host/websocket-wire.d.ts +2 -2
  26. package/dist/host/websocket-wire.js +21 -4
  27. package/dist/host/websocket-wire.js.map +1 -1
  28. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-Ckl8_XWW.d.ts} +2 -2
  29. package/dist/index.d.ts +4 -4
  30. package/dist/index.js +2 -2
  31. package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
  32. package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-CFn_D3MH.d.ts} +3 -3
  33. package/dist/{prompt-projector-DimXJPOJ.d.ts → prompt-projector-C2meuNrV.d.ts} +5 -5
  34. package/dist/{reduced-state-C4nVVzz9.js → reduced-state-TMi7ISla.js} +20 -4
  35. package/dist/reduced-state-TMi7ISla.js.map +1 -0
  36. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-K9FqZq5-.d.ts} +2 -2
  37. package/dist/{runtime-DcdPOEuE.d.ts → runtime-5NEJngu3.d.ts} +12 -6
  38. package/dist/services/compaction.d.ts +1 -1
  39. package/dist/services/compaction.js +4 -3
  40. package/dist/services/compaction.js.map +1 -1
  41. package/dist/services/id-generator.d.ts +1 -1
  42. package/dist/services/keep-alive.d.ts +2 -0
  43. package/dist/services/keep-alive.js +13 -0
  44. package/dist/services/keep-alive.js.map +1 -0
  45. package/dist/services/prompt-projector.d.ts +1 -1
  46. package/dist/services/reducer-registry.d.ts +1 -1
  47. package/dist/services/runtime-layer.d.ts +58 -0
  48. package/dist/services/runtime-layer.js +42 -0
  49. package/dist/services/runtime-layer.js.map +1 -0
  50. package/dist/services/runtime.d.ts +1 -1
  51. package/dist/services/runtime.js +9 -4
  52. package/dist/services/runtime.js.map +1 -1
  53. package/dist/services/session-query.d.ts +2 -2
  54. package/dist/services/session-query.js +93 -1
  55. package/dist/services/session-query.js.map +1 -0
  56. package/dist/services/session-state.d.ts +2 -0
  57. package/dist/services/session-state.js +2 -0
  58. package/dist/services/session-store.d.ts +2 -2
  59. package/dist/services/session-store.js +181 -2
  60. package/dist/services/session-store.js.map +1 -0
  61. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  62. package/dist/services/sink-checkpoint-store.js +49 -0
  63. package/dist/services/sink-checkpoint-store.js.map +1 -0
  64. package/dist/services/sink-registry.d.ts +1 -1
  65. package/dist/services/sink-registry.js +1 -1
  66. package/dist/services/span-names.d.ts +1 -1
  67. package/dist/services/span-names.js +1 -0
  68. package/dist/services/span-names.js.map +1 -1
  69. package/dist/services/tool-registry.d.ts +1 -1
  70. package/dist/services/websocket-delivery.d.ts +90 -0
  71. package/dist/services/websocket-delivery.js +221 -0
  72. package/dist/services/websocket-delivery.js.map +1 -0
  73. package/dist/session-query-5oyZRaQL.d.ts +45 -0
  74. package/dist/{session-query-hxfujxUH.d.ts → session-state-CI1xeT6f.d.ts} +134 -42
  75. package/dist/{session-query-Cbf-e0rG.js → session-state-D7dqko7r.js} +19 -78
  76. package/dist/session-state-D7dqko7r.js.map +1 -0
  77. package/dist/{session-store-D2Ore1QC.d.ts → session-store-BLg6UvZa.d.ts} +5 -94
  78. package/dist/sink-checkpoint-store-B9WNvDtY.d.ts +40 -0
  79. package/dist/{sink-registry-CFC6xjsN.js → sink-registry-BbmoI9uv.js} +25 -70
  80. package/dist/sink-registry-BbmoI9uv.js.map +1 -0
  81. package/dist/{sink-registry-BziFpxoE.d.ts → sink-registry-CO3YPS1p.d.ts} +31 -48
  82. package/dist/testkit/layers.d.ts +14 -11
  83. package/dist/testkit/layers.js +9 -6
  84. package/dist/testkit/layers.js.map +1 -1
  85. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-B8H1P6Pu.d.ts} +3 -3
  86. package/dist/types/core.d.ts +1 -1
  87. package/dist/types/core.js +1 -1
  88. package/dist/types/core.js.map +1 -1
  89. package/dist/types/events/durable.d.ts +2 -2
  90. package/dist/types/events/durable.js +2 -2
  91. package/dist/types/events.d.ts +2 -2
  92. package/dist/types/events.js +2 -2
  93. package/dist/{websocket-wire-D3tLrhe2.d.ts → websocket-wire-DPxwY4G5.d.ts} +112 -11
  94. package/package.json +48 -40
  95. package/testing/offline-trace/README.md +2 -1
  96. package/CHANGELOG.md +0 -25
  97. package/CONTRIBUTING.md +0 -26
  98. package/SECURITY.md +0 -7
  99. package/dist/durable-C3Rz7kg3.js.map +0 -1
  100. package/dist/durable-object-runtime-CiMKxGs6.d.ts +0 -257
  101. package/dist/durable-object-runtime-wKiqaAt2.js +0 -1494
  102. package/dist/durable-object-runtime-wKiqaAt2.js.map +0 -1
  103. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  104. package/dist/host/durable-object-runtime.d.ts +0 -2
  105. package/dist/host/durable-object-runtime.js +0 -2
  106. package/dist/host/durable-object-storage.d.ts +0 -2
  107. package/dist/host/durable-object-storage.js +0 -0
  108. package/dist/host/durable-object.d.ts +0 -83
  109. package/dist/host/durable-object.js +0 -191
  110. package/dist/host/durable-object.js.map +0 -1
  111. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  112. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  113. package/dist/session-query-Cbf-e0rG.js.map +0 -1
  114. package/dist/session-store-pYxQW9qh.js +0 -214
  115. package/dist/session-store-pYxQW9qh.js.map +0 -1
  116. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  117. package/docs/assets/architecture.svg +0 -216
  118. package/docs/assets/event-sequence.svg +0 -133
  119. package/docs/assets/gcp-trace.png +0 -0
  120. package/docs/assets/hero.svg +0 -33
  121. package/docs/message-steering.md +0 -831
  122. package/docs/releasing.md +0 -96
  123. package/docs/spec.md +0 -777
  124. package/docs/subagents.md +0 -725
  125. package/docs/testing.md +0 -64
  126. package/docs/ui-projection.md +0 -742
  127. package/docs/websocket-protocol.md +0 -639
  128. package/examples/001-no-tools/README.md +0 -65
  129. package/examples/001-no-tools/worker.ts +0 -79
  130. package/examples/002-slack-bridge/README.md +0 -134
  131. package/examples/002-slack-bridge/events.ts +0 -115
  132. package/examples/002-slack-bridge/reducer.ts +0 -216
  133. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  134. package/examples/002-slack-bridge/sinks.ts +0 -109
  135. package/examples/002-slack-bridge/worker.ts +0 -140
  136. package/examples/003-sandbox-lifecycle/README.md +0 -78
  137. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  138. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  139. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  140. package/examples/_shared/event-id.ts +0 -12
  141. package/examples/_shared/http.ts +0 -27
  142. package/examples/_shared/openai.ts +0 -33
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * 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 { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { 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 plus its derived durable transcript. */\nexport interface EDASessionSnapshot {\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly messages: ReadonlyArray<DurableTranscriptMessage>;\n}\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\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 eventsSlice: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventsSlice, EDASessionStoreError>;\n}\n\n/** Bounded committed durable replay slice for pull-based delivery. */\nexport interface EDASessionEventsSlice {\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 messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\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({ position: entry.position, event: entry.event }),\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 eventsSlice: (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 EDASessionEventsSlice;\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({ position: entry.position, event: entry.event }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventsSlice;\n }).pipe(\n Effect.withSpan(\"agent.events.slice\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.slice.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":";;;;;;;;;;;;;AAwDA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;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;IACpB,UAAU,yBAAyB,KAAK,OAAO;GACjD;EACF,CAAC;EAED,OAAO;GACL,gBAAgB;GAChB,gBAAgB,SAAS,KAAK,OAAO,KAAK,aAAa,SAAS,QAAQ,CAAC;GACzE,cAAc,aACZ,OAAO,IAAI,aAAa;IACtB,MAAM,OAAO,OAAO,QAAQ,eAAe;IAC3C,MAAM,cAAc,OAAO,aAAa,SAAS,GAAG;IAIpD,MAAM,SAAS,OAAO,MAAM,YAAY,QAAQ,EAAE,KAChD,OAAO,QAAQ,UAAU,MAAM,SAAS,OAAO,UAAU,GACzD,OAAO,KAAK,UACV,gBAAgB,KAAK;KAAE,UAAU,MAAM;KAAU,OAAO,MAAM;IAAM,CAAC,CACvE,GACA,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;IACA,MAAM,mBAAmB,OAAO,QAAQ,iBAAiB;IACzD,MAAM,eAAe,OAAO,OAAO,SAAS,MAAM,OAAO,iBAAiB,GAAG,QAC1E,UAAU,oBAAoB,OAAO,UAAU,CAClD;IACA,MAAM,kBAAkD,MAAM,KAC5D,uBAAuB;KAAC,GAAG;KA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AK,SAAS,MAAM,MAAM,SAAS;CAC/C,OAAO,QAAQ,IAAI,KAAK,SAAS,SAAS,MAAM,SAAS,SAAS;AACpE;AAEA,MAAM,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 { _ as SessionStateShape, a as SessionCommandCompleted, c as SessionCommandResult, d as SessionForkedCommand, f as SessionNoRunnableCommand, g as SessionStateError, h as SessionState, i as SessionCommandCancelled, l as SessionDrainProcessed, m as SessionRunInput, n as SessionCommandAdmissionConflict, o as SessionCommandFailed, p as SessionNoRunnableReason, r as SessionCommandAdmissionError, s as SessionCommandOutcome, t as EDASubmittable, u as SessionDrainResult, v as SessionStateSnapshotData } from "../session-state-CI1xeT6f.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-D7dqko7r.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 EDASessionStore, c as FindCommandAdmissionInput, i as EDAReducerCheckpoint, l as SaveReducerCheckpointInput, n as DurableAppendBatch, o as EDASessionStoreError, r as DurableAppendEntry, s as EDASessionStoreShape, t as CommittedDurableEvent, u as hasEDASessionStoreError } from "../session-store-BLg6UvZa.js";
2
+ export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError };
@@ -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 Ref from "effect/Ref";
10
+ import * as Cause from "effect/Cause";
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,OAAO,iBAAuC,EACtF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,EAAE,CAAC;;AAGH,MAAa,2BAA2B,UACtC,MAAM,QAAQ,MACX,WAAW,MAAM,aAAa,MAAM,KAAK,OAAO,iBAAiB,oBACpE;;;;;;;AAQF,MAAa,qBAAqB,OAAO,OAAO,EAC9C,OAAO,qBACT,CAAC;;;;;;;;AAUD,MAAa,qBAAqB,OAAO,OAAO,EAC9C,SAAS,OAAO,MAAM,kBAAkB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AI,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-B9WNvDtY.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-CO3YPS1p.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-BbmoI9uv.js";
2
2
  export { EDASink, EDASinkRegistry };
@@ -20,7 +20,7 @@
20
20
  *
21
21
  * Application-specific operations belong in the application catalog, not this reusable catalog.
22
22
  */
23
- declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.stream", "agent.inference", "agent.messages.list", "agent.run", "agent.session.snapshot", "agent.sink.drain", "agent.tool", "agent.turn"];
23
+ declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.slice", "agent.events.stream", "agent.inference", "agent.messages.list", "agent.run", "agent.session.snapshot", "agent.sink.drain", "agent.tool", "agent.turn"];
24
24
  /** Union of values admitted by the centralized EDA span-name catalog. */
25
25
  type SpanName = (typeof SpanNames)[number];
26
26
  //#endregion
@@ -27,6 +27,7 @@ const SpanNames = defineSpanNames([
27
27
  "agent.command.wait",
28
28
  "agent.compaction",
29
29
  "agent.events.follow",
30
+ "agent.events.slice",
30
31
  "agent.events.stream",
31
32
  "agent.inference",
32
33
  "agent.messages.list",
@@ -1 +1 @@
1
- {"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.messages.list\",\n \"agent.run\",\n \"agent.session.snapshot\",\n \"agent.sink.drain\",\n \"agent.tool\",\n \"agent.turn\",\n]);\n\n/** Union of values admitted by the centralized EDA span-name catalog. */\nexport type SpanName = (typeof SpanNames)[number];\n"],"mappings":";AAEA,MAAM,mBACJ,UACU;;;;;;;;;;;;;;;;;;;;;;AAuBZ,MAAa,YAAY,gBAAgB;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
1
+ {"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.slice\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.messages.list\",\n \"agent.run\",\n \"agent.session.snapshot\",\n \"agent.sink.drain\",\n \"agent.tool\",\n \"agent.turn\",\n]);\n\n/** Union of values admitted by the centralized EDA span-name catalog. */\nexport type SpanName = (typeof SpanNames)[number];\n"],"mappings":";AAEA,MAAM,mBACJ,UACU;;;;;;;;;;;;;;;;;;;;;;AAuBZ,MAAa,YAAY,gBAAgB;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
@@ -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-B8H1P6Pu.js";
2
2
  export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
@@ -0,0 +1,90 @@
1
+ import { m as SequenceNumber } from "../core-CYT6DBaS.js";
2
+ import { L as PositionedEvent } from "../events-Bb9-Cu-7.js";
3
+ import { EDAWebSocketAckFrame, EDAWebSocketFlowControl, EDAWebSocketHelloFrame, EDAWebSocketServerFrame, FrameId, SubscriberId } from "../host/websocket-protocol.js";
4
+ import * as Schema from "effect/Schema";
5
+
6
+ //#region src/services/websocket-delivery.d.ts
7
+ /** Slow subscriber reasons that intentionally close only the lagging socket. */
8
+ declare const SubscriberLagReason: Schema.Literals<readonly ["buffer-overflow", "ack-timeout"]>;
9
+ type SubscriberLagReason = typeof SubscriberLagReason.Type;
10
+ /** One sent-but-unacknowledged events frame. */
11
+ interface InFlightFrame {
12
+ readonly frameId: FrameId;
13
+ readonly durableThroughSeq: SequenceNumber;
14
+ readonly sentAtMs: number;
15
+ }
16
+ /**
17
+ * In-memory delivery state for one accepted event WebSocket.
18
+ *
19
+ * This state is deliberately disposable: hibernation-capable hosts persist
20
+ * only the acknowledged durable cursor in the socket attachment and rebuild
21
+ * a cold state after isolate eviction. Nothing here owns a fiber, a timer,
22
+ * or a stream; all progress is driven by explicit host calls.
23
+ */
24
+ interface EDAWebSocketDeliveryState {
25
+ readonly subscriberId: SubscriberId;
26
+ readonly policy: EDAWebSocketFlowControl;
27
+ /**
28
+ * True when this state was rebuilt from a persisted attachment after the
29
+ * in-memory frame bookkeeping was lost. Frame-id validation is relaxed for
30
+ * the remainder of the connection because pre-eviction frame ids are
31
+ * unknowable; durable cursors stay strictly monotonic either way.
32
+ */
33
+ readonly coldRestored: boolean;
34
+ readonly lastAckedSeq: SequenceNumber;
35
+ readonly lastAckedFrameId: number;
36
+ readonly lastSentFrameId: number;
37
+ readonly nextFrameId: number;
38
+ readonly sentDurableThroughSeq: SequenceNumber;
39
+ readonly inFlight: ReadonlyArray<InFlightFrame>;
40
+ readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;
41
+ }
42
+ /** Close instruction for the host WebSocket boundary. */
43
+ interface DeliveryClose {
44
+ readonly code: number;
45
+ readonly reason: string;
46
+ }
47
+ /** Result of one pure delivery transition. */
48
+ interface EDAWebSocketDeliveryResult {
49
+ readonly state: EDAWebSocketDeliveryState;
50
+ /** Frames to send in order, including any final lagged/error frame before `close`. */
51
+ readonly frames: ReadonlyArray<EDAWebSocketServerFrame>;
52
+ /** When set, persist this acknowledged durable cursor to the socket attachment. */
53
+ readonly persistSeq?: SequenceNumber;
54
+ /** When set, send `frames` then close the socket and drop its state. */
55
+ readonly close?: DeliveryClose;
56
+ /** When set, the host should read a durable slice after this seq and call `onDurableEvents`. */
57
+ readonly wantsCatchUpAfterSeq?: SequenceNumber;
58
+ }
59
+ /** Inputs for one fresh or cold-restored delivery state. */
60
+ interface MakeDeliveryStateInput {
61
+ readonly subscriberId: SubscriberId;
62
+ readonly resumeSeq: SequenceNumber;
63
+ readonly policy: EDAWebSocketFlowControl;
64
+ readonly coldRestored?: boolean;
65
+ }
66
+ /** Build the delivery state for a new connection or a post-eviction restore. */
67
+ declare const makeWebSocketDeliveryState: (input: MakeDeliveryStateInput) => EDAWebSocketDeliveryState;
68
+ /** First frame for a freshly accepted connection. Cold restores never re-send hello. */
69
+ declare const deliveryHelloFrame: (state: EDAWebSocketDeliveryState) => EDAWebSocketHelloFrame;
70
+ /**
71
+ * Deliver committed durable events read from the store.
72
+ *
73
+ * The store is the only buffer for durable events: frames are emitted while
74
+ * the ACK window has room and the remainder is requested again via
75
+ * `wantsCatchUpAfterSeq` once ACKs reopen the window.
76
+ */
77
+ declare const onDurableEvents: (state: EDAWebSocketDeliveryState, events: ReadonlyArray<PositionedEvent>, head: SequenceNumber, nowMs: number) => EDAWebSocketDeliveryResult;
78
+ /**
79
+ * Deliver one live ephemeral event.
80
+ *
81
+ * Ephemeral events have no durable backing, so a bounded in-memory buffer
82
+ * holds them while the ACK window is full; overflow lag-closes only this
83
+ * subscriber, mirroring the previous streaming behavior.
84
+ */
85
+ declare const onEphemeralEvent: (state: EDAWebSocketDeliveryState, event: PositionedEvent, nowMs: number) => EDAWebSocketDeliveryResult;
86
+ /** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */
87
+ declare const onClientAck: (state: EDAWebSocketDeliveryState, ack: EDAWebSocketAckFrame, nowMs: number) => EDAWebSocketDeliveryResult;
88
+ //#endregion
89
+ export { DeliveryClose, EDAWebSocketDeliveryResult, EDAWebSocketDeliveryState, InFlightFrame, MakeDeliveryStateInput, SubscriberLagReason, deliveryHelloFrame, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent };
90
+ //# sourceMappingURL=websocket-delivery.d.ts.map