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

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 (77) hide show
  1. package/README.md +19 -18
  2. package/dist/{command-queues-CV7O-51r.d.ts → command-queues-Dwdf41mq.d.ts} +2 -2
  3. package/dist/{compaction-zbvLREI8.d.ts → compaction-DpHOf-g7.d.ts} +5 -5
  4. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-B4DWOZgi.d.ts} +3 -3
  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/host/websocket-protocol.d.ts +26 -3
  10. package/dist/host/websocket-protocol.js +16 -4
  11. package/dist/host/websocket-protocol.js.map +1 -1
  12. package/dist/host/websocket-wire.d.ts +2 -2
  13. package/dist/host/websocket-wire.js +19 -2
  14. package/dist/host/websocket-wire.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/{message-transcript-DiOPBY3l.d.ts → message-transcript-CFn_D3MH.d.ts} +3 -3
  17. package/dist/{prompt-projector-C1IbkHr0.d.ts → prompt-projector-C2meuNrV.d.ts} +4 -4
  18. package/dist/{reducer-registry-CjSJBPKo.d.ts → reducer-registry-K9FqZq5-.d.ts} +2 -2
  19. package/dist/{runtime-DOgmAKsO.d.ts → runtime-5NEJngu3.d.ts} +10 -5
  20. package/dist/services/compaction.d.ts +1 -1
  21. package/dist/services/prompt-projector.d.ts +1 -1
  22. package/dist/services/reducer-registry.d.ts +1 -1
  23. package/dist/services/runtime-layer.d.ts +9 -9
  24. package/dist/services/runtime-layer.js +2 -2
  25. package/dist/services/runtime.d.ts +1 -1
  26. package/dist/services/runtime.js +6 -2
  27. package/dist/services/runtime.js.map +1 -1
  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/session-store.js +1 -1
  35. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  36. package/dist/services/sink-registry.d.ts +1 -1
  37. package/dist/services/sink-registry.js +1 -1
  38. package/dist/services/span-names.d.ts +1 -1
  39. package/dist/services/span-names.js +1 -0
  40. package/dist/services/span-names.js.map +1 -1
  41. package/dist/services/tool-registry.d.ts +1 -1
  42. package/dist/services/websocket-delivery.d.ts +90 -0
  43. package/dist/services/websocket-delivery.js +221 -0
  44. package/dist/services/websocket-delivery.js.map +1 -0
  45. package/dist/{session-query-C-C4m1eq.d.ts → session-query-5oyZRaQL.d.ts} +16 -9
  46. package/dist/{session-state-CjOSvWbe.d.ts → session-state-CI1xeT6f.d.ts} +11 -11
  47. package/dist/{session-state-SStf0KUo.js → session-state-D7dqko7r.js} +3 -3
  48. package/dist/{session-state-SStf0KUo.js.map → session-state-D7dqko7r.js.map} +1 -1
  49. package/dist/{session-store-DZZUffUy.d.ts → session-store-BLg6UvZa.d.ts} +2 -2
  50. package/dist/{sink-checkpoint-store-BZmQFTRE.d.ts → sink-checkpoint-store-B9WNvDtY.d.ts} +2 -2
  51. package/dist/{sink-registry-D13eUO_c.js → sink-registry-BbmoI9uv.js} +17 -24
  52. package/dist/sink-registry-BbmoI9uv.js.map +1 -0
  53. package/dist/{sink-registry-Cf79ICdW.d.ts → sink-registry-CO3YPS1p.d.ts} +26 -14
  54. package/dist/testkit/layers.d.ts +10 -10
  55. package/dist/testkit/layers.js +3 -3
  56. package/dist/{tool-registry-B7Wona6N.d.ts → tool-registry-B8H1P6Pu.d.ts} +2 -2
  57. package/dist/{websocket-wire-QD2SquQE.d.ts → websocket-wire-DPxwY4G5.d.ts} +39 -10
  58. package/package.json +11 -23
  59. package/testing/offline-trace/README.md +2 -1
  60. package/CHANGELOG.md +0 -34
  61. package/CONTRIBUTING.md +0 -26
  62. package/SECURITY.md +0 -7
  63. package/dist/services/websocket-subscriber.d.ts +0 -54
  64. package/dist/services/websocket-subscriber.js +0 -190
  65. package/dist/services/websocket-subscriber.js.map +0 -1
  66. package/dist/sink-registry-D13eUO_c.js.map +0 -1
  67. package/docs/assets/architecture.svg +0 -216
  68. package/docs/assets/event-sequence.svg +0 -133
  69. package/docs/assets/gcp-trace.png +0 -0
  70. package/docs/assets/hero.svg +0 -33
  71. package/docs/message-steering.md +0 -831
  72. package/docs/releasing.md +0 -114
  73. package/docs/spec.md +0 -777
  74. package/docs/subagents.md +0 -725
  75. package/docs/testing.md +0 -64
  76. package/docs/ui-projection.md +0 -742
  77. package/docs/websocket-protocol.md +0 -639
