effect-durable-agent 0.1.0-alpha.4 → 0.1.0-alpha.6

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 (85) hide show
  1. package/README.md +19 -18
  2. package/dist/{command-queues-CV7O-51r.d.ts → command-queues-C8muEqeQ.d.ts} +2 -2
  3. package/dist/{compaction-zbvLREI8.d.ts → compaction-F4HEWzuI.d.ts} +5 -5
  4. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-C43pyxn2.d.ts} +2 -2
  5. package/dist/domain/command-queues.d.ts +1 -1
  6. package/dist/domain/context-projection.d.ts +1 -1
  7. package/dist/domain/message-transcript.d.ts +1 -1
  8. package/dist/domain/reduced-state.d.ts +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/{message-transcript-DiOPBY3l.d.ts → message-transcript-DsKTT47f.d.ts} +3 -3
  11. package/dist/{prompt-projector-C1IbkHr0.d.ts → prompt-projector-hqPh5-NI.d.ts} +4 -4
  12. package/dist/{reducer-registry-CjSJBPKo.d.ts → reducer-registry--vQFATXb.d.ts} +16 -6
  13. package/dist/{runtime-DOgmAKsO.d.ts → runtime-BO9KJq_Y.d.ts} +7 -5
  14. package/dist/services/compaction.d.ts +1 -1
  15. package/dist/services/prompt-projector.d.ts +1 -1
  16. package/dist/services/reducer-registry.d.ts +2 -2
  17. package/dist/services/reducer-registry.js +7 -3
  18. package/dist/services/reducer-registry.js.map +1 -1
  19. package/dist/services/runtime-layer.d.ts +12 -9
  20. package/dist/services/runtime-layer.js +6 -4
  21. package/dist/services/runtime-layer.js.map +1 -1
  22. package/dist/services/runtime.d.ts +1 -1
  23. package/dist/services/runtime.js +3 -2
  24. package/dist/services/runtime.js.map +1 -1
  25. package/dist/services/session-event-observer.d.ts +2 -0
  26. package/dist/services/session-event-observer.js +13 -0
  27. package/dist/services/session-event-observer.js.map +1 -0
  28. package/dist/services/session-query.d.ts +2 -2
  29. package/dist/services/session-query.js +20 -3
  30. package/dist/services/session-query.js.map +1 -1
  31. package/dist/services/session-state.d.ts +1 -1
  32. package/dist/services/session-state.js +1 -1
  33. package/dist/services/session-store.d.ts +1 -1
  34. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  35. package/dist/services/sink-registry.d.ts +1 -1
  36. package/dist/services/sink-registry.js +1 -1
  37. package/dist/services/span-names.d.ts +1 -1
  38. package/dist/services/span-names.js +1 -0
  39. package/dist/services/span-names.js.map +1 -1
  40. package/dist/services/tool-registry.d.ts +1 -1
  41. package/dist/services/tracing.js +23 -2
  42. package/dist/services/tracing.js.map +1 -1
  43. package/dist/session-event-observer-D_aoFnQs.d.ts +24 -0
  44. package/dist/{session-query-C-C4m1eq.d.ts → session-query-_Z3Kw6jj.d.ts} +15 -8
  45. package/dist/{session-state-CjOSvWbe.d.ts → session-state-BfoXKafd.d.ts} +11 -11
  46. package/dist/{session-state-SStf0KUo.js → session-state-C4m0j6CJ.js} +2 -2
  47. package/dist/{session-state-SStf0KUo.js.map → session-state-C4m0j6CJ.js.map} +1 -1
  48. package/dist/{session-store-DZZUffUy.d.ts → session-store-ofm8FFxs.d.ts} +2 -2
  49. package/dist/{sink-checkpoint-store-BZmQFTRE.d.ts → sink-checkpoint-store-BQVbI9DQ.d.ts} +2 -2
  50. package/dist/{sink-registry-D13eUO_c.js → sink-registry-DH6uiEgP.js} +19 -21
  51. package/dist/sink-registry-DH6uiEgP.js.map +1 -0
  52. package/dist/{sink-registry-Cf79ICdW.d.ts → sink-registry-PRYbj6dp.d.ts} +18 -14
  53. package/dist/testkit/layers.d.ts +10 -10
  54. package/dist/testkit/layers.js +3 -3
  55. package/dist/testkit/layers.js.map +1 -1
  56. package/dist/{tool-registry-B7Wona6N.d.ts → tool-registry-ClHdr_G5.d.ts} +2 -2
  57. package/dist/{websocket-wire-QD2SquQE.d.ts → websocket.d.ts} +335 -12
  58. package/dist/websocket.js +428 -0
  59. package/dist/websocket.js.map +1 -0
  60. package/package.json +15 -31
  61. package/testing/offline-trace/README.md +2 -1
  62. package/CHANGELOG.md +0 -34
  63. package/CONTRIBUTING.md +0 -26
  64. package/SECURITY.md +0 -7
  65. package/dist/host/websocket-protocol.d.ts +0 -229
  66. package/dist/host/websocket-protocol.js +0 -99
  67. package/dist/host/websocket-protocol.js.map +0 -1
  68. package/dist/host/websocket-wire.d.ts +0 -2
  69. package/dist/host/websocket-wire.js +0 -105
  70. package/dist/host/websocket-wire.js.map +0 -1
  71. package/dist/services/websocket-subscriber.d.ts +0 -54
  72. package/dist/services/websocket-subscriber.js +0 -190
  73. package/dist/services/websocket-subscriber.js.map +0 -1
  74. package/dist/sink-registry-D13eUO_c.js.map +0 -1
  75. package/docs/assets/architecture.svg +0 -216
  76. package/docs/assets/event-sequence.svg +0 -133
  77. package/docs/assets/gcp-trace.png +0 -0
  78. package/docs/assets/hero.svg +0 -33
  79. package/docs/message-steering.md +0 -831
  80. package/docs/releasing.md +0 -114
  81. package/docs/spec.md +0 -777
  82. package/docs/subagents.md +0 -725
  83. package/docs/testing.md +0 -64
  84. package/docs/ui-projection.md +0 -742
  85. package/docs/websocket-protocol.md +0 -639
