effect-durable-agent 0.1.0-alpha.8 → 0.1.0

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 (173) hide show
  1. package/README.md +5 -5
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/{commands-Ce1ec6kH.d.ts → commands-BUquEZVP.d.ts} +31 -12
  5. package/dist/{compaction-BgDr5VJy.js → compaction-63iEDHHl.js} +63 -13
  6. package/dist/compaction-63iEDHHl.js.map +1 -0
  7. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-Bezx3drD.d.ts} +16 -40
  8. package/dist/{core-CYT6DBaS.d.ts → core-BcimKMIv.d.ts} +5 -3
  9. package/dist/delivery-2ZILvoRD.js +507 -0
  10. package/dist/delivery-2ZILvoRD.js.map +1 -0
  11. package/dist/delivery-D3MxW4wg.d.ts +3026 -0
  12. package/dist/domain/command-queues.d.ts +81 -2
  13. package/dist/domain/command-queues.js +1 -1
  14. package/dist/domain/command-queues.js.map +1 -1
  15. package/dist/domain/context-projection.d.ts +1 -1
  16. package/dist/domain/context-projection.js +1 -1
  17. package/dist/domain/context-projection.js.map +1 -1
  18. package/dist/domain/message-transcript.d.ts +36 -2
  19. package/dist/domain/message-transcript.js +10 -2
  20. package/dist/domain/message-transcript.js.map +1 -1
  21. package/dist/domain/model-usage.d.ts +1 -1
  22. package/dist/domain/model-usage.js +1 -1
  23. package/dist/domain/reduced-state-schema.d.ts +3 -992
  24. package/dist/domain/reduced-state-schema.js +126 -7
  25. package/dist/domain/reduced-state-schema.js.map +1 -1
  26. package/dist/domain/reduced-state.d.ts +2 -2
  27. package/dist/domain/reduced-state.js +936 -2
  28. package/dist/domain/reduced-state.js.map +1 -0
  29. package/dist/domain/run-scheduling.d.ts +2 -0
  30. package/dist/domain/run-scheduling.js +127 -0
  31. package/dist/domain/run-scheduling.js.map +1 -0
  32. package/dist/{durable-br2C1bWK.d.ts → durable-168Womqp.d.ts} +8535 -2859
  33. package/dist/{durable-BGFvX7Mh.js → durable-D13w1Qr3.js} +229 -15
  34. package/dist/durable-D13w1Qr3.js.map +1 -0
  35. package/dist/{envelope-DxQzo5rN.js → envelope-BCzKUq_z.js} +12 -3
  36. package/dist/envelope-BCzKUq_z.js.map +1 -0
  37. package/dist/{envelope-DkZyMIgp.d.ts → envelope-Che6KatU.d.ts} +70 -7
  38. package/dist/{event-factory-DTFdy0Cb.js → event-factory-_vF1bIJ7.js} +7 -3
  39. package/dist/event-factory-_vF1bIJ7.js.map +1 -0
  40. package/dist/{events-LZFNoESe.d.ts → events-DwTARLMv.d.ts} +139 -137
  41. package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
  42. package/dist/in-memory-CeODnZhE.js +150 -0
  43. package/dist/in-memory-CeODnZhE.js.map +1 -0
  44. package/dist/index.d.ts +8 -8
  45. package/dist/index.js +6 -6
  46. package/dist/interpreter-DKGJ1sSx.js +1452 -0
  47. package/dist/interpreter-DKGJ1sSx.js.map +1 -0
  48. package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
  49. package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-DeBDK8XO.d.ts} +11 -5
  50. package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-0GeHwaaU.d.ts} +2 -3
  51. package/dist/records--54mZEBx.js +675 -0
  52. package/dist/records--54mZEBx.js.map +1 -0
  53. package/dist/reduced-state-B1cvy8N_.d.ts +51110 -0
  54. package/dist/reduced-state-schema-B98exWxQ.d.ts +2338 -0
  55. package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-DhGVzHBV.d.ts} +12 -6
  56. package/dist/run-scheduling-wakeup-Mjic4tb_.d.ts +24 -0
  57. package/dist/services/compaction.d.ts +2 -2
  58. package/dist/services/compaction.js +2 -2
  59. package/dist/services/id-generator.d.ts +1 -1
  60. package/dist/services/id-generator.js +6 -12
  61. package/dist/services/id-generator.js.map +1 -1
  62. package/dist/services/keep-alive.d.ts +1 -1
  63. package/dist/services/keep-alive.js.map +1 -1
  64. package/dist/services/model-call.d.ts +15 -0
  65. package/dist/services/model-call.js +15 -0
  66. package/dist/services/model-call.js.map +1 -0
  67. package/dist/services/model-resolver.d.ts +1 -1
  68. package/dist/services/model-resolver.js +1 -1
  69. package/dist/services/model-resolver.js.map +1 -1
  70. package/dist/services/prompt-projector.d.ts +2 -2
  71. package/dist/services/prompt-projector.js +49 -5
  72. package/dist/services/prompt-projector.js.map +1 -1
  73. package/dist/services/reducer-registry.d.ts +1 -1
  74. package/dist/services/reducer-registry.js +19 -6
  75. package/dist/services/reducer-registry.js.map +1 -1
  76. package/dist/services/run-scheduler.d.ts +2 -0
  77. package/dist/services/run-scheduler.js +25 -0
  78. package/dist/services/run-scheduler.js.map +1 -0
  79. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  80. package/dist/services/run-scheduling-wakeup.js +13 -0
  81. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  82. package/dist/services/runtime-layer.d.ts +18 -31
  83. package/dist/services/runtime-layer.js +19 -13
  84. package/dist/services/runtime-layer.js.map +1 -1
  85. package/dist/services/runtime.d.ts +1 -1
  86. package/dist/services/runtime.js +31 -20
  87. package/dist/services/runtime.js.map +1 -1
  88. package/dist/services/session-event-observer.d.ts +1 -1
  89. package/dist/services/session-event-observer.js.map +1 -1
  90. package/dist/services/session-query.d.ts +1 -1
  91. package/dist/services/session-query.js +57 -10
  92. package/dist/services/session-query.js.map +1 -1
  93. package/dist/services/session-state.d.ts +1 -1
  94. package/dist/services/session-state.js +1 -1
  95. package/dist/services/session-store.d.ts +2 -2
  96. package/dist/services/session-store.js +127 -37
  97. package/dist/services/session-store.js.map +1 -1
  98. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  99. package/dist/services/sink-checkpoint-store.js +2 -1
  100. package/dist/services/sink-checkpoint-store.js.map +1 -1
  101. package/dist/services/sink-registry.d.ts +2 -2
  102. package/dist/services/sink-registry.js +1 -1
  103. package/dist/services/span-names.d.ts +1 -1
  104. package/dist/services/span-names.js +6 -1
  105. package/dist/services/span-names.js.map +1 -1
  106. package/dist/services/tool-registry.d.ts +2 -2
  107. package/dist/services/tool-registry.js +12 -3
  108. package/dist/services/tool-registry.js.map +1 -1
  109. package/dist/services/tracing.d.ts +3 -3
  110. package/dist/services/tracing.js +2 -2
  111. package/dist/services/tracing.js.map +1 -1
  112. package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-DlP9ITB2.d.ts} +3 -3
  113. package/dist/{session-state-aIqe9CLa.js → session-state-BehvUVyq.js} +669 -160
  114. package/dist/session-state-BehvUVyq.js.map +1 -0
  115. package/dist/session-store-BL6sfrnn.d.ts +3326 -0
  116. package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-DvuHwvx_.d.ts} +3 -4
  117. package/dist/sink-registry-DskRcyOS.js +345 -0
  118. package/dist/sink-registry-DskRcyOS.js.map +1 -0
  119. package/dist/subscription-DZNWFDTV.d.ts +966 -0
  120. package/dist/subscription-DmO3BcdT.js +505 -0
  121. package/dist/subscription-DmO3BcdT.js.map +1 -0
  122. package/dist/testkit/layers.d.ts +31 -22
  123. package/dist/testkit/layers.js +23 -14
  124. package/dist/testkit/layers.js.map +1 -1
  125. package/dist/testkit/transcript.d.ts +226 -0
  126. package/dist/testkit/transcript.js +1475 -0
  127. package/dist/testkit/transcript.js.map +1 -0
  128. package/dist/{tool-registry-BJaVNtw4.d.ts → tool-registry-CHHUU9BN.d.ts} +44 -8
  129. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  130. package/dist/transcript.d.ts +101 -0
  131. package/dist/transcript.js +107 -0
  132. package/dist/transcript.js.map +1 -0
  133. package/dist/types/commands.d.ts +2 -2
  134. package/dist/types/commands.js +8 -3
  135. package/dist/types/commands.js.map +1 -1
  136. package/dist/types/core.d.ts +2 -2
  137. package/dist/types/core.js +3 -1
  138. package/dist/types/core.js.map +1 -1
  139. package/dist/types/events/durable.d.ts +2 -2
  140. package/dist/types/events/durable.js +2 -2
  141. package/dist/types/events.d.ts +5 -5
  142. package/dist/types/events.js +3 -3
  143. package/dist/types/tracing.d.ts +1 -1
  144. package/dist/types/tracing.js.map +1 -1
  145. package/dist/websocket/events.d.ts +2 -0
  146. package/dist/websocket/events.js +2 -0
  147. package/dist/websocket.d.ts +2123 -2552
  148. package/dist/websocket.js +628 -442
  149. package/dist/websocket.js.map +1 -1
  150. package/dist/window-read-Brov9VdQ.d.ts +113 -0
  151. package/dist/window-read-DPFAA1hM.js +264 -0
  152. package/dist/window-read-DPFAA1hM.js.map +1 -0
  153. package/package.json +42 -14
  154. package/dist/command-queues-DdDB_aYM.d.ts +0 -462
  155. package/dist/compaction-BEor3jKv.d.ts +0 -165
  156. package/dist/compaction-BgDr5VJy.js.map +0 -1
  157. package/dist/durable-BGFvX7Mh.js.map +0 -1
  158. package/dist/envelope-DxQzo5rN.js.map +0 -1
  159. package/dist/event-factory-DTFdy0Cb.js.map +0 -1
  160. package/dist/event-factory-pFzsPlDs.d.ts +0 -87
  161. package/dist/index-BVVgDSdq.d.ts +0 -1
  162. package/dist/message-transcript-DQNlzxle.d.ts +0 -32
  163. package/dist/prompt-projector-f4ElyXCE.d.ts +0 -39
  164. package/dist/reduced-state-DF0-6mbR.js +0 -921
  165. package/dist/reduced-state-DF0-6mbR.js.map +0 -1
  166. package/dist/runtime-DbTCb32-.d.ts +0 -63
  167. package/dist/session-query-l8xpJYp8.d.ts +0 -45
  168. package/dist/session-state-YHFzOGDf.d.ts +0 -861
  169. package/dist/session-state-aIqe9CLa.js.map +0 -1
  170. package/dist/session-store-Cpi_NwTR.d.ts +0 -206
  171. package/dist/sink-registry-NDgeyzO0.js +0 -272
  172. package/dist/sink-registry-NDgeyzO0.js.map +0 -1
  173. package/dist/sink-registry-T1wOUuzq.d.ts +0 -133
