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
@@ -1,6 +1,7 @@
1
- import { _ as SummaryId, h as SessionId, m as SequenceNumber, n as CommandId } from "./core-Hv3cFydL.js";
1
+ import { _ as SummaryId, h as SessionId, m as SequenceNumber, n as CommandId } from "./core-CYT6DBaS.js";
2
2
  import { n as CommandIdempotencyKey } from "./commands-Ce1ec6kH.js";
3
3
  import { D as DurableEventEnvelope } from "./events-Bb9-Cu-7.js";
4
+ import { r as CompactionSummaryArtifact } from "./context-projection-B4DWOZgi.js";
4
5
  import * as Context from "effect/Context";
5
6
  import * as Effect from "effect/Effect";
6
7
  import * as Layer from "effect/Layer";
@@ -8,89 +9,6 @@ import * as Schema from "effect/Schema";
8
9
  import * as Stream from "effect/Stream";
9
10
  import * as Cause from "effect/Cause";
10
11
 
11
- //#region src/domain/context-projection.d.ts
12
- /** Stable identifier for the compaction policy that selected a summary plan. */
13
- declare const CompactionPolicyId: Schema.brand<Schema.NonEmptyString, "CompactionPolicyId">;
14
- type CompactionPolicyId = typeof CompactionPolicyId.Type;
15
- /** Stable identifier for the executor that produced a summary artifact. */
16
- declare const CompactionExecutorId: Schema.brand<Schema.NonEmptyString, "CompactionExecutorId">;
17
- type CompactionExecutorId = typeof CompactionExecutorId.Type;
18
- /** Authoritative cumulative model-context summary written with `SummaryCreated`. */
19
- declare const CompactionSummaryArtifact: Schema.Struct<{
20
- readonly compactionId: Schema.brand<Schema.String, "CompactionId">;
21
- readonly summaryId: Schema.brand<Schema.String, "SummaryId">;
22
- readonly previousSummaryId: Schema.optionalKey<Schema.brand<Schema.String, "SummaryId">>;
23
- readonly sourceFromSeq: Schema.brand<Schema.Int, "SequenceNumber">;
24
- readonly sourceToSeq: Schema.brand<Schema.Int, "SequenceNumber">;
25
- readonly retainedFromContextSeq: Schema.brand<Schema.Int, "SequenceNumber">;
26
- readonly text: Schema.NonEmptyString;
27
- readonly promptMessage: Schema.Struct<{
28
- readonly role: Schema.Literal<"user">;
29
- readonly content: Schema.Union<readonly [Schema.decodeTo<Schema.NonEmptyArray<Schema.toType<Schema.Struct<{
30
- readonly type: Schema.Literal<"text">;
31
- readonly text: Schema.String;
32
- readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
33
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
34
- }>>>, Schema.String, never, never>, Schema.$Array<Schema.Union<readonly [Schema.Struct<{
35
- readonly type: Schema.Literal<"text">;
36
- readonly text: Schema.String;
37
- readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
38
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
39
- }>, Schema.Struct<{
40
- readonly type: Schema.Literal<"file">;
41
- readonly mediaType: Schema.String;
42
- readonly fileName: Schema.optional<Schema.String>;
43
- readonly data: Schema.Union<readonly [Schema.String, Schema.Uint8Array, Schema.URL]>;
44
- readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
45
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
46
- }>]>>]>;
47
- readonly "~effect/ai/Prompt/Message": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Message">>;
48
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
49
- }>;
50
- readonly policyId: Schema.brand<Schema.NonEmptyString, "CompactionPolicyId">;
51
- readonly executorId: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CompactionExecutorId">>;
52
- }>;
53
- type CompactionSummaryArtifact = typeof CompactionSummaryArtifact.Type;
54
- /** Current durable context cursor projected from framework reducer state and summary rows. */
55
- declare const ContextProjection: Schema.Struct<{
56
- readonly contextVersion: Schema.brand<Schema.Int, "ContextVersion">;
57
- readonly currentSummary: Schema.optionalKey<Schema.Struct<{
58
- readonly compactionId: Schema.brand<Schema.String, "CompactionId">;
59
- readonly summaryId: Schema.brand<Schema.String, "SummaryId">;
60
- readonly previousSummaryId: Schema.optionalKey<Schema.brand<Schema.String, "SummaryId">>;
61
- readonly sourceFromSeq: Schema.brand<Schema.Int, "SequenceNumber">;
62
- readonly sourceToSeq: Schema.brand<Schema.Int, "SequenceNumber">;
63
- readonly retainedFromContextSeq: Schema.brand<Schema.Int, "SequenceNumber">;
64
- readonly text: Schema.NonEmptyString;
65
- readonly promptMessage: Schema.Struct<{
66
- readonly role: Schema.Literal<"user">;
67
- readonly content: Schema.Union<readonly [Schema.decodeTo<Schema.NonEmptyArray<Schema.toType<Schema.Struct<{
68
- readonly type: Schema.Literal<"text">;
69
- readonly text: Schema.String;
70
- readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
71
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
72
- }>>>, Schema.String, never, never>, Schema.$Array<Schema.Union<readonly [Schema.Struct<{
73
- readonly type: Schema.Literal<"text">;
74
- readonly text: Schema.String;
75
- readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
76
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
77
- }>, Schema.Struct<{
78
- readonly type: Schema.Literal<"file">;
79
- readonly mediaType: Schema.String;
80
- readonly fileName: Schema.optional<Schema.String>;
81
- readonly data: Schema.Union<readonly [Schema.String, Schema.Uint8Array, Schema.URL]>;
82
- readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
83
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
84
- }>]>>]>;
85
- readonly "~effect/ai/Prompt/Message": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Message">>;
86
- readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
87
- }>;
88
- readonly policyId: Schema.brand<Schema.NonEmptyString, "CompactionPolicyId">;
89
- readonly executorId: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CompactionExecutorId">>;
90
- }>>;
91
- }>;
92
- type ContextProjection = typeof ContextProjection.Type;
93
- //#endregion
94
12
  //#region src/services/session-store.d.ts
95
13
  /** A durable event after the store has assigned its replay position. */