@@ -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}\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 };\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;;AAiDD,IAAa,aAAb,MAAa,mBAAmB,QAAQ,QAAqC,EAC3E,kCACF,EAAE;CACA,OAAgB,QAAQ,WACtB,MAAM,OAAO,YAAY,gBAAgB,MAAM,CAAC;AACpD;A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EACtD,CAGO;EACL;EACA,gBAAgB,OAAO,GAAG,WAAW,SAAqB;GACxD,OAAO,gBAAgB;IACrB,oBAAoB,QAAQ;IAC5B,kBAAkB,QAAQ;IAC1B,2BAA2B,iBAAiB,UAAU,QAAQ,cAAc,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;CACvE;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
+ {"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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SessionEventObserver, SessionEventObserverShape };
@@ -0,0 +1,13 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Layer from "effect/Layer";
4
+ //#region src/services/session-event-observer.ts
5
+ /** Host-provided observer for append-driven integrations such as hibernatable WebSockets. */
6
+ var SessionEventObserver = class SessionEventObserver extends Context.Service()("@effect-durable-agent/SessionEventObserver") {
7
+ static Noop = Layer.succeed(SessionEventObserver, { onEvent: () => Effect.void });
8
+ static FromHandler = (onEvent) => Layer.succeed(SessionEventObserver, { onEvent });
9
+ };
10
+ //#endregion
11
+ export { SessionEventObserver };
12
+
13
+ //# sourceMappingURL=session-event-observer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-event-observer.js","names":[],"sources":["../../src/services/session-event-observer.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport type { PositionedEvent } from \"../types/events\";\n\n/**\n * Outbound integration point notified synchronously after EDA publishes an event.\n *\n * Hosts provide this service while composing the runtime. Implementations own\n * their failures and never expose host errors to the session runtime.\n */\nexport interface SessionEventObserverShape {\n readonly onEvent: (event: PositionedEvent) => Effect.Effect<void>;\n}\n\n/** Host-provided observer for append-driven integrations such as hibernatable WebSockets. */\nexport class SessionEventObserver extends Context.Service<\n SessionEventObserver,\n SessionEventObserverShape\n>()(\"@effect-durable-agent/SessionEventObserver\") {\n static readonly Noop = Layer.succeed(SessionEventObserver, {\n onEvent: () => Effect.void,\n });\n\n static readonly FromHandler = (\n onEvent: SessionEventObserverShape[\"onEvent\"],\n ): Layer.Layer<SessionEventObserver> => Layer.succeed(SessionEventObserver, { onEvent });\n}\n"],"mappings":";;;;;AAiBA,IAAa,uBAAb,MAAa,6BAA6B,QAAQ,QAGhD,EAAE,4CAA4C,EAAE;CAChD,OAAgB,OAAO,MAAM,QAAQ,sBAAsB,EACzD,eAAe,OAAO,KACxB,CAAC;CAED,OAAgB,eACd,YACsC,MAAM,QAAQ,sBAAsB,EAAE,QAAQ,CAAC;AACzF"}
@@ -1,2 +1,2 @@
1
- import { n as EDASessionQueryShape, r as EDASessionSnapshot, t as EDASessionQuery } from "../session-query-C-C4m1eq.js";
2
- export { EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
1
+ import { i as EDASessionSnapshot, n as EDASessionQuery, r as EDASessionQueryShape, t as EDASessionEventPage } from "../session-query-_Z3Kw6jj.js";
2
+ export { EDASessionEventPage, EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
@@ -1,9 +1,9 @@
1
1
  import { mr as PositionedEvent } from "../durable-DsV9PxZC.js";
2
- import { u as SessionState } from "../session-state-SStf0KUo.js";
2
+ import { u as SessionState } from "../session-state-C4m0j6CJ.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-D13eUO_c.js";
6
+ import { r as LiveEventBus } from "../sink-registry-DH6uiEgP.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";
@@ -51,7 +51,24 @@ var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-d
51
51
  });
52
52
  const follow = Stream.fromEffectRepeat(PubSub.take(live)).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));
53
53
  return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));
54
- }).pipe(Effect.withSpan("agent.events.follow", { attributes: { "eda.seq.after": afterSeq } }))
54
+ }).pipe(Effect.withSpan("agent.events.follow", { attributes: { "eda.seq.after": afterSeq } })),
55
+ readEventPage: (afterSeq, limit) => Effect.gen(function* () {
56
+ const head = (yield* sessionState.snapshot()).lastSeq;
57
+ if (limit <= 0 || afterSeq >= head) return {
58
+ events: [],
59
+ head
60
+ };
61
+ return {
62
+ events: yield* store.eventsAfter(afterSeq).pipe(Stream.filter((entry) => entry.position.seq <= head), Stream.take(limit), Stream.map((entry) => PositionedEvent.make({
63
+ position: entry.position,
64
+ event: entry.event
65
+ })), Stream.runCollect, Effect.map((events) => Array.from(events))),
66
+ head
67
+ };
68
+ }).pipe(Effect.withSpan("agent.events.page", { attributes: {
69
+ "eda.seq.after": afterSeq,
70
+ "eda.page.limit": limit
71
+ } }))
55
72
  };
56
73
  }));
57
74
  };
