effect-durable-agent 0.1.0 → 0.2.1

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 (110) hide show
  1. package/dist/{compaction-63iEDHHl.js → compaction-D7WJa899.js} +3 -3
  2. package/dist/{compaction-63iEDHHl.js.map → compaction-D7WJa899.js.map} +1 -1
  3. package/dist/{delivery-2ZILvoRD.js → delivery-BoF-NZbZ.js} +3 -3
  4. package/dist/{delivery-2ZILvoRD.js.map → delivery-BoF-NZbZ.js.map} +1 -1
  5. package/dist/{delivery-D3MxW4wg.d.ts → delivery-v42MAMEP.d.ts} +153 -10
  6. package/dist/domain/command-queues.d.ts +1 -1
  7. package/dist/domain/message-transcript.d.ts +1 -1
  8. package/dist/domain/model-usage.d.ts +1 -1
  9. package/dist/domain/model-usage.js +1 -1
  10. package/dist/domain/reduced-state-schema.d.ts +2 -2
  11. package/dist/domain/reduced-state-schema.js +2 -2
  12. package/dist/domain/reduced-state.d.ts +2 -2
  13. package/dist/domain/reduced-state.js +3 -2
  14. package/dist/domain/reduced-state.js.map +1 -1
  15. package/dist/domain/run-scheduling.d.ts +1 -1
  16. package/dist/{durable-168Womqp.d.ts → durable-BXqwM70o.d.ts} +510 -3
  17. package/dist/{durable-D13w1Qr3.js → durable-Da57Rcml.js} +17 -3
  18. package/dist/durable-Da57Rcml.js.map +1 -0
  19. package/dist/{envelope-BCzKUq_z.js → envelope-BSI_Xh-f.js} +21 -5
  20. package/dist/envelope-BSI_Xh-f.js.map +1 -0
  21. package/dist/{envelope-Che6KatU.d.ts → envelope-CJnPfbjC.d.ts} +53 -6
  22. package/dist/{event-factory-_vF1bIJ7.js → event-factory-BUoBwqAy.js} +3 -3
  23. package/dist/{event-factory-_vF1bIJ7.js.map → event-factory-BUoBwqAy.js.map} +1 -1
  24. package/dist/{events-DwTARLMv.d.ts → events-AIIwZ6dS.d.ts} +3 -3
  25. package/dist/{in-memory-CeODnZhE.js → in-memory-E497WhtS.js} +3 -3
  26. package/dist/{in-memory-CeODnZhE.js.map → in-memory-E497WhtS.js.map} +1 -1
  27. package/dist/index.d.ts +5 -5
  28. package/dist/index.js +3 -3
  29. package/dist/{interpreter-DKGJ1sSx.js → interpreter-BwYN2PCC.js} +5 -4
  30. package/dist/interpreter-BwYN2PCC.js.map +1 -0
  31. package/dist/{model-resolver-DeBDK8XO.d.ts → model-resolver-O8Kn27GH.d.ts} +3 -3
  32. package/dist/{model-usage-0GeHwaaU.d.ts → model-usage-mttrPN0j.d.ts} +2 -2
  33. package/dist/{records--54mZEBx.js → records-D0ZIAOzd.js} +3 -3
  34. package/dist/{records--54mZEBx.js.map → records-D0ZIAOzd.js.map} +1 -1
  35. package/dist/{reduced-state-B1cvy8N_.d.ts → reduced-state-DB_iANjR.d.ts} +50549 -48726
  36. package/dist/{reduced-state-schema-B98exWxQ.d.ts → reduced-state-schema-B9TYxkP9.d.ts} +2 -2
  37. package/dist/{reducer-registry-DhGVzHBV.d.ts → reducer-registry-Bqn5B4JO.d.ts} +5 -5
  38. package/dist/{run-scheduling-wakeup-Mjic4tb_.d.ts → run-scheduling-wakeup-DX2zRAxd.d.ts} +2 -2
  39. package/dist/services/compaction.d.ts +1 -1
  40. package/dist/services/compaction.js +1 -1
  41. package/dist/services/decider.d.ts +2 -0
  42. package/dist/services/decider.js +97 -0
  43. package/dist/services/decider.js.map +1 -0
  44. package/dist/services/model-call.d.ts +1 -1
  45. package/dist/services/model-resolver.d.ts +1 -1
  46. package/dist/services/prompt-projector.d.ts +1 -1
  47. package/dist/services/reducer-registry.d.ts +1 -1
  48. package/dist/services/run-scheduler.d.ts +1 -1
  49. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  50. package/dist/services/runtime-layer.d.ts +13 -9
  51. package/dist/services/runtime-layer.js +10 -7
  52. package/dist/services/runtime-layer.js.map +1 -1
  53. package/dist/services/runtime.d.ts +1 -1
  54. package/dist/services/runtime.js +4 -3
  55. package/dist/services/runtime.js.map +1 -1
  56. package/dist/services/session-event-observer.d.ts +1 -1
  57. package/dist/services/session-query.d.ts +1 -1
  58. package/dist/services/session-query.js +3 -3
  59. package/dist/services/session-state.d.ts +2 -2
  60. package/dist/services/session-state.js +2 -1
  61. package/dist/services/session-store.d.ts +2 -2
  62. package/dist/services/session-store.js +32 -17
  63. package/dist/services/session-store.js.map +1 -1
  64. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  65. package/dist/services/sink-registry.d.ts +1 -1
  66. package/dist/services/sink-registry.js +1 -1
  67. package/dist/services/span-names.d.ts +1 -1
  68. package/dist/services/span-names.js +1 -0
  69. package/dist/services/span-names.js.map +1 -1
  70. package/dist/services/tool-registry.d.ts +1 -1
  71. package/dist/services/tool-registry.js.map +1 -1
  72. package/dist/services/tracing.d.ts +2 -2
  73. package/dist/session-admission-WE8J_0z9.js +138 -0
  74. package/dist/session-admission-WE8J_0z9.js.map +1 -0
  75. package/dist/{session-event-observer-DlP9ITB2.d.ts → session-event-observer-BWQUJTcN.d.ts} +3 -3
  76. package/dist/{session-state-BehvUVyq.js → session-state-BII-Jhf-.js} +171 -19
  77. package/dist/session-state-BII-Jhf-.js.map +1 -0
  78. package/dist/{session-store-BL6sfrnn.d.ts → session-store-DaSHeg8Q.d.ts} +25 -8
  79. package/dist/{sink-checkpoint-store-DvuHwvx_.d.ts → sink-checkpoint-store-CUvIVvlZ.d.ts} +2 -2
  80. package/dist/{sink-registry-DskRcyOS.js → sink-registry-AOjX5_A1.js} +34 -10
  81. package/dist/sink-registry-AOjX5_A1.js.map +1 -0
  82. package/dist/{subscription-DZNWFDTV.d.ts → subscription-BhwUmsl4.d.ts} +2 -2
  83. package/dist/{subscription-DmO3BcdT.js → subscription-D7U4Tziv.js} +3 -3
  84. package/dist/{subscription-DmO3BcdT.js.map → subscription-D7U4Tziv.js.map} +1 -1
  85. package/dist/testkit/layers.d.ts +13 -10
  86. package/dist/testkit/layers.js +16 -9
  87. package/dist/testkit/layers.js.map +1 -1
  88. package/dist/testkit/transcript.d.ts +10 -4
  89. package/dist/testkit/transcript.js +58 -7
  90. package/dist/testkit/transcript.js.map +1 -1
  91. package/dist/transcript.d.ts +5 -5
  92. package/dist/transcript.js +5 -5
  93. package/dist/types/events/durable.d.ts +2 -2
  94. package/dist/types/events/durable.js +2 -2
  95. package/dist/types/events.d.ts +4 -4
  96. package/dist/types/events.js +3 -3
  97. package/dist/websocket/events.d.ts +1 -1
  98. package/dist/websocket/events.js +1 -1
  99. package/dist/websocket.d.ts +3 -3
  100. package/dist/websocket.js +3 -3
  101. package/dist/{window-read-Brov9VdQ.d.ts → window-read-BELSkO-r.d.ts} +2 -2
  102. package/dist/{window-read-DPFAA1hM.js → window-read-FJTCDaSq.js} +3 -3
  103. package/dist/{window-read-DPFAA1hM.js.map → window-read-FJTCDaSq.js.map} +1 -1
  104. package/package.json +5 -1
  105. package/dist/durable-D13w1Qr3.js.map +0 -1
  106. package/dist/envelope-BCzKUq_z.js.map +0 -1
  107. package/dist/interpreter-DKGJ1sSx.js.map +0 -1
  108. package/dist/session-state-BehvUVyq.js.map +0 -1
  109. package/dist/sink-registry-DskRcyOS.js.map +0 -1
  110. package/dist/tool-registry-CHHUU9BN.d.ts +0 -87
