effect-durable-agent 0.1.0-alpha.6 → 0.1.0-alpha.8
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/{command-queues-C8muEqeQ.d.ts → command-queues-DdDB_aYM.d.ts} +11 -18
- package/dist/{compaction-F4HEWzuI.d.ts → compaction-BEor3jKv.d.ts} +27 -8
- package/dist/compaction-BgDr5VJy.js +473 -0
- package/dist/compaction-BgDr5VJy.js.map +1 -0
- package/dist/{context-projection-C43pyxn2.d.ts → context-projection-n6Rdup0N.d.ts} +2 -2
- package/dist/domain/command-queues.d.ts +1 -1
- 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 +2 -0
- package/dist/domain/model-usage.js +59 -0
- package/dist/domain/model-usage.js.map +1 -0
- package/dist/domain/reduced-state-schema.d.ts +11 -17
- package/dist/domain/reduced-state-schema.js +6 -11
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +3 -2
- package/dist/domain/reduced-state.js +3 -2
- package/dist/{durable-DsV9PxZC.js → durable-BGFvX7Mh.js} +17 -80
- package/dist/durable-BGFvX7Mh.js.map +1 -0
- package/dist/{durable-B7M6TD_0.d.ts → durable-br2C1bWK.d.ts} +247 -4
- package/dist/envelope-DkZyMIgp.d.ts +191 -0
- package/dist/envelope-DxQzo5rN.js +82 -0
- package/dist/envelope-DxQzo5rN.js.map +1 -0
- package/dist/{event-factory-tcpLgdMN.js → event-factory-DTFdy0Cb.js} +3 -2
- package/dist/{event-factory-tcpLgdMN.js.map → event-factory-DTFdy0Cb.js.map} +1 -1
- package/dist/{event-factory-CLJcyymV.d.ts → event-factory-pFzsPlDs.d.ts} +4 -4
- package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
- package/dist/index.d.ts +5 -4
- package/dist/index.js +4 -3
- package/dist/{message-transcript-DsKTT47f.d.ts → message-transcript-DQNlzxle.d.ts} +3 -3
- package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
- package/dist/model-usage-CdBEkTwU.d.ts +55 -0
- package/dist/{prompt-projector-hqPh5-NI.d.ts → prompt-projector-f4ElyXCE.d.ts} +4 -4
- package/dist/{reduced-state-TMi7ISla.js → reduced-state-DF0-6mbR.js} +25 -30
- package/dist/reduced-state-DF0-6mbR.js.map +1 -0
- package/dist/{reducer-registry--vQFATXb.d.ts → reducer-registry-aFjz_ZLT.d.ts} +2 -2
- package/dist/{runtime-BO9KJq_Y.d.ts → runtime-DbTCb32-.d.ts} +5 -5
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -426
- package/dist/services/model-resolver.d.ts +2 -0
- package/dist/services/model-resolver.js +17 -0
- package/dist/services/model-resolver.js.map +1 -0
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +14 -14
- package/dist/services/runtime-layer.js +8 -7
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +3 -2
- 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 +1 -1
- package/dist/services/session-query.js +3 -3
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +1 -1
- package/dist/services/session-store.js +2 -1
- 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/tracing.d.ts +1 -1
- package/dist/{session-event-observer-D_aoFnQs.d.ts → session-event-observer-DaFMKKNc.d.ts} +2 -2
- package/dist/{session-query-_Z3Kw6jj.d.ts → session-query-l8xpJYp8.d.ts} +8 -8
- package/dist/{session-state-BfoXKafd.d.ts → session-state-YHFzOGDf.d.ts} +16 -16
- package/dist/{session-state-C4m0j6CJ.js → session-state-aIqe9CLa.js} +30 -39
- package/dist/session-state-aIqe9CLa.js.map +1 -0
- package/dist/{session-store-ofm8FFxs.d.ts → session-store-Cpi_NwTR.d.ts} +3 -3
- package/dist/{sink-checkpoint-store-BQVbI9DQ.d.ts → sink-checkpoint-store-M7qIxoSH.d.ts} +2 -2
- package/dist/{sink-registry-DH6uiEgP.js → sink-registry-NDgeyzO0.js} +4 -4
- package/dist/{sink-registry-DH6uiEgP.js.map → sink-registry-NDgeyzO0.js.map} +1 -1
- package/dist/{sink-registry-PRYbj6dp.d.ts → sink-registry-T1wOUuzq.d.ts} +9 -9
- package/dist/testkit/layers.d.ts +17 -14
- package/dist/testkit/layers.js +10 -8
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-ClHdr_G5.d.ts → tool-registry-BJaVNtw4.d.ts} +3 -3
- package/dist/types/events/durable.d.ts +2 -2
- package/dist/types/events/durable.js +2 -2
- package/dist/types/events.d.ts +4 -3
- package/dist/types/events.js +3 -2
- package/dist/types/events.js.map +1 -1
- package/dist/websocket.d.ts +83 -4
- package/dist/websocket.js +82 -12
- package/dist/websocket.js.map +1 -1
- package/package.json +10 -1
- package/dist/durable-DsV9PxZC.js.map +0 -1
- package/dist/reduced-state-TMi7ISla.js.map +0 -1
- package/dist/services/compaction.js.map +0 -1
- package/dist/session-state-C4m0j6CJ.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/services/runtime.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\";\n\nimport { EDACommand } from \"../types/commands\";\nimport { CommandId, SequenceNumber, durablePosition } from \"../types/core\";\nimport {\n ModelSelectionPayload,\n NonNegativeInt,\n SystemPromptText,\n commandCancelledEventType,\n commandCompletedEventType,\n commandFailedEventType,\n} from \"../types/events\";\nimport type {\n CommandCancelledEvent,\n CommandCompletedEvent,\n CommandFailedEvent,\n PositionedEvent,\n} from \"../types/events\";\nimport { SessionState } from \"./session-state\";\nimport type { EDASubmittable, SessionCommandAdmissionError } from \"./session-state\";\nimport { CommittedDurableEvent } from \"./session-store\";\nimport { EDASessionQuery } from \"./session-query\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"./tracing\";\nimport type { EDASessionQueryShape } from \"./session-query\";\n\n/** Configuration for one scoped session runtime instance. */\nexport const EDARuntimeConfig = Schema.Struct({\n modelSelection: ModelSelectionPayload,\n /** Maximum framework-owned tool calls one model run may execute before failing safely. */\n maxToolCallsPerRun: Schema.optionalKey(NonNegativeInt),\n systemPrompt: Schema.optionalKey(SystemPromptText),\n});\nexport type EDARuntimeConfig = typeof EDARuntimeConfig.Type;\n\n/** Public runtime error surface for command admission helpers. */\nexport type EDARuntimeError = SessionCommandAdmissionError;\n\n/** Command terminal events observed by blocking runtime helpers. */\nexport type EDACommandTerminalEvent =\n | CommandCompletedEvent\n | CommandFailedEvent\n | CommandCancelledEvent;\n\n/** Committed durable event narrowed to a command terminal boundary. */\nexport type CommittedCommandTerminalEvent = CommittedDurableEvent & {\n readonly event: EDACommandTerminalEvent;\n};\n\n/** Overloaded public submit API for single commands or ordered durable batches. */\nexport interface EDARuntimeSubmit {\n /** Submit one command and return its committed CommandAdmitted event. */\n (command: EDACommand): Effect.Effect<CommittedDurableEvent, EDARuntimeError>;\n /** Submit one ordered durable batch of commands and/or app events. */\n (\n input: ReadonlyArray<EDASubmittable>,\n ): Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDARuntimeError>;\n}\n\n/** Public facade exposed to hosts and route handlers for one live session runtime. */\nexport interface EDARuntimeShape {\n /** Submit commands and/or app durable events durably and wake the dispatch process if needed. */\n readonly submit: EDARuntimeSubmit;\n /** Block until the command reaches CommandCompleted, CommandFailed, or CommandCancelled. */\n readonly blockOnCommand: (\n commandId: CommandId,\n afterSeq?: SequenceNumber,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Admit one command and block until that command reaches a terminal command boundary. */\n readonly submitAndBlock: (\n command: EDACommand,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Read the authoritative live session snapshot. */\n readonly snapshot: EDASessionQueryShape[\"snapshot\"];\n /** Read durable user/assistant messages in committed order. */\n readonly messages: EDASessionQueryShape[\"messages\"];\n /** Backfill durable events after a committed sequence, then follow live events. */\n readonly eventsAfter: EDASessionQueryShape[\"eventsAfter\"];\n /** Read one bounded page of committed durable events plus the committed head. */\n readonly readEventPage: EDASessionQueryShape[\"readEventPage\"];\n}\n\n/** Top-level public facade for one effect-durable-agent session runtime. */\nexport class EDARuntime extends Context.Service<EDARuntime, EDARuntimeShape>()(\n \"@effect-durable-agent/EDARuntime\",\n) {\n static readonly Live = (config: EDARuntimeConfig) =>\n Layer.effect(EDARuntime, makeLiveRuntime(config));\n}\n\nconst makeLiveRuntime = (config: EDARuntimeConfig) =>\n Effect.gen(function* () {\n const sessionState = yield* SessionState;\n const query = yield* EDASessionQuery;\n\n const runInput = {\n modelSelection: config.modelSelection,\n ...(config.maxToolCallsPerRun === undefined\n ? {}\n : { maxToolCallsPerRun: config.maxToolCallsPerRun }),\n ...(config.systemPrompt === undefined ? {} : { systemPrompt: config.systemPrompt }),\n };\n yield* sessionState.start(runInput);\n\n const blockOnCommand = Effect.fn(function* (\n commandId: CommandId,\n afterSeq: SequenceNumber = SequenceNumber.make(0),\n ) {\n yield* annotateEdaSpan({ \"eda.command.id\": commandId, \"eda.seq.after\": afterSeq });\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const events = yield* query.eventsAfter(afterSeq);\n const terminal = yield* events.pipe(\n Stream.filter(isCommandTerminalFor(commandId)),\n Stream.take(1),\n Stream.map(toCommittedCommandTerminal),\n Stream.runCollect,\n Effect.map((events) => events[0]),\n );\n return terminal === undefined\n ? yield* Effect.die(new Error(\"Expected command terminal event\"))\n : terminal;\n }),\n );\n });\n\n const submit = Effect.fn(function* (input: EDACommand | ReadonlyArray<EDASubmittable>) {\n const items = Array.isArray(input) ? input : [input as EDACommand];\n yield* annotateEdaSpan({\n \"eda.command.submittable_count\": items.length,\n \"eda.command.count\": items.filter((item) => \"_tag\" in item).length,\n });\n const committed = Array.isArray(input)\n ? yield* sessionState.submitBatch(input)\n : [yield* sessionState.admitCommand(input as EDACommand)];\n yield* annotateEdaSpan(committedBatchAttributes(committed));\n return Array.isArray(input) ? committed : committed[0]!;\n }) as EDARuntimeSubmit;\n\n return {\n submit,\n blockOnCommand,\n submitAndBlock: Effect.fn(function* (command: EDACommand) {\n yield* annotateEdaSpan({\n \"eda.command.kind\": command._tag,\n \"eda.command.id\": command.commandId,\n \"eda.command.disposition\": \"disposition\" in command ? command.disposition : undefined,\n });\n const admitted = yield* sessionState.admitCommand(command);\n return yield* blockOnCommand(commandIdFromCommandAdmitted(admitted), admitted.position.seq);\n }),\n snapshot: () => query.snapshot(),\n messages: () => query.messages(),\n eventsAfter: (afterSeq: SequenceNumber) => query.eventsAfter(afterSeq),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n query.readEventPage(afterSeq, limit),\n };\n });\n\nconst isCommandTerminalFor =\n (commandId: CommandId) =>\n (event: PositionedEvent): boolean => {\n if (\n event.event.type !== commandCompletedEventType &&\n event.event.type !== commandFailedEventType &&\n event.event.type !== commandCancelledEventType\n ) {\n return false;\n }\n return (event.event.payload as { readonly commandId: CommandId }).commandId === commandId;\n };\n\nconst toCommittedCommandTerminal = (event: PositionedEvent): CommittedCommandTerminalEvent =>\n CommittedDurableEvent.make({\n position: durablePosition(event.position.seq),\n event: event.event as EDACommandTerminalEvent,\n }) as CommittedCommandTerminalEvent;\n\nconst commandIdFromCommandAdmitted = (committed: CommittedDurableEvent): CommandId => {\n const commandId = (committed.event.payload as { readonly command?: EDACommand }).command\n ?.commandId;\n if (commandId === undefined) {\n throw new Error(\"CommandAdmitted event is missing a framework commandId\");\n }\n return commandId;\n};\n"],"mappings":";;;;;;;;;;;;;AA8BA,MAAa,mBAAmB,OAAO,OAAO;CAC5C,gBAAgB;;CAEhB,oBAAoB,OAAO,YAAY,cAAc;CACrD,cAAc,OAAO,YAAY,gBAAgB;AACnD,CAAC;;AAmDD,IAAa,aAAb,MAAa,mBAAmB,QAAQ,QAAqC,EAC3E,kCACF,EAAE;CACA,OAAgB,QAAQ,WACtB,MAAM,OAAO,YAAY,gBAAgB,MAAM,CAAC;AACpD;AAEA,MAAM,mBAAmB,WACvB,OAAO,IAAI,aAAa;CACtB,MAAM,eAAe,OAAO;CAC5B,MAAM,QAAQ,OAAO;CAErB,MAAM,WAAW;EACf,gBAAgB,OAAO;EACvB,GAAI,OAAO,uBAAuB,KAAA,IAC9B,CAAC,IACD,EAAE,oBAAoB,OAAO,mBAAmB;EACpD,GAAI,OAAO,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,OAAO,aAAa;CACnF;CACA,OAAO,aAAa,MAAM,QAAQ;CAElC,MAAM,iBAAiB,OAAO,GAAG,WAC/B,WACA,WAA2B,eAAe,KAAK,CAAC,GAChD;EACA,OAAO,gBAAgB;GAAE,kBAAkB;GAAW,iBAAiB;EAAS,CAAC;EACjF,OAAO,OAAO,OAAO,OACnB,OAAO,IAAI,aAAa;GAEtB,MAAM,WAAW,QAAO,OADF,MAAM,YAAY,QAAQ,GACjB,KAC7B,OAAO,OAAO,qBAAqB,SAAS,CAAC,GAC7C,OAAO,KAAK,CAAC,GACb,OAAO,IAAI,0BAA0B,GACrC,OAAO,YACP,OAAO,KAAK,WAAW,OAAO,EAAE,CAClC;GACA,OAAO,aAAa,KAAA,IAChB,OAAO,OAAO,oBAAI,IAAI,MAAM,iCAAiC,CAAC,IAC9D;EACN,CAAC,CACH;CACF,CAAC;CAeD,OAAO;EACL,QAda,OAAO,GAAG,WAAW,OAAmD;GACrF,MAAM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1E,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/services/runtime.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\";\n\nimport { EDACommand } from \"../types/commands\";\nimport { CommandId, SequenceNumber, durablePosition } from \"../types/core\";\nimport {\n ModelSelectionPayload,\n NonNegativeInt,\n SystemPromptText,\n commandCancelledEventType,\n commandCompletedEventType,\n commandFailedEventType,\n} from \"../types/events\";\nimport type {\n CommandCancelledEvent,\n CommandCompletedEvent,\n CommandFailedEvent,\n PositionedEvent,\n} from \"../types/events\";\nimport { SessionState } from \"./session-state\";\nimport type { EDASubmittable, SessionCommandAdmissionError } from \"./session-state\";\nimport { CommittedDurableEvent } from \"./session-store\";\nimport { EDASessionQuery } from \"./session-query\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"./tracing\";\nimport type { EDASessionQueryShape } from \"./session-query\";\n\n/** Configuration for one scoped session runtime instance. */\nexport const EDARuntimeConfig = Schema.Struct({\n modelSelection: ModelSelectionPayload,\n /** Maximum framework-owned tool calls one model run may execute before failing safely. */\n maxToolCallsPerRun: Schema.optionalKey(NonNegativeInt),\n systemPrompt: Schema.optionalKey(SystemPromptText),\n});\nexport type EDARuntimeConfig = typeof EDARuntimeConfig.Type;\n\n/** Public runtime error surface for command admission helpers. */\nexport type EDARuntimeError = SessionCommandAdmissionError;\n\n/** Command terminal events observed by blocking runtime helpers. */\nexport type EDACommandTerminalEvent =\n | CommandCompletedEvent\n | CommandFailedEvent\n | CommandCancelledEvent;\n\n/** Committed durable event narrowed to a command terminal boundary. */\nexport type CommittedCommandTerminalEvent = CommittedDurableEvent & {\n readonly event: EDACommandTerminalEvent;\n};\n\n/** Overloaded public submit API for single commands or ordered durable batches. */\nexport interface EDARuntimeSubmit {\n /** Submit one command and return its committed CommandAdmitted event. */\n (command: EDACommand): Effect.Effect<CommittedDurableEvent, EDARuntimeError>;\n /** Submit one ordered durable batch of commands and/or app events. */\n (\n input: ReadonlyArray<EDASubmittable>,\n ): Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDARuntimeError>;\n}\n\n/** Public facade exposed to hosts and route handlers for one live session runtime. */\nexport interface EDARuntimeShape {\n /** Submit commands and/or app durable events durably and wake the dispatch process if needed. */\n readonly submit: EDARuntimeSubmit;\n /** Block until the command reaches CommandCompleted, CommandFailed, or CommandCancelled. */\n readonly blockOnCommand: (\n commandId: CommandId,\n afterSeq?: SequenceNumber,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Admit one command and block until that command reaches a terminal command boundary. */\n readonly submitAndBlock: (\n command: EDACommand,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Read the authoritative live session snapshot. */\n readonly snapshot: EDASessionQueryShape[\"snapshot\"];\n /** Read durable user/assistant messages in committed order. */\n readonly messages: EDASessionQueryShape[\"messages\"];\n /** Backfill durable events after a committed sequence, then follow live events. */\n readonly eventsAfter: EDASessionQueryShape[\"eventsAfter\"];\n /** Read one bounded page of committed durable events plus the committed head. */\n readonly readEventPage: EDASessionQueryShape[\"readEventPage\"];\n}\n\n/** Top-level public facade for one effect-durable-agent session runtime. */\nexport class EDARuntime extends Context.Service<EDARuntime, EDARuntimeShape>()(\n \"@effect-durable-agent/EDARuntime\",\n) {\n static readonly Live = (config: EDARuntimeConfig) =>\n Layer.effect(EDARuntime, makeLiveRuntime(config));\n}\n\nconst makeLiveRuntime = (config: EDARuntimeConfig) =>\n Effect.gen(function* () {\n const sessionState = yield* SessionState;\n const query = yield* EDASessionQuery;\n\n const runInput = {\n modelSelection: config.modelSelection,\n ...(config.maxToolCallsPerRun === undefined\n ? {}\n : { maxToolCallsPerRun: config.maxToolCallsPerRun }),\n ...(config.systemPrompt === undefined ? {} : { systemPrompt: config.systemPrompt }),\n };\n yield* sessionState.start(runInput);\n\n const blockOnCommand = Effect.fn(function* (\n commandId: CommandId,\n afterSeq: SequenceNumber = SequenceNumber.make(0),\n ) {\n yield* annotateEdaSpan({ \"eda.command.id\": commandId, \"eda.seq.after\": afterSeq });\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const events = yield* query.eventsAfter(afterSeq);\n const terminal = yield* events.pipe(\n Stream.filter(isCommandTerminalFor(commandId)),\n Stream.take(1),\n Stream.map(toCommittedCommandTerminal),\n Stream.runCollect,\n Effect.map((events) => events[0]),\n );\n return terminal === undefined\n ? yield* Effect.die(new Error(\"Expected command terminal event\"))\n : terminal;\n }),\n );\n });\n\n const submit = Effect.fn(function* (input: EDACommand | ReadonlyArray<EDASubmittable>) {\n const items = Array.isArray(input) ? input : [input as EDACommand];\n yield* annotateEdaSpan({\n \"eda.command.submittable_count\": items.length,\n \"eda.command.count\": items.filter((item) => \"_tag\" in item).length,\n });\n const committed = Array.isArray(input)\n ? yield* sessionState.submitBatch(input)\n : [yield* sessionState.admitCommand(input as EDACommand)];\n yield* annotateEdaSpan(committedBatchAttributes(committed));\n return Array.isArray(input) ? committed : committed[0]!;\n }) as EDARuntimeSubmit;\n\n return {\n submit,\n blockOnCommand,\n submitAndBlock: Effect.fn(function* (command: EDACommand) {\n yield* annotateEdaSpan({\n \"eda.command.kind\": command._tag,\n \"eda.command.id\": command.commandId,\n \"eda.command.disposition\": \"disposition\" in command ? command.disposition : undefined,\n });\n const admitted = yield* sessionState.admitCommand(command);\n return yield* blockOnCommand(commandIdFromCommandAdmitted(admitted), admitted.position.seq);\n }),\n snapshot: () => query.snapshot(),\n messages: () => query.messages(),\n eventsAfter: (afterSeq: SequenceNumber) => query.eventsAfter(afterSeq),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n query.readEventPage(afterSeq, limit),\n };\n });\n\nconst isCommandTerminalFor =\n (commandId: CommandId) =>\n (event: PositionedEvent): boolean => {\n if (\n event.event.type !== commandCompletedEventType &&\n event.event.type !== commandFailedEventType &&\n event.event.type !== commandCancelledEventType\n ) {\n return false;\n }\n return (event.event.payload as { readonly commandId: CommandId }).commandId === commandId;\n };\n\nconst toCommittedCommandTerminal = (event: PositionedEvent): CommittedCommandTerminalEvent =>\n CommittedDurableEvent.make({\n position: durablePosition(event.position.seq),\n event: event.event as EDACommandTerminalEvent,\n }) as CommittedCommandTerminalEvent;\n\nconst commandIdFromCommandAdmitted = (committed: CommittedDurableEvent): CommandId => {\n const commandId = (committed.event.payload as { readonly command?: EDACommand }).command\n ?.commandId;\n if (commandId === undefined) {\n throw new Error(\"CommandAdmitted event is missing a framework commandId\");\n }\n return commandId;\n};\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAa,mBAAmB,OAAO,OAAO;CAC5C,gBAAgB;;CAEhB,oBAAoB,OAAO,YAAY,cAAc;CACrD,cAAc,OAAO,YAAY,gBAAgB;AACnD,CAAC;;AAmDD,IAAa,aAAb,MAAa,mBAAmB,QAAQ,QAAqC,EAC3E,kCACF,EAAE;CACA,OAAgB,QAAQ,WACtB,MAAM,OAAO,YAAY,gBAAgB,MAAM,CAAC;AACpD;AAEA,MAAM,mBAAmB,WACvB,OAAO,IAAI,aAAa;CACtB,MAAM,eAAe,OAAO;CAC5B,MAAM,QAAQ,OAAO;CAErB,MAAM,WAAW;EACf,gBAAgB,OAAO;EACvB,GAAI,OAAO,uBAAuB,KAAA,IAC9B,CAAC,IACD,EAAE,oBAAoB,OAAO,mBAAmB;EACpD,GAAI,OAAO,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,OAAO,aAAa;CACnF;CACA,OAAO,aAAa,MAAM,QAAQ;CAElC,MAAM,iBAAiB,OAAO,GAAG,WAC/B,WACA,WAA2B,eAAe,KAAK,CAAC,GAChD;EACA,OAAO,gBAAgB;GAAE,kBAAkB;GAAW,iBAAiB;EAAS,CAAC;EACjF,OAAO,OAAO,OAAO,OACnB,OAAO,IAAI,aAAa;GAEtB,MAAM,WAAW,QAAO,OADF,MAAM,YAAY,QAAQ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MAAM,MAAM,SAAS,2BAErB,OAAO;CAET,OAAQ,MAAM,MAAM,QAA8C,cAAc;AAClF;AAEF,MAAM,8BAA8B,UAClC,sBAAsB,KAAK;CACzB,UAAU,gBAAgB,MAAM,SAAS,GAAG;CAC5C,OAAO,MAAM;AACf,CAAC;AAEH,MAAM,gCAAgC,cAAgD;CACpF,MAAM,YAAa,UAAU,MAAM,QAA8C,SAC7E;CACJ,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,MAAM,wDAAwD;CAE1E,OAAO;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as SessionEventObserverShape, t as SessionEventObserver } from "../session-event-observer-
|
|
1
|
+
import { n as SessionEventObserverShape, t as SessionEventObserver } from "../session-event-observer-DaFMKKNc.js";
|
|
2
2
|
export { SessionEventObserver, SessionEventObserverShape };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as EDASessionSnapshot, n as EDASessionQuery, r as EDASessionQueryShape, t as EDASessionEventPage } from "../session-query-
|
|
1
|
+
import { i as EDASessionSnapshot, n as EDASessionQuery, r as EDASessionQueryShape, t as EDASessionEventPage } from "../session-query-l8xpJYp8.js";
|
|
2
2
|
export { EDASessionEventPage, EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { u as SessionState } from "../session-state-
|
|
1
|
+
import { u as PositionedEvent } from "../envelope-DxQzo5rN.js";
|
|
2
|
+
import { u as SessionState } from "../session-state-aIqe9CLa.js";
|
|
3
3
|
import { EDASessionStore } from "./session-store.js";
|
|
4
4
|
import { durableMessageTranscript } from "../domain/message-transcript.js";
|
|
5
5
|
import { annotateEdaSpan } from "./tracing.js";
|
|
6
|
-
import { r as LiveEventBus } from "../sink-registry-
|
|
6
|
+
import { r as LiveEventBus } from "../sink-registry-NDgeyzO0.js";
|
|
7
7
|
import * as Context from "effect/Context";
|
|
8
8
|
import * as Effect from "effect/Effect";
|
|
9
9
|
import * as Layer from "effect/Layer";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as SessionStateShape, a as SessionCommandCompleted, c as SessionCommandResult, d as SessionForkedCommand, f as SessionNoRunnableCommand, g as SessionStateError, h as SessionState, i as SessionCommandCancelled, l as SessionDrainProcessed, m as SessionRunInput, n as SessionCommandAdmissionConflict, o as SessionCommandFailed, p as SessionNoRunnableReason, r as SessionCommandAdmissionError, s as SessionCommandOutcome, t as EDASubmittable, u as SessionDrainResult, v as SessionStateSnapshotData } from "../session-state-
|
|
1
|
+
import { _ as SessionStateShape, a as SessionCommandCompleted, c as SessionCommandResult, d as SessionForkedCommand, f as SessionNoRunnableCommand, g as SessionStateError, h as SessionState, i as SessionCommandCancelled, l as SessionDrainProcessed, m as SessionRunInput, n as SessionCommandAdmissionConflict, o as SessionCommandFailed, p as SessionNoRunnableReason, r as SessionCommandAdmissionError, s as SessionCommandOutcome, t as EDASubmittable, u as SessionDrainResult, v as SessionStateSnapshotData } from "../session-state-YHFzOGDf.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-aIqe9CLa.js";
|
|
2
2
|
export { SessionCommandAdmissionConflict, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as EDASessionStore, c as FindCommandAdmissionInput, i as EDAReducerCheckpoint, l as SaveReducerCheckpointInput, n as DurableAppendBatch, o as EDASessionStoreError, r as DurableAppendEntry, s as EDASessionStoreShape, t as CommittedDurableEvent, u as hasEDASessionStoreError } from "../session-store-
|
|
1
|
+
import { a as EDASessionStore, c as FindCommandAdmissionInput, i as EDAReducerCheckpoint, l as SaveReducerCheckpointInput, n as DurableAppendBatch, o as EDASessionStoreError, r as DurableAppendEntry, s as EDASessionStoreShape, t as CommittedDurableEvent, u as hasEDASessionStoreError } from "../session-store-Cpi_NwTR.js";
|
|
2
2
|
export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CommandId, DurablePosition, SequenceNumber, durablePosition } from "../types/core.js";
|
|
2
|
-
import {
|
|
2
|
+
import { t as DurableEventEnvelope } from "../envelope-DxQzo5rN.js";
|
|
3
|
+
import { Dn as contextRebasedEventType, Gn as summaryCreatedEventType, _n as commandAdmittedEventType } from "../durable-BGFvX7Mh.js";
|
|
3
4
|
import { CompactionSummaryArtifact } from "../domain/context-projection.js";
|
|
4
5
|
import * as Context from "effect/Context";
|
|
5
6
|
import * as Effect from "effect/Effect";
|
|
@@ -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,O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AAO,OAAO,YAAY;GAC5B,MAAM,qBAAqB,IAAI,IAAI,QAAQ,kBAAkB;GAC7D,KAAK,MAAM,cAAc,aACvB,mBAAmB,IAAI,WAAW,MAAM,UAAU;GAEpD,OAAO;IAAE,GAAG;IAAS;GAAmB;EAC1C,CAAC;CACL;AACF;AAEA,MAAM,2BACJ,OACA,UACY;CACZ,IAAI,MAAM,MAAM,SAAS,0BACvB,OAAO;CAET,MAAM,WAAY,MAAM,MAAM,QAA8C;CAC5E,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,mBAAmB,KAAA,KAAa,SAAS,mBAAmB,MAAM,gBAC1E,OAAO;CAET,OAAO,MAAM,cAAc,KAAA,KAAa,SAAS,cAAc,MAAM;AACvE"}
|
|
1
|
+
{"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { type CommandIdempotencyKey, type EDACommand } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope,\n});\nexport type CommittedDurableEvent = typeof CommittedDurableEvent.Type;\n\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedErrorClass<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /** Deterministic in-memory implementation used by runtime and recovery tests. */\n static readonly InMemory = (sessionId: SessionId) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const data = yield* Ref.make<InMemoryStoreData>(emptyInMemoryStoreData());\n return makeInMemoryStore(sessionId, data);\n }),\n );\n\n /** In-memory store seeded with a durable prefix; intended for recovery tests. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n ) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const committed = seedCommittedEvents(sessionId, events);\n const data = yield* Ref.make<InMemoryStoreData>({\n ...emptyInMemoryStoreData(),\n committed,\n summaries: summariesFromCommittedEvents(committed),\n });\n return makeInMemoryStore(sessionId, data);\n }),\n );\n}\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n}\n\nconst emptyInMemoryStoreData = (): InMemoryStoreData => ({\n committed: [],\n summaries: new Map(),\n reducerCheckpoints: new Map(),\n});\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(index + 1)),\n event,\n });\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload as { readonly summary?: unknown };\n if (payload.summary !== undefined) {\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed = CommittedDurableEvent.make({\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event,\n });\n nextEntries.push(committed);\n committedEvents.push(committed);\n\n if (event.type === summaryCreatedEventType) {\n const payload = event.payload as {\n readonly summary?: unknown;\n readonly summaryId?: CompactionSummaryArtifact[\"summaryId\"];\n };\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = CompactionSummaryArtifact.make(payload.summary as never);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (event.type === contextRebasedEventType) {\n const payload = event.payload as { readonly summaryId?: SummaryId };\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = (entry.event.payload as { readonly command?: EDACommand }).command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,wBAAwB,OAAO,OAAO;CACjD,UAAU;CACV,OAAO;AACT,CAAC;;;;;;;;AAUD,IAAa,uBAAb,cAA0C,OAAO,iBAAuC,EACtF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,EAAE,CAAC;;AAGH,MAAa,2BAA2B,UACtC,MAAM,QAAQ,MACX,WAAW,MAAM,aAAa,MAAM,KAAK,OAAO,iBAAiB,oBACpE;;;;;;;AAQF,MAAa,qBAAqB,OAAO,OAAO,EAC9C,OAAO,qBACT,CAAC;;;;;;;;AAUD,MAAa,qBAAqB,OAAO,OAAO,EAC9C,SAAS,OAAO,MAAM,kBAAkB,EAC1C,CAAC;;AAsBD,MAAa,4BAA4B,OAAO,OAAO;CACrD,WAAW,OAAO,YAAY,SAAS;CACvC,gBAAgB,OAAO,YAAY,OAAO,MAAM;AAClD,CAAC;;;;;;;;AAwDD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;;CAEA,OAAgB,YAAY,cAC1B,MAAM,OACJ,iBACA,OAAO,IAAI,aAAa;EAEtB,OAAO,kBAAkB,WAAW,OADhB,IAAI,KAAwB,uBAAuB,CAAC,CAChC;CAC1C,CAAC,CACH;;CAGF,OAAgB,kBACd,WACA,WAEA,MAAM,OACJ,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,YAAY,oBAAoB,WAAW,MAAM;EAMvD,OAAO,kBAAkB,WAAW,OALhB,IAAI,KAAwB;GAC9C,GAAG,uBAAuB;GAC1B;GACA,WAAW,6BAA6B,SAAS;EACnD,CAAC,CACuC;CAC1C,CAAC,CACH;AACJ;AAQA,MAAM,gCAAmD;CACvD,WAAW,CAAC;CACZ,2BAAW,IAAI,IAAI;CACnB,oCAAoB,IAAI,IAAI;AAC9B;AAEA,M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U,UAAU,IAAI,OAAO,MAAM,SAAS,GAAG,CAAC,CAAC;EAC9E,CAAC,CACH;EACF,uBAAuB,UACrB,IAAI,IAAI,IAAI,EAAE,KACZ,OAAO,KAAK,EAAE,gBACZ,UAAU,MAAM,UAAU,wBAAwB,OAAO,KAAK,CAAC,CACjE,CACF;EACF,sBAAsB,cACpB,IAAI,IAAI,IAAI,EAAE,KAAK,OAAO,KAAK,EAAE,gBAAgB,UAAU,IAAI,SAAS,CAAC,CAAC;EAC5E,wBAAwB,SACtB,IAAI,IAAI,IAAI,EAAE,KAAK,OAAO,KAAK,EAAE,yBAAyB,mBAAmB,IAAI,IAAI,CAAC,CAAC;EACzF,wBAAwB,eACtB,IAAI,OAAO,OAAO,aAAa;GAC7B,GAAG;GACH,oBAAoB,IAAI,IAAI,QAAQ,kBAAkB,EAAE,IAAI,WAAW,MAAM,UAAU;EACzF,EAAE;EACJ,yBAAyB,gBACvB,IAAI,OAAO,OAAO,YAAY;GAC5B,MAAM,qBAAqB,IAAI,IAAI,QAAQ,kBAAkB;GAC7D,KAAK,MAAM,cAAc,aACvB,mBAAmB,IAAI,WAAW,MAAM,UAAU;GAEpD,OAAO;IAAE,GAAG;IAAS;GAAmB;EAC1C,CAAC;CACL;AACF;AAEA,MAAM,2BACJ,OACA,UACY;CACZ,IAAI,MAAM,MAAM,SAAS,0BACvB,OAAO;CAET,MAAM,WAAY,MAAM,MAAM,QAA8C;CAC5E,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,mBAAmB,KAAA,KAAa,SAAS,mBAAmB,MAAM,gBAC1E,OAAO;CAET,OAAO,MAAM,cAAc,KAAA,KAAa,SAAS,cAAc,MAAM;AACvE"}
|
|
@@ -1,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-M7qIxoSH.js";
|
|
2
2
|
export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as EDASinkContext, c as EDASinkRegistryShape, i as EDASinkCheckpoint, l as EDASinkRunnerStartInput, n as EDAEphemeralSinkDefinition, o as EDASinkDurableBatch, r as EDASink, s as EDASinkRegistry, t as EDADurableSinkDefinition } from "../sink-registry-
|
|
1
|
+
import { a as EDASinkContext, c as EDASinkRegistryShape, i as EDASinkCheckpoint, l as EDASinkRunnerStartInput, n as EDAEphemeralSinkDefinition, o as EDASinkDurableBatch, r as EDASink, s as EDASinkRegistry, t as EDADurableSinkDefinition } from "../sink-registry-T1wOUuzq.js";
|
|
2
2
|
export { EDADurableSinkDefinition, EDAEphemeralSinkDefinition, EDASink, EDASinkCheckpoint, EDASinkContext, EDASinkDurableBatch, 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-NDgeyzO0.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-BJaVNtw4.js";
|
|
2
2
|
export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { _ as UsagePayload } from "../envelope-DkZyMIgp.js";
|
|
1
2
|
import { _ as parseEDATraceparent, c as EDATraceLink, d as makeEDAEventTrace, f as makeEDARunTrace, g as makeRootEDATraceMetadata, h as makeRootEDAEventTrace, i as EDATraceAttributeValue, l as EDATraceMetadata, m as makeEDATraceMetadataFromParent, n as EDARunTrace, o as EDATraceContext, p as makeEDATraceContext, t as EDAEventTrace, u as buildEDATraceparent } from "../tracing-BXHAkxkx.js";
|
|
2
|
-
import { U as UsagePayload } from "../events-Bb9-Cu-7.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 { d as PositionedEvent } from "./envelope-DkZyMIgp.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-DaFMKKNc.d.ts.map
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
+
import { d as PositionedEvent } from "./envelope-DkZyMIgp.js";
|
|
1
2
|
import { m as SequenceNumber } from "./core-CYT6DBaS.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { h as SessionState } from "./session-state-BfoXKafd.js";
|
|
3
|
+
import { a as EDASessionStore, o as EDASessionStoreError } from "./session-store-Cpi_NwTR.js";
|
|
4
|
+
import { S as ReducedState } from "./command-queues-DdDB_aYM.js";
|
|
5
|
+
import { t as DurableTranscriptMessage } from "./message-transcript-DQNlzxle.js";
|
|
6
|
+
import { u as LiveEventBus } from "./sink-registry-T1wOUuzq.js";
|
|
7
|
+
import { a as EDAReducerStateSnapshot } from "./reducer-registry-aFjz_ZLT.js";
|
|
8
|
+
import { h as SessionState } from "./session-state-YHFzOGDf.js";
|
|
9
9
|
import * as Context from "effect/Context";
|
|
10
10
|
import * as Effect from "effect/Effect";
|
|
11
11
|
import * as Layer from "effect/Layer";
|
|
@@ -42,4 +42,4 @@ declare class EDASessionQuery extends EDASessionQuery_base {
|
|
|
42
42
|
}
|
|
43
43
|
//#endregion
|
|
44
44
|
export { EDASessionSnapshot as i, EDASessionQuery as n, EDASessionQueryShape as r, EDASessionEventPage as t };
|
|
45
|
-
//# sourceMappingURL=session-query-
|
|
45
|
+
//# sourceMappingURL=session-query-l8xpJYp8.d.ts.map
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
+
import { d as PositionedEvent, l as ModelSelectionPayload, n as EphemeralEventEnvelope, t as DurableEventEnvelope, u as NonNegativeInt } from "./envelope-DkZyMIgp.js";
|
|
1
2
|
import { r as EDACommand } from "./commands-Ce1ec6kH.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { At as ToolCallCreatedEvent } from "./durable-br2C1bWK.js";
|
|
4
|
+
import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-Cpi_NwTR.js";
|
|
5
|
+
import { S as ReducedState } from "./command-queues-DdDB_aYM.js";
|
|
6
|
+
import { t as ModelResolver } from "./model-resolver-BPPJAsuh.js";
|
|
6
7
|
import { t as IdGenerator } from "./id-generator-Ckl8_XWW.js";
|
|
7
|
-
import { r as SessionContext, t as EventFactory } from "./event-factory-
|
|
8
|
+
import { r as SessionContext, t as EventFactory } from "./event-factory-pFzsPlDs.js";
|
|
8
9
|
import { t as EDAKeepAlive } from "./keep-alive-Chl5SJxy.js";
|
|
9
|
-
import { d as CompactionRunner } from "./compaction-
|
|
10
|
-
import { s as EDASinkRegistry, u as LiveEventBus } from "./sink-registry-
|
|
11
|
-
import { a as EDAReducerStateSnapshot, r as EDAReducerRegistry } from "./reducer-registry
|
|
12
|
-
import { r as EDAPromptProjector } from "./prompt-projector-
|
|
13
|
-
import { r as EDAToolRegistry } from "./tool-registry-
|
|
10
|
+
import { d as CompactionRunner } from "./compaction-BEor3jKv.js";
|
|
11
|
+
import { s as EDASinkRegistry, u as LiveEventBus } from "./sink-registry-T1wOUuzq.js";
|
|
12
|
+
import { a as EDAReducerStateSnapshot, r as EDAReducerRegistry } from "./reducer-registry-aFjz_ZLT.js";
|
|
13
|
+
import { r as EDAPromptProjector } from "./prompt-projector-f4ElyXCE.js";
|
|
14
|
+
import { r as EDAToolRegistry } from "./tool-registry-BJaVNtw4.js";
|
|
14
15
|
import * as Context from "effect/Context";
|
|
15
16
|
import * as Effect from "effect/Effect";
|
|
16
17
|
import * as Layer from "effect/Layer";
|
|
17
18
|
import * as Schema from "effect/Schema";
|
|
18
19
|
import * as Prompt from "effect/unstable/ai/Prompt";
|
|
19
20
|
import * as Cause from "effect/Cause";
|
|
20
|
-
import * as LanguageModel from "effect/unstable/ai/LanguageModel";
|
|
21
21
|
import * as Response from "effect/unstable/ai/Response";
|
|
22
22
|
|
|
23
23
|
//#region src/services/session-event-sink.d.ts
|
|
@@ -143,7 +143,7 @@ interface ToolExecutorShape {
|
|
|
143
143
|
declare const ToolExecutor_base: Context.ServiceClass<ToolExecutor, "@effect-durable-agent/ToolExecutor", ToolExecutorShape>;
|
|
144
144
|
/** Executes sealed framework-owned tool calls and commits tool lifecycle boundaries. */
|
|
145
145
|
declare class ToolExecutor extends ToolExecutor_base {
|
|
146
|
-
static readonly Live: Layer.Layer<ToolExecutor, never,
|
|
146
|
+
static readonly Live: Layer.Layer<ToolExecutor, never, SessionContext | EventFactory | IdGenerator | EDAToolRegistry>;
|
|
147
147
|
}
|
|
148
148
|
//#endregion
|
|
149
149
|
//#region src/services/inference-runner.d.ts
|
|
@@ -291,7 +291,7 @@ interface InferenceRunnerShape {
|
|
|
291
291
|
declare const InferenceRunner_base: Context.ServiceClass<InferenceRunner, "@effect-durable-agent/InferenceRunner", InferenceRunnerShape>;
|
|
292
292
|
/** Owns provider inference streams and routes them into durable/live inference emissions. */
|
|
293
293
|
declare class InferenceRunner extends InferenceRunner_base {
|
|
294
|
-
static readonly Live: Layer.Layer<InferenceRunner, never,
|
|
294
|
+
static readonly Live: Layer.Layer<InferenceRunner, never, ModelResolver | EventFactory | IdGenerator | EDAToolRegistry>;
|
|
295
295
|
}
|
|
296
296
|
//#endregion
|
|
297
297
|
//#region src/services/turn-runner.d.ts
|
|
@@ -544,7 +544,7 @@ interface TurnRunnerShape {
|
|
|
544
544
|
declare const TurnRunner_base: Context.ServiceClass<TurnRunner, "@effect-durable-agent/TurnRunner", TurnRunnerShape>;
|
|
545
545
|
/** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
|
|
546
546
|
declare class TurnRunner extends TurnRunner_base {
|
|
547
|
-
static readonly Live: Layer.Layer<TurnRunner, never,
|
|
547
|
+
static readonly Live: Layer.Layer<TurnRunner, never, EventFactory | IdGenerator | InferenceRunner | ToolExecutor>;
|
|
548
548
|
}
|
|
549
549
|
//#endregion
|
|
550
550
|
//#region src/services/session-state.d.ts
|
|
@@ -854,8 +854,8 @@ interface SessionStateShape extends SessionEventSink {
|
|
|
854
854
|
declare const SessionState_base: Context.ServiceClass<SessionState, "@effect-durable-agent/SessionState", SessionStateShape>;
|
|
855
855
|
/** Internal authoritative live state and root control loop for one session. */
|
|
856
856
|
declare class SessionState extends SessionState_base {
|
|
857
|
-
static readonly Live: Layer.Layer<SessionState, EDASessionStoreError, EDAKeepAlive | EDAPromptProjector | EDAReducerRegistry | EDASessionStore |
|
|
857
|
+
static readonly Live: Layer.Layer<SessionState, EDASessionStoreError, EDAKeepAlive | EDAPromptProjector | EDAReducerRegistry | EDASessionStore | LiveEventBus | EDASinkRegistry | SessionContext | EventFactory | IdGenerator | TurnRunner | CompactionRunner>;
|
|
858
858
|
}
|
|
859
859
|
//#endregion
|
|
860
860
|
export { ToolExecutor as S, SessionStateShape as _, SessionCommandCompleted as a, InferenceRunner as b, SessionCommandResult as c, SessionForkedCommand as d, SessionNoRunnableCommand as f, SessionStateError as g, SessionState as h, SessionCommandCancelled as i, SessionDrainProcessed as l, SessionRunInput as m, SessionCommandAdmissionConflict as n, SessionCommandFailed as o, SessionNoRunnableReason as p, SessionCommandAdmissionError as r, SessionCommandOutcome as s, EDASubmittable as t, SessionDrainResult as u, SessionStateSnapshotData as v, InferenceRunnerStreamPart as x, TurnRunner as y };
|
|
861
|
-
//# sourceMappingURL=session-state-
|
|
861
|
+
//# sourceMappingURL=session-state-YHFzOGDf.d.ts.map
|
|
@@ -1,16 +1,18 @@
|
|
|
1
|
+
import { ModelResolver } from "./services/model-resolver.js";
|
|
1
2
|
import { CommandId, InferenceId, MessageId, Position, RunId, SequenceNumber, SubSequenceNumber, TurnId } from "./types/core.js";
|
|
2
|
-
import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
|
|
3
3
|
import { makeEDARunTrace } from "./types/tracing.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { c as ModelSelectionPayload, d as ProviderPartId, l as NonNegativeInt, m as ToolName, p as SystemPromptText, s as FailurePayload, u as PositionedEvent } from "./envelope-DxQzo5rN.js";
|
|
5
|
+
import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
|
|
6
|
+
import { $n as turnFailedEventType, An as inferenceCompletedEventType, Jn as toolCallCreatedEventType, Xn as toolCallRejectedEventType, _n as commandAdmittedEventType, jn as inferenceFailedEventType } from "./durable-BGFvX7Mh.js";
|
|
7
|
+
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-DF0-6mbR.js";
|
|
6
8
|
import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
|
|
7
9
|
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError } from "./services/session-store.js";
|
|
10
|
+
import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-BgDr5VJy.js";
|
|
8
11
|
import { IdGenerator } from "./services/id-generator.js";
|
|
9
|
-
import { n as SessionContext, t as EventFactory } from "./event-factory-
|
|
12
|
+
import { n as SessionContext, t as EventFactory } from "./event-factory-DTFdy0Cb.js";
|
|
10
13
|
import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
11
14
|
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
12
|
-
import {
|
|
13
|
-
import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-DH6uiEgP.js";
|
|
15
|
+
import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-NDgeyzO0.js";
|
|
14
16
|
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
15
17
|
import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
|
|
16
18
|
import { EDAToolRegistry } from "./services/tool-registry.js";
|
|
@@ -28,7 +30,6 @@ import * as Queue from "effect/Queue";
|
|
|
28
30
|
import * as Ref from "effect/Ref";
|
|
29
31
|
import * as Scope from "effect/Scope";
|
|
30
32
|
import * as Semaphore from "effect/Semaphore";
|
|
31
|
-
import * as LanguageModel from "effect/unstable/ai/LanguageModel";
|
|
32
33
|
import * as Option from "effect/Option";
|
|
33
34
|
import * as Response from "effect/unstable/ai/Response";
|
|
34
35
|
//#region src/domain/dispatch-policy.ts
|
|
@@ -757,7 +758,7 @@ Schema.TaggedErrorClass()("UnsupportedInferencePart", {
|
|
|
757
758
|
const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
758
759
|
const ids = yield* IdGenerator;
|
|
759
760
|
const events = yield* EventFactory;
|
|
760
|
-
const
|
|
761
|
+
const models = yield* ModelResolver;
|
|
761
762
|
const toolRegistry = yield* EDAToolRegistry;
|
|
762
763
|
const recordPart = (eventSink, state, part, setLatestState) => Effect.gen(function* () {
|
|
763
764
|
if (state.inference.phase === "sealed") {
|
|
@@ -972,6 +973,7 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
|
972
973
|
return yield* requireTerminal(yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []));
|
|
973
974
|
});
|
|
974
975
|
return { runInference: Effect.fn("agent.inference")(function* (input) {
|
|
976
|
+
const languageModel = yield* models.resolve(input.modelSelection);
|
|
975
977
|
const inferenceIdentity = {
|
|
976
978
|
runId: input.runId,
|
|
977
979
|
turnId: input.turnId,
|
|
@@ -1146,31 +1148,6 @@ const makeFinishMetadata = (part) => ({
|
|
|
1146
1148
|
response: part.response,
|
|
1147
1149
|
metadata: part.metadata
|
|
1148
1150
|
});
|
|
1149
|
-
const makeUsagePayload = (usage) => {
|
|
1150
|
-
const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);
|
|
1151
|
-
const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);
|
|
1152
|
-
const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);
|
|
1153
|
-
const inputTokens = nonNegativeInt(usage.inputTokens.total) ?? sumDefined([
|
|
1154
|
-
uncachedInputTokens,
|
|
1155
|
-
cachedInputTokens,
|
|
1156
|
-
cacheWriteInputTokens
|
|
1157
|
-
]);
|
|
1158
|
-
const textTokens = nonNegativeInt(usage.outputTokens.text);
|
|
1159
|
-
const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);
|
|
1160
|
-
const outputTokens = nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);
|
|
1161
|
-
return UsagePayload.make({
|
|
1162
|
-
...inputTokens === void 0 ? {} : { inputTokens },
|
|
1163
|
-
...cachedInputTokens === void 0 ? {} : { cachedInputTokens },
|
|
1164
|
-
...outputTokens === void 0 ? {} : { outputTokens },
|
|
1165
|
-
...textTokens === void 0 ? {} : { textTokens },
|
|
1166
|
-
...reasoningTokens === void 0 ? {} : { reasoningTokens }
|
|
1167
|
-
});
|
|
1168
|
-
};
|
|
1169
|
-
const sumDefined = (values) => {
|
|
1170
|
-
const present = values.filter((value) => value !== void 0);
|
|
1171
|
-
return present.length === 0 ? void 0 : present.reduce((sum, value) => sum + value, 0);
|
|
1172
|
-
};
|
|
1173
|
-
const nonNegativeInt = (value) => value === void 0 || !Number.isFinite(value) ? void 0 : Math.max(0, Math.trunc(value));
|
|
1174
1151
|
Schema.Struct({
|
|
1175
1152
|
runId: RunId,
|
|
1176
1153
|
turnId: TurnId
|
|
@@ -1557,7 +1534,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1557
1534
|
}));
|
|
1558
1535
|
const buildReducerCheckpointSnapshot = (snapshot) => [{
|
|
1559
1536
|
name: frameworkReducedStateReducerName,
|
|
1560
|
-
schemaVersion:
|
|
1537
|
+
schemaVersion: 6,
|
|
1561
1538
|
throughSeq: snapshot.reduced.lastSeq,
|
|
1562
1539
|
payload: encodeReducedStateCheckpoint(snapshot.reduced),
|
|
1563
1540
|
updatedAtMs: snapshot.updatedAtMs
|
|
@@ -2157,6 +2134,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2157
2134
|
});
|
|
2158
2135
|
const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
|
|
2159
2136
|
const plan = planSessionRecovery(reduced);
|
|
2137
|
+
input = {
|
|
2138
|
+
...input,
|
|
2139
|
+
modelSelection: plan.continuation?.run.modelSelection ?? input.modelSelection
|
|
2140
|
+
};
|
|
2160
2141
|
yield* annotateEdaSpan({
|
|
2161
2142
|
"eda.recovery.reason": reason,
|
|
2162
2143
|
"eda.recovery.open_tool_calls": plan.openToolCalls.length,
|
|
@@ -2268,6 +2249,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2268
2249
|
continuation: plan.continuation === void 0 || continuationRunId === void 0 || continuationRunTrace === void 0 ? void 0 : {
|
|
2269
2250
|
command: plan.continuation.command,
|
|
2270
2251
|
runId: continuationRunId,
|
|
2252
|
+
modelSelection: input.modelSelection,
|
|
2271
2253
|
inputMessageIds: plan.continuation.inputMessageIds,
|
|
2272
2254
|
runScope: continuationRunTrace.runScope,
|
|
2273
2255
|
runSpan: continuationRunTrace.runSpan
|
|
@@ -2290,7 +2272,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2290
2272
|
commandStarted,
|
|
2291
2273
|
inputMessageIds: pendingInputs.map((message) => message.messageId),
|
|
2292
2274
|
runId: continuation.runId,
|
|
2293
|
-
modelSelection:
|
|
2275
|
+
modelSelection: continuation.modelSelection,
|
|
2294
2276
|
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2295
2277
|
runScope: continuation.runScope,
|
|
2296
2278
|
runSpan: continuation.runSpan
|
|
@@ -2577,6 +2559,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2577
2559
|
const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
|
|
2578
2560
|
const execution = yield* inspectExecutionState();
|
|
2579
2561
|
const current = yield* currentReduced();
|
|
2562
|
+
input = {
|
|
2563
|
+
...input,
|
|
2564
|
+
modelSelection: current.modelSelection ?? input.modelSelection
|
|
2565
|
+
};
|
|
2580
2566
|
if (execution?._tag === "FailedTurn") return execution.result;
|
|
2581
2567
|
if (execution?._tag === "CompletedTurn") {
|
|
2582
2568
|
const decision = decideDispatch(current);
|
|
@@ -2680,7 +2666,12 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2680
2666
|
"eda.model.id": input.modelSelection.modelId
|
|
2681
2667
|
});
|
|
2682
2668
|
yield* failIfFatal;
|
|
2683
|
-
const
|
|
2669
|
+
const initial = yield* currentReduced();
|
|
2670
|
+
input = {
|
|
2671
|
+
...input,
|
|
2672
|
+
modelSelection: initial.modelSelection ?? input.modelSelection
|
|
2673
|
+
};
|
|
2674
|
+
const recovery = yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, input));
|
|
2684
2675
|
yield* requestStartupRecoveryCheckpointIfNeeded();
|
|
2685
2676
|
if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
|
|
2686
2677
|
});
|
|
@@ -2739,8 +2730,8 @@ const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function
|
|
|
2739
2730
|
});
|
|
2740
2731
|
const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
|
|
2741
2732
|
const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
|
|
2742
|
-
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
2743
|
-
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
2733
|
+
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 6 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
|
|
2734
|
+
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 6 ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2744
2735
|
return {
|
|
2745
2736
|
state: foldReducedState(checkpointState, yield* store.eventsAfter(checkpointSeq).pipe(Stream.runCollect, Effect.map((events) => Array.from(events)))),
|
|
2746
2737
|
checkpointSeq
|
|
@@ -2824,4 +2815,4 @@ const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag =
|
|
|
2824
2815
|
//#endregion
|
|
2825
2816
|
export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
|
|
2826
2817
|
|
|
2827
|
-
//# sourceMappingURL=session-state-
|
|
2818
|
+
//# sourceMappingURL=session-state-aIqe9CLa.js.map
|