@@ -1,7 +1,11 @@
1
1
  import { CommandId, DurablePosition, SequenceNumber, durablePosition } from "../types/core.js";
2
- import { t as DurableEventEnvelope } from "../envelope-DxQzo5rN.js";
3
- import { Dn as contextRebasedEventType, Gn as summaryCreatedEventType, _n as commandAdmittedEventType } from "../durable-BGFvX7Mh.js";
2
+ import { t as DurableEventEnvelope } from "../envelope-BCzKUq_z.js";
3
+ import { H as DecodedDurableEvent, Nn as commandAdmittedEventType, Un as contextRebasedEventType, Wn as decodeDurableEventSync, kr as decodeRetainingExcess, mr as summaryCreatedEventType, qn as durableEventEnvelope } from "../durable-D13w1Qr3.js";
4
4
  import { CompactionSummaryArtifact } from "../domain/context-projection.js";
5
+ import { m as makeTranscriptDefinition, p as emptyTranscriptMappings } from "../interpreter-DKGJ1sSx.js";
6
+ import { T as TranscriptLogIncarnation } from "../records--54mZEBx.js";
7
+ import { a as maintainTranscripts, i as initialTranscriptState, r as inMemoryTranscriptWindowSource } from "../in-memory-CeODnZhE.js";
8
+ import { a as EDATranscriptStore, n as inactiveTranscriptWindow, r as readTranscriptWindowFrom } from "../window-read-DPFAA1hM.js";
5
9
  import * as Context from "effect/Context";
6
10
  import * as Effect from "effect/Effect";
7
11
  import * as Layer from "effect/Layer";
@@ -9,11 +13,16 @@ import * as Schema from "effect/Schema";
9
13
  import * as Stream from "effect/Stream";
10
14
  import * as Cause from "effect/Cause";
11
15
  import * as Ref from "effect/Ref";
16
+ import * as Result from "effect/Result";
17
+ import * as SchemaGetter from "effect/SchemaGetter";
12
18
  //#region src/services/session-store.ts
13
19
  /** A durable event after the store has assigned its replay position. */
14
20
  const CommittedDurableEvent = Schema.Struct({
15
21
  position: DurablePosition,
16
- event: DurableEventEnvelope
22
+ event: DurableEventEnvelope.pipe(Schema.decodeTo(Schema.declare(Schema.is(DecodedDurableEvent)), {
23
+ decode: SchemaGetter.transform(decodeDurableEventSync),
24
+ encode: SchemaGetter.transform(durableEventEnvelope)
25
+ }))
17
26
  });
18
27
  /**
19
28
  * Store-level failure surfaced by durable append, replay, and hydration APIs.
@@ -22,7 +31,7 @@ const CommittedDurableEvent = Schema.Struct({
22
31
  * framework services can treat SQL-backed hosts, in-memory tests, and future adapters
23
32
  * as the same durability boundary.
24
33
  */
25
- var EDASessionStoreError = class extends Schema.TaggedErrorClass()("EDASessionStoreError", { message: Schema.String }) {};
34
+ var EDASessionStoreError = class extends Schema.TaggedError()("EDASessionStoreError", { message: Schema.String }) {};
26
35
  /** True when a Cause contains an escaped durable-store failure. */
27
36
  const hasEDASessionStoreError = (cause) => cause.reasons.some((reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError);
28
37
  /**
@@ -52,36 +61,39 @@ const FindCommandAdmissionInput = Schema.Struct({
52
61
  * adapters own physical tables and synchronous transaction mechanics; callers
53
62
  * only express durable append/replay/lookup intent.
54
63
  */
55
- var EDASessionStore = class EDASessionStore extends Context.Service()("@effect-durable-agent/EDASessionStore") {
56
- /** Deterministic in-memory implementation used by runtime and recovery tests. */
57
- static InMemory = (sessionId) => Layer.effect(EDASessionStore, Effect.gen(function* () {
58
- return makeInMemoryStore(sessionId, yield* Ref.make(emptyInMemoryStoreData()));
59
- }));
60
- /** In-memory store seeded with a durable prefix; intended for recovery tests. */
61
- static InMemorySeeded = (sessionId, events) => Layer.effect(EDASessionStore, Effect.gen(function* () {
62
- const committed = seedCommittedEvents(sessionId, events);
63
- return makeInMemoryStore(sessionId, yield* Ref.make({
64
- ...emptyInMemoryStoreData(),
65
- committed,
66
- summaries: summariesFromCommittedEvents(committed)
67
- }));
68
- }));
64
+ var EDASessionStore = class extends Context.Service()("@effect-durable-agent/EDASessionStore") {
65
+ /**
66
+ * Deterministic in-memory implementation used by runtime and recovery tests.
67
+ *
68
+ * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append
69
+ * critical section. Without `options.transcript` it maintains the definition with no host
70
+ * mappings.
71
+ */
72
+ static InMemory = (sessionId, options) => inMemoryStoreLayer(sessionId, () => [], options);
73
+ /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */
74
+ static InMemorySeeded = (sessionId, events, options) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);
69
75
  };
70
- const emptyInMemoryStoreData = () => ({
71
- committed: [],
72
- summaries: /* @__PURE__ */ new Map(),
73
- reducerCheckpoints: /* @__PURE__ */ new Map()
74
- });
76
+ const inMemoryStoreLayer = (sessionId, seed, options) => Layer.effectContext(Effect.gen(function* () {
77
+ const committed = seed();
78
+ const config = options?.transcript ?? { current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie) };
79
+ const data = yield* Ref.make({
80
+ committed,
81
+ summaries: summariesFromCommittedEvents(committed),
82
+ reducerCheckpoints: /* @__PURE__ */ new Map(),
83
+ transcript: initialTranscriptState(TranscriptLogIncarnation.make(`memory:${sessionId}`), config, committed)
84
+ });
85
+ return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)));
86
+ }));
75
87
  const seedCommittedEvents = (sessionId, events) => {
76
88
  const seen = /* @__PURE__ */ new Set();
77
89
  return events.map((event, index) => {
78
90
  if (event.sessionId !== sessionId) throw new Error(`EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`);
79
91
  if (seen.has(event.eventId)) throw new Error(`Duplicate seed eventId ${event.eventId}`);
80
92
  seen.add(event.eventId);
81
- return CommittedDurableEvent.make({
93
+ return {
82
94
  position: durablePosition(SequenceNumber.make(index + 1)),
83
- event
84
- });
95
+ event: decodeDurableEventSync(DurableEventEnvelope.make(event))
96
+ };
85
97
  });
86
98
  };