@@ -1,9 +1,10 @@
1
1
  import { m as SequenceNumber, n as CommandId } from "./core-CYT6DBaS.js";
2
2
  import { r as EDACommand } from "./commands-Ce1ec6kH.js";
3
3
  import { w as CommandFailedEvent, x as CommandCompletedEvent, y as CommandCancelledEvent } from "./durable-B7M6TD_0.js";
4
- import { t as CommittedDurableEvent } from "./session-store-DZZUffUy.js";
5
- import { h as SessionState, r as SessionCommandAdmissionError, t as EDASubmittable } from "./session-state-CjOSvWbe.js";
6
- import { n as EDASessionQueryShape, t as EDASessionQuery } from "./session-query-C-C4m1eq.js";
4
+ import { t as CommittedDurableEvent } from "./session-store-BLg6UvZa.js";
5
+ import { d as LiveEventBusShape, u as LiveEventBus } from "./sink-registry-CO3YPS1p.js";
6
+ import { h as SessionState, r as SessionCommandAdmissionError, t as EDASubmittable } from "./session-state-CI1xeT6f.js";
7
+ import { n as EDASessionQuery, r as EDASessionQueryShape } from "./session-query-5oyZRaQL.js";
7
8
  import * as Context from "effect/Context";
8
9
  import * as Effect from "effect/Effect";
9
10
  import * as Layer from "effect/Layer";
@@ -50,12 +51,16 @@ interface EDARuntimeShape {
50
51
  readonly messages: EDASessionQueryShape["messages"];
51
52
  /** Backfill durable events after a committed sequence, then follow live events. */
52
53
  readonly eventsAfter: EDASessionQueryShape["eventsAfter"];
54
+ /** Read one bounded committed durable slice plus the committed head. */
55
+ readonly eventsSlice: EDASessionQueryShape["eventsSlice"];
56
+ /** Register one push-delivery listener invoked inline on every published event. */
57
+ readonly registerDeliveryListener: LiveEventBusShape["registerDeliveryListener"];
53
58
  }
54
59
  declare const EDARuntime_base: Context.ServiceClass<EDARuntime, "@effect-durable-agent/EDARuntime", EDARuntimeShape>;
55
60
  /** Top-level public facade for one effect-durable-agent session runtime. */
56
61
  declare class EDARuntime extends EDARuntime_base {
57
- static readonly Live: (config: EDARuntimeConfig) => Layer.Layer<EDARuntime, SessionCommandAdmissionError, SessionState | EDASessionQuery>;
62
+ static readonly Live: (config: EDARuntimeConfig) => Layer.Layer<EDARuntime, SessionCommandAdmissionError, SessionState | LiveEventBus | EDASessionQuery>;
58
63
  }
59
64
  //#endregion
60
65
  export { EDARuntimeError as a, EDARuntimeConfig as i, EDACommandTerminalEvent as n, EDARuntimeShape as o, EDARuntime as r, EDARuntimeSubmit as s, CommittedCommandTerminalEvent as t };
