effect-durable-agent 0.1.0-alpha.7 → 0.1.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/{command-queues-C8muEqeQ.d.ts → command-queues-DdDB_aYM.d.ts} +11 -18
  2. package/dist/compaction-BgDr5VJy.js +473 -0
  3. package/dist/compaction-BgDr5VJy.js.map +1 -0
  4. package/dist/{compaction-D7W0-Ur1.d.ts → compaction-ch8z6G9x.d.ts} +26 -7
  5. package/dist/{context-projection-C43pyxn2.d.ts → context-projection-n6Rdup0N.d.ts} +2 -2
  6. package/dist/domain/command-queues.d.ts +1 -1
  7. package/dist/domain/context-projection.d.ts +1 -1
  8. package/dist/domain/message-transcript.d.ts +1 -1
  9. package/dist/domain/model-usage.d.ts +2 -0
  10. package/dist/domain/model-usage.js +59 -0
  11. package/dist/domain/model-usage.js.map +1 -0
  12. package/dist/domain/reduced-state-schema.d.ts +11 -17
  13. package/dist/domain/reduced-state-schema.js +6 -11
  14. package/dist/domain/reduced-state-schema.js.map +1 -1
  15. package/dist/domain/reduced-state.d.ts +3 -2
  16. package/dist/domain/reduced-state.js +3 -2
  17. package/dist/{durable-DsV9PxZC.js → durable-BGFvX7Mh.js} +17 -80
  18. package/dist/durable-BGFvX7Mh.js.map +1 -0
  19. package/dist/{durable-B7M6TD_0.d.ts → durable-br2C1bWK.d.ts} +247 -4
  20. package/dist/envelope-DkZyMIgp.d.ts +191 -0
  21. package/dist/envelope-DxQzo5rN.js +82 -0
  22. package/dist/envelope-DxQzo5rN.js.map +1 -0
  23. package/dist/{event-factory-tcpLgdMN.js → event-factory-DTFdy0Cb.js} +3 -2
  24. package/dist/{event-factory-tcpLgdMN.js.map → event-factory-DTFdy0Cb.js.map} +1 -1
  25. package/dist/{event-factory-CLJcyymV.d.ts → event-factory-Di1jwQvm.d.ts} +3 -3
  26. package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
  27. package/dist/index.d.ts +5 -4
  28. package/dist/index.js +4 -3
  29. package/dist/{message-transcript-DsKTT47f.d.ts → message-transcript-DQNlzxle.d.ts} +3 -3
  30. package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
  31. package/dist/model-usage-CdBEkTwU.d.ts +55 -0
  32. package/dist/{prompt-projector-hqPh5-NI.d.ts → prompt-projector-f4ElyXCE.d.ts} +4 -4
  33. package/dist/{reduced-state-TMi7ISla.js → reduced-state-DF0-6mbR.js} +25 -30
  34. package/dist/reduced-state-DF0-6mbR.js.map +1 -0
  35. package/dist/{reducer-registry--vQFATXb.d.ts → reducer-registry-aFjz_ZLT.d.ts} +2 -2
  36. package/dist/run-scheduler-CAt7dF6C.js +21 -0
  37. package/dist/run-scheduler-CAt7dF6C.js.map +1 -0
  38. package/dist/run-scheduler-xkhZyto5.d.ts +44 -0
  39. package/dist/{runtime-DXvMCq-J.d.ts → runtime-DDSYP9jS.d.ts} +6 -6
  40. package/dist/services/compaction.d.ts +1 -1
  41. package/dist/services/compaction.js +1 -426
  42. package/dist/services/model-resolver.d.ts +2 -0
  43. package/dist/services/model-resolver.js +17 -0
  44. package/dist/services/model-resolver.js.map +1 -0
  45. package/dist/services/prompt-projector.d.ts +1 -1
  46. package/dist/services/reducer-registry.d.ts +1 -1
  47. package/dist/services/run-scheduler.d.ts +2 -0
  48. package/dist/services/run-scheduler.js +2 -0
  49. package/dist/services/runtime-layer.d.ts +17 -14
  50. package/dist/services/runtime-layer.js +10 -8
  51. package/dist/services/runtime-layer.js.map +1 -1
  52. package/dist/services/runtime.d.ts +1 -1
  53. package/dist/services/runtime.js +3 -2
  54. package/dist/services/runtime.js.map +1 -1
  55. package/dist/services/session-event-observer.d.ts +1 -1
  56. package/dist/services/session-query.d.ts +1 -1
  57. package/dist/services/session-query.js +3 -3
  58. package/dist/services/session-state.d.ts +1 -1
  59. package/dist/services/session-state.js +1 -1
  60. package/dist/services/session-store.d.ts +1 -1
  61. package/dist/services/session-store.js +2 -1
  62. package/dist/services/session-store.js.map +1 -1
  63. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  64. package/dist/services/sink-registry.d.ts +1 -1
  65. package/dist/services/sink-registry.js +1 -1
  66. package/dist/services/tool-registry.d.ts +1 -1
  67. package/dist/services/tracing.d.ts +1 -1
  68. package/dist/{session-event-observer-D_aoFnQs.d.ts → session-event-observer-DaFMKKNc.d.ts} +2 -2
  69. package/dist/{session-query-lUZQpMvM.d.ts → session-query-B72HY_0L.d.ts} +9 -9
  70. package/dist/{session-state-C4m0j6CJ.js → session-state-Bkc6u-Wr.js} +44 -39
  71. package/dist/session-state-Bkc6u-Wr.js.map +1 -0
  72. package/dist/{session-state-Bi3oEbJU.d.ts → session-state-C9YLSAso.d.ts} +16 -15
  73. package/dist/{session-store-ofm8FFxs.d.ts → session-store-Cpi_NwTR.d.ts} +3 -3
  74. package/dist/{sink-checkpoint-store-BQVbI9DQ.d.ts → sink-checkpoint-store-M7qIxoSH.d.ts} +2 -2
  75. package/dist/{sink-registry-CE-hL7cB.d.ts → sink-registry-Bl-vQES6.d.ts} +9 -9
  76. package/dist/{sink-registry-DH6uiEgP.js → sink-registry-NDgeyzO0.js} +4 -4
  77. package/dist/{sink-registry-DH6uiEgP.js.map → sink-registry-NDgeyzO0.js.map} +1 -1
  78. package/dist/testkit/layers.d.ts +19 -14
  79. package/dist/testkit/layers.js +12 -9
  80. package/dist/testkit/layers.js.map +1 -1
  81. package/dist/{tool-registry-ClHdr_G5.d.ts → tool-registry-BJaVNtw4.d.ts} +3 -3
  82. package/dist/types/events/durable.d.ts +2 -2
  83. package/dist/types/events/durable.js +2 -2
  84. package/dist/types/events.d.ts +4 -3
  85. package/dist/types/events.js +3 -2
  86. package/dist/types/events.js.map +1 -1
  87. package/dist/websocket.d.ts +63 -2
  88. package/dist/websocket.js +2 -1
  89. package/dist/websocket.js.map +1 -1
  90. package/package.json +15 -2
  91. package/dist/durable-DsV9PxZC.js.map +0 -1
  92. package/dist/reduced-state-TMi7ISla.js.map +0 -1
  93. package/dist/services/compaction.js.map +0 -1
  94. 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,OAA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,wBACH,eACA,UAAoC;CACnC,IACE,MAAM,MAAM,SAAS,6BACrB,MAAM,MAAM,SAAS,0BACrB,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