87
99
  const summariesFromCommittedEvents = (events) => {
@@ -90,7 +102,7 @@ const summariesFromCommittedEvents = (events) => {
90
102
  if (event.type !== summaryCreatedEventType) continue;
91
103
  const payload = event.payload;
92
104
  if (payload.summary !== void 0) {
93
- const summary = CompactionSummaryArtifact.make(payload.summary);
105
+ const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
94
106
  summaries.set(summary.summaryId, summary);
95
107
  }
96
108
  }
@@ -113,6 +125,7 @@ const makeInMemoryStore = (sessionId, data) => {
113
125
  const nextEntries = [...current.committed];
114
126
  const nextSummaries = new Map(current.summaries);
115
127
  const committedEvents = [];
128
+ const appended = [];
116
129
  for (const entry of batch.entries) {
117
130
  const { event } = entry;
118
131
  const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);
@@ -120,28 +133,30 @@ const makeInMemoryStore = (sessionId, data) => {
120
133
  committedEvents.push(existing);
121
134
  continue;
122
135
  }
123
- const committed = CommittedDurableEvent.make({
136
+ const committed = {
124
137
  position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),
125
- event
126
- });
138
+ event: decodeDurableEventSync(DurableEventEnvelope.make(event))
139
+ };
127
140
  nextEntries.push(committed);
128
141
  committedEvents.push(committed);
129
- if (event.type === summaryCreatedEventType) {
130
- const payload = event.payload;
142
+ appended.push(committed);
143
+ if (committed.event.type === summaryCreatedEventType) {
144
+ const payload = committed.event.payload;
131
145
  if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
132
- const summary = CompactionSummaryArtifact.make(payload.summary);
146
+ const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
133
147
  if (payload.summaryId !== void 0 && summary.summaryId !== payload.summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
134
148
  nextSummaries.set(summary.summaryId, summary);
135
149
  }
136
- if (event.type === contextRebasedEventType) {
137
- const payload = event.payload;
150
+ if (committed.event.type === contextRebasedEventType) {
151
+ const payload = committed.event.payload;
138
152
  if (payload.summaryId === void 0 || !nextSummaries.has(payload.summaryId)) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
139
153
  }
140
154
  }
141
155
  return [committedEvents, {
142
156
  committed: nextEntries,
143
157
  summaries: nextSummaries,
144
- reducerCheckpoints: current.reducerCheckpoints
158
+ reducerCheckpoints: current.reducerCheckpoints,
159
+ transcript: appended.length === 0 ? current.transcript : maintainTranscripts(current.transcript, appended)
145
160
  }];
146
161
  });
147
162
  });
@@ -169,6 +184,17 @@ const makeInMemoryStore = (sessionId, data) => {
169
184
  })
170
185
  };
171
186
  };
187
+ /** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */
188
+ const makeInMemoryTranscriptStore = (data) => ({
189
+ readTranscriptWindow: (selector, limits) => Effect.gen(function* () {
190
+ const { transcript } = yield* Ref.get(data);
191
+ const source = inMemoryTranscriptWindowSource(transcript);
192
+ if (source === void 0) return inactiveTranscriptWindow(transcript.incarnation, transcript.config.current.version, transcript.versions.find((version) => version.meta.role === "building")?.meta);
193
+ const window = readTranscriptWindowFrom(source, selector, limits);
194
+ return Result.isSuccess(window) ? window.success : yield* window.failure;
195
+ }),
196
+ readTranscriptMeta: Ref.get(data).pipe(Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)))
197
+ });
172
198
  const commandAdmissionMatches = (entry, input) => {
173
199
  if (entry.event.type !== commandAdmittedEventType) return false;
174
200
  const admitted = entry.event.payload.command;
@@ -176,7 +202,71 @@ const commandAdmissionMatches = (entry, input) => {
176
202
  if (input.idempotencyKey !== void 0 && admitted.idempotencyKey === input.idempotencyKey) return true;
177
203
  return input.commandId !== void 0 && admitted.commandId === input.commandId;
178
204
  };
205
+ const eventNamespaces = (ast) => {
206
+ if (ast._tag === "Union") return ast.types.flatMap(eventNamespaces);
207
+ if (ast._tag === "Objects") {
208
+ const namespace = ast.propertySignatures.find((field) => field.name === "namespace")?.type;
209
+ if (namespace?._tag === "Literal" && typeof namespace.literal === "string") return [namespace.literal];
210
+ }
211
+ throw new Error("App event schemas must be a union of structs with literal namespaces");
212
+ };
213
+ /** Attach the app decoder to every event-returning store operation without changing storage bytes. */
214
+ const registerAppEvents = (store, schema) => {
215
+ const namespaces = new Set(eventNamespaces(schema.ast));
216
+ const decode = decodeRetainingExcess(schema);
217
+ const envelopeKey = (event) => JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));
218
+ const decodeEntry = (entry, prepared) => {
219
+ if (entry.event.namespace !== "__foreign" || !namespaces.has(entry.event.envelope.namespace)) return entry;
220
+ return {
221
+ ...entry,
222
+ event: {
223
+ ...entry.event,
224
+ decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope)
225
+ }
226
+ };
227
+ };
228
+ const decodeEntryEffect = (entry) => Effect.try({
229
+ try: () => decodeEntry(entry),
230
+ catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
231
+ });
232
+ const decodeEntries = (entries) => Effect.forEach(entries, decodeEntryEffect);
233
+ return {
234
+ ...store,
235
+ append: (batch) => Effect.gen(function* () {
236
+ const prepared = yield* Effect.try({
237
+ try: () => {
238
+ const decoded = /* @__PURE__ */ new Map();
239
+ for (const { event } of batch.entries) {
240
+ if (!namespaces.has(event.namespace)) continue;
241
+ const key = envelopeKey(event);
242
+ if (!decoded.has(key)) decoded.set(key, decode(event));
243
+ }
244
+ return decoded;
245
+ },
246
+ catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
247
+ });
248
+ const committed = yield* store.append(batch);
249
+ return yield* Effect.forEach(committed, (entry) => Effect.try({
250
+ try: () => decodeEntry(entry, prepared),
251
+ catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
252
+ }));
253
+ }),
254
+ eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),
255
+ loadCommittedEventsBySeq: (seqs) => store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),
256
+ findCommandAdmission: (input) => store.findCommandAdmission(input).pipe(Effect.flatMap((entry) => entry === void 0 ? Effect.succeed(void 0) : decodeEntryEffect(entry)))
257
+ };
258
+ };
259
+ /** Narrow an already decoded fact from one schema, without decoding its payload again. */
260
+ const selectCommittedEvent = (schema, entry) => {
261
+ const event = entry.event.namespace === "__foreign" ? entry.event.decoded ?? entry.event.envelope : entry.event;
262
+ return Schema.is(schema)(event) ? {
263
+ position: entry.position,
264
+ event
265
+ } : void 0;
266
+ };
267
+ /** Typed journal read available to tools and application services without private SQL access. */
268
+ const queryCommittedEvents = (store, schema, options = {}) => store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(Stream.map((entry) => selectCommittedEvent(schema, entry)), Stream.filter((entry) => entry !== void 0), Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER), Stream.runCollect);
179
269
  //#endregion
180
- export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDASessionStore, EDASessionStoreError, FindCommandAdmissionInput, hasEDASessionStoreError };
270
+ export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDASessionStore, EDASessionStoreError, FindCommandAdmissionInput, hasEDASessionStoreError, queryCommittedEvents, registerAppEvents, selectCommittedEvent };
181
271
 