61
- //# sourceMappingURL=runtime-DOgmAKsO.d.ts.map
66
+ //# sourceMappingURL=runtime-5NEJngu3.d.ts.map
@@ -1,2 +1,2 @@
1
- import { _ as defaultCompactionRetainTailTokens, a as CompactionExecutorShape, c as CompactionPolicy, d as CompactionRunner, f as CompactionRunnerInput, g as defaultCompactionMinSummarizableTokens, h as defaultCompactionCharsPerToken, i as CompactionExecutorInput, l as CompactionPolicyInput, m as LanguageModelSummaryCompactionExecutorOptions, n as CompactionError, o as CompactionOutput, p as CompactionRunnerShape, r as CompactionExecutor, s as CompactionPlan, t as ApproximateTokenThresholdCompactionPolicyOptions, u as CompactionPolicyShape, v as defaultCompactionThresholdTokens } from "../compaction-zbvLREI8.js";
1
+ import { _ as defaultCompactionRetainTailTokens, a as CompactionExecutorShape, c as CompactionPolicy, d as CompactionRunner, f as CompactionRunnerInput, g as defaultCompactionMinSummarizableTokens, h as defaultCompactionCharsPerToken, i as CompactionExecutorInput, l as CompactionPolicyInput, m as LanguageModelSummaryCompactionExecutorOptions, n as CompactionError, o as CompactionOutput, p as CompactionRunnerShape, r as CompactionExecutor, s as CompactionPlan, t as ApproximateTokenThresholdCompactionPolicyOptions, u as CompactionPolicyShape, v as defaultCompactionThresholdTokens } from "../compaction-DpHOf-g7.js";
2
2
  export { ApproximateTokenThresholdCompactionPolicyOptions, CompactionError, CompactionExecutor, CompactionExecutorInput, CompactionExecutorShape, CompactionOutput, CompactionPlan, CompactionPolicy, CompactionPolicyInput, CompactionPolicyShape, CompactionRunner, CompactionRunnerInput, CompactionRunnerShape, LanguageModelSummaryCompactionExecutorOptions, defaultCompactionCharsPerToken, defaultCompactionMinSummarizableTokens, defaultCompactionRetainTailTokens, defaultCompactionThresholdTokens };
@@ -1,2 +1,2 @@
1
- import { a as buildEDAPrompt, i as EDAPromptProjectorShape, n as EDAPromptProjectionInput, r as EDAPromptProjector, t as EDAProjectedPromptContext } from "../prompt-projector-C1IbkHr0.js";
1
+ import { a as buildEDAPrompt, i as EDAPromptProjectorShape, n as EDAPromptProjectionInput, r as EDAPromptProjector, t as EDAProjectedPromptContext } from "../prompt-projector-C2meuNrV.js";
2
2
  export { EDAProjectedPromptContext, EDAPromptProjectionInput, EDAPromptProjector, EDAPromptProjectorShape, buildEDAPrompt };
@@ -1,2 +1,2 @@
1
- import { a as EDAReducersFor, c as defineEDAReducerRegistry, d as getEDAReducerState, f as reducerSchemaVersion, i as EDAReducerStateSnapshot, l as edaReservedReducerNamePrefix, n as EDAReducerRegistry, o as EDATypedReducerRegistry, r as EDAReducerRegistryShape, s as decodeReducerState, t as EDAReducer, u as encodeReducerState } from "../reducer-registry-CjSJBPKo.js";
1
+ import { a as EDAReducersFor, c as defineEDAReducerRegistry, d as getEDAReducerState, f as reducerSchemaVersion, i as EDAReducerStateSnapshot, l as edaReservedReducerNamePrefix, n as EDAReducerRegistry, o as EDATypedReducerRegistry, r as EDAReducerRegistryShape, s as decodeReducerState, t as EDAReducer, u as encodeReducerState } from "../reducer-registry-K9FqZq5-.js";
2
2
  export { EDAReducer, EDAReducerRegistry, EDAReducerRegistryShape, EDAReducerStateSnapshot, EDAReducersFor, EDATypedReducerRegistry, decodeReducerState, defineEDAReducerRegistry, edaReservedReducerNamePrefix, encodeReducerState, getEDAReducerState, reducerSchemaVersion };
@@ -1,14 +1,14 @@
1
1
  import { h as SessionId } from "../core-CYT6DBaS.js";
2
- import { a as EDASessionStore, o as EDASessionStoreError } from "../session-store-DZZUffUy.js";
2
+ import { a as EDASessionStore, o as EDASessionStoreError } from "../session-store-BLg6UvZa.js";
3
+ import { r as EDASink } from "../sink-registry-CO3YPS1p.js";
3
4
  import { t as EDAKeepAlive } from "../keep-alive-Chl5SJxy.js";