@@ -1 +1 @@
1
- {"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */\nexport interface EDASessionSnapshot {\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly messages: ReadonlyArray<DurableTranscriptMessage>;\n}\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({ position: entry.position, event: entry.event }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n output.push(event);\n }\n return output;\n};\n"],"mappings":";;;;;;;;;;;;;AA6CA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO;EACvB,MAAM,eAAe,OAAO;EAE5B,MAAM,WAAW,OAAO,IAAI,aAAa;GACvC,MAAM,OAAO,OAAO,aAAa,aAAa;GAC9C,OAAO;IACL,OAAO,KAAK;IACZ,eAAe,KAAK;IACpB,UAAU,yBAAyB,KAAK,OAAO;GACjD;EACF,CAAC;EAED,OAAO;GACL,gBAAgB;GA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AAS,MAAM;AAEjE,MAAM,2BAA2B,MAAuB,UAAmC;CACzF,MAAM,MAAM,KAAK,SAAS,MAAM,MAAM,SAAS;CAC/C,OAAO,QAAQ,IAAI,KAAK,SAAS,SAAS,MAAM,SAAS,SAAS;AACpE;AAEA,MAAM,0BACJ,WACmC;CACnC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */\nexport interface EDASessionSnapshot {\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly messages: ReadonlyArray<DurableTranscriptMessage>;\n}\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({ position: entry.position, event: entry.event }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({ position: entry.position, event: entry.event }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n output.push(event);\n }\n return output;\n};\n"],"mappings":";;;;;;;;;;;;;AAwDA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO;EACvB,MAAM,eAAe,OAAO;EAE5B,MAAM,WAAW,OAAO,IAAI,aAAa;GACvC,MAAM,OAAO,OAAO,aAAa,aAAa;GAC9C,OAAO;IACL,OAAO,KAAK;IACZ,eAAe,KAAK;IACpB,UAAU,yBAAyB,KAAK,OAAO;GACjD;EACF,CAAC;EAED,OAAO;GACL,gBAAgB;GAChB,gBAAgB,SAAS,KAAK,OAAO,KAAK,aAAa,SAAS,QAAQ,CAAC;GACzE,cAAc,aACZ,OAAO,IAAI,aAAa;IACtB,MAAM,OAAO,OAAO,QAAQ,eAAe;IAC3C,MAAM,cAAc,OAAO,aAAa,SAAS,GAAG;IAIpD,MAAM,SAAS,OAAO,MAAM,YAAY,QAAQ,EAAE,KAChD,OAAO,QAAQ,UAAU,MAAM,SAAS,OAAO,UAAU,GACzD,OAAO,KAAK,UACV,gBAAgB,KAAK;KAAE,UAAU,MAAM;KAAU,OAAO,MAAM;IAAM,CAAC,CACvE,GACA,OAAO,YACP,OAA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ACD,OAAO,SAAS,qBAAqB,EACnC,YAAY;IAAE,iBAAiB;IAAU,kBAAkB;GAAM,EACnE,CAAC,CACH;EACJ;CACF,CAAC,CACH;AACF;AAEA,MAAM,uBAAuB,OAAwB,eACnD,MAAM,MAAM,eAAe,eAAe,MAAM,SAAS,MAAM;AAEjE,MAAM,2BAA2B,MAAuB,UAAmC;CACzF,MAAM,MAAM,KAAK,SAAS,MAAM,MAAM,SAAS;CAC/C,OAAO,QAAQ,IAAI,KAAK,SAAS,SAAS,MAAM,SAAS,SAAS;AACpE;AAEA,MAAM,0BACJ,WACmC;CACnC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
@@ -1,2 +1,2 @@
1
- import { _ 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-CjOSvWbe.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-BfoXKafd.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-SStf0KUo.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-C4m0j6CJ.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-DZZUffUy.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-ofm8FFxs.js";
2
2
  export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError };
@@ -1,2 +1,2 @@
1
- import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-BZmQFTRE.js";
1
+ import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-BQVbI9DQ.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-Cf79ICdW.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-PRYbj6dp.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-D13eUO_c.js";
1
+ import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-DH6uiEgP.js";
2
2
  export { EDASink, EDASinkRegistry };
@@ -20,7 +20,7 @@
20
20
  *
21
21
  * Application-specific operations belong in the application catalog, not this reusable catalog.
22
22
  */
23
- declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.stream", "agent.inference", "agent.messages.list", "agent.run", "agent.session.snapshot", "agent.sink.drain", "agent.tool", "agent.turn"];
23
+ declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.page", "agent.events.stream", "agent.inference", "agent.messages.list", "agent.run", "agent.session.snapshot", "agent.sink.drain", "agent.tool", "agent.turn"];
24
24
  /** Union of values admitted by the centralized EDA span-name catalog. */
25
25
  type SpanName = (typeof SpanNames)[number];
26
26
  //#endregion