96
14
  declare const CommittedDurableEvent: Schema.Struct<{
@@ -135,19 +53,12 @@ declare const EDASessionStoreError_base: Schema.Class<EDASessionStoreError, Sche
135
53
  * Store-level failure surfaced by durable append, replay, and hydration APIs.
136
54
  *
137
55
  * The error intentionally stays storage-semantic rather than SQL-specific so
138
- * framework services can treat DO SQLite, in-memory tests, and future adapters
56
+ * framework services can treat SQL-backed hosts, in-memory tests, and future adapters
139
57
  * as the same durability boundary.
140
58
  */
141
59
  declare class EDASessionStoreError extends EDASessionStoreError_base {}
142
60
  /** True when a Cause contains an escaped durable-store failure. */
143
61
  declare const hasEDASessionStoreError: (cause: Cause.Cause<unknown>) => boolean;
144
- /**
145
- * Initial hard cap for one serialized JSON value stored in DO SQLite.
146
- *
147
- * Cloudflare's SQL row/string limit is 2MB; failing around 1.5MB leaves margin
148
- * for encoding overhead and makes the future blob/chunk decision explicit.
149
- */
150
- declare const durableObjectSerializedJsonHardCapBytes = 1500000;
151
62
  /**
152
63
  * One logical event to persist in the durable session log.
153
64
  *
@@ -291,5 +202,5 @@ declare class EDASessionStore extends EDASessionStore_base {
291
202
  static readonly InMemorySeeded: (sessionId: SessionId, events: ReadonlyArray<DurableEventEnvelope>) => Layer.Layer<EDASessionStore, never, never>;
292
203
  }
293
204
  //#endregion
294
- export { EDASessionStore as a, FindCommandAdmissionInput as c, hasEDASessionStoreError as d, CompactionExecutorId as f, EDAReducerCheckpoint as i, SaveReducerCheckpointInput as l, ContextProjection as m, DurableAppendBatch as n, EDASessionStoreError as o, CompactionPolicyId as p, DurableAppendEntry as r, EDASessionStoreShape as s, CommittedDurableEvent as t, durableObjectSerializedJsonHardCapBytes as u };
295
- //# sourceMappingURL=session-store-D2Ore1QC.d.ts.map
205
+ export { EDASessionStore as a, FindCommandAdmissionInput as c, EDAReducerCheckpoint as i, SaveReducerCheckpointInput as l, DurableAppendBatch as n, EDASessionStoreError as o, DurableAppendEntry as r, EDASessionStoreShape as s, CommittedDurableEvent as t, hasEDASessionStoreError as u };
206
+ //# sourceMappingURL=session-store-BLg6UvZa.d.ts.map
@@ -0,0 +1,40 @@
1
+ import { m as SequenceNumber } from "./core-CYT6DBaS.js";
2
+ import { o as EDASessionStoreError } from "./session-store-BLg6UvZa.js";
3
+ import * as Context from "effect/Context";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Layer from "effect/Layer";
6
+ import * as Schema from "effect/Schema";
7
+
8
+ //#region src/services/sink-checkpoint-store.d.ts
9
+ /** Stable sink name used as the durable checkpoint key. */
10
+ declare const EDASinkName: Schema.brand<Schema.NonEmptyString, "EDASinkName">;
11
+ type EDASinkName = typeof EDASinkName.Type;
12
+ /** Persisted cursor and sink-owned payload for one registered sink. */
13
+ interface StoredSinkCheckpoint {
14
+ readonly afterSeq: SequenceNumber;
15
+ readonly payload: unknown | undefined;
16
+ }
17
+ /** Durable checkpoint persistence port for at-least-once sink runners. */
18
+ interface SinkCheckpointStoreShape {
19
+ /** Read the latest committed cursor and sink-owned payload. */
20
+ readonly load: (sinkName: EDASinkName) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;
21
+ /** Save sink-owned state without advancing the durable cursor. */
22
+ readonly saveState: (sinkName: EDASinkName, payload: unknown) => Effect.Effect<void, EDASessionStoreError>;
23
+ /** Atomically commit the processed cursor together with current sink-owned state. */
24
+ readonly commit: (sinkName: EDASinkName, afterSeq: SequenceNumber, payload: unknown | undefined) => Effect.Effect<void, EDASessionStoreError>;
25
+ }
26
+ declare const SinkCheckpointStore_base: Context.ServiceClass<SinkCheckpointStore, "@effect-durable-agent/SinkCheckpointStore", SinkCheckpointStoreShape>;
27
+ /**
28
+ * Semantic checkpoint store for registered EDA sinks.
29
+ *
30
+ * Checkpoints are intentionally exposed as load/save/commit operations rather
31
+ * than SQL. Sink side effects happen outside event append transactions, and the
32
+ * cursor advances only after the sink finishes its own external work.
33
+ */
34
+ declare class SinkCheckpointStore extends SinkCheckpointStore_base {
35
+ /** In-memory checkpoint implementation for store/runtime tests. */
36
+ static readonly InMemory: Layer.Layer<SinkCheckpointStore, never, never>;
37
+ }
38
+ //#endregion
39
+ export { StoredSinkCheckpoint as i, SinkCheckpointStore as n, SinkCheckpointStoreShape as r, EDASinkName as t };
40
+ //# sourceMappingURL=sink-checkpoint-store-B9WNvDtY.d.ts.map
@@ -1,22 +1,22 @@
1
1
  import { SequenceNumber, durablePosition } from "./types/core.js";
2
- import { Jn as turnFailedEventType, Xn as turnStoppedEventType, Yn as turnStartedEventType, qn as turnCompletedEventType } from "./durable-C3Rz7kg3.js";
3
- import { f as reduceCommittedEvents, o as foldReducedState } from "./reduced-state-C4nVVzz9.js";
4
- import { a as EDASessionStoreError, i as EDASessionStore, t as CommittedDurableEvent } from "./session-store-pYxQW9qh.js";
2
+ import { $n as turnStoppedEventType, Qn as turnStartedEventType, Xn as turnCompletedEventType, Zn as turnFailedEventType } from "./durable-DsV9PxZC.js";
3
+ import { f as reduceCommittedEvents, o as foldReducedState } from "./reduced-state-TMi7ISla.js";
4
+ import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from "./services/session-store.js";
5
5
  import { IdGenerator } from "./services/id-generator.js";
6
- import { n as EventFactory, r as SessionContext, t as EDAKeepAlive } from "./keep-alive-p8dIcSVy.js";
6
+ import { n as SessionContext, t as EventFactory } from "./event-factory-tcpLgdMN.js";
7
7
  import { annotateEdaSpan } from "./services/tracing.js";
8
+ import { EDAKeepAlive } from "./services/keep-alive.js";
8
9
  import { EDAReducerRegistry } from "./services/reducer-registry.js";
10
+ import { EDASinkName, SinkCheckpointStore } from "./services/sink-checkpoint-store.js";
9
11
  import * as Context from "effect/Context";
10
12
  import * as Effect from "effect/Effect";
11
13
  import * as Layer from "effect/Layer";
12
14
  import * as Schema from "effect/Schema";
13
15
  import * as Stream from "effect/Stream";
14
- import * as Cause from "effect/Cause";
16
+ import * as PubSub from "effect/PubSub";
15
17
  import * as Ref from "effect/Ref";
18
+ import * as Cause from "effect/Cause";
16
19
  import * as Scope from "effect/Scope";
17
- import * as PubSub from "effect/PubSub";
18
- import * as Duration from "effect/Duration";
19
- import * as Schedule from "effect/Schedule";
20
20
  import * as SynchronizedRef from "effect/SynchronizedRef";
21
21
  //#region src/services/live-event-bus.ts
22
22
  /** Conservative raw-delta cap for one open turn's live-only reconnect replay. */
@@ -27,15 +27,17 @@ var LiveEventBus = class LiveEventBus extends Context.Service()("@effect-durable
27
27
  return makeLiveBus(yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown), yield* Ref.make({
28
28
  events: [],
29
29
  overflowed: false
30
- }));
30
+ }), yield* Ref.make([]));
31
31
  }));
32
32
  };
33
- const makeLiveBus = (pubsub, activeTurnReplay) => ({
34
- publish: (event) => updateActiveTurnReplay(activeTurnReplay, event).pipe(Effect.andThen(PubSub.publish(pubsub, event))),
33
+ const makeLiveBus = (pubsub, activeTurnReplay, listeners) => ({
34
+ publish: (event) => updateActiveTurnReplay(activeTurnReplay, event).pipe(Effect.andThen(notifyDeliveryListeners(listeners, event)), Effect.andThen(PubSub.publish(pubsub, event))),
35
35
  subscribeQueue: () => PubSub.subscribe(pubsub),
36
36
  subscribe: () => Effect.map(PubSub.subscribe(pubsub), (subscription) => Stream.fromEffectRepeat(PubSub.take(subscription))),
37
- activeTurnReplay: () => Ref.get(activeTurnReplay)
37
+ activeTurnReplay: () => Ref.get(activeTurnReplay),
38
+ registerDeliveryListener: (listener) => Ref.update(listeners, (current) => [...current, listener])
38
39
  });
40
+ const notifyDeliveryListeners = (listeners, event) => Ref.get(listeners).pipe(Effect.flatMap((current) => Effect.forEach(current, (listener) => listener(event).pipe(Effect.catchCause((cause) => Effect.logWarning("EDA live delivery listener defected", cause))), { discard: true })));
39
41
  const updateActiveTurnReplay = (ref, event) => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));