@@ -1,11 +1,12 @@
1
1
  import { CommandId, DurablePosition, SequenceNumber, durablePosition } from "../types/core.js";
2
- import { t as DurableEventEnvelope } from "../envelope-BCzKUq_z.js";
3
- import { H as DecodedDurableEvent, Nn as commandAdmittedEventType, Un as contextRebasedEventType, Wn as decodeDurableEventSync, kr as decodeRetainingExcess, mr as summaryCreatedEventType, qn as durableEventEnvelope } from "../durable-D13w1Qr3.js";
2
+ import { t as DurableEventEnvelope } from "../envelope-BSI_Xh-f.js";
3
+ import { Fn as commandAdmittedEventType, Gn as contextRebasedEventType, Mr as decodeRetainingExcess, W as DecodedDurableEvent, Xn as durableEventEnvelope, _r as summaryCreatedEventType, qn as decodeDurableEventSync } from "../durable-Da57Rcml.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
+ import { i as eventSchemaNamespaces } from "../session-admission-WE8J_0z9.js";
6
+ import { m as makeTranscriptDefinition, p as emptyTranscriptMappings } from "../interpreter-BwYN2PCC.js";
7
+ import { T as TranscriptLogIncarnation } from "../records-D0ZIAOzd.js";
8
+ import { a as maintainTranscripts, i as initialTranscriptState, r as inMemoryTranscriptWindowSource } from "../in-memory-E497WhtS.js";
9
+ import { a as EDATranscriptStore, n as inactiveTranscriptWindow, r as readTranscriptWindowFrom } from "../window-read-FJTCDaSq.js";
9
10
  import * as Context from "effect/Context";
10
11
  import * as Effect from "effect/Effect";
11
12
  import * as Layer from "effect/Layer";
@@ -86,10 +87,20 @@ const inMemoryStoreLayer = (sessionId, seed, options) => Layer.effectContext(Eff
86
87
  }));
87
88
  const seedCommittedEvents = (sessionId, events) => {
88
89
  const seen = /* @__PURE__ */ new Set();
90
+ const seenKeys = /* @__PURE__ */ new Set();
89
91
  return events.map((event, index) => {
90
92
  if (event.sessionId !== sessionId) throw new Error(`EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`);
91
93
  if (seen.has(event.eventId)) throw new Error(`Duplicate seed eventId ${event.eventId}`);
92
94
  seen.add(event.eventId);
95
+ if (event.dedupeKey !== void 0) {
96
+ const triple = JSON.stringify([
97
+ event.namespace,
98
+ event.type,
99
+ event.dedupeKey
100
+ ]);
101
+ if (seenKeys.has(triple)) throw new Error(`Duplicate seed dedupe key ${triple}`);
102
+ seenKeys.add(triple);
103
+ }
93
104
  return {
94
105
  position: durablePosition(SequenceNumber.make(index + 1)),
95
106
  event: decodeDurableEventSync(DurableEventEnvelope.make(event))
@@ -128,7 +139,12 @@ const makeInMemoryStore = (sessionId, data) => {
128
139
  const appended = [];
129
140
  for (const entry of batch.entries) {
130
141
  const { event } = entry;
131
- const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);
142
+ const { dedupeKey, namespace, type } = event;
143
+ const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId) ?? (dedupeKey === void 0 ? void 0 : nextEntries.find((entry) => dedupeTripleMatches(entry, {
144
+ namespace,
145
+ type,
146
+ dedupeKey
147
+ })));
132
148
  if (existing !== void 0) {
133
149
  committedEvents.push(existing);
134
150
  continue;
@@ -168,6 +184,7 @@ const makeInMemoryStore = (sessionId, data) => {
168
184
  return committed.filter((entry) => requested.has(Number(entry.position.seq)));
169
185
  })),
170
186
  findCommandAdmission: (input) => Ref.get(data).pipe(Effect.map(({ committed }) => committed.find((entry) => commandAdmissionMatches(entry, input)))),
187
+ findEventByDedupeKey: (input) => Ref.get(data).pipe(Effect.map(({ committed }) => committed.find((entry) => dedupeTripleMatches(entry, input)))),
171
188
  loadSummaryArtifact: (summaryId) => Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),
172
189
  loadReducerCheckpoint: (name) => Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),
173
190
  saveReducerCheckpoint: (checkpoint) => Ref.update(data, (current) => ({
@@ -195,6 +212,11 @@ const makeInMemoryTranscriptStore = (data) => ({
195
212
  }),
196
213
  readTranscriptMeta: Ref.get(data).pipe(Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)))
197
214
  });
