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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +28 -27
  3. package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-CV7O-51r.d.ts} +7 -6
  4. package/dist/{compaction-1LSZR944.d.ts → compaction-zbvLREI8.d.ts} +8 -6
  5. package/dist/context-projection-n6Rdup0N.d.ts +140 -0
  6. package/dist/{core-Hv3cFydL.d.ts → core-CYT6DBaS.d.ts} +2 -2
  7. package/dist/domain/command-queues.d.ts +1 -1
  8. package/dist/domain/context-projection.d.ts +2 -0
  9. package/dist/domain/context-projection.js +32 -0
  10. package/dist/domain/context-projection.js.map +1 -0
  11. package/dist/domain/message-transcript.d.ts +1 -1
  12. package/dist/domain/reduced-state-schema.d.ts +2 -0
  13. package/dist/domain/reduced-state-schema.js +2 -1
  14. package/dist/domain/reduced-state-schema.js.map +1 -1
  15. package/dist/domain/reduced-state.d.ts +1 -1
  16. package/dist/domain/reduced-state.js +1 -1
  17. package/dist/{durable-DlScwmCy.d.ts → durable-B7M6TD_0.d.ts} +341 -2
  18. package/dist/{durable-C3Rz7kg3.js → durable-DsV9PxZC.js} +13 -2
  19. package/dist/durable-DsV9PxZC.js.map +1 -0
  20. package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-CLJcyymV.d.ts} +5 -29
  21. package/dist/{keep-alive-p8dIcSVy.js → event-factory-tcpLgdMN.js} +3 -10
  22. package/dist/event-factory-tcpLgdMN.js.map +1 -0
  23. package/dist/host/websocket-protocol.d.ts +229 -0
  24. package/dist/host/websocket-protocol.js +99 -0
  25. package/dist/host/websocket-protocol.js.map +1 -0
  26. package/dist/host/websocket-wire.d.ts +1 -1
  27. package/dist/host/websocket-wire.js +2 -2
  28. package/dist/host/websocket-wire.js.map +1 -1
  29. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-Ckl8_XWW.d.ts} +2 -2
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +2 -2
  32. package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
  33. package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-DiOPBY3l.d.ts} +3 -3
  34. package/dist/{prompt-projector-DimXJPOJ.d.ts → prompt-projector-C1IbkHr0.d.ts} +5 -5
  35. package/dist/{reduced-state-C4nVVzz9.js → reduced-state-TMi7ISla.js} +20 -4
  36. package/dist/reduced-state-TMi7ISla.js.map +1 -0
  37. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-CjSJBPKo.d.ts} +2 -2
  38. package/dist/{runtime-DcdPOEuE.d.ts → runtime-DOgmAKsO.d.ts} +7 -6
  39. package/dist/services/compaction.d.ts +1 -1
  40. package/dist/services/compaction.js +4 -3
  41. package/dist/services/compaction.js.map +1 -1
  42. package/dist/services/id-generator.d.ts +1 -1
  43. package/dist/services/keep-alive.d.ts +2 -0
  44. package/dist/services/keep-alive.js +13 -0
  45. package/dist/services/keep-alive.js.map +1 -0
  46. package/dist/services/prompt-projector.d.ts +1 -1
  47. package/dist/services/reducer-registry.d.ts +1 -1
  48. package/dist/services/runtime-layer.d.ts +58 -0
  49. package/dist/services/runtime-layer.js +42 -0
  50. package/dist/services/runtime-layer.js.map +1 -0
  51. package/dist/services/runtime.d.ts +1 -1
  52. package/dist/services/runtime.js +4 -3
  53. package/dist/services/runtime.js.map +1 -1
  54. package/dist/services/session-query.d.ts +1 -1
  55. package/dist/services/session-query.js +76 -1
  56. package/dist/services/session-query.js.map +1 -0
  57. package/dist/services/session-state.d.ts +2 -0
  58. package/dist/services/session-state.js +2 -0
  59. package/dist/services/session-store.d.ts +2 -2
  60. package/dist/services/session-store.js +181 -2
  61. package/dist/services/session-store.js.map +1 -0
  62. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  63. package/dist/services/sink-checkpoint-store.js +49 -0
  64. package/dist/services/sink-checkpoint-store.js.map +1 -0
  65. package/dist/services/sink-registry.d.ts +1 -1
  66. package/dist/services/sink-registry.js +1 -1
  67. package/dist/services/tool-registry.d.ts +1 -1
  68. package/dist/services/websocket-subscriber.d.ts +54 -0
  69. package/dist/services/websocket-subscriber.js +190 -0
  70. package/dist/services/websocket-subscriber.js.map +1 -0
  71. package/dist/session-query-C-C4m1eq.d.ts +38 -0
  72. package/dist/{session-query-hxfujxUH.d.ts → session-state-CjOSvWbe.d.ts} +134 -42
  73. package/dist/{session-query-Cbf-e0rG.js → session-state-SStf0KUo.js} +18 -77
  74. package/dist/session-state-SStf0KUo.js.map +1 -0
  75. package/dist/{session-store-D2Ore1QC.d.ts → session-store-DZZUffUy.d.ts} +5 -94
  76. package/dist/sink-checkpoint-store-BZmQFTRE.d.ts +40 -0
  77. package/dist/{sink-registry-BziFpxoE.d.ts → sink-registry-Cf79ICdW.d.ts} +11 -40
  78. package/dist/{sink-registry-CFC6xjsN.js → sink-registry-D13eUO_c.js} +9 -47
  79. package/dist/sink-registry-D13eUO_c.js.map +1 -0
  80. package/dist/testkit/layers.d.ts +14 -11
  81. package/dist/testkit/layers.js +8 -5
  82. package/dist/testkit/layers.js.map +1 -1
  83. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-B7Wona6N.d.ts} +3 -3
  84. package/dist/types/core.d.ts +1 -1
  85. package/dist/types/core.js +1 -1
  86. package/dist/types/core.js.map +1 -1
  87. package/dist/types/events/durable.d.ts +2 -2
  88. package/dist/types/events/durable.js +2 -2
  89. package/dist/types/events.d.ts +2 -2
  90. package/dist/types/events.js +2 -2
  91. package/dist/{websocket-wire-D3tLrhe2.d.ts → websocket-wire-QD2SquQE.d.ts} +74 -2
  92. package/docs/message-steering.md +1 -1
  93. package/docs/releasing.md +42 -24
  94. package/docs/spec.md +11 -11
  95. package/docs/websocket-protocol.md +4 -4
  96. package/package.json +55 -35
  97. package/dist/durable-C3Rz7kg3.js.map +0 -1
  98. package/dist/durable-object-runtime-CiMKxGs6.d.ts +0 -257
  99. package/dist/durable-object-runtime-wKiqaAt2.js +0 -1494
  100. package/dist/durable-object-runtime-wKiqaAt2.js.map +0 -1
  101. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  102. package/dist/host/durable-object-runtime.d.ts +0 -2
  103. package/dist/host/durable-object-runtime.js +0 -2
  104. package/dist/host/durable-object-storage.d.ts +0 -2
  105. package/dist/host/durable-object-storage.js +0 -0
  106. package/dist/host/durable-object.d.ts +0 -83
  107. package/dist/host/durable-object.js +0 -191
  108. package/dist/host/durable-object.js.map +0 -1
  109. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  110. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  111. package/dist/session-query-Cbf-e0rG.js.map +0 -1
  112. package/dist/session-store-pYxQW9qh.js +0 -214
  113. package/dist/session-store-pYxQW9qh.js.map +0 -1
  114. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  115. package/examples/001-no-tools/README.md +0 -65
  116. package/examples/001-no-tools/worker.ts +0 -79
  117. package/examples/002-slack-bridge/README.md +0 -134
  118. package/examples/002-slack-bridge/events.ts +0 -115
  119. package/examples/002-slack-bridge/reducer.ts +0 -216
  120. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  121. package/examples/002-slack-bridge/sinks.ts +0 -109
  122. package/examples/002-slack-bridge/worker.ts +0 -140
  123. package/examples/003-sandbox-lifecycle/README.md +0 -78
  124. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  125. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  126. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  127. package/examples/_shared/event-id.ts +0 -12
  128. package/examples/_shared/http.ts +0 -27
  129. package/examples/_shared/openai.ts +0 -33