40
42
  const nextActiveTurnReplay = (state, event) => {
41
43
  if (event.event.type === turnStartedEventType) return {
@@ -63,46 +65,6 @@ const nextActiveTurnReplay = (state, event) => {
63
65
  };
64
66
  };
65
67
  //#endregion
66
- //#region src/services/sink-checkpoint-store.ts
67
- /** Stable sink name used as the durable checkpoint key. */
68
- const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand("EDASinkName"));
69
- /**
70
- * Semantic checkpoint store for registered EDA sinks.
71
- *
72
- * Checkpoints are intentionally exposed as load/save/commit operations rather
73
- * than SQL. Sink side effects happen outside event append transactions, and the
74
- * cursor advances only after the sink finishes its own external work.
75
- */
76
- var SinkCheckpointStore = class SinkCheckpointStore extends Context.Service()("@effect-durable-agent/SinkCheckpointStore") {
77
- /** In-memory checkpoint implementation for store/runtime tests. */
78
- static InMemory = Layer.effect(SinkCheckpointStore, Effect.gen(function* () {
79
- return makeInMemorySinkCheckpointStore(yield* Ref.make(/* @__PURE__ */ new Map()));
80
- }));
81
- };
82
- /** Build a ref-backed checkpoint map with the same public semantics as host adapters. */
83
- const makeInMemorySinkCheckpointStore = (checkpoints) => ({
84
- load: (sinkName) => Ref.get(checkpoints).pipe(Effect.map((map) => map.get(sinkName) ?? {
85
- afterSeq: SequenceNumber.make(0),
86
- payload: void 0
87
- })),
88
- saveState: (sinkName, payload) => Ref.update(checkpoints, (map) => {
89
- const next = new Map(map);
90
- next.set(sinkName, {
91
- afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),
92
- payload
93
- });
94
- return next;
95
- }),
96
- commit: (sinkName, afterSeq, payload) => Ref.update(checkpoints, (map) => {
97
- const next = new Map(map);
98
- next.set(sinkName, {
99
- afterSeq,
100
- payload
101
- });
102
- return next;
103
- })
104
- });
105
- //#endregion
106
68
  //#region src/services/sink-registry.ts
107
69
  /** Convenience constructor preserving a sink's literal name/type information. */
108
70
  const EDASink = { make: (sink) => sink };
@@ -117,9 +79,7 @@ var EDASinkRegistry = class EDASinkRegistry extends Context.Service()("@effect-d
117
79
  static Live = (sinks) => Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));
118
80
  };
119
81
  const defaultBatchSize = 100;
120
- const maxDurableSinkRetryDelay = Duration.seconds(5);
121
82
  const sinkCheckpointFormatVersion = 1;
122
- const durableSinkRetrySchedule = Schedule.exponential("100 millis").pipe(Schedule.jittered, Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, maxDurableSinkRetryDelay))));
123
83
  const makeSinkRegistry = (sinks) => Effect.gen(function* () {
124
84
  const session = yield* SessionContext;
125
85
  const store = yield* EDASessionStore;
@@ -164,14 +124,16 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
164
124
  const eventsForSink = durable === void 0 ? [] : filterInterested(fresh, durable.interests);
165
125
  if (durable !== void 0 && eventsForSink.length > 0) yield* Effect.gen(function* () {
166
126
  const staged = [];
167
- yield* durable.process({
127
+ if ((yield* durable.process({
168
128
  allEvents: fresh,
169
129
  events: eventsForSink,
170
130
  stateAfter: nextReduced,
171
131
  reducerStates: nextReducerStates,
172
132
  throughSeq
173
- }, baseContext(staged, input.publishEphemeral, input.scope, checkpoint));
174
- if (staged.length > 0) {
133
+ }, baseContext(staged, input.publishEphemeral, input.scope, checkpoint)).pipe(Effect.as(true), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logError("EDA durable sink violated its infallible contract", {
134
+ cause: Cause.pretty(cause),
135
+ sink: sink.name
136
+ }).pipe(Effect.as(false))))) && staged.length > 0) {
175
137
  yield* annotateEdaSpan({ "eda.sink.staged_events": staged.length });
176
138
  yield* input.appendDurableBatch(staged);
177
139
  }
@@ -189,17 +151,14 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
189
151
  reducerStates: nextReducerStates
190
152
  });
191
153
  });
192
- const processDurableBatchWithRetry = (events) => keepAlive.withActiveWork(`sink:${sink.name}`, processDurableBatch(events).pipe(Effect.tapError((error) => Effect.logWarning("EDA sink durable projection failed; retrying", {
193
- error: formatSinkError(error),
194
- sink: sink.name
195
- })), Effect.retry(durableSinkRetrySchedule)));
154
+ const processDurableBatchWithKeepAlive = (events) => keepAlive.withActiveWork(`sink:${sink.name}`, processDurableBatch(events));
196
155
  const drainDurablesThrough = (targetHead) => Effect.gen(function* () {
197
156
  while (true) {
198
157
  const current = yield* Ref.get(state);
199
158
  if (current.cursor >= targetHead) return;
200
159
  const allEvents = yield* readCursorBatchThrough(store, current.cursor, targetHead, sink.durable?.batchSize);
201
160
  if (allEvents.length === 0) return;
202
- yield* processDurableBatchWithRetry(allEvents);
161
+ yield* processDurableBatchWithKeepAlive(allEvents);
203
162
  }
204
163
  });
205
164
  const processLiveDurable = (event) => Effect.gen(function* () {
@@ -215,7 +174,7 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
215
174
  });
216
175
  return;
217
176
  }
218
- yield* processDurableBatchWithRetry([committedDurableFromPositioned(event)]);
177
+ yield* processDurableBatchWithKeepAlive([committedDurableFromPositioned(event)]);
219
178
  });