4
- import { c as CompactionPolicy, r as CompactionExecutor } from "../compaction-zbvLREI8.js";
5
- import { r as EDASink } from "../sink-registry-Cf79ICdW.js";
6
- import { n as EDAReducerRegistry } from "../reducer-registry-CjSJBPKo.js";
7
- import { r as EDAPromptProjector } from "../prompt-projector-C1IbkHr0.js";
8
- import { n as SinkCheckpointStore } from "../sink-checkpoint-store-BZmQFTRE.js";
9
- import { r as SessionCommandAdmissionError } from "../session-state-CjOSvWbe.js";
10
- import { i as EDAToolRegistryShape, t as EDAModelToolkit } from "../tool-registry-B7Wona6N.js";
11
- import { i as EDARuntimeConfig, r as EDARuntime } from "../runtime-DOgmAKsO.js";
5
+ import { c as CompactionPolicy, r as CompactionExecutor } from "../compaction-DpHOf-g7.js";
6
+ import { n as EDAReducerRegistry } from "../reducer-registry-K9FqZq5-.js";
7
+ import { r as EDAPromptProjector } from "../prompt-projector-C2meuNrV.js";
8
+ import { n as SinkCheckpointStore } from "../sink-checkpoint-store-B9WNvDtY.js";
9
+ import { r as SessionCommandAdmissionError } from "../session-state-CI1xeT6f.js";
10
+ import { i as EDAToolRegistryShape, t as EDAModelToolkit } from "../tool-registry-B8H1P6Pu.js";
11
+ import { i as EDARuntimeConfig, r as EDARuntime } from "../runtime-5NEJngu3.js";
12
12
  import * as Layer from "effect/Layer";
13
13
  import * as LanguageModel from "effect/unstable/ai/LanguageModel";
14
14
  import * as Tracer from "effect/Tracer";
@@ -1,9 +1,9 @@
1
- import { d as TurnRunner, f as InferenceRunner, p as ToolExecutor, u as SessionState } from "../session-state-SStf0KUo.js";
1
+ import { n as EDASinkRegistry, r as LiveEventBus } from "../sink-registry-BbmoI9uv.js";
2
+ import { d as TurnRunner, f as InferenceRunner, p as ToolExecutor, u as SessionState } from "../session-state-D7dqko7r.js";
2
3
  import { IdGenerator } from "./id-generator.js";
3
4
  import { n as SessionContext, t as EventFactory } from "../event-factory-tcpLgdMN.js";
4
5
  import { EDAKeepAlive } from "./keep-alive.js";
5
6
  import { CompactionExecutor, CompactionPolicy, CompactionRunner } from "./compaction.js";
6
- import { n as EDASinkRegistry, r as LiveEventBus } from "../sink-registry-D13eUO_c.js";
7
7
  import { EDAPromptProjector } from "./prompt-projector.js";
8
8
  import { EDAReducerRegistry } from "./reducer-registry.js";
9
9
  import { EDAToolRegistry } from "./tool-registry.js";
@@ -1,2 +1,2 @@
1
- import { a as EDARuntimeError, i as EDARuntimeConfig, n as EDACommandTerminalEvent, o as EDARuntimeShape, r as EDARuntime, s as EDARuntimeSubmit, t as CommittedCommandTerminalEvent } from "../runtime-DOgmAKsO.js";
1
+ import { a as EDARuntimeError, i as EDARuntimeConfig, n as EDACommandTerminalEvent, o as EDARuntimeShape, r as EDARuntime, s as EDARuntimeSubmit, t as CommittedCommandTerminalEvent } from "../runtime-5NEJngu3.js";
2
2
  export { CommittedCommandTerminalEvent, EDACommandTerminalEvent, EDARuntime, EDARuntimeConfig, EDARuntimeError, EDARuntimeShape, EDARuntimeSubmit };
@@ -1,6 +1,7 @@
1
1
  import { SequenceNumber, durablePosition } from "../types/core.js";
2
2
  import { _n as commandCancelledEventType, _r as SystemPromptText, fr as ModelSelectionPayload, pr as NonNegativeInt, vn as commandCompletedEventType, yn as commandFailedEventType } from "../durable-DsV9PxZC.js";
3
- import { u as SessionState } from "../session-state-SStf0KUo.js";
3
+ import { r as LiveEventBus } from "../sink-registry-BbmoI9uv.js";
4
+ import { u as SessionState } from "../session-state-D7dqko7r.js";
4
5
  import { CommittedDurableEvent } from "./session-store.js";