215
+ /** Compare the stored envelope, so a foreign event matches by its own namespace and type. */
216
+ const dedupeTripleMatches = (entry, input) => {
217
+ const envelope = durableEventEnvelope(entry.event);
218
+ return envelope.dedupeKey === input.dedupeKey && envelope.namespace === input.namespace && envelope.type === input.type;
219
+ };
198
220
  const commandAdmissionMatches = (entry, input) => {
199
221
  if (entry.event.type !== commandAdmittedEventType) return false;
200
222
  const admitted = entry.event.payload.command;
@@ -202,17 +224,9 @@ const commandAdmissionMatches = (entry, input) => {
202
224
  if (input.idempotencyKey !== void 0 && admitted.idempotencyKey === input.idempotencyKey) return true;
203
225
  return input.commandId !== void 0 && admitted.commandId === input.commandId;
204
226
  };
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
227
  /** Attach the app decoder to every event-returning store operation without changing storage bytes. */
214
228
  const registerAppEvents = (store, schema) => {
215
- const namespaces = new Set(eventNamespaces(schema.ast));
229
+ const namespaces = new Set(eventSchemaNamespaces(schema.ast));
216
230
  const decode = decodeRetainingExcess(schema);
217
231
  const envelopeKey = (event) => JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));
218
232
  const decodeEntry = (entry, prepared) => {
@@ -253,7 +267,8 @@ const registerAppEvents = (store, schema) => {
253
267
  }),
254
268
  eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),
255
269
  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)))
270
+ findCommandAdmission: (input) => store.findCommandAdmission(input).pipe(Effect.flatMap((entry) => entry === void 0 ? Effect.succeed(void 0) : decodeEntryEffect(entry))),
271
+ findEventByDedupeKey: (input) => store.findEventByDedupeKey(input).pipe(Effect.flatMap((entry) => entry === void 0 ? Effect.succeed(void 0) : decodeEntryEffect(entry)))
257
272
  };
258
273
  };
259
274
  /** Narrow an already decoded fact from one schema, without decoding its payload again. */