@@ -27,6 +27,7 @@ const SpanNames = defineSpanNames([
27
27
  "agent.command.wait",
28
28
  "agent.compaction",
29
29
  "agent.events.follow",
30
+ "agent.events.page",
30
31
  "agent.events.stream",
31
32
  "agent.inference",
32
33
  "agent.messages.list",
@@ -1 +1 @@
1
- {"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.messages.list\",\n \"agent.run\",\n \"agent.session.snapshot\",\n \"agent.sink.drain\",\n \"agent.tool\",\n \"agent.turn\",\n]);\n\n/** Union of values admitted by the centralized EDA span-name catalog. */\nexport type SpanName = (typeof SpanNames)[number];\n"],"mappings":";AAEA,MAAM,mBACJ,UACU;;;;;;;;;;;;;;;;;;;;;;AAuBZ,MAAa,YAAY,gBAAgB;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
1
+ {"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.page\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.messages.list\",\n \"agent.run\",\n \"agent.session.snapshot\",\n \"agent.sink.drain\",\n \"agent.tool\",\n \"agent.turn\",\n]);\n\n/** Union of values admitted by the centralized EDA span-name catalog. */\nexport type SpanName = (typeof SpanNames)[number];\n"],"mappings":";AAEA,MAAM,mBACJ,UACU;;;;;;;;;;;;;;;;;;;;;;AAuBZ,MAAa,YAAY,gBAAgB;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
@@ -1,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-B7Wona6N.js";
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";
2
2
  export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
@@ -5,6 +5,8 @@ import * as Exit from "effect/Exit";
5
5
  import * as Option from "effect/Option";
6
6
  import * as Tracer from "effect/Tracer";
7
7
  //#region src/services/tracing.ts
8
+ /** Maximum primitive attributes copied from one native Effect span or link. */
9
+ const MAX_EXPORTED_SPAN_ATTRIBUTES = 256;
8
10
  /** Compact undefined tracing attributes before handing them to Effect spans. */
9
11
  const compactSpanAttributes = (attributes) => {
10
12
  const compacted = {};
@@ -12,9 +14,28 @@ const compactSpanAttributes = (attributes) => {
12
14
  return compacted;
13
15
  };
14
16
  const compactUnknownAttributes = (attributes) => {
15
- const entries = attributes instanceof Map ? attributes.entries() : Object.entries(attributes);
16
17
  const compacted = {};
17
- for (const [key, value] of entries) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") compacted[key] = value;
18
+ try {
19
+ if (attributes instanceof Map) {
20
+ let count = 0;
21
+ for (const [key, value] of attributes) {
22
+ if (count >= MAX_EXPORTED_SPAN_ATTRIBUTES) break;
23
+ count += 1;
24
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") compacted[key] = value;
25
+ }
26
+ return compacted;
27
+ }
28
+ const keys = Object.keys(attributes).slice(0, MAX_EXPORTED_SPAN_ATTRIBUTES);
29
+ for (const key of keys) {
30
+ let value;
31
+ try {
32
+ value = Reflect.get(attributes, key);
33
+ } catch {
34
+ continue;
35
+ }
36
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") compacted[key] = value;
37
+ }
38
+ } catch {}
18
39
  return compacted;
19
40
  };
20
41
  const toEdaExternalSpan = (context) => Tracer.externalSpan({
@@ -1 +1 @@
1
- {"version":3,"file":"tracing.js","names":["#emit"],"sources":["../../src/services/tracing.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Tracer from \"effect/Tracer\";\n\nimport type { UsagePayload } from \"../types/events\";\nimport {\n EDATraceContext,\n type EDAEventTrace,\n type EDATraceAttributeValue,\n type EDATraceMetadata,\n makeEDAEventTrace,\n makeEDATraceContext,\n makeRootEDAEventTrace,\n} from \"../types/tracing\";\n\nexport {\n EDATraceContext,\n EDARunTrace,\n EDATraceLink,\n EDATraceMetadata,\n EDAEventTrace,\n makeEDAEventTrace,\n makeEDARunTrace,\n makeEDATraceContext,\n makeEDATraceMetadataFromParent,\n makeRootEDAEventTrace,\n makeRootEDATraceMetadata,\n} from \"../types/tracing\";\n\nexport { buildEDATraceparent, parseEDATraceparent } from \"../types/tracing\";\n\n/** Attribute value types accepted by Effect span annotations after compaction. */\nexport type EdaSpanAttributeValue = EDATraceAttributeValue | undefined;\n\n/** EDA span attribute map; undefined values are intentionally dropped before annotation. */\nexport type EdaSpanAttributes = Record<string, EdaSpanAttributeValue>;\n\nexport interface EDATracingOptions {\n readonly disableTracing?: boolean;\n readonly disableSpanPropagation?: boolean;\n readonly spanAttributes?: EdaSpanAttributes;\n readonly spanPrefix?: string;\n}\n\nexport interface EDAExportedSpanLink {\n readonly attributes: Record<string, string | number | boolean>;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly traceId: string;\n}\n\nexport interface EDAExportedSpan {\n readonly attributes: Record<string, string | number | boolean>;\n readonly endedAtMs: number;\n readonly endedAtUnixNano: string;\n readonly kind: Tracer.SpanKind;\n readonly links: ReadonlyArray<EDAExportedSpanLink>;\n readonly name: string;\n readonly outcome: \"ok\" | \"error\" | \"timeout\" | \"canceled\";\n readonly parentSpanId?: string;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly startedAtMs: number;\n readonly startedAtUnixNano: string;\n readonly statusCode: \"OK\" | \"ERROR\";\n readonly statusMessage?: string;\n readonly traceId: string;\n}\n\ninterface EventLike {\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n readonly type?: unknown;\n}\n\ninterface PositionedEventLike {\n readonly position?: { readonly seq?: unknown; readonly subSeq?: unknown };\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n}\n\n/** Compact undefined tracing attributes before handing them to Effect spans. */\nexport const compactSpanAttributes = (\n attributes: EdaSpanAttributes,\n): Record<string, string | number | boolean> => {\n const compacted: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n compacted[key] = value;\n }\n }\n return compacted;\n};\n\nconst compactUnknownAttributes = (\n attributes: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>,\n): Record<string, string | number | boolean> => {\n const entries = attributes instanceof Map ? attributes.entries() : Object.entries(attributes);\n const compacted: Record<string, string | number | boolean> = {};\n for (const [key, value] of entries) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n compacted[key] = value;\n }\n }\n return compacted;\n};\n\nexport const toEdaExternalSpan = (context: EDATraceContext): Tracer.ExternalSpan =>\n Tracer.externalSpan({\n traceId: context.traceId,\n spanId: context.spanId,\n sampled: context.sampled,\n });\n\nexport const edaTraceContextFromSpan = (span: Tracer.AnySpan): EDATraceContext =>\n makeEDATraceContext({\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled,\n tracestate: null,\n });\n\nexport const currentEDATraceContext: Effect.Effect<EDATraceContext, unknown> =\n Effect.currentSpan.pipe(Effect.map(edaTraceContextFromSpan));\n\nexport const currentOrRootEDAEventTrace: Effect.Effect<EDAEventTrace> = Effect.currentSpan.pipe(\n Effect.map((span) => makeEDAEventTrace(edaTraceContextFromSpan(span))),\n Effect.catch(() => Effect.sync(makeRootEDAEventTrace)),\n);\n\nexport const withEdaTraceMetadata =\n (metadata: EDATraceMetadata) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n effect.pipe(Effect.annotateSpans(metadata.attributes));\n\n/** Add EDA attributes to the currently active span. */\nexport const annotateEdaSpan = (attributes: EdaSpanAttributes): Effect.Effect<void> =>\n Effect.annotateCurrentSpan(compactSpanAttributes(attributes));\n\nconst nanosToMillis = (nanos: bigint): number => Number(nanos / 1_000_000n);\n\nconst outcomeFromExit = (exit: Exit.Exit<unknown, unknown>): EDAExportedSpan[\"outcome\"] => {\n if (Exit.isSuccess(exit)) {\n return \"ok\";\n }\n return Cause.hasInterruptsOnly(exit.cause) ? \"canceled\" : \"error\";\n};\n\nconst statusMessageFromExit = (exit: Exit.Exit<unknown, unknown>): string | undefined => {\n if (Exit.isSuccess(exit)) {\n return undefined;\n }\n const error = Cause.squash(exit.cause);\n return error instanceof Error ? error.message : String(error);\n};\n\nclass ExportingNativeSpan extends Tracer.NativeSpan {\n readonly #emit: (span: EDAExportedSpan) => void;\n\n constructor(\n options: ConstructorParameters<typeof Tracer.NativeSpan>[0],\n emit: (span: EDAExportedSpan) => void,\n ) {\n super(options);\n this.#emit = emit;\n }\n\n override end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n super.end(endTime, exit);\n // Workers can report the same clock tick for very fast operations. Such spans\n // add noise without describing execution, so keep them out of exported traces.\n if (endTime <= this.startTime) {\n return;\n }\n const parent = Option.getOrUndefined(this.parent);\n this.#emit({\n attributes: compactUnknownAttributes(this.attributes),\n endedAtMs: nanosToMillis(endTime),\n endedAtUnixNano: endTime.toString(),\n kind: this.kind,\n links: this.links.map((link) => ({\n attributes: compactUnknownAttributes(link.attributes),\n traceId: link.span.traceId,\n spanId: link.span.spanId,\n sampled: link.span.sampled,\n })),\n name: this.name,\n outcome: outcomeFromExit(exit),\n ...(parent === undefined ? {} : { parentSpanId: parent.spanId }),\n sampled: this.sampled,\n spanId: this.spanId,\n startedAtMs: nanosToMillis(this.startTime),\n startedAtUnixNano: this.startTime.toString(),\n statusCode: Exit.isSuccess(exit) ? \"OK\" : \"ERROR\",\n ...(statusMessageFromExit(exit) === undefined\n ? {}\n : { statusMessage: statusMessageFromExit(exit) }),\n traceId: this.traceId,\n });\n }\n}\n\n/** Create an Effect tracer that exports only spans with observable duration. */\nexport const makeEdaExportingTracer = (emit: (span: EDAExportedSpan) => void): Tracer.Tracer =>\n Tracer.make({\n span: (options) => new ExportingNativeSpan(options, emit),\n });\n\n/** Summarize a durable/logical event collection for span attributes. */\nexport const eventBatchAttributes = (events: ReadonlyArray<EventLike>): EdaSpanAttributes => ({\n \"eda.event.count\": events.length,\n \"eda.event.types\": eventTypeSummary(events),\n});\n\n/** Summarize a committed positioned event collection for span attributes. */\nexport const committedBatchAttributes = (\n events: ReadonlyArray<PositionedEventLike>,\n): EdaSpanAttributes => {\n const seqs = events\n .map((entry) => entry.position?.seq)\n .filter((seq): seq is number => typeof seq === \"number\");\n return {\n ...eventBatchAttributes(events),\n \"eda.seq.min\": seqs.length === 0 ? undefined : Math.min(...seqs),\n \"eda.seq.max\": seqs.length === 0 ? undefined : Math.max(...seqs),\n };\n};\n\n/** Stable, low-cardinality usage attributes for model lifecycle spans. */\nexport const usageAttributes = (usage: UsagePayload | undefined): EdaSpanAttributes => ({\n \"eda.usage.input_tokens\": usage?.inputTokens,\n \"eda.usage.cached_input_tokens\": usage?.cachedInputTokens,\n \"eda.usage.output_tokens\": usage?.outputTokens,\n \"eda.usage.text_tokens\": usage?.textTokens,\n \"eda.usage.reasoning_tokens\": usage?.reasoningTokens,\n});\n\nconst eventTypeSummary = (events: ReadonlyArray<EventLike>): string | undefined => {\n if (events.length === 0) {\n return undefined;\n }\n const seen = new Set<string>();\n for (const event of events) {\n const type = event.event?.type ?? event.type;\n if (typeof type === \"string\") {\n seen.add(type);\n }\n }\n return seen.size === 0 ? undefined : Array.from(seen).join(\",\");\n};\n"],"mappings":";;;;;;;;AAkFA,MAAa,yBACX,eAC8C;CAC9C,MAAM,YAAuD,CAAC;CAC9D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,UAAU,KAAA,GACZ,UAAU,OAAO;CAGrB,OAAO;AACT;AAEA,MAAM,4BACJ,eAC8C;CAC9C,MAAM,UAAU,sBAAsB,MAAM,WAAW,QAAQ,IAAI,OAAO,QAAQ,UAAU;CAC5F,MAAM,YAAuD,CAAC;CAC9D,KAAK,MAAM,CAAC,KAAK,UAAU,SACzB,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC7E,UAAU,OAAO;CAGrB,OAAO;AACT;AAEA,MAAa,qBAAqB,YAChC,OAAO,aAAa;CAClB,SAAS,QAAQ;CACjB,QAAQ,QAAQ;CAChB,SAAS,QAAQ;AACnB,CAAC;AAEH,MAAa,2BAA2B,SACtC,oBAAoB;CAClB,SAAS,KAAK;CACd,QAAQ,KAAK;CACb,SAAS,KAAK;CACd,YAAY;AACd,CAAC;AAEH,MAAa,yBACX,OAAO,YAAY,KAAK,OAAO,IAAI,uBAAuB,CAAC;AAE7D,MAAa,6BAA2D,OAAO,YAAY,KACzF,OAAO,KAAK,SAAS,kBAAkB,wBAAwB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GACzC,mBAAmB,KAAK,UAAU,SAAS;GAC3C,YAAY,KAAK,UAAU,IAAI,IAAI,OAAO;GAC1C,GAAI,sBAAsB,IAAI,MAAM,KAAA,IAChC,CAAC,IACD,EAAE,eAAe,sBAAsB,IAAI,EAAE;GACjD,SAAS,KAAK;EAChB,CAAC;CACH;AACF;;AAGA,MAAa,0BAA0B,SACrC,OAAO,KAAK,EACV,OAAO,YAAY,IAAI,oBAAoB,SAAS,IAAI,EAC1D,CAAC;;AAGH,MAAa,wBAAwB,YAAyD;CAC5F,mBAAmB,OAAO;CAC1B,mBAAmB,iBAAiB,MAAM;AAC5C;;AAGA,MAAa,4BACX,WACsB;CACtB,MAAM,OAAO,OACV,KAAK,UAAU,MAAM,UAAU,GAAG,EAClC,QAAQ,QAAuB,OAAO,QAAQ,QAAQ;CACzD,OAAO;EACL,GAAG,qBAAqB,MAAM;EAC9B,eAAe,KAAK,WAAW,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,IAAI;EAC/D,eAAe,KAAK,WAAW,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,IAAI;CACjE;AACF;;AAGA,MAAa,mBAAmB,WAAwD;CACtF,0BAA0B,OAAO;CACjC,iCAAiC,OAAO;CACxC,2BAA2B,OAAO;CAClC,yBAAyB,OAAO;CAChC,8BAA8B,OAAO;AACvC;AAEA,MAAM,oBAAoB,WAAyD;CACjF,IAAI,OAAO,WAAW,GACpB;CAEF,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAM;EACxC,IAAI,OAAO,SAAS,UAClB,KAAK,IAAI,IAAI;CAEjB;CACA,OAAO,KAAK,SAAS,IAAI,KAAA,IAAY,MAAM,KAAK,IAAI,EAAE,KAAK,GAAG;AAChE"}
1
+ {"version":3,"file":"tracing.js","names":["#emit"],"sources":["../../src/services/tracing.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Tracer from \"effect/Tracer\";\n\nimport type { UsagePayload } from \"../types/events\";\nimport {\n EDATraceContext,\n type EDAEventTrace,\n type EDATraceAttributeValue,\n type EDATraceMetadata,\n makeEDAEventTrace,\n makeEDATraceContext,\n makeRootEDAEventTrace,\n} from \"../types/tracing\";\n\nexport {\n EDATraceContext,\n EDARunTrace,\n EDATraceLink,\n EDATraceMetadata,\n EDAEventTrace,\n makeEDAEventTrace,\n makeEDARunTrace,\n makeEDATraceContext,\n makeEDATraceMetadataFromParent,\n makeRootEDAEventTrace,\n makeRootEDATraceMetadata,\n} from \"../types/tracing\";\n\nexport { buildEDATraceparent, parseEDATraceparent } from \"../types/tracing\";\n\n/** Attribute value types accepted by Effect span annotations after compaction. */\nexport type EdaSpanAttributeValue = EDATraceAttributeValue | undefined;\n\n/** EDA span attribute map; undefined values are intentionally dropped before annotation. */\nexport type EdaSpanAttributes = Record<string, EdaSpanAttributeValue>;\n\nexport interface EDATracingOptions {\n readonly disableTracing?: boolean;\n readonly disableSpanPropagation?: boolean;\n readonly spanAttributes?: EdaSpanAttributes;\n readonly spanPrefix?: string;\n}\n\nexport interface EDAExportedSpanLink {\n readonly attributes: Record<string, string | number | boolean>;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly traceId: string;\n}\n\nexport interface EDAExportedSpan {\n readonly attributes: Record<string, string | number | boolean>;\n readonly endedAtMs: number;\n readonly endedAtUnixNano: string;\n readonly kind: Tracer.SpanKind;\n readonly links: ReadonlyArray<EDAExportedSpanLink>;\n readonly name: string;\n readonly outcome: \"ok\" | \"error\" | \"timeout\" | \"canceled\";\n readonly parentSpanId?: string;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly startedAtMs: number;\n readonly startedAtUnixNano: string;\n readonly statusCode: \"OK\" | \"ERROR\";\n readonly statusMessage?: string;\n readonly traceId: string;\n}\n\n/** Maximum primitive attributes copied from one native Effect span or link. */\nconst MAX_EXPORTED_SPAN_ATTRIBUTES = 256;\n\ninterface EventLike {\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n readonly type?: unknown;\n}\n\ninterface PositionedEventLike {\n readonly position?: { readonly seq?: unknown; readonly subSeq?: unknown };\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n}\n\n/** Compact undefined tracing attributes before handing them to Effect spans. */\nexport const compactSpanAttributes = (\n attributes: EdaSpanAttributes,\n): Record<string, string | number | boolean> => {\n const compacted: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n compacted[key] = value;\n }\n }\n return compacted;\n};\n\nconst compactUnknownAttributes = (\n attributes: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>,\n): Record<string, string | number | boolean> => {\n const compacted: Record<string, string | number | boolean> = {};\n try {\n if (attributes instanceof Map) {\n let count = 0;\n for (const [key, value] of attributes) {\n if (count >= MAX_EXPORTED_SPAN_ATTRIBUTES) {\n break;\n }\n count += 1;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n compacted[key] = value;\n }\n }\n return compacted;\n }\n\n const keys = Object.keys(attributes).slice(0, MAX_EXPORTED_SPAN_ATTRIBUTES);\n for (const key of keys) {\n let value: unknown;\n try {\n value = Reflect.get(attributes, key);\n } catch {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n compacted[key] = value;\n }\n }\n } catch {\n // Tracing diagnostics must not replace the operation whose span is ending.\n }\n return compacted;\n};\n\nexport const toEdaExternalSpan = (context: EDATraceContext): Tracer.ExternalSpan =>\n Tracer.externalSpan({\n traceId: context.traceId,\n spanId: context.spanId,\n sampled: context.sampled,\n });\n\nexport const edaTraceContextFromSpan = (span: Tracer.AnySpan): EDATraceContext =>\n makeEDATraceContext({\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled,\n tracestate: null,\n });\n\nexport const currentEDATraceContext: Effect.Effect<EDATraceContext, unknown> =\n Effect.currentSpan.pipe(Effect.map(edaTraceContextFromSpan));\n\nexport const currentOrRootEDAEventTrace: Effect.Effect<EDAEventTrace> = Effect.currentSpan.pipe(\n Effect.map((span) => makeEDAEventTrace(edaTraceContextFromSpan(span))),\n Effect.catch(() => Effect.sync(makeRootEDAEventTrace)),\n);\n\nexport const withEdaTraceMetadata =\n (metadata: EDATraceMetadata) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n effect.pipe(Effect.annotateSpans(metadata.attributes));\n\n/** Add EDA attributes to the currently active span. */\nexport const annotateEdaSpan = (attributes: EdaSpanAttributes): Effect.Effect<void> =>\n Effect.annotateCurrentSpan(compactSpanAttributes(attributes));\n\nconst nanosToMillis = (nanos: bigint): number => Number(nanos / 1_000_000n);\n\nconst outcomeFromExit = (exit: Exit.Exit<unknown, unknown>): EDAExportedSpan[\"outcome\"] => {\n if (Exit.isSuccess(exit)) {\n return \"ok\";\n }\n return Cause.hasInterruptsOnly(exit.cause) ? \"canceled\" : \"error\";\n};\n\nconst statusMessageFromExit = (exit: Exit.Exit<unknown, unknown>): string | undefined => {\n if (Exit.isSuccess(exit)) {\n return undefined;\n }\n const error = Cause.squash(exit.cause);\n return error instanceof Error ? error.message : String(error);\n};\n\nclass ExportingNativeSpan extends Tracer.NativeSpan {\n readonly #emit: (span: EDAExportedSpan) => void;\n\n constructor(\n options: ConstructorParameters<typeof Tracer.NativeSpan>[0],\n emit: (span: EDAExportedSpan) => void,\n ) {\n super(options);\n this.#emit = emit;\n }\n\n override end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n super.end(endTime, exit);\n // Workers can report the same clock tick for very fast operations. Such spans\n // add noise without describing execution, so keep them out of exported traces.\n if (endTime <= this.startTime) {\n return;\n }\n const parent = Option.getOrUndefined(this.parent);\n this.#emit({\n attributes: compactUnknownAttributes(this.attributes),\n endedAtMs: nanosToMillis(endTime),\n endedAtUnixNano: endTime.toString(),\n kind: this.kind,\n links: this.links.map((link) => ({\n attributes: compactUnknownAttributes(link.attributes),\n traceId: link.span.traceId,\n spanId: link.span.spanId,\n sampled: link.span.sampled,\n })),\n name: this.name,\n outcome: outcomeFromExit(exit),\n ...(parent === undefined ? {} : { parentSpanId: parent.spanId }),\n sampled: this.sampled,\n spanId: this.spanId,\n startedAtMs: nanosToMillis(this.startTime),\n startedAtUnixNano: this.startTime.toString(),\n statusCode: Exit.isSuccess(exit) ? \"OK\" : \"ERROR\",\n ...(statusMessageFromExit(exit) === undefined\n ? {}\n : { statusMessage: statusMessageFromExit(exit) }),\n traceId: this.traceId,\n });\n }\n}\n\n/** Create an Effect tracer that exports only spans with observable duration. */\nexport const makeEdaExportingTracer = (emit: (span: EDAExportedSpan) => void): Tracer.Tracer =>\n Tracer.make({\n span: (options) => new ExportingNativeSpan(options, emit),\n });\n\n/** Summarize a durable/logical event collection for span attributes. */\nexport const eventBatchAttributes = (events: ReadonlyArray<EventLike>): EdaSpanAttributes => ({\n \"eda.event.count\": events.length,\n \"eda.event.types\": eventTypeSummary(events),\n});\n\n/** Summarize a committed positioned event collection for span attributes. */\nexport const committedBatchAttributes = (\n events: ReadonlyArray<PositionedEventLike>,\n): EdaSpanAttributes => {\n const seqs = events\n .map((entry) => entry.position?.seq)\n .filter((seq): seq is number => typeof seq === \"number\");\n return {\n ...eventBatchAttributes(events),\n \"eda.seq.min\": seqs.length === 0 ? undefined : Math.min(...seqs),\n \"eda.seq.max\": seqs.length === 0 ? undefined : Math.max(...seqs),\n };\n};\n\n/** Stable, low-cardinality usage attributes for model lifecycle spans. */\nexport const usageAttributes = (usage: UsagePayload | undefined): EdaSpanAttributes => ({\n \"eda.usage.input_tokens\": usage?.inputTokens,\n \"eda.usage.cached_input_tokens\": usage?.cachedInputTokens,\n \"eda.usage.output_tokens\": usage?.outputTokens,\n \"eda.usage.text_tokens\": usage?.textTokens,\n \"eda.usage.reasoning_tokens\": usage?.reasoningTokens,\n});\n\nconst eventTypeSummary = (events: ReadonlyArray<EventLike>): string | undefined => {\n if (events.length === 0) {\n return undefined;\n }\n const seen = new Set<string>();\n for (const event of events) {\n const type = event.event?.type ?? event.type;\n if (typeof type === \"string\") {\n seen.add(type);\n }\n }\n return seen.size === 0 ? undefined : Array.from(seen).join(\",\");\n};\n"],"mappings":";;;;;;;;AAwEA,MAAM,+BAA+B;;AAarC,MAAa,yBACX,eAC8C;CAC9C,MAAM,YAAuD,CAAC;CAC9D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,UAAU,KAAA,GACZ,UAAU,OAAO;CAGrB,OAAO;AACT;AAEA,MAAM,4BACJ,eAC8C;CAC9C,MAAM,YAAuD,CAAC;CAC9D,IAAI;EACF,IAAI,sBAAsB,KAAK;GAC7B,IAAI,QAAQ;GACZ,KAAK,MAAM,CAAC,KAAK,UAAU,YAAY;IACrC,IAAI,SAAS,8BACX;IAEF,SAAS;IACT,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC7E,UAAU,OAAO;GAErB;GACA,OAAO;EACT;EAEA,MAAM,OAAO,OAAO,KAAK,UAAU,EAAE,MAAM,GAAG,4BAA4B;EAC1E,KAAK,MAAM,OAAO,MAAM;GACtB,IAAI;GACJ,IAAI;IACF,QAAQ,QAAQ,IAAI,YAAY,GAAG;GACrC,QAAQ;IACN;GACF;GACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC7E,UAAU,OAAO;EAErB;CACF,QAAQ,CAER;CACA,OAAO;AACT;AAEA,MAAa,qBAAqB,YAChC,OAAO,aAAa;CAClB,SAAS,QAAQ;CACjB,QAAQ,QAAQ;CAChB,SAAS,QAAQ;AACnB,CAAC;AAEH,MAAa,2BAA2B,SACtC,oBAAoB;CAClB,SAAS,KAAK;CACd,QAAQ,KAAK;CACb,SAAS,KAAK;CACd,YAAY;AACd,CAAC;AAEH,MAAa,yBACX,OAAO,YAAY,KAAK,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}
@@ -0,0 +1,24 @@
1
+ import { L as PositionedEvent } from "./events-Bb9-Cu-7.js";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+
6
+ //#region src/services/session-event-observer.d.ts
7
+ /**
8
+ * Outbound integration point notified synchronously after EDA publishes an event.
9
+ *
10
+ * Hosts provide this service while composing the runtime. Implementations own
11
+ * their failures and never expose host errors to the session runtime.
12
+ */
13
+ interface SessionEventObserverShape {
14
+ readonly onEvent: (event: PositionedEvent) => Effect.Effect<void>;
15
+ }
16
+ declare const SessionEventObserver_base: Context.ServiceClass<SessionEventObserver, "@effect-durable-agent/SessionEventObserver", SessionEventObserverShape>;
17
+ /** Host-provided observer for append-driven integrations such as hibernatable WebSockets. */
18
+ declare class SessionEventObserver extends SessionEventObserver_base {
19
+ static readonly Noop: Layer.Layer<SessionEventObserver, never, never>;
20
+ static readonly FromHandler: (onEvent: SessionEventObserverShape["onEvent"]) => Layer.Layer<SessionEventObserver>;
21
+ }
22
+ //#endregion
23
+ export { SessionEventObserverShape as n, SessionEventObserver as t };
24
+ //# sourceMappingURL=session-event-observer-D_aoFnQs.d.ts.map
@@ -1,11 +1,11 @@
1
1
  import { m as SequenceNumber } from "./core-CYT6DBaS.js";
2
2
  import { L as PositionedEvent } from "./events-Bb9-Cu-7.js";
3
- import { a as EDASessionStore, o as EDASessionStoreError } from "./session-store-DZZUffUy.js";
4
- import { S as ReducedState } from "./command-queues-CV7O-51r.js";
5
- import { t as DurableTranscriptMessage } from "./message-transcript-DiOPBY3l.js";
6
- import { u as LiveEventBus } from "./sink-registry-Cf79ICdW.js";
7
- import { i as EDAReducerStateSnapshot } from "./reducer-registry-CjSJBPKo.js";
8
- import { h as SessionState } from "./session-state-CjOSvWbe.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-PRYbj6dp.js";
7
+ import { a as EDAReducerStateSnapshot } from "./reducer-registry--vQFATXb.js";
8
+ import { h as SessionState } from "./session-state-BfoXKafd.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";
@@ -27,6 +27,13 @@ interface EDASessionQueryShape {
27
27
  readonly messages: () => Effect.Effect<ReadonlyArray<DurableTranscriptMessage>, EDASessionStoreError>;
28
28
  /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */
29
29
  readonly eventsAfter: (afterSeq: SequenceNumber) => Effect.Effect<Stream.Stream<PositionedEvent, EDASessionStoreError>, EDASessionStoreError, Scope.Scope>;
30
+ /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */
31
+ readonly readEventPage: (afterSeq: SequenceNumber, limit: number) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;
32
+ }
33
+ /** Bounded committed durable event page for pull-based host delivery. */
34
+ interface EDASessionEventPage {
35
+ readonly events: ReadonlyArray<PositionedEvent>;
36
+ readonly head: SequenceNumber;
30
37
  }
31
38
  declare const EDASessionQuery_base: Context.ServiceClass<EDASessionQuery, "@effect-durable-agent/EDASessionQuery", EDASessionQueryShape>;
32
39
  /** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
@@ -34,5 +41,5 @@ declare class EDASessionQuery extends EDASessionQuery_base {
34
41
  static readonly Live: Layer.Layer<EDASessionQuery, never, EDASessionStore | SessionState | LiveEventBus>;
35
42
  }
36
43
  //#endregion
37
- export { EDASessionQueryShape as n, EDASessionSnapshot as r, EDASessionQuery as t };
38
- //# sourceMappingURL=session-query-C-C4m1eq.d.ts.map
44
+ export { EDASessionSnapshot as i, EDASessionQuery as n, EDASessionQueryShape as r, EDASessionEventPage as t };
45
+ //# sourceMappingURL=session-query-_Z3Kw6jj.d.ts.map
@@ -1,16 +1,16 @@
1
1
  import { r as EDACommand } from "./commands-Ce1ec6kH.js";
2
2
  import { D as DurableEventEnvelope, F as ModelSelectionPayload, I as NonNegativeInt, L as PositionedEvent, O as EphemeralEventEnvelope } from "./events-Bb9-Cu-7.js";
3
3
  import { kt as ToolCallCreatedEvent } from "./durable-B7M6TD_0.js";
4
- import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-DZZUffUy.js";
5
- import { S as ReducedState } from "./command-queues-CV7O-51r.js";
4
+ import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-ofm8FFxs.js";
5
+ import { S as ReducedState } from "./command-queues-C8muEqeQ.js";
6
6
  import { t as IdGenerator } from "./id-generator-Ckl8_XWW.js";
7
7
  import { r as SessionContext, t as EventFactory } from "./event-factory-CLJcyymV.js";
8
8
  import { t as EDAKeepAlive } from "./keep-alive-Chl5SJxy.js";
9
- import { d as CompactionRunner } from "./compaction-zbvLREI8.js";
10
- import { s as EDASinkRegistry, u as LiveEventBus } from "./sink-registry-Cf79ICdW.js";
11
- import { i as EDAReducerStateSnapshot, n as EDAReducerRegistry } from "./reducer-registry-CjSJBPKo.js";
12
- import { r as EDAPromptProjector } from "./prompt-projector-C1IbkHr0.js";
13
- import { r as EDAToolRegistry } from "./tool-registry-B7Wona6N.js";
9
+ import { d as CompactionRunner } from "./compaction-F4HEWzuI.js";
10
+ import { s as EDASinkRegistry, u as LiveEventBus } from "./sink-registry-PRYbj6dp.js";
11
+ import { a as EDAReducerStateSnapshot, r as EDAReducerRegistry } from "./reducer-registry--vQFATXb.js";
12
+ import { r as EDAPromptProjector } from "./prompt-projector-hqPh5-NI.js";
13
+ import { r as EDAToolRegistry } from "./tool-registry-ClHdr_G5.js";
14
14
  import * as Context from "effect/Context";
15
15
  import * as Effect from "effect/Effect";
16
16
  import * as Layer from "effect/Layer";
@@ -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, IdGenerator | EventFactory | SessionContext | EDAToolRegistry>;
146
+ static readonly Live: Layer.Layer<ToolExecutor, never, EDAToolRegistry | IdGenerator | EventFactory | SessionContext>;
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, IdGenerator | EventFactory | EDAToolRegistry | LanguageModel.LanguageModel>;
294
+ static readonly Live: Layer.Layer<InferenceRunner, never, LanguageModel.LanguageModel | EDAToolRegistry | IdGenerator | EventFactory>;
295
295
  }
296
296
  //#endregion
297
297
  //#region src/services/turn-runner.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, EDAPromptProjector | EDASessionStore | LiveEventBus | EDAKeepAlive | IdGenerator | EventFactory | TurnRunner | CompactionRunner | SessionContext | EDAReducerRegistry | EDASinkRegistry>;
857
+ static readonly Live: Layer.Layer<SessionState, EDASessionStoreError, EDAKeepAlive | EDAPromptProjector | EDAReducerRegistry | EDASessionStore | IdGenerator | CompactionRunner | EventFactory | LiveEventBus | TurnRunner | SessionContext | EDASinkRegistry>;
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-CjOSvWbe.d.ts.map
861
+ //# sourceMappingURL=session-state-BfoXKafd.d.ts.map
@@ -10,7 +10,7 @@ import { n as SessionContext, t as EventFactory } from "./event-factory-tcpLgdMN
10
10
  import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
11
11
  import { EDAKeepAlive } from "./services/keep-alive.js";
12
12
  import { CompactionRunner } from "./services/compaction.js";
13
- import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-D13eUO_c.js";
13
+ import { n as EDASinkRegistry, r as LiveEventBus } from "./sink-registry-DH6uiEgP.js";
14
14
  import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
15
15
  import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
16
16
  import { EDAToolRegistry } from "./services/tool-registry.js";
@@ -2824,4 +2824,4 @@ const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag =
2824
2824
  //#endregion
2825
2825
  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
2826
 
2827
- //# sourceMappingURL=session-state-SStf0KUo.js.map
2827
+ //# sourceMappingURL=session-state-C4m0j6CJ.js.map