5
6
  import { annotateEdaSpan, committedBatchAttributes } from "./tracing.js";
6
7
  import { EDASessionQuery } from "./session-query.js";
@@ -24,6 +25,7 @@ var EDARuntime = class EDARuntime extends Context.Service()("@effect-durable-age
24
25
  const makeLiveRuntime = (config) => Effect.gen(function* () {
25
26
  const sessionState = yield* SessionState;
26
27
  const query = yield* EDASessionQuery;
28
+ const liveBus = yield* LiveEventBus;
27
29
  const runInput = {
28
30
  modelSelection: config.modelSelection,
29
31
  ...config.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: config.maxToolCallsPerRun },
@@ -63,7 +65,9 @@ const makeLiveRuntime = (config) => Effect.gen(function* () {
63
65
  }),
64
66
  snapshot: () => query.snapshot(),
65
67
  messages: () => query.messages(),
66
- eventsAfter: (afterSeq) => query.eventsAfter(afterSeq)
68
+ eventsAfter: (afterSeq) => query.eventsAfter(afterSeq),
69
+ eventsSlice: (afterSeq, limit) => query.eventsSlice(afterSeq, limit),
70
+ registerDeliveryListener: (listener) => liveBus.registerDeliveryListener(listener)
67
71
  };
68
72
  });
