effect-durable-agent 0.1.0-alpha.16 → 0.1.0-alpha.18
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.
- package/dist/{compaction-CCdfxYkq.js → compaction-Db6eoLce.js} +3 -3
- package/dist/{compaction-CCdfxYkq.js.map → compaction-Db6eoLce.js.map} +1 -1
- package/dist/{context-projection-C43pyxn2.d.ts → context-projection-Dr_kA41k.d.ts} +3 -3
- package/dist/domain/command-queues.d.ts +82 -2
- package/dist/domain/context-projection.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/model-usage.d.ts +1 -1
- package/dist/domain/model-usage.js +1 -1
- package/dist/domain/reduced-state-schema.d.ts +3 -992
- package/dist/domain/reduced-state-schema.js +116 -4
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +2 -2
- package/dist/domain/reduced-state.js +1 -1
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/{durable-D_tjjz4B.js → durable-DRY7AcsF.js} +59 -40
- package/dist/durable-DRY7AcsF.js.map +1 -0
- package/dist/{durable-RSiz3YBK.d.ts → durable-DeQBR5wA.d.ts} +4266 -235
- package/dist/{envelope-DxQzo5rN.js → envelope-BCzKUq_z.js} +12 -3
- package/dist/envelope-BCzKUq_z.js.map +1 -0
- package/dist/{envelope-DkZyMIgp.d.ts → envelope-VXFEC8zr.d.ts} +68 -4
- package/dist/{event-factory-CX0_laE5.js → event-factory-CKuWhjS4.js} +3 -3
- package/dist/{event-factory-CX0_laE5.js.map → event-factory-CKuWhjS4.js.map} +1 -1
- package/dist/{events-LZFNoESe.d.ts → events-D3OAPXgS.d.ts} +22 -22
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-ci5D5WQv.d.ts} +2 -2
- package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-CNcnhj72.d.ts} +2 -2
- package/dist/{reduced-state-BAKvToAh.js → reduced-state-DFIYylAq.js} +55 -56
- package/dist/reduced-state-DFIYylAq.js.map +1 -0
- package/dist/reduced-state-schema-CgW0mzpS.d.ts +2167 -0
- package/dist/reduced-state-xY-tYuGo.d.ts +47902 -0
- package/dist/{reducer-registry-BgtK0NuX.d.ts → reducer-registry-bRbc4COf.d.ts} +7 -4
- package/dist/{run-scheduling-wakeup-DRYZztL6.d.ts → run-scheduling-wakeup-CY5hfgMR.d.ts} +2 -2
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -1
- package/dist/services/model-resolver.d.ts +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/reducer-registry.js +19 -6
- package/dist/services/reducer-registry.js.map +1 -1
- package/dist/services/run-scheduler.d.ts +1 -2
- package/dist/services/run-scheduling-wakeup.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +11 -13
- package/dist/services/runtime-layer.js +11 -7
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +17 -9
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-query.d.ts +2 -2
- package/dist/services/session-query.js +30 -13
- package/dist/services/session-query.js.map +1 -1
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +2 -2
- package/dist/services/session-store.js +84 -16
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/tracing.d.ts +1 -1
- package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-BWppl2Fr.d.ts} +2 -2
- package/dist/{session-state-CWKwjwdx.js → session-state-8PJZvuR3.js} +28 -20
- package/dist/session-state-8PJZvuR3.js.map +1 -0
- package/dist/{session-store-DCs--1kc.d.ts → session-store-CERvTeaV.d.ts} +25 -40
- package/dist/{sink-checkpoint-store-CasqHvDz.d.ts → sink-checkpoint-store-DTiswoqy.d.ts} +2 -2
- package/dist/{sink-registry-DUkifMag.js → sink-registry-B4yxTmlI.js} +33 -8
- package/dist/sink-registry-B4yxTmlI.js.map +1 -0
- package/dist/testkit/layers.d.ts +10 -16
- package/dist/testkit/layers.js +6 -6
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-CHMtDCJ5.d.ts → tool-registry-D4ALie3K.d.ts} +11 -4
- package/dist/types/events/durable.d.ts +2 -2
- package/dist/types/events/durable.js +2 -2
- package/dist/types/events.d.ts +4 -4
- package/dist/types/events.js +3 -3
- package/dist/websocket.d.ts +66 -66
- package/dist/websocket.js +2 -2
- package/package.json +1 -1
- package/dist/command-queues-CtOtDZm3.d.ts +0 -556
- package/dist/compaction-BfzzyWko.d.ts +0 -165
- package/dist/durable-D_tjjz4B.js.map +0 -1
- package/dist/envelope-DxQzo5rN.js.map +0 -1
- package/dist/event-factory-CClLXzI9.d.ts +0 -91
- package/dist/index-BVVgDSdq.d.ts +0 -1
- package/dist/message-transcript-CEp0gCSQ.d.ts +0 -32
- package/dist/prompt-projector-Dh1-qvCH.d.ts +0 -39
- package/dist/reduced-state-BAKvToAh.js.map +0 -1
- package/dist/run-scheduler-CpPjFQD7.d.ts +0 -43
- package/dist/runtime-CX1M7jgX.d.ts +0 -69
- package/dist/session-query-BHB4OxR_.d.ts +0 -46
- package/dist/session-state-CWKwjwdx.js.map +0 -1
- package/dist/session-state-dE07Zzcr.d.ts +0 -895
- package/dist/sink-registry-CEBjrMd_.d.ts +0 -140
- package/dist/sink-registry-DUkifMag.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { RunRequestOutcome } from \"../domain/run-scheduling\";\nimport {\n RunSchedulingRequestedPayload,\n RunSchedulingGrantedPayload,\n RunSchedulingInvalidatedPayload,\n RunCompletedPayload,\n RunFailedPayload,\n RunInterruptedPayload,\n effectDurableAgentNamespace,\n} from \"../types/events\";\nimport { type RunRequestId, SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */\nexport interface EDASessionSnapshot {\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly messages: ReadonlyArray<DurableTranscriptMessage>;\n}\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Reconcile one request against committed facts, including after reducer history pruning. */\n readonly runRequestOutcome: (\n requestId: RunRequestId,\n ) => Effect.Effect<RunRequestOutcome, EDASessionStoreError>;\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n runRequestOutcome: Effect.fn(\"agent.run.request.outcome\")(function* (\n requestId: RunRequestId,\n ) {\n const head = (yield* sessionState.snapshot()).lastSeq;\n let outcome: RunRequestOutcome = { _tag: \"Unknown\" };\n yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((entry) => entry.position.seq <= head),\n Stream.runForEach((entry) =>\n Effect.sync(() => {\n const event = entry.event;\n if (event.namespace !== effectDurableAgentNamespace) return;\n switch (event.type) {\n case \"RunSchedulingRequested\":\n if (\n Schema.decodeUnknownSync(RunSchedulingRequestedPayload)(event.payload)\n .requestId === requestId\n )\n outcome = { _tag: \"Waiting\" };\n break;\n case \"RunSchedulingInvalidated\":\n if (\n Schema.decodeUnknownSync(RunSchedulingInvalidatedPayload)(event.payload)\n .requestId === requestId\n )\n outcome = { _tag: \"Invalidated\" };\n break;\n case \"RunSchedulingGranted\": {\n const grant = Schema.decodeUnknownSync(RunSchedulingGrantedPayload)(\n event.payload,\n );\n if (grant.requestId === requestId)\n outcome = { _tag: \"Granted\", runId: grant.runId, status: \"Running\" };\n break;\n }\n case \"RunCompleted\":\n if (\n outcome._tag === \"Granted\" &&\n Schema.decodeUnknownSync(RunCompletedPayload)(event.payload).runId ===\n outcome.runId\n )\n outcome = { ...outcome, status: \"Completed\" };\n break;\n case \"RunFailed\":\n if (\n outcome._tag === \"Granted\" &&\n Schema.decodeUnknownSync(RunFailedPayload)(event.payload).runId ===\n outcome.runId\n )\n outcome = { ...outcome, status: \"Failed\" };\n break;\n case \"RunInterrupted\":\n if (\n outcome._tag === \"Granted\" &&\n Schema.decodeUnknownSync(RunInterruptedPayload)(event.payload).runId ===\n outcome.runId\n )\n outcome = { ...outcome, status: \"Interrupted\" };\n break;\n }\n }),\n ),\n );\n return outcome;\n }),\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({ position: entry.position, event: entry.event }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({ position: entry.position, event: entry.event }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.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S;AACpE;AAEA,MAAM,0BACJ,WACmC;CACnC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport { ReducedStateSchema, QueryMessageRecordSchema } from \"../domain/reduced-state-schema\";\nimport { durableEventEnvelope } from \"../types/events/durable\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport { RunRequestOutcome } from \"../domain/run-scheduling\";\nimport { effectDurableAgentNamespace } from \"../types/events\";\nimport { type RunRequestId, SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Reconnect-safe transcript query preserving the existing structured-clone Prompt parts. */\nexport const DurableTranscriptMessages = Schema.Array(\n Schema.Union([\n QueryMessageRecordSchema.members[1],\n QueryMessageRecordSchema.members[3],\n QueryMessageRecordSchema.members[4],\n Schema.Struct({ ...QueryMessageRecordSchema.members[2].fields, consumedSeq: SequenceNumber }),\n ]),\n);\n/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */\nexport const EDASessionSnapshot = Schema.Struct({\n state: ReducedStateSchema,\n reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown),\n messages: DurableTranscriptMessages,\n});\nexport type EDASessionSnapshot = typeof EDASessionSnapshot.Type;\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Reconcile one request against committed facts, including after reducer history pruning. */\n readonly runRequestOutcome: (\n requestId: RunRequestId,\n ) => Effect.Effect<RunRequestOutcome, EDASessionStoreError>;\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n runRequestOutcome: Effect.fn(\"agent.run.request.outcome\")(function* (\n requestId: RunRequestId,\n ) {\n const head = (yield* sessionState.snapshot()).lastSeq;\n let outcome: RunRequestOutcome = { _tag: \"Unknown\" };\n yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((entry) => entry.position.seq <= head),\n Stream.runForEach((entry) =>\n Effect.sync(() => {\n const event = entry.event;\n if (event.namespace !== effectDurableAgentNamespace) return;\n switch (event.type) {\n case \"RunSchedulingRequested\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Waiting\" };\n break;\n case \"RunSchedulingInvalidated\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Invalidated\" };\n break;\n case \"RunSchedulingGranted\": {\n const grant = event.payload;\n if (grant.requestId === requestId)\n outcome = { _tag: \"Granted\", runId: grant.runId, status: \"Running\" };\n break;\n }\n case \"RunCompleted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Completed\" };\n break;\n case \"RunFailed\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Failed\" };\n break;\n case \"RunInterrupted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Interrupted\" };\n break;\n }\n }),\n ),\n );\n return outcome;\n }),\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n output.push(event);\n }\n return output;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAa,4BAA4B,OAAO,MAC9C,OAAO,MAAM;CACX,yBAAyB,QAAQ;CACjC,yBAAyB,QAAQ;CACjC,yBAAyB,QAAQ;CACjC,OAAO,OAAO;EAAE,GAAG,yBAAyB,QAAQ,GAAG;EAAQ,aAAa;CAAe,CAAC;AAC9F,CAAC,CACH;;AAEA,MAAa,qBAAqB,OAAO,OAAO;CAC9C,OAAO;CACP,eAAe,OAAO,YAAY,OAAO,QAAQ,OAAO,OAAO;CAC/D,UAAU;AACZ,CAAC;;AAsCD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO;EACvB,MAAM,eAAe,OAAO;EAE5B,MAAM,WAAW,OAAO,IAAI,aAAa;GACvC,MAAM,OAAO,OAAO,aAAa,aAAa;GAC9C,OAAO;IACL,OAAO,KAAK;IACZ,eAAe,KAAK;IACpB,UAAU,yBAAyB,KAAK,OAAO;GACjD;EACF,CAAC;EAED,OAAO;GACL,mBAAmB,OAAO,GAAG,2BAA2B,EAAE,WACxD,WACA;IACA,MAAM,QAAQ,OAAO,aAAa,SAAS,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;MACnB,UAAU,MAAM;MAChB,OAAO,qBAAqB,MAAM,KAAK;KACzC,CAAC,CACH,GACA,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;KACiB;IAAK;GACxB,CAAC,EAAE,KACD,OAAO,SAAS,qBAAqB,EACnC,YAAY;IAAE,iBAAiB;IAAU,kBAAkB;GAAM,EACnE,CAAC,CACH;EACJ;CACF,CAAC,CACH;AACF;AAEA,MAAM,uBAAuB,OAAwB,eACnD,MAAM,MAAM,eAAe,eAAe,MAAM,SAAS,MAAM;AAEjE,MAAM,2BAA2B,MAAuB,UAAmC;CACzF,MAAM,MAAM,KAAK,SAAS,MAAM,MAAM,SAAS;CAC/C,OAAO,QAAQ,IAAI,KAAK,SAAS,SAAS,MAAM,SAAS,SAAS;AACpE;AAEA,MAAM,0BACJ,WACmC;CACnC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ct as SessionState, Et as SessionStateSnapshotData, St as SessionRunInput, Tt as SessionStateShape, _t as SessionDrainProcessed, bt as SessionNoRunnableCommand, dt as SessionCommandAdmissionError, ft as SessionCommandCancelled, gt as SessionCommandResult, ht as SessionCommandOutcome, lt as EDASubmittable, mt as SessionCommandFailed, pt as SessionCommandCompleted, ut as SessionCommandAdmissionConflict, vt as SessionDrainResult, wt as SessionStateError, xt as SessionNoRunnableReason, yt as SessionForkedCommand } from "../reduced-state-xY-tYuGo.js";
|
|
2
2
|
export { EDASubmittable, SessionCommandAdmissionConflict, SessionCommandAdmissionError, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionCommandResult, SessionDrainProcessed, SessionDrainResult, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState, SessionStateError, SessionStateShape, SessionStateSnapshotData };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SessionCommandOutcome, c as SessionNoRunnableReason, i as SessionCommandFailed, l as SessionRunInput, n as SessionCommandCancelled, o as SessionForkedCommand, r as SessionCommandCompleted, s as SessionNoRunnableCommand, t as SessionCommandAdmissionConflict, u as SessionState } from "../session-state-
|
|
1
|
+
import { a as SessionCommandOutcome, c as SessionNoRunnableReason, i as SessionCommandFailed, l as SessionRunInput, n as SessionCommandCancelled, o as SessionForkedCommand, r as SessionCommandCompleted, s as SessionNoRunnableCommand, t as SessionCommandAdmissionConflict, u as SessionState } from "../session-state-8PJZvuR3.js";
|
|
2
2
|
export { SessionCommandAdmissionConflict, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError };
|
|
1
|
+
import { a as EDAReducerCheckpoint, c as EDASessionStoreShape, d as hasEDASessionStoreError, f as queryCommittedEvents, i as EDAAppEvents, l as FindCommandAdmissionInput, m as selectCommittedEvent, n as DurableAppendBatch, o as EDASessionStore, p as registerAppEvents, r as DurableAppendEntry, s as EDASessionStoreError, t as CommittedDurableEvent, u as SaveReducerCheckpointInput } from "../session-store-CERvTeaV.js";
|
|
2
|
+
export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAAppEvents, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError, queryCommittedEvents, registerAppEvents, selectCommittedEvent };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CommandId, DurablePosition, SequenceNumber, durablePosition } from "../types/core.js";
|
|
2
|
-
import { t as DurableEventEnvelope } from "../envelope-
|
|
3
|
-
import {
|
|
2
|
+
import { t as DurableEventEnvelope } from "../envelope-BCzKUq_z.js";
|
|
3
|
+
import { H as DecodedDurableEvent, Nn as commandAdmittedEventType, Un as contextRebasedEventType, Wn as decodeDurableEventSync, mr as summaryCreatedEventType, qn as durableEventEnvelope } from "../durable-DRY7AcsF.js";
|
|
4
4
|
import { CompactionSummaryArtifact } from "../domain/context-projection.js";
|
|
5
5
|
import * as Context from "effect/Context";
|
|
6
6
|
import * as Effect from "effect/Effect";
|
|
@@ -9,11 +9,15 @@ import * as Schema from "effect/Schema";
|
|
|
9
9
|
import * as Stream from "effect/Stream";
|
|
10
10
|
import * as Cause from "effect/Cause";
|
|
11
11
|
import * as Ref from "effect/Ref";
|
|
12
|
+
import * as SchemaGetter from "effect/SchemaGetter";
|
|
12
13
|
//#region src/services/session-store.ts
|
|
13
14
|
/** A durable event after the store has assigned its replay position. */
|
|
14
15
|
const CommittedDurableEvent = Schema.Struct({
|
|
15
16
|
position: DurablePosition,
|
|
16
|
-
event: DurableEventEnvelope
|
|
17
|
+
event: DurableEventEnvelope.pipe(Schema.decodeTo(Schema.declare(Schema.is(DecodedDurableEvent)), {
|
|
18
|
+
decode: SchemaGetter.transform(decodeDurableEventSync),
|
|
19
|
+
encode: SchemaGetter.transform(durableEventEnvelope)
|
|
20
|
+
}))
|
|
17
21
|
});
|
|
18
22
|
/**
|
|
19
23
|
* Store-level failure surfaced by durable append, replay, and hydration APIs.
|
|
@@ -78,10 +82,10 @@ const seedCommittedEvents = (sessionId, events) => {
|
|
|
78
82
|
if (event.sessionId !== sessionId) throw new Error(`EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`);
|
|
79
83
|
if (seen.has(event.eventId)) throw new Error(`Duplicate seed eventId ${event.eventId}`);
|
|
80
84
|
seen.add(event.eventId);
|
|
81
|
-
return
|
|
85
|
+
return {
|
|
82
86
|
position: durablePosition(SequenceNumber.make(index + 1)),
|
|
83
|
-
event
|
|
84
|
-
}
|
|
87
|
+
event: decodeDurableEventSync(DurableEventEnvelope.make(event))
|
|
88
|
+
};
|
|
85
89
|
});
|
|
86
90
|
};
|
|
87
91
|
const summariesFromCommittedEvents = (events) => {
|
|
@@ -90,7 +94,7 @@ const summariesFromCommittedEvents = (events) => {
|
|
|
90
94
|
if (event.type !== summaryCreatedEventType) continue;
|
|
91
95
|
const payload = event.payload;
|
|
92
96
|
if (payload.summary !== void 0) {
|
|
93
|
-
const summary =
|
|
97
|
+
const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
|
|
94
98
|
summaries.set(summary.summaryId, summary);
|
|
95
99
|
}
|
|
96
100
|
}
|
|
@@ -120,21 +124,21 @@ const makeInMemoryStore = (sessionId, data) => {
|
|
|
120
124
|
committedEvents.push(existing);
|
|
121
125
|
continue;
|
|
122
126
|
}
|
|
123
|
-
const committed =
|
|
127
|
+
const committed = {
|
|
124
128
|
position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),
|
|
125
|
-
event
|
|
126
|
-
}
|
|
129
|
+
event: decodeDurableEventSync(DurableEventEnvelope.make(event))
|
|
130
|
+
};
|
|
127
131
|
nextEntries.push(committed);
|
|
128
132
|
committedEvents.push(committed);
|
|
129
|
-
if (event.type === summaryCreatedEventType) {
|
|
130
|
-
const payload = event.payload;
|
|
133
|
+
if (committed.event.type === summaryCreatedEventType) {
|
|
134
|
+
const payload = committed.event.payload;
|
|
131
135
|
if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
|
|
132
|
-
const summary =
|
|
136
|
+
const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
|
|
133
137
|
if (payload.summaryId !== void 0 && summary.summaryId !== payload.summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
|
|
134
138
|
nextSummaries.set(summary.summaryId, summary);
|
|
135
139
|
}
|
|
136
|
-
if (event.type === contextRebasedEventType) {
|
|
137
|
-
const payload = event.payload;
|
|
140
|
+
if (committed.event.type === contextRebasedEventType) {
|
|
141
|
+
const payload = committed.event.payload;
|
|
138
142
|
if (payload.summaryId === void 0 || !nextSummaries.has(payload.summaryId)) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
|
|
139
143
|
}
|
|
140
144
|
}
|
|
@@ -176,7 +180,71 @@ const commandAdmissionMatches = (entry, input) => {
|
|
|
176
180
|
if (input.idempotencyKey !== void 0 && admitted.idempotencyKey === input.idempotencyKey) return true;
|
|
177
181
|
return input.commandId !== void 0 && admitted.commandId === input.commandId;
|
|
178
182
|
};
|
|
183
|
+
const eventNamespaces = (ast) => {
|
|
184
|
+
if (ast._tag === "Union") return ast.types.flatMap(eventNamespaces);
|
|
185
|
+
if (ast._tag === "Objects") {
|
|
186
|
+
const namespace = ast.propertySignatures.find((field) => field.name === "namespace")?.type;
|
|
187
|
+
if (namespace?._tag === "Literal" && typeof namespace.literal === "string") return [namespace.literal];
|
|
188
|
+
}
|
|
189
|
+
throw new Error("App event schemas must be a union of structs with literal namespaces");
|
|
190
|
+
};
|
|
191
|
+
/** Attach the app decoder to every event-returning store operation without changing storage bytes. */
|
|
192
|
+
const registerAppEvents = (store, schema) => {
|
|
193
|
+
const namespaces = new Set(eventNamespaces(schema.ast));
|
|
194
|
+
const decode = Schema.decodeUnknownSync(schema);
|
|
195
|
+
const envelopeKey = (event) => JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));
|
|
196
|
+
const decodeEntry = (entry, prepared) => {
|
|
197
|
+
if (entry.event.namespace !== "__foreign" || !namespaces.has(entry.event.envelope.namespace)) return entry;
|
|
198
|
+
return {
|
|
199
|
+
...entry,
|
|
200
|
+
event: {
|
|
201
|
+
...entry.event,
|
|
202
|
+
decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope, { onExcessProperty: "preserve" })
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
};
|
|
206
|
+
const decodeEntryEffect = (entry) => Effect.try({
|
|
207
|
+
try: () => decodeEntry(entry),
|
|
208
|
+
catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
|
|
209
|
+
});
|
|
210
|
+
const decodeEntries = (entries) => Effect.forEach(entries, decodeEntryEffect);
|
|
211
|
+
return {
|
|
212
|
+
...store,
|
|
213
|
+
append: (batch) => Effect.gen(function* () {
|
|
214
|
+
const prepared = yield* Effect.try({
|
|
215
|
+
try: () => {
|
|
216
|
+
const decoded = /* @__PURE__ */ new Map();
|
|
217
|
+
for (const { event } of batch.entries) {
|
|
218
|
+
if (!namespaces.has(event.namespace)) continue;
|
|
219
|
+
const key = envelopeKey(event);
|
|
220
|
+
if (!decoded.has(key)) decoded.set(key, decode(event, { onExcessProperty: "preserve" }));
|
|
221
|
+
}
|
|
222
|
+
return decoded;
|
|
223
|
+
},
|
|
224
|
+
catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
|
|
225
|
+
});
|
|
226
|
+
const committed = yield* store.append(batch);
|
|
227
|
+
return yield* Effect.forEach(committed, (entry) => Effect.try({
|
|
228
|
+
try: () => decodeEntry(entry, prepared),
|
|
229
|
+
catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
|
|
230
|
+
}));
|
|
231
|
+
}),
|
|
232
|
+
eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),
|
|
233
|
+
loadCommittedEventsBySeq: (seqs) => store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),
|
|
234
|
+
findCommandAdmission: (input) => store.findCommandAdmission(input).pipe(Effect.flatMap((entry) => entry === void 0 ? Effect.succeed(void 0) : decodeEntryEffect(entry)))
|
|
235
|
+
};
|
|
236
|
+
};
|
|
237
|
+
/** Narrow an already decoded fact from one schema, without decoding its payload again. */
|
|
238
|
+
const selectCommittedEvent = (schema, entry) => {
|
|
239
|
+
const event = entry.event.namespace === "__foreign" ? entry.event.decoded ?? entry.event.envelope : entry.event;
|
|
240
|
+
return Schema.is(schema)(event) ? {
|
|
241
|
+
position: entry.position,
|
|
242
|
+
event
|
|
243
|
+
} : void 0;
|
|
244
|
+
};
|
|
245
|
+
/** Typed journal read available to tools and application services without private SQL access. */
|
|
246
|
+
const queryCommittedEvents = (store, schema, options = {}) => store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(Stream.map((entry) => selectCommittedEvent(schema, entry)), Stream.filter((entry) => entry !== void 0), Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER), Stream.runCollect);
|
|
179
247
|
//#endregion
|
|
180
|
-
export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDASessionStore, EDASessionStoreError, FindCommandAdmissionInput, hasEDASessionStoreError };
|
|
248
|
+
export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDASessionStore, EDASessionStoreError, FindCommandAdmissionInput, hasEDASessionStoreError, queryCommittedEvents, registerAppEvents, selectCommittedEvent };
|
|
181
249
|
|
|
182
250
|
//# sourceMappingURL=session-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { type CommandIdempotencyKey, type EDACommand } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope,\n});\nexport type CommittedDurableEvent = typeof CommittedDurableEvent.Type;\n\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedErrorClass<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /** Deterministic in-memory implementation used by runtime and recovery tests. */\n static readonly InMemory = (sessionId: SessionId) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const data = yield* Ref.make<InMemoryStoreData>(emptyInMemoryStoreData());\n return makeInMemoryStore(sessionId, data);\n }),\n );\n\n /** In-memory store seeded with a durable prefix; intended for recovery tests. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n ) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const committed = seedCommittedEvents(sessionId, events);\n const data = yield* Ref.make<InMemoryStoreData>({\n ...emptyInMemoryStoreData(),\n committed,\n summaries: summariesFromCommittedEvents(committed),\n });\n return makeInMemoryStore(sessionId, data);\n }),\n );\n}\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n}\n\nconst emptyInMemoryStoreData = (): InMemoryStoreData => ({\n committed: [],\n summaries: new Map(),\n reducerCheckpoints: new Map(),\n});\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(index + 1)),\n event,\n });\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload as { readonly summary?: unknown };\n if (payload.summary !== undefined) {\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed = CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event,\n });\n nextEntries.push(committed);\n committedEvents.push(committed);\n\n if (event.type === summaryCreatedEventType) {\n const payload = event.payload as {\n readonly summary?: unknown;\n readonly summaryId?: CompactionSummaryArtifact[\"summaryId\"];\n };\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (event.type === contextRebasedEventType) {\n const payload = event.payload as { readonly summaryId?: SummaryId };\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = (entry.event.payload as { readonly command?: EDACommand }).command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,wBAAwB,OAAO,OAAO;CACjD,UAAU;CACV,OAAO;AACT,CAAC;;;;;;;;AAUD,IAAa,uBAAb,cAA0C,OAAO,iBAAuC,EACtF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,EAAE,CAAC;;AAGH,MAAa,2BAA2B,UACtC,MAAM,QAAQ,MACX,WAAW,MAAM,aAAa,MAAM,KAAK,OAAO,iBAAiB,oBACpE;;;;;;;AAQF,MAAa,qBAAqB,OAAO,OAAO,EAC9C,OAAO,qBACT,CAAC;;;;;;;;AAUD,MAAa,qBAAqB,OAAO,OAAO,EAC9C,SAAS,OAAO,MAAM,kBAAkB,EAC1C,CAAC;;AAsBD,MAAa,4BAA4B,OAAO,OAAO;CACrD,WAAW,OAAO,YAAY,SAAS;CACvC,gBAAgB,OAAO,YAAY,OAAO,MAAM;AAClD,CAAC;;;;;;;;AAwDD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;;CAEA,OAAgB,YAAY,cAC1B,MAAM,OACJ,iBACA,OAAO,IAAI,aAAa;EA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OACA,UACY;CACZ,IAAI,MAAM,MAAM,SAAS,0BACvB,OAAO;CAET,MAAM,WAAY,MAAM,MAAM,QAA8C;CAC5E,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,mBAAmB,KAAA,KAAa,SAAS,mBAAmB,MAAM,gBAC1E,OAAO;CAET,OAAO,MAAM,cAAc,KAAA,KAAa,SAAS,cAAc,MAAM;AACvE"}
|
|
1
|
+
{"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as 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\";\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.TaggedErrorClass<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /** Deterministic in-memory implementation used by runtime and recovery tests. */\n static readonly InMemory = (sessionId: SessionId) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const data = yield* Ref.make<InMemoryStoreData>(emptyInMemoryStoreData());\n return makeInMemoryStore(sessionId, data);\n }),\n );\n\n /** In-memory store seeded with a durable prefix; intended for recovery tests. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n ) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const committed = seedCommittedEvents(sessionId, events);\n const data = yield* Ref.make<InMemoryStoreData>({\n ...emptyInMemoryStoreData(),\n committed,\n summaries: summariesFromCommittedEvents(committed),\n });\n return makeInMemoryStore(sessionId, data);\n }),\n );\n}\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n}\n\nconst emptyInMemoryStoreData = (): InMemoryStoreData => ({\n committed: [],\n summaries: new Map(),\n reducerCheckpoints: new Map(),\n});\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return {\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\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\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 },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = entry.event.payload.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 = Schema.decodeUnknownSync(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:\n prepared?.get(envelopeKey(entry.event.envelope)) ??\n decode(entry.event.envelope, { onExcessProperty: \"preserve\" }),\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, { onExcessProperty: \"preserve\" }));\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":";;;;;;;;;;;;;;AAuCA,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,iBAAuC,EACtF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,EAAE,CAAC;;AAGH,MAAa,2BAA2B,UACtC,MAAM,QAAQ,MACX,WAAW,MAAM,aAAa,MAAM,KAAK,OAAO,iBAAiB,oBACpE;;;;;;;AAQF,MAAa,qBAAqB,OAAO,OAAO,EAC9C,OAAO,qBACT,CAAC;;;;;;;;AAUD,MAAa,qBAAqB,OAAO,OAAO,EAC9C,SAAS,OAAO,MAAM,kBAAkB,EAC1C,CAAC;;AAsBD,MAAa,4BAA4B,OAAO,OAAO;CACrD,WAAW,OAAO,YAAY,SAAS;CACvC,gBAAgB,OAAO,YAAY,OAAO,MAAM;AAClD,CAAC;;;;;;;;AAwDD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;;CAEA,OAAgB,YAAY,cAC1B,MAAM,OACJ,iBACA,OAAO,IAAI,aAAa;EAEtB,OAAO,kBAAkB,WAAW,OADhB,IAAI,KAAwB,uBAAuB,CA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,EAAE,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,EAAE,KAC5D,OAAO,KAAK,UAAU,qBAAqB,QAAQ,KAAK,CAAC,GACzD,OAAO,QAAQ,UAA6C,UAAU,KAAA,CAAS,GAC/E,OAAO,KAAK,QAAQ,SAAS,OAAO,gBAAgB,GACpD,OAAO,UACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-
|
|
1
|
+
import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-DTiswoqy.js";
|
|
2
2
|
export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $t as EDAProjectedSink, Qt as EDAProjectedDurableSinkDefinition, Xt as EDADurableSinkDefinition, Zt as EDAEphemeralSinkDefinition, an as EDASinkDurableBatch, cn as EDASinkRegistry, en as EDARawDurableSinkDefinition, in as EDASinkContext, ln as EDASinkRegistryShape, nn as EDASink, on as EDASinkInterests, rn as EDASinkCheckpoint, sn as EDASinkRawDurableBatch, tn as EDARawSink, un as EDASinkRunnerStartInput } from "../reduced-state-xY-tYuGo.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-
|
|
1
|
+
import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-B4yxTmlI.js";
|
|
2
2
|
export { EDASink, EDASinkRegistry };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as ToolParamsSchema, i as EDAToolRegistryShape, n as EDAToolExecutionContext, o as makeEDAToolkit, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-
|
|
1
|
+
import { a as ToolParamsSchema, i as EDAToolRegistryShape, n as EDAToolExecutionContext, o as makeEDAToolkit, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-D4ALie3K.js";
|
|
2
2
|
export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tool from \"effect/unstable/ai/Tool\";\nimport * as Toolkit from \"effect/unstable/ai/Toolkit\";\n\nimport { EventId, SessionId, ToolCallId } from \"../types/core\";\nimport { DurableEventEnvelope, ToolName } from \"../types/events\";\nimport type { CommittedDurableEvent, EDASessionStoreError } from \"./session-store\";\n\n/** Runtime parameter schema associated with a provider-visible tool name. */\nexport type ToolParamsSchema = Schema.Top;\n\n/** Provider-visible Effect AI toolkit with handlers available for local execution. */\nexport type EDAModelToolkit = Toolkit.WithHandler<Record<string, Tool.Any>>;\n\n/** Framework context passed to product tool handlers without model-visible params. */\nexport interface EDAToolExecutionContext {\n /** Framework-owned tool-call identity for this execution. */\n readonly toolCallId: ToolCallId;\n /** Session identity fixed for this runtime instance. */\n readonly sessionId: SessionId;\n /** Mint an app durable event id for tool-emitted facts. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Emit an app durable event through `SessionState`, never directly through the store. */\n readonly emitDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<CommittedDurableEvent, EDASessionStoreError>;\n}\n\n/** Registry contract used by model streaming and post-finish tool execution. */\nexport interface EDAToolRegistryShape {\n /** Look up the parameter schema for a registered tool name. */\n readonly getParamsSchema: (toolName: ToolName) => Effect.Effect<ToolParamsSchema | undefined>;\n /** Build provider-visible tool definitions while keeping EDA in charge of lifecycle events. */\n readonly getModelToolkit: () => Effect.Effect<EDAModelToolkit | undefined>;\n /** Execute a tool. EDA records the durable lifecycle around this effect. */\n readonly execute: (\n toolName: ToolName,\n params: unknown,\n context: EDAToolExecutionContext,\n ) => Effect.Effect<unknown, unknown>;\n}\n\n/** Build a handler-backed Effect Toolkit from tools and handlers. */\nexport const makeEDAToolkit = <const Tools extends ReadonlyArray<Tool.Any>>(\n tools: Tools,\n handlers: Toolkit.HandlersFrom<Toolkit.ToolsByName<Tools>>,\n): Effect.Effect<EDAModelToolkit> => {\n const toolkit = Toolkit.make(...tools);\n return toolkit.pipe(\n Effect.provide(toolkit.toLayer(handlers)),\n Effect.map((withHandlers) => withHandlers as unknown as EDAModelToolkit),\n );\n};\n\nconst makeToolRegistry = (toolkit: EDAModelToolkit | undefined): EDAToolRegistryShape => ({\n getParamsSchema: (toolName) => Effect.succeed(toolkit?.tools[toolName]?.parametersSchema),\n getModelToolkit: () => Effect.succeed(toolkit),\n execute: (toolName, params, _context) =>\n Effect.gen(function* () {\n if (toolkit === undefined || toolkit.tools[toolName] === undefined) {\n return yield* Effect.fail(new Error(`No handler registered for tool ${toolName}`));\n }\n\n const results = yield* (yield* toolkit.handle(toolName, params)).pipe(Stream.runCollect);\n const final = Array.from(results)\n .filter((result) => !result.preliminary)\n .at(-1);\n if (final === undefined) {\n return yield* Effect.fail(new Error(`Tool ${toolName} completed without a final result`));\n }\n if (final.isFailure) {\n return yield* Effect.fail(final.result);\n }\n return final.encodedResult;\n }) as Effect.Effect<unknown, unknown>,\n});\n\nconst toolkitFromSchemas = (\n schemas: ReadonlyMap<string, ToolParamsSchema>,\n): EDAModelToolkit | undefined => {\n if (schemas.size === 0) {\n return undefined;\n }\n\n const tools = Object.fromEntries(\n Array.from(schemas.entries()).map(([name, schema]) => [\n name,\n Tool.dynamic(name, { parameters: schema }),\n ]),\n );\n\n return {\n tools,\n handle: ((name: string) =>\n Effect.die(\n new Error(`No test handler registered for schema-only tool ${name}`),\n )) as unknown as EDAModelToolkit[\"handle\"],\n };\n};\n\n/** Registry of Effect AI tools available to the model and EDA lifecycle executor. */\nexport class EDAToolRegistry extends Context.Service<EDAToolRegistry, EDAToolRegistryShape>()(\n \"@effect-durable-agent/EDAToolRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDAToolRegistry, makeToolRegistry(undefined));\n\n static readonly FromToolkit = (toolkit: EDAModelToolkit) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkit));\n\n static readonly FromToolkitEffect = <E, R>(toolkit: Effect.Effect<EDAModelToolkit, E, R>) =>\n Layer.effect(\n EDAToolRegistry,\n toolkit.pipe(Effect.map((withHandlers) => makeToolRegistry(withHandlers))),\n );\n\n static readonly FromShape = (shape: EDAToolRegistryShape) =>\n Layer.succeed(EDAToolRegistry, shape);\n\n static readonly FromShapeEffect = <E, R>(shape: Effect.Effect<EDAToolRegistryShape, E, R>) =>\n Layer.effect(EDAToolRegistry, shape);\n\n /** Test/convenience schema-only tools. Runtime execution will fail unless a real Toolkit is provided. */\n static readonly FromSchemas = (schemas: ReadonlyMap<string, ToolParamsSchema>) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkitFromSchemas(schemas)));\n}\n"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tool from \"effect/unstable/ai/Tool\";\nimport * as Toolkit from \"effect/unstable/ai/Toolkit\";\n\nimport { EventId, SessionId, ToolCallId, RunId, TurnId } from \"../types/core\";\nimport { DurableEventEnvelope, ToolName } from \"../types/events\";\nimport type { CommittedDurableEvent, EDASessionStoreError } from \"./session-store\";\n\n/** Runtime parameter schema associated with a provider-visible tool name. */\nexport type ToolParamsSchema = Schema.Top;\n\n/** Provider-visible Effect AI toolkit with handlers available for local execution. */\nexport type EDAModelToolkit = Toolkit.WithHandler<Record<string, Tool.Any>>;\n\n/** Framework context passed to product tool handlers without model-visible params. */\nexport interface EDAToolExecutionContext {\n /** Framework-owned tool-call identity for this execution. */\n readonly toolCallId: ToolCallId;\n /** 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. */\n readonly queryEvents: <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n options?: { readonly limit?: number },\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\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":";;;;;;;;;AAuDA,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,WAAW,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,GAAG,KAAK,OAAO,UAAU;EACvF,MAAM,QAAQ,MAAM,KAAK,OAAO,EAC7B,QAAQ,WAAW,CAAC,OAAO,WAAW,EACtC,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,EAAE,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,EAC1F,uCACF,EAAE;CACA,OAAgB,QAAQ,MAAM,QAAQ,iBAAiB,iBAAiB,KAAA,CAAS,CAAC;CAElF,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,OAAO,CAAC;CAE1D,OAAgB,qBAA2B,YACzC,MAAM,OACJ,iBACA,QAAQ,KAAK,OAAO,KAAK,iBAAiB,iBAAiB,YAAY,CAAC,CAAC,CAC3E;CAEF,OAAgB,aAAa,UAC3B,MAAM,QAAQ,iBAAiB,KAAK;CAEtC,OAAgB,mBAAyB,UACvC,MAAM,OAAO,iBAAiB,KAAK;;CAGrC,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,mBAAmB,OAAO,CAAC,CAAC;AAChF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { _ as UsagePayload } from "../envelope-DkZyMIgp.js";
|
|
2
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-BXHAkxkx.js";
|
|
2
|
+
import { v as UsagePayload } from "../envelope-VXFEC8zr.js";
|
|
3
3
|
import * as Effect from "effect/Effect";
|
|
4
4
|
import * as Tracer from "effect/Tracer";
|
|
5
5
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { f as PositionedEvent } from "./envelope-VXFEC8zr.js";
|
|
2
2
|
import * as Context from "effect/Context";
|
|
3
3
|
import * as Effect from "effect/Effect";
|
|
4
4
|
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-
|
|
24
|
+
//# sourceMappingURL=session-event-observer-BWppl2Fr.d.ts.map
|
|
@@ -4,21 +4,21 @@ import { canGrantRun, planRunSchedulingCancellation, planWaitingRunInterruption,
|
|
|
4
4
|
import { RunScheduler } from "./services/run-scheduler.js";
|
|
5
5
|
import { ModelResolver } from "./services/model-resolver.js";
|
|
6
6
|
import { makeEDARunTrace } from "./types/tracing.js";
|
|
7
|
-
import {
|
|
7
|
+
import { d as PositionedEvent, f as ProviderPartId, h as ToolName, l as ModelSelectionPayload, m as SystemPromptText, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
|
|
8
8
|
import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
|
|
9
|
-
import {
|
|
10
|
-
import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-
|
|
9
|
+
import { Jn as inferenceCompletedEventType, Kt as ToolCallCreatedEvent, Sr as turnFailedEventType, Yn as inferenceFailedEventType, _ as CommandAdmittedEvent, _r as toolCallCreatedEventType, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent, pn as TurnStartedEvent, qn as durableEventEnvelope, yr as toolCallRejectedEventType } from "./durable-DRY7AcsF.js";
|
|
10
|
+
import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-DFIYylAq.js";
|
|
11
11
|
import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
|
|
12
|
-
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError } from "./services/session-store.js";
|
|
13
|
-
import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-
|
|
12
|
+
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
|
|
13
|
+
import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-Db6eoLce.js";
|
|
14
14
|
import { IdGenerator } from "./services/id-generator.js";
|
|
15
|
-
import { n as SessionContext, t as EventFactory } from "./event-factory-
|
|
15
|
+
import { n as SessionContext, t as EventFactory } from "./event-factory-CKuWhjS4.js";
|
|
16
16
|
import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
17
17
|
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
18
18
|
import { SessionEventObserver } from "./services/session-event-observer.js";
|
|
19
19
|
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
20
20
|
import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
|
|
21
|
-
import { n as EDASinkRegistry } from "./sink-registry-
|
|
21
|
+
import { n as EDASinkRegistry } from "./sink-registry-B4yxTmlI.js";
|
|
22
22
|
import { EDAToolRegistry } from "./services/tool-registry.js";
|
|
23
23
|
import * as Context from "effect/Context";
|
|
24
24
|
import * as Effect from "effect/Effect";
|
|
@@ -287,12 +287,12 @@ const makeLiveBus = (pubsub, activeTurnReplay, observer) => ({
|
|
|
287
287
|
});
|
|
288
288
|
const updateActiveTurnReplay = (ref, event) => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));
|
|
289
289
|
const nextActiveTurnReplay = (state, event) => {
|
|
290
|
-
if (event.event
|
|
290
|
+
if (Schema.is(TurnStartedEvent)(event.event)) return {
|
|
291
291
|
turnId: event.event.payload.turnId,
|
|
292
292
|
events: [],
|
|
293
293
|
overflowed: false
|
|
294
294
|
};
|
|
295
|
-
if (event.event
|
|
295
|
+
if (Schema.is(TurnCompletedEvent)(event.event) || Schema.is(TurnFailedEvent)(event.event) || Schema.is(TurnStoppedEvent)(event.event)) {
|
|
296
296
|
const turnId = event.event.payload.turnId;
|
|
297
297
|
return turnId === void 0 || state.turnId === void 0 || turnId === state.turnId ? {
|
|
298
298
|
events: [],
|
|
@@ -377,6 +377,7 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
377
377
|
const ids = yield* IdGenerator;
|
|
378
378
|
const registry = yield* EDAToolRegistry;
|
|
379
379
|
const session = yield* SessionContext;
|
|
380
|
+
const store = yield* EDASessionStore;
|
|
380
381
|
const failToolCall = (input, created, error) => Effect.gen(function* () {
|
|
381
382
|
const event = yield* events.toolCallFailed({
|
|
382
383
|
toolCallId: created.event.payload.toolCallId,
|
|
@@ -406,6 +407,9 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
406
407
|
body: () => Effect.gen(function* () {
|
|
407
408
|
const handled = yield* registry.execute(created.event.payload.promptPart.name, created.event.payload.promptPart.params, {
|
|
408
409
|
toolCallId: created.event.payload.toolCallId,
|
|
410
|
+
runId: created.event.payload.runId,
|
|
411
|
+
turnId: created.event.payload.turnId,
|
|
412
|
+
queryEvents: (schema, options) => queryCommittedEvents(store, schema, options),
|
|
409
413
|
sessionId: session.sessionId,
|
|
410
414
|
makeEventId: ids.makeEventId,
|
|
411
415
|
emitDurable: input.eventSink.appendDurable
|
|
@@ -1107,7 +1111,8 @@ var InferenceRunner = class InferenceRunner extends Context.Service()("@effect-d
|
|
|
1107
1111
|
};
|
|
1108
1112
|
const inferenceUsageAttributes = (terminal) => {
|
|
1109
1113
|
if (terminal._tag !== "InferenceRunFinished") return {};
|
|
1110
|
-
|
|
1114
|
+
const completed = terminal.committed.find((entry) => entry.event.type === "InferenceCompleted");
|
|
1115
|
+
return usageAttributes(completed?.event.type === "InferenceCompleted" ? completed.event.payload.usage : void 0);
|
|
1111
1116
|
};
|
|
1112
1117
|
const initialRunInferenceState = (identity) => ({
|
|
1113
1118
|
inference: initialInferenceState(identity),
|
|
@@ -1459,11 +1464,11 @@ const requireFrameworkCreatedToolCalls = (created) => Effect.gen(function* () {
|
|
|
1459
1464
|
if (unsupported !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Provider-executed tool calls are unsupported: ${unsupported.event.payload.promptPart.name}`));
|
|
1460
1465
|
return created;
|
|
1461
1466
|
});
|
|
1462
|
-
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.payload.usage) : {};
|
|
1463
|
-
const isInferenceCompleted = (committed) => committed.event.type === inferenceCompletedEventType;
|
|
1464
|
-
const isInferenceFailed = (committed) => committed.event.type === inferenceFailedEventType;
|
|
1465
|
-
const isToolCallCreated = (committed) => committed.event.
|
|
1466
|
-
const isToolCallRejected = (committed) => committed.event.type === toolCallRejectedEventType;
|
|
1467
|
+
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.type === "TurnCompleted" ? result.outcome.committed.event.payload.usage : void 0) : {};
|
|
1468
|
+
const isInferenceCompleted = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceCompletedEventType;
|
|
1469
|
+
const isInferenceFailed = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceFailedEventType;
|
|
1470
|
+
const isToolCallCreated = (committed) => committed.event.namespace === "effect-durable-agent" && Schema.is(ToolCallCreatedEvent)(committed.event);
|
|
1471
|
+
const isToolCallRejected = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === toolCallRejectedEventType;
|
|
1467
1472
|
const isToolDecisionBoundary = (committed) => isToolCallCreated(committed) || isToolCallRejected(committed);
|
|
1468
1473
|
const requireInferenceCompleted = (committed) => {
|
|
1469
1474
|
const completed = committed.find(isInferenceCompleted);
|
|
@@ -1664,7 +1669,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1664
1669
|
reducerStates: nextReducerStates,
|
|
1665
1670
|
ephemeral: current.ephemeral
|
|
1666
1671
|
});
|
|
1667
|
-
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make(
|
|
1672
|
+
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make({
|
|
1673
|
+
position: entry.position,
|
|
1674
|
+
event: durableEventEnvelope(entry.event)
|
|
1675
|
+
}));
|
|
1668
1676
|
return { head: nextReduced.lastSeq };
|
|
1669
1677
|
});
|
|
1670
1678
|
const snapshot = () => Ref.get(state).pipe(Effect.map((state) => state.reduced));
|
|
@@ -1745,8 +1753,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1745
1753
|
}
|
|
1746
1754
|
const existing = yield* findExistingCommandAdmission(command);
|
|
1747
1755
|
if (existing !== void 0) {
|
|
1748
|
-
rememberPreparedCommand(existing.event, preparedByIdempotencyKey, preparedByCommandId);
|
|
1749
|
-
return [existing.event];
|
|
1756
|
+
rememberPreparedCommand(durableEventEnvelope(existing.event), preparedByIdempotencyKey, preparedByCommandId);
|
|
1757
|
+
return [durableEventEnvelope(existing.event)];
|
|
1750
1758
|
}
|
|
1751
1759
|
const commandId = command.commandId ?? (yield* ids.makeCommandId());
|
|
1752
1760
|
const admitted = commandWithId(command, commandId);
|
|
@@ -3134,7 +3142,7 @@ const commandWithId = (command, commandId) => {
|
|
|
3134
3142
|
}
|
|
3135
3143
|
};
|
|
3136
3144
|
const rememberPreparedCommand = (event, preparedByIdempotencyKey, preparedByCommandId) => {
|
|
3137
|
-
if (
|
|
3145
|
+
if (!Schema.is(CommandAdmittedEvent)(event)) return;
|
|
3138
3146
|
const command = event.payload.command;
|
|
3139
3147
|
if (command?.idempotencyKey !== void 0) preparedByIdempotencyKey.set(command.idempotencyKey, event);
|
|
3140
3148
|
if (command?.commandId !== void 0) preparedByCommandId.set(command.commandId, event);
|
|
@@ -3159,4 +3167,4 @@ const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag =
|
|
|
3159
3167
|
//#endregion
|
|
3160
3168
|
export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, LiveEventBus as m, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
|
|
3161
3169
|
|
|
3162
|
-
//# sourceMappingURL=session-state-
|
|
3170
|
+
//# sourceMappingURL=session-state-8PJZvuR3.js.map
|