+ {"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,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KAAA;GAC9E,CAAC;GACD,MAAM,WAAW,OAAO,aAAa,aAAa,OAAO;GACzD,OAAO,OAAO,eAAe,6BAA6B,QAAQ,GAAG,SAAS,SAAS,GAAG;EAC5F,CAAC;EACD,gBAAgB,MAAM,SAAS;EAC/B,gBAAgB,MAAM,SAAS;EAC/B,cAAc,aAA6B,MAAM,YAAY,QAAQ;EACrE,gBAAgB,UAA0B,UACxC,MAAM,cAAc,UAAU,KAAK;CACvC;AACF,CAAC;AAEH,MAAM,wBACH,eACA,UAAoC;CACnC,IACE,MAAM,MAAM,SAAS,6BACrB,MAAM,MAAM,SAAS,0BACrB,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-D_aoFnQs.js";
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-lUZQpMvM.js";
1
+ import { i as EDASessionSnapshot, n as EDASessionQuery, r as EDASessionQueryShape, t as EDASessionEventPage } from "../session-query-B72HY_0L.js";
2
2
  export { EDASessionEventPage, EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
@@ -1,9 +1,9 @@
1
- import { mr as PositionedEvent } from "../durable-DsV9PxZC.js";
2
- import { u as SessionState } from "../session-state-C4m0j6CJ.js";
1
+ import { u as PositionedEvent } from "../envelope-DxQzo5rN.js";
2
+ import { u as SessionState } from "../session-state-Bkc6u-Wr.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-DH6uiEgP.js";
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-Bi3oEbJU.js";
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-C9YLSAso.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-C4m0j6CJ.js";
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-Bkc6u-Wr.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-ofm8FFxs.js";
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 { En as contextRebasedEventType, Un as summaryCreatedEventType, ar as DurableEventEnvelope, gn as commandAdmittedEventType } from "../durable-DsV9PxZC.js";
2
+ import { t as DurableEventEnvelope } from "../envelope-DxQzo5rN.js";
3
+ import { Dn as contextRebasedEventType, Gn as summaryCreatedEventType, _n as commandAdmittedEventType } from "../durable-BGFvX7Mh.js";
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,C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AAI,SAAS,CAAC,CAAC;EAC5E,wBAAwB,SACtB,IAAI,IAAI,IAAI,EAAE,KAAK,OAAO,KAAK,EAAE,yBAAyB,mBAAmB,IAAI,IAAI,CAAC,CAAC;EACzF,wBAAwB,eACtB,IAAI,OAAO,OAAO,aAAa;GAC7B,GAAG;GACH,oBAAoB,IAAI,IAAI,QAAQ,kBAAkB,EAAE,IAAI,WAAW,MAAM,UAAU;EACzF,EAAE;EACJ,yBAAyB,gBACvB,IAAI,OAAO,OAAO,YAAY;GAC5B,MAAM,qBAAqB,IAAI,IAAI,QAAQ,kBAAkB;GAC7D,KAAK,MAAM,cAAc,aACvB,mBAAmB,IAAI,WAAW,MAAM,UAAU;GAEpD,OAAO;IAAE,GAAG;IAAS;GAAmB;EAC1C,CAAC;CACL;AACF;AAEA,MAAM,2BACJ,OACA,UACY;CACZ,IAAI,MAAM,MAAM,SAAS,0BACvB,OAAO;CAET,MAAM,WAAY,MAAM,MAAM,QAA8C;CAC5E,IAAI,aAAa,KAAA,GACf,OAAO;CAET,IAAI,MAAM,mBAAmB,KAAA,KAAa,SAAS,mBAAmB,MAAM,gBAC1E,OAAO;CAET,OAAO,MAAM,cAAc,KAAA,KAAa,SAAS,cAAc,MAAM;AACvE"}
1
+ {"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as 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,IA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,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-BQVbI9DQ.js";
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-CE-hL7cB.js";
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-Bl-vQES6.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-DH6uiEgP.js";
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-ClHdr_G5.js";
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 { L as PositionedEvent } from "./events-Bb9-Cu-7.js";
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-D_aoFnQs.d.ts.map
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 { L as PositionedEvent } from "./events-Bb9-Cu-7.js";
3
- import { a as EDASessionStore, o as EDASessionStoreError } from "./session-store-ofm8FFxs.js";
4
- import { S as ReducedState } from "./command-queues-C8muEqeQ.js";
5
- import { t as DurableTranscriptMessage } from "./message-transcript-DsKTT47f.js";
6
- import { u as LiveEventBus } from "./sink-registry-CE-hL7cB.js";
7
- import { a as EDAReducerStateSnapshot } from "./reducer-registry--vQFATXb.js";
8
- import { h as SessionState } from "./session-state-Bi3oEbJU.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-Bl-vQES6.js";
7
+ import { a as EDAReducerStateSnapshot } from "./reducer-registry-aFjz_ZLT.js";
8
+ import { h as SessionState } from "./session-state-C9YLSAso.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";
@@ -38,8 +38,8 @@ interface EDASessionEventPage {
38
38
  declare const EDASessionQuery_base: Context.ServiceClass<EDASessionQuery, "@effect-durable-agent/EDASessionQuery", EDASessionQueryShape>;
39
39
  /** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
40
40
  declare class EDASessionQuery extends EDASessionQuery_base {
41
- static readonly Live: Layer.Layer<EDASessionQuery, never, SessionState | EDASessionStore | LiveEventBus>;
41
+ static readonly Live: Layer.Layer<EDASessionQuery, never, EDASessionStore | SessionState | LiveEventBus>;
42
42
  }
43
43
  //#endregion
44
44
  export { EDASessionSnapshot as i, EDASessionQuery as n, EDASessionQueryShape as r, EDASessionEventPage as t };
45
- //# sourceMappingURL=session-query-lUZQpMvM.d.ts.map
45
+ //# sourceMappingURL=session-query-B72HY_0L.d.ts.map
@@ -1,16 +1,19 @@
1
+ import { t as RunScheduler } from "./run-scheduler-CAt7dF6C.js";
2
+ import { ModelResolver } from "./services/model-resolver.js";
1
3
  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
4
  import { makeEDARunTrace } from "./types/tracing.js";
4
- import { An as inferenceFailedEventType, Jn as toolCallRejectedEventType, Kn as toolCallCreatedEventType, Zn as turnFailedEventType, _r as SystemPromptText, br as UsagePayload, dr as FailurePayload, fr as ModelSelectionPayload, gn as commandAdmittedEventType, hr as ProviderPartId, kn as inferenceCompletedEventType, mr as PositionedEvent, pr as NonNegativeInt, vr as ToolName } from "./durable-DsV9PxZC.js";
5
- 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-TMi7ISla.js";
5
+ 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";
6
+ import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
7
+ import { $n as turnFailedEventType, An as inferenceCompletedEventType, Jn as toolCallCreatedEventType, Xn as toolCallRejectedEventType, _n as commandAdmittedEventType, jn as inferenceFailedEventType } from "./durable-BGFvX7Mh.js";
8
+ 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
9
  import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
7
10
  import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError } from "./services/session-store.js";
11
+ import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-BgDr5VJy.js";
8
12
  import { IdGenerator } from "./services/id-generator.js";
9
- import { n as SessionContext, t as EventFactory } from "./event-factory-tcpLgdMN.js";
13
+ import { n as SessionContext, t as EventFactory } from "./event-factory-DTFdy0Cb.js";
10
14
  import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
11
15
  import { EDAKeepAlive } from "./services/keep-alive.js";
12
- import { CompactionRunner } from "./services/compaction.js";
13
- import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-DH6uiEgP.js";
16
+ import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-NDgeyzO0.js";
14
17
  import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
15
18
  import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
16
19
  import { EDAToolRegistry } from "./services/tool-registry.js";
@@ -28,7 +31,6 @@ import * as Queue from "effect/Queue";
28
31
  import * as Ref from "effect/Ref";
29
32
  import * as Scope from "effect/Scope";
30
33
  import * as Semaphore from "effect/Semaphore";
31
- import * as LanguageModel from "effect/unstable/ai/LanguageModel";
32
34
  import * as Option from "effect/Option";
33
35
  import * as Response from "effect/unstable/ai/Response";
34
36
  //#region src/domain/dispatch-policy.ts
@@ -757,7 +759,7 @@ Schema.TaggedErrorClass()("UnsupportedInferencePart", {
757
759
  const makeLiveInferenceRunner = Effect.gen(function* () {
758
760
  const ids = yield* IdGenerator;
759
761
  const events = yield* EventFactory;
760
- const languageModel = yield* LanguageModel.LanguageModel;
762
+ const models = yield* ModelResolver;
761
763
  const toolRegistry = yield* EDAToolRegistry;
762
764
  const recordPart = (eventSink, state, part, setLatestState) => Effect.gen(function* () {
763
765
  if (state.inference.phase === "sealed") {
@@ -972,6 +974,7 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
972
974
  return yield* requireTerminal(yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []));
973
975
  });
974
976
  return { runInference: Effect.fn("agent.inference")(function* (input) {
977
+ const languageModel = yield* models.resolve(input.modelSelection);
975
978
  const inferenceIdentity = {
976
979
  runId: input.runId,
977
980
  turnId: input.turnId,
@@ -1146,31 +1149,6 @@ const makeFinishMetadata = (part) => ({
1146
1149
  response: part.response,
1147
1150
  metadata: part.metadata
1148
1151
  });
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
1152
  Schema.Struct({
1175
1153
  runId: RunId,
1176
1154
  turnId: TurnId
@@ -1516,6 +1494,7 @@ const makeLiveSessionState = Effect.gen(function* () {
1516
1494
  const compactionRunner = yield* CompactionRunner;
1517
1495
  const promptProjector = yield* EDAPromptProjector;
1518
1496
  const sessionContext = yield* SessionContext;
1497
+ const runScheduler = yield* RunScheduler;
1519
1498
  const reducerRegistry = yield* EDAReducerRegistry;
1520
1499
  const sinkRegistry = yield* EDASinkRegistry;
1521
1500
  const hydrated = yield* hydrateFrameworkReducedState(store);
@@ -1557,7 +1536,7 @@ const makeLiveSessionState = Effect.gen(function* () {
1557
1536
  }));
1558
1537
  const buildReducerCheckpointSnapshot = (snapshot) => [{
1559
1538
  name: frameworkReducedStateReducerName,
1560
- schemaVersion: 5,
1539
+ schemaVersion: 6,
1561
1540
  throughSeq: snapshot.reduced.lastSeq,
1562
1541
  payload: encodeReducedStateCheckpoint(snapshot.reduced),
1563
1542
  updatedAtMs: snapshot.updatedAtMs
@@ -1994,6 +1973,10 @@ const makeLiveSessionState = Effect.gen(function* () {
1994
1973
  if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("startSubmitCommand requires SubmitMessage"));
1995
1974
  const submit = command.command;
1996
1975
  const commandId = command.commandId;
1976
+ yield* runScheduler.resolve({
1977
+ sessionId: sessionContext.sessionId,
1978
+ commandId
1979
+ });
1997
1980
  yield* annotateEdaSpan({
1998
1981
  "eda.command.id": commandId,
1999
1982
  "eda.command.disposition": submit.disposition,
@@ -2047,6 +2030,10 @@ const makeLiveSessionState = Effect.gen(function* () {
2047
2030
  return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
2048
2031
  });
2049
2032
  if (pending.length === 0) return yield* processInactiveStopCommand(command);
2033
+ yield* runScheduler.resolve({
2034
+ sessionId: sessionContext.sessionId,
2035
+ commandId: command.commandId
2036
+ });
2050
2037
  const commandStarted = yield* events.commandStarted({ commandId: command.commandId });
2051
2038
  const runId = yield* ids.makeRunId();
2052
2039
  const activeRunTrace = yield* startRunTrace({
@@ -2157,6 +2144,10 @@ const makeLiveSessionState = Effect.gen(function* () {
2157
2144
  });
2158
2145
  const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
2159
2146
  const plan = planSessionRecovery(reduced);
2147
+ input = {
2148
+ ...input,
2149
+ modelSelection: plan.continuation?.run.modelSelection ?? input.modelSelection
2150
+ };
2160
2151
  yield* annotateEdaSpan({
2161
2152
  "eda.recovery.reason": reason,
2162
2153
  "eda.recovery.open_tool_calls": plan.openToolCalls.length,
@@ -2238,6 +2229,10 @@ const makeLiveSessionState = Effect.gen(function* () {
2238
2229
  commandId: yield* ids.makeCommandId(),
2239
2230
  messageIds: plan.messageIdsToResume
2240
2231
  }) }));
2232
+ if (plan.continuation !== void 0) yield* runScheduler.resolve({
2233
+ sessionId: sessionContext.sessionId,
2234
+ commandId: plan.continuation.command.commandId
2235
+ });
2241
2236
  const continuationRunId = plan.continuation === void 0 ? void 0 : yield* ids.makeRunId();
2242
2237
  const continuationRunTrace = plan.continuation === void 0 || continuationRunId === void 0 ? void 0 : yield* startRunTrace({
2243
2238
  admissionTrace: plan.continuation.command.admissionTrace,
@@ -2268,6 +2263,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2268
2263
  continuation: plan.continuation === void 0 || continuationRunId === void 0 || continuationRunTrace === void 0 ? void 0 : {
2269
2264
  command: plan.continuation.command,
2270
2265
  runId: continuationRunId,
2266
+ modelSelection: input.modelSelection,
2271
2267
  inputMessageIds: plan.continuation.inputMessageIds,
2272
2268
  runScope: continuationRunTrace.runScope,
2273
2269
  runSpan: continuationRunTrace.runSpan
@@ -2290,7 +2286,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2290
2286
  commandStarted,
2291
2287
  inputMessageIds: pendingInputs.map((message) => message.messageId),
2292
2288
  runId: continuation.runId,
2293
- modelSelection: input.modelSelection,
2289
+ modelSelection: continuation.modelSelection,
2294
2290
  ...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
2295
2291
  runScope: continuation.runScope,
2296
2292
  runSpan: continuation.runSpan
@@ -2577,6 +2573,10 @@ const makeLiveSessionState = Effect.gen(function* () {
2577
2573
  const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
2578
2574
  const execution = yield* inspectExecutionState();
2579
2575
  const current = yield* currentReduced();
2576
+ input = {
2577
+ ...input,
2578
+ modelSelection: current.modelSelection ?? input.modelSelection
2579
+ };
2580
2580
  if (execution?._tag === "FailedTurn") return execution.result;
2581
2581
  if (execution?._tag === "CompletedTurn") {
2582
2582
  const decision = decideDispatch(current);
@@ -2680,7 +2680,12 @@ const makeLiveSessionState = Effect.gen(function* () {
2680
2680
  "eda.model.id": input.modelSelection.modelId
2681
2681
  });
2682
2682
  yield* failIfFatal;
2683
- const recovery = yield* withFatalRecording(recoverSession(yield* currentReduced(), startupRecoveryReason, input));
2683
+ const initial = yield* currentReduced();
2684
+ input = {
2685
+ ...input,
2686
+ modelSelection: initial.modelSelection ?? input.modelSelection
2687
+ };
2688
+ const recovery = yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, input));
2684
2689
  yield* requestStartupRecoveryCheckpointIfNeeded();
2685
2690
  if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
2686
2691
  });
@@ -2739,8 +2744,8 @@ const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function
2739
2744
  });
2740
2745
  const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
2741
2746
  const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
2742
- const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 5 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
2743
- const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 5 ? SequenceNumber.make(0) : checkpoint.throughSeq;
2747
+ const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 6 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
2748
+ const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 6 ? SequenceNumber.make(0) : checkpoint.throughSeq;
2744
2749
  return {
2745
2750
  state: foldReducedState(checkpointState, yield* store.eventsAfter(checkpointSeq).pipe(Stream.runCollect, Effect.map((events) => Array.from(events)))),
2746
2751
  checkpointSeq
@@ -2824,4 +2829,4 @@ const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag =
2824
2829
  //#endregion
2825
2830
  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
2831
 
2827
- //# sourceMappingURL=session-state-C4m0j6CJ.js.map
2832
+ //# sourceMappingURL=session-state-Bkc6u-Wr.js.map