69
73
  const isCommandTerminalFor = (commandId) => (event) => {
@@ -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,cA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Q,KAAK,IACjC,OAAO,aAAa,YAAY,KAAK,IACrC,CAAC,OAAO,aAAa,aAAa,KAAmB,CAAC;GAC1D,OAAO,gBAAgB,yBAAyB,SAAS,CAAC;GAC1D,OAAO,MAAM,QAAQ,KAAK,IAAI,YAAY,UAAU;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 { LiveEventBus } from \"./live-event-bus\";\nimport type { LiveDeliveryListener, LiveEventBusShape } from \"./live-event-bus\";\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 committed durable slice plus the committed head. */\n readonly eventsSlice: EDASessionQueryShape[\"eventsSlice\"];\n /** Register one push-delivery listener invoked inline on every published event. */\n readonly registerDeliveryListener: LiveEventBusShape[\"registerDeliveryListener\"];\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 const liveBus = yield* LiveEventBus;\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 eventsSlice: (afterSeq: SequenceNumber, limit: number) => query.eventsSlice(afterSeq, limit),\n registerDeliveryListener: (listener: LiveDeliveryListener) =>\n liveBus.registerDeliveryListener(listener),\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":";;;;;;;;;;;;;;AAgCA,MAAa,mBAAmB,OAAO,OAAO;CAC5C,gBAAgB;;CAEhB,oBAAoB,OAAO,YAAY,cAAc;CACrD,cAAc,OAAO,YAAY,gBAAgB;AACnD,CAAC;;AAqDD,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;CACrB,MAAM,UAAU,OAAO;CAEvB,MAAM,WAAW;EACf,gBAAgB,OAAO;EACvB,GAAI,OAAO,uBAAuB,KAAA,IAC9B,CAAC,IACD,EAAE,oBAAoB,OAAO,mBAAmB;EACpD,GAAI,OAAO,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,OAAO,aAAa;CACnF;CACA,OAAO,aAAa,MAAM,QAAQ;CAElC,MAAM,iBAAiB,OAAO,GAAG,WAC/B,WACA,WAA2B,eAAe,KAAK,CAAC,GAChD;EACA,OAAO,gBAAgB;GAAE,kBAAkB;GAAW,iBAAiB;EAAS,CAAC;EACjF,OAAO,OAAO,OAAO,OACnB,OAAO,IAAI,aAAa;GAEtB,MAAM,WAAW,QAAO,OADF,MA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ACnC,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 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 EDASessionEventsSlice } from "../session-query-5oyZRaQL.js";
2
+ export { EDASessionEventsSlice, 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 { r as LiveEventBus } from "../sink-registry-BbmoI9uv.js";
3
+ import { u as SessionState } from "../session-state-D7dqko7r.js";
3
4
  import { EDASessionStore } from "./session-store.js";
4
5
  import { durableMessageTranscript } from "../domain/message-transcript.js";
5
6
  import { annotateEdaSpan } from "./tracing.js";
6
- import { r as LiveEventBus } from "../sink-registry-D13eUO_c.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
+ eventsSlice: (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.slice", { attributes: {
69
+ "eda.seq.after": afterSeq,
70
+ "eda.slice.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,EAC1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,OAAO,KAAK,IAAI,CAClB,EAAE,KAAK,OAAO,QAAQ,UAAU,oBAAoB,OAAO,UAAU,CAAC,CAAC;IACvE,OAAO,OAAO,aAAa,eAAe,EAAE,KAAK,OAAO,OAAO,MAAM,CAAC;GACxE,CAAC,EAAE,KACD,OAAO,SAAS,uBAAuB,EACrC,YAAY,EAAE,iBAAiB,SAAS,EAC1C,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
+ {"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 eventsSlice: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventsSlice, EDASessionStoreError>;\n}\n\n/** Bounded committed durable replay slice for pull-based delivery. */\nexport interface EDASessionEventsSlice {\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 eventsSlice: (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 EDASessionEventsSlice;\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 EDASessionEventsSlice;\n }).pipe(\n Effect.withSpan(\"agent.events.slice\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.slice.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,KA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OAAO;KAAE,QAAQ,CAAC;KAAG;IAAK;IAW5B,OAAO;KAAE,QAAA,OATa,MAAM,YAAY,QAAQ,EAAE,KAChD,OAAO,QAAQ,UAAU,MAAM,SAAS,OAAO,IAAI,GACnD,OAAO,KAAK,KAAK,GACjB,OAAO,KAAK,UACV,gBAAgB,KAAK;MAAE,UAAU,MAAM;MAAU,OAAO,MAAM;KAAM,CAAC,CACvE,GACA,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;KACiB;IAAK;GACxB,CAAC,EAAE,KACD,OAAO,SAAS,sBAAsB,EACpC,YAAY;IAAE,iBAAiB;IAAU,mBAAmB;GAAM,EACpE,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-CI1xeT6f.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-D7dqko7r.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-BLg6UvZa.js";
2
2
  export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError };
@@ -6,8 +6,8 @@ import * as Effect from "effect/Effect";
6
6
  import * as Layer from "effect/Layer";
7
7
  import * as Schema from "effect/Schema";
8
8
  import * as Stream from "effect/Stream";
9
- import * as Cause from "effect/Cause";
10
9
  import * as Ref from "effect/Ref";
10
+ import * as Cause from "effect/Cause";
11
11
  //#region src/services/session-store.ts
12
12
  /** A durable event after the store has assigned its replay position. */
13
13
  const CommittedDurableEvent = Schema.Struct({
@@ -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-B9WNvDtY.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-CO3YPS1p.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-BbmoI9uv.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.slice", "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.slice",
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.slice\",\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-B8H1P6Pu.js";
2
2
  export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
@@ -0,0 +1,90 @@
1
+ import { m as SequenceNumber } from "../core-CYT6DBaS.js";
2
+ import { L as PositionedEvent } from "../events-Bb9-Cu-7.js";
3
+ import { EDAWebSocketAckFrame, EDAWebSocketFlowControl, EDAWebSocketHelloFrame, EDAWebSocketServerFrame, FrameId, SubscriberId } from "../host/websocket-protocol.js";
4
+ import * as Schema from "effect/Schema";
5
+
6
+ //#region src/services/websocket-delivery.d.ts
7
+ /** Slow subscriber reasons that intentionally close only the lagging socket. */
8
+ declare const SubscriberLagReason: Schema.Literals<readonly ["buffer-overflow", "ack-timeout"]>;
9
+ type SubscriberLagReason = typeof SubscriberLagReason.Type;
10
+ /** One sent-but-unacknowledged events frame. */
11
+ interface InFlightFrame {
12
+ readonly frameId: FrameId;
13
+ readonly durableThroughSeq: SequenceNumber;
14
+ readonly sentAtMs: number;
15
+ }
16
+ /**
17
+ * In-memory delivery state for one accepted event WebSocket.
18
+ *
19
+ * This state is deliberately disposable: hibernation-capable hosts persist
20
+ * only the acknowledged durable cursor in the socket attachment and rebuild
21
+ * a cold state after isolate eviction. Nothing here owns a fiber, a timer,
22
+ * or a stream; all progress is driven by explicit host calls.
23
+ */
24
+ interface EDAWebSocketDeliveryState {
25
+ readonly subscriberId: SubscriberId;
26
+ readonly policy: EDAWebSocketFlowControl;
27
+ /**
28
+ * True when this state was rebuilt from a persisted attachment after the
29
+ * in-memory frame bookkeeping was lost. Frame-id validation is relaxed for
30
+ * the remainder of the connection because pre-eviction frame ids are
31
+ * unknowable; durable cursors stay strictly monotonic either way.
32
+ */
33
+ readonly coldRestored: boolean;
34
+ readonly lastAckedSeq: SequenceNumber;
35
+ readonly lastAckedFrameId: number;
36
+ readonly lastSentFrameId: number;
37
+ readonly nextFrameId: number;
38
+ readonly sentDurableThroughSeq: SequenceNumber;
39
+ readonly inFlight: ReadonlyArray<InFlightFrame>;
40
+ readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;
41
+ }
42
+ /** Close instruction for the host WebSocket boundary. */
43
+ interface DeliveryClose {
44
+ readonly code: number;
45
+ readonly reason: string;
46
+ }
47
+ /** Result of one pure delivery transition. */
48
+ interface EDAWebSocketDeliveryResult {
49
+ readonly state: EDAWebSocketDeliveryState;
50
+ /** Frames to send in order, including any final lagged/error frame before `close`. */
51
+ readonly frames: ReadonlyArray<EDAWebSocketServerFrame>;
52
+ /** When set, persist this acknowledged durable cursor to the socket attachment. */
53
+ readonly persistSeq?: SequenceNumber;
54
+ /** When set, send `frames` then close the socket and drop its state. */
55
+ readonly close?: DeliveryClose;
56
+ /** When set, the host should read a durable slice after this seq and call `onDurableEvents`. */
57
+ readonly wantsCatchUpAfterSeq?: SequenceNumber;
58
+ }
59
+ /** Inputs for one fresh or cold-restored delivery state. */
60
+ interface MakeDeliveryStateInput {
61
+ readonly subscriberId: SubscriberId;
62
+ readonly resumeSeq: SequenceNumber;
63
+ readonly policy: EDAWebSocketFlowControl;
64
+ readonly coldRestored?: boolean;
65
+ }
66
+ /** Build the delivery state for a new connection or a post-eviction restore. */
67
+ declare const makeWebSocketDeliveryState: (input: MakeDeliveryStateInput) => EDAWebSocketDeliveryState;
68
+ /** First frame for a freshly accepted connection. Cold restores never re-send hello. */
69
+ declare const deliveryHelloFrame: (state: EDAWebSocketDeliveryState) => EDAWebSocketHelloFrame;
70
+ /**
71
+ * Deliver committed durable events read from the store.
72
+ *
73
+ * The store is the only buffer for durable events: frames are emitted while
74
+ * the ACK window has room and the remainder is requested again via
75
+ * `wantsCatchUpAfterSeq` once ACKs reopen the window.
76
+ */
77
+ declare const onDurableEvents: (state: EDAWebSocketDeliveryState, events: ReadonlyArray<PositionedEvent>, head: SequenceNumber, nowMs: number) => EDAWebSocketDeliveryResult;
78
+ /**
79
+ * Deliver one live ephemeral event.
80
+ *
81
+ * Ephemeral events have no durable backing, so a bounded in-memory buffer
82
+ * holds them while the ACK window is full; overflow lag-closes only this
83
+ * subscriber, mirroring the previous streaming behavior.
84
+ */
85
+ declare const onEphemeralEvent: (state: EDAWebSocketDeliveryState, event: PositionedEvent, nowMs: number) => EDAWebSocketDeliveryResult;
86
+ /** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */
87
+ declare const onClientAck: (state: EDAWebSocketDeliveryState, ack: EDAWebSocketAckFrame, nowMs: number) => EDAWebSocketDeliveryResult;
88
+ //#endregion
89
+ export { DeliveryClose, EDAWebSocketDeliveryResult, EDAWebSocketDeliveryState, InFlightFrame, MakeDeliveryStateInput, SubscriberLagReason, deliveryHelloFrame, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent };
90
+ //# sourceMappingURL=websocket-delivery.d.ts.map