182
272
  //# sourceMappingURL=session-store.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { type CommandIdempotencyKey, type EDACommand } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope,\n});\nexport type CommittedDurableEvent = typeof CommittedDurableEvent.Type;\n\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedErrorClass<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /** Deterministic in-memory implementation used by runtime and recovery tests. */\n static readonly InMemory = (sessionId: SessionId) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const data = yield* Ref.make<InMemoryStoreData>(emptyInMemoryStoreData());\n return makeInMemoryStore(sessionId, data);\n }),\n );\n\n /** In-memory store seeded with a durable prefix; intended for recovery tests. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n ) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const committed = seedCommittedEvents(sessionId, events);\n const data = yield* Ref.make<InMemoryStoreData>({\n ...emptyInMemoryStoreData(),\n committed,\n summaries: summariesFromCommittedEvents(committed),\n });\n return makeInMemoryStore(sessionId, data);\n }),\n );\n}\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n}\n\nconst emptyInMemoryStoreData = (): InMemoryStoreData => ({\n committed: [],\n summaries: new Map(),\n reducerCheckpoints: new Map(),\n});\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(index + 1)),\n event,\n });\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload as { readonly summary?: unknown };\n if (payload.summary !== undefined) {\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed = CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event,\n });\n nextEntries.push(committed);\n committedEvents.push(committed);\n\n if (event.type === summaryCreatedEventType) {\n const payload = event.payload as {\n readonly summary?: unknown;\n readonly summaryId?: CompactionSummaryArtifact[\"summaryId\"];\n };\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (event.type === contextRebasedEventType) {\n const payload = event.payload as { readonly summaryId?: SummaryId };\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = (entry.event.payload as { readonly command?: EDACommand }).command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,wBAAwB,OAAO,OAAO;CACjD,UAAU;CACV,OAAO;AACT,CAAC;;;;;;;;AAUD,IAAa,uBAAb,cAA0C,OAAO,iBAAuC,EACtF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,EAAE,CAAC;;AAGH,MAAa,2BAA2B,UACtC,MAAM,QAAQ,MACX,WAAW,MAAM,aAAa,MAAM,KAAK,OAAO,iBAAiB,oBACpE;;;;;;;AAQF,MAAa,qBAAqB,OAAO,OAAO,EAC9C,OAAO,qBACT,CAAC;;;;;;;;AAUD,MAAa,qBAAqB,OAAO,OAAO,EAC9C,SAAS,OAAO,MAAM,kBAAkB,EAC1C,CAAC;;AAsBD,MAAa,4BAA4B,OAAO,OAAO;CACrD,WAAW,OAAO,YAAY,SAAS;CACvC,gBAAgB,OAAO,YAAY,OAAO,MAAM;AAClD,CAAC;;;;;;;;AAwDD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;;CAEA,OAAgB,YAAY,cAC1B,MAAM,OACJ,iBACA,OAAO,IAAI,aAAa;EAEtB,OAAO,kBAAkB,WAAW,OADhB,IAAI,KAAwB,uBAAuB,CAAC,CAChC;CAC1C,CAAC,CACH;;CAGF,OAAgB,kBACd,WACA,WAEA,MAAM,OACJ,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,YAAY,oBAAoB,WAAW,MAAM;EAMvD,OAAO,kBAAkB,WAAW,OALhB,IAAI,KAAwB;GAC9C,GAAG,uBAAuB;GAC1B;GACA,WAAW,6BAA6B,SAAS;EACnD,CAAC,CACuC;CAC1C,CAAC,CACH;AAC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AgB;GAC5B,MAAM,YAAY,IAAI,IAAI,KAAK,KAAK,QAAQ,OAAO,GAAG,CAAC,CAAC;GACxD,OAAO,UAAU,QAAQ,UAAU,UAAU,IAAI,OAAO,MAAM,SAAS,GAAG,CAAC,CAAC;EAC9E,CAAC,CACH;EACF,uBAAuB,UACrB,IAAI,IAAI,IAAI,EAAE,KACZ,OAAO,KAAK,EAAE,gBACZ,UAAU,MAAM,UAAU,wBAAwB,OAAO,KAAK,CAAC,CACjE,CACF;EACF,sBAAsB,cACpB,IAAI,IAAI,IAAI,EAAE,KAAK,OAAO,KAAK,EAAE,gBAAgB,UAAU,IAAI,SAAS,CAAC,CAAC;EAC5E,wBAAwB,SACtB,IAAI,IAAI,IAAI,EAAE,KAAK,OAAO,KAAK,EAAE,yBAAyB,mBAAmB,IAAI,IAAI,CAAC,CAAC;EACzF,wBAAwB,eACtB,IAAI,OAAO,OAAO,aAAa;GAC7B,GAAG;GACH,oBAAoB,IAAI,IAAI,QAAQ,kBAAkB,EAAE,IAAI,WAAW,MAAM,UAAU;EACzF,EAAE;EACJ,yBAAyB,gBACvB,IAAI,OAAO,OAAO,YAAY;GAC5B,MAAM,qBAAqB,IAAI,IAAI,QAAQ,kBAAkB;GAC7D,KAAK,MAAM,cAAc,aACvB,mBAAmB,IAAI,WAAW,MAAM,UAAU;GAEpD,OAAO;IAAE,GAAG;IAAS;GAAmB;EAC1C,CAAC;CACL;AACF;AAEA,MAAM,2BACJ,OACA,UACY;CACZ,IAAI,MAAM,MAAM,SAAS,0BACvB,OAAO;CAET,MAAM,WAAY,MAAM,MAAM,QAA8C;CAC5E,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,mBAAmB,KAAA,KAAa,SAAS,mBAAmB,MAAM,gBAC1E,OAAO;CAET,OAAO,MAAM,cAAc,KAAA,KAAa,SAAS,cAAc,MAAM;AACvE"}
1
+ {"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n DecodedDurableEvent,\n decodeDurableEventSync,\n durableEventEnvelope,\n} from \"../types/events/durable\";\n\nimport { type CommandIdempotencyKey } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport {\n initialTranscriptState,\n inMemoryTranscriptWindowSource,\n maintainTranscripts,\n type InMemoryTranscriptState,\n} from \"../transcript/in-memory\";\nimport { emptyTranscriptMappings, makeTranscriptDefinition } from \"../transcript/mapping\";\nimport { TranscriptLogIncarnation } from \"../transcript/records\";\nimport {\n EDATranscriptStore,\n type EDATranscriptStoreShape,\n type TranscriptMaintenanceConfig,\n} from \"../transcript/store\";\nimport { inactiveTranscriptWindow, readTranscriptWindowFrom } from \"../transcript/window-read\";\n\nexport type CommittedDurableEvent<E = DecodedDurableEvent> = {\n readonly position: typeof DurablePosition.Type;\n readonly event: E;\n};\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent: Schema.Codec<\n CommittedDurableEvent,\n {\n readonly position: typeof DurablePosition.Encoded;\n readonly event: typeof DurableEventEnvelope.Encoded;\n },\n never,\n never\n> = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope.pipe(\n Schema.decodeTo(Schema.declare<DecodedDurableEvent>(Schema.is(DecodedDurableEvent)), {\n decode: SchemaGetter.transform(decodeDurableEventSync),\n encode: SchemaGetter.transform(durableEventEnvelope),\n }),\n ),\n});\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedError<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /**\n * Deterministic in-memory implementation used by runtime and recovery tests.\n *\n * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append\n * critical section. Without `options.transcript` it maintains the definition with no host\n * mappings.\n */\n static readonly InMemory = (sessionId: SessionId, options?: InMemoryStoreOptions) =>\n inMemoryStoreLayer(sessionId, () => [], options);\n\n /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n options?: InMemoryStoreOptions,\n ) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);\n}\n\n/** Construction options for the in-memory store. */\nexport interface InMemoryStoreOptions {\n /** Transcript definitions to maintain; defaults to the definition with no host mappings. */\n readonly transcript?: TranscriptMaintenanceConfig;\n}\n\nconst inMemoryStoreLayer = (\n sessionId: SessionId,\n seed: () => ReadonlyArray<CommittedDurableEvent>,\n options: InMemoryStoreOptions | undefined,\n) =>\n Layer.effectContext(\n Effect.gen(function* () {\n const committed = seed();\n const config = options?.transcript ?? {\n current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie),\n };\n const data = yield* Ref.make<InMemoryStoreData>({\n committed,\n summaries: summariesFromCommittedEvents(committed),\n reducerCheckpoints: new Map(),\n transcript: initialTranscriptState(\n TranscriptLogIncarnation.make(`memory:${sessionId}`),\n config,\n committed,\n ),\n });\n return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(\n Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)),\n );\n }),\n );\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n readonly transcript: InMemoryTranscriptState;\n}\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return {\n position: durablePosition(SequenceNumber.make(index + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload;\n if (payload.summary !== undefined) {\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n const appended: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed: CommittedDurableEvent = {\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n nextEntries.push(committed);\n committedEvents.push(committed);\n appended.push(committed);\n\n if (committed.event.type === summaryCreatedEventType) {\n const payload = committed.event.payload;\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (committed.event.type === contextRebasedEventType) {\n const payload = committed.event.payload;\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n // Projection staging commits with the events; a projection failure freezes only\n // the failed version and never fails the append.\n transcript:\n appended.length === 0\n ? current.transcript\n : maintainTranscripts(current.transcript, appended),\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\n/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */\nconst makeInMemoryTranscriptStore = (\n data: Ref.Ref<InMemoryStoreData>,\n): EDATranscriptStoreShape => ({\n readTranscriptWindow: (selector, limits) =>\n Effect.gen(function* () {\n const { transcript } = yield* Ref.get(data);\n const source = inMemoryTranscriptWindowSource(transcript);\n if (source === undefined) {\n return inactiveTranscriptWindow(\n transcript.incarnation,\n transcript.config.current.version,\n transcript.versions.find((version) => version.meta.role === \"building\")?.meta,\n );\n }\n const window = readTranscriptWindowFrom(source, selector, limits);\n return Result.isSuccess(window) ? window.success : yield* window.failure;\n }),\n readTranscriptMeta: Ref.get(data).pipe(\n Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)),\n ),\n});\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = entry.event.payload.command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n\n/** App schemas are registered once; known namespaces fail at the store boundary when malformed. */\nexport type EDAAppEvents = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\nconst eventNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventNamespaces);\n if (ast._tag === \"Objects\") {\n const namespace = ast.propertySignatures.find((field) => field.name === \"namespace\")?.type;\n if (namespace?._tag === \"Literal\" && typeof namespace.literal === \"string\")\n return [namespace.literal];\n }\n throw new Error(\"App event schemas must be a union of structs with literal namespaces\");\n};\n\n/** Attach the app decoder to every event-returning store operation without changing storage bytes. */\nexport const registerAppEvents = (\n store: EDASessionStoreShape,\n schema: EDAAppEvents,\n): EDASessionStoreShape => {\n const namespaces = new Set(eventNamespaces(schema.ast));\n const decode = decodeRetainingExcess(schema);\n const envelopeKey = (event: DurableEventEnvelope): string =>\n JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));\n const decodeEntry = (\n entry: CommittedDurableEvent,\n prepared?: ReadonlyMap<string, DurableEventEnvelope>,\n ): CommittedDurableEvent => {\n if (entry.event.namespace !== \"__foreign\" || !namespaces.has(entry.event.envelope.namespace))\n return entry;\n return {\n ...entry,\n event: {\n ...entry.event,\n decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope),\n },\n };\n };\n const decodeEntryEffect = (entry: CommittedDurableEvent) =>\n Effect.try({\n try: () => decodeEntry(entry),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const decodeEntries = (entries: ReadonlyArray<CommittedDurableEvent>) =>\n Effect.forEach(entries, decodeEntryEffect);\n return {\n ...store,\n append: (batch) =>\n Effect.gen(function* () {\n // Idempotent append can return different retained bytes for the same event id.\n // Reuse a prepared decode only when the complete persisted envelope matches.\n const prepared = yield* Effect.try({\n try: () => {\n const decoded = new Map<string, DurableEventEnvelope>();\n for (const { event } of batch.entries) {\n if (!namespaces.has(event.namespace)) continue;\n const key = envelopeKey(event);\n if (!decoded.has(key)) {\n decoded.set(key, decode(event));\n }\n }\n return decoded;\n },\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const committed = yield* store.append(batch);\n return yield* Effect.forEach(committed, (entry) =>\n Effect.try({\n try: () => decodeEntry(entry, prepared),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n }),\n );\n }),\n eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),\n loadCommittedEventsBySeq: (seqs) =>\n store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),\n findCommandAdmission: (input) =>\n store\n .findCommandAdmission(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): ent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,OAAO,OAAO,OAAO,QAAQ,YAAY,UACvC,OAAO,IAAI;IACT,WAAW,YAAY,OAAO,QAAQ;IACtC,QAAQ,UACN,IAAI,qBAAqB,EACvB,SAAS,uCAAuC,OAAO,KAAK,IAC9D,CAAC;GACL,CAAC,CACH;EACF,CAAC;EACH,cAAc,QAAQ,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,OAAO,UAAU,iBAAiB,CAAC;EACrF,2BAA2B,SACzB,MAAM,yBAAyB,IAAI,CAAC,CAAC,KAAK,OAAO,QAAQ,aAAa,CAAC;EACzE,uBAAuB,UACrB,MACG,qBAAqB,KAAK,CAAC,CAC3B,KACC,OAAO,SAAS,UACd,UAAU,KAAA,IAAY,OAAO,QAAQ,KAAA,CAAS,IAAI,kBAAkB,KAAK,CAC3E,CACF;CACN;AACF;;AAGA,MAAa,wBACX,QACA,UACyC;CACzC,MAAM,QACJ,MAAM,MAAM,cAAc,cACrB,MAAM,MAAM,WAAW,MAAM,MAAM,WACpC,MAAM;CACZ,OAAO,OAAO,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI;EAAE,UAAU,MAAM;EAAU;CAAM,IAAI,KAAA;AAC1E;;AAGA,MAAa,wBACX,OACA,QACA,UAA2E,CAAC,MAE5E,MAAM,YAAY,QAAQ,YAAY,eAAe,KAAK,CAAC,CAAC,CAAC,CAAC,KAC5D,OAAO,KAAK,UAAU,qBAAqB,QAAQ,KAAK,CAAC,GACzD,OAAO,QAAQ,UAA6C,UAAU,KAAA,CAAS,GAC/E,OAAO,KAAK,QAAQ,SAAS,OAAO,gBAAgB,GACpD,OAAO,UACT"}
@@ -1,2 +1,2 @@
1
- import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-M7qIxoSH.js";
1
+ import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-DvuHwvx_.js";
2
2
  export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
