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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/{command-queues-C8muEqeQ.d.ts → command-queues-DdDB_aYM.d.ts} +11 -18
  2. package/dist/{compaction-F4HEWzuI.d.ts → compaction-BEor3jKv.d.ts} +27 -8
  3. package/dist/compaction-BgDr5VJy.js +473 -0
  4. package/dist/compaction-BgDr5VJy.js.map +1 -0
  5. package/dist/{context-projection-C43pyxn2.d.ts → context-projection-n6Rdup0N.d.ts} +2 -2
  6. package/dist/domain/command-queues.d.ts +1 -1
  7. package/dist/domain/context-projection.d.ts +1 -1
  8. package/dist/domain/message-transcript.d.ts +1 -1
  9. package/dist/domain/model-usage.d.ts +2 -0
  10. package/dist/domain/model-usage.js +59 -0
  11. package/dist/domain/model-usage.js.map +1 -0
  12. package/dist/domain/reduced-state-schema.d.ts +11 -17
  13. package/dist/domain/reduced-state-schema.js +6 -11
  14. package/dist/domain/reduced-state-schema.js.map +1 -1
  15. package/dist/domain/reduced-state.d.ts +3 -2
  16. package/dist/domain/reduced-state.js +3 -2
  17. package/dist/{durable-DsV9PxZC.js → durable-BGFvX7Mh.js} +17 -80
  18. package/dist/durable-BGFvX7Mh.js.map +1 -0
  19. package/dist/{durable-B7M6TD_0.d.ts → durable-br2C1bWK.d.ts} +247 -4
  20. package/dist/envelope-DkZyMIgp.d.ts +191 -0
  21. package/dist/envelope-DxQzo5rN.js +82 -0
  22. package/dist/envelope-DxQzo5rN.js.map +1 -0
  23. package/dist/{event-factory-tcpLgdMN.js → event-factory-DTFdy0Cb.js} +3 -2
  24. package/dist/{event-factory-tcpLgdMN.js.map → event-factory-DTFdy0Cb.js.map} +1 -1
  25. package/dist/{event-factory-CLJcyymV.d.ts → event-factory-pFzsPlDs.d.ts} +4 -4
  26. package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
  27. package/dist/index.d.ts +5 -4
  28. package/dist/index.js +4 -3
  29. package/dist/{message-transcript-DsKTT47f.d.ts → message-transcript-DQNlzxle.d.ts} +3 -3
  30. package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
  31. package/dist/model-usage-CdBEkTwU.d.ts +55 -0
  32. package/dist/{prompt-projector-hqPh5-NI.d.ts → prompt-projector-f4ElyXCE.d.ts} +4 -4
  33. package/dist/{reduced-state-TMi7ISla.js → reduced-state-DF0-6mbR.js} +25 -30
  34. package/dist/reduced-state-DF0-6mbR.js.map +1 -0
  35. package/dist/{reducer-registry--vQFATXb.d.ts → reducer-registry-aFjz_ZLT.d.ts} +2 -2
  36. package/dist/{runtime-BO9KJq_Y.d.ts → runtime-DbTCb32-.d.ts} +5 -5
  37. package/dist/services/compaction.d.ts +1 -1
  38. package/dist/services/compaction.js +1 -426
  39. package/dist/services/model-resolver.d.ts +2 -0
  40. package/dist/services/model-resolver.js +17 -0
  41. package/dist/services/model-resolver.js.map +1 -0
  42. package/dist/services/prompt-projector.d.ts +1 -1
  43. package/dist/services/reducer-registry.d.ts +1 -1
  44. package/dist/services/runtime-layer.d.ts +14 -14
  45. package/dist/services/runtime-layer.js +8 -7
  46. package/dist/services/runtime-layer.js.map +1 -1
  47. package/dist/services/runtime.d.ts +1 -1
  48. package/dist/services/runtime.js +3 -2
  49. package/dist/services/runtime.js.map +1 -1
  50. package/dist/services/session-event-observer.d.ts +1 -1
  51. package/dist/services/session-query.d.ts +1 -1
  52. package/dist/services/session-query.js +3 -3
  53. package/dist/services/session-state.d.ts +1 -1
  54. package/dist/services/session-state.js +1 -1
  55. package/dist/services/session-store.d.ts +1 -1
  56. package/dist/services/session-store.js +2 -1
  57. package/dist/services/session-store.js.map +1 -1
  58. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  59. package/dist/services/sink-registry.d.ts +1 -1
  60. package/dist/services/sink-registry.js +1 -1
  61. package/dist/services/tool-registry.d.ts +1 -1
  62. package/dist/services/tracing.d.ts +1 -1
  63. package/dist/{session-event-observer-D_aoFnQs.d.ts → session-event-observer-DaFMKKNc.d.ts} +2 -2
  64. package/dist/{session-query-_Z3Kw6jj.d.ts → session-query-l8xpJYp8.d.ts} +8 -8
  65. package/dist/{session-state-BfoXKafd.d.ts → session-state-YHFzOGDf.d.ts} +16 -16
  66. package/dist/{session-state-C4m0j6CJ.js → session-state-aIqe9CLa.js} +30 -39
  67. package/dist/session-state-aIqe9CLa.js.map +1 -0
  68. package/dist/{session-store-ofm8FFxs.d.ts → session-store-Cpi_NwTR.d.ts} +3 -3
  69. package/dist/{sink-checkpoint-store-BQVbI9DQ.d.ts → sink-checkpoint-store-M7qIxoSH.d.ts} +2 -2
  70. package/dist/{sink-registry-DH6uiEgP.js → sink-registry-NDgeyzO0.js} +4 -4
  71. package/dist/{sink-registry-DH6uiEgP.js.map → sink-registry-NDgeyzO0.js.map} +1 -1
  72. package/dist/{sink-registry-PRYbj6dp.d.ts → sink-registry-T1wOUuzq.d.ts} +9 -9
  73. package/dist/testkit/layers.d.ts +17 -14
  74. package/dist/testkit/layers.js +10 -8
  75. package/dist/testkit/layers.js.map +1 -1
  76. package/dist/{tool-registry-ClHdr_G5.d.ts → tool-registry-BJaVNtw4.d.ts} +3 -3
  77. package/dist/types/events/durable.d.ts +2 -2
  78. package/dist/types/events/durable.js +2 -2
  79. package/dist/types/events.d.ts +4 -3
  80. package/dist/types/events.js +3 -2
  81. package/dist/types/events.js.map +1 -1
  82. package/dist/websocket.d.ts +83 -4
  83. package/dist/websocket.js +82 -12
  84. package/dist/websocket.js.map +1 -1
  85. package/package.json +10 -1
  86. package/dist/durable-DsV9PxZC.js.map +0 -1
  87. package/dist/reduced-state-TMi7ISla.js.map +0 -1
  88. package/dist/services/compaction.js.map +0 -1
  89. package/dist/session-state-C4m0j6CJ.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"websocket.js","names":[],"sources":["../src/websocket/protocol.ts","../src/websocket/messages.ts","../src/websocket/delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { Position } from \"../types/core\";\nimport { EDADurableEvent, EDAEphemeralEvent, EventEnvelope } from \"../types/events\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** Current EDA live-event WebSocket wire protocol version. */\nexport const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1 as const;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketWireFlowControl = Schema.Struct({\n ackTimeoutMs: PositiveInt,\n /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */\n heartbeatIntervalMs: PositiveInt,\n maxFrameBytes: PositiveInt,\n maxFrameEvents: PositiveInt,\n maxInFlightFrames: PositiveInt,\n /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */\n pingIntervalMs: Schema.optionalKey(PositiveInt),\n subscriberBufferCapacityEvents: PositiveInt,\n});\nexport type EDAWebSocketWireFlowControl = typeof EDAWebSocketWireFlowControl.Type;\n\n/**\n * Canonical client liveness ping message.\n *\n * The exact string matters: hibernation-capable hosts register it with\n * WebSocket auto-response so the runtime answers without waking the object.\n */\nexport const EDA_WEB_SOCKET_PING_MESSAGE = '{\"_tag\":\"ping\"}';\n\n/** Canonical server pong message paired with {@link EDA_WEB_SOCKET_PING_MESSAGE}. */\nexport const EDA_WEB_SOCKET_PONG_MESSAGE = '{\"_tag\":\"pong\"}';\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketWirePingFrame = Schema.Struct({\n _tag: Schema.Literal(\"ping\"),\n});\nexport type EDAWebSocketWirePingFrame = typeof EDAWebSocketWirePingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketWirePongFrame = Schema.Struct({\n _tag: Schema.Literal(\"pong\"),\n});\nexport type EDAWebSocketWirePongFrame = typeof EDAWebSocketWirePongFrame.Type;\n\nexport const EDAWebSocketWireHelloFrame = Schema.Struct({\n _tag: Schema.Literal(\"hello\"),\n protocolVersion: Schema.Literal(EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION),\n subscriberId: Schema.NonEmptyString,\n resumeSeq: NonNegativeInt,\n flowControl: EDAWebSocketWireFlowControl,\n});\nexport type EDAWebSocketWireHelloFrame = typeof EDAWebSocketWireHelloFrame.Type;\n\nexport const EDAWebSocketWireHeartbeatFrame = Schema.Struct({\n _tag: Schema.Literal(\"heartbeat\"),\n serverTimeMs: NonNegativeInt,\n durableThroughSeq: NonNegativeInt,\n});\nexport type EDAWebSocketWireHeartbeatFrame = typeof EDAWebSocketWireHeartbeatFrame.Type;\n\nexport const EDAWebSocketWireLaggedFrame = Schema.Struct({\n _tag: Schema.Literal(\"lagged\"),\n resumeSeq: NonNegativeInt,\n reason: Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]),\n});\nexport type EDAWebSocketWireLaggedFrame = typeof EDAWebSocketWireLaggedFrame.Type;\n\nexport const EDAWebSocketWireErrorFrame = Schema.Struct({\n _tag: Schema.Literal(\"error\"),\n message: Schema.String,\n});\nexport type EDAWebSocketWireErrorFrame = typeof EDAWebSocketWireErrorFrame.Type;\n\nexport const EDAWebSocketWireAckFrame = Schema.Struct({\n _tag: Schema.Literal(\"ack\"),\n frameId: PositiveInt,\n durableThroughSeq: NonNegativeInt,\n});\nexport type EDAWebSocketWireAckFrame = typeof EDAWebSocketWireAckFrame.Type;\n\nexport const EDAWebSocketWireClientFrame = Schema.Union([\n EDAWebSocketWireAckFrame,\n EDAWebSocketWirePingFrame,\n]);\nexport type EDAWebSocketWireClientFrame = typeof EDAWebSocketWireClientFrame.Type;\n\n/** Exhaustive decision table for a concrete WebSocket event union. */\nexport type EDAWebSocketEventConsumerPolicy<\n Event extends { readonly type: string },\n Disposition,\n> = Readonly<Record<Event[\"type\"], Disposition>>;\n\n/** Complete framework-owned event union present on every EDA WebSocket. */\nexport const EDAFrameworkWebSocketEvent = Schema.Union([EDADurableEvent, EDAEphemeralEvent]);\nexport type EDAFrameworkWebSocketEvent = typeof EDAFrameworkWebSocketEvent.Type;\n\nconst makeEDAWebSocketDomainSchemas = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n) => {\n const positionedEvent = Schema.Struct({\n position: Position,\n event,\n });\n const eventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: PositiveInt,\n events: Schema.NonEmptyArray(positionedEvent),\n durableThroughSeq: NonNegativeInt,\n });\n const serverFrame = Schema.Union([\n EDAWebSocketWireHelloFrame,\n eventsFrame,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWirePongFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWireErrorFrame,\n ]);\n return { event, positionedEvent, eventsFrame, serverFrame };\n};\n\ntype EDAWebSocketDomainSchemas<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> = ReturnType<typeof makeEDAWebSocketDomainSchemas<EventSchema>>;\n\nconst EDAWebSocketHostDomain = makeEDAWebSocketDomainSchemas(EventEnvelope);\n\n/** Domain frame shape accepted by an app-bound encoder at the EDA host boundary. */\nexport type EDAWebSocketServerFrameInput = typeof EDAWebSocketHostDomain.serverFrame.Type;\n\n/** Minimal typed encoder surface consumed by an EDA host. */\nexport interface EDAWebSocketServerFrameEncoder {\n readonly encodeServerFrame: (frame: EDAWebSocketServerFrameInput) => string;\n}\n\n/** App-bound domain schemas, wire schemas, and encoders for protocol version 1. */\nexport interface EDAWebSocketWireProtocol<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> {\n /** Exact app-bound schemas whose `Type` values are used inside the server. */\n readonly domain: EDAWebSocketDomainSchemas<EventSchema>;\n /** Exact app-bound schemas whose `Type` values are the serialized JSON representation. */\n readonly wire: {\n readonly event: Schema.toEncoded<EventSchema>;\n readonly positionedEvent: Schema.toEncoded<\n EDAWebSocketDomainSchemas<EventSchema>[\"positionedEvent\"]\n >;\n readonly eventsFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"eventsFrame\"]>;\n readonly serverFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>;\n readonly clientFrame: typeof EDAWebSocketWireClientFrame;\n };\n /** Serialize one exact app-bound domain frame to a JSON text message. */\n readonly encodeServerFrame: (\n frame: Schema.Schema.Type<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>,\n ) => string;\n /** Validate broad host frames against the app event union before serialization. */\n readonly host: EDAWebSocketServerFrameEncoder;\n}\n\nconst makeEDAWebSocketWireProtocolFromEventSchema = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n): EDAWebSocketWireProtocol<EventSchema> => {\n const domain = makeEDAWebSocketDomainSchemas(event);\n const encodeDomainServerFrame = Schema.encodeSync(domain.serverFrame);\n const encodeUnknownDomainServerFrame = Schema.encodeUnknownSync(domain.serverFrame);\n const encodeServerFrame = (frame: typeof domain.serverFrame.Type): string =>\n JSON.stringify(encodeDomainServerFrame(frame));\n const host: EDAWebSocketServerFrameEncoder = {\n encodeServerFrame: (frame) => JSON.stringify(encodeUnknownDomainServerFrame(frame)),\n };\n\n return {\n domain,\n wire: {\n event: Schema.toEncoded(domain.event),\n positionedEvent: Schema.toEncoded(domain.positionedEvent),\n eventsFrame: Schema.toEncoded(domain.eventsFrame),\n serverFrame: Schema.toEncoded(domain.serverFrame),\n clientFrame: EDAWebSocketWireClientFrame,\n },\n encodeServerFrame,\n host,\n };\n};\n\n/** Strict framework-only protocol used when an app registers no custom events. */\nexport const edaFrameworkWebSocketWireProtocol: EDAWebSocketWireProtocol<\n typeof EDAFrameworkWebSocketEvent\n> = makeEDAWebSocketWireProtocolFromEventSchema(EDAFrameworkWebSocketEvent);\n\n/**\n * Bind the generic EDA WebSocket transport to one app's custom event schema.\n *\n * Framework durable and ephemeral events are included automatically. Future EDA\n * apps register only their custom events. Servers use the returned domain schemas\n * and typed encoder; external consumers decode with the wire schemas. Pass the\n * returned `host` adapter to the selected host package.\n */\nexport const makeEDAWebSocketWireProtocol = <\n AppEventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(options: {\n readonly appEvents: AppEventSchema;\n}): EDAWebSocketWireProtocol<\n Schema.Union<readonly [typeof EDAFrameworkWebSocketEvent, AppEventSchema]>\n> =>\n makeEDAWebSocketWireProtocolFromEventSchema(\n Schema.Union([EDAFrameworkWebSocketEvent, options.appEvents]),\n );\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport {\n EDA_WEB_SOCKET_PING_MESSAGE,\n EDA_WEB_SOCKET_PONG_MESSAGE,\n EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION,\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireClientFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireFlowControl,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWirePingFrame,\n EDAWebSocketWirePongFrame,\n edaFrameworkWebSocketWireProtocol,\n type EDAWebSocketServerFrameEncoder,\n} from \"./protocol\";\n\nexport { EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE };\n\nimport { SequenceNumber } from \"../types/core\";\nimport { PositionedEvent, UnixEpochMillis } from \"../types/events\";\n\n/** Current EDA live-event WebSocket protocol version. */\nexport const EDA_WEB_SOCKET_PROTOCOL_VERSION = EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION;\n\n/** WebSocket close code used when a subscriber cannot keep up with live delivery. */\nexport const EDA_WS_CLOSE_LAGGED = 4008;\n\n/** WebSocket close code used for normal host-driven shutdown. */\nexport const EDA_WS_CLOSE_GOING_AWAY = 1001;\n\n/** WebSocket close code used for malformed client protocol messages. */\nexport const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;\n\n/** WebSocket close code used when the host cannot send a frame. */\nexport const EDA_WS_CLOSE_SEND_FAILED = 1011;\n\n/** WebSocket close code used for unsupported binary messages. */\nexport const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;\n\n/** Live subscriber identity persisted in WebSocket attachments. */\nexport const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand(\"SubscriberId\"));\nexport type SubscriberId = typeof SubscriberId.Type;\n\n/** Per-connection monotonically increasing server frame id. */\nexport const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(\n Schema.brand(\"FrameId\"),\n);\nexport type FrameId = typeof FrameId.Type;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;\nexport type EDAWebSocketFlowControl = typeof EDAWebSocketFlowControl.Type;\n\n/** Default bounded policy sized for fast model deltas and large durable tool/message events. */\nexport const defaultEDAWebSocketFlowControl: EDAWebSocketFlowControl = {\n ackTimeoutMs: 30_000,\n // Deprecated wire-compat field: servers no longer schedule or send heartbeats.\n heartbeatIntervalMs: 10_000,\n maxFrameBytes: 256 * 1024,\n maxFrameEvents: 1,\n maxInFlightFrames: 16,\n pingIntervalMs: 30_000,\n subscriberBufferCapacityEvents: 2_048,\n};\n\n/** First server frame; announces protocol and flow-control policy. */\nexport const EDAWebSocketHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n subscriberId: SubscriberId,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketHelloFrame = typeof EDAWebSocketHelloFrame.Type;\n\n/** Ordered positioned events delivered to the client. */\nexport const EDAWebSocketEventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: FrameId,\n events: Schema.NonEmptyArray(PositionedEvent),\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketEventsFrame = typeof EDAWebSocketEventsFrame.Type;\n\n/**\n * Deprecated idle server keepalive frame.\n *\n * Servers no longer send heartbeats; the schema remains so deployed clients\n * keep decoding the server frame union. Liveness is client-originated via\n * {@link EDAWebSocketPingFrame} and the host-level auto-response pong.\n */\nexport const EDAWebSocketHeartbeatFrame = Schema.Struct({\n ...EDAWebSocketWireHeartbeatFrame.fields,\n serverTimeMs: UnixEpochMillis,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketHeartbeatFrame = typeof EDAWebSocketHeartbeatFrame.Type;\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketPingFrame = EDAWebSocketWirePingFrame;\nexport type EDAWebSocketPingFrame = typeof EDAWebSocketPingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketPongFrame = EDAWebSocketWirePongFrame;\nexport type EDAWebSocketPongFrame = typeof EDAWebSocketPongFrame.Type;\n\n/** Optional final frame sent before a lag-close. */\nexport const EDAWebSocketLaggedFrame = Schema.Struct({\n ...EDAWebSocketWireLaggedFrame.fields,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketLaggedFrame = typeof EDAWebSocketLaggedFrame.Type;\n\n/** Optional final frame sent before a protocol/internal close. */\nexport const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;\nexport type EDAWebSocketErrorFrame = typeof EDAWebSocketErrorFrame.Type;\n\n/** Server-to-client application frame union. */\nexport const EDAWebSocketServerFrame = Schema.Union([\n EDAWebSocketHelloFrame,\n EDAWebSocketEventsFrame,\n EDAWebSocketHeartbeatFrame,\n EDAWebSocketPongFrame,\n EDAWebSocketLaggedFrame,\n EDAWebSocketErrorFrame,\n]);\nexport type EDAWebSocketServerFrame = typeof EDAWebSocketServerFrame.Type;\n\n/** Client acknowledgement after applying a server frame. */\nexport const EDAWebSocketAckFrame = Schema.Struct({\n ...EDAWebSocketWireAckFrame.fields,\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketAckFrame = typeof EDAWebSocketAckFrame.Type;\n\n/** Client-to-server application frame union. */\nexport const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame, EDAWebSocketPingFrame]);\nexport type EDAWebSocketClientFrame = typeof EDAWebSocketClientFrame.Type;\n\n/** Serialize a server frame for a text WebSocket message. */\nexport const encodeEDAWebSocketServerFrame = (\n frame: EDAWebSocketServerFrame,\n protocol?: EDAWebSocketServerFrameEncoder,\n): string => (protocol ?? edaFrameworkWebSocketWireProtocol.host).encodeServerFrame(frame);\n\n/** Decode an inbound text WebSocket message at the host boundary. */\nexport const decodeEDAWebSocketClientMessage = (\n input: string,\n): Effect.Effect<EDAWebSocketClientFrame, unknown> =>\n Effect.try({\n try: () => JSON.parse(input) as unknown,\n catch: (error) => error,\n }).pipe(\n Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)),\n Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)),\n );\n\n/** Short close reason that fits the WebSocket protocol reason limit. */\nexport const laggedCloseReason = (seq: SequenceNumber): string => `lag;seq=${seq}`;\n","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDA_WS_CLOSE_LAGGED,\n EDA_WS_CLOSE_PROTOCOL_ERROR,\n EDAWebSocketEventsFrame,\n EDAWebSocketErrorFrame,\n EDAWebSocketHelloFrame,\n EDAWebSocketLaggedFrame,\n FrameId,\n SubscriberId,\n laggedCloseReason,\n type EDAWebSocketAckFrame,\n type EDAWebSocketFlowControl,\n type EDAWebSocketServerFrame,\n} from \"./messages\";\n\n/** Slow subscriber reasons that intentionally close only the lagging socket. */\nexport const SubscriberLagReason = Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]);\nexport type SubscriberLagReason = typeof SubscriberLagReason.Type;\n\n/** One sent-but-unacknowledged events frame. */\nexport const EDAWebSocketInFlightFrame = Schema.Struct({\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n sentAtMs: Schema.Number,\n});\nexport type EDAWebSocketInFlightFrame = typeof EDAWebSocketInFlightFrame.Type;\n\n/** Complete delivery bookkeeping persisted in the WebSocket attachment. */\nexport const EDAWebSocketDeliveryCheckpoint = Schema.Struct({\n lastAckedSeq: SequenceNumber,\n lastAckedFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lastSentFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n nextFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n sentDurableThroughSeq: SequenceNumber,\n inFlight: Schema.Array(EDAWebSocketInFlightFrame),\n});\nexport type EDAWebSocketDeliveryCheckpoint = typeof EDAWebSocketDeliveryCheckpoint.Type;\n\n/** In-memory delivery state for one accepted event WebSocket. */\nexport interface EDAWebSocketDeliveryState extends EDAWebSocketDeliveryCheckpoint {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n /** Ephemeral events are live-only and intentionally absent from the attachment. */\n readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;\n}\n\n/** Explicit instructions emitted by the pure delivery state machine. */\nexport type EDAWebSocketDeliveryAction =\n | { readonly _tag: \"Persist\" }\n | { readonly _tag: \"Send\"; readonly frames: ReadonlyArray<EDAWebSocketServerFrame> }\n | { readonly _tag: \"ReadEventPage\"; readonly afterSeq: SequenceNumber }\n | { readonly _tag: \"Close\"; readonly code: number; readonly reason: string };\n\n/** Result of one pure delivery transition. */\nexport interface EDAWebSocketDeliveryResult {\n readonly state: EDAWebSocketDeliveryState;\n readonly actions: ReadonlyArray<EDAWebSocketDeliveryAction>;\n}\n\nexport interface MakeDeliveryStateInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n}\n\n/** Build delivery state for a newly accepted connection. */\nexport const makeWebSocketDeliveryState = (\n input: MakeDeliveryStateInput,\n): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n lastAckedSeq: input.resumeSeq,\n lastAckedFrameId: 0,\n lastSentFrameId: 0,\n nextFrameId: 1,\n sentDurableThroughSeq: input.resumeSeq,\n inFlight: [],\n pendingEphemeral: [],\n});\n\n/** Rebuild exact ACK bookkeeping from a hibernating WebSocket attachment. */\nexport const restoreWebSocketDeliveryState = (input: {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n readonly checkpoint: EDAWebSocketDeliveryCheckpoint;\n}): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n ...input.checkpoint,\n pendingEphemeral: [],\n});\n\n/** Project in-memory delivery state into the attachment-safe checkpoint. */\nexport const checkpointWebSocketDeliveryState = (\n state: EDAWebSocketDeliveryState,\n): EDAWebSocketDeliveryCheckpoint => ({\n lastAckedSeq: state.lastAckedSeq,\n lastAckedFrameId: state.lastAckedFrameId,\n lastSentFrameId: state.lastSentFrameId,\n nextFrameId: state.nextFrameId,\n sentDurableThroughSeq: state.sentDurableThroughSeq,\n inFlight: state.inFlight,\n});\n\n/** First frame for a freshly accepted connection. Restores never re-send hello. */\nexport const deliveryHelloFrame = (state: EDAWebSocketDeliveryState): EDAWebSocketHelloFrame =>\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: state.subscriberId,\n resumeSeq: state.lastAckedSeq,\n flowControl: state.policy,\n });\n\n/** Deliver committed durable events read from the store. */\nexport const onDurableEvents = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n head: SequenceNumber,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n let batch: PositionedEvent[] = [];\n\n const flushBatch = (): void => {\n if (batch.length === 0) return;\n const sent = sendEventsFrame(next, batch, nowMs);\n next = sent.state;\n frames.push(sent.frame);\n batch = [];\n };\n\n for (const event of events) {\n if (event.event.durability === \"durable\" && event.position.seq <= next.sentDurableThroughSeq) {\n continue;\n }\n if (batch.length === 0 && windowCapacity(next) <= 0) break;\n batch.push(event);\n if (batch.length >= next.policy.maxFrameEvents) flushBatch();\n }\n flushBatch();\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.sentDurableThroughSeq < head\n ? next.sentDurableThroughSeq\n : undefined,\n );\n};\n\n/** Deliver one live ephemeral event, buffering only while this isolate is active. */\nexport const onEphemeralEvent = (\n state: EDAWebSocketDeliveryState,\n event: PositionedEvent,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {\n const sent = sendEventsFrame(state, [event], nowMs);\n return sentResult(sent.state, [sent.frame]);\n }\n\n const pendingEphemeral = [...state.pendingEphemeral, event];\n if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) {\n return laggedResult(state, \"buffer-overflow\");\n }\n return { state: { ...state, pendingEphemeral }, actions: [] };\n};\n\n/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */\nexport const onClientAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const validated = applyAck(state, ack);\n if (validated._tag === \"close\") return validated.result;\n if (validated._tag === \"ignore\") return { state, actions: [] };\n\n let next = validated.state;\n const frames: EDAWebSocketServerFrame[] = [];\n while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {\n const [head, ...rest] = next.pendingEphemeral;\n if (head === undefined) break;\n const sent = sendEventsFrame({ ...next, pendingEphemeral: rest }, [head], nowMs);\n next = sent.state;\n frames.push(sent.frame);\n }\n\n const stale = staleAckResult(next, nowMs);\n if (stale !== undefined) return stale;\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.pendingEphemeral.length === 0\n ? next.sentDurableThroughSeq\n : undefined,\n true,\n );\n};\n\ntype AckValidation =\n | { readonly _tag: \"ignore\" }\n | { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult }\n | { readonly _tag: \"apply\"; readonly state: EDAWebSocketDeliveryState };\n\nconst applyAck = (state: EDAWebSocketDeliveryState, ack: EDAWebSocketAckFrame): AckValidation => {\n if (ack.frameId <= state.lastAckedFrameId) {\n return ack.durableThroughSeq > state.lastAckedSeq\n ? protocolClose(state, \"Duplicate ACK attempted to advance durable seq\")\n : { _tag: \"ignore\" };\n }\n if (ack.frameId > state.lastSentFrameId) {\n return protocolClose(state, \"ACK referenced an unsent frame\");\n }\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return protocolClose(state, \"ACK durable seq moved backwards\");\n }\n const acknowledged = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledged.length === 0) {\n return protocolClose(state, \"ACK referenced no in-flight frames\");\n }\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, frame) => Math.max(max, frame.durableThroughSeq),\n state.lastAckedSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n return protocolClose(state, \"ACK durable seq exceeded sent frame boundary\");\n }\n return {\n _tag: \"apply\",\n state: {\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: ack.frameId,\n lastAckedSeq: ack.durableThroughSeq,\n },\n };\n};\n\nconst windowCapacity = (state: EDAWebSocketDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\nconst sendEventsFrame = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n nowMs: number,\n): { readonly state: EDAWebSocketDeliveryState; readonly frame: EDAWebSocketEventsFrame } => {\n const [first, ...rest] = events;\n if (first === undefined) throw new Error(\"Cannot send an empty events frame\");\n const frameId = FrameId.make(state.nextFrameId);\n const durableThroughSeq = SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n state.sentDurableThroughSeq,\n ),\n );\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: [first, ...rest],\n durableThroughSeq,\n });\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, { frameId, durableThroughSeq, sentAtMs: nowMs }],\n lastSentFrameId: frameId,\n nextFrameId: frameId + 1,\n sentDurableThroughSeq: durableThroughSeq,\n },\n frame,\n };\n};\n\nconst sentResult = (\n state: EDAWebSocketDeliveryState,\n frames: ReadonlyArray<EDAWebSocketServerFrame>,\n catchUpAfterSeq?: SequenceNumber,\n stateChanged = frames.length > 0,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n ...(stateChanged ? ([{ _tag: \"Persist\" }] as const) : []),\n ...(frames.length > 0 ? ([{ _tag: \"Send\", frames }] as const) : []),\n ...(catchUpAfterSeq === undefined\n ? []\n : ([{ _tag: \"ReadEventPage\", afterSeq: catchUpAfterSeq }] as const)),\n ],\n});\n\n/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */\nconst staleAckResult = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult | undefined =>\n state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs)\n ? laggedResult(state, \"ack-timeout\")\n : undefined;\n\nconst laggedResult = (\n state: EDAWebSocketDeliveryState,\n reason: SubscriberLagReason,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [\n EDAWebSocketLaggedFrame.make({\n _tag: \"lagged\",\n resumeSeq: state.lastAckedSeq,\n reason,\n }),\n ],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_LAGGED, reason: laggedCloseReason(state.lastAckedSeq) },\n ],\n});\n\nconst protocolClose = (\n state: EDAWebSocketDeliveryState,\n message: string,\n): { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult } => ({\n _tag: \"close\",\n result: {\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [EDAWebSocketErrorFrame.make({ _tag: \"error\", message: message.slice(0, 120) })],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_PROTOCOL_ERROR, reason: \"protocol\" },\n ],\n },\n});\n"],"mappings":";;;;;;AAKA,MAAM,cAAc,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAC5D,MAAM,iBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;;AAGxE,MAAa,uCAAuC;;AAGpD,MAAa,8BAA8B,OAAO,OAAO;CACvD,cAAc;;CAEd,qBAAqB;CACrB,eAAe;CACf,gBAAgB;CAChB,mBAAmB;;CAEnB,gBAAgB,OAAO,YAAY,WAAW;CAC9C,gCAAgC;AAClC,CAAC;;;;;;;AASD,MAAa,8BAA8B;;AAG3C,MAAa,8BAA8B;;AAG3C,MAAa,4BAA4B,OAAO,OAAO,EACrD,MAAM,OAAO,QAAQ,MAAM,EAC7B,CAAC;;AAID,MAAa,4BAA4B,OAAO,OAAO,EACrD,MAAM,OAAO,QAAQ,MAAM,EAC7B,CAAC;AAGD,MAAa,6BAA6B,OAAO,OAAO;CACtD,MAAM,OAAO,QAAQ,OAAO;CAC5B,iBAAiB,OAAO,QAAA,CAA4C;CACpE,cAAc,OAAO;CACrB,WAAW;CACX,aAAa;AACf,CAAC;AAGD,MAAa,iCAAiC,OAAO,OAAO;CAC1D,MAAM,OAAO,QAAQ,WAAW;CAChC,cAAc;CACd,mBAAmB;AACrB,CAAC;AAGD,MAAa,8BAA8B,OAAO,OAAO;CACvD,MAAM,OAAO,QAAQ,QAAQ;CAC7B,WAAW;CACX,QAAQ,OAAO,SAAS,CAAC,mBAAmB,aAAa,CAAC;AAC5D,CAAC;AAGD,MAAa,6BAA6B,OAAO,OAAO;CACtD,MAAM,OAAO,QAAQ,OAAO;CAC5B,SAAS,OAAO;AAClB,CAAC;A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K,IAC9E,aAAa,OAAO,aAAa,IACjC,KAAA;AAEN,MAAM,gBACJ,OACA,YACgC;CAChC;CACA,SAAS,CACP;EACE,MAAM;EACN,QAAQ,CACN,wBAAwB,KAAK;GAC3B,MAAM;GACN,WAAW,MAAM;GACjB;EACF,CAAC,CACH;CACF,GACA;EAAE,MAAM;EAAS,MAAM;EAAqB,QAAQ,kBAAkB,MAAM,YAAY;CAAE,CAC5F;AACF;AAEA,MAAM,iBACJ,OACA,aAC6E;CAC7E,MAAM;CACN,QAAQ;EACN;EACA,SAAS,CACP;GACE,MAAM;GACN,QAAQ,CAAC,uBAAuB,KAAK;IAAE,MAAM;IAAS,SAAS,QAAQ,MAAM,GAAG,GAAG;GAAE,CAAC,CAAC;EACzF,GACA;GAAE,MAAM;GAAS,MAAM;GAA6B,QAAQ;EAAW,CACzE;CACF;AACF"}