@@ -1,214 +0,0 @@
1
- import { CommandId, CompactionId, ContextVersion, DurablePosition, SequenceNumber, SummaryId, durablePosition } from "./types/core.js";
2
- import { Bn as summaryCreatedEventType, Cn as contextRebasedEventType, nr as DurableEventEnvelope, pn as commandAdmittedEventType } from "./durable-C3Rz7kg3.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
- import * as Stream from "effect/Stream";
8
- import * as Prompt from "effect/unstable/ai/Prompt";
9
- import * as Cause from "effect/Cause";
10
- import * as Ref from "effect/Ref";
11
- //#region src/domain/context-projection.ts
12
- /** Stable identifier for the compaction policy that selected a summary plan. */
13
- const CompactionPolicyId = Schema.NonEmptyString.pipe(Schema.brand("CompactionPolicyId"));
14
- /** Stable identifier for the executor that produced a summary artifact. */
15
- const CompactionExecutorId = Schema.NonEmptyString.pipe(Schema.brand("CompactionExecutorId"));
16
- /** Authoritative cumulative model-context summary written with `SummaryCreated`. */
17
- const CompactionSummaryArtifact = Schema.Struct({
18
- compactionId: CompactionId,
19
- summaryId: SummaryId,
20
- previousSummaryId: Schema.optionalKey(SummaryId),
21
- sourceFromSeq: SequenceNumber,
22
- sourceToSeq: SequenceNumber,
23
- retainedFromContextSeq: SequenceNumber,
24
- text: Schema.NonEmptyString,
25
- promptMessage: Prompt.UserMessage,
26
- policyId: CompactionPolicyId,
27
- executorId: Schema.optionalKey(CompactionExecutorId)
28
- });
29
- /** Current durable context cursor projected from framework reducer state and summary rows. */
30
- const ContextProjection = Schema.Struct({
31
- contextVersion: ContextVersion,
32
- currentSummary: Schema.optionalKey(CompactionSummaryArtifact)
33
- });
34
- /** Genesis context before any compaction has rebased prompt history. */
35
- const emptyContextProjection = ContextProjection.make({ contextVersion: ContextVersion.make(0) });
36
- //#endregion
37
- //#region src/services/session-store.ts
38
- /** A durable event after the store has assigned its replay position. */
39
- const CommittedDurableEvent = Schema.Struct({
40
- position: DurablePosition,
41
- event: DurableEventEnvelope
42
- });
43
- /**
44
- * Store-level failure surfaced by durable append, replay, and hydration APIs.
45
- *
46
- * The error intentionally stays storage-semantic rather than SQL-specific so
47
- * framework services can treat DO SQLite, in-memory tests, and future adapters
48
- * as the same durability boundary.
49
- */
50
- var EDASessionStoreError = class extends Schema.TaggedErrorClass()("EDASessionStoreError", { message: Schema.String }) {};
51
- /** True when a Cause contains an escaped durable-store failure. */
52
- const hasEDASessionStoreError = (cause) => cause.reasons.some((reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError);
53
- /**
54
- * Initial hard cap for one serialized JSON value stored in DO SQLite.
55
- *
56
- * Cloudflare's SQL row/string limit is 2MB; failing around 1.5MB leaves margin
57
- * for encoding overhead and makes the future blob/chunk decision explicit.
58
- */
59
- const durableObjectSerializedJsonHardCapBytes = 15e5;
60
- /**
61
- * One logical event to persist in the durable session log.
62
- *
63
- * Store adapters may split large logical payload fields into sidecar rows after
64
- * the event insert assigns `seq`, but callers still provide one fat event.
65
- */
66
- const DurableAppendEntry = Schema.Struct({ event: DurableEventEnvelope });
67
- /**
68
- * Ordered durable append intent. Adapters assign positions in entry order.
69
- *
70
- * This is the single write shape exposed to framework services. It avoids raw
71
- * SQL and public transaction callbacks while still expressing the full atomic
72
- * transition EDA needs for events, normalized bodies, and metadata.
73
- */
74
- const DurableAppendBatch = Schema.Struct({ entries: Schema.Array(DurableAppendEntry) });
75
- /** Indexed command-admission lookup used for idempotent ingress. */
76
- const FindCommandAdmissionInput = Schema.Struct({
77
- commandId: Schema.optionalKey(CommandId),
78
- idempotencyKey: Schema.optionalKey(Schema.String)
79
- });
80
- /**
81
- * SQL-agnostic durable storage port for one EDA session.
82
- *
83
- * Framework services depend on this semantic port rather than raw SQL. Host
84
- * adapters own physical tables and synchronous transaction mechanics; callers
85
- * only express durable append/replay/lookup intent.
86
- */
87
- var EDASessionStore = class EDASessionStore extends Context.Service()("@effect-durable-agent/EDASessionStore") {
88
- /** Deterministic in-memory implementation used by runtime and recovery tests. */
89
- static InMemory = (sessionId) => Layer.effect(EDASessionStore, Effect.gen(function* () {
90
- return makeInMemoryStore(sessionId, yield* Ref.make(emptyInMemoryStoreData()));
91
- }));
92
- /** In-memory store seeded with a durable prefix; intended for recovery tests. */
93
- static InMemorySeeded = (sessionId, events) => Layer.effect(EDASessionStore, Effect.gen(function* () {
94
- const committed = seedCommittedEvents(sessionId, events);
95
- return makeInMemoryStore(sessionId, yield* Ref.make({
96
- ...emptyInMemoryStoreData(),
97
- committed,
98
- summaries: summariesFromCommittedEvents(committed)
99
- }));
100
- }));
101
- };
102
- const emptyInMemoryStoreData = () => ({
103
- committed: [],
104
- summaries: /* @__PURE__ */ new Map(),
105
- reducerCheckpoints: /* @__PURE__ */ new Map()
106
- });
107
- const seedCommittedEvents = (sessionId, events) => {
108
- const seen = /* @__PURE__ */ new Set();
109
- return events.map((event, index) => {
110
- if (event.sessionId !== sessionId) throw new Error(`EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`);
111
- if (seen.has(event.eventId)) throw new Error(`Duplicate seed eventId ${event.eventId}`);
112
- seen.add(event.eventId);
113
- return CommittedDurableEvent.make({
114
- position: durablePosition(SequenceNumber.make(index + 1)),
115
- event
116
- });
117
- });
118
- };
119
- const summariesFromCommittedEvents = (events) => {
120
- const summaries = /* @__PURE__ */ new Map();
121
- for (const { event } of events) {
122
- if (event.type !== summaryCreatedEventType) continue;
123
- const payload = event.payload;
124
- if (payload.summary !== void 0) {
125
- const summary = CompactionSummaryArtifact.make(payload.summary);
126
- summaries.set(summary.summaryId, summary);
127
- }
128
- }
129
- return summaries;
130
- };
131
- /**
132
- * Build an in-memory store with one `Ref.modify` append critical section.
133
- *
134
- * The fake models the semantic atomicity of the production adapter without
135
- * exposing SQL, so runtime tests exercise the same store contract.
136
- */
137
- const makeInMemoryStore = (sessionId, data) => {
138
- const ensureSession = (event) => Effect.gen(function* () {
139
- if (event.sessionId === sessionId) return;
140
- return yield* new EDASessionStoreError({ message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}` });
141
- });
142
- const append = (batch) => Effect.gen(function* () {
143
- for (const entry of batch.entries) yield* ensureSession(entry.event);
144
- return yield* Ref.modify(data, (current) => {
145
- const nextEntries = [...current.committed];
146
- const nextSummaries = new Map(current.summaries);
147
- const committedEvents = [];
148
- for (const entry of batch.entries) {
149
- const { event } = entry;
150
- const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);
151
- if (existing !== void 0) {
152
- committedEvents.push(existing);
153
- continue;
154
- }
155
- const committed = CommittedDurableEvent.make({
156
- position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),
157
- event
158
- });
159
- nextEntries.push(committed);
160
- committedEvents.push(committed);
161
- if (event.type === summaryCreatedEventType) {
162
- const payload = event.payload;
163
- if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
164
- const summary = CompactionSummaryArtifact.make(payload.summary);
165
- if (payload.summaryId !== void 0 && summary.summaryId !== payload.summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
166
- nextSummaries.set(summary.summaryId, summary);
167
- }
168
- if (event.type === contextRebasedEventType) {
169
- const payload = event.payload;
170
- if (payload.summaryId === void 0 || !nextSummaries.has(payload.summaryId)) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
171
- }
172
- }
173
- return [committedEvents, {
174
- committed: nextEntries,
175
- summaries: nextSummaries,
176
- reducerCheckpoints: current.reducerCheckpoints
177
- }];
178
- });
179
- });
180
- return {
181
- append,
182
- eventsAfter: (afterSeq) => Stream.fromIterableEffect(Ref.get(data).pipe(Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)))),
183
- loadCommittedEventsBySeq: (seqs) => Ref.get(data).pipe(Effect.map(({ committed }) => {
184
- const requested = new Set(seqs.map((seq) => Number(seq)));
185
- return committed.filter((entry) => requested.has(Number(entry.position.seq)));
186
- })),
187
- findCommandAdmission: (input) => Ref.get(data).pipe(Effect.map(({ committed }) => committed.find((entry) => commandAdmissionMatches(entry, input)))),
188
- loadSummaryArtifact: (summaryId) => Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),
189
- loadReducerCheckpoint: (name) => Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),
190
- saveReducerCheckpoint: (checkpoint) => Ref.update(data, (current) => ({
191
- ...current,
192
- reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint)
193
- })),
194
- saveReducerCheckpoints: (checkpoints) => Ref.update(data, (current) => {
195
- const reducerCheckpoints = new Map(current.reducerCheckpoints);
196
- for (const checkpoint of checkpoints) reducerCheckpoints.set(checkpoint.name, checkpoint);
197
- return {
198
- ...current,
199
- reducerCheckpoints
200
- };
201
- })
202
- };
203
- };
204
- const commandAdmissionMatches = (entry, input) => {
205
- if (entry.event.type !== commandAdmittedEventType) return false;
206
- const admitted = entry.event.payload.command;
207
- if (admitted === void 0) return false;
208
- if (input.idempotencyKey !== void 0 && admitted.idempotencyKey === input.idempotencyKey) return true;
209
- return input.commandId !== void 0 && admitted.commandId === input.commandId;
210
- };
211
- //#endregion
212
- export { EDASessionStoreError as a, hasEDASessionStoreError as c, CompactionSummaryArtifact as d, ContextProjection as f, EDASessionStore as i, CompactionExecutorId as l, DurableAppendBatch as n, FindCommandAdmissionInput as o, emptyContextProjection as p, DurableAppendEntry as r, durableObjectSerializedJsonHardCapBytes as s, CommittedDurableEvent as t, CompactionPolicyId as u };
213
-
214
- //# sourceMappingURL=session-store-pYxQW9qh.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"session-store-pYxQW9qh.js","names":[],"sources":["../src/domain/context-projection.ts","../src/services/session-store.ts"],"sourcesContent":["import * as Prompt from \"effect/unstable/ai/Prompt\";\nimport * as Schema from \"effect/Schema\";\n\nimport { CompactionId, ContextVersion, SequenceNumber, SummaryId } from \"../types/core\";\n\n/** Stable identifier for the compaction policy that selected a summary plan. */\nexport const CompactionPolicyId = Schema.NonEmptyString.pipe(Schema.brand(\"CompactionPolicyId\"));\nexport type CompactionPolicyId = typeof CompactionPolicyId.Type;\n\n/** Stable identifier for the executor that produced a summary artifact. */\nexport const CompactionExecutorId = Schema.NonEmptyString.pipe(\n Schema.brand(\"CompactionExecutorId\"),\n);\nexport type CompactionExecutorId = typeof CompactionExecutorId.Type;\n\n/** Authoritative cumulative model-context summary written with `SummaryCreated`. */\nexport const CompactionSummaryArtifact = Schema.Struct({\n compactionId: CompactionId,\n summaryId: SummaryId,\n previousSummaryId: Schema.optionalKey(SummaryId),\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n retainedFromContextSeq: SequenceNumber,\n text: Schema.NonEmptyString,\n promptMessage: Prompt.UserMessage,\n policyId: CompactionPolicyId,\n executorId: Schema.optionalKey(CompactionExecutorId),\n});\nexport type CompactionSummaryArtifact = typeof CompactionSummaryArtifact.Type;\n\n/** Current durable context cursor projected from framework reducer state and summary rows. */\nexport const ContextProjection = Schema.Struct({\n contextVersion: ContextVersion,\n currentSummary: Schema.optionalKey(CompactionSummaryArtifact),\n});\nexport type ContextProjection = typeof ContextProjection.Type;\n\n/** Genesis context before any compaction has rebased prompt history. */\nexport const emptyContextProjection = ContextProjection.make({\n contextVersion: ContextVersion.make(0),\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 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 DO SQLite, 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 * Initial hard cap for one serialized JSON value stored in DO SQLite.\n *\n * Cloudflare's SQL row/string limit is 2MB; failing around 1.5MB leaves margin\n * for encoding overhead and makes the future blob/chunk decision explicit.\n */\nexport const durableObjectSerializedJsonHardCapBytes = 1_500_000;\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":";;;;;;;;;;;;AAMA,MAAa,qBAAqB,OAAO,eAAe,KAAK,OAAO,MAAM,oBAAoB,CAAC;;AAI/F,MAAa,uBAAuB,OAAO,eAAe,KACxD,OAAO,MAAM,sBAAsB,CACrC;;AAIA,MAAa,4BAA4B,OAAO,OAAO;CACrD,cAAc;CACd,WAAW;CACX,mBAAmB,OAAO,YAAY,SAAS;CAC/C,eAAe;CACf,aAAa;CACb,wBAAwB;CACxB,MAAM,OAAO;CACb,eAAe,OAAO;CACtB,UAAU;CACV,YAAY,OAAO,YAAY,oBAAoB;AACrD,CAAC;;AAID,MAAa,oBAAoB,OAAO,OAAO;CAC7C,gBAAgB;CAChB,gBAAgB,OAAO,YAAY,yBAAyB;AAC9D,CAAC;;AAID,MAAa,yBAAyB,kBAAkB,KAAK,EAC3D,gBAAgB,eAAe,KAAK,CAAC,EACvC,CAAC;;;;ACdD,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,0CAA0C;;;;;;;AAQvD,MAAa,qB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AC,CAAC;EACzF,wBAAwB,eACtB,IAAI,OAAO,OAAO,aAAa;GAC7B,GAAG;GACH,oBAAoB,IAAI,IAAI,QAAQ,kBAAkB,EAAE,IAAI,WAAW,MAAM,UAAU;EACzF,EAAE;EACJ,yBAAyB,gBACvB,IAAI,OAAO,OAAO,YAAY;GAC5B,MAAM,qBAAqB,IAAI,IAAI,QAAQ,kBAAkB;GAC7D,KAAK,MAAM,cAAc,aACvB,mBAAmB,IAAI,WAAW,MAAM,UAAU;GAEpD,OAAO;IAAE,GAAG;IAAS;GAAmB;EAC1C,CAAC;CACL;AACF;AAEA,MAAM,2BACJ,OACA,UACY;CACZ,IAAI,MAAM,MAAM,SAAS,0BACvB,OAAO;CAET,MAAM,WAAY,MAAM,MAAM,QAA8C;CAC5E,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,mBAAmB,KAAA,KAAa,SAAS,mBAAmB,MAAM,gBAC1E,OAAO;CAET,OAAO,MAAM,cAAc,KAAA,KAAa,SAAS,cAAc,MAAM;AACvE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sink-registry-CFC6xjsN.js","names":[],"sources":["../src/services/live-event-bus.ts","../src/services/sink-checkpoint-store.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/** 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}\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 return makeLiveBus(pubsub, activeTurnReplay);\n }),\n );\n}\n\nconst makeLiveBus = (\n pubsub: PubSub.PubSub<PositionedEvent>,\n activeTurnReplay: Ref.Ref<ActiveTurnEphemeralReplay>,\n): LiveEventBusShape => ({\n publish: (event) =>\n updateActiveTurnReplay(activeTurnReplay, event).pipe(\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});\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 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","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\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 Schedule from \"effect/Schedule\";\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/** At-least-once sink definition backed by a durable checkpoint. */\nexport interface EDADurableSinkDefinition {\n readonly interests?: ReadonlyArray<EventType | string>;\n readonly batchSize?: number;\n readonly process: (\n batch: EDASinkDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, unknown>;\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, unknown>;\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. Durable callbacks are\n * retried before the sink checkpoint advances; ephemeral callbacks are best-effort\n * and are only processed after the durable prefix at their anchor sequence has\n * 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 maxDurableSinkRetryDelay = Duration.seconds(5);\nconst sinkCheckpointFormatVersion = 1;\nconst durableSinkRetrySchedule = Schedule.exponential(\"100 millis\").pipe(\n Schedule.jittered,\n Schedule.modifyDelay(({ duration }) =>\n Effect.succeed(Duration.min(duration, maxDurableSinkRetryDelay)),\n ),\n);\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 yield* durable.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 if (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 processDurableBatchWithRetry = (events: ReadonlyArray<CommittedDurableEvent>) =>\n keepAlive.withActiveWork(\n `sink:${sink.name}`,\n processDurableBatch(events).pipe(\n Effect.tapError((error) =>\n Effect.logWarning(\"EDA sink durable projection failed; retrying\", {\n error: formatSinkError(error),\n sink: sink.name,\n }),\n ),\n Effect.retry(durableSinkRetrySchedule),\n ),\n );\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* processDurableBatchWithRetry(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* processDurableBatchWithRetry([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 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\nconst formatSinkError = (error: unknown): string => {\n if (Cause.isUnknownError(error)) {\n return `${error.message ?? error._tag}: ${formatSinkError(error.cause)}`;\n }\n return error instanceof Error ? error.message : String(error);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,oCAAoC;;AAuBjD,IAAa,eAAb,MAAa,qBAAqB,QAAQ,QAAyC,EACjF,oCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,cACA,OAAO,IAAI,aAAa;EAStB,OAAO,YAAY,OARG,OAAO,eAC3B,OAAO,UAA2B,GAClC,OAAO,QACT,GAK2B,OAJK,IAAI,KAAgC;GAClE,QAAQ,CAAC;GACT,YAAY;EACd,CAAC,CAC0C;CAC7C,CAAC,CACH;AACF;AAEA,MAAM,eACJ,QACA,sBACuB;CACvB,UAAU,UACR,uBAAuB,kBAAkB,KAAK,EAAE,KAC9C,OAAO,QAAQ,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAC9C;CACF,sBAAsB,OAAO,UAAU,MAAM;CAC7C,iBACE,OAAO,IAAI,OAAO,UAAU,MAAM,IAAI,iBACpC,OAAO,iBAAiB,OAAO,KAAK,YAAY,CAAC,CACnD;CACF,wBAAwB,IAAI,IAAI,gBAAgB;AAClD;AAEA,MAAM,0BACJ,KACA,UACwB,IA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,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;AAEvF,MAAM,mBAAmB,UAA2B;CAClD,IAAI,MAAM,eAAe,KAAK,GAC5B,OAAO,GAAG,MAAM,WAAW,MAAM,KAAK,IAAI,gBAAgB,MAAM,KAAK;CAEvE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
@@ -1,65 +0,0 @@
1
- # 001 — No Tools
2
-
3
- The smallest useful EDA host: one Durable Object-backed session, no tools, and a tiny HTTP facade.
4
-
5
- ## What to notice
6
-
7
- This example exists to make the baseline durable-agent flow obvious:
8
-
9
- ```text
10
- POST /sessions/:sessionId/messages
11
- -> SubmitMessageCommand
12
- -> effect-durable-agent/CommandAdmitted
13
- -> model runs
14
- -> effect-durable-agent/AssistantMessageCommitted
15
- ```
16
-
17
- The app code does not save a final chat array by hand. It submits a command. EDA admits that command durably before execution starts, owns the run/turn/message lifecycle, and exposes durable messages afterward.
18
-
19
- ## Files
20
-
21
- - `worker.ts` — concrete Durable Object subclass plus a minimal HTTP route.
22
- - `../_shared/*` — boring example plumbing shared by later examples.
23
-
24
- This example intentionally stays free of custom reducers, app events, tools, and sinks. Those appear in later examples.
25
-
26
- ## HTTP facade
27
-
28
- - `POST /sessions/:sessionId/messages`
29
- - body: `{ "text": "hello", "idempotencyKey": "optional-retry-key" }`
30
- - returns immediately after durable admission
31
- - `GET /sessions/:sessionId/messages`
32
- - returns durable user/assistant messages in committed order
33
-
34
- `sessionId` must be a UUIDv7 because EDA validates lifecycle ids at ingress.
35
-
36
- ## Wrangler binding sketch
37
-
38
- ```jsonc
39
- {
40
- "main": "./examples/001-no-tools/worker.ts",
41
- "durable_objects": {
42
- "bindings": [
43
- {
44
- "class_name": "NoToolsEDASession",
45
- "name": "NoToolsEDASession"
46
- }
47
- ]
48
- },
49
- "migrations": [
50
- {
51
- "new_sqlite_classes": ["NoToolsEDASession"],
52
- "tag": "eda-no-tools-v1"
53
- }
54
- ]
55
- }
56
- ```
57
-
58
- ## Example request
59
-
60
- ```bash
61
- curl -X POST \
62
- http://localhost:8787/sessions/018f6bd5-2f2a-7b1e-8f1a-1f2e3d4c5b6a/messages \
63
- -H 'content-type: application/json' \
64
- -d '{"text":"Say pong in one sentence.","idempotencyKey":"demo-message-1"}'
65
- ```
@@ -1,79 +0,0 @@
1
- import * as Prompt from "effect/unstable/ai/Prompt";
2
-
3
- import { CommandIdempotencyKey, SubmitMessageCommand } from "../../src/types/commands";
4
- import { SessionId } from "../../src/types/core";
5
- import { makeRootEDATraceMetadata } from "../../src/types/tracing";
6
- import {
7
- EDASessionDurableObject,
8
- getEDASessionDurableObjectByName,
9
- } from "../../src/host/durable-object";
10
- import { json, parseJsonObject, pathParam, requiredString } from "../_shared/http";
11
- import { makeExampleOpenAiOptions, type ExampleOpenAiEnv } from "../_shared/openai";
12
-
13
- /** Bindings used by the no-tools EDA example Worker. */
14
- export interface NoToolsEDAEnv extends ExampleOpenAiEnv {
15
- readonly NoToolsEDASession: DurableObjectNamespace<NoToolsEDASession>;
16
- }
17
-
18
- /** Concrete no-tools session object; register this subclass, never the EDA base class. */
19
- export class NoToolsEDASession extends EDASessionDurableObject<NoToolsEDAEnv> {
20
- constructor(ctx: DurableObjectState, env: NoToolsEDAEnv) {
21
- super(ctx, env, makeExampleOpenAiOptions(env));
22
- }
23
- }
24
-
25
- /**
26
- * Tiny HTTP facade for the baseline example.
27
- *
28
- * The important line is `session.submit(...)`: the user message becomes a
29
- * durable `CommandAdmitted` fact before model execution begins.
30
- */
31
- export default {
32
- async fetch(request, env): Promise<Response> {
33
- const url = new URL(request.url);
34
- const rawSessionId = pathParam(url.pathname, /^\/sessions\/([^/]+)\/messages\/?$/);
35
- if (rawSessionId === null) {
36
- return json({ error: "Use /sessions/:sessionId/messages" }, 404);
37
- }
38
-
39
- const sessionId = SessionId.make(rawSessionId);
40
- const session = getEDASessionDurableObjectByName(env.NoToolsEDASession, sessionId);
41
-
42
- if (request.method === "GET") {
43
- return json(await session.messages({ sessionId, trace: makeRootEDATraceMetadata() }));
44
- }
45
-
46
- if (request.method !== "POST") {
47
- return json({ error: "Method not allowed" }, 405);
48
- }
49
-
50
- const body = await parseJsonObject(request);
51
- const text = requiredString(body, "text");
52
- if (text === undefined) {
53
- return json({ error: 'Expected JSON body: { "text": "..." }' }, 400);
54
- }
55
-
56
- const idempotencyKey =
57
- requiredString(body, "idempotencyKey") ?? `http:message:${crypto.randomUUID()}`;
58
- const admitted = await session.submit({
59
- command: new SubmitMessageCommand({
60
- idempotencyKey: CommandIdempotencyKey.make(idempotencyKey),
61
- disposition: "queue",
62
- content: [Prompt.textPart({ text })],
63
- }),
64
- sessionId,
65
- trace: makeRootEDATraceMetadata(),
66
- });
67
-
68
- return json(
69
- {
70
- admitted,
71
- messages: await session.messages({ sessionId, trace: makeRootEDATraceMetadata() }),
72
- },
73
- 202,
74
- );
75
- },
76
- } satisfies ExportedHandler<NoToolsEDAEnv>;
77
-
78
- // Session ids are externally supplied in this tiny example. They must be UUIDv7
79
- // because EDA validates lifecycle ids at ingress.
@@ -1,134 +0,0 @@
1
- # 002 — Slack Bridge
2
-
3
- A focused example of EDA’s end-to-end durability story:
4
-
5
- ```text
6
- Slack webhook retry
7
- -> idempotent EDA command admission
8
- -> Slack metadata committed in the same durable batch
9
- -> framework + app reducers derive the bridge state
10
- -> assistant message commits durably
11
- -> durable sink posts the Slack reply
12
- -> SlackReplyDelivered is staged back into the same session log
13
- ```
14
-
15
- The point is not Slack specifically. The point is that EDA gives you one ordered state-machine history for ingress, agent execution, app metadata, sink delivery, retries, and multi-client sync.
16
-
17
- ## What to notice
18
-
19
- ### 1. Ingress is one durable batch
20
-
21
- `worker.ts` submits the model command and Slack metadata together:
22
-
23
- ```ts
24
- const idempotencyKey = CommandIdempotencyKey.make(`slack:event:${slackEventId}`);
25
-
26
- await session.submitBatch({
27
- sessionId,
28
- items: [
29
- new SubmitMessageCommand({
30
- idempotencyKey,
31
- disposition: "queue",
32
- content: [Prompt.textPart({ text })],
33
- }),
34
- SlackEvents.messageReceived({
35
- relatedCommandIdempotencyKey: idempotencyKey,
36
- teamId,
37
- channelId,
38
- threadTs,
39
- slackEventId,
40
- slackUserId,
41
- text,
42
- sessionId,
43
- eventId,
44
- createdAtMs,
45
- }),
46
- ],
47
- });
48
- ```
49
-
50
- If the process crashes after this commit, both the EDA command and the Slack metadata survive. If Slack retries the webhook, the same idempotency key identifies the same ingress fact.
51
-
52
- ### 2. The reducer reads framework events and app events
53
-
54
- `reducer.ts` is the heart of the example. It derives mappings across both event families:
55
-
56
- ```text
57
- SlackMessageReceived.relatedCommandIdempotencyKey
58
- -> CommandAdmitted.command.commandId
59
- -> UserMessageCommitted.messageId
60
- -> RunStarted.commandIds
61
- -> AssistantMessageCommitted.messageId
62
- -> SlackReplyDelivered.slackMessageTs
63
- ```
64
-
65
- This is the pattern you want in real integrations: do not hide correlation state in callback-local variables. Put the durable facts in the log and derive the bridge state with a pure reducer.
66
-
67
- ### 3. The sink is reliable and idempotent
68
-
69
- `sinks.ts` watches for `AssistantMessageCommitted`. It uses reducer state to find the Slack thread, posts a reply with a deterministic outbound idempotency key, and stages `SlackReplyDelivered` only after the send succeeds.
70
-
71
- If posting fails, the sink cursor does not advance and EDA retries. If posting succeeds but the worker dies before the delivery event commits, the deterministic outbound key lets the retry collapse into one Slack-visible reply.
72
-
73
- ### 4. Multi-client sync is a free consequence
74
-
75
- A browser transcript, an internal support console, and the Slack bridge are all consuming projections over the same ordered sequence. Render through `seq = N`, request `events > N`, and converge.
76
-
77
- ## Files
78
-
79
- - `events.ts` — Slack durable event schemas and constructors.
80
- - `reducer.ts` — pure bridge projection over framework + Slack events.
81
- - `sinks.ts` — durable Slack reply sink with at-least-once retry semantics.
82
- - `scenario.test.ts` — executable scenarios for reducer correlation and sink retry.
83
- - `worker.ts` — minimal Cloudflare Worker/Durable Object facade.
84
-
85
- ## Example event sequence
86
-
87
- ```text
88
- seq event why it matters
89
- --- ----------------------------------------- -----------------------------------------
90
- 1 effect-durable-agent/CommandAdmitted idempotent model ingress
91
- 2 example.slack/SlackMessageReceived Slack identity committed beside command
92
- 3 effect-durable-agent/UserMessageCommitted durable user transcript
93
- 4 effect-durable-agent/RunStarted links command ids to a run
94
- 5 effect-durable-agent/AssistantMessageCommitted final answer is durable
95
- 6 example.slack/SlackReplyDelivered outbound delivery is durable too
96
- ```
97
-
98
- ## Wrangler binding sketch
99
-
100
- ```jsonc
101
- {
102
- "main": "./examples/002-slack-bridge/worker.ts",
103
- "durable_objects": {
104
- "bindings": [
105
- {
106
- "class_name": "SlackBridgeEDASession",
107
- "name": "SlackBridgeEDASession"
108
- }
109
- ]
110
- },
111
- "migrations": [
112
- {
113
- "new_sqlite_classes": ["SlackBridgeEDASession"],
114
- "tag": "eda-slack-bridge-v1"
115
- }
116
- ]
117
- }
118
- ```
119
-
120
- ## Example request
121
-
122
- ```bash
123
- curl -X POST \
124
- http://localhost:8787/sessions/018f6bd5-2f2a-7b1e-8f1a-1f2e3d4c5b6a/slack/events \
125
- -H 'content-type: application/json' \
126
- -d '{
127
- "teamId":"T1",
128
- "channelId":"C1",
129
- "threadTs":"1729.000",
130
- "slackEventId":"Ev123",
131
- "slackUserId":"U1",
132
- "text":"Please summarize this incident."
133
- }'
134
- ```