@@ -17,7 +17,8 @@ const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand("EDASinkName"));
17
17
  var SinkCheckpointStore = class SinkCheckpointStore extends Context.Service()("@effect-durable-agent/SinkCheckpointStore") {
18
18
  /** In-memory checkpoint implementation for store/runtime tests. */
19
19
  static InMemory = Layer.effect(SinkCheckpointStore, Effect.gen(function* () {
20
- return makeInMemorySinkCheckpointStore(yield* Ref.make(/* @__PURE__ */ new Map()));
20
+ const checkpoints = yield* Ref.make(/* @__PURE__ */ new Map());
21
+ return makeInMemorySinkCheckpointStore(checkpoints);
21
22
  }));
22
23
  };
23
24
  /** Build a ref-backed checkpoint map with the same public semantics as host adapters. */
@@ -1 +1 @@
1
- {"version":3,"file":"sink-checkpoint-store.js","names":[],"sources":["../../src/services/sink-checkpoint-store.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { EDASessionStoreError } from \"./session-store\";\n\n/** Stable sink name used as the durable checkpoint key. */\nexport const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand(\"EDASinkName\"));\nexport type EDASinkName = typeof EDASinkName.Type;\n\n/** Persisted cursor and sink-owned payload for one registered sink. */\nexport interface StoredSinkCheckpoint {\n readonly afterSeq: SequenceNumber;\n readonly payload: unknown | undefined;\n}\n\n/** Durable checkpoint persistence port for at-least-once sink runners. */\nexport interface SinkCheckpointStoreShape {\n /** Read the latest committed cursor and sink-owned payload. */\n readonly load: (\n sinkName: EDASinkName,\n ) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;\n /** Save sink-owned state without advancing the durable cursor. */\n readonly saveState: (\n sinkName: EDASinkName,\n payload: unknown,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Atomically commit the processed cursor together with current sink-owned state. */\n readonly commit: (\n sinkName: EDASinkName,\n afterSeq: SequenceNumber,\n payload: unknown | undefined,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * Semantic checkpoint store for registered EDA sinks.\n *\n * Checkpoints are intentionally exposed as load/save/commit operations rather\n * than SQL. Sink side effects happen outside event append transactions, and the\n * cursor advances only after the sink finishes its own external work.\n */\nexport class SinkCheckpointStore extends Context.Service<\n SinkCheckpointStore,\n SinkCheckpointStoreShape\n>()(\"@effect-durable-agent/SinkCheckpointStore\") {\n /** In-memory checkpoint implementation for store/runtime tests. */\n static readonly InMemory = Layer.effect(\n SinkCheckpointStore,\n Effect.gen(function* () {\n const checkpoints = yield* Ref.make<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>(\n new Map(),\n );\n return makeInMemorySinkCheckpointStore(checkpoints);\n }),\n );\n}\n\n/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */\nconst makeInMemorySinkCheckpointStore = (\n checkpoints: Ref.Ref<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>,\n): SinkCheckpointStoreShape => ({\n load: (sinkName) =>\n Ref.get(checkpoints).pipe(\n Effect.map(\n (map) =>\n map.get(sinkName) ?? {\n afterSeq: SequenceNumber.make(0),\n payload: undefined,\n },\n ),\n ),\n saveState: (sinkName, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, {\n afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),\n payload,\n });\n return next;\n }),\n commit: (sinkName, afterSeq, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, { afterSeq, payload });\n return next;\n }),\n});\n"],"mappings":";;;;;;;;AAUA,MAAa,cAAc,OAAO,eAAe,KAAK,OAAO,MAAM,aAAa,CAAC;;;;;;;;AAmCjF,IAAa,sBAAb,MAAa,4BAA4B,QAAQ,QAG/C,EAAE,2CAA2C,EAAE;;CAE/C,OAAgB,WAAW,MAAM,OAC/B,qBACA,OAAO,IAAI,aAAa;EAItB,OAAO,gCAAgC,OAHZ,IAAI,qBAC7B,IAAI,IAAI,CACV,CACkD;CACpD,CAAC,CACH;AACF;;AAGA,MAAM,mCACJ,iBAC8B;CAC9B,OAAO,aACL,IAAI,IAAI,WAAW,EAAE,KACnB,OAAO,KACJ,QACC,IAAI,IAAI,QAAQ,KAAK;EACnB,UAAU,eAAe,KAAK,CAAC;EAC/B,SAAS,KAAA;CACX,CACJ,CACF;CACF,YAAY,UAAU,YACpB,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GACjB,UAAU,IAAI,IAAI,QAAQ,GAAG,YAAY,eAAe,KAAK,CAAC;GAC9D;EACF,CAAC;EACD,OAAO;CACT,CAAC;CACH,SAAS,UAAU,UAAU,YAC3B,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GAAE;GAAU;EAAQ,CAAC;EACxC,OAAO;CACT,CAAC;AACL"}
1
+ {"version":3,"file":"sink-checkpoint-store.js","names":[],"sources":["../../src/services/sink-checkpoint-store.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { EDASessionStoreError } from \"./session-store\";\n\n/** Stable sink name used as the durable checkpoint key. */\nexport const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand(\"EDASinkName\"));\nexport type EDASinkName = typeof EDASinkName.Type;\n\n/** Persisted cursor and sink-owned payload for one registered sink. */\nexport interface StoredSinkCheckpoint {\n readonly afterSeq: SequenceNumber;\n readonly payload: unknown | undefined;\n}\n\n/** Durable checkpoint persistence port for at-least-once sink runners. */\nexport interface SinkCheckpointStoreShape {\n /** Read the latest committed cursor and sink-owned payload. */\n readonly load: (\n sinkName: EDASinkName,\n ) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;\n /** Save sink-owned state without advancing the durable cursor. */\n readonly saveState: (\n sinkName: EDASinkName,\n payload: unknown,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Atomically commit the processed cursor together with current sink-owned state. */\n readonly commit: (\n sinkName: EDASinkName,\n afterSeq: SequenceNumber,\n payload: unknown | undefined,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * Semantic checkpoint store for registered EDA sinks.\n *\n * Checkpoints are intentionally exposed as load/save/commit operations rather\n * than SQL. Sink side effects happen outside event append transactions, and the\n * cursor advances only after the sink finishes its own external work.\n */\nexport class SinkCheckpointStore extends Context.Service<\n SinkCheckpointStore,\n SinkCheckpointStoreShape\n>()(\"@effect-durable-agent/SinkCheckpointStore\") {\n /** In-memory checkpoint implementation for store/runtime tests. */\n static readonly InMemory = Layer.effect(\n SinkCheckpointStore,\n Effect.gen(function* () {\n const checkpoints = yield* Ref.make<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>(\n new Map(),\n );\n return makeInMemorySinkCheckpointStore(checkpoints);\n }),\n );\n}\n\n/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */\nconst makeInMemorySinkCheckpointStore = (\n checkpoints: Ref.Ref<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>,\n): SinkCheckpointStoreShape => ({\n load: (sinkName) =>\n Ref.get(checkpoints).pipe(\n Effect.map(\n (map) =>\n map.get(sinkName) ?? {\n afterSeq: SequenceNumber.make(0),\n payload: undefined,\n },\n ),\n ),\n saveState: (sinkName, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, {\n afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),\n payload,\n });\n return next;\n }),\n commit: (sinkName, afterSeq, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, { afterSeq, payload });\n return next;\n }),\n});\n"],"mappings":";;;;;;;;AAUA,MAAa,cAAc,OAAO,eAAe,KAAK,OAAO,MAAM,aAAa,CAAC;;;;;;;;AAmCjF,IAAa,sBAAb,MAAa,4BAA4B,QAAQ,QAG/C,CAAC,CAAC,2CAA2C,CAAC,CAAC;;CAE/C,OAAgB,WAAW,MAAM,OAC/B,qBACA,OAAO,IAAI,aAAa;EACtB,MAAM,cAAc,OAAO,IAAI,qBAC7B,IAAI,IAAI,CACV;EACA,OAAO,gCAAgC,WAAW;CACpD,CAAC,CACH;AACF;;AAGA,MAAM,mCACJ,iBAC8B;CAC9B,OAAO,aACL,IAAI,IAAI,WAAW,CAAC,CAAC,KACnB,OAAO,KACJ,QACC,IAAI,IAAI,QAAQ,KAAK;EACnB,UAAU,eAAe,KAAK,CAAC;EAC/B,SAAS,KAAA;CACX,CACJ,CACF;CACF,YAAY,UAAU,YACpB,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GACjB,UAAU,IAAI,IAAI,QAAQ,CAAC,EAAE,YAAY,eAAe,KAAK,CAAC;GAC9D;EACF,CAAC;EACD,OAAO;CACT,CAAC;CACH,SAAS,UAAU,UAAU,YAC3B,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GAAE;GAAU;EAAQ,CAAC;EACxC,OAAO;CACT,CAAC;AACL"}
@@ -1,2 +1,2 @@
1
- import { a as EDASinkContext, c as EDASinkRegistryShape, i as EDASinkCheckpoint, l as EDASinkRunnerStartInput, n as EDAEphemeralSinkDefinition, o as EDASinkDurableBatch, r as EDASink, s as EDASinkRegistry, t as EDADurableSinkDefinition } from "../sink-registry-T1wOUuzq.js";
2
- export { EDADurableSinkDefinition, EDAEphemeralSinkDefinition, EDASink, EDASinkCheckpoint, EDASinkContext, EDASinkDurableBatch, EDASinkRegistry, EDASinkRegistryShape, EDASinkRunnerStartInput };
1
+ import { $t as EDASinkRawDurableBatch, Gt as EDAProjectedSink, Ht as EDADurableSinkDefinition, Jt as EDASink, Kt as EDARawDurableSinkDefinition, Qt as EDASinkInterests, Ut as EDAEphemeralSinkDefinition, Wt as EDAProjectedDurableSinkDefinition, Xt as EDASinkContext, Yt as EDASinkCheckpoint, Zt as EDASinkDurableBatch, en as EDASinkRegistry, nn as EDASinkRunnerStartInput, qt as EDARawSink, tn as EDASinkRegistryShape } from "../reduced-state-B1cvy8N_.js";
2
+ export { EDADurableSinkDefinition, EDAEphemeralSinkDefinition, EDAProjectedDurableSinkDefinition, EDAProjectedSink, EDARawDurableSinkDefinition, EDARawSink, EDASink, EDASinkCheckpoint, EDASinkContext, EDASinkDurableBatch, EDASinkInterests, EDASinkRawDurableBatch, EDASinkRegistry, EDASinkRegistryShape, EDASinkRunnerStartInput };
@@ -1,2 +1,2 @@
1
- import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-NDgeyzO0.js";
1
+ import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-DskRcyOS.js";
2
2
  export { EDASink, EDASinkRegistry };