220
179
  const processLiveEphemeral = (event) => Effect.gen(function* () {
221
180
  const before = yield* Ref.get(state);
@@ -232,7 +191,7 @@ const makeSinkRegistry = (sinks) => Effect.gen(function* () {
232
191
  const processLiveEvent = (event) => event.event.durability === "durable" ? processLiveDurable(event) : processLiveEphemeral(event);
233
192
  yield* Effect.gen(function* () {
234
193
  yield* drainDurablesThrough(input.initialHead);
235
- yield* Effect.forever(Effect.gen(function* () {
194
+ return yield* Effect.forever(Effect.gen(function* () {
236
195
  yield* processLiveEvent(yield* PubSub.take(live));
237
196
  }));
238
197
  }).pipe(Effect.catchCause((cause) => Effect.logError("EDA sink runner failed", {
@@ -302,11 +261,7 @@ const committedDurableFromPositioned = (event) => CommittedDurableEvent.make({
302
261
  });
303
262
  const filterInterested = (events, interests) => events.filter((event) => matchesInterest(event.event.type, interests));
304
263
  const matchesInterest = (type, interests) => interests === void 0 || interests.some((interest) => interest === type);
305
- const formatSinkError = (error) => {
306
- if (Cause.isUnknownError(error)) return `${error.message ?? error._tag}: ${formatSinkError(error.cause)}`;
307
- return error instanceof Error ? error.message : String(error);
308
- };
309
264
  //#endregion
310
- export { LiveEventBus as i, EDASinkRegistry as n, SinkCheckpointStore as r, EDASink as t };
265
+ export { EDASinkRegistry as n, LiveEventBus as r, EDASink as t };
311
266
 
312
- //# sourceMappingURL=sink-registry-CFC6xjsN.js.map
267
+ //# sourceMappingURL=sink-registry-BbmoI9uv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sink-registry-BbmoI9uv.js","names":[],"sources":["../src/services/live-event-bus.ts","../src/services/sink-registry.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 * as Ref from \"effect/Ref\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { TurnId } from \"../types/core\";\nimport {\n PositionedEvent,\n turnCompletedEventType,\n turnFailedEventType,\n turnStartedEventType,\n turnStoppedEventType,\n} from \"../types/events\";\n\n/** Conservative raw-delta cap for one open turn's live-only reconnect replay. */\nexport const activeTurnEphemeralReplayCapacity = 4_096;\n\n/** Live-only replay buffer for the currently open turn. */\nexport interface ActiveTurnEphemeralReplay {\n readonly turnId?: TurnId;\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly overflowed: boolean;\n}\n\n/**\n * Push-delivery listener invoked inline as each event is published.\n *\n * Listeners let hibernation-capable hosts fan events out to accepted\n * WebSockets during the already-active turn instead of parking a resident\n * subscriber fiber on the pub/sub. Listeners must not fail; defects are\n * logged and never interrupt the publishing turn.\n */\nexport type LiveDeliveryListener = (event: PositionedEvent) => Effect.Effect<void>;\n\n/** In-memory live fanout plus active-turn replay source for reconnect streams. */\nexport interface LiveEventBusShape {\n readonly publish: (event: PositionedEvent) => Effect.Effect<boolean>;\n readonly subscribe: () => Effect.Effect<Stream.Stream<PositionedEvent>, never, Scope.Scope>;\n readonly subscribeQueue: () => Effect.Effect<\n PubSub.Subscription<PositionedEvent>,\n never,\n Scope.Scope\n >;\n /** Snapshot raw live-only events retained for the currently open turn. */\n readonly activeTurnReplay: () => Effect.Effect<ActiveTurnEphemeralReplay>;\n /** Register one push-delivery listener invoked inline on every published event. */\n readonly registerDeliveryListener: (listener: LiveDeliveryListener) => Effect.Effect<void>;\n}\n\n/** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */\nexport class LiveEventBus extends Context.Service<LiveEventBus, LiveEventBusShape>()(\n \"@effect-durable-agent/LiveEventBus\",\n) {\n static readonly Live = Layer.effect(\n LiveEventBus,\n Effect.gen(function* () {\n const pubsub = yield* Effect.acquireRelease(\n PubSub.unbounded<PositionedEvent>(),\n PubSub.shutdown,\n );\n const activeTurnReplay = yield* Ref.make<ActiveTurnEphemeralReplay>({\n events: [],\n overflowed: false,\n });\n const listeners = yield* Ref.make<ReadonlyArray<LiveDeliveryListener>>([]);\n return makeLiveBus(pubsub, activeTurnReplay, listeners);\n }),\n );\n}\n\nconst makeLiveBus = (\n pubsub: PubSub.PubSub<PositionedEvent>,\n activeTurnReplay: Ref.Ref<ActiveTurnEphemeralReplay>,\n listeners: Ref.Ref<ReadonlyArray<LiveDeliveryListener>>,\n): LiveEventBusShape => ({\n publish: (event) =>\n updateActiveTurnReplay(activeTurnReplay, event).pipe(\n Effect.andThen(notifyDeliveryListeners(listeners, event)),\n Effect.andThen(PubSub.publish(pubsub, event)),\n ),\n subscribeQueue: () => PubSub.subscribe(pubsub),\n subscribe: () =>\n Effect.map(PubSub.subscribe(pubsub), (subscription) =>\n Stream.fromEffectRepeat(PubSub.take(subscription)),\n ),\n activeTurnReplay: () => Ref.get(activeTurnReplay),\n registerDeliveryListener: (listener) =>\n Ref.update(listeners, (current) => [...current, listener]),\n});\n\nconst notifyDeliveryListeners = (\n listeners: Ref.Ref<ReadonlyArray<LiveDeliveryListener>>,\n event: PositionedEvent,\n): Effect.Effect<void> =>\n Ref.get(listeners).pipe(\n Effect.flatMap((current) =>\n Effect.forEach(\n current,\n (listener) =>\n listener(event).pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(\"EDA live delivery listener defected\", cause),\n ),\n ),\n { discard: true },\n ),\n ),\n );\n\nconst updateActiveTurnReplay = (\n ref: Ref.Ref<ActiveTurnEphemeralReplay>,\n event: PositionedEvent,\n): Effect.Effect<void> => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));\n\nconst nextActiveTurnReplay = (\n state: ActiveTurnEphemeralReplay,\n event: PositionedEvent,\n): ActiveTurnEphemeralReplay => {\n if (event.event.type === turnStartedEventType) {\n return {\n turnId: (event.event.payload as { readonly turnId: TurnId }).turnId,\n events: [],\n overflowed: false,\n };\n }\n\n if (\n event.event.type === turnCompletedEventType ||\n event.event.type === turnFailedEventType ||\n event.event.type === turnStoppedEventType\n ) {\n const turnId = (event.event.payload as { readonly turnId?: TurnId }).turnId;\n return turnId === undefined || state.turnId === undefined || turnId === state.turnId\n ? { events: [], overflowed: false }\n : state;\n }\n\n if (event.event.durability !== \"ephemeral\" || state.turnId === undefined) {\n return state;\n }\n\n const events = [...state.events, event];\n if (events.length <= activeTurnEphemeralReplayCapacity) {\n return { ...state, events };\n }\n return {\n ...state,\n events: events.slice(events.length - activeTurnEphemeralReplayCapacity),\n overflowed: true,\n };\n};\n","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 PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport {\n foldReducedState,\n reduceCommittedEvents,\n type ReducedState,\n} from \"../domain/reduced-state\";\nimport { EDAReducerRegistry, type EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { EventId, SessionId, SequenceNumber, durablePosition } from \"../types/core\";\nimport type {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n EventType,\n PositionedEvent,\n} from \"../types/events\";\nimport type { EDASessionStoreShape } from \"./session-store\";\nimport { CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport type { EventFactoryShape } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionContext } from \"./session-context\";\nimport {\n EDASinkName,\n SinkCheckpointStore,\n type SinkCheckpointStoreShape,\n type StoredSinkCheckpoint,\n} from \"./sink-checkpoint-store\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Cursor-window input delivered to one durable sink drain. */\nexport interface EDASinkDurableBatch {\n /** All durable events replayed for this cursor window, including uninterested events. */\n readonly allEvents: ReadonlyArray<CommittedDurableEvent>;\n /** Events matching the sink's durable interests. */\n readonly events: ReadonlyArray<CommittedDurableEvent>;\n /** Authoritative reduced state folded exactly through `throughSeq`. */\n readonly stateAfter: ReducedState;\n /** App-specific durable reducer states folded exactly through `throughSeq`. */\n readonly reducerStates: EDAReducerStateSnapshot;\n /** Durable sequence through which the sink may advance after success. */\n readonly throughSeq: SequenceNumber;\n}\n\n/** Typed, sink-owned durable state stored independently from cursor advancement. */\nexport interface EDASinkCheckpoint {\n /** Decode current durable state, or return `initial` for a new or legacy cursor row. */\n readonly get: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n initial: State,\n ) => Effect.Effect<State, EDASessionStoreError>;\n /** Validate, encode, and durably save state without advancing the sink cursor. */\n readonly save: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/** Capabilities exposed to sink processors without granting raw store or bus access. */\nexport interface EDASinkContext {\n readonly sessionId: SessionId;\n /** Sink-owned checkpoint state, serialized with cursor commits and background writes. */\n readonly checkpoint: EDASinkCheckpoint;\n /** Build a framework durable event if the sink needs to emit one. */\n readonly events: EventFactoryShape;\n /** Mint an app durable event id for staged custom events. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Publish a best-effort live-only event. */\n readonly emitEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n /** Stage durable events; the runner commits them after the sink succeeds. */\n readonly stageDurable: (event: DurableEventEnvelope) => Effect.Effect<void>;\n /** Fork background sink work into the session scope. */\n readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;\n}\n\n/** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */\nexport interface EDADurableSinkDefinition {\n readonly interests?: ReadonlyArray<EventType | string>;\n readonly batchSize?: number;\n readonly process: (batch: EDASinkDurableBatch, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/** Best-effort live-only sink definition. */\nexport interface EDAEphemeralSinkDefinition {\n readonly interests?: ReadonlyArray<EventType | string>;\n readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/**\n * Named app integration hook with optional durable and ephemeral filters.\n *\n * Every sink runs on one serialized position-ordered lane. Sinks own retry and\n * terminal failure handling, so callbacks must have an infallible typed error\n * channel. An unexpected defect is logged and skipped before the durable checkpoint\n * advances. Ephemeral callbacks are best-effort and are only processed after the\n * durable prefix at their anchor sequence has been projected.\n */\nexport interface EDASink {\n readonly name: string;\n readonly durable?: EDADurableSinkDefinition;\n readonly ephemeral?: EDAEphemeralSinkDefinition;\n}\n\n/** Convenience constructor preserving a sink's literal name/type information. */\nexport const EDASink = {\n make: <const Sink extends EDASink>(sink: Sink): Sink => sink,\n};\n\n/** Session-owned capabilities needed to start all registered sink runners. */\nexport interface EDASinkRunnerStartInput {\n readonly appendDurableBatch: (\n events: ReadonlyArray<DurableEventEnvelope>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n readonly initialHead: SequenceNumber;\n readonly publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n readonly scope: Scope.Scope;\n}\n\n/** Registry service coordinating durable checkpoints and live sink delivery. */\nexport interface EDASinkRegistryShape {\n readonly sinks: ReadonlyArray<EDASink>;\n /** Start long-lived sink runners. Safe to call once during session-state acquisition. */\n readonly startSinkRunners: (\n input: EDASinkRunnerStartInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Coalesced non-blocking nudge that the durable log head advanced. */\n readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;\n /** Best-effort non-blocking delivery to ephemeral sink workers. */\n readonly publishEphemeralToSinks: (\n event: PositionedEvent,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n ) => Effect.Effect<void>;\n}\n\n/** Registry and runner for app-provided EDA sinks. */\nexport class EDASinkRegistry extends Context.Service<EDASinkRegistry, EDASinkRegistryShape>()(\n \"@effect-durable-agent/EDASinkRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDASinkRegistry, {\n sinks: [],\n startSinkRunners: () => Effect.void,\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape);\n\n static readonly Live = (sinks: ReadonlyArray<EDASink>) =>\n Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));\n}\n\nconst defaultBatchSize = 100;\nconst sinkCheckpointFormatVersion = 1;\n\ninterface DurableRunnerState {\n readonly cursor: SequenceNumber;\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\ninterface SerializedSinkState {\n readonly formatVersion: typeof sinkCheckpointFormatVersion;\n readonly state: unknown;\n readonly updatedAtMs: number;\n}\n\nconst makeSinkRegistry = (sinks: ReadonlyArray<EDASink>) =>\n Effect.gen(function* () {\n const session = yield* SessionContext;\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const checkpointStore = yield* SinkCheckpointStore;\n const eventFactory = yield* EventFactory;\n const ids = yield* IdGenerator;\n const reducerRegistry = yield* EDAReducerRegistry;\n const keepAlive = yield* EDAKeepAlive;\n const started = yield* Ref.make(false);\n\n const baseContext = (\n staged: Array<DurableEventEnvelope>,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n scope: Scope.Scope,\n checkpoint: EDASinkCheckpoint,\n ): EDASinkContext => ({\n sessionId: session.sessionId,\n checkpoint,\n events: eventFactory,\n makeEventId: ids.makeEventId,\n emitEphemeral: publishEphemeral,\n stageDurable: (event) => Effect.sync(() => staged.push(event)),\n forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid),\n });\n\n const makeSinkRunner = (sink: EDASink, input: EDASinkRunnerStartInput) =>\n Effect.gen(function* () {\n const sinkName = EDASinkName.make(sink.name);\n const storedCheckpoint = yield* checkpointStore.load(sinkName);\n const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);\n const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);\n const cursor = storedCheckpoint.afterSeq;\n const prefix = yield* readDurablePrefixThrough(store, cursor);\n const state = yield* Ref.make<DurableRunnerState>({\n cursor,\n reduced: reduceCommittedEvents(prefix),\n reducerStates: reducerRegistry.reduce(reducerRegistry.initial, prefix),\n });\n const live = yield* liveBus.subscribeQueue().pipe(Scope.provide(input.scope));\n\n const processDurableBatch = Effect.fnUntraced(function* (\n allEvents: ReadonlyArray<CommittedDurableEvent>,\n ) {\n if (allEvents.length === 0) {\n return;\n }\n\n const current = yield* Ref.get(state);\n const fresh = allEvents.filter((entry) => entry.position.seq > current.cursor);\n if (fresh.length === 0) {\n return;\n }\n\n const durable = sink.durable;\n const throughSeq = fresh.at(-1)!.position.seq;\n const nextReduced = foldReducedState(current.reduced, fresh);\n const nextReducerStates = reducerRegistry.reduce(current.reducerStates, fresh);\n const eventsForSink =\n durable === undefined ? [] : filterInterested(fresh, durable.interests);\n\n if (durable !== undefined && eventsForSink.length > 0) {\n yield* Effect.gen(function* () {\n const staged: Array<DurableEventEnvelope> = [];\n const completed = yield* durable\n .process(\n {\n allEvents: fresh,\n events: eventsForSink,\n stateAfter: nextReduced,\n reducerStates: nextReducerStates,\n throughSeq,\n },\n baseContext(staged, input.publishEphemeral, input.scope, checkpoint),\n )\n .pipe(\n Effect.as(true),\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA durable sink violated its infallible contract\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }).pipe(Effect.as(false)),\n ),\n );\n if (completed && staged.length > 0) {\n yield* annotateEdaSpan({ \"eda.sink.staged_events\": staged.length });\n yield* input.appendDurableBatch(staged);\n }\n }).pipe(\n Effect.withSpan(\"agent.sink.drain\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.sink.cursor.before\": current.cursor,\n \"eda.sink.events.read\": fresh.length,\n \"eda.sink.events.interested\": eventsForSink.length,\n \"eda.sink.cursor.after\": throughSeq,\n },\n }),\n );\n }\n\n yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);\n yield* Ref.set(state, {\n cursor: throughSeq,\n reduced: nextReduced,\n reducerStates: nextReducerStates,\n });\n });\n\n const processDurableBatchWithKeepAlive = (events: ReadonlyArray<CommittedDurableEvent>) =>\n keepAlive.withActiveWork(`sink:${sink.name}`, processDurableBatch(events));\n\n const drainDurablesThrough = (targetHead: SequenceNumber) =>\n Effect.gen(function* () {\n while (true) {\n const current = yield* Ref.get(state);\n if (current.cursor >= targetHead) {\n return;\n }\n const allEvents = yield* readCursorBatchThrough(\n store,\n current.cursor,\n targetHead,\n sink.durable?.batchSize,\n );\n if (allEvents.length === 0) {\n return;\n }\n yield* processDurableBatchWithKeepAlive(allEvents);\n }\n });\n\n const processLiveDurable = (event: PositionedEvent) =>\n Effect.gen(function* () {\n const current = yield* Ref.get(state);\n if (event.position.seq <= current.cursor) {\n return;\n }\n if (event.position.seq > current.cursor + 1) {\n yield* drainDurablesThrough(SequenceNumber.make(event.position.seq - 1));\n }\n const afterCatchup = yield* Ref.get(state);\n if (event.position.seq > afterCatchup.cursor + 1) {\n yield* Effect.logWarning(\"EDA sink runner could not catch up before live durable\", {\n cursor: afterCatchup.cursor,\n eventSeq: event.position.seq,\n sink: sink.name,\n });\n return;\n }\n yield* processDurableBatchWithKeepAlive([committedDurableFromPositioned(event)]);\n });\n\n const processLiveEphemeral = (event: PositionedEvent) =>\n Effect.gen(function* () {\n const before = yield* Ref.get(state);\n if (event.position.seq < before.cursor) {\n return;\n }\n if (event.position.seq > before.cursor) {\n yield* drainDurablesThrough(event.position.seq);\n }\n const after = yield* Ref.get(state);\n if (event.position.seq !== after.cursor) {\n return;\n }\n if (\n sink.ephemeral === undefined ||\n !matchesInterest(event.event.type, sink.ephemeral.interests)\n ) {\n return;\n }\n yield* sink.ephemeral\n .process(event, baseContext([], input.publishEphemeral, input.scope, checkpoint))\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"EDA sink ephemeral projection failed\", {\n cause: String(cause),\n sink: sink.name,\n }),\n ),\n );\n });\n\n const processLiveEvent = (event: PositionedEvent) =>\n event.event.durability === \"durable\"\n ? processLiveDurable(event)\n : processLiveEphemeral(event);\n\n const runLoop = Effect.gen(function* () {\n yield* drainDurablesThrough(input.initialHead);\n return yield* Effect.forever(\n Effect.gen(function* () {\n const event = yield* PubSub.take(live);\n yield* processLiveEvent(event);\n }),\n );\n }).pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"EDA sink runner failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n\n yield* runLoop.pipe(Effect.forkIn(input.scope));\n });\n\n return {\n sinks,\n startSinkRunners: Effect.fnUntraced(function* (input: EDASinkRunnerStartInput) {\n const wasStarted = yield* Ref.getAndSet(started, true);\n if (wasStarted) {\n return;\n }\n yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {\n discard: true,\n concurrency: \"unbounded\",\n });\n }),\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape;\n });\n\nconst readDurablePrefixThrough = (store: EDASessionStoreShape, throughSeq: SequenceNumber) => {\n if (throughSeq <= SequenceNumber.make(0)) {\n return Effect.succeed([]);\n }\n return store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n};\n\nconst makeSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n): EDASinkCheckpoint => ({\n get: (schema, initial) =>\n SynchronizedRef.get(checkpointRef).pipe(\n Effect.flatMap((checkpoint) => {\n const serialized = serializedSinkState(checkpoint.payload);\n return serialized === undefined\n ? Effect.succeed(initial)\n : decodeSinkState(schema, serialized.state);\n }),\n ),\n save: (schema, state) =>\n encodeSinkState(schema, state).pipe(\n Effect.flatMap((encoded) => {\n const payload: SerializedSinkState = {\n formatVersion: sinkCheckpointFormatVersion,\n state: encoded,\n updatedAtMs: Date.now(),\n };\n return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.saveState(sinkName, payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq: checkpoint.afterSeq,\n payload,\n },\n ] as const),\n ),\n );\n }),\n ),\n});\n\nconst commitSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n afterSeq: SequenceNumber,\n): Effect.Effect<void, EDASessionStoreError> =>\n SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.commit(sinkName, afterSeq, checkpoint.payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq,\n payload: checkpoint.payload,\n },\n ] as const),\n ),\n );\n\nconst serializedSinkState = (payload: unknown): SerializedSinkState | undefined => {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n !(\"formatVersion\" in payload) ||\n payload.formatVersion !== sinkCheckpointFormatVersion ||\n !(\"state\" in payload) ||\n !(\"updatedAtMs\" in payload) ||\n typeof payload.updatedAtMs !== \"number\"\n ) {\n return undefined;\n }\n return {\n formatVersion: sinkCheckpointFormatVersion,\n state: payload.state,\n updatedAtMs: payload.updatedAtMs,\n };\n};\n\nconst decodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n encoded: unknown,\n): Effect.Effect<State, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(encoded),\n catch: (cause) => sinkCheckpointCodecError(\"decoding\", cause),\n });\n\nconst encodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n): Effect.Effect<unknown, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.encodeUnknownSync(schema)(state),\n catch: (cause) => sinkCheckpointCodecError(\"encoding\", cause),\n });\n\nconst sinkCheckpointCodecError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error\n ? `${operation} sink checkpoint: ${cause.message}`\n : `${operation} sink checkpoint: ${String(cause)}`,\n });\n\nconst readCursorBatchThrough = (\n store: EDASessionStoreShape,\n afterSeq: SequenceNumber,\n throughSeq: SequenceNumber,\n batchSize = defaultBatchSize,\n) =>\n store.eventsAfter(afterSeq).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.take(batchSize),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n\nconst committedDurableFromPositioned = (event: PositionedEvent): CommittedDurableEvent =>\n CommittedDurableEvent.make({\n event: event.event as DurableEventEnvelope,\n position: durablePosition(event.position.seq),\n });\n\nconst filterInterested = (\n events: ReadonlyArray<CommittedDurableEvent>,\n interests: ReadonlyArray<EventType | string> | undefined,\n): ReadonlyArray<CommittedDurableEvent> =>\n events.filter((event) => matchesInterest(event.event.type, interests));\n\nconst matchesInterest = (\n type: EventType | string,\n interests: ReadonlyArray<EventType | string> | undefined,\n): boolean => interests === undefined || interests.some((interest) => interest === type);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,oCAAoC;;AAmCjD,IAAa,eAAb,MAAa,qBAAqB,QAAQ,QAAyC,EACjF,oCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,cACA,OAAO,IAAI,aAAa;EAUtB,OAAO,YAAY,OATG,OAAO,eAC3B,OAAO,UAA2B,GAClC,OAAO,QACT,GAM2B,OALK,IAAI,KAAgC;GAClE,QAAQ,CAAC;GACT,YAAY;EACd,CAAC,GAE4C,OADpB,IAAI,KAA0C,CAAC,CAAC,CACnB;CACxD,CAAC,CACH;AACF;AAEA,MAAM,eACJ,QACA,kBACA,eACuB;CACvB,UAAU,UACR,uBAAuB,kBAAkB,KAAK,EAAE,KAC9C,OAAO,QAAQ,wBAAwB,WAAW,KAAK,CAAC,GACxD,OAAO,QAAQ,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAC9C;CACF,sBAAsB,OAAO,UAAU,MAAM;CA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,eAAe;EACf,OAAO,QAAQ;EACf,aAAa,QAAQ;CACvB;AACF;AAEA,MAAM,mBACJ,QACA,YAEA,OAAO,IAAI;CACT,WAAW,OAAO,kBAAkB,MAAM,EAAE,OAAO;CACnD,QAAQ,UAAU,yBAAyB,YAAY,KAAK;AAC9D,CAAC;AAEH,MAAM,mBACJ,QACA,UAEA,OAAO,IAAI;CACT,WAAW,OAAO,kBAAkB,MAAM,EAAE,KAAK;CACjD,QAAQ,UAAU,yBAAyB,YAAY,KAAK;AAC9D,CAAC;AAEH,MAAM,4BAA4B,WAAmB,UACnD,IAAI,qBAAqB,EACvB,SACE,iBAAiB,QACb,GAAG,UAAU,oBAAoB,MAAM,YACvC,GAAG,UAAU,oBAAoB,OAAO,KAAK,IACrD,CAAC;AAEH,MAAM,0BACJ,OACA,UACA,YACA,YAAY,qBAEZ,MAAM,YAAY,QAAQ,EAAE,KAC1B,OAAO,WAAW,UAAU,MAAM,SAAS,OAAO,UAAU,GAC5D,OAAO,KAAK,SAAS,GACrB,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;AAEF,MAAM,kCAAkC,UACtC,sBAAsB,KAAK;CACzB,OAAO,MAAM;CACb,UAAU,gBAAgB,MAAM,SAAS,GAAG;AAC9C,CAAC;AAEH,MAAM,oBACJ,QACA,cAEA,OAAO,QAAQ,UAAU,gBAAgB,MAAM,MAAM,MAAM,SAAS,CAAC;AAEvE,MAAM,mBACJ,MACA,cACY,cAAc,KAAA,KAAa,UAAU,MAAM,aAAa,aAAa,IAAI"}
@@ -1,17 +1,19 @@
1
- import { c as EventId, h as SessionId, m as SequenceNumber, y as TurnId } from "./core-Hv3cFydL.js";
1
+ import { c as EventId, h as SessionId, m as SequenceNumber, y as TurnId } from "./core-CYT6DBaS.js";
2
2
  import { D as DurableEventEnvelope, L as PositionedEvent, M as EventType, O as EphemeralEventEnvelope } from "./events-Bb9-Cu-7.js";
3
- import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-D2Ore1QC.js";
4
- import { S as ReducedState } from "./command-queues-CQ9cwRP7.js";
5
- import { i as EDAReducerStateSnapshot, n as EDAReducerRegistry } from "./reducer-registry-C0svUa63.js";
6
- import { t as IdGenerator } from "./id-generator-C2Q15uZM.js";
7
- import { i as SessionContext, n as EventFactory, r as EventFactoryShape, t as EDAKeepAlive } from "./keep-alive-DYDsH6qN.js";
3
+ import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-BLg6UvZa.js";
4
+ import { S as ReducedState } from "./command-queues-Dwdf41mq.js";
5
+ import { t as IdGenerator } from "./id-generator-Ckl8_XWW.js";
6
+ import { n as EventFactoryShape, r as SessionContext, t as EventFactory } from "./event-factory-CLJcyymV.js";
7
+ import { t as EDAKeepAlive } from "./keep-alive-Chl5SJxy.js";
8
+ import { i as EDAReducerStateSnapshot, n as EDAReducerRegistry } from "./reducer-registry-K9FqZq5-.js";
9
+ import { n as SinkCheckpointStore } from "./sink-checkpoint-store-B9WNvDtY.js";
8
10
  import * as Context from "effect/Context";
9
11
  import * as Effect from "effect/Effect";
10
12
  import * as Layer from "effect/Layer";
11
13
  import * as Schema from "effect/Schema";
12
14
  import * as Stream from "effect/Stream";
13
- import * as Scope from "effect/Scope";
14
15
  import * as PubSub from "effect/PubSub";
16
+ import * as Scope from "effect/Scope";
15
17
 
16
18
  //#region src/services/live-event-bus.d.ts
17
19
  /** Live-only replay buffer for the currently open turn. */
@@ -20,6 +22,15 @@ interface ActiveTurnEphemeralReplay {
20
22
  readonly events: ReadonlyArray<PositionedEvent>;
21
23
  readonly overflowed: boolean;
22
24
  }
25
+ /**
26
+ * Push-delivery listener invoked inline as each event is published.
27
+ *
28
+ * Listeners let hibernation-capable hosts fan events out to accepted
29
+ * WebSockets during the already-active turn instead of parking a resident
30
+ * subscriber fiber on the pub/sub. Listeners must not fail; defects are
31
+ * logged and never interrupt the publishing turn.
32
+ */
33
+ type LiveDeliveryListener = (event: PositionedEvent) => Effect.Effect<void>;
23
34
  /** In-memory live fanout plus active-turn replay source for reconnect streams. */
24
35
  interface LiveEventBusShape {
25
36
  readonly publish: (event: PositionedEvent) => Effect.Effect<boolean>;
@@ -27,6 +38,8 @@ interface LiveEventBusShape {
27
38
  readonly subscribeQueue: () => Effect.Effect<PubSub.Subscription<PositionedEvent>, never, Scope.Scope>;
28
39
  /** Snapshot raw live-only events retained for the currently open turn. */
29
40
  readonly activeTurnReplay: () => Effect.Effect<ActiveTurnEphemeralReplay>;
41
+ /** Register one push-delivery listener invoked inline on every published event. */
42
+ readonly registerDeliveryListener: (listener: LiveDeliveryListener) => Effect.Effect<void>;
30
43
  }
31
44
  declare const LiveEventBus_base: Context.ServiceClass<LiveEventBus, "@effect-durable-agent/LiveEventBus", LiveEventBusShape>;
32
45
  /** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
@@ -34,37 +47,6 @@ declare class LiveEventBus extends LiveEventBus_base {
34
47
  static readonly Live: Layer.Layer<LiveEventBus, never, never>;
35
48
  }
36
49
  //#endregion
37
- //#region src/services/sink-checkpoint-store.d.ts
38
- /** Stable sink name used as the durable checkpoint key. */
39
- declare const EDASinkName: Schema.brand<Schema.NonEmptyString, "EDASinkName">;
40
- type EDASinkName = typeof EDASinkName.Type;
41
- /** Persisted cursor and sink-owned payload for one registered sink. */
42
- interface StoredSinkCheckpoint {
43
- readonly afterSeq: SequenceNumber;
44
- readonly payload: unknown | undefined;
45
- }
46
- /** Durable checkpoint persistence port for at-least-once sink runners. */
47
- interface SinkCheckpointStoreShape {
48
- /** Read the latest committed cursor and sink-owned payload. */
49
- readonly load: (sinkName: EDASinkName) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;
50
- /** Save sink-owned state without advancing the durable cursor. */
51
- readonly saveState: (sinkName: EDASinkName, payload: unknown) => Effect.Effect<void, EDASessionStoreError>;
52
- /** Atomically commit the processed cursor together with current sink-owned state. */
53
- readonly commit: (sinkName: EDASinkName, afterSeq: SequenceNumber, payload: unknown | undefined) => Effect.Effect<void, EDASessionStoreError>;
54
- }
55
- declare const SinkCheckpointStore_base: Context.ServiceClass<SinkCheckpointStore, "@effect-durable-agent/SinkCheckpointStore", SinkCheckpointStoreShape>;
56
- /**
57
- * Semantic checkpoint store for registered EDA sinks.
58
- *
59
- * Checkpoints are intentionally exposed as load/save/commit operations rather
60
- * than SQL. Sink side effects happen outside event append transactions, and the
61
- * cursor advances only after the sink finishes its own external work.
62
- */
63
- declare class SinkCheckpointStore extends SinkCheckpointStore_base {
64
- /** In-memory checkpoint implementation for store/runtime tests. */
65
- static readonly InMemory: Layer.Layer<SinkCheckpointStore, never, never>;
66
- }
67
- //#endregion
68
50
  //#region src/services/sink-registry.d.ts
69
51
  /** Cursor-window input delivered to one durable sink drain. */
70
52
  interface EDASinkDurableBatch {
@@ -102,24 +84,25 @@ interface EDASinkContext {
102
84
  /** Fork background sink work into the session scope. */
103
85
  readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;
104
86
  }
105
- /** At-least-once sink definition backed by a durable checkpoint. */
87
+ /** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */
106
88
  interface EDADurableSinkDefinition {
107
89
  readonly interests?: ReadonlyArray<EventType | string>;
108
90
  readonly batchSize?: number;
109
- readonly process: (batch: EDASinkDurableBatch, ctx: EDASinkContext) => Effect.Effect<void, unknown>;
91
+ readonly process: (batch: EDASinkDurableBatch, ctx: EDASinkContext) => Effect.Effect<void, never>;
110
92
  }
111
93
  /** Best-effort live-only sink definition. */
112
94
  interface EDAEphemeralSinkDefinition {
113
95
  readonly interests?: ReadonlyArray<EventType | string>;
114
- readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, unknown>;
96
+ readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, never>;
115
97
  }
116
98
  /**
117
99
  * Named app integration hook with optional durable and ephemeral filters.
118
100
  *
119
- * Every sink runs on one serialized position-ordered lane. Durable callbacks are
120
- * retried before the sink checkpoint advances; ephemeral callbacks are best-effort
121
- * and are only processed after the durable prefix at their anchor sequence has
122
- * been projected.
101
+ * Every sink runs on one serialized position-ordered lane. Sinks own retry and
102
+ * terminal failure handling, so callbacks must have an infallible typed error
103
+ * channel. An unexpected defect is logged and skipped before the durable checkpoint
104
+ * advances. Ephemeral callbacks are best-effort and are only processed after the
105
+ * durable prefix at their anchor sequence has been projected.
123
106
  */
124
107
  interface EDASink {
125
108
  readonly name: string;
@@ -151,8 +134,8 @@ declare const EDASinkRegistry_base: Context.ServiceClass<EDASinkRegistry, "@effe
151
134
  /** Registry and runner for app-provided EDA sinks. */
152
135
  declare class EDASinkRegistry extends EDASinkRegistry_base {
153
136
  static readonly Empty: Layer.Layer<EDASinkRegistry, never, never>;
154
- static readonly Live: (sinks: ReadonlyArray<EDASink>) => Layer.Layer<EDASinkRegistry, never, EventFactory | IdGenerator | EDAKeepAlive | SinkCheckpointStore | EDASessionStore | EDAReducerRegistry | LiveEventBus | SessionContext>;
137
+ static readonly Live: (sinks: ReadonlyArray<EDASink>) => Layer.Layer<EDASinkRegistry, never, EDASessionStore | LiveEventBus | EDAKeepAlive | IdGenerator | EventFactory | SessionContext | EDAReducerRegistry | SinkCheckpointStore>;
155
138
  }
156
139
  //#endregion
157
- export { EDASinkContext as a, EDASinkRegistryShape as c, LiveEventBus as d, EDASinkCheckpoint as i, EDASinkRunnerStartInput as l, EDAEphemeralSinkDefinition as n, EDASinkDurableBatch as o, EDASink as r, EDASinkRegistry as s, EDADurableSinkDefinition as t, SinkCheckpointStore as u };
158
- //# sourceMappingURL=sink-registry-BziFpxoE.d.ts.map
140
+ export { EDASinkContext as a, EDASinkRegistryShape as c, LiveEventBusShape as d, EDASinkCheckpoint as i, EDASinkRunnerStartInput as l, EDAEphemeralSinkDefinition as n, EDASinkDurableBatch as o, EDASink as r, EDASinkRegistry as s, EDADurableSinkDefinition as t, LiveEventBus as u };
141
+ //# sourceMappingURL=sink-registry-CO3YPS1p.d.ts.map
@@ -1,14 +1,17 @@
1
- import { h as SessionId } from "../core-Hv3cFydL.js";
1
+ import { h as SessionId } from "../core-CYT6DBaS.js";
2
2
  import { D as DurableEventEnvelope } from "../events-Bb9-Cu-7.js";
3
- import { a as EDASessionStore, o as EDASessionStoreError, s as EDASessionStoreShape } from "../session-store-D2Ore1QC.js";
4
- import { n as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-C0svUa63.js";
5
- import { d as LiveEventBus, r as EDASink, s as EDASinkRegistry, u as SinkCheckpointStore } from "../sink-registry-BziFpxoE.js";
6
- import { t as IdGenerator } from "../id-generator-C2Q15uZM.js";
7
- import { i as SessionContext, n as EventFactory, t as EDAKeepAlive } from "../keep-alive-DYDsH6qN.js";
8
- import { c as CompactionPolicy, d as CompactionRunner, r as CompactionExecutor } from "../compaction-1LSZR944.js";
9
- import { r as EDAPromptProjector } from "../prompt-projector-DimXJPOJ.js";
10
- import { c as InferenceRunner, l as InferenceRunnerStreamPart, o as SessionState, s as TurnRunner, t as EDASessionQuery, u as ToolExecutor } from "../session-query-hxfujxUH.js";
11
- import { a as ToolParamsSchema, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-CcnkAAQK.js";
3
+ import { a as EDASessionStore, o as EDASessionStoreError, s as EDASessionStoreShape } from "../session-store-BLg6UvZa.js";
4
+ import { r as EDASink, s as EDASinkRegistry, u as LiveEventBus } from "../sink-registry-CO3YPS1p.js";
5
+ import { t as IdGenerator } from "../id-generator-Ckl8_XWW.js";
6
+ import { r as SessionContext, t as EventFactory } from "../event-factory-CLJcyymV.js";
7
+ import { t as EDAKeepAlive } from "../keep-alive-Chl5SJxy.js";
8
+ import { c as CompactionPolicy, d as CompactionRunner, r as CompactionExecutor } from "../compaction-DpHOf-g7.js";
9
+ import { n as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-K9FqZq5-.js";
10
+ import { r as EDAPromptProjector } from "../prompt-projector-C2meuNrV.js";
11
+ import { n as SinkCheckpointStore } from "../sink-checkpoint-store-B9WNvDtY.js";
12
+ import { S as ToolExecutor, b as InferenceRunner, h as SessionState, x as InferenceRunnerStreamPart, y as TurnRunner } from "../session-state-CI1xeT6f.js";
13
+ import { a as ToolParamsSchema, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-B8H1P6Pu.js";
14
+ import { n as EDASessionQuery } from "../session-query-5oyZRaQL.js";
12
15
  import * as Layer from "effect/Layer";
13
16
  import * as Stream from "effect/Stream";
14
17
  import * as Prompt from "effect/unstable/ai/Prompt";
@@ -95,7 +98,7 @@ interface EdaTestLayerOptions {
95
98
  * EDA service plus the fixed Clock. Layer constants are shared by reference,
96
99
  * so all services see the same store, bus, and ID counter.
97
100
  */
98
- declare const makeEdaTestLayer: (options: EdaTestLayerOptions) => Layer.Layer<CompactionPolicy | CompactionExecutor | LanguageModel.LanguageModel | CompactionRunner | EventFactory | IdGenerator | EDAKeepAlive | EDASinkRegistry | SinkCheckpointStore | EDASessionStore | EDAReducerRegistry | LiveEventBus | SessionContext | EDAToolRegistry | EDASessionQuery | SessionState | EDAPromptProjector | TurnRunner | InferenceRunner | ToolExecutor, EDASessionStoreError, never>;
101
+ declare const makeEdaTestLayer: (options: EdaTestLayerOptions) => Layer.Layer<EDAToolRegistry | LanguageModel.LanguageModel | SessionState | EDASessionStore | LiveEventBus | EDAKeepAlive | IdGenerator | EventFactory | TurnRunner | CompactionRunner | EDAPromptProjector | SessionContext | EDAReducerRegistry | EDASinkRegistry | SinkCheckpointStore | CompactionPolicy | CompactionExecutor | InferenceRunner | ToolExecutor | EDASessionQuery, EDASessionStoreError, never>;
99
102
  //#endregion
100
103
  export { EdaTestLayerOptions, FixedClock, TestLanguageModelOptions, TestModelParts, makeEdaTestLayer, makeFixedClock, makeLanguageModelLayer, testNowMs };
101
104
  //# sourceMappingURL=layers.d.ts.map