1
+ {"version":3,"file":"websocket.js","names":[],"sources":["../src/websocket/protocol.ts","../src/websocket/messages.ts","../src/websocket/delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { Position } from \"../types/core\";\nimport { EDADurableEvent, EDAEphemeralEvent, EventEnvelope } from \"../types/events\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** Current EDA live-event WebSocket wire protocol version. */\nexport const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1 as const;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketWireFlowControl = Schema.Struct({\n ackTimeoutMs: PositiveInt,\n /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */\n heartbeatIntervalMs: PositiveInt,\n maxFrameBytes: PositiveInt,\n maxFrameEvents: PositiveInt,\n maxInFlightFrames: PositiveInt,\n /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */\n pingIntervalMs: Schema.optionalKey(PositiveInt),\n subscriberBufferCapacityEvents: PositiveInt,\n});\nexport type EDAWebSocketWireFlowControl = typeof EDAWebSocketWireFlowControl.Type;\n\n/**\n * Canonical client liveness ping message.\n *\n * The exact string matters: hibernation-capable hosts register it with\n * WebSocket auto-response so the runtime answers without waking the object.\n */\nexport const EDA_WEB_SOCKET_PING_MESSAGE = '{\"_tag\":\"ping\"}';\n\n/** Canonical server pong message paired with {@link EDA_WEB_SOCKET_PING_MESSAGE}. */\nexport const EDA_WEB_SOCKET_PONG_MESSAGE = '{\"_tag\":\"pong\"}';\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketWirePingFrame = Schema.Struct({\n _tag: Schema.Literal(\"ping\"),\n});\nexport type EDAWebSocketWirePingFrame = typeof EDAWebSocketWirePingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketWirePongFrame = Schema.Struct({\n _tag: Schema.Literal(\"pong\"),\n});\nexport type EDAWebSocketWirePongFrame = typeof EDAWebSocketWirePongFrame.Type;\n\nexport const EDAWebSocketWireHelloFrame = Schema.Struct({\n _tag: Schema.Literal(\"hello\"),\n protocolVersion: Schema.Literal(EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION),\n subscriberId: Schema.NonEmptyString,\n resumeSeq: NonNegativeInt,\n flowControl: EDAWebSocketWireFlowControl,\n});\nexport type EDAWebSocketWireHelloFrame = typeof EDAWebSocketWireHelloFrame.Type;\n\nexport const EDAWebSocketWireHeartbeatFrame = Schema.Struct({\n _tag: Schema.Literal(\"heartbeat\"),\n serverTimeMs: NonNegativeInt,\n durableThroughSeq: NonNegativeInt,\n});\nexport type EDAWebSocketWireHeartbeatFrame = typeof EDAWebSocketWireHeartbeatFrame.Type;\n\nexport const EDAWebSocketWireLaggedFrame = Schema.Struct({\n _tag: Schema.Literal(\"lagged\"),\n resumeSeq: NonNegativeInt,\n reason: Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]),\n});\nexport type EDAWebSocketWireLaggedFrame = typeof EDAWebSocketWireLaggedFrame.Type;\n\nexport const EDAWebSocketWireErrorFrame = Schema.Struct({\n _tag: Schema.Literal(\"error\"),\n message: Schema.String,\n});\nexport type EDAWebSocketWireErrorFrame = typeof EDAWebSocketWireErrorFrame.Type;\n\nexport const EDAWebSocketWireAckFrame = Schema.Struct({\n _tag: Schema.Literal(\"ack\"),\n frameId: PositiveInt,\n durableThroughSeq: NonNegativeInt,\n});\nexport type EDAWebSocketWireAckFrame = typeof EDAWebSocketWireAckFrame.Type;\n\nexport const EDAWebSocketWireClientFrame = Schema.Union([\n EDAWebSocketWireAckFrame,\n EDAWebSocketWirePingFrame,\n]);\nexport type EDAWebSocketWireClientFrame = typeof EDAWebSocketWireClientFrame.Type;\n\n/** Exhaustive decision table for a concrete WebSocket event union. */\nexport type EDAWebSocketEventConsumerPolicy<\n Event extends { readonly type: string },\n Disposition,\n> = Readonly<Record<Event[\"type\"], Disposition>>;\n\n/** Complete framework-owned event union present on every EDA WebSocket. */\nexport const EDAFrameworkWebSocketEvent = Schema.Union([EDADurableEvent, EDAEphemeralEvent]);\nexport type EDAFrameworkWebSocketEvent = typeof EDAFrameworkWebSocketEvent.Type;\n\nconst makeEDAWebSocketDomainSchemas = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n) => {\n const positionedEvent = Schema.Struct({\n position: Position,\n event,\n });\n const eventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: PositiveInt,\n events: Schema.NonEmptyArray(positionedEvent),\n durableThroughSeq: NonNegativeInt,\n });\n const serverFrame = Schema.Union([\n EDAWebSocketWireHelloFrame,\n eventsFrame,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWirePongFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWireErrorFrame,\n ]);\n return { event, positionedEvent, eventsFrame, serverFrame };\n};\n\ntype EDAWebSocketDomainSchemas<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> = ReturnType<typeof makeEDAWebSocketDomainSchemas<EventSchema>>;\n\nconst EDAWebSocketHostDomain = makeEDAWebSocketDomainSchemas(EventEnvelope);\n\n/** Domain frame shape accepted by an app-bound encoder at the EDA host boundary. */\nexport type EDAWebSocketServerFrameInput = typeof EDAWebSocketHostDomain.serverFrame.Type;\n\n/** Minimal typed encoder surface consumed by an EDA host. */\nexport interface EDAWebSocketServerFrameEncoder {\n readonly encodeServerFrame: (frame: EDAWebSocketServerFrameInput) => string;\n}\n\n/** App-bound domain schemas, wire schemas, and encoders for protocol version 1. */\nexport interface EDAWebSocketWireProtocol<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> {\n /** Exact app-bound schemas whose `Type` values are used inside the server. */\n readonly domain: EDAWebSocketDomainSchemas<EventSchema>;\n /** Exact app-bound schemas whose `Type` values are the serialized JSON representation. */\n readonly wire: {\n readonly event: Schema.toEncoded<EventSchema>;\n readonly positionedEvent: Schema.toEncoded<\n EDAWebSocketDomainSchemas<EventSchema>[\"positionedEvent\"]\n >;\n readonly eventsFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"eventsFrame\"]>;\n readonly serverFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>;\n readonly clientFrame: typeof EDAWebSocketWireClientFrame;\n };\n /** Serialize one exact app-bound domain frame to a JSON text message. */\n readonly encodeServerFrame: (\n frame: Schema.Schema.Type<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>,\n ) => string;\n /** Validate broad host frames against the app event union before serialization. */\n readonly host: EDAWebSocketServerFrameEncoder;\n}\n\nconst makeEDAWebSocketWireProtocolFromEventSchema = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n): EDAWebSocketWireProtocol<EventSchema> => {\n const domain = makeEDAWebSocketDomainSchemas(event);\n const encodeDomainServerFrame = Schema.encodeSync(domain.serverFrame);\n const encodeUnknownDomainServerFrame = Schema.encodeUnknownSync(domain.serverFrame);\n const encodeServerFrame = (frame: typeof domain.serverFrame.Type): string =>\n JSON.stringify(encodeDomainServerFrame(frame));\n const host: EDAWebSocketServerFrameEncoder = {\n encodeServerFrame: (frame) => JSON.stringify(encodeUnknownDomainServerFrame(frame)),\n };\n\n return {\n domain,\n wire: {\n event: Schema.toEncoded(domain.event),\n positionedEvent: Schema.toEncoded(domain.positionedEvent),\n eventsFrame: Schema.toEncoded(domain.eventsFrame),\n serverFrame: Schema.toEncoded(domain.serverFrame),\n clientFrame: EDAWebSocketWireClientFrame,\n },\n encodeServerFrame,\n host,\n };\n};\n\n/** Strict framework-only protocol used when an app registers no custom events. */\nexport const edaFrameworkWebSocketWireProtocol: EDAWebSocketWireProtocol<\n typeof EDAFrameworkWebSocketEvent\n> = makeEDAWebSocketWireProtocolFromEventSchema(EDAFrameworkWebSocketEvent);\n\n/**\n * Bind the generic EDA WebSocket transport to one app's custom event schema.\n *\n * Framework durable and ephemeral events are included automatically. Future EDA\n * apps register only their custom events. Servers use the returned domain schemas\n * and typed encoder; external consumers decode with the wire schemas. Pass the\n * returned `host` adapter to the selected host package.\n */\nexport const makeEDAWebSocketWireProtocol = <\n AppEventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(options: {\n readonly appEvents: AppEventSchema;\n}): EDAWebSocketWireProtocol<\n Schema.Union<readonly [typeof EDAFrameworkWebSocketEvent, AppEventSchema]>\n> =>\n makeEDAWebSocketWireProtocolFromEventSchema(\n Schema.Union([EDAFrameworkWebSocketEvent, options.appEvents]),\n );\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport {\n EDA_WEB_SOCKET_PING_MESSAGE,\n EDA_WEB_SOCKET_PONG_MESSAGE,\n EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION,\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireClientFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireFlowControl,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWirePingFrame,\n EDAWebSocketWirePongFrame,\n edaFrameworkWebSocketWireProtocol,\n type EDAWebSocketServerFrameEncoder,\n} from \"./protocol\";\n\nexport { EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE };\n\nimport { SequenceNumber } from \"../types/core\";\nimport { PositionedEvent, UnixEpochMillis } from \"../types/events\";\n\n/** Current EDA live-event WebSocket protocol version. */\nexport const EDA_WEB_SOCKET_PROTOCOL_VERSION = EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION;\n\n/** WebSocket close code used when a subscriber cannot keep up with live delivery. */\nexport const EDA_WS_CLOSE_LAGGED = 4008;\n\n/** WebSocket close code used for normal host-driven shutdown. */\nexport const EDA_WS_CLOSE_GOING_AWAY = 1001;\n\n/** WebSocket close code used for malformed client protocol messages. */\nexport const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;\n\n/** WebSocket close code used when the host cannot send a frame. */\nexport const EDA_WS_CLOSE_SEND_FAILED = 1011;\n\n/** WebSocket close code used for unsupported binary messages. */\nexport const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;\n\n/** Live subscriber identity persisted in WebSocket attachments. */\nexport const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand(\"SubscriberId\"));\nexport type SubscriberId = typeof SubscriberId.Type;\n\n/** Per-connection monotonically increasing server frame id. */\nexport const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(\n Schema.brand(\"FrameId\"),\n);\nexport type FrameId = typeof FrameId.Type;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;\nexport type EDAWebSocketFlowControl = typeof EDAWebSocketFlowControl.Type;\n\n/** Default bounded policy sized for fast model deltas and large durable tool/message events. */\nexport const defaultEDAWebSocketFlowControl: EDAWebSocketFlowControl = {\n ackTimeoutMs: 30_000,\n // Deprecated wire-compat field: servers no longer schedule or send heartbeats.\n heartbeatIntervalMs: 10_000,\n maxFrameBytes: 256 * 1024,\n maxFrameEvents: 1,\n maxInFlightFrames: 16,\n pingIntervalMs: 30_000,\n subscriberBufferCapacityEvents: 2_048,\n};\n\n/** First server frame; announces protocol and flow-control policy. */\nexport const EDAWebSocketHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n subscriberId: SubscriberId,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketHelloFrame = typeof EDAWebSocketHelloFrame.Type;\n\n/** Ordered positioned events delivered to the client. */\nexport const EDAWebSocketEventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: FrameId,\n events: Schema.NonEmptyArray(PositionedEvent),\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketEventsFrame = typeof EDAWebSocketEventsFrame.Type;\n\n/**\n * Deprecated idle server keepalive frame.\n *\n * Servers no longer send heartbeats; the schema remains so deployed clients\n * keep decoding the server frame union. Liveness is client-originated via\n * {@link EDAWebSocketPingFrame} and the host-level auto-response pong.\n */\nexport const EDAWebSocketHeartbeatFrame = Schema.Struct({\n ...EDAWebSocketWireHeartbeatFrame.fields,\n serverTimeMs: UnixEpochMillis,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketHeartbeatFrame = typeof EDAWebSocketHeartbeatFrame.Type;\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketPingFrame = EDAWebSocketWirePingFrame;\nexport type EDAWebSocketPingFrame = typeof EDAWebSocketPingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketPongFrame = EDAWebSocketWirePongFrame;\nexport type EDAWebSocketPongFrame = typeof EDAWebSocketPongFrame.Type;\n\n/** Optional final frame sent before a lag-close. */\nexport const EDAWebSocketLaggedFrame = Schema.Struct({\n ...EDAWebSocketWireLaggedFrame.fields,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketLaggedFrame = typeof EDAWebSocketLaggedFrame.Type;\n\n/** Optional final frame sent before a protocol/internal close. */\nexport const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;\nexport type EDAWebSocketErrorFrame = typeof EDAWebSocketErrorFrame.Type;\n\n/** Server-to-client application frame union. */\nexport const EDAWebSocketServerFrame = Schema.Union([\n EDAWebSocketHelloFrame,\n EDAWebSocketEventsFrame,\n EDAWebSocketHeartbeatFrame,\n EDAWebSocketPongFrame,\n EDAWebSocketLaggedFrame,\n EDAWebSocketErrorFrame,\n]);\nexport type EDAWebSocketServerFrame = typeof EDAWebSocketServerFrame.Type;\n\n/** Client acknowledgement after applying a server frame. */\nexport const EDAWebSocketAckFrame = Schema.Struct({\n ...EDAWebSocketWireAckFrame.fields,\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketAckFrame = typeof EDAWebSocketAckFrame.Type;\n\n/** Client-to-server application frame union. */\nexport const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame, EDAWebSocketPingFrame]);\nexport type EDAWebSocketClientFrame = typeof EDAWebSocketClientFrame.Type;\n\n/** Serialize a server frame for a text WebSocket message. */\nexport const encodeEDAWebSocketServerFrame = (\n frame: EDAWebSocketServerFrame,\n protocol?: EDAWebSocketServerFrameEncoder,\n): string => (protocol ?? edaFrameworkWebSocketWireProtocol.host).encodeServerFrame(frame);\n\n/** Decode an inbound text WebSocket message at the host boundary. */\nexport const decodeEDAWebSocketClientMessage = (\n input: string,\n): Effect.Effect<EDAWebSocketClientFrame, unknown> =>\n Effect.try({\n try: () => JSON.parse(input) as unknown,\n catch: (error) => error,\n }).pipe(\n Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)),\n Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)),\n );\n\n/** Short close reason that fits the WebSocket protocol reason limit. */\nexport const laggedCloseReason = (seq: SequenceNumber): string => `lag;seq=${seq}`;\n","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDA_WS_CLOSE_LAGGED,\n EDA_WS_CLOSE_PROTOCOL_ERROR,\n EDAWebSocketEventsFrame,\n EDAWebSocketErrorFrame,\n EDAWebSocketHelloFrame,\n EDAWebSocketLaggedFrame,\n FrameId,\n SubscriberId,\n laggedCloseReason,\n type EDAWebSocketAckFrame,\n type EDAWebSocketFlowControl,\n type EDAWebSocketServerFrame,\n} from \"./messages\";\n\n/** Slow subscriber reasons that intentionally close only the lagging socket. */\nexport const SubscriberLagReason = Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]);\nexport type SubscriberLagReason = typeof SubscriberLagReason.Type;\n\n/** One sent-but-unacknowledged events frame. */\nexport const EDAWebSocketInFlightFrame = Schema.Struct({\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n sentAtMs: Schema.Number,\n});\nexport type EDAWebSocketInFlightFrame = typeof EDAWebSocketInFlightFrame.Type;\n\n/** Compact consecutive host-suppressed receipts blocked by a visible ACK. */\nexport const EDAWebSocketSuppressedRange = Schema.Struct({\n fromFrameId: FrameId,\n throughFrameId: FrameId,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketSuppressedRange = typeof EDAWebSocketSuppressedRange.Type;\n\n/** Complete delivery bookkeeping persisted in the WebSocket attachment. */\nexport const EDAWebSocketDeliveryCheckpoint = Schema.Struct({\n lastAckedSeq: SequenceNumber,\n lastAckedFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lastSentFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n nextFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n sentDurableThroughSeq: SequenceNumber,\n inFlight: Schema.Array(EDAWebSocketInFlightFrame),\n /** Host-projected receipts waiting behind an earlier client-visible ACK. */\n suppressed: Schema.optionalKey(Schema.Array(EDAWebSocketSuppressedRange)),\n});\nexport type EDAWebSocketDeliveryCheckpoint = typeof EDAWebSocketDeliveryCheckpoint.Type;\n\n/** In-memory delivery state for one accepted event WebSocket. */\nexport interface EDAWebSocketDeliveryState extends EDAWebSocketDeliveryCheckpoint {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n /** Ephemeral events are live-only and intentionally absent from the attachment. */\n readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;\n readonly suppressed: ReadonlyArray<EDAWebSocketSuppressedRange>;\n}\n\n/** Explicit instructions emitted by the pure delivery state machine. */\nexport type EDAWebSocketDeliveryAction =\n | { readonly _tag: \"Persist\" }\n | { readonly _tag: \"Send\"; readonly frames: ReadonlyArray<EDAWebSocketServerFrame> }\n | { readonly _tag: \"ReadEventPage\"; readonly afterSeq: SequenceNumber }\n | { readonly _tag: \"Close\"; readonly code: number; readonly reason: string };\n\n/** Result of one pure delivery transition. */\nexport interface EDAWebSocketDeliveryResult {\n readonly state: EDAWebSocketDeliveryState;\n readonly actions: ReadonlyArray<EDAWebSocketDeliveryAction>;\n}\n\nexport interface MakeDeliveryStateInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n}\n\n/** Build delivery state for a newly accepted connection. */\nexport const makeWebSocketDeliveryState = (\n input: MakeDeliveryStateInput,\n): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n lastAckedSeq: input.resumeSeq,\n lastAckedFrameId: 0,\n lastSentFrameId: 0,\n nextFrameId: 1,\n sentDurableThroughSeq: input.resumeSeq,\n inFlight: [],\n suppressed: [],\n pendingEphemeral: [],\n});\n\n/** Rebuild exact ACK bookkeeping from a hibernating WebSocket attachment. */\nexport const restoreWebSocketDeliveryState = (input: {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n readonly checkpoint: EDAWebSocketDeliveryCheckpoint;\n}): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n ...input.checkpoint,\n pendingEphemeral: [],\n suppressed: input.checkpoint.suppressed ?? [],\n});\n\n/** Project in-memory delivery state into the attachment-safe checkpoint. */\nexport const checkpointWebSocketDeliveryState = (\n state: EDAWebSocketDeliveryState,\n): EDAWebSocketDeliveryCheckpoint => ({\n lastAckedSeq: state.lastAckedSeq,\n lastAckedFrameId: state.lastAckedFrameId,\n lastSentFrameId: state.lastSentFrameId,\n nextFrameId: state.nextFrameId,\n sentDurableThroughSeq: state.sentDurableThroughSeq,\n inFlight: state.inFlight,\n ...(state.suppressed.length === 0 ? {} : { suppressed: state.suppressed }),\n});\n\n/** First frame for a freshly accepted connection. Restores never re-send hello. */\nexport const deliveryHelloFrame = (state: EDAWebSocketDeliveryState): EDAWebSocketHelloFrame =>\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: state.subscriberId,\n resumeSeq: state.lastAckedSeq,\n flowControl: state.policy,\n });\n\n/** Deliver committed durable events read from the store. */\nexport const onDurableEvents = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n head: SequenceNumber,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n let batch: PositionedEvent[] = [];\n\n const flushBatch = (): void => {\n if (batch.length === 0) return;\n const sent = sendEventsFrame(next, batch, nowMs);\n next = sent.state;\n frames.push(sent.frame);\n batch = [];\n };\n\n for (const event of events) {\n if (event.event.durability === \"durable\" && event.position.seq <= next.sentDurableThroughSeq) {\n continue;\n }\n if (batch.length === 0 && windowCapacity(next) <= 0) break;\n batch.push(event);\n if (batch.length >= next.policy.maxFrameEvents) flushBatch();\n }\n flushBatch();\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.sentDurableThroughSeq < head\n ? next.sentDurableThroughSeq\n : undefined,\n );\n};\n\n/** Deliver one live ephemeral event, buffering only while this isolate is active. */\nexport const onEphemeralEvent = (\n state: EDAWebSocketDeliveryState,\n event: PositionedEvent,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {\n const sent = sendEventsFrame(state, [event], nowMs);\n return sentResult(sent.state, [sent.frame]);\n }\n\n const pendingEphemeral = [...state.pendingEphemeral, event];\n if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) {\n return laggedResult(state, \"buffer-overflow\");\n }\n return { state: { ...state, pendingEphemeral }, actions: [] };\n};\n\n/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */\nexport const onClientAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const validated = applyAck(state, ack);\n if (validated._tag === \"close\") return validated.result;\n if (validated._tag === \"ignore\") return { state, actions: [] };\n\n return reopenDeliveryWindow(validated.state, nowMs);\n};\n\n/**\n * Apply one exact host-suppressed receipt without cumulatively ACKing any\n * earlier client-visible frame.\n */\nexport const onHostSuppressedFrame = (\n state: EDAWebSocketDeliveryState,\n frame: Pick<EDAWebSocketEventsFrame, \"durableThroughSeq\" | \"frameId\">,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const receipt = state.inFlight.find((candidate) => candidate.frameId === frame.frameId);\n if (receipt === undefined || receipt.durableThroughSeq !== frame.durableThroughSeq) {\n return protocolClose(state, \"Host suppressed an unknown frame receipt\").result;\n }\n const next = advanceSuppressedReceipts({\n ...state,\n inFlight: state.inFlight.filter((candidate) => candidate.frameId !== frame.frameId),\n suppressed: insertSuppressedReceipt(state.suppressed, receipt),\n });\n return reopenDeliveryWindow(next, nowMs);\n};\n\nconst reopenDeliveryWindow = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {\n const [head, ...rest] = next.pendingEphemeral;\n if (head === undefined) break;\n const sent = sendEventsFrame({ ...next, pendingEphemeral: rest }, [head], nowMs);\n next = sent.state;\n frames.push(sent.frame);\n }\n\n const stale = staleAckResult(next, nowMs);\n if (stale !== undefined) return stale;\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.pendingEphemeral.length === 0\n ? next.sentDurableThroughSeq\n : undefined,\n true,\n );\n};\n\ntype AckValidation =\n | { readonly _tag: \"ignore\" }\n | { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult }\n | { readonly _tag: \"apply\"; readonly state: EDAWebSocketDeliveryState };\n\nconst applyAck = (state: EDAWebSocketDeliveryState, ack: EDAWebSocketAckFrame): AckValidation => {\n if (ack.frameId <= state.lastAckedFrameId) {\n return ack.durableThroughSeq > state.lastAckedSeq\n ? protocolClose(state, \"Duplicate ACK attempted to advance durable seq\")\n : { _tag: \"ignore\" };\n }\n if (ack.frameId > state.lastSentFrameId) {\n return protocolClose(state, \"ACK referenced an unsent frame\");\n }\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return protocolClose(state, \"ACK durable seq moved backwards\");\n }\n const acknowledgedVisible = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledgedVisible.length === 0) {\n return protocolClose(state, \"ACK referenced no in-flight frames\");\n }\n if (\n state.suppressed.some(\n (range) => range.fromFrameId <= ack.frameId && ack.frameId <= range.throughFrameId,\n )\n ) {\n return protocolClose(state, \"ACK referenced a host-suppressed frame\");\n }\n const acknowledgedSuppressed = state.suppressed.filter(\n (range) => range.throughFrameId <= ack.frameId,\n );\n const acknowledged = [...acknowledgedVisible, ...acknowledgedSuppressed];\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, receipt) => Math.max(max, receipt.durableThroughSeq),\n state.lastAckedSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n return protocolClose(state, \"ACK durable seq exceeded sent frame boundary\");\n }\n return {\n _tag: \"apply\",\n state: advanceSuppressedReceipts({\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: ack.frameId,\n lastAckedSeq: ack.durableThroughSeq,\n suppressed: state.suppressed.filter((range) => range.throughFrameId > ack.frameId),\n }),\n };\n};\n\nconst advanceSuppressedReceipts = (state: EDAWebSocketDeliveryState): EDAWebSocketDeliveryState => {\n let lastAckedFrameId = state.lastAckedFrameId;\n let lastAckedSeq = state.lastAckedSeq;\n let consumed = 0;\n for (const range of state.suppressed) {\n if (range.fromFrameId !== lastAckedFrameId + 1) break;\n lastAckedFrameId = range.throughFrameId;\n lastAckedSeq = SequenceNumber.make(Math.max(lastAckedSeq, range.durableThroughSeq));\n consumed += 1;\n }\n return consumed === 0\n ? state\n : {\n ...state,\n lastAckedFrameId,\n lastAckedSeq,\n suppressed: state.suppressed.slice(consumed),\n };\n};\n\nconst insertSuppressedReceipt = (\n ranges: ReadonlyArray<EDAWebSocketSuppressedRange>,\n receipt: EDAWebSocketInFlightFrame,\n): ReadonlyArray<EDAWebSocketSuppressedRange> => {\n const inserted = [\n ...ranges,\n EDAWebSocketSuppressedRange.make({\n fromFrameId: receipt.frameId,\n throughFrameId: receipt.frameId,\n durableThroughSeq: receipt.durableThroughSeq,\n }),\n ].sort((left, right) => left.fromFrameId - right.fromFrameId);\n const compacted: EDAWebSocketSuppressedRange[] = [];\n for (const range of inserted) {\n const previous = compacted.at(-1);\n if (previous === undefined || range.fromFrameId > previous.throughFrameId + 1) {\n compacted.push(range);\n continue;\n }\n compacted[compacted.length - 1] = EDAWebSocketSuppressedRange.make({\n fromFrameId: previous.fromFrameId,\n throughFrameId: FrameId.make(Math.max(previous.throughFrameId, range.throughFrameId)),\n durableThroughSeq: SequenceNumber.make(\n Math.max(previous.durableThroughSeq, range.durableThroughSeq),\n ),\n });\n }\n return compacted;\n};\n\nconst windowCapacity = (state: EDAWebSocketDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\nconst sendEventsFrame = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n nowMs: number,\n): { readonly state: EDAWebSocketDeliveryState; readonly frame: EDAWebSocketEventsFrame } => {\n const [first, ...rest] = events;\n if (first === undefined) throw new Error(\"Cannot send an empty events frame\");\n const frameId = FrameId.make(state.nextFrameId);\n const durableThroughSeq = SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n state.sentDurableThroughSeq,\n ),\n );\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: [first, ...rest],\n durableThroughSeq,\n });\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, { frameId, durableThroughSeq, sentAtMs: nowMs }],\n lastSentFrameId: frameId,\n nextFrameId: frameId + 1,\n sentDurableThroughSeq: durableThroughSeq,\n },\n frame,\n };\n};\n\nconst sentResult = (\n state: EDAWebSocketDeliveryState,\n frames: ReadonlyArray<EDAWebSocketServerFrame>,\n catchUpAfterSeq?: SequenceNumber,\n stateChanged = frames.length > 0,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n ...(stateChanged ? ([{ _tag: \"Persist\" }] as const) : []),\n ...(frames.length > 0 ? ([{ _tag: \"Send\", frames }] as const) : []),\n ...(catchUpAfterSeq === undefined\n ? []\n : ([{ _tag: \"ReadEventPage\", afterSeq: catchUpAfterSeq }] as const)),\n ],\n});\n\n/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */\nconst staleAckResult = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult | undefined =>\n state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs)\n ? laggedResult(state, \"ack-timeout\")\n : undefined;\n\nconst laggedResult = (\n state: EDAWebSocketDeliveryState,\n reason: SubscriberLagReason,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [\n EDAWebSocketLaggedFrame.make({\n _tag: \"lagged\",\n resumeSeq: state.lastAckedSeq,\n reason,\n }),\n ],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_LAGGED, reason: laggedCloseReason(state.lastAckedSeq) },\n ],\n});\n\nconst protocolClose = (\n state: EDAWebSocketDeliveryState,\n message: string,\n): { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult } => ({\n _tag: \"close\",\n result: {\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [EDAWebSocketErrorFrame.make({ _tag: \"error\", message: message.slice(0, 120) })],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_PROTOCOL_ERROR, reason: \"protocol\" },\n ],\n },\n});\n"],"mappings":";;;;;;;AAKA,MAAM,cAAc,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAC5D,MAAM,iBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;;AAGxE,MAAa,uCAAuC;;AAGpD,MAAa,8BAA8B,OAAO,OAAO;CACvD,cAAc;;CAEd,qBAAqB;CACrB,eAAe;CACf,gBAAgB;CAChB,mBAAmB;;CAEnB,gBAAgB,OAAO,YAAY,WAAW;CAC9C,gCAAgC;AAClC,CAAC;;;;;;;AASD,MAAa,8BAA8B;;AAG3C,MAAa,8BAA8B;;AAG3C,MAAa,4BAA4B,OAAO,OAAO,EACrD,MAAM,OAAO,QAAQ,MAAM,EAC7B,CAAC;;AAID,MAAa,4BAA4B,OAAO,OAAO,EACrD,MAAM,OAAO,QAAQ,MAAM,EAC7B,CAAC;AAGD,MAAa,6BAA6B,OAAO,OAAO;CACtD,MAAM,OAAO,QAAQ,OAAO;CAC5B,iBAAiB,OAAO,QAAA,CAA4C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IACjC,KAAA;AAEN,MAAM,gBACJ,OACA,YACgC;CAChC;CACA,SAAS,CACP;EACE,MAAM;EACN,QAAQ,CACN,wBAAwB,KAAK;GAC3B,MAAM;GACN,WAAW,MAAM;GACjB;EACF,CAAC,CACH;CACF,GACA;EAAE,MAAM;EAAS,MAAM;EAAqB,QAAQ,kBAAkB,MAAM,YAAY;CAAE,CAC5F;AACF;AAEA,MAAM,iBACJ,OACA,aAC6E;CAC7E,MAAM;CACN,QAAQ;EACN;EACA,SAAS,CACP;GACE,MAAM;GACN,QAAQ,CAAC,uBAAuB,KAAK;IAAE,MAAM;IAAS,SAAS,QAAQ,MAAM,GAAG,GAAG;GAAE,CAAC,CAAC;EACzF,GACA;GAAE,MAAM;GAAS,MAAM;GAA6B,QAAQ;EAAW,CACzE;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-durable-agent",
3
- "version": "0.1.0-alpha.6",
3
+ "version": "0.1.0-alpha.8",
4
4
  "description": "A host-independent, event-sourced durable state-management and execution layer for agentic applications.",
5
5
  "keywords": [
6
6
  "agents",
@@ -30,6 +30,14 @@
30
30
  "tooling/oxlint/rules/*.mjs"
31
31
  ],
32
32
  "exports": {
33
+ "./services/model-resolver": {
34
+ "types": "./dist/services/model-resolver.d.ts",
35
+ "import": "./dist/services/model-resolver.js"
36
+ },
37
+ "./domain/model-usage": {
38
+ "types": "./dist/domain/model-usage.d.ts",
39
+ "import": "./dist/domain/model-usage.js"
40
+ },
33
41
  ".": {
34
42
  "types": "./dist/index.d.ts",
35
43
  "import": "./dist/index.js"
@@ -161,6 +169,7 @@
161
169
  "@cloudflare/workers-types": "5.20260813.1",
162
170
  "@effect/ai-openai": "4.0.0-beta.102",
163
171
  "@effect/tsgo": "0.31.0",
172
+ "@effect/vitest": "4.0.0-beta.102",
164
173
  "@types/node": "^25.7.0",
165
174
  "effect": "4.0.0-beta.102",
166
175
  "esbuild": "^0.28.1",
@@ -1 +0,0 @@
1
- {"version":3,"file":"durable-DsV9PxZC.js","names":[],"sources":["../src/types/events/envelope.ts","../src/types/events/internal.ts","../src/types/events/durable.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { CorrelationId, EventId, Position, SessionId } from \"../core\";\nimport { EDAEventTrace, makeRootEDAEventTrace } from \"../tracing\";\n\n/** Event namespace, such as `effect-durable-agent`, `sandbox`, or `gia`. */\nexport const EventNamespace = Schema.NonEmptyString;\nexport type EventNamespace = typeof EventNamespace.Type;\n\n/** Event type within a namespace, such as `CommandAdmitted` or `TextDelta`. */\nexport const EventType = Schema.NonEmptyString;\nexport type EventType = typeof EventType.Type;\n\n/** Build a non-empty event type while preserving its string literal for exhaustive unions. */\nexport const makeEventType = <const Value extends string>(\n value: Value extends \"\" ? never : Value,\n) => value;\n\n/** Extract the literal name retained by `makeEventType`. */\nexport type EventTypeName<Type extends EventType> = Type;\n\n/** Provider-supplied stream part identity, preserved for correlation/debugging. */\nexport const ProviderPartId = Schema.NonEmptyString.pipe(Schema.brand(\"ProviderPartId\"));\nexport type ProviderPartId = typeof ProviderPartId.Type;\n\n/** Positive schema version for one namespace/type payload contract. */\nexport const SchemaVersion = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nexport type SchemaVersion = typeof SchemaVersion.Type;\n\n/** Milliseconds since unix epoch, represented as a non-negative integer. */\nexport const UnixEpochMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)).pipe(\n Schema.brand(\"UnixEpochMillis\"),\n);\nexport type UnixEpochMillis = typeof UnixEpochMillis.Type;\n\n/** Whether an event is persisted or live-only. */\nexport const EventDurability = Schema.Literals([\"durable\", \"ephemeral\"]);\nexport type EventDurability = typeof EventDurability.Type;\n\n/** Common event envelope decoded before payload-specific schemas. */\nexport const EventEnvelope = Schema.Struct({\n namespace: EventNamespace,\n type: EventType,\n schemaVersion: SchemaVersion,\n durability: EventDurability,\n eventId: EventId,\n sessionId: SessionId,\n correlationId: Schema.optionalKey(CorrelationId),\n createdAtMs: UnixEpochMillis,\n trace: EDAEventTrace.pipe(Schema.withConstructorDefault(Effect.sync(makeRootEDAEventTrace))),\n payload: Schema.Unknown,\n});\nexport type EventEnvelope = typeof EventEnvelope.Type;\n\n/** Common envelope narrowed to committed durable events. */\nexport const DurableEventEnvelope = Schema.Struct({\n ...EventEnvelope.fields,\n durability: Schema.Literal(\"durable\"),\n});\nexport type DurableEventEnvelope = typeof DurableEventEnvelope.Type;\n\n/** Common envelope narrowed to live-only ephemeral events. */\nexport const EphemeralEventEnvelope = Schema.Struct({\n ...EventEnvelope.fields,\n durability: Schema.Literal(\"ephemeral\"),\n});\nexport type EphemeralEventEnvelope = typeof EphemeralEventEnvelope.Type;\n\n/** Event delivered to live subscribers with its durable/ephemeral position. */\nexport const PositionedEvent = Schema.Struct({\n position: Position,\n event: EventEnvelope,\n});\nexport type PositionedEvent = typeof PositionedEvent.Type;\n\n/** Built-in framework event namespace. */\nexport const effectDurableAgentNamespace = EventNamespace.make(\"effect-durable-agent\");\n\n/** Initial schema version for built-in event payloads. */\nexport const schemaV1 = SchemaVersion.make(1);\n\n/** Non-negative integer used by token counts and similar counters. */\nexport const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nexport type NonNegativeInt = typeof NonNegativeInt.Type;\n\n/** Registered tool name; plain non-empty text, not a lifecycle identity. */\nexport const ToolName = Schema.NonEmptyString;\nexport type ToolName = typeof ToolName.Type;\n\n/** Error details stored on failed lifecycle events. */\nexport const FailurePayload = Schema.Struct({\n message: Schema.String,\n code: Schema.optionalKey(Schema.String),\n details: Schema.optionalKey(Schema.Unknown),\n});\nexport type FailurePayload = typeof FailurePayload.Type;\n\n/** Token usage reported by a model provider when available. */\nexport const UsagePayload = Schema.Struct({\n inputTokens: Schema.optionalKey(NonNegativeInt),\n cachedInputTokens: Schema.optionalKey(NonNegativeInt),\n outputTokens: Schema.optionalKey(NonNegativeInt),\n textTokens: Schema.optionalKey(NonNegativeInt),\n reasoningTokens: Schema.optionalKey(NonNegativeInt),\n});\nexport type UsagePayload = typeof UsagePayload.Type;\n\n/** Intended provider/model selection known before a model request starts. */\nexport const ModelSelectionPayload = Schema.Struct({\n provider: Schema.NonEmptyString,\n modelId: Schema.NonEmptyString,\n settings: Schema.optionalKey(Schema.Unknown),\n});\nexport type ModelSelectionPayload = typeof ModelSelectionPayload.Type;\n\n/** App-owned instructions inserted into model context as a system message. */\nexport const SystemPromptText = Schema.NonEmptyString;\nexport type SystemPromptText = typeof SystemPromptText.Type;\n","import * as Schema from \"effect/Schema\";\n\nimport {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n EventType,\n effectDurableAgentNamespace,\n schemaV1,\n} from \"./envelope\";\n\n/** Build a built-in durable event schema from its fixed event type and payload schema. */\nexport const durableEventSchema = <const Type extends EventType, Payload extends Schema.Top>(\n type: Type,\n payload: Payload,\n) =>\n Schema.Struct({\n ...DurableEventEnvelope.fields,\n namespace: Schema.Literal(effectDurableAgentNamespace),\n type: Schema.Literal(type),\n schemaVersion: Schema.Literal(schemaV1),\n payload,\n });\n\n/** Build a built-in ephemeral event schema from its fixed event type and payload schema. */\nexport const ephemeralEventSchema = <const Type extends EventType, Payload extends Schema.Top>(\n type: Type,\n payload: Payload,\n) =>\n Schema.Struct({\n ...EphemeralEventEnvelope.fields,\n namespace: Schema.Literal(effectDurableAgentNamespace),\n type: Schema.Literal(type),\n schemaVersion: Schema.Literal(schemaV1),\n payload,\n });\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport * as Prompt from \"effect/unstable/ai/Prompt\";\n\nimport { EDACommand, UserMessageContent } from \"../commands\";\nimport {\n BaseStateId,\n CommandId,\n CompactionId,\n ContextVersion,\n InferenceId,\n MessageId,\n RunId,\n SequenceNumber,\n SummaryId,\n ToolCallId,\n TurnId,\n} from \"../core\";\nimport {\n DurableEventEnvelope,\n FailurePayload,\n ModelSelectionPayload,\n ProviderPartId,\n SystemPromptText,\n ToolName,\n UsagePayload,\n effectDurableAgentNamespace,\n makeEventType,\n schemaV1,\n} from \"./envelope\";\nimport { durableEventSchema } from \"./internal\";\nimport { EDARunTrace, makeEDARunTrace } from \"../tracing\";\n\n/** Event type values for durable command lifecycle events. */\nexport const commandAdmittedEventType = makeEventType(\"CommandAdmitted\");\nexport const commandStartedEventType = makeEventType(\"CommandStarted\");\nexport const commandCompletedEventType = makeEventType(\"CommandCompleted\");\nexport const commandFailedEventType = makeEventType(\"CommandFailed\");\nexport const commandCancelledEventType = makeEventType(\"CommandCancelled\");\n\n/** Payload recorded when a command enters the durable session log. */\nexport const CommandAdmittedPayload = Schema.Struct({ command: EDACommand });\nexport type CommandAdmittedPayload = typeof CommandAdmittedPayload.Type;\nexport const CommandAdmittedEvent = durableEventSchema(\n commandAdmittedEventType,\n CommandAdmittedPayload,\n);\nexport type CommandAdmittedEvent = typeof CommandAdmittedEvent.Type;\n\n/** Payload recorded when command execution starts. */\nexport const CommandStartedPayload = Schema.Struct({ commandId: CommandId });\nexport type CommandStartedPayload = typeof CommandStartedPayload.Type;\nexport const CommandStartedEvent = durableEventSchema(\n commandStartedEventType,\n CommandStartedPayload,\n);\nexport type CommandStartedEvent = typeof CommandStartedEvent.Type;\n\n/** Payload recorded when command execution completes normally. */\nexport const CommandCompletedPayload = Schema.Struct({ commandId: CommandId });\nexport type CommandCompletedPayload = typeof CommandCompletedPayload.Type;\nexport const CommandCompletedEvent = durableEventSchema(\n commandCompletedEventType,\n CommandCompletedPayload,\n);\nexport type CommandCompletedEvent = typeof CommandCompletedEvent.Type;\n\n/** Payload recorded when command execution fails. */\nexport const CommandFailedPayload = Schema.Struct({ commandId: CommandId, error: FailurePayload });\nexport type CommandFailedPayload = typeof CommandFailedPayload.Type;\nexport const CommandFailedEvent = durableEventSchema(commandFailedEventType, CommandFailedPayload);\nexport type CommandFailedEvent = typeof CommandFailedEvent.Type;\n\n/** Payload recorded when a command is cancelled before completion. */\nexport const CommandCancelledPayload = Schema.Struct({\n commandId: CommandId,\n reason: Schema.String,\n});\nexport type CommandCancelledPayload = typeof CommandCancelledPayload.Type;\nexport const CommandCancelledEvent = durableEventSchema(\n commandCancelledEventType,\n CommandCancelledPayload,\n);\nexport type CommandCancelledEvent = typeof CommandCancelledEvent.Type;\n\n/** Durable event union for the command lifecycle. */\nexport const CommandEvent = Schema.Union([\n CommandAdmittedEvent,\n CommandStartedEvent,\n CommandCompletedEvent,\n CommandFailedEvent,\n CommandCancelledEvent,\n]);\nexport type CommandEvent = typeof CommandEvent.Type;\n\n/** Event type values for durable message lifecycle events. */\nexport const systemMessageCommittedEventType = makeEventType(\"SystemMessageCommitted\");\nexport const userMessageCommittedEventType = makeEventType(\"UserMessageCommitted\");\nexport const steeringMessageQueuedEventType = makeEventType(\"SteeringMessageQueued\");\nexport const steeringMessageCancelledEventType = makeEventType(\"SteeringMessageCancelled\");\nexport const userMessageSubmittedEventType = makeEventType(\"UserMessageSubmitted\");\nexport const userMessagePromotedEventType = makeEventType(\"UserMessagePromoted\");\nexport const userMessageCancelledEventType = makeEventType(\"UserMessageCancelled\");\nexport const messageQueuePausedEventType = makeEventType(\"MessageQueuePaused\");\nexport const pendingMessagesPausedEventType = makeEventType(\"PendingMessagesPaused\");\nexport const assistantMessageCommittedEventType = makeEventType(\"AssistantMessageCommitted\");\nexport const assistantMessageImportedEventType = makeEventType(\"AssistantMessageImported\");\nexport const assistantPartialCommittedEventType = makeEventType(\"AssistantPartialCommitted\");\n\n/** Semantic assistant content derived from canonical prompt parts for query convenience. */\nexport const AssistantMessageContent = Schema.Struct({\n text: Schema.String,\n reasoning: Schema.optionalKey(Schema.String),\n});\nexport type AssistantMessageContent = typeof AssistantMessageContent.Type;\n\n/** Exact assistant-role prompt parts sent to the model for cache-faithful replay. */\nexport const AssistantPromptPart = Schema.Union([\n Prompt.TextPart,\n Prompt.FilePart,\n Prompt.ReasoningPart,\n Prompt.ToolCallPart,\n Prompt.ToolResultPart,\n Prompt.ToolApprovalRequestPart,\n]);\nexport type AssistantPromptPart = typeof AssistantPromptPart.Type;\n\n/** Exact non-empty assistant-role prompt content sent to the model. */\nexport const AssistantPromptParts = Schema.NonEmptyArray(AssistantPromptPart);\nexport type AssistantPromptParts = typeof AssistantPromptParts.Type;\n\n/** Exact assistant tool-call prompt part with EDA-branded provider identity. */\nexport const ToolCallPromptPart = Schema.Struct({\n ...Prompt.ToolCallPart.fields,\n id: ProviderPartId,\n name: ToolName,\n});\nexport type ToolCallPromptPart = typeof ToolCallPromptPart.Type;\n\n/** Exact tool-role prompt part sent to the model with EDA-branded provider identity. */\nexport const ToolPromptPart = Schema.Struct({\n ...Prompt.ToolResultPart.fields,\n id: ProviderPartId,\n name: ToolName,\n});\nexport type ToolPromptPart = typeof ToolPromptPart.Type;\n\n/** Payload recorded when app instructions become durable system-message context. */\nexport const SystemMessageCommittedPayload = Schema.Struct({\n messageId: MessageId,\n content: SystemPromptText,\n});\nexport type SystemMessageCommittedPayload = typeof SystemMessageCommittedPayload.Type;\nexport const SystemMessageCommittedEvent = durableEventSchema(\n systemMessageCommittedEventType,\n SystemMessageCommittedPayload,\n);\nexport type SystemMessageCommittedEvent = typeof SystemMessageCommittedEvent.Type;\n\n/** Payload recorded when a user message becomes durable session context. */\nexport const UserMessageCommittedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n content: UserMessageContent,\n});\nexport type UserMessageCommittedPayload = typeof UserMessageCommittedPayload.Type;\nexport const UserMessageCommittedEvent = durableEventSchema(\n userMessageCommittedEventType,\n UserMessageCommittedPayload,\n);\nexport type UserMessageCommittedEvent = typeof UserMessageCommittedEvent.Type;\n\n/** Payload recorded when steering context is queued for a future turn. */\nexport const SteeringMessageQueuedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n runId: RunId,\n content: UserMessageContent,\n});\nexport type SteeringMessageQueuedPayload = typeof SteeringMessageQueuedPayload.Type;\nexport const SteeringMessageQueuedEvent = durableEventSchema(\n steeringMessageQueuedEventType,\n SteeringMessageQueuedPayload,\n);\nexport type SteeringMessageQueuedEvent = typeof SteeringMessageQueuedEvent.Type;\n\n/** Payload recorded when queued steering will never be consumed by its target run. */\nexport const SteeringMessageCancelledPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n reason: Schema.String,\n});\nexport type SteeringMessageCancelledPayload = typeof SteeringMessageCancelledPayload.Type;\nexport const SteeringMessageCancelledEvent = durableEventSchema(\n steeringMessageCancelledEventType,\n SteeringMessageCancelledPayload,\n);\nexport type SteeringMessageCancelledEvent = typeof SteeringMessageCancelledEvent.Type;\n\nexport const UserMessageDisposition = Schema.Literals([\"queue\", \"steer\"]);\nexport type UserMessageDisposition = typeof UserMessageDisposition.Type;\n\nexport const UserMessageSubmittedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n disposition: UserMessageDisposition,\n content: UserMessageContent,\n});\nexport type UserMessageSubmittedPayload = typeof UserMessageSubmittedPayload.Type;\nexport const UserMessageSubmittedEvent = durableEventSchema(\n userMessageSubmittedEventType,\n UserMessageSubmittedPayload,\n);\nexport type UserMessageSubmittedEvent = typeof UserMessageSubmittedEvent.Type;\n\nexport const UserMessagePromotedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n from: Schema.Literal(\"queue\"),\n to: Schema.Literal(\"steer\"),\n});\nexport type UserMessagePromotedPayload = typeof UserMessagePromotedPayload.Type;\nexport const UserMessagePromotedEvent = durableEventSchema(\n userMessagePromotedEventType,\n UserMessagePromotedPayload,\n);\nexport type UserMessagePromotedEvent = typeof UserMessagePromotedEvent.Type;\n\nexport const UserMessageCancellationReason = Schema.Literals([\n \"edit\",\n \"user-cancel\",\n \"clear-paused-queue\",\n]);\nexport type UserMessageCancellationReason = typeof UserMessageCancellationReason.Type;\nexport const UserMessageCancelledPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n reason: UserMessageCancellationReason,\n});\nexport type UserMessageCancelledPayload = typeof UserMessageCancelledPayload.Type;\nexport const UserMessageCancelledEvent = durableEventSchema(\n userMessageCancelledEventType,\n UserMessageCancelledPayload,\n);\nexport type UserMessageCancelledEvent = typeof UserMessageCancelledEvent.Type;\n\n/** Legacy V1 pause fact retained for replay compatibility. */\nexport const MessageQueuePausedPayload = Schema.Struct({\n stopCommandId: CommandId,\n runId: RunId,\n messageIds: Schema.Array(MessageId),\n reason: Schema.Literal(\"user-interrupted\"),\n});\nexport type MessageQueuePausedPayload = typeof MessageQueuePausedPayload.Type;\nexport const MessageQueuePausedEvent = durableEventSchema(\n messageQueuePausedEventType,\n MessageQueuePausedPayload,\n);\nexport type MessageQueuePausedEvent = typeof MessageQueuePausedEvent.Type;\n\nexport const PendingMessagesPausedPayload = Schema.Struct({\n interruptionCommandId: CommandId,\n runId: RunId,\n messageIds: Schema.NonEmptyArray(MessageId),\n reason: Schema.Literal(\"user-interrupted\"),\n});\nexport type PendingMessagesPausedPayload = typeof PendingMessagesPausedPayload.Type;\nexport const PendingMessagesPausedEvent = durableEventSchema(\n pendingMessagesPausedEventType,\n PendingMessagesPausedPayload,\n);\nexport type PendingMessagesPausedEvent = typeof PendingMessagesPausedEvent.Type;\n\n/** Payload recorded when an assistant message is durably finalized. */\nexport const AssistantMessageCommittedPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n promptParts: AssistantPromptParts,\n});\nexport type AssistantMessageCommittedPayload = typeof AssistantMessageCommittedPayload.Type;\nexport const AssistantMessageCommittedEvent = durableEventSchema(\n assistantMessageCommittedEventType,\n AssistantMessageCommittedPayload,\n);\nexport type AssistantMessageCommittedEvent = typeof AssistantMessageCommittedEvent.Type;\n\n/** Payload recorded when pre-existing assistant context is imported from an external transport. */\nexport const AssistantMessageImportedPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n promptParts: AssistantPromptParts,\n});\nexport type AssistantMessageImportedPayload = typeof AssistantMessageImportedPayload.Type;\nexport const AssistantMessageImportedEvent = durableEventSchema(\n assistantMessageImportedEventType,\n AssistantMessageImportedPayload,\n);\nexport type AssistantMessageImportedEvent = typeof AssistantMessageImportedEvent.Type;\n\n/** Payload recorded when a partial assistant message is preserved durably. */\nexport const AssistantPartialCommittedPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n promptParts: AssistantPromptParts,\n reason: Schema.String,\n});\nexport type AssistantPartialCommittedPayload = typeof AssistantPartialCommittedPayload.Type;\nexport const AssistantPartialCommittedEvent = durableEventSchema(\n assistantPartialCommittedEventType,\n AssistantPartialCommittedPayload,\n);\nexport type AssistantPartialCommittedEvent = typeof AssistantPartialCommittedEvent.Type;\n\n/** Durable event union for message commit/queue boundaries. */\nexport const MessageEvent = Schema.Union([\n SystemMessageCommittedEvent,\n UserMessageCommittedEvent,\n SteeringMessageQueuedEvent,\n SteeringMessageCancelledEvent,\n UserMessageSubmittedEvent,\n UserMessagePromotedEvent,\n UserMessageCancelledEvent,\n MessageQueuePausedEvent,\n PendingMessagesPausedEvent,\n AssistantMessageCommittedEvent,\n AssistantMessageImportedEvent,\n AssistantPartialCommittedEvent,\n]);\nexport type MessageEvent = typeof MessageEvent.Type;\n\n/** Event type values for durable run lifecycle events. */\nexport const runStartedEventType = makeEventType(\"RunStarted\");\nexport const runCompletedEventType = makeEventType(\"RunCompleted\");\nexport const runFailedEventType = makeEventType(\"RunFailed\");\n/** @deprecated Legacy terminal retained for durable replay. Emit `RunFailed` with an interruption-coded `FailurePayload` instead. */\nexport const runInterruptedEventType = makeEventType(\"RunInterrupted\");\n\n/** Payload recorded when a run starts with its intended model selection. */\nexport const RunStartedPayload = Schema.Struct({\n runId: RunId,\n commandIds: Schema.Array(CommandId),\n modelSelection: ModelSelectionPayload,\n trace: EDARunTrace.pipe(Schema.withConstructorDefault(Effect.sync(() => makeEDARunTrace()))),\n});\nexport type RunStartedPayload = typeof RunStartedPayload.Type;\nexport const RunStartedEvent = durableEventSchema(runStartedEventType, RunStartedPayload);\nexport type RunStartedEvent = typeof RunStartedEvent.Type;\n\n/** Payload recorded when a run completes. */\nexport const RunCompletedPayload = Schema.Struct({ runId: RunId });\nexport type RunCompletedPayload = typeof RunCompletedPayload.Type;\nexport const RunCompletedEvent = durableEventSchema(runCompletedEventType, RunCompletedPayload);\nexport type RunCompletedEvent = typeof RunCompletedEvent.Type;\n\n/** Payload recorded when a run fails. */\nexport const RunFailedPayload = Schema.Struct({ runId: RunId, error: FailurePayload });\nexport type RunFailedPayload = typeof RunFailedPayload.Type;\nexport const RunFailedEvent = durableEventSchema(runFailedEventType, RunFailedPayload);\nexport type RunFailedEvent = typeof RunFailedEvent.Type;\n\n/** @deprecated Legacy payload retained for durable replay. New interruptions use `RunFailedPayload` with `error.code = \"run.interrupted\"`. */\nexport const RunInterruptedPayload = Schema.Struct({ runId: RunId, reason: Schema.String });\n/** @deprecated Use `RunFailedPayload` with interruption metadata. */\nexport type RunInterruptedPayload = typeof RunInterruptedPayload.Type;\n/** @deprecated Legacy event schema retained for durable replay; new producers emit `RunFailedEvent`. */\nexport const RunInterruptedEvent = durableEventSchema(\n runInterruptedEventType,\n RunInterruptedPayload,\n);\n/** @deprecated Use `RunFailedEvent` with interruption metadata. */\nexport type RunInterruptedEvent = typeof RunInterruptedEvent.Type;\n\n/** Durable event union for run lifecycle boundaries. */\nexport const RunEvent = Schema.Union([\n RunStartedEvent,\n RunCompletedEvent,\n RunFailedEvent,\n RunInterruptedEvent,\n]);\nexport type RunEvent = typeof RunEvent.Type;\n\n/** Event type value for the durable barrier written after real startup recovery work. */\nexport const recoveryCompletedEventType = makeEventType(\"RecoveryCompleted\");\n\n/** Explicit relationship between an interrupted run and its startup-recovery replacement. */\nexport const RecoveryContinuation = Schema.Struct({\n commandId: CommandId,\n interruptedRunId: RunId,\n replacementRunId: RunId,\n});\nexport type RecoveryContinuation = typeof RecoveryContinuation.Type;\n\n/**\n * Durable completion barrier for a startup recovery transaction that repaired\n * unfinished state. Idle runtime construction does not emit this event.\n */\nexport const RecoveryCompletedPayload = Schema.Struct({\n trigger: Schema.Literal(\"runtime-restart\"),\n continuation: Schema.optionalKey(RecoveryContinuation),\n});\nexport type RecoveryCompletedPayload = typeof RecoveryCompletedPayload.Type;\nexport const RecoveryCompletedEvent = durableEventSchema(\n recoveryCompletedEventType,\n RecoveryCompletedPayload,\n);\nexport type RecoveryCompletedEvent = typeof RecoveryCompletedEvent.Type;\n\n/** Durable facts written only by the framework startup-recovery transaction. */\nexport const RecoveryEvent = RecoveryCompletedEvent;\nexport type RecoveryEvent = typeof RecoveryEvent.Type;\n\n/** Event type values for durable turn lifecycle events. */\nexport const turnStartedEventType = makeEventType(\"TurnStarted\");\nexport const turnCompletedEventType = makeEventType(\"TurnCompleted\");\nexport const turnFailedEventType = makeEventType(\"TurnFailed\");\n/** @deprecated Legacy terminal retained for durable replay. Emit `TurnFailed` with an interruption-coded `FailurePayload` instead. */\nexport const turnStoppedEventType = makeEventType(\"TurnStopped\");\n\n/** Payload recorded when one turn starts inside a run. */\nexport const TurnStartedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inputMessageIds: Schema.optionalKey(Schema.Array(MessageId)),\n});\nexport type TurnStartedPayload = typeof TurnStartedPayload.Type;\nexport const TurnStartedEvent = durableEventSchema(turnStartedEventType, TurnStartedPayload);\nexport type TurnStartedEvent = typeof TurnStartedEvent.Type;\n\n/** Payload recorded when one turn completes. */\nexport const TurnCompletedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n usage: Schema.optionalKey(UsagePayload),\n});\nexport type TurnCompletedPayload = typeof TurnCompletedPayload.Type;\nexport const TurnCompletedEvent = durableEventSchema(turnCompletedEventType, TurnCompletedPayload);\nexport type TurnCompletedEvent = typeof TurnCompletedEvent.Type;\n\n/** Payload recorded when one turn fails. */\nexport const TurnFailedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n error: FailurePayload,\n});\nexport type TurnFailedPayload = typeof TurnFailedPayload.Type;\nexport const TurnFailedEvent = durableEventSchema(turnFailedEventType, TurnFailedPayload);\nexport type TurnFailedEvent = typeof TurnFailedEvent.Type;\n\n/** @deprecated Legacy payload retained for durable replay. New stops use `TurnFailedPayload` with `error.code = \"turn.interrupted\"`. */\nexport const TurnStoppedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n reason: Schema.String,\n});\n/** @deprecated Use `TurnFailedPayload` with interruption metadata. */\nexport type TurnStoppedPayload = typeof TurnStoppedPayload.Type;\n/** @deprecated Legacy event schema retained for durable replay; new producers emit `TurnFailedEvent`. */\nexport const TurnStoppedEvent = durableEventSchema(turnStoppedEventType, TurnStoppedPayload);\n/** @deprecated Use `TurnFailedEvent` with interruption metadata. */\nexport type TurnStoppedEvent = typeof TurnStoppedEvent.Type;\n\n/** Durable event union for turn lifecycle boundaries. */\nexport const TurnEvent = Schema.Union([\n TurnStartedEvent,\n TurnCompletedEvent,\n TurnFailedEvent,\n TurnStoppedEvent,\n]);\nexport type TurnEvent = typeof TurnEvent.Type;\n\n/** Event type values for durable model-inference lifecycle events. */\nexport const inferenceStartedEventType = makeEventType(\"InferenceStarted\");\nexport const inferenceCompletedEventType = makeEventType(\"InferenceCompleted\");\nexport const inferenceFailedEventType = makeEventType(\"InferenceFailed\");\n\n/** Payload recorded when one model inference starts for a turn. */\nexport const InferenceStartedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n});\nexport type InferenceStartedPayload = typeof InferenceStartedPayload.Type;\nexport const InferenceStartedEvent = durableEventSchema(\n inferenceStartedEventType,\n InferenceStartedPayload,\n);\nexport type InferenceStartedEvent = typeof InferenceStartedEvent.Type;\n\n/** Payload recorded when one model inference completes. */\nexport const InferenceCompletedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n finishReason: Schema.optionalKey(Schema.String),\n usage: Schema.optionalKey(UsagePayload),\n responseMetadata: Schema.optionalKey(Schema.Unknown),\n finishMetadata: Schema.optionalKey(Schema.Unknown),\n});\nexport type InferenceCompletedPayload = typeof InferenceCompletedPayload.Type;\nexport const InferenceCompletedEvent = durableEventSchema(\n inferenceCompletedEventType,\n InferenceCompletedPayload,\n);\nexport type InferenceCompletedEvent = typeof InferenceCompletedEvent.Type;\n\n/** Payload recorded when one model inference fails or is interrupted. */\nexport const InferenceFailedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n error: FailurePayload,\n});\nexport type InferenceFailedPayload = typeof InferenceFailedPayload.Type;\nexport const InferenceFailedEvent = durableEventSchema(\n inferenceFailedEventType,\n InferenceFailedPayload,\n);\nexport type InferenceFailedEvent = typeof InferenceFailedEvent.Type;\n\n/** Durable event union for canonical model-inference lifecycle boundaries. */\nexport const InferenceEvent = Schema.Union([\n InferenceStartedEvent,\n InferenceCompletedEvent,\n InferenceFailedEvent,\n]);\nexport type InferenceEvent = typeof InferenceEvent.Type;\n\n/** Event type values for durable tool lifecycle events. */\nexport const toolCallCreatedEventType = makeEventType(\"ToolCallCreated\");\nexport const toolCallRejectedEventType = makeEventType(\"ToolCallRejected\");\nexport const toolCallStartedEventType = makeEventType(\"ToolCallStarted\");\nexport const toolCallCompletedEventType = makeEventType(\"ToolCallCompleted\");\nexport const toolCallFailedEventType = makeEventType(\"ToolCallFailed\");\n\n/** Reason a model-requested tool call was rejected before execution. */\nexport const ToolCallRejectionReason = Schema.Literals([\"unknown-tool\", \"invalid-params\"]);\nexport type ToolCallRejectionReason = typeof ToolCallRejectionReason.Type;\n\n/** Exact synthetic tool-result feedback for a rejected model-requested tool call. */\nexport const ToolCallRejectionFeedback = Schema.Struct({\n message: Schema.String,\n reason: ToolCallRejectionReason,\n modelFeedback: Schema.NonEmptyString,\n});\nexport type ToolCallRejectionFeedback = typeof ToolCallRejectionFeedback.Type;\n\n/** Exact prompt part for a rejected model-requested tool call. */\nexport const ToolRejectionPromptPart = Schema.Struct({\n ...ToolPromptPart.fields,\n isFailure: Schema.Literal(true),\n result: ToolCallRejectionFeedback,\n});\nexport type ToolRejectionPromptPart = typeof ToolRejectionPromptPart.Type;\n\n/** Exact prompt part for a successful framework-owned tool result. */\nexport const ToolSuccessPromptPart = Schema.Struct({\n ...ToolPromptPart.fields,\n isFailure: Schema.Literal(false),\n result: Schema.Unknown,\n});\nexport type ToolSuccessPromptPart = typeof ToolSuccessPromptPart.Type;\n\n/** Exact prompt part for a failed framework-owned tool result. */\nexport const ToolFailurePromptPart = Schema.Struct({\n ...ToolPromptPart.fields,\n isFailure: Schema.Literal(true),\n result: FailurePayload,\n});\nexport type ToolFailurePromptPart = typeof ToolFailurePromptPart.Type;\n\n/** Payload recorded once streamed tool parameters validate and become executable. */\nexport const ToolCallCreatedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n toolCallId: ToolCallId,\n promptPart: ToolCallPromptPart,\n});\nexport type ToolCallCreatedPayload = typeof ToolCallCreatedPayload.Type;\nexport const ToolCallCreatedEvent = durableEventSchema(\n toolCallCreatedEventType,\n ToolCallCreatedPayload,\n);\nexport type ToolCallCreatedEvent = typeof ToolCallCreatedEvent.Type;\n\n/** Payload recorded when a model-requested tool call is not executable. */\nexport const ToolCallRejectedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n toolCallId: ToolCallId,\n promptPart: ToolRejectionPromptPart,\n});\nexport type ToolCallRejectedPayload = typeof ToolCallRejectedPayload.Type;\nexport const ToolCallRejectedEvent = durableEventSchema(\n toolCallRejectedEventType,\n ToolCallRejectedPayload,\n);\nexport type ToolCallRejectedEvent = typeof ToolCallRejectedEvent.Type;\n\n/** Payload recorded when framework-owned tool execution starts. */\nexport const ToolCallStartedPayload = Schema.Struct({ toolCallId: ToolCallId });\nexport type ToolCallStartedPayload = typeof ToolCallStartedPayload.Type;\nexport const ToolCallStartedEvent = durableEventSchema(\n toolCallStartedEventType,\n ToolCallStartedPayload,\n);\nexport type ToolCallStartedEvent = typeof ToolCallStartedEvent.Type;\n\n/** Payload recorded when a tool call completes with a result. */\nexport const ToolCallCompletedPayload = Schema.Struct({\n toolCallId: ToolCallId,\n promptPart: ToolSuccessPromptPart,\n});\nexport type ToolCallCompletedPayload = typeof ToolCallCompletedPayload.Type;\nexport const ToolCallCompletedEvent = durableEventSchema(\n toolCallCompletedEventType,\n ToolCallCompletedPayload,\n);\nexport type ToolCallCompletedEvent = typeof ToolCallCompletedEvent.Type;\n\n/** Payload recorded when a tool call fails. */\nexport const ToolCallFailedPayload = Schema.Struct({\n toolCallId: ToolCallId,\n error: Schema.optionalKey(FailurePayload),\n promptPart: ToolFailurePromptPart,\n});\nexport type ToolCallFailedPayload = typeof ToolCallFailedPayload.Type;\nexport const ToolCallFailedEvent = durableEventSchema(\n toolCallFailedEventType,\n ToolCallFailedPayload,\n);\nexport type ToolCallFailedEvent = typeof ToolCallFailedEvent.Type;\n\n/** Durable event union for tool lifecycle boundaries. */\nexport const ToolCallEvent = Schema.Union([\n ToolCallCreatedEvent,\n ToolCallRejectedEvent,\n ToolCallStartedEvent,\n ToolCallCompletedEvent,\n ToolCallFailedEvent,\n]);\nexport type ToolCallEvent = typeof ToolCallEvent.Type;\n\n/** Event type values for durable stop-control events. */\nexport const stopTurnRequestedEventType = makeEventType(\"StopTurnRequested\");\nexport const stopTurnAppliedEventType = makeEventType(\"StopTurnApplied\");\n\n/** Payload recorded when a stop command targets active or future turn work. */\nexport const StopTurnRequestedPayload = Schema.Struct({\n commandId: CommandId,\n runId: Schema.optionalKey(RunId),\n turnId: Schema.optionalKey(TurnId),\n});\nexport type StopTurnRequestedPayload = typeof StopTurnRequestedPayload.Type;\nexport const StopTurnRequestedEvent = durableEventSchema(\n stopTurnRequestedEventType,\n StopTurnRequestedPayload,\n);\nexport type StopTurnRequestedEvent = typeof StopTurnRequestedEvent.Type;\n\n/** Payload recorded when a stop request has affected runtime work. */\nexport const StopTurnAppliedPayload = Schema.Struct({\n commandId: CommandId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: Schema.optionalKey(InferenceId),\n});\nexport type StopTurnAppliedPayload = typeof StopTurnAppliedPayload.Type;\nexport const StopTurnAppliedEvent = durableEventSchema(\n stopTurnAppliedEventType,\n StopTurnAppliedPayload,\n);\nexport type StopTurnAppliedEvent = typeof StopTurnAppliedEvent.Type;\n\n/** Durable event union for stop-request lifecycle boundaries. */\nexport const StopControlEvent = Schema.Union([StopTurnRequestedEvent, StopTurnAppliedEvent]);\nexport type StopControlEvent = typeof StopControlEvent.Type;\n\n/** Event type values for durable context and compaction events. */\nexport const contextProjectedEventType = makeEventType(\"ContextProjected\");\nexport const compactionRequestedEventType = makeEventType(\"CompactionRequested\");\nexport const compactionStartedEventType = makeEventType(\"CompactionStarted\");\nexport const summaryCreatedEventType = makeEventType(\"SummaryCreated\");\nexport const compactionCompletedEventType = makeEventType(\"CompactionCompleted\");\nexport const contextRebasedEventType = makeEventType(\"ContextRebased\");\nexport const compactionFailedEventType = makeEventType(\"CompactionFailed\");\n\n/** Payload recorded when the prompt context projection advances. */\nexport const ContextProjectedPayload = Schema.Struct({\n contextVersion: ContextVersion,\n throughSeq: SequenceNumber,\n});\nexport type ContextProjectedPayload = typeof ContextProjectedPayload.Type;\nexport const ContextProjectedEvent = durableEventSchema(\n contextProjectedEventType,\n ContextProjectedPayload,\n);\nexport type ContextProjectedEvent = typeof ContextProjectedEvent.Type;\n\n/** Payload recorded when compaction is requested for a durable range. */\nexport const CompactionRequestedPayload = Schema.Struct({\n compactionId: CompactionId,\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n});\nexport type CompactionRequestedPayload = typeof CompactionRequestedPayload.Type;\nexport const CompactionRequestedEvent = durableEventSchema(\n compactionRequestedEventType,\n CompactionRequestedPayload,\n);\nexport type CompactionRequestedEvent = typeof CompactionRequestedEvent.Type;\n\n/** Payload recorded when compaction starts. */\nexport const CompactionStartedPayload = Schema.Struct({ compactionId: CompactionId });\nexport type CompactionStartedPayload = typeof CompactionStartedPayload.Type;\nexport const CompactionStartedEvent = durableEventSchema(\n compactionStartedEventType,\n CompactionStartedPayload,\n);\nexport type CompactionStartedEvent = typeof CompactionStartedEvent.Type;\n\n/** Payload recorded when a summary artifact is created. */\nexport const SummaryCreatedPayload = Schema.Struct({\n compactionId: CompactionId,\n summaryId: SummaryId,\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n summary: Schema.Unknown,\n});\nexport type SummaryCreatedPayload = typeof SummaryCreatedPayload.Type;\nexport const SummaryCreatedEvent = durableEventSchema(\n summaryCreatedEventType,\n SummaryCreatedPayload,\n);\nexport type SummaryCreatedEvent = typeof SummaryCreatedEvent.Type;\n\n/** Payload recorded when compaction completes. */\nexport const CompactionCompletedPayload = Schema.Struct({ compactionId: CompactionId });\nexport type CompactionCompletedPayload = typeof CompactionCompletedPayload.Type;\nexport const CompactionCompletedEvent = durableEventSchema(\n compactionCompletedEventType,\n CompactionCompletedPayload,\n);\nexport type CompactionCompletedEvent = typeof CompactionCompletedEvent.Type;\n\n/** Payload recorded when durable context is rebased onto a summary. */\nexport const ContextRebasedPayload = Schema.Struct({\n compactionId: CompactionId,\n summaryId: SummaryId,\n contextVersion: ContextVersion,\n retainedFromContextSeq: SequenceNumber,\n});\nexport type ContextRebasedPayload = typeof ContextRebasedPayload.Type;\nexport const ContextRebasedEvent = durableEventSchema(\n contextRebasedEventType,\n ContextRebasedPayload,\n);\nexport type ContextRebasedEvent = typeof ContextRebasedEvent.Type;\n\n/** Payload recorded when compaction fails. */\nexport const CompactionFailedPayload = Schema.Struct({\n compactionId: CompactionId,\n error: FailurePayload,\n});\nexport type CompactionFailedPayload = typeof CompactionFailedPayload.Type;\nexport const CompactionFailedEvent = durableEventSchema(\n compactionFailedEventType,\n CompactionFailedPayload,\n);\nexport type CompactionFailedEvent = typeof CompactionFailedEvent.Type;\n\n/** Durable event union for context projection and compaction boundaries. */\nexport const ContextAndCompactionEvent = Schema.Union([\n ContextProjectedEvent,\n CompactionRequestedEvent,\n CompactionStartedEvent,\n SummaryCreatedEvent,\n CompactionCompletedEvent,\n ContextRebasedEvent,\n CompactionFailedEvent,\n]);\nexport type ContextAndCompactionEvent = typeof ContextAndCompactionEvent.Type;\n\n/** Event type values for durable BaseState lifecycle events. */\nexport const baseStateRequestedEventType = makeEventType(\"BaseStateRequested\");\nexport const baseStateCreatedEventType = makeEventType(\"BaseStateCreated\");\nexport const baseStateFailedEventType = makeEventType(\"BaseStateFailed\");\n\n/** Payload recorded when durable BaseState generation is requested. */\nexport const BaseStateRequestedPayload = Schema.Struct({\n baseStateId: BaseStateId,\n requestedThroughSeq: SequenceNumber,\n});\nexport type BaseStateRequestedPayload = typeof BaseStateRequestedPayload.Type;\nexport const BaseStateRequestedEvent = durableEventSchema(\n baseStateRequestedEventType,\n BaseStateRequestedPayload,\n);\nexport type BaseStateRequestedEvent = typeof BaseStateRequestedEvent.Type;\n\n/** Payload recorded when a BaseState snapshot is created. */\nexport const BaseStateCreatedPayload = Schema.Struct({\n baseStateId: BaseStateId,\n coversThroughSeq: SequenceNumber,\n});\nexport type BaseStateCreatedPayload = typeof BaseStateCreatedPayload.Type;\nexport const BaseStateCreatedEvent = durableEventSchema(\n baseStateCreatedEventType,\n BaseStateCreatedPayload,\n);\nexport type BaseStateCreatedEvent = typeof BaseStateCreatedEvent.Type;\n\n/** Payload recorded when BaseState generation fails. */\nexport const BaseStateFailedPayload = Schema.Struct({\n baseStateId: BaseStateId,\n error: FailurePayload,\n});\nexport type BaseStateFailedPayload = typeof BaseStateFailedPayload.Type;\nexport const BaseStateFailedEvent = durableEventSchema(\n baseStateFailedEventType,\n BaseStateFailedPayload,\n);\nexport type BaseStateFailedEvent = typeof BaseStateFailedEvent.Type;\n\n/** Durable event union for BaseState lifecycle boundaries. */\nexport const BaseStateEvent = Schema.Union([\n BaseStateRequestedEvent,\n BaseStateCreatedEvent,\n BaseStateFailedEvent,\n]);\nexport type BaseStateEvent = typeof BaseStateEvent.Type;\n\n/** Built-in durable event union for framework-owned session facts. */\nexport const EDADurableEvent = Schema.Union([\n CommandEvent,\n MessageEvent,\n RunEvent,\n RecoveryEvent,\n TurnEvent,\n InferenceEvent,\n ToolCallEvent,\n StopControlEvent,\n ContextAndCompactionEvent,\n BaseStateEvent,\n]);\nexport type EDADurableEvent = typeof EDADurableEvent.Type;\n\n/** Current V1 framework durable event schema. Future versions route beside this alias. */\nexport const EDADurableEventV1 = EDADurableEvent;\nexport type EDADurableEventV1 = typeof EDADurableEventV1.Type;\n\n/** Decode one framework-owned durable event through the namespace/type/version router. */\nexport const decodeUnknownEDADurableEventSync = (input: unknown): EDADurableEvent => {\n const envelope = Schema.decodeUnknownSync(DurableEventEnvelope)(input);\n if (envelope.namespace !== effectDurableAgentNamespace) {\n throw new Error(\n `EDADurableEvent decoder only accepts namespace ${effectDurableAgentNamespace}; received ${envelope.namespace}`,\n );\n }\n\n switch (envelope.schemaVersion) {\n case schemaV1:\n return Schema.decodeUnknownSync(EDADurableEventV1)(envelope);\n default:\n throw new Error(\n `Unsupported EDA durable event schemaVersion ${envelope.schemaVersion} for ${envelope.type}`,\n );\n }\n};\n\n/** Effectful V1+ router for untrusted framework-owned durable event boundaries. */\nexport const decodeUnknownEDADurableEvent = (\n input: unknown,\n): Effect.Effect<EDADurableEvent, unknown> =>\n Effect.try({\n try: () => decodeUnknownEDADurableEventSync(input),\n catch: (error) => error,\n });\n"],"mappings":";;;;;;;;AAOA,MAAa,iBAAiB,OAAO;;AAIrC,MAAa,YAAY,OAAO;;AAIhC,MAAa,iBACX,UACG;;AAML,MAAa,iBAAiB,OAAO,eAAe,KAAK,OAAO,MAAM,gBAAgB,CAAC;;AAIvF,MAAa,gBAAgB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;;AAI9E,MAAa,kBAAkB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,EAAE,KAChF,OAAO,MAAM,iBAAiB,CAChC;;AAIA,MAAa,kBAAkB,O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CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAID,MAAa,oBAAoB;;AAIjC,MAAa,oCAAoC,UAAoC;CACnF,MAAM,WAAW,OAAO,kBAAkB,oBAAoB,EAAE,KAAK;CACrE,IAAI,SAAS,cAAc,6BACzB,MAAM,IAAI,MACR,kDAAkD,4BAA4B,aAAa,SAAS,WACtG;CAGF,QAAQ,SAAS,eAAjB;EACE,KAAK,UACH,OAAO,OAAO,kBAAkB,iBAAiB,EAAE,QAAQ;EAC7D,SACE,MAAM,IAAI,MACR,+CAA+C,SAAS,cAAc,OAAO,SAAS,MACxF;CACJ;AACF;;AAGA,MAAa,gCACX,UAEA,OAAO,IAAI;CACT,WAAW,iCAAiC,KAAK;CACjD,QAAQ,UAAU;AACpB,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reduced-state-TMi7ISla.js","names":[],"sources":["../src/domain/assert-never.ts","../src/domain/reduced-state.ts"],"sourcesContent":["const formatNeverValue = (value: never): string => {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\n/** Build the defect used when an exhaustive switch receives an impossible value. */\nexport const assertNeverError = (value: never, context: string) =>\n new Error(`Unhandled ${context}: ${formatNeverValue(value)}`);\n\n/** Throw for impossible branches in pure code after TypeScript exhaustiveness checking. */\nexport const assertNever = (value: never, context: string): never => {\n throw assertNeverError(value, context);\n};\n","import type * as Prompt from \"effect/unstable/ai/Prompt\";\n\nimport { assertNever } from \"./assert-never\";\nimport { deriveCommandQueues, emptyCommandQueues, type CommandQueues } from \"./command-queues\";\nimport {\n InferenceId,\n CommandId,\n CompactionId,\n ContextVersion,\n MessageId,\n RunId,\n SequenceNumber,\n SummaryId,\n ToolCallId,\n TurnId,\n} from \"../types/core\";\nimport {\n assistantMessageCommittedEventType,\n assistantMessageImportedEventType,\n assistantPartialCommittedEventType,\n baseStateCreatedEventType,\n baseStateFailedEventType,\n baseStateRequestedEventType,\n commandAdmittedEventType,\n commandCancelledEventType,\n commandCompletedEventType,\n commandFailedEventType,\n commandStartedEventType,\n compactionCompletedEventType,\n compactionFailedEventType,\n compactionRequestedEventType,\n compactionStartedEventType,\n contextProjectedEventType,\n effectDurableAgentNamespace,\n contextRebasedEventType,\n inferenceCompletedEventType,\n inferenceFailedEventType,\n inferenceStartedEventType,\n runCompletedEventType,\n runFailedEventType,\n runInterruptedEventType,\n runStartedEventType,\n stopTurnAppliedEventType,\n stopTurnRequestedEventType,\n steeringMessageCancelledEventType,\n steeringMessageQueuedEventType,\n userMessageSubmittedEventType,\n userMessagePromotedEventType,\n userMessageCancelledEventType,\n messageQueuePausedEventType,\n pendingMessagesPausedEventType,\n recoveryCompletedEventType,\n summaryCreatedEventType,\n systemMessageCommittedEventType,\n toolCallCompletedEventType,\n toolCallCreatedEventType,\n toolCallFailedEventType,\n toolCallRejectedEventType,\n toolCallStartedEventType,\n turnCompletedEventType,\n turnFailedEventType,\n turnStartedEventType,\n turnStoppedEventType,\n userMessageCommittedEventType,\n} from \"../types/events\";\nimport { type EDACommand as EDACommandValue, type UserMessageContent } from \"../types/commands\";\nimport type {\n AssistantMessageContent,\n EDAEventTrace,\n EDARunTrace,\n FailurePayload,\n ProviderPartId,\n RecoveryContinuation,\n SystemPromptText,\n ToolName,\n UsagePayload,\n} from \"../types/events\";\nimport type { CommittedDurableEvent } from \"../services/session-store\";\n\n/** Failure payload paired with the durable sequence that recorded it. */\nexport type LifecycleFailure = {\n readonly seq: SequenceNumber;\n readonly error: FailurePayload;\n};\n\n/** Terminal command state folded from command lifecycle events. */\nexport type CommandTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Cancelled\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Durable command lifecycle projection used for scheduling and recovery. */\nexport interface CommandRecord {\n readonly commandId: CommandId;\n readonly command?: EDACommandValue;\n readonly admittedSeq?: SequenceNumber;\n readonly admissionTrace?: EDAEventTrace;\n readonly startedSeq?: SequenceNumber;\n readonly terminal?: CommandTerminal;\n}\n\n/** Terminal run state folded from run lifecycle events. */\nexport type RunTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Interrupted\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Common wall-clock lifecycle timing folded from durable event envelopes. */\nexport interface LifecycleTiming {\n readonly startedAtMs?: number;\n readonly terminalAtMs?: number;\n readonly durationMs?: number;\n}\n\n/** Durable run lifecycle projection tying one run to its owning command ids. */\nexport interface RunRecord extends LifecycleTiming {\n readonly runId: RunId;\n readonly commandIds: ReadonlyArray<CommandId>;\n readonly startedSeq: SequenceNumber;\n readonly trace: EDARunTrace;\n readonly terminal?: RunTerminal;\n}\n\n/** Terminal turn state folded from turn lifecycle events. */\nexport type TurnTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber; readonly usage?: UsagePayload }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Stopped\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Durable turn lifecycle projection nested under a run. */\nexport interface TurnRecord extends LifecycleTiming {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly startedSeq: SequenceNumber;\n readonly terminal?: TurnTerminal;\n}\n\n/** Terminal inference state folded from inference lifecycle events. */\nexport type InferenceTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber; readonly usage?: UsagePayload }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload };\n\n/** Durable model-inference lifecycle projection nested under a turn. */\nexport interface InferenceRecord extends LifecycleTiming {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly startedSeq: SequenceNumber;\n readonly terminal?: InferenceTerminal;\n}\n\n/** Durable decision produced after a model inference seals final tool calls. */\nexport type ToolDecision =\n | {\n readonly _tag: \"Created\";\n readonly seq: SequenceNumber;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly providerPartId: ProviderPartId;\n readonly toolName: ToolName;\n readonly params: unknown;\n readonly providerExecuted: boolean;\n readonly promptPart?: Prompt.ToolCallPart;\n }\n | {\n readonly _tag: \"Rejected\";\n readonly seq: SequenceNumber;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly providerPartId: ProviderPartId;\n readonly toolName: ToolName;\n readonly reason: \"unknown-tool\" | \"invalid-params\";\n readonly modelFeedback: string;\n readonly promptPart?: Prompt.ToolResultPart;\n };\n\n/** Terminal framework-owned tool-call execution state. */\nexport type ToolTerminal =\n | {\n readonly _tag: \"Completed\";\n readonly seq: SequenceNumber;\n readonly result: unknown;\n readonly promptPart?: Prompt.ToolResultPart;\n }\n | {\n readonly _tag: \"Failed\";\n readonly seq: SequenceNumber;\n readonly error: FailurePayload;\n readonly promptPart?: Prompt.ToolResultPart;\n };\n\n/** Durable tool-call projection from decision through execution terminal. */\nexport interface ToolCallRecord extends LifecycleTiming {\n readonly toolCallId: ToolCallId;\n readonly decision?: ToolDecision;\n readonly startedSeq?: SequenceNumber;\n readonly terminal?: ToolTerminal;\n}\n\n/** Durable message-like facts folded from the event log. */\nexport type MessageRecord =\n | {\n readonly _tag: \"System\";\n readonly messageId: MessageId;\n readonly content: SystemPromptText;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n }\n | {\n readonly _tag: \"User\";\n readonly messageId: MessageId;\n readonly commandId: CommandId;\n readonly content: UserMessageContent;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n /** Present for admission-time message entities; absent on legacy committed users. */\n readonly requestedDisposition?: \"queue\" | \"steer\";\n readonly disposition?: \"queue\" | \"steer\";\n readonly promotedSeq?: SequenceNumber;\n readonly pausedSeq?: SequenceNumber;\n readonly pausedByCommandId?: CommandId;\n readonly consumedSeq?: SequenceNumber;\n readonly consumedTurnId?: TurnId;\n readonly cancelledSeq?: SequenceNumber;\n readonly cancelledByCommandId?: CommandId;\n readonly cancellationReason?: string;\n }\n | {\n readonly _tag: \"Steering\";\n readonly messageId: MessageId;\n readonly commandId: CommandId;\n readonly runId: RunId;\n readonly content: UserMessageContent;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n readonly promotedSeq?: SequenceNumber;\n readonly consumedSeq?: SequenceNumber;\n readonly consumedTurnId?: TurnId;\n readonly cancelledSeq?: SequenceNumber;\n readonly cancelledByCommandId?: CommandId;\n readonly cancellationReason?: string;\n readonly pausedSeq?: SequenceNumber;\n readonly pausedByCommandId?: CommandId;\n }\n | {\n readonly _tag: \"Assistant\";\n readonly messageId: MessageId;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n /** True when the assistant message originated outside this EDA session. */\n readonly imported?: true;\n readonly content: AssistantMessageContent;\n readonly createdAtMs?: number;\n readonly promptParts?: ReadonlyArray<Prompt.AssistantMessagePart>;\n readonly seq: SequenceNumber;\n }\n | {\n readonly _tag: \"AssistantPartial\";\n readonly messageId: MessageId;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly content: AssistantMessageContent;\n readonly createdAtMs?: number;\n readonly promptParts?: ReadonlyArray<Prompt.AssistantMessagePart>;\n readonly reason: string;\n readonly seq: SequenceNumber;\n };\n\n/** Terminal compaction state folded from compaction lifecycle events. */\nexport type CompactionTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload };\n\n/** Durable compaction lifecycle projection and its produced summary cursor. */\nexport interface CompactionRecord {\n readonly compactionId: CompactionId;\n readonly requestedSeq?: SequenceNumber;\n readonly startedSeq?: SequenceNumber;\n readonly summaryCreatedSeq?: SequenceNumber;\n readonly summaryId?: SummaryId;\n readonly sourceFromSeq?: SequenceNumber;\n readonly sourceToSeq?: SequenceNumber;\n readonly rebasedSeq?: SequenceNumber;\n readonly contextVersion?: ContextVersion;\n readonly terminal?: CompactionTerminal;\n}\n\n/** Current model-context version and summary selected by compaction. */\nexport interface ContextRecord {\n readonly version: ContextVersion;\n readonly currentSummaryId?: SummaryId;\n}\n\n/** Durable StopTurn request and the lifecycle boundary it eventually applied to. */\nexport interface StopRequestRecord {\n readonly commandId: CommandId;\n readonly requestedSeq: SequenceNumber;\n readonly requestedRunId?: RunId;\n readonly requestedTurnId?: TurnId;\n readonly appliedSeq?: SequenceNumber;\n readonly appliedRunId?: RunId;\n readonly appliedTurnId?: TurnId;\n readonly appliedInferenceId?: InferenceId;\n}\n\n/** Rolling session totals for provider-reported model token usage. */\nexport interface TokenUsageTotals {\n readonly inputTokens: number;\n readonly cachedInputTokens: number;\n readonly outputTokens: number;\n readonly textTokens: number;\n readonly reasoningTokens: number;\n}\n\n/** First-party token consumption metadata folded by the framework reducer. */\nexport interface TokenConsumptionState {\n readonly total: TokenUsageTotals;\n}\n\n/** Admitted command that has not yet crossed the `CommandStarted` boundary. */\nexport interface PendingCommand {\n /** Lifecycle ID for the admitted command. */\n readonly commandId: CommandId;\n /** Typed command payload admitted durably. */\n readonly command: EDACommandValue;\n /** Admission sequence used for deterministic FIFO/control ordering. */\n readonly admittedSeq: SequenceNumber;\n /** Trace context captured at the durable command admission boundary. */\n readonly admissionTrace?: EDAEventTrace;\n}\n\n/** Started command without a terminal command boundary, optionally tied to an open run. */\nexport interface ActiveCommandEvidence {\n readonly commandId: CommandId;\n readonly runId?: RunId;\n}\n\n/** Active run/turn/inference identity derived from unfinished lifecycle records. */\nexport type ActiveTurnIdentity = {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId?: InferenceId;\n};\n\n/** Canonical durable replay product used by queries, recovery, and scheduling. */\nexport interface ReducedState {\n readonly lastSeq: SequenceNumber;\n readonly commands: ReadonlyMap<CommandId, CommandRecord>;\n readonly runs: ReadonlyMap<RunId, RunRecord>;\n /** Explicit startup-recovery links keyed by replacement physical run id. */\n readonly recoveryContinuations: ReadonlyMap<RunId, RecoveryContinuationRecord>;\n readonly turns: ReadonlyMap<TurnId, TurnRecord>;\n readonly inferences: ReadonlyMap<InferenceId, InferenceRecord>;\n readonly toolCalls: ReadonlyMap<ToolCallId, ToolCallRecord>;\n readonly messages: ReadonlyMap<MessageId, MessageRecord>;\n readonly stopRequests: ReadonlyMap<CommandId, StopRequestRecord>;\n readonly compactions: ReadonlyMap<CompactionId, CompactionRecord>;\n readonly context: ContextRecord;\n /** Rolling model-token usage totals derived from completed provider inferences. */\n readonly tokenConsumption: TokenConsumptionState;\n /** Materialized scheduler queues derived from the maps above after every fold. */\n readonly commandQueues: CommandQueues;\n}\n\n/** Durable recovery continuation plus the sequence of its completion barrier. */\nexport interface RecoveryContinuationRecord extends RecoveryContinuation {\n readonly seq: SequenceNumber;\n}\n\n/** Unfinished lifecycle records requiring deterministic startup recovery. */\nexport interface RecoverableWork {\n readonly activeCommands: ReadonlyArray<CommandRecord>;\n readonly activeRuns: ReadonlyArray<RunRecord>;\n readonly activeTurns: ReadonlyArray<TurnRecord>;\n readonly activeInferences: ReadonlyArray<InferenceRecord>;\n readonly openToolCalls: ReadonlyArray<ToolCallRecord>;\n readonly runningToolCalls: ReadonlyArray<ToolCallRecord>;\n readonly pendingStopRequests: ReadonlyArray<StopRequestRecord>;\n readonly openCompactions: ReadonlyArray<CompactionRecord>;\n}\n\nconst emptyTokenUsageTotals: TokenUsageTotals = {\n inputTokens: 0,\n cachedInputTokens: 0,\n outputTokens: 0,\n textTokens: 0,\n reasoningTokens: 0,\n};\n\nconst emptyTokenConsumptionState: TokenConsumptionState = {\n total: emptyTokenUsageTotals,\n};\n\n/** Empty durable replay state before any session event has committed. */\nexport const initialReducedState: ReducedState = {\n lastSeq: SequenceNumber.make(0),\n commands: new Map(),\n runs: new Map(),\n recoveryContinuations: new Map(),\n turns: new Map(),\n inferences: new Map(),\n toolCalls: new Map(),\n messages: new Map(),\n stopRequests: new Map(),\n compactions: new Map(),\n context: { version: ContextVersion.make(0) },\n tokenConsumption: emptyTokenConsumptionState,\n commandQueues: emptyCommandQueues,\n};\n\n/** Reserved reducer checkpoint name for the framework-owned `ReducedState`. */\nexport const frameworkReducedStateReducerName = \"_eda.framework.reduced-state\";\n\n/** Schema version for the framework-owned `ReducedState` checkpoint payload. */\nexport const frameworkReducedStateReducerSchemaVersion = 5;\n\n/** JSON payload stored for the framework-owned reduced-state reducer checkpoint. */\nexport type ReducedStateCheckpointCommandRecord = Omit<CommandRecord, \"command\">;\n\ntype SystemMessageRecord = Extract<MessageRecord, { readonly _tag: \"System\" }>;\ntype UserMessageRecord = Extract<MessageRecord, { readonly _tag: \"User\" }>;\ntype SteeringMessageRecord = Extract<MessageRecord, { readonly _tag: \"Steering\" }>;\ntype AssistantMessageRecord = Extract<MessageRecord, { readonly _tag: \"Assistant\" }>;\ntype AssistantPartialMessageRecord = Extract<MessageRecord, { readonly _tag: \"AssistantPartial\" }>;\n\nexport type ReducedStateCheckpointMessageRecord =\n | Omit<SystemMessageRecord, \"content\">\n | Omit<UserMessageRecord, \"content\">\n | Omit<SteeringMessageRecord, \"content\">\n | Omit<AssistantMessageRecord, \"content\" | \"promptParts\">\n | Omit<AssistantPartialMessageRecord, \"content\" | \"promptParts\">;\n\ntype CreatedToolDecision = Extract<ToolDecision, { readonly _tag: \"Created\" }>;\ntype RejectedToolDecision = Extract<ToolDecision, { readonly _tag: \"Rejected\" }>;\ntype CompletedToolTerminal = Extract<ToolTerminal, { readonly _tag: \"Completed\" }>;\ntype FailedToolTerminal = Extract<ToolTerminal, { readonly _tag: \"Failed\" }>;\n\nexport type ReducedStateCheckpointToolDecision =\n | Omit<CreatedToolDecision, \"params\" | \"promptPart\">\n | Omit<RejectedToolDecision, \"promptPart\">;\n\nexport type ReducedStateCheckpointToolTerminal =\n | Omit<CompletedToolTerminal, \"result\" | \"promptPart\">\n | Omit<FailedToolTerminal, \"error\" | \"promptPart\">;\n\nexport interface ReducedStateCheckpointToolCallRecord extends Omit<\n ToolCallRecord,\n \"decision\" | \"terminal\"\n> {\n readonly decision?: ReducedStateCheckpointToolDecision;\n readonly terminal?: ReducedStateCheckpointToolTerminal;\n}\n\nexport interface ReducedStateCheckpointPayload {\n readonly lastSeq: SequenceNumber;\n readonly commands: ReadonlyArray<readonly [CommandId, ReducedStateCheckpointCommandRecord]>;\n readonly runs: ReadonlyArray<readonly [RunId, RunRecord]>;\n readonly recoveryContinuations?: ReadonlyArray<readonly [RunId, RecoveryContinuationRecord]>;\n readonly turns: ReadonlyArray<readonly [TurnId, TurnRecord]>;\n readonly inferences: ReadonlyArray<readonly [InferenceId, InferenceRecord]>;\n readonly toolCalls: ReadonlyArray<readonly [ToolCallId, ReducedStateCheckpointToolCallRecord]>;\n readonly messages: ReadonlyArray<readonly [MessageId, ReducedStateCheckpointMessageRecord]>;\n readonly stopRequests: ReadonlyArray<readonly [CommandId, StopRequestRecord]>;\n readonly compactions: ReadonlyArray<readonly [CompactionId, CompactionRecord]>;\n readonly context: ContextRecord;\n readonly tokenConsumption?: TokenConsumptionState;\n}\n\n/** Encode the framework reducer state into a pointer-based JSON-safe checkpoint payload. */\nexport const encodeReducedStateCheckpoint = (\n state: ReducedState,\n): ReducedStateCheckpointPayload => ({\n lastSeq: state.lastSeq,\n commands: Array.from(state.commands.entries()).map(([commandId, record]) => [\n commandId,\n encodeCheckpointCommandRecord(record),\n ]),\n runs: Array.from(state.runs.entries()),\n recoveryContinuations: Array.from(state.recoveryContinuations.entries()),\n turns: Array.from(state.turns.entries()),\n inferences: Array.from(state.inferences.entries()),\n toolCalls: Array.from(state.toolCalls.entries()).map(([toolCallId, record]) => [\n toolCallId,\n encodeCheckpointToolCallRecord(record),\n ]),\n messages: Array.from(state.messages.entries()).map(([messageId, record]) => [\n messageId,\n encodeCheckpointMessageRecord(record),\n ]),\n stopRequests: Array.from(state.stopRequests.entries()),\n compactions: Array.from(state.compactions.entries()),\n context: state.context,\n tokenConsumption: state.tokenConsumption,\n});\n\n/** Event-log positions required to hydrate a pointer-based framework checkpoint. */\nexport const reducedStateCheckpointEventSeqs = (\n payload: unknown,\n): ReadonlyArray<SequenceNumber> => {\n const checkpoint = payload as ReducedStateCheckpointPayload;\n const seqs: Array<SequenceNumber> = [];\n for (const [, record] of checkpoint.commands ?? []) {\n if (record.admittedSeq !== undefined) {\n seqs.push(record.admittedSeq);\n }\n }\n for (const [, record] of checkpoint.messages ?? []) {\n seqs.push(record.seq);\n }\n for (const [, record] of checkpoint.toolCalls ?? []) {\n if (record.decision !== undefined) {\n seqs.push(record.decision.seq);\n }\n if (\n record.terminal !== undefined &&\n (record.terminal._tag === \"Completed\" || record.terminal._tag === \"Failed\")\n ) {\n seqs.push(record.terminal.seq);\n }\n }\n return uniqueSequenceNumbers(seqs);\n};\n\n/** Decode the framework reducer checkpoint and rebuild derived scheduler queues. */\nexport const decodeReducedStateCheckpoint = (\n payload: unknown,\n referencedEvents: ReadonlyArray<CommittedDurableEvent>,\n): ReducedState => {\n const checkpoint = payload as ReducedStateCheckpointPayload;\n const eventsBySeq = committedEventMapBySeq(referencedEvents);\n const commands = decodeCheckpointCommandRecords(checkpoint.commands ?? [], eventsBySeq);\n const runs = new Map(checkpoint.runs ?? []);\n const messages = decodeCheckpointMessageRecords(checkpoint.messages ?? [], eventsBySeq);\n return {\n lastSeq: SequenceNumber.make(Number(checkpoint.lastSeq ?? 0)),\n commands,\n runs,\n recoveryContinuations: new Map(checkpoint.recoveryContinuations ?? []),\n turns: new Map(checkpoint.turns ?? []),\n inferences: new Map(checkpoint.inferences ?? []),\n toolCalls: decodeCheckpointToolCallRecords(checkpoint.toolCalls ?? [], eventsBySeq),\n messages,\n stopRequests: new Map(checkpoint.stopRequests ?? []),\n compactions: new Map(checkpoint.compactions ?? []),\n context: checkpoint.context ?? { version: ContextVersion.make(0) },\n tokenConsumption: decodeTokenConsumptionState(checkpoint.tokenConsumption),\n commandQueues: deriveCommandQueues({ commands, runs, messages }),\n };\n};\n\nconst encodeCheckpointCommandRecord = (\n record: CommandRecord,\n): ReducedStateCheckpointCommandRecord => {\n const { command: _command, ...checkpoint } = record;\n return checkpoint;\n};\n\nconst encodeCheckpointMessageRecord = (\n record: MessageRecord,\n): ReducedStateCheckpointMessageRecord => {\n switch (record._tag) {\n case \"System\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"User\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"Steering\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"Assistant\": {\n const { content: _content, promptParts: _promptParts, ...checkpoint } = record;\n return checkpoint;\n }\n case \"AssistantPartial\": {\n const { content: _content, promptParts: _promptParts, ...checkpoint } = record;\n return checkpoint;\n }\n default:\n return assertNever(record, \"checkpoint message record\");\n }\n};\n\nconst encodeCheckpointToolCallRecord = (\n record: ToolCallRecord,\n): ReducedStateCheckpointToolCallRecord => ({\n toolCallId: record.toolCallId,\n ...(record.decision === undefined\n ? {}\n : { decision: encodeCheckpointToolDecision(record.decision) }),\n ...(record.durationMs === undefined ? {} : { durationMs: record.durationMs }),\n ...(record.startedAtMs === undefined ? {} : { startedAtMs: record.startedAtMs }),\n ...(record.startedSeq === undefined ? {} : { startedSeq: record.startedSeq }),\n ...(record.terminalAtMs === undefined ? {} : { terminalAtMs: record.terminalAtMs }),\n ...(record.terminal === undefined\n ? {}\n : { terminal: encodeCheckpointToolTerminal(record.terminal) }),\n});\n\nconst encodeCheckpointToolDecision = (\n decision: ToolDecision,\n): ReducedStateCheckpointToolDecision => {\n switch (decision._tag) {\n case \"Created\": {\n const { params: _params, promptPart: _promptPart, ...checkpoint } = decision;\n return checkpoint;\n }\n case \"Rejected\": {\n const { promptPart: _promptPart, ...checkpoint } = decision;\n return checkpoint;\n }\n default:\n return assertNever(decision, \"checkpoint tool decision\");\n }\n};\n\nconst encodeCheckpointToolTerminal = (\n terminal: ToolTerminal,\n): ReducedStateCheckpointToolTerminal => {\n switch (terminal._tag) {\n case \"Completed\": {\n const { result: _result, promptPart: _promptPart, ...checkpoint } = terminal;\n return checkpoint;\n }\n case \"Failed\": {\n const { error: _error, promptPart: _promptPart, ...checkpoint } = terminal;\n return checkpoint;\n }\n default:\n return assertNever(terminal, \"checkpoint tool terminal\");\n }\n};\n\nconst decodeCheckpointCommandRecords = (\n records: ReducedStateCheckpointPayload[\"commands\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<CommandId, CommandRecord> =>\n new Map(\n records.map(([commandId, record]) => {\n if (record.admittedSeq === undefined) {\n return [commandId, record];\n }\n const admitted = reduceSingleCheckpointEvent(\n eventsBySeq,\n record.admittedSeq,\n commandAdmittedEventType,\n ).commands.get(commandId);\n if (admitted?.command === undefined) {\n throw new Error(`Checkpoint command ${commandId} missing admission payload`);\n }\n return [commandId, { ...record, command: admitted.command }];\n }),\n );\n\nconst decodeCheckpointMessageRecords = (\n records: ReducedStateCheckpointPayload[\"messages\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<MessageId, MessageRecord> =>\n new Map(\n records.map(([messageId, record]) => {\n const message = reduceSingleCheckpointEvent(\n eventsBySeq,\n record.seq,\n checkpointMessageEventType(record),\n ).messages.get(messageId);\n if (message === undefined) {\n throw new Error(`Checkpoint message ${messageId} missing message payload`);\n }\n return [messageId, { ...message, ...record } as MessageRecord];\n }),\n );\n\nconst decodeCheckpointToolCallRecords = (\n records: ReducedStateCheckpointPayload[\"toolCalls\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<ToolCallId, ToolCallRecord> =>\n new Map(\n records.map(([toolCallId, record]) => [\n toolCallId,\n {\n toolCallId,\n ...(record.decision === undefined\n ? {}\n : { decision: decodeCheckpointToolDecision(toolCallId, record.decision, eventsBySeq) }),\n ...(record.durationMs === undefined ? {} : { durationMs: record.durationMs }),\n ...(record.startedAtMs === undefined ? {} : { startedAtMs: record.startedAtMs }),\n ...(record.startedSeq === undefined ? {} : { startedSeq: record.startedSeq }),\n ...(record.terminalAtMs === undefined ? {} : { terminalAtMs: record.terminalAtMs }),\n ...(record.terminal === undefined\n ? {}\n : { terminal: decodeCheckpointToolTerminal(toolCallId, record.terminal, eventsBySeq) }),\n },\n ]),\n );\n\nconst decodeCheckpointToolDecision = (\n toolCallId: ToolCallId,\n decision: ReducedStateCheckpointToolDecision,\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ToolDecision => {\n const hydrated = reduceSingleCheckpointEvent(\n eventsBySeq,\n decision.seq,\n decision._tag === \"Created\" ? toolCallCreatedEventType : toolCallRejectedEventType,\n ).toolCalls.get(toolCallId)?.decision;\n if (hydrated === undefined || hydrated._tag !== decision._tag) {\n throw new Error(`Checkpoint tool decision ${toolCallId} missing ${decision._tag} payload`);\n }\n return hydrated;\n};\n\nconst decodeCheckpointToolTerminal = (\n toolCallId: ToolCallId,\n terminal: ReducedStateCheckpointToolTerminal,\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ToolTerminal => {\n const hydrated = reduceSingleCheckpointEvent(\n eventsBySeq,\n terminal.seq,\n terminal._tag === \"Completed\" ? toolCallCompletedEventType : toolCallFailedEventType,\n ).toolCalls.get(toolCallId)?.terminal;\n if (hydrated === undefined || hydrated._tag !== terminal._tag) {\n throw new Error(`Checkpoint tool terminal ${toolCallId} missing ${terminal._tag} payload`);\n }\n return hydrated;\n};\n\nconst checkpointMessageEventType = (record: ReducedStateCheckpointMessageRecord) => {\n switch (record._tag) {\n case \"System\":\n return systemMessageCommittedEventType;\n case \"User\":\n return record.requestedDisposition === undefined\n ? userMessageCommittedEventType\n : userMessageSubmittedEventType;\n case \"Steering\":\n return steeringMessageQueuedEventType;\n case \"Assistant\":\n return record.imported === true\n ? assistantMessageImportedEventType\n : assistantMessageCommittedEventType;\n case \"AssistantPartial\":\n return assistantPartialCommittedEventType;\n default:\n return assertNever(record, \"checkpoint message type\");\n }\n};\n\nconst reduceSingleCheckpointEvent = (\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n seq: SequenceNumber,\n expectedType: string,\n): ReducedState => {\n const event = eventsBySeq.get(Number(seq));\n if (event === undefined) {\n throw new Error(`Checkpoint reference seq ${seq} is missing`);\n }\n if (event.event.type !== expectedType) {\n throw new Error(\n `Checkpoint reference seq ${seq} expected ${expectedType}; got ${event.event.type}`,\n );\n }\n return foldReducedState(initialReducedState, [event]);\n};\n\nconst committedEventMapBySeq = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<number, CommittedDurableEvent> =>\n new Map(events.map((event) => [Number(event.position.seq), event]));\n\nconst uniqueSequenceNumbers = (\n seqs: ReadonlyArray<SequenceNumber>,\n): ReadonlyArray<SequenceNumber> =>\n Array.from(new Set(seqs.map((seq) => Number(seq))))\n .sort((left, right) => left - right)\n .map((seq) => SequenceNumber.make(seq));\n\nconst decodeTokenConsumptionState = (\n value: TokenConsumptionState | undefined,\n): TokenConsumptionState => ({\n total: {\n inputTokens: nonNegativeNumber(value?.total?.inputTokens),\n cachedInputTokens: nonNegativeNumber(value?.total?.cachedInputTokens),\n outputTokens: nonNegativeNumber(value?.total?.outputTokens),\n textTokens: nonNegativeNumber(value?.total?.textTokens),\n reasoningTokens: nonNegativeNumber(value?.total?.reasoningTokens),\n },\n});\n\n/** Fold newly committed durable events into the canonical replay state. */\nexport const foldReducedState = (\n state: ReducedState,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): ReducedState => {\n let lastSeq = state.lastSeq;\n const commands = new Map(state.commands);\n const runs = new Map(state.runs);\n const recoveryContinuations = new Map(state.recoveryContinuations);\n const turns = new Map(state.turns);\n const inferences = new Map(state.inferences);\n const toolCalls = new Map(state.toolCalls);\n const messages = new Map(state.messages);\n const stopRequests = new Map(state.stopRequests);\n const compactions = new Map(state.compactions);\n let context = state.context;\n let tokenConsumption = state.tokenConsumption;\n\n for (const entry of committed) {\n lastSeq = entry.position.seq;\n const { event } = entry;\n if (event.namespace !== effectDurableAgentNamespace) {\n continue;\n }\n\n const payload = event.payload as any;\n const seq = entry.position.seq;\n const eventCreatedAtMs = Number(event.createdAtMs);\n\n switch (event.type) {\n case commandAdmittedEventType: {\n const { command } = payload;\n const commandId = requireAdmittedCommandId(command);\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n admittedSeq: seq,\n admissionTrace: event.trace,\n command,\n }));\n break;\n }\n case commandStartedEventType: {\n const { commandId } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({ ...record, startedSeq: seq }));\n break;\n }\n case commandCompletedEventType: {\n const { commandId } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Completed\", seq } as CommandTerminal,\n }));\n break;\n }\n case commandFailedEventType: {\n const { commandId, error } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Failed\", seq, error } as CommandTerminal,\n }));\n break;\n }\n case commandCancelledEventType: {\n const { commandId, reason } = payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Cancelled\", seq, reason } as CommandTerminal,\n }));\n break;\n }\n case runStartedEventType: {\n const { runId, commandIds, trace } = payload;\n const terminal = runs.get(runId)?.terminal;\n runs.set(runId, {\n runId,\n commandIds,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n trace,\n ...(terminal === undefined ? {} : { terminal }),\n });\n break;\n }\n case runCompletedEventType: {\n const { runId } = payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Completed\", seq } as RunTerminal,\n }));\n break;\n }\n case runFailedEventType: {\n const { runId, error } = payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as RunTerminal,\n }));\n break;\n }\n case runInterruptedEventType: {\n const { runId, reason } = payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Interrupted\", seq, reason } as RunTerminal,\n }));\n break;\n }\n case turnStartedEventType: {\n const { runId, turnId, inputMessageIds } = payload;\n const terminal = turns.get(turnId)?.terminal;\n turns.set(turnId, {\n runId,\n turnId,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n ...(terminal === undefined ? {} : { terminal }),\n });\n for (const messageId of inputMessageIds ?? []) {\n const message = messages.get(messageId);\n if (message?._tag === \"Steering\" || message?._tag === \"User\") {\n messages.set(messageId, { ...message, consumedSeq: seq, consumedTurnId: turnId });\n }\n }\n break;\n }\n case turnCompletedEventType: {\n const { turnId, usage } = payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n ...(usage === undefined ? {} : { usage }),\n } as TurnTerminal,\n }));\n break;\n }\n case turnFailedEventType: {\n const { turnId, error } = payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as TurnTerminal,\n }));\n break;\n }\n case turnStoppedEventType: {\n const { turnId, reason } = payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Stopped\", seq, reason } as TurnTerminal,\n }));\n break;\n }\n case inferenceStartedEventType: {\n const { runId, turnId, inferenceId } = payload;\n const terminal = inferences.get(inferenceId)?.terminal;\n inferences.set(inferenceId, {\n runId,\n turnId,\n inferenceId: inferenceId,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n ...(terminal === undefined ? {} : { terminal }),\n });\n break;\n }\n case inferenceCompletedEventType: {\n const { inferenceId, usage } = payload;\n const previouslyCompleted = inferences.get(inferenceId)?.terminal?._tag === \"Completed\";\n updateExisting(inferences, inferenceId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n ...(usage === undefined ? {} : { usage }),\n } as InferenceTerminal,\n }));\n if (!previouslyCompleted && inferences.get(inferenceId)?.terminal?._tag === \"Completed\") {\n tokenConsumption = addTokenUsage(tokenConsumption, usage);\n }\n break;\n }\n case inferenceFailedEventType: {\n const { inferenceId, error } = payload;\n updateExisting(inferences, inferenceId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as InferenceTerminal,\n }));\n break;\n }\n case toolCallCreatedEventType: {\n const { runId, turnId, inferenceId, toolCallId, promptPart } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n decision: {\n _tag: \"Created\",\n seq,\n runId,\n turnId,\n inferenceId: inferenceId,\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n params: promptPart.params,\n providerExecuted: promptPart.providerExecuted,\n promptPart,\n } as ToolDecision,\n }));\n break;\n }\n case toolCallRejectedEventType: {\n const { runId, turnId, inferenceId, toolCallId, promptPart } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n decision: {\n _tag: \"Rejected\",\n seq,\n runId,\n turnId,\n inferenceId: inferenceId,\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n reason: promptPart.result.reason,\n modelFeedback: promptPart.result.modelFeedback,\n promptPart,\n } as ToolDecision,\n }));\n break;\n }\n case toolCallStartedEventType: {\n const { toolCallId } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n }));\n break;\n }\n case toolCallCompletedEventType: {\n const { toolCallId, promptPart } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n result: promptPart.result,\n promptPart,\n } as ToolTerminal,\n }));\n break;\n }\n case toolCallFailedEventType: {\n const { toolCallId, promptPart, error } = payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Failed\",\n seq,\n error: error ?? promptPart.result,\n promptPart,\n } as ToolTerminal,\n }));\n break;\n }\n case systemMessageCommittedEventType: {\n const { messageId, content } = payload;\n messages.set(messageId, {\n _tag: \"System\",\n messageId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessageCommittedEventType: {\n const { commandId, messageId, content } = payload;\n messages.set(messageId, {\n _tag: \"User\",\n messageId,\n commandId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessageSubmittedEventType: {\n const { commandId, messageId, disposition: requestedDisposition, content } = payload;\n messages.set(messageId, {\n _tag: \"User\",\n messageId,\n commandId,\n content,\n requestedDisposition,\n disposition: requestedDisposition,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessagePromotedEventType: {\n const { messageId } = payload;\n const message = messages.get(messageId);\n if (\n (message?._tag === \"User\" && message.disposition === \"queue\") ||\n (message?._tag === \"Steering\" && message.pausedByCommandId !== undefined)\n ) {\n const {\n pausedByCommandId: _pausedByCommandId,\n pausedSeq: _pausedSeq,\n ...unpausedMessage\n } = message;\n messages.set(messageId, {\n ...unpausedMessage,\n ...(message._tag === \"User\" ? { disposition: \"steer\" as const } : {}),\n promotedSeq: seq,\n });\n }\n break;\n }\n case userMessageCancelledEventType: {\n const { commandId, messageId, reason } = payload;\n const message = messages.get(messageId);\n if (message?._tag === \"User\" || message?._tag === \"Steering\") {\n messages.set(messageId, {\n ...message,\n cancelledSeq: seq,\n cancelledByCommandId: commandId,\n cancellationReason: reason,\n });\n }\n break;\n }\n case messageQueuePausedEventType:\n case pendingMessagesPausedEventType: {\n const messageIds = payload.messageIds;\n const interruptionCommandId =\n event.type === messageQueuePausedEventType\n ? payload.stopCommandId\n : payload.interruptionCommandId;\n for (const messageId of messageIds) {\n const message = messages.get(messageId);\n if (\n (message?._tag === \"User\" || message?._tag === \"Steering\") &&\n message.consumedSeq === undefined &&\n message.cancelledSeq === undefined\n ) {\n messages.set(messageId, {\n ...message,\n ...(message._tag === \"User\" ? { disposition: \"queue\" as const } : {}),\n pausedSeq: seq,\n pausedByCommandId: interruptionCommandId,\n });\n }\n }\n break;\n }\n case steeringMessageQueuedEventType: {\n const { commandId, messageId, runId, content } = payload;\n messages.set(messageId, {\n _tag: \"Steering\",\n messageId,\n commandId,\n runId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case steeringMessageCancelledEventType: {\n const { messageId, reason } = payload;\n const message = messages.get(messageId);\n if (message?._tag === \"Steering\") {\n messages.set(messageId, { ...message, cancelledSeq: seq, cancellationReason: reason });\n }\n break;\n }\n case assistantMessageCommittedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = payload;\n messages.set(messageId, {\n _tag: \"Assistant\",\n messageId,\n runId,\n turnId,\n inferenceId: inferenceId,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n seq,\n });\n break;\n }\n case assistantMessageImportedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = payload;\n messages.set(messageId, {\n _tag: \"Assistant\",\n messageId,\n runId,\n turnId,\n inferenceId,\n imported: true,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n seq,\n });\n break;\n }\n case assistantPartialCommittedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts, reason } = payload;\n messages.set(messageId, {\n _tag: \"AssistantPartial\",\n messageId,\n runId,\n turnId,\n inferenceId: inferenceId,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n reason,\n seq,\n });\n break;\n }\n case stopTurnRequestedEventType: {\n const { commandId, runId, turnId } = payload;\n stopRequests.set(commandId, {\n commandId,\n requestedSeq: seq,\n ...(runId === undefined ? {} : { requestedRunId: runId }),\n ...(turnId === undefined ? {} : { requestedTurnId: turnId }),\n ...appliedFields(stopRequests.get(commandId)),\n });\n break;\n }\n case stopTurnAppliedEventType: {\n const { commandId, runId, turnId, inferenceId } = payload;\n const existing = stopRequests.get(commandId);\n stopRequests.set(commandId, {\n commandId,\n requestedSeq: existing?.requestedSeq ?? seq,\n ...(existing?.requestedRunId === undefined\n ? {}\n : { requestedRunId: existing.requestedRunId }),\n ...(existing?.requestedTurnId === undefined\n ? {}\n : { requestedTurnId: existing.requestedTurnId }),\n appliedSeq: seq,\n appliedRunId: runId,\n appliedTurnId: turnId,\n ...(inferenceId === undefined ? {} : { appliedInferenceId: inferenceId }),\n });\n break;\n }\n case contextProjectedEventType: {\n const { contextVersion } = payload;\n context = { ...context, version: contextVersion };\n break;\n }\n case compactionRequestedEventType: {\n const { compactionId, sourceFromSeq, sourceToSeq } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n requestedSeq: seq,\n sourceFromSeq,\n sourceToSeq,\n }));\n break;\n }\n case compactionStartedEventType: {\n const { compactionId } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n startedSeq: seq,\n }));\n break;\n }\n case summaryCreatedEventType: {\n const { compactionId, summaryId, sourceFromSeq, sourceToSeq } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n summaryCreatedSeq: seq,\n summaryId,\n sourceFromSeq,\n sourceToSeq,\n }));\n break;\n }\n case contextRebasedEventType: {\n const { compactionId, summaryId, contextVersion, retainedFromContextSeq } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n summaryId,\n rebasedSeq: seq,\n contextVersion,\n }));\n pruneForContextRebase(\n {\n commands,\n runs,\n recoveryContinuations,\n turns,\n inferences,\n toolCalls,\n messages,\n stopRequests,\n compactions,\n },\n retainedFromContextSeq,\n summaryId,\n );\n context = {\n version: contextVersion,\n currentSummaryId: summaryId,\n };\n break;\n }\n case compactionCompletedEventType: {\n const { compactionId } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n terminal: { _tag: \"Completed\", seq } as CompactionTerminal,\n }));\n break;\n }\n case compactionFailedEventType: {\n const { compactionId, error } = payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n terminal: { _tag: \"Failed\", seq, error } as CompactionTerminal,\n }));\n const failed = compactions.get(compactionId);\n if (failed?.summaryId === undefined || failed.summaryId !== context.currentSummaryId) {\n compactions.delete(compactionId);\n }\n break;\n }\n case recoveryCompletedEventType: {\n const { continuation } = payload;\n if (continuation !== undefined) {\n recoveryContinuations.set(continuation.replacementRunId, { ...continuation, seq });\n }\n break;\n }\n case baseStateRequestedEventType:\n case baseStateCreatedEventType:\n case baseStateFailedEventType:\n break;\n default:\n assertNever(event as never, \"reduced-state durable event\");\n }\n }\n\n return {\n lastSeq,\n commands,\n runs,\n recoveryContinuations,\n turns,\n inferences,\n toolCalls,\n messages,\n stopRequests,\n compactions,\n context,\n tokenConsumption,\n commandQueues: deriveCommandQueues({ commands, runs, messages }),\n };\n};\n\n/** Fold committed events from genesis into a fresh `ReducedState`. */\nexport const reduceCommittedEvents = (committed: ReadonlyArray<CommittedDurableEvent>) =>\n foldReducedState(initialReducedState, committed);\n\nconst addTokenUsage = (\n state: TokenConsumptionState,\n usage: UsagePayload | undefined,\n): TokenConsumptionState => {\n if (usage === undefined) {\n return state;\n }\n return {\n total: {\n inputTokens: state.total.inputTokens + tokenCount(usage.inputTokens),\n cachedInputTokens: state.total.cachedInputTokens + tokenCount(usage.cachedInputTokens),\n outputTokens: state.total.outputTokens + tokenCount(usage.outputTokens),\n textTokens: state.total.textTokens + tokenCount(usage.textTokens),\n reasoningTokens: state.total.reasoningTokens + tokenCount(usage.reasoningTokens),\n },\n };\n};\n\nconst tokenCount = (value: number | undefined): number => nonNegativeNumber(value);\n\nconst nonNegativeNumber = (value: number | undefined): number =>\n value === undefined || !Number.isFinite(value) ? 0 : Math.max(0, Math.trunc(value));\n\ninterface MutableReplayMaps {\n readonly commands: Map<CommandId, CommandRecord>;\n readonly runs: Map<RunId, RunRecord>;\n readonly recoveryContinuations: Map<RunId, RecoveryContinuationRecord>;\n readonly turns: Map<TurnId, TurnRecord>;\n readonly inferences: Map<InferenceId, InferenceRecord>;\n readonly toolCalls: Map<ToolCallId, ToolCallRecord>;\n readonly messages: Map<MessageId, MessageRecord>;\n readonly stopRequests: Map<CommandId, StopRequestRecord>;\n readonly compactions: Map<CompactionId, CompactionRecord>;\n}\n\n/** Drop runtime state made model-invisible by a context rebase; storage remains append-only. */\nconst pruneForContextRebase = (\n maps: MutableReplayMaps,\n retainedFromContextSeq: SequenceNumber,\n currentSummaryId: SummaryId,\n): void => {\n for (const [messageId, message] of maps.messages) {\n if (message._tag !== \"System\" && messagePruneSeq(message) < retainedFromContextSeq) {\n maps.messages.delete(messageId);\n }\n }\n\n for (const [toolCallId, tool] of maps.toolCalls) {\n const terminalSeq = tool.terminal?.seq;\n if (terminalSeq !== undefined && terminalSeq < retainedFromContextSeq) {\n maps.toolCalls.delete(toolCallId);\n }\n }\n\n for (const [inferenceId, inference] of maps.inferences) {\n if (inference.terminal !== undefined && inference.terminal.seq < retainedFromContextSeq) {\n maps.inferences.delete(inferenceId);\n }\n }\n\n for (const [turnId, turn] of maps.turns) {\n if (turn.terminal !== undefined && turn.terminal.seq < retainedFromContextSeq) {\n maps.turns.delete(turnId);\n }\n }\n\n for (const [runId, run] of maps.runs) {\n if (run.terminal !== undefined && run.terminal.seq < retainedFromContextSeq) {\n maps.runs.delete(runId);\n }\n }\n\n for (const replacementRunId of maps.recoveryContinuations.keys()) {\n if (!maps.runs.has(replacementRunId)) {\n maps.recoveryContinuations.delete(replacementRunId);\n }\n }\n\n for (const [commandId, command] of maps.commands) {\n if (command.terminal !== undefined && command.terminal.seq < retainedFromContextSeq) {\n maps.commands.delete(commandId);\n }\n }\n\n for (const [commandId, request] of maps.stopRequests) {\n if (request.appliedSeq !== undefined && request.appliedSeq < retainedFromContextSeq) {\n maps.stopRequests.delete(commandId);\n }\n }\n\n for (const [compactionId, compaction] of maps.compactions) {\n if (compaction.terminal !== undefined && compaction.summaryId !== currentSummaryId) {\n maps.compactions.delete(compactionId);\n }\n }\n};\n\nconst messagePruneSeq = (message: Exclude<MessageRecord, { readonly _tag: \"System\" }>): number => {\n if (message._tag === \"Steering\") {\n return message.consumedSeq ?? message.cancelledSeq ?? Number.POSITIVE_INFINITY;\n }\n return message.seq;\n};\n\n/** Pending admitted commands in deterministic scheduler order. */\nexport const pendingCommands = (state: ReducedState): ReadonlyArray<PendingCommand> =>\n state.commandQueues.pendingCommands;\n\n/** First pending StopTurn control command, when one is waiting. */\nexport const pendingStopCommand = (state: ReducedState): PendingCommand | undefined =>\n state.commandQueues.activeControlCommands.find((command) => command.command._tag === \"StopTurn\");\n\n/** Currently active command evidence, if any unfinished command is blocking FIFO work. */\nexport const activeCommand = (state: ReducedState): ActiveCommandEvidence | undefined =>\n state.commandQueues.active;\n\n/** Active run/turn/inference identity owned by a specific active command. */\nexport const activeTurnIdentityForCommand = (\n state: ReducedState,\n commandId: CommandId,\n): ActiveTurnIdentity | undefined => {\n const run = findLast(Array.from(state.runs.values()), (candidate): candidate is RunRecord =>\n candidate.commandIds.includes(commandId),\n );\n if (run === undefined) {\n return undefined;\n }\n\n const turn = findLast(\n Array.from(state.turns.values()),\n (candidate): candidate is TurnRecord => candidate.runId === run.runId,\n );\n if (turn === undefined) {\n return undefined;\n }\n\n const inference = findLast(\n Array.from(state.inferences.values()),\n (candidate): candidate is InferenceRecord =>\n candidate.runId === run.runId && candidate.turnId === turn.turnId,\n );\n\n return {\n runId: run.runId,\n turnId: turn.turnId,\n ...(inference === undefined ? {} : { inferenceId: inference.inferenceId }),\n };\n};\n\n/** Classify unfinished durable lifecycles that recovery may need to repair. */\nexport const classifyRecoverableWork = (state: ReducedState): RecoverableWork => {\n const activeCommands = Array.from(state.commands.values()).filter(\n (command) => command.startedSeq !== undefined && command.terminal === undefined,\n );\n const activeRuns = Array.from(state.runs.values()).filter((run) => run.terminal === undefined);\n const activeTurns = Array.from(state.turns.values()).filter(\n (turn) => turn.terminal === undefined,\n );\n const activeInferences = Array.from(state.inferences.values()).filter(\n (inference) => inference.terminal === undefined,\n );\n const openToolCalls = Array.from(state.toolCalls.values()).filter(\n (tool) =>\n tool.decision?._tag === \"Created\" &&\n !tool.decision.providerExecuted &&\n tool.terminal === undefined,\n );\n const runningToolCalls = openToolCalls.filter((tool) => tool.startedSeq !== undefined);\n const pendingStopRequests = Array.from(state.stopRequests.values()).filter(\n (request) =>\n request.appliedSeq === undefined &&\n state.commands.get(request.commandId)?.terminal === undefined,\n );\n const openCompactions = Array.from(state.compactions.values()).filter(\n (compaction) => compaction.terminal === undefined,\n );\n\n return {\n activeCommands,\n activeRuns,\n activeTurns,\n activeInferences,\n openToolCalls,\n runningToolCalls,\n pendingStopRequests,\n openCompactions,\n };\n};\n\nconst assistantContentFromPromptParts = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart>,\n): AssistantMessageContent => {\n const text = promptParts\n .filter((part): part is Prompt.TextPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n const reasoning = promptParts\n .filter((part): part is Prompt.ReasoningPart => part.type === \"reasoning\")\n .map((part) => part.text)\n .join(\"\");\n return {\n text,\n ...(reasoning.length === 0 ? {} : { reasoning }),\n };\n};\n\nconst findLast = <A, B extends A>(\n items: ReadonlyArray<A>,\n predicate: (item: A) => item is B,\n): B | undefined => {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n const item = items[index] as A;\n if (predicate(item)) {\n return item;\n }\n }\n return undefined;\n};\n\nconst requireAdmittedCommandId = (command: EDACommandValue): CommandId => {\n if (command.commandId !== undefined) {\n return command.commandId;\n }\n throw new Error(\"CommandAdmitted command is missing a framework commandId\");\n};\n\nconst terminalTiming = (\n record: Pick<LifecycleTiming, \"startedAtMs\">,\n terminalAtMs: number,\n): LifecycleTiming => ({\n terminalAtMs,\n ...(record.startedAtMs === undefined\n ? {}\n : { durationMs: Math.max(0, terminalAtMs - record.startedAtMs) }),\n});\n\nconst upsert = <K, V>(map: Map<K, V>, key: K, fallback: V, update: (record: V) => V) => {\n map.set(key, update(map.get(key) ?? fallback));\n};\n\nconst updateExisting = <K, V>(map: Map<K, V>, key: K, update: (record: V) => V) => {\n const record = map.get(key);\n if (record !== undefined) {\n map.set(key, update(record));\n }\n};\n\nconst appliedFields = (record: StopRequestRecord | undefined) =>\n record?.appliedSeq === undefined\n ? {}\n : {\n appliedSeq: record.appliedSeq,\n appliedRunId: record.appliedRunId,\n appliedTurnId: record.appliedTurnId,\n ...(record.appliedInferenceId === undefined\n ? {}\n : { appliedInferenceId: record.appliedInferenceId }),\n };\n"],"mappings":";;;;AAAA,MAAM,oBAAoB,UAAyB;CACjD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;AAGA,MAAa,oBAAoB,OAAc,4BAC7C,IAAI,MAAM,aAAa,QAAQ,IAAI,iBAAiB,KAAK,GAAG;;AAG9D,MAAa,eAAe,OAAc,YAA2B;CACnE,MAAM,iBAAiB,OAAO,OAAO;AACvC;;AC+XA,MAAa,sBAAoC;CAC/C,SAAS,eAAe,KAAK,CAAC;CAC9B,0BAAU,IAAI,IAAI;CAClB,sBAAM,IAAI,IAAI;CACd,uCAAuB,IAAI,IAAI;CAC/B,uBAAO,IAAI,IAAI;CACf,4BAAY,IAAI,IAAI;CACpB,2BAAW,IAAI,IAAI;CACnB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