@@ -20,7 +20,7 @@
20
20
  *
21
21
  * Application-specific operations belong in the application catalog, not this reusable catalog.
22
22
  */
23
- declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.page", "agent.events.stream", "agent.inference", "agent.messages.list", "agent.run", "agent.session.snapshot", "agent.sink.drain", "agent.tool", "agent.turn"];
23
+ declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.page", "agent.events.stream", "agent.inference", "agent.run", "agent.run.grant", "agent.run.request.outcome", "agent.session.hydrate", "agent.session.recover.tools", "agent.session.snapshot", "agent.sink.drain", "agent.sink.hydrate", "agent.sinks.initialize", "agent.tool", "agent.turn"];
24
24
  /** Union of values admitted by the centralized EDA span-name catalog. */
25
25
  type SpanName = (typeof SpanNames)[number];
26
26
  //#endregion
@@ -30,10 +30,15 @@ const SpanNames = defineSpanNames([
30
30
  "agent.events.page",
31
31
  "agent.events.stream",
32
32
  "agent.inference",
33
- "agent.messages.list",
34
33
  "agent.run",
34
+ "agent.run.grant",
35
+ "agent.run.request.outcome",
36
+ "agent.session.hydrate",
37
+ "agent.session.recover.tools",
35
38
  "agent.session.snapshot",
36
39
  "agent.sink.drain",
40
+ "agent.sink.hydrate",
41
+ "agent.sinks.initialize",
37
42
  "agent.tool",
38
43
  "agent.turn"
39
44
  ]);
@@ -1 +1 @@
1
- {"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.page\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.messages.list\",\n \"agent.run\",\n \"agent.session.snapshot\",\n \"agent.sink.drain\",\n \"agent.tool\",\n \"agent.turn\",\n]);\n\n/** Union of values admitted by the centralized EDA span-name catalog. */\nexport type SpanName = (typeof SpanNames)[number];\n"],"mappings":";AAEA,MAAM,mBACJ,UACU;;;;;;;;;;;;;;;;;;;;;;AAuBZ,MAAa,YAAY,gBAAgB;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
1
+ {"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.page\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.run\",\n \"agent.run.grant\",\n \"agent.run.request.outcome\",\n \"agent.session.hydrate\",\n \"agent.session.recover.tools\",\n \"agent.session.snapshot\",\n \"agent.sink.drain\",\n \"agent.sink.hydrate\",\n \"agent.sinks.initialize\",\n \"agent.tool\",\n \"agent.turn\",\n]);\n\n/** Union of values admitted by the centralized EDA span-name catalog. */\nexport type SpanName = (typeof SpanNames)[number];\n"],"mappings":";AAEA,MAAM,mBACJ,UACU;;;;;;;;;;;;;;;;;;;;;;AAuBZ,MAAa,YAAY,gBAAgB;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
@@ -1,2 +1,2 @@
1
- import { a as ToolParamsSchema, i as EDAToolRegistryShape, n as EDAToolExecutionContext, o as makeEDAToolkit, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-BJaVNtw4.js";
2
- export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
1
+ import { a as ToolParamsSchema, c as makeEDAToolkit, i as EDAToolRegistryShape, l as maxToolCallAttempts, n as EDAToolExecutionContext, o as ToolRecovery, r as EDAToolRegistry, s as ToolRecoveryPolicy, t as EDAModelToolkit, u as toolRecoveryPolicy } from "../tool-registry-CHHUU9BN.js";
2
+ export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, ToolRecovery, ToolRecoveryPolicy, makeEDAToolkit, maxToolCallAttempts, toolRecoveryPolicy };
@@ -3,9 +3,18 @@ import * as Effect from "effect/Effect";
3
3
  import * as Layer from "effect/Layer";
4
4
  import "effect/Schema";
5
5
  import * as Stream from "effect/Stream";
6
- import * as Tool from "effect/unstable/ai/Tool";
7
- import * as Toolkit from "effect/unstable/ai/Toolkit";
6
+ import * as Tool from "effect/ai/Tool";
7
+ import * as Toolkit from "effect/ai/Toolkit";
8
8
  //#region src/services/tool-registry.ts
9
+ /** Effect AI tool annotation declaring a tool's {@link ToolRecoveryPolicy}. */
10
+ const ToolRecovery = Context.Reference("effect-durable-agent/ToolRecovery", { defaultValue: () => "fail" });
11
+ /** Total execution attempts, including the first, that recovery allows one tool call. */
12
+ const maxToolCallAttempts = 3;
13
+ /** The recovery policy a toolkit declares for `toolName`; `fail` for unknown tools. */
14
+ const toolRecoveryPolicy = (toolkit, toolName) => {
15
+ const tool = toolkit?.tools[toolName];
16
+ return tool === void 0 ? "fail" : Context.get(tool.annotations, ToolRecovery);
17
+ };
9
18
  /** Build a handler-backed Effect Toolkit from tools and handlers. */