@@ -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 Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n DecodedDurableEvent,\n decodeDurableEventSync,\n durableEventEnvelope,\n} from \"../types/events/durable\";\n\nimport { type CommandIdempotencyKey } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport {\n initialTranscriptState,\n inMemoryTranscriptWindowSource,\n maintainTranscripts,\n type InMemoryTranscriptState,\n} from \"../transcript/in-memory\";\nimport { emptyTranscriptMappings, makeTranscriptDefinition } from \"../transcript/mapping\";\nimport { TranscriptLogIncarnation } from \"../transcript/records\";\nimport {\n EDATranscriptStore,\n type EDATranscriptStoreShape,\n type TranscriptMaintenanceConfig,\n} from \"../transcript/store\";\nimport { inactiveTranscriptWindow, readTranscriptWindowFrom } from \"../transcript/window-read\";\n\nexport type CommittedDurableEvent<E = DecodedDurableEvent> = {\n readonly position: typeof DurablePosition.Type;\n readonly event: E;\n};\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent: Schema.Codec<\n CommittedDurableEvent,\n {\n readonly position: typeof DurablePosition.Encoded;\n readonly event: typeof DurableEventEnvelope.Encoded;\n },\n never,\n never\n> = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope.pipe(\n Schema.decodeTo(Schema.declare<DecodedDurableEvent>(Schema.is(DecodedDurableEvent)), {\n decode: SchemaGetter.transform(decodeDurableEventSync),\n encode: SchemaGetter.transform(durableEventEnvelope),\n }),\n ),\n});\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedError<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /**\n * Deterministic in-memory implementation used by runtime and recovery tests.\n *\n * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append\n * critical section. Without `options.transcript` it maintains the definition with no host\n * mappings.\n */\n static readonly InMemory = (sessionId: SessionId, options?: InMemoryStoreOptions) =>\n inMemoryStoreLayer(sessionId, () => [], options);\n\n /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n options?: InMemoryStoreOptions,\n ) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);\n}\n\n/** Construction options for the in-memory store. */\nexport interface InMemoryStoreOptions {\n /** Transcript definitions to maintain; defaults to the definition with no host mappings. */\n readonly transcript?: TranscriptMaintenanceConfig;\n}\n\nconst inMemoryStoreLayer = (\n sessionId: SessionId,\n seed: () => ReadonlyArray<CommittedDurableEvent>,\n options: InMemoryStoreOptions | undefined,\n) =>\n Layer.effectContext(\n Effect.gen(function* () {\n const committed = seed();\n const config = options?.transcript ?? {\n current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie),\n };\n const data = yield* Ref.make<InMemoryStoreData>({\n committed,\n summaries: summariesFromCommittedEvents(committed),\n reducerCheckpoints: new Map(),\n transcript: initialTranscriptState(\n TranscriptLogIncarnation.make(`memory:${sessionId}`),\n config,\n committed,\n ),\n });\n return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(\n Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)),\n );\n }),\n );\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n readonly transcript: InMemoryTranscriptState;\n}\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return {\n position: durablePosition(SequenceNumber.make(index + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload;\n if (payload.summary !== undefined) {\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n const appended: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed: CommittedDurableEvent = {\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n nextEntries.push(committed);\n committedEvents.push(committed);\n appended.push(committed);\n\n if (committed.event.type === summaryCreatedEventType) {\n const payload = committed.event.payload;\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (committed.event.type === contextRebasedEventType) {\n const payload = committed.event.payload;\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n // Projection staging commits with the events; a projection failure freezes only\n // the failed version and never fails the append.\n transcript:\n appended.length === 0\n ? current.transcript\n : maintainTranscripts(current.transcript, appended),\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\n/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */\nconst makeInMemoryTranscriptStore = (\n data: Ref.Ref<InMemoryStoreData>,\n): EDATranscriptStoreShape => ({\n readTranscriptWindow: (selector, limits) =>\n Effect.gen(function* () {\n const { transcript } = yield* Ref.get(data);\n const source = inMemoryTranscriptWindowSource(transcript);\n if (source === undefined) {\n return inactiveTranscriptWindow(\n transcript.incarnation,\n transcript.config.current.version,\n transcript.versions.find((version) => version.meta.role === \"building\")?.meta,\n );\n }\n const window = readTranscriptWindowFrom(source, selector, limits);\n return Result.isSuccess(window) ? window.success : yield* window.failure;\n }),\n readTranscriptMeta: Ref.get(data).pipe(\n Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)),\n ),\n});\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = entry.event.payload.command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n\n/** App schemas are registered once; known namespaces fail at the store boundary when malformed. */\nexport type EDAAppEvents = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\nconst eventNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventNamespaces);\n if (ast._tag === \"Objects\") {\n const namespace = ast.propertySignatures.find((field) => field.name === \"namespace\")?.type;\n if (namespace?._tag === \"Literal\" && typeof namespace.literal === \"string\")\n return [namespace.literal];\n }\n throw new Error(\"App event schemas must be a union of structs with literal namespaces\");\n};\n\n/** Attach the app decoder to every event-returning store operation without changing storage bytes. */\nexport const registerAppEvents = (\n store: EDASessionStoreShape,\n schema: EDAAppEvents,\n): EDASessionStoreShape => {\n const namespaces = new Set(eventNamespaces(schema.ast));\n const decode = decodeRetainingExcess(schema);\n const envelopeKey = (event: DurableEventEnvelope): string =>\n JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));\n const decodeEntry = (\n entry: CommittedDurableEvent,\n prepared?: ReadonlyMap<string, DurableEventEnvelope>,\n ): CommittedDurableEvent => {\n if (entry.event.namespace !== \"__foreign\" || !namespaces.has(entry.event.envelope.namespace))\n return entry;\n return {\n ...entry,\n event: {\n ...entry.event,\n decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope),\n },\n };\n };\n const decodeEntryEffect = (entry: CommittedDurableEvent) =>\n Effect.try({\n try: () => decodeEntry(entry),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const decodeEntries = (entries: ReadonlyArray<CommittedDurableEvent>) =>\n Effect.forEach(entries, decodeEntryEffect);\n return {\n ...store,\n append: (batch) =>\n Effect.gen(function* () {\n // Idempotent append can return different retained bytes for the same event id.\n // Reuse a prepared decode only when the complete persisted envelope matches.\n const prepared = yield* Effect.try({\n try: () => {\n const decoded = new Map<string, DurableEventEnvelope>();\n for (const { event } of batch.entries) {\n if (!namespaces.has(event.namespace)) continue;\n const key = envelopeKey(event);\n if (!decoded.has(key)) {\n decoded.set(key, decode(event));\n }\n }\n return decoded;\n },\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const committed = yield* store.append(batch);\n return yield* Effect.forEach(committed, (entry) =>\n Effect.try({\n try: () => decodeEntry(entry, prepared),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n }),\n );\n }),\n eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),\n loadCommittedEventsBySeq: (seqs) =>\n store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),\n findCommandAdmission: (input) =>\n store\n .findCommandAdmission(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): entry is CommittedDurableEvent<E> => entry !== undefined),\n Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER),\n Stream.runCollect,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,MAAa,wBAQT,OAAO,OAAO;CAChB,UAAU;CACV,OAAO,qBAAqB,KAC1B,OAAO,SAAS,OAAO,QAA6B,OAAO,GAAG,mBAAmB,CAAC,GAAG;EACnF,QAAQ,aAAa,UAAU,sBAAsB;EACrD,QAAQ,aAAa,UAAU,oBAAoB;CACrD,CAAC,CACH;AACF,CAAC;;;;;;;;AAQD,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,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,cAAqC,QAAQ,QAA+C,CAAC,CAC3F,uCACF,CAAC,CAAC;;;;;;;;CAQA,OAAgB,YAAY,WAAsB,YAChD,mBAAmB,iBAAiB,CAAC,GAAG,OAAO;;CAGjD,OAAgB,kBACd,WACA,QACA,YACG,mBAAmB,iBAAiB,oBAAoB,WAAW,MAAM,GAAG,OAAO;AAC1F;AAQA,MAAM,sBACJ,WACA,MACA,YAEA,MAAM,cACJ,OAAO,IA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B,EACvB,SAAS,uCAAuC,OAAO,KAAK,IAC9D,CAAC;GACL,CAAC;GACD,MAAM,YAAY,OAAO,MAAM,OAAO,KAAK;GAC3C,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
+ {"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 * 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 EventDedupeKey,\n EventNamespace,\n EventType,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport { eventSchemaNamespaces } from \"./session-admission\";\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/** Indexed lookup of the one event a session log holds for a dedupe triple. */\nexport interface FindEventByDedupeKeyInput {\n readonly namespace: EventNamespace;\n readonly type: EventType;\n readonly dedupeKey: EventDedupeKey;\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 * Each entry, in order and inside the one append transaction, resolves to:\n * 1. the committed event with the same `eventId`, if one exists; else\n * 2. the committed event with the same `(namespace, type, dedupeKey)`, if the entry has a\n * `dedupeKey` and one exists; else\n * 3. a newly inserted event.\n *\n * An entry that resolves to an existing event (including one earlier in the same batch) returns\n * that event's own id, payload and position, writes nothing and does not advance the durable\n * head. First write wins. Live publish remains outside the store and is owned by\n * `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 /** Lookup the event committed for a `(namespace, type, dedupeKey)` triple. */\n readonly findEventByDedupeKey: (\n input: FindEventByDedupeKeyInput,\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 const seenKeys = 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 if (event.dedupeKey !== undefined) {\n const triple = JSON.stringify([event.namespace, event.type, event.dedupeKey]);\n if (seenKeys.has(triple)) {\n throw new Error(`Duplicate seed dedupe key ${triple}`);\n }\n seenKeys.add(triple);\n }\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 { dedupeKey, namespace, type } = event;\n const existing =\n nextEntries.find((entry) => entry.event.eventId === event.eventId) ??\n (dedupeKey === undefined\n ? undefined\n : nextEntries.find((entry) =>\n dedupeTripleMatches(entry, { namespace, type, dedupeKey }),\n ));\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 findEventByDedupeKey: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.find((entry) => dedupeTripleMatches(entry, input))),\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\n/** Compare the stored envelope, so a foreign event matches by its own namespace and type. */\nconst dedupeTripleMatches = (\n entry: CommittedDurableEvent,\n input: FindEventByDedupeKeyInput,\n): boolean => {\n const envelope = durableEventEnvelope(entry.event);\n return (\n envelope.dedupeKey === input.dedupeKey &&\n envelope.namespace === input.namespace &&\n envelope.type === input.type\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\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(eventSchemaNamespaces(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 findEventByDedupeKey: (input) =>\n store\n .findEventByDedupeKey(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): entry is CommittedDurableEvent<E> => entry !== undefined),\n Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER),\n Stream.runCollect,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0DA,MAAa,wBAQT,OAAO,OAAO;CAChB,UAAU;CACV,OAAO,qBAAqB,KAC1B,OAAO,SAAS,OAAO,QAA6B,OAAO,GAAG,mBAAmB,CAAC,GAAG;EACnF,QAAQ,aAAa,UAAU,sBAAsB;EACrD,QAAQ,aAAa,UAAU,oBAAoB;CACrD,CAAC,CACH;AACF,CAAC;;;;;;;;AAQD,IAAa,uBAAb,cAA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"../sink-checkpoint-store-DvuHwvx_.js";
1
+ import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-CUvIVvlZ.js";
2
2
  export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
@@ -1,2 +1,2 @@
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";
1
+ import { At as EDASinkCheckpoint, Ct as EDADurableSinkDefinition, Dt as EDARawDurableSinkDefinition, Et as EDAProjectedSink, Ft as EDASinkRegistry, It as EDASinkRegistryShape, Lt as EDASinkRunnerStartInput, Mt as EDASinkDurableBatch, Nt as EDASinkInterests, Ot as EDARawSink, Pt as EDASinkRawDurableBatch, Tt as EDAProjectedDurableSinkDefinition, jt as EDASinkContext, kt as EDASink, wt as EDAEphemeralSinkDefinition } from "../reduced-state-DB_iANjR.js";
2
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-DskRcyOS.js";
1
+ import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-AOjX5_A1.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.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"];
23
+ declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.decide", "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
@@ -26,6 +26,7 @@ const SpanNames = defineSpanNames([
26
26
  "agent.command.submit.wait",
27
27
  "agent.command.wait",
28
28
  "agent.compaction",
29
+ "agent.decide",
29
30
  "agent.events.follow",
30
31
  "agent.events.page",
31
32
  "agent.events.stream",
@@ -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.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
+ {"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.decide\",\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;CACA;AACF,CAAC"}
@@ -1,2 +1,2 @@
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";
1
+ import { cn as EDAToolRegistry, dn as ToolRecovery, fn as ToolRecoveryPolicy, hn as toolRecoveryPolicy, ln as EDAToolRegistryShape, mn as maxToolCallAttempts, on as EDAModelToolkit, pn as makeEDAToolkit, sn as EDAToolExecutionContext, un as ToolParamsSchema } from "../reduced-state-DB_iANjR.js";
2
2
  export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, ToolRecovery, ToolRecoveryPolicy, makeEDAToolkit, maxToolCallAttempts, toolRecoveryPolicy };
@@ -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/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,QAAQ,IAAI,KAAK,aAAa,YAAY;AACjF;;AAwDA,MAAa,kBACX,OACA,aACmC;CACnC,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;CACrC,OAAO,QAAQ,KACb,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,CAAC,GACxC,OAAO,KAAK,iBAAiB,YAA0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A2B,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 { EDADecider, EDADeciderError, EDADeciderOutcome } from \"./decider\";\nimport type { SessionCommandAdmissionConflict } from \"./session-admission\";\nimport type { EDASessionSnapshot } from \"./session-query\";\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 /**\n * Emit an app durable event through `SessionState`, never directly through the store. A payload\n * that is not JSON-native, is over `maxAppEventBytes`, or does not match the registered\n * `appEvents` schema fails with a `SessionCommandAdmissionConflict` and commits nothing.\n */\n readonly emitDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<CommittedDurableEvent, EDASessionStoreError | SessionCommandAdmissionConflict>;\n /**\n * Run a registered decider for this session: it reads the committed state and appends its\n * marker and items in one step, so nothing can commit in between. Use it when the fact the tool\n * emits depends on state. Pass `toolCallId` in the input and use it as the idempotency key, so a\n * call re-invoked under `ToolRecovery: \"reinvoke\"` finds the first acceptance. Return facts, not\n * commands: a command admitted from inside the run it affects is legal but confusing.\n */\n readonly decide: <Input, Result, Rejection>(\n decider: EDADecider<string, Input, Result, Rejection>,\n input: Input,\n ) => Effect.Effect<\n EDADeciderOutcome<Result, Rejection>,\n EDASessionStoreError | SessionCommandAdmissionConflict | EDADeciderError\n >;\n /**\n * Read the session's framework state and app reducer states, as `EDARuntime.snapshot` does.\n * For a tool that only reads (to prefill a form, say). The state can be stale by the time the\n * tool emits: when what the tool writes depends on it, use `decide` instead.\n */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot>;\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":";;;;;;;;;AA4BA,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,QAAQ,IAAI,KAAK,aAAa,YAAY;AACjF;;AAgFA,MAAa,kBACX,OACA,aACmC;CACnC,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;CACrC,OAAO,QAAQ,KACb,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,CAAC,GACxC,OAAO,KAAK,iBAAiB,YAA0C,CACzE;AACF;AAEA,MAAM,oBAAoB,aAAgE;CACxF,kBAAkB,aAAa,OAAO,QAAQ,SAAS,MAAM,SAAS,EAAE,gBAAgB;CACxF,uBAAuB,OAAO,QAAQ,OAAO;CAC7C,UAAU,UAAU,QAAQ,aAC1B,OAAO,IAAI,aAAa;EACtB,IAAI,YAAY,KAAA,KAAa,QAAQ,MAAM,cAAc,KAAA,GACvD,OAAO,OAAO,OAAO,qBAAK,IAAI,MAAM,kCAAkC,UAAU,CAAC;EAGnF,MAAM,UAAU,QAAQ,OAAO,QAAQ,OAAO,UAAU,MAAM,EAAA,CAAG,KAAK,OAAO,UAAU;EACvF,MAAM,QAAQ,MAAM,KAAK,OAAO,CAAC,CAC9B,QAAQ,WAAW,CAAC,OAAO,WAAW,CAAC,CACvC,GAAG,EAAE;EACR,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,OAAO,qBAAK,IAAI,MAAM,QAAQ,SAAS,kCAAkC,CAAC;EAE1F,IAAI,MAAM,WACR,OAAO,OAAO,OAAO,KAAK,MAAM,MAAM;EAExC,OAAO,MAAM;CACf,CAAC;AACL;AAEA,MAAM,sBACJ,YACgC;CAChC,IAAI,QAAQ,SAAS,GACnB;CAUF,OAAO;EACL,OARY,OAAO,YACnB,MAAM,KAAK,QAAQ,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY,CACpD,MACA,KAAK,QAAQ,MAAM,EAAE,YAAY,OAAO,CAAC,CAC3C,CAAC,CAIG;EACJ,UAAU,SACR,OAAO,oBACL,IAAI,MAAM,mDAAmD,MAAM,CACrE;CACJ;AACF;;AAGA,IAAa,kBAAb,MAAa,wBAAwB,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,6 +1,6 @@
1
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";
2
+ import { y as UsagePayload } from "../envelope-CJnPfbjC.js";
3
+ import "../events-AIIwZ6dS.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Tracer from "effect/Tracer";
6
6
  //#region src/services/tracing.d.ts
@@ -0,0 +1,138 @@
1
+ import { MessageId } from "./types/core.js";
2
+ import { x as maxAppEventBytes, y as effectDurableAgentNamespace } from "./envelope-BSI_Xh-f.js";
3
+ import { Mr as decodeRetainingExcess, qn as decodeDurableEventSync } from "./durable-Da57Rcml.js";
4
+ import * as Context from "effect/Context";
5
+ import * as Schema from "effect/Schema";
6
+ import * as Result from "effect/Result";
7
+ import * as Brand from "effect/Brand";
8
+ //#region src/services/session-admission.ts
9
+ /**
10
+ * Admission rules every app-written durable event passes before it reaches the store, shared by
11
+ * `submit`, decider drafts, tool `emitDurable` and sink `stageDurable`. A refusal here is not a
12
+ * store error, so it never makes the live runtime fatal. Internal: not an exported subpath.
13
+ */
14
+ var SessionCommandAdmissionConflict = class extends Schema.TaggedError()("SessionCommandAdmissionConflict", {
15
+ code: Schema.Literals([
16
+ "queue_paused",
17
+ "paused_queue_changed",
18
+ "event_too_large",
19
+ "framework_event",
20
+ "invalid_event",
21
+ "payload_not_json"
22
+ ]),
23
+ message: Schema.String,
24
+ pausedMessageIds: Schema.Array(MessageId)
25
+ }) {};
26
+ /**
27
+ * Framework event types app code may still write through `submit`, decider drafts, `emitDurable`
28
+ * and `stageDurable`: a session seed (`SessionConfigured`, `SystemMessageCommitted`) and imported
29
+ * history. Every other `effect-durable-agent` event is the framework's alone; a forged
30
+ * `DeciderAccepted` would make a later decision replay a result nobody decided.
31
+ */
32
+ const appWritableFrameworkEventTypes = /* @__PURE__ */ new Set([
33
+ "SessionConfigured",
34
+ "SystemMessageCommitted",
35
+ "AssistantMessageImported"
36
+ ]);
37
+ /** App event schemas are a union of structs with literal namespaces; throw for any other shape. */
38
+ const eventSchemaNamespaces = (ast) => {
39
+ if (ast._tag === "Union") return ast.types.flatMap(eventSchemaNamespaces);
40
+ if (ast._tag === "Objects") {
41
+ const namespace = ast.propertySignatures.find((field) => field.name === "namespace")?.type;
42
+ if (namespace?._tag === "Literal" && typeof namespace.literal === "string") return [namespace.literal];
43
+ }
44
+ throw new Error("App event schemas must be a union of structs with literal namespaces");
45
+ };
46
+ /**
47
+ * The JSON form the store keeps, `JSON.parse(JSON.stringify(value))`, or why `value` has none.
48
+ * The round trip may only drop an object property whose value is `undefined`; anything else it
49
+ * would change is refused rather than silently rewritten: anything with a prototype (`Redacted`,
50
+ * `Option`, `Date`, a class instance), `undefined` in an array, a non-finite number, a bigint, a
51
+ * function, a symbol or a cycle. Every check that must hold for what is stored runs on this form.
52
+ */
53
+ const storedJsonForm = (value, path) => {
54
+ const violation = jsonNativeAt(value, path, /* @__PURE__ */ new Set());
55
+ if (violation !== void 0) return Result.fail(violation);
56
+ const json = JSON.parse(JSON.stringify(value));
57
+ return Result.succeed(json);
58
+ };
59
+ const jsonNativeAt = (value, path, seen) => {
60
+ if (value === null || typeof value === "string" || typeof value === "boolean") return void 0;
61
+ if (typeof value === "number") return Number.isFinite(value) ? void 0 : `${path} is the non-finite number ${value}`;
62
+ if (typeof value !== "object") return `${path} is a ${typeof value}`;
63
+ if (seen.has(value)) return `${path} is a cycle`;
64
+ seen.add(value);
65
+ try {
66
+ if (Array.isArray(value)) {
67
+ for (let index = 0; index < value.length; index += 1) {
68
+ if (!(index in value) || value[index] === void 0) return `${path}[${index}] is undefined`;
69
+ const violation = jsonNativeAt(value[index], `${path}[${index}]`, seen);
70
+ if (violation !== void 0) return violation;
71
+ }
72
+ return;
73
+ }
74
+ const prototype = Object.getPrototypeOf(value);
75
+ if (prototype !== Object.prototype && prototype !== null) return `${path} is not a plain object (prototype ${(typeof prototype === "object" && prototype !== null && "constructor" in prototype && typeof prototype.constructor === "function" ? prototype.constructor.name : "unknown") || "anonymous"})`;
76
+ if (Object.getOwnPropertySymbols(value).length > 0) return `${path} has symbol keys`;
77
+ for (const [key, entry] of Object.entries(value)) {
78
+ if (entry === void 0) continue;
79
+ const violation = jsonNativeAt(entry, `${path}.${key}`, seen);
80
+ if (violation !== void 0) return violation;
81
+ }
82
+ return;
83
+ } finally {
84
+ seen.delete(value);
85
+ }
86
+ };
87
+ const jsonEncoder = new TextEncoder();
88
+ /** UTF-8 size of a JSON-native value's JSON text. */
89
+ const jsonBytes = (value) => {
90
+ const json = JSON.stringify(value);
91
+ return json === void 0 ? 0 : jsonEncoder.encode(json).byteLength;
92
+ };
93
+ /** The runtime's registered `appEvents` union; absent for a framework-only runtime. */
94
+ const RegisteredAppEvents = Context.Reference("effect-durable-agent/RegisteredAppEvents", { defaultValue: () => void 0 });
95
+ const AdmittedAppEvent = Brand.nominal();
96
+ /** Build the checker for a runtime, with its registered `appEvents` codec if any. */
97
+ const makeAppEventAdmission = (appEvents) => {
98
+ const namespaces = new Set(appEvents === void 0 ? [] : eventSchemaNamespaces(appEvents.ast));
99
+ const decode = appEvents === void 0 ? void 0 : decodeRetainingExcess(appEvents);
100
+ const describe = (event) => `Event ${event.namespace}/${event.type} ${event.eventId}`;
101
+ const refuse = (code, message) => Result.fail({
102
+ code,
103
+ message
104
+ });
105
+ return { admit: (event) => {
106
+ const isFramework = event.namespace === effectDurableAgentNamespace;
107
+ if (isFramework && !appWritableFrameworkEventTypes.has(event.type)) return refuse("framework_event", `${describe(event)} is a framework lifecycle event; app code may write only ${Array.from(appWritableFrameworkEventTypes).join(", ")}`);
108
+ const payload = storedJsonForm(event.payload, "payload");
109
+ if (Result.isFailure(payload)) return refuse("payload_not_json", `${describe(event)} payload is not JSON-native: ${payload.failure}. Encode it before writing; the store keeps JSON only.`);
110
+ const stored = {
111
+ ...event,
112
+ payload: payload.success
113
+ };
114
+ const bytes = jsonBytes(stored.payload);
115
+ if (bytes > 1048576) return refuse("event_too_large", `${describe(event)} payload is ${bytes} bytes; the limit is ${maxAppEventBytes} bytes`);
116
+ try {
117
+ if (isFramework) decodeDurableEventSync(stored);
118
+ } catch (cause) {
119
+ return refuse("invalid_event", `${describe(event)} does not match its framework event schema once stored as JSON: ${String(cause)}`);
120
+ }
121
+ try {
122
+ if (decode !== void 0 && namespaces.has(event.namespace)) decode(stored);
123
+ } catch (cause) {
124
+ return refuse("invalid_event", `${describe(event)} does not match the registered appEvents schema once stored as JSON: ${String(cause)}`);
125
+ }
126
+ return Result.succeed(AdmittedAppEvent(stored));
127
+ } };
128
+ };
129
+ /** The admission conflict a refused `submit` item fails with. */
130
+ const appEventConflict = (refusal) => new SessionCommandAdmissionConflict({
131
+ code: refusal.code,
132
+ message: refusal.message,
133
+ pausedMessageIds: []
134
+ });
135
+ //#endregion
136
+ export { jsonBytes as a, eventSchemaNamespaces as i, SessionCommandAdmissionConflict as n, makeAppEventAdmission as o, appEventConflict as r, storedJsonForm as s, RegisteredAppEvents as t };
137
+
138
+ //# sourceMappingURL=session-admission-WE8J_0z9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-admission-WE8J_0z9.js","names":[],"sources":["../src/services/session-admission.ts"],"sourcesContent":["import * as Brand from \"effect/Brand\";\nimport * as Context from \"effect/Context\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\n\nimport { MessageId } from \"../types/core\";\nimport {\n type DurableEventEnvelope,\n effectDurableAgentNamespace,\n maxAppEventBytes,\n} from \"../types/events/envelope\";\nimport { decodeDurableEventSync } from \"../types/events/durable\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\n\n/**\n * Admission rules every app-written durable event passes before it reaches the store, shared by\n * `submit`, decider drafts, tool `emitDurable` and sink `stageDurable`. A refusal here is not a\n * store error, so it never makes the live runtime fatal. Internal: not an exported subpath.\n */\n\nexport class SessionCommandAdmissionConflict extends Schema.TaggedError<SessionCommandAdmissionConflict>()(\n \"SessionCommandAdmissionConflict\",\n {\n code: Schema.Literals([\n \"queue_paused\",\n \"paused_queue_changed\",\n \"event_too_large\",\n \"framework_event\",\n \"invalid_event\",\n \"payload_not_json\",\n ]),\n message: Schema.String,\n pausedMessageIds: Schema.Array(MessageId),\n },\n) {}\n\n/** Why an app event is refused. */\nexport interface AppEventRefusal {\n readonly code: \"event_too_large\" | \"framework_event\" | \"invalid_event\" | \"payload_not_json\";\n readonly message: string;\n}\n\n/**\n * Framework event types app code may still write through `submit`, decider drafts, `emitDurable`\n * and `stageDurable`: a session seed (`SessionConfigured`, `SystemMessageCommitted`) and imported\n * history. Every other `effect-durable-agent` event is the framework's alone; a forged\n * `DeciderAccepted` would make a later decision replay a result nobody decided.\n */\nexport const appWritableFrameworkEventTypes: ReadonlySet<string> = new Set([\n \"SessionConfigured\",\n \"SystemMessageCommitted\",\n \"AssistantMessageImported\",\n]);\n\n/** App event schemas are a union of structs with literal namespaces; throw for any other shape. */\nexport const eventSchemaNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventSchemaNamespaces);\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/**\n * The JSON form the store keeps, `JSON.parse(JSON.stringify(value))`, or why `value` has none.\n * The round trip may only drop an object property whose value is `undefined`; anything else it\n * would change is refused rather than silently rewritten: anything with a prototype (`Redacted`,\n * `Option`, `Date`, a class instance), `undefined` in an array, a non-finite number, a bigint, a\n * function, a symbol or a cycle. Every check that must hold for what is stored runs on this form.\n */\nexport const storedJsonForm = (\n value: unknown,\n path: string,\n): Result.Result<Schema.Json, string> => {\n const violation = jsonNativeAt(value, path, new Set());\n if (violation !== undefined) return Result.fail(violation);\n const json: Schema.Json = JSON.parse(JSON.stringify(value));\n return Result.succeed(json);\n};\n\nconst jsonNativeAt = (value: unknown, path: string, seen: Set<object>): string | undefined => {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return undefined;\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? undefined : `${path} is the non-finite number ${value}`;\n }\n if (typeof value !== \"object\") return `${path} is a ${typeof value}`;\n if (seen.has(value)) return `${path} is a cycle`;\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index += 1) {\n if (!(index in value) || value[index] === undefined) {\n return `${path}[${index}] is undefined`;\n }\n const violation = jsonNativeAt(value[index], `${path}[${index}]`, seen);\n if (violation !== undefined) return violation;\n }\n return undefined;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n const name =\n typeof prototype === \"object\" &&\n prototype !== null &&\n \"constructor\" in prototype &&\n typeof prototype.constructor === \"function\"\n ? prototype.constructor.name\n : \"unknown\";\n return `${path} is not a plain object (prototype ${name || \"anonymous\"})`;\n }\n if (Object.getOwnPropertySymbols(value).length > 0) return `${path} has symbol keys`;\n for (const [key, entry] of Object.entries(value)) {\n if (entry === undefined) continue;\n const violation = jsonNativeAt(entry, `${path}.${key}`, seen);\n if (violation !== undefined) return violation;\n }\n return undefined;\n } finally {\n seen.delete(value);\n }\n};\n\nconst jsonEncoder = new TextEncoder();\n\n/** UTF-8 size of a JSON-native value's JSON text. */\nexport const jsonBytes = (value: unknown): number => {\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? 0 : jsonEncoder.encode(json).byteLength;\n};\n\n/** The registered application event union, if the runtime has one. */\nexport type AppEventCodec = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\n/** The runtime's registered `appEvents` union; absent for a framework-only runtime. */\nexport const RegisteredAppEvents = Context.Reference<AppEventCodec | undefined>(\n \"effect-durable-agent/RegisteredAppEvents\",\n { defaultValue: () => undefined },\n);\n\n/**\n * An app-written durable event that passed admission. Its payload is already the JSON form the\n * store keeps, so what is appended is exactly what was checked. Only `admit` makes one.\n */\nexport type AdmittedAppEvent = DurableEventEnvelope & Brand.Brand<\"AdmittedAppEvent\">;\nconst AdmittedAppEvent = Brand.nominal<AdmittedAppEvent>();\n\n/** Admits app-written durable events under the runtime's rules. */\nexport interface AppEventAdmission {\n /**\n * The event to append in place of `event`, or why it is refused. The payload is replaced by its\n * stored JSON form first; the size, framework-schema and `appEvents` checks all read that form.\n */\n readonly admit: (event: DurableEventEnvelope) => Result.Result<AdmittedAppEvent, AppEventRefusal>;\n}\n\n/** Build the checker for a runtime, with its registered `appEvents` codec if any. */\nexport const makeAppEventAdmission = (appEvents: AppEventCodec | undefined): AppEventAdmission => {\n const namespaces = new Set(appEvents === undefined ? [] : eventSchemaNamespaces(appEvents.ast));\n const decode = appEvents === undefined ? undefined : decodeRetainingExcess(appEvents);\n const describe = (event: DurableEventEnvelope) =>\n `Event ${event.namespace}/${event.type} ${event.eventId}`;\n const refuse = (code: AppEventRefusal[\"code\"], message: string) =>\n Result.fail<AppEventRefusal>({ code, message });\n return {\n admit: (event) => {\n const isFramework = event.namespace === effectDurableAgentNamespace;\n if (isFramework && !appWritableFrameworkEventTypes.has(event.type)) {\n return refuse(\n \"framework_event\",\n `${describe(event)} is a framework lifecycle event; app code may write only ${Array.from(appWritableFrameworkEventTypes).join(\", \")}`,\n );\n }\n const payload = storedJsonForm(event.payload, \"payload\");\n if (Result.isFailure(payload)) {\n return refuse(\n \"payload_not_json\",\n `${describe(event)} payload is not JSON-native: ${payload.failure}. Encode it before writing; the store keeps JSON only.`,\n );\n }\n const stored = { ...event, payload: payload.success };\n const bytes = jsonBytes(stored.payload);\n if (bytes > maxAppEventBytes) {\n return refuse(\n \"event_too_large\",\n `${describe(event)} payload is ${bytes} bytes; the limit is ${maxAppEventBytes} bytes`,\n );\n }\n try {\n // The store decodes framework events with their own schema and would fail a malformed one\n // as a store error, so an allowlisted type is checked against that schema here.\n if (isFramework) decodeDurableEventSync(stored);\n } catch (cause) {\n return refuse(\n \"invalid_event\",\n `${describe(event)} does not match its framework event schema once stored as JSON: ${String(cause)}`,\n );\n }\n try {\n if (decode !== undefined && namespaces.has(event.namespace)) decode(stored);\n } catch (cause) {\n return refuse(\n \"invalid_event\",\n `${describe(event)} does not match the registered appEvents schema once stored as JSON: ${String(cause)}`,\n );\n }\n return Result.succeed(AdmittedAppEvent(stored));\n },\n };\n};\n\n/** The admission conflict a refused `submit` item fails with. */\nexport const appEventConflict = (refusal: AppEventRefusal): SessionCommandAdmissionConflict =>\n new SessionCommandAdmissionConflict({\n code: refusal.code,\n message: refusal.message,\n pausedMessageIds: [],\n });\n"],"mappings":";;;;;;;;;;;;;AAqBA,IAAa,kCAAb,cAAqD,OAAO,YAA6C,CAAC,CACxG,mCACA;CACE,MAAM,OAAO,SAAS;EACpB;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,SAAS,OAAO;CAChB,kBAAkB,OAAO,MAAM,SAAS;AAC1C,CACF,CAAC,CAAC,CAAC;;;;;;;AAcH,MAAa,iDAAsD,IAAI,IAAI;CACzE;CACA;CACA;AACF,CAAC;;AAGD,MAAa,yBAAyB,QAA8C;CAClF,IAAI,IAAI,SAAS,SAAS,OAAO,IAAI,MAAM,QAAQ,qBAAqB;CACxE,IAAI,IAAI,SAAS,WAAW;EAC1B,MAAM,YAAY,IAAI,mBAAmB,MAAM,UAAU,MAAM,SAAS,WAAW,CAAC,EAAE;EACtF,IAAI,WAAW,SAAS,aAAa,OAAO,UAAU,YAAY,UAChE,OAAO,CAAC,UAAU,OAAO;CAC7B;CACA,MAAM,IAAI,MAAM,sEAAsE;AACxF;;;;;;;;AASA,MAAa,kBACX,OACA,SACuC;CACvC,MAAM,YAAY,aAAa,OAAO,sBAAM,IAAI,IAAI,CAAC;CACrD,IAAI,cAAc,KAAA,GAAW,OAAO,OAAO,KAAK,SAAS;CACzD,MAAM,OAAoB,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;CAC1D,OAAO,OAAO,QAAQ,IAAI;AAC5B;AA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AkE,OAAO,KAAK,GACnG;EACF;EACA,IAAI;GACF,IAAI,WAAW,KAAA,KAAa,WAAW,IAAI,MAAM,SAAS,GAAG,OAAO,MAAM;EAC5E,SAAS,OAAO;GACd,OAAO,OACL,iBACA,GAAG,SAAS,KAAK,EAAE,uEAAuE,OAAO,KAAK,GACxG;EACF;EACA,OAAO,OAAO,QAAQ,iBAAiB,MAAM,CAAC;CAChD,EACF;AACF;;AAGA,MAAa,oBAAoB,YAC/B,IAAI,gCAAgC;CAClC,MAAM,QAAQ;CACd,SAAS,QAAQ;CACjB,kBAAkB,CAAC;AACrB,CAAC"}
@@ -1,5 +1,5 @@
1
- import { f as PositionedEvent } from "./envelope-Che6KatU.js";
2
- import "./events-DwTARLMv.js";
1
+ import { p as PositionedEvent } from "./envelope-CJnPfbjC.js";
2
+ import "./events-AIIwZ6dS.js";
3
3
  import * as Context from "effect/Context";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Layer from "effect/Layer";
@@ -21,4 +21,4 @@ declare class SessionEventObserver extends SessionEventObserver_base {
21
21
  }
22
22
  //#endregion
23
23
  export { SessionEventObserverShape as n, SessionEventObserver as t };
24
- //# sourceMappingURL=session-event-observer-DlP9ITB2.d.ts.map
24
+ //# sourceMappingURL=session-event-observer-BWQUJTcN.d.ts.map