10
19
  const makeEDAToolkit = (tools, handlers) => {
11
20
  const toolkit = Toolkit.make(...tools);
@@ -41,6 +50,6 @@ var EDAToolRegistry = class EDAToolRegistry extends Context.Service()("@effect-d
41
50
  static FromSchemas = (schemas) => Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkitFromSchemas(schemas)));
42
51
  };
43
52
  //#endregion
44
- export { EDAToolRegistry, makeEDAToolkit };
53
+ export { EDAToolRegistry, ToolRecovery, makeEDAToolkit, maxToolCallAttempts, toolRecoveryPolicy };
45
54
 
46
55
  //# sourceMappingURL=tool-registry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tool from \"effect/unstable/ai/Tool\";\nimport * as Toolkit from \"effect/unstable/ai/Toolkit\";\n\nimport { EventId, SessionId, ToolCallId } from \"../types/core\";\nimport { DurableEventEnvelope, ToolName } from \"../types/events\";\nimport type { CommittedDurableEvent, EDASessionStoreError } from \"./session-store\";\n\n/** Runtime parameter schema associated with a provider-visible tool name. */\nexport type ToolParamsSchema = Schema.Top;\n\n/** Provider-visible Effect AI toolkit with handlers available for local execution. */\nexport type EDAModelToolkit = Toolkit.WithHandler<Record<string, Tool.Any>>;\n\n/** Framework context passed to product tool handlers without model-visible params. */\nexport interface EDAToolExecutionContext {\n /** Framework-owned tool-call identity for this execution. */\n readonly toolCallId: ToolCallId;\n /** Session identity fixed for this runtime instance. */\n readonly sessionId: SessionId;\n /** Mint an app durable event id for tool-emitted facts. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Emit an app durable event through `SessionState`, never directly through the store. */\n readonly emitDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<CommittedDurableEvent, EDASessionStoreError>;\n}\n\n/** Registry contract used by model streaming and post-finish tool execution. */\nexport interface EDAToolRegistryShape {\n /** Look up the parameter schema for a registered tool name. */\n readonly getParamsSchema: (toolName: ToolName) => Effect.Effect<ToolParamsSchema | undefined>;\n /** Build provider-visible tool definitions while keeping EDA in charge of lifecycle events. */\n readonly getModelToolkit: () => Effect.Effect<EDAModelToolkit | undefined>;\n /** Execute a tool. EDA records the durable lifecycle around this effect. */\n readonly execute: (\n toolName: ToolName,\n params: unknown,\n context: EDAToolExecutionContext,\n ) => Effect.Effect<unknown, unknown>;\n}\n\n/** Build a handler-backed Effect Toolkit from tools and handlers. */\nexport const makeEDAToolkit = <const Tools extends ReadonlyArray<Tool.Any>>(\n tools: Tools,\n handlers: Toolkit.HandlersFrom<Toolkit.ToolsByName<Tools>>,\n): Effect.Effect<EDAModelToolkit> => {\n const toolkit = Toolkit.make(...tools);\n return toolkit.pipe(\n Effect.provide(toolkit.toLayer(handlers)),\n Effect.map((withHandlers) => withHandlers as unknown as EDAModelToolkit),\n );\n};\n\nconst makeToolRegistry = (toolkit: EDAModelToolkit | undefined): EDAToolRegistryShape => ({\n getParamsSchema: (toolName) => Effect.succeed(toolkit?.tools[toolName]?.parametersSchema),\n getModelToolkit: () => Effect.succeed(toolkit),\n execute: (toolName, params, _context) =>\n Effect.gen(function* () {\n if (toolkit === undefined || toolkit.tools[toolName] === undefined) {\n return yield* Effect.fail(new Error(`No handler registered for tool ${toolName}`));\n }\n\n const results = yield* (yield* toolkit.handle(toolName, params)).pipe(Stream.runCollect);\n const final = Array.from(results)\n .filter((result) => !result.preliminary)\n .at(-1);\n if (final === undefined) {\n return yield* Effect.fail(new Error(`Tool ${toolName} completed without a final result`));\n }\n if (final.isFailure) {\n return yield* Effect.fail(final.result);\n }\n return final.encodedResult;\n }) as Effect.Effect<unknown, unknown>,\n});\n\nconst toolkitFromSchemas = (\n schemas: ReadonlyMap<string, ToolParamsSchema>,\n): EDAModelToolkit | undefined => {\n if (schemas.size === 0) {\n return undefined;\n }\n\n const tools = Object.fromEntries(\n Array.from(schemas.entries()).map(([name, schema]) => [\n name,\n Tool.dynamic(name, { parameters: schema }),\n ]),\n );\n\n return {\n tools,\n handle: ((name: string) =>\n Effect.die(\n new Error(`No test handler registered for schema-only tool ${name}`),\n )) as unknown as EDAModelToolkit[\"handle\"],\n };\n};\n\n/** Registry of Effect AI tools available to the model and EDA lifecycle executor. */\nexport class EDAToolRegistry extends Context.Service<EDAToolRegistry, EDAToolRegistryShape>()(\n \"@effect-durable-agent/EDAToolRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDAToolRegistry, makeToolRegistry(undefined));\n\n static readonly FromToolkit = (toolkit: EDAModelToolkit) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkit));\n\n static readonly FromToolkitEffect = <E, R>(toolkit: Effect.Effect<EDAModelToolkit, E, R>) =>\n Layer.effect(\n EDAToolRegistry,\n toolkit.pipe(Effect.map((withHandlers) => makeToolRegistry(withHandlers))),\n );\n\n static readonly FromShape = (shape: EDAToolRegistryShape) =>\n Layer.succeed(EDAToolRegistry, shape);\n\n static readonly FromShapeEffect = <E, R>(shape: Effect.Effect<EDAToolRegistryShape, E, R>) =>\n Layer.effect(EDAToolRegistry, shape);\n\n /** Test/convenience schema-only tools. Runtime execution will fail unless a real Toolkit is provided. */\n static readonly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AmD,MAAM,CACrE;CACJ;AACF;;AAGA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;CACA,OAAgB,QAAQ,MAAM,QAAQ,iBAAiB,iBAAiB,KAAA,CAAS,CAAC;CAElF,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,OAAO,CAAC;CAE1D,OAAgB,qBAA2B,YACzC,MAAM,OACJ,iBACA,QAAQ,KAAK,OAAO,KAAK,iBAAiB,iBAAiB,YAAY,CAAC,CAAC,CAC3E;CAEF,OAAgB,aAAa,UAC3B,MAAM,QAAQ,iBAAiB,KAAK;CAEtC,OAAgB,mBAAyB,UACvC,MAAM,OAAO,iBAAiB,KAAK;;CAGrC,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,mBAAmB,OAAO,CAAC,CAAC;AAChF"}
1
+ {"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tool from \"effect/ai/Tool\";\nimport * as Toolkit from \"effect/ai/Toolkit\";\n\nimport { EventId, SequenceNumber, SessionId, ToolCallId, RunId, TurnId } from \"../types/core\";\nimport { DurableEventEnvelope, ToolName } from \"../types/events\";\nimport type { CommittedDurableEvent, EDASessionStoreError } from \"./session-store\";\n\n/**\n * What startup recovery does with a call to this tool that had started when the runtime died.\n *\n * - `fail` (default): record the call as failed; the model sees the interruption and decides.\n * - `reinvoke`: run the handler again with the same tool-call id and params, passing\n * {@link EDAToolExecutionContext.recovery}. Declare it only when a second invocation of the\n * same call is safe: it must attach to, or return the outcome of, the original execution\n * rather than repeat its side effects (for example an idempotency key derived from the\n * tool-call id). Recovery re-invokes at most {@link maxToolCallAttempts} times in total.\n */\nexport type ToolRecoveryPolicy = \"fail\" | \"reinvoke\";\n\n/** Effect AI tool annotation declaring a tool's {@link ToolRecoveryPolicy}. */\nexport const ToolRecovery = Context.Reference<ToolRecoveryPolicy>(\n \"effect-durable-agent/ToolRecovery\",\n { defaultValue: () => \"fail\" },\n);\n\n/** Total execution attempts, including the first, that recovery allows one tool call. */\nexport const maxToolCallAttempts = 3;\n\n/** The recovery policy a toolkit declares for `toolName`; `fail` for unknown tools. */\nexport const toolRecoveryPolicy = (\n toolkit: EDAModelToolkit | undefined,\n toolName: string,\n): ToolRecoveryPolicy => {\n const tool = toolkit?.tools[toolName];\n return tool === undefined ? \"fail\" : Context.get(tool.annotations, ToolRecovery);\n};\n\n/** Runtime parameter schema associated with a provider-visible tool name. */\nexport type ToolParamsSchema = Schema.Top;\n\n/** Provider-visible Effect AI toolkit with handlers available for local execution. */\nexport type EDAModelToolkit = Toolkit.WithHandler<Record<string, Tool.Any>>;\n\n/** Framework context passed to product tool handlers without model-visible params. */\nexport interface EDAToolExecutionContext {\n /** Framework-owned tool-call identity for this execution. */\n readonly toolCallId: ToolCallId;\n /** Run and turn that durably created this tool call. */\n readonly runId: RunId;\n readonly turnId: TurnId;\n /** Read typed facts from this session journal, optionally only those after `afterSeq`. */\n readonly queryEvents: <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n options?: { readonly limit?: number; readonly afterSeq?: SequenceNumber },\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError>;\n /** Session identity fixed for this runtime instance. */\n readonly sessionId: SessionId;\n /** Mint an app durable event id for tool-emitted facts. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Emit an app durable event through `SessionState`, never directly through the store. */\n readonly emitDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<CommittedDurableEvent, EDASessionStoreError>;\n /**\n * Present when startup recovery re-invokes a call that had started before the runtime died\n * (its tool declares `ToolRecovery: \"reinvoke\"`). Facts the first attempt committed are in the\n * journal after `firstStartedSeq`.\n */\n readonly recovery?: {\n /** This attempt, 2 or more. */\n readonly attempt: number;\n readonly firstStartedAtMs: number;\n readonly firstStartedSeq: SequenceNumber;\n };\n}\n\n/** Registry contract used by model streaming and post-finish tool execution. */\nexport interface EDAToolRegistryShape {\n /** Look up the parameter schema for a registered tool name. */\n readonly getParamsSchema: (toolName: ToolName) => Effect.Effect<ToolParamsSchema | undefined>;\n /** Build provider-visible tool definitions while keeping EDA in charge of lifecycle events. */\n readonly getModelToolkit: () => Effect.Effect<EDAModelToolkit | undefined>;\n /** Execute a tool. EDA records the durable lifecycle around this effect. */\n readonly execute: (\n toolName: ToolName,\n params: unknown,\n context: EDAToolExecutionContext,\n ) => Effect.Effect<unknown, unknown>;\n}\n\n/** Build a handler-backed Effect Toolkit from tools and handlers. */\nexport const makeEDAToolkit = <const Tools extends ReadonlyArray<Tool.Any>>(\n tools: Tools,\n handlers: Toolkit.HandlersFrom<Toolkit.ToolsByName<Tools>>,\n): Effect.Effect<EDAModelToolkit> => {\n const toolkit = Toolkit.make(...tools);\n return toolkit.pipe(\n Effect.provide(toolkit.toLayer(handlers)),\n Effect.map((withHandlers) => withHandlers as unknown as EDAModelToolkit),\n );\n};\n\nconst makeToolRegistry = (toolkit: EDAModelToolkit | undefined): EDAToolRegistryShape => ({\n getParamsSchema: (toolName) => Effect.succeed(toolkit?.tools[toolName]?.parametersSchema),\n getModelToolkit: () => Effect.succeed(toolkit),\n execute: (toolName, params, _context) =>\n Effect.gen(function* () {\n if (toolkit === undefined || toolkit.tools[toolName] === undefined) {\n return yield* Effect.fail(new Error(`No handler registered for tool ${toolName}`));\n }\n\n const results = yield* (yield* toolkit.handle(toolName, params)).pipe(Stream.runCollect);\n const final = Array.from(results)\n .filter((result) => !result.preliminary)\n .at(-1);\n if (final === undefined) {\n return yield* Effect.fail(new Error(`Tool ${toolName} completed without a final result`));\n }\n if (final.isFailure) {\n return yield* Effect.fail(final.result);\n }\n return final.encodedResult;\n }) as Effect.Effect<unknown, unknown>,\n});\n\nconst toolkitFromSchemas = (\n schemas: ReadonlyMap<string, ToolParamsSchema>,\n): EDAModelToolkit | undefined => {\n if (schemas.size === 0) {\n return undefined;\n }\n\n const tools = Object.fromEntries(\n Array.from(schemas.entries()).map(([name, schema]) => [\n name,\n Tool.dynamic(name, { parameters: schema }),\n ]),\n );\n\n return {\n tools,\n handle: ((name: string) =>\n Effect.die(\n new Error(`No test handler registered for schema-only tool ${name}`),\n )) as unknown as EDAModelToolkit[\"handle\"],\n };\n};\n\n/** Registry of Effect AI tools available to the model and EDA lifecycle executor. */\nexport class EDAToolRegistry extends Context.Service<EDAToolRegistry, EDAToolRegistryShape>()(\n \"@effect-durable-agent/EDAToolRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDAToolRegistry, makeToolRegistry(undefined));\n\n static readonly FromToolkit = (toolkit: EDAModelToolkit) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkit));\n\n static readonly FromToolkitEffect = <E, R>(toolkit: Effect.Effect<EDAModelToolkit, E, R>) =>\n Layer.effect(\n EDAToolRegistry,\n toolkit.pipe(Effect.map((withHandlers) => makeToolRegistry(withHandlers))),\n );\n\n static readonly FromShape = (shape: EDAToolRegistryShape) =>\n Layer.succeed(EDAToolRegistry, shape);\n\n static readonly FromShapeEffect = <E, R>(shape: Effect.Effect<EDAToolRegistryShape, E, R>) =>\n Layer.effect(EDAToolRegistry, shape);\n\n /** Test/convenience schema-only tools. Runtime execution will fail unless a real Toolkit is provided. */\n static readonly FromSchemas = (schemas: ReadonlyMap<string, ToolParamsSchema>) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkitFromSchemas(schemas)));\n}\n"],"mappings":";;;;;;;;;AAyBA,MAAa,eAAe,QAAQ,UAClC,qCACA,EAAE,oBAAoB,OAAO,CAC/B;;AAGA,MAAa,sBAAsB;;AAGnC,MAAa,sBACX,SACA,aACuB;CACvB,MAAM,OAAO,SAAS,MAAM;CAC5B,OAAO,SAAS,KAAA,IAAY,SAAS,QAA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AwB,QAAQ,QAA+C,CAAC,CAC3F,uCACF,CAAC,CAAC;CACA,OAAgB,QAAQ,MAAM,QAAQ,iBAAiB,iBAAiB,KAAA,CAAS,CAAC;CAElF,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,OAAO,CAAC;CAE1D,OAAgB,qBAA2B,YACzC,MAAM,OACJ,iBACA,QAAQ,KAAK,OAAO,KAAK,iBAAiB,iBAAiB,YAAY,CAAC,CAAC,CAC3E;CAEF,OAAgB,aAAa,UAC3B,MAAM,QAAQ,iBAAiB,KAAK;CAEtC,OAAgB,mBAAyB,UACvC,MAAM,OAAO,iBAAiB,KAAK;;CAGrC,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,mBAAmB,OAAO,CAAC,CAAC;AAChF"}
@@ -1,8 +1,8 @@
1
- import { _ as UsagePayload } from "../envelope-DkZyMIgp.js";
2
- import { _ as parseEDATraceparent, c as EDATraceLink, d as makeEDAEventTrace, f as makeEDARunTrace, g as makeRootEDATraceMetadata, h as makeRootEDAEventTrace, i as EDATraceAttributeValue, l as EDATraceMetadata, m as makeEDATraceMetadataFromParent, n as EDARunTrace, o as EDATraceContext, p as makeEDATraceContext, t as EDAEventTrace, u as buildEDATraceparent } from "../tracing-BXHAkxkx.js";
1
+ import { _ as parseEDATraceparent, c as EDATraceLink, d as makeEDAEventTrace, f as makeEDARunTrace, g as makeRootEDATraceMetadata, h as makeRootEDAEventTrace, i as EDATraceAttributeValue, l as EDATraceMetadata, m as makeEDATraceMetadataFromParent, n as EDARunTrace, o as EDATraceContext, p as makeEDATraceContext, t as EDAEventTrace, u as buildEDATraceparent } from "../tracing-BwjbF285.js";
2
+ import { v as UsagePayload } from "../envelope-Che6KatU.js";
3
+ import "../events-DwTARLMv.js";
3
4
  import * as Effect from "effect/Effect";
4
5
  import * as Tracer from "effect/Tracer";
5
-
6
6
  //#region src/services/tracing.d.ts
7
7
  /** Attribute value types accepted by Effect span annotations after compaction. */
8
8
  type EdaSpanAttributeValue = EDATraceAttributeValue | undefined;
@@ -1,7 +1,7 @@
1
1
  import { EDAEventTrace, EDARunTrace, EDATraceContext, EDATraceLink, EDATraceMetadata, buildEDATraceparent, makeEDAEventTrace, makeEDARunTrace, makeEDATraceContext, makeEDATraceMetadataFromParent, makeRootEDAEventTrace, makeRootEDATraceMetadata, parseEDATraceparent } from "../types/tracing.js";
2
2
  import * as Effect from "effect/Effect";
3
- import * as Cause from "effect/Cause";
4
3
  import * as Exit from "effect/Exit";
4
+ import * as Cause from "effect/Cause";
5
5
  import * as Option from "effect/Option";
6
6
  import * as Tracer from "effect/Tracer";
7
7
  //#region src/services/tracing.ts
@@ -72,7 +72,7 @@ var ExportingNativeSpan = class extends Tracer.NativeSpan {
72
72
  }
73
73
  end(endTime, exit) {
74
74
  super.end(endTime, exit);
75
- if (endTime <= this.startTime) return;
75
+ if (endTime <= this.startTime && this.name !== "agent.session.hydrate" && this.name !== "agent.sinks.initialize") return;
76
76
  const parent = Option.getOrUndefined(this.parent);
77
77
  this.#emit({
78
78
  attributes: compactUnknownAttributes(this.attributes),