effect-durable-agent 0.1.0-alpha.3 → 0.1.0-alpha.30

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 (221) hide show
  1. package/README.md +43 -41
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/{commands-Ce1ec6kH.d.ts → commands-3OD-p8dD.d.ts} +16 -9
  5. package/dist/compaction-63iEDHHl.js +523 -0
  6. package/dist/compaction-63iEDHHl.js.map +1 -0
  7. package/dist/context-projection-D_uRtK3r.d.ts +139 -0
  8. package/dist/{core-Hv3cFydL.d.ts → core-BcimKMIv.d.ts} +6 -4
  9. package/dist/delivery-2ZILvoRD.js +507 -0
  10. package/dist/delivery-2ZILvoRD.js.map +1 -0
  11. package/dist/{websocket-wire-D3tLrhe2.d.ts → delivery-RjM1_NAE.d.ts} +1019 -200
  12. package/dist/domain/command-queues.d.ts +81 -2
  13. package/dist/domain/command-queues.js +1 -1
  14. package/dist/domain/command-queues.js.map +1 -1
  15. package/dist/domain/context-projection.d.ts +2 -0
  16. package/dist/domain/context-projection.js +32 -0
  17. package/dist/domain/context-projection.js.map +1 -0
  18. package/dist/domain/message-transcript.d.ts +36 -2
  19. package/dist/domain/message-transcript.js +10 -2
  20. package/dist/domain/message-transcript.js.map +1 -1
  21. package/dist/domain/model-usage.d.ts +2 -0
  22. package/dist/domain/model-usage.js +59 -0
  23. package/dist/domain/model-usage.js.map +1 -0
  24. package/dist/domain/reduced-state-schema.d.ts +3 -996
  25. package/dist/domain/reduced-state-schema.js +121 -12
  26. package/dist/domain/reduced-state-schema.js.map +1 -1
  27. package/dist/domain/reduced-state.d.ts +3 -2
  28. package/dist/domain/reduced-state.js +937 -2
  29. package/dist/domain/reduced-state.js.map +1 -0
  30. package/dist/domain/run-scheduling.d.ts +2 -0
  31. package/dist/domain/run-scheduling.js +127 -0
  32. package/dist/domain/run-scheduling.js.map +1 -0
  33. package/dist/{durable-DlScwmCy.d.ts → durable-Cqv5ZRFA.d.ts} +8505 -2497
  34. package/dist/{durable-C3Rz7kg3.js → durable-D13w1Qr3.js} +253 -91
  35. package/dist/durable-D13w1Qr3.js.map +1 -0
  36. package/dist/envelope-BCzKUq_z.js +91 -0
  37. package/dist/envelope-BCzKUq_z.js.map +1 -0
  38. package/dist/envelope-Che6KatU.d.ts +254 -0
  39. package/dist/{keep-alive-p8dIcSVy.js → event-factory-_vF1bIJ7.js} +8 -10
  40. package/dist/event-factory-_vF1bIJ7.js.map +1 -0
  41. package/dist/{events-Bb9-Cu-7.d.ts → events-Dg0o5wWs.d.ts} +140 -324
  42. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
  43. package/dist/in-memory-CeODnZhE.js +150 -0
  44. package/dist/in-memory-CeODnZhE.js.map +1 -0
  45. package/dist/index.d.ts +8 -7
  46. package/dist/index.js +6 -5
  47. package/dist/interpreter-DKGJ1sSx.js +1452 -0
  48. package/dist/interpreter-DKGJ1sSx.js.map +1 -0
  49. package/dist/keep-alive-_zFCUvt3.d.ts +28 -0
  50. package/dist/model-resolver-D0vcDZsU.d.ts +24 -0
  51. package/dist/model-usage-0GeHwaaU.d.ts +54 -0
  52. package/dist/records--54mZEBx.js +675 -0
  53. package/dist/records--54mZEBx.js.map +1 -0
  54. package/dist/reduced-state-DU2ECOUp.d.ts +47821 -0
  55. package/dist/reduced-state-schema-B2t3cobf.d.ts +2187 -0
  56. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-JLU1yptN.d.ts} +24 -8
  57. package/dist/run-scheduling-wakeup-D_bGdicf.d.ts +24 -0
  58. package/dist/services/compaction.d.ts +2 -2
  59. package/dist/services/compaction.js +2 -426
  60. package/dist/services/id-generator.d.ts +1 -1
  61. package/dist/services/id-generator.js +4 -2
  62. package/dist/services/id-generator.js.map +1 -1
  63. package/dist/services/keep-alive.d.ts +2 -0
  64. package/dist/services/keep-alive.js +13 -0
  65. package/dist/services/keep-alive.js.map +1 -0
  66. package/dist/services/model-call.d.ts +15 -0
  67. package/dist/services/model-call.js +15 -0
  68. package/dist/services/model-call.js.map +1 -0
  69. package/dist/services/model-resolver.d.ts +2 -0
  70. package/dist/services/model-resolver.js +17 -0
  71. package/dist/services/model-resolver.js.map +1 -0
  72. package/dist/services/prompt-projector.d.ts +2 -2
  73. package/dist/services/prompt-projector.js +49 -5
  74. package/dist/services/prompt-projector.js.map +1 -1
  75. package/dist/services/reducer-registry.d.ts +2 -2
  76. package/dist/services/reducer-registry.js +21 -4
  77. package/dist/services/reducer-registry.js.map +1 -1
  78. package/dist/services/run-scheduler.d.ts +2 -0
  79. package/dist/services/run-scheduler.js +25 -0
  80. package/dist/services/run-scheduler.js.map +1 -0
  81. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  82. package/dist/services/run-scheduling-wakeup.js +13 -0
  83. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  84. package/dist/services/runtime-layer.d.ts +48 -0
  85. package/dist/services/runtime-layer.js +51 -0
  86. package/dist/services/runtime-layer.js.map +1 -0
  87. package/dist/services/runtime.d.ts +1 -1
  88. package/dist/services/runtime.js +34 -20
  89. package/dist/services/runtime.js.map +1 -1
  90. package/dist/services/session-event-observer.d.ts +2 -0
  91. package/dist/services/session-event-observer.js +13 -0
  92. package/dist/services/session-event-observer.js.map +1 -0
  93. package/dist/services/session-query.d.ts +2 -2
  94. package/dist/services/session-query.js +141 -2
  95. package/dist/services/session-query.js.map +1 -0
  96. package/dist/services/session-state.d.ts +2 -0
  97. package/dist/services/session-state.js +2 -0
  98. package/dist/services/session-store.d.ts +2 -2
  99. package/dist/services/session-store.js +272 -2
  100. package/dist/services/session-store.js.map +1 -0
  101. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  102. package/dist/services/sink-checkpoint-store.js +50 -0
  103. package/dist/services/sink-checkpoint-store.js.map +1 -0
  104. package/dist/services/sink-registry.d.ts +2 -2
  105. package/dist/services/sink-registry.js +1 -1
  106. package/dist/services/span-names.d.ts +1 -1
  107. package/dist/services/span-names.js +7 -1
  108. package/dist/services/span-names.js.map +1 -1
  109. package/dist/services/tool-registry.d.ts +2 -2
  110. package/dist/services/tool-registry.js +12 -3
  111. package/dist/services/tool-registry.js.map +1 -1
  112. package/dist/services/tracing.d.ts +3 -3
  113. package/dist/services/tracing.js +25 -4
  114. package/dist/services/tracing.js.map +1 -1
  115. package/dist/session-event-observer-HvrRckbC.d.ts +24 -0
  116. package/dist/{session-query-Cbf-e0rG.js → session-state-BQYsuBqi.js} +693 -251
  117. package/dist/session-state-BQYsuBqi.js.map +1 -0
  118. package/dist/session-store-CQxg9U82.d.ts +3302 -0
  119. package/dist/sink-checkpoint-store-DWGifxp0.d.ts +39 -0
  120. package/dist/sink-registry-DskRcyOS.js +345 -0
  121. package/dist/sink-registry-DskRcyOS.js.map +1 -0
  122. package/dist/subscription-DmO3BcdT.js +505 -0
  123. package/dist/subscription-DmO3BcdT.js.map +1 -0
  124. package/dist/subscription-rC35dAWn.d.ts +958 -0
  125. package/dist/testkit/layers.d.ts +34 -19
  126. package/dist/testkit/layers.js +30 -16
  127. package/dist/testkit/layers.js.map +1 -1
  128. package/dist/testkit/transcript.d.ts +226 -0
  129. package/dist/testkit/transcript.js +1475 -0
  130. package/dist/testkit/transcript.js.map +1 -0
  131. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-BzlMhwzj.d.ts} +44 -8
  132. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  133. package/dist/transcript.d.ts +101 -0
  134. package/dist/transcript.js +107 -0
  135. package/dist/transcript.js.map +1 -0
  136. package/dist/types/commands.d.ts +2 -2
  137. package/dist/types/commands.js +8 -3
  138. package/dist/types/commands.js.map +1 -1
  139. package/dist/types/core.d.ts +2 -2
  140. package/dist/types/core.js +4 -2
  141. package/dist/types/core.js.map +1 -1
  142. package/dist/types/events/durable.d.ts +2 -2
  143. package/dist/types/events/durable.js +2 -2
  144. package/dist/types/events.d.ts +5 -4
  145. package/dist/types/events.js +3 -2
  146. package/dist/types/events.js.map +1 -1
  147. package/dist/types/tracing.d.ts +1 -1
  148. package/dist/types/tracing.js.map +1 -1
  149. package/dist/websocket/events.d.ts +2 -0
  150. package/dist/websocket/events.js +2 -0
  151. package/dist/websocket.d.ts +2201 -0
  152. package/dist/websocket.js +684 -0
  153. package/dist/websocket.js.map +1 -0
  154. package/dist/window-read-CBZEJ84M.d.ts +113 -0
  155. package/dist/window-read-DPFAA1hM.js +264 -0
  156. package/dist/window-read-DPFAA1hM.js.map +1 -0
  157. package/package.json +87 -46
  158. package/testing/offline-trace/README.md +2 -1
  159. package/CHANGELOG.md +0 -25
  160. package/CONTRIBUTING.md +0 -26
  161. package/SECURITY.md +0 -7
  162. package/dist/command-queues-CQ9cwRP7.d.ts +0 -468
  163. package/dist/compaction-1LSZR944.d.ts +0 -144
  164. package/dist/durable-C3Rz7kg3.js.map +0 -1
  165. package/dist/durable-object-runtime-CiMKxGs6.d.ts +0 -257
  166. package/dist/durable-object-runtime-wKiqaAt2.js +0 -1494
  167. package/dist/durable-object-runtime-wKiqaAt2.js.map +0 -1
  168. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  169. package/dist/host/durable-object-runtime.d.ts +0 -2
  170. package/dist/host/durable-object-runtime.js +0 -2
  171. package/dist/host/durable-object-storage.d.ts +0 -2
  172. package/dist/host/durable-object-storage.js +0 -0
  173. package/dist/host/durable-object.d.ts +0 -83
  174. package/dist/host/durable-object.js +0 -191
  175. package/dist/host/durable-object.js.map +0 -1
  176. package/dist/host/websocket-wire.d.ts +0 -2
  177. package/dist/host/websocket-wire.js +0 -105
  178. package/dist/host/websocket-wire.js.map +0 -1
  179. package/dist/index-BVVgDSdq.d.ts +0 -1
  180. package/dist/keep-alive-DYDsH6qN.d.ts +0 -111
  181. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  182. package/dist/message-transcript-BCHdHAe2.d.ts +0 -32
  183. package/dist/prompt-projector-DimXJPOJ.d.ts +0 -39
  184. package/dist/reduced-state-C4nVVzz9.js +0 -910
  185. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  186. package/dist/runtime-DcdPOEuE.d.ts +0 -60
  187. package/dist/services/compaction.js.map +0 -1
  188. package/dist/session-query-Cbf-e0rG.js.map +0 -1
  189. package/dist/session-query-hxfujxUH.d.ts +0 -769
  190. package/dist/session-store-D2Ore1QC.d.ts +0 -295
  191. package/dist/session-store-pYxQW9qh.js +0 -214
  192. package/dist/session-store-pYxQW9qh.js.map +0 -1
  193. package/dist/sink-registry-BziFpxoE.d.ts +0 -158
  194. package/dist/sink-registry-CFC6xjsN.js +0 -312
  195. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  196. package/docs/assets/architecture.svg +0 -216
  197. package/docs/assets/event-sequence.svg +0 -133
  198. package/docs/assets/gcp-trace.png +0 -0
  199. package/docs/assets/hero.svg +0 -33
  200. package/docs/message-steering.md +0 -831
  201. package/docs/releasing.md +0 -96
  202. package/docs/spec.md +0 -777
  203. package/docs/subagents.md +0 -725
  204. package/docs/testing.md +0 -64
  205. package/docs/ui-projection.md +0 -742
  206. package/docs/websocket-protocol.md +0 -639
  207. package/examples/001-no-tools/README.md +0 -65
  208. package/examples/001-no-tools/worker.ts +0 -79
  209. package/examples/002-slack-bridge/README.md +0 -134
  210. package/examples/002-slack-bridge/events.ts +0 -115
  211. package/examples/002-slack-bridge/reducer.ts +0 -216
  212. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  213. package/examples/002-slack-bridge/sinks.ts +0 -109
  214. package/examples/002-slack-bridge/worker.ts +0 -140
  215. package/examples/003-sandbox-lifecycle/README.md +0 -78
  216. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  217. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  218. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  219. package/examples/_shared/event-id.ts +0 -12
  220. package/examples/_shared/http.ts +0 -27
  221. package/examples/_shared/openai.ts +0 -33
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.js","names":["PositiveInt","NonNegativeInt"],"sources":["../src/websocket/transcript.ts","../src/websocket/transcript-client.ts","../src/websocket/transcript-delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { TranscriptCursor } from \"../transcript/records\";\nimport {\n TranscriptCoverage,\n TranscriptRequestId,\n TranscriptUpdate,\n} from \"../transcript/subscription\";\nimport {\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWirePingFrame,\n EDAWebSocketWirePongFrame,\n} from \"./protocol\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n// ---------------------------------------------------------------------------------------------\n// Negotiation\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Transcript protocol major. A change of meaning that an older client would misread bumps it;\n * a client that sees another major performs one bounded reload.\n */\nexport const EDA_TRANSCRIPT_PROTOCOL_MAJOR = 1;\n\n/** Additive wire revision within a major; older clients drop fields they do not know. */\nexport const EDA_TRANSCRIPT_WIRE_VERSION = 1;\n\n/**\n * The small, stable envelope a client decodes before any version-specific schema, from the\n * socket hello and from the host's SSR data. Its shape never changes; everything else may.\n */\nexport const EDATranscriptNegotiation = Schema.Struct({\n protocolMajor: PositiveInt,\n wireVersion: PositiveInt,\n /** Optional features this server speaks; clients ignore names they do not know. */\n capabilities: Schema.Array(Schema.String),\n});\nexport type EDATranscriptNegotiation = typeof EDATranscriptNegotiation.Type;\n\n/** What this EDA release speaks. Hosts embed it in SSR data next to the transcript window. */\nexport const edaTranscriptNegotiation: EDATranscriptNegotiation = {\n protocolMajor: EDA_TRANSCRIPT_PROTOCOL_MAJOR,\n wireVersion: EDA_TRANSCRIPT_WIRE_VERSION,\n capabilities: [\"window\", \"page\", \"retain\", \"chunked-updates\", \"active-content\"],\n};\n\n/** Any value carrying the envelope under `negotiation`: a hello frame or SSR data. */\nconst NegotiationCarrier = Schema.Struct({ negotiation: EDATranscriptNegotiation });\n\n/** How a client should treat a server's negotiation envelope. */\nexport type EDATranscriptNegotiationResult =\n | { readonly _tag: \"Compatible\"; readonly remote: EDATranscriptNegotiation }\n /** The server speaks another major: reload once, preserving the viewport and draft. */\n | { readonly _tag: \"MajorMismatch\"; readonly remote: EDATranscriptNegotiation }\n /** No envelope could be decoded: an incompatible or non-transcript peer; also reload. */\n | { readonly _tag: \"Undecodable\" };\n\nconst decodeNegotiationCarrier = Schema.decodeUnknownOption(NegotiationCarrier);\n\n/**\n * Decode only the negotiation envelope from an untrusted hello frame or SSR payload and compare\n * it with this client's major. Run before decoding anything version-specific.\n */\nexport const negotiateEDATranscript = (\n carrier: unknown,\n localMajor: number = EDA_TRANSCRIPT_PROTOCOL_MAJOR,\n): EDATranscriptNegotiationResult => {\n const decoded = decodeNegotiationCarrier(carrier);\n if (decoded._tag === \"None\") return { _tag: \"Undecodable\" };\n const remote = decoded.value.negotiation;\n return remote.protocolMajor === localMajor\n ? { _tag: \"Compatible\", remote }\n : { _tag: \"MajorMismatch\", remote };\n};\n\n// ---------------------------------------------------------------------------------------------\n// Frames\n// ---------------------------------------------------------------------------------------------\n\n/** WebSocket close code: the server lost volatile transfer state; reconnect and resubscribe. */\nexport const EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE = 4009;\n\n/** First frame on a transcript socket: the event-socket hello plus the negotiation envelope. */\nexport const EDATranscriptHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n negotiation: EDATranscriptNegotiation,\n});\nexport type EDATranscriptHelloFrame = typeof EDATranscriptHelloFrame.Type;\n\n/** A transcript update that fits one frame. */\nexport const EDATranscriptUpdateFrame = Schema.Struct({\n _tag: Schema.Literal(\"transcript\"),\n frameId: PositiveInt,\n update: TranscriptUpdate,\n});\nexport type EDATranscriptUpdateFrame = typeof EDATranscriptUpdateFrame.Type;\n\n/**\n * One slice of an update too large for a frame. `data` slices concatenated in `index` order are\n * the JSON of one `TranscriptUpdate`; the client applies it only after slice `count - 1` (the\n * completion marker) and discards a transfer that is interrupted.\n */\nexport const EDATranscriptChunkFrame = Schema.Struct({\n _tag: Schema.Literal(\"transcript-chunk\"),\n frameId: PositiveInt,\n updateSeq: PositiveInt,\n index: NonNegativeInt,\n count: PositiveInt,\n data: Schema.String,\n}).check(Schema.makeFilter((chunk) => chunk.index < chunk.count || \"chunk index out of range\"));\nexport type EDATranscriptChunkFrame = typeof EDATranscriptChunkFrame.Type;\n\n/** Every server frame a transcript socket may carry. */\nexport const EDATranscriptServerFrame = Schema.Union([\n EDATranscriptHelloFrame,\n EDATranscriptUpdateFrame,\n EDATranscriptChunkFrame,\n EDAWebSocketWirePongFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWireErrorFrame,\n]);\nexport type EDATranscriptServerFrame = typeof EDATranscriptServerFrame.Type;\n\n/**\n * Start or restart the subscription. After SSR, `range` is what the page rendered, `tail` its\n * `!hasNewer`, and `since` its `throughSeq`; a reconnecting client sends what it last applied.\n * Without `range` the server replies with the latest `count` records.\n */\nexport const EDATranscriptSubscribeFrame = Schema.Struct({\n _tag: Schema.Literal(\"subscribe\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n range: Schema.optionalKey(TranscriptCoverage),\n tail: Schema.optionalKey(Schema.Boolean),\n since: Schema.optionalKey(SequenceNumber),\n count: Schema.optionalKey(PositiveInt),\n});\nexport type EDATranscriptSubscribeFrame = typeof EDATranscriptSubscribeFrame.Type;\n\n/** Extend the coverage from its edge: `cursor` is the coverage's `from` (before) or `to` (after). */\nexport const EDATranscriptPageFrame = Schema.Struct({\n _tag: Schema.Literal(\"page\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n direction: Schema.Literals([\"before\", \"after\"]),\n cursor: TranscriptCursor,\n count: PositiveInt,\n});\nexport type EDATranscriptPageFrame = typeof EDATranscriptPageFrame.Type;\n\n/** Narrow the coverage to a span inside it, so the server stops sending changes outside it. */\nexport const EDATranscriptRetainFrame = Schema.Struct({\n _tag: Schema.Literal(\"retain\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n from: TranscriptCursor,\n to: TranscriptCursor,\n});\nexport type EDATranscriptRetainFrame = typeof EDATranscriptRetainFrame.Type;\n\n/** A client request; each is answered by exactly one update, in arrival order. */\nexport const EDATranscriptRequestFrame = Schema.Union([\n EDATranscriptSubscribeFrame,\n EDATranscriptPageFrame,\n EDATranscriptRetainFrame,\n]);\nexport type EDATranscriptRequestFrame = typeof EDATranscriptRequestFrame.Type;\n\n/** Every client frame a transcript socket accepts. */\nexport const EDATranscriptClientFrame = Schema.Union([\n EDAWebSocketWireAckFrame,\n EDAWebSocketWirePingFrame,\n EDATranscriptSubscribeFrame,\n EDATranscriptPageFrame,\n EDATranscriptRetainFrame,\n]);\nexport type EDATranscriptClientFrame = typeof EDATranscriptClientFrame.Type;\n\n// ---------------------------------------------------------------------------------------------\n// Encoding and chunking\n// ---------------------------------------------------------------------------------------------\n\nconst encodeUpdate = Schema.encodeSync(TranscriptUpdate);\nconst encodeServerFrame = Schema.encodeSync(EDATranscriptServerFrame);\n\n/** Serialize one update once; frames embed this text, chunks slice it. */\nexport const encodeEDATranscriptUpdate = (update: TranscriptUpdate): string =>\n JSON.stringify(encodeUpdate(update));\n\n/** Serialize a non-update server frame. */\nexport const encodeEDATranscriptServerFrame = (frame: EDATranscriptServerFrame): string =>\n JSON.stringify(encodeServerFrame(frame));\n\n/** The single-frame form of an encoded update. */\nexport const edaTranscriptUpdateFrameText = (frameId: number, encodedUpdate: string): string =>\n `{\"_tag\":\"transcript\",\"frameId\":${frameId},\"update\":${encodedUpdate}}`;\n\n/** One chunk frame of an encoded update. */\nexport const edaTranscriptChunkFrameText = (input: {\n readonly frameId: number;\n readonly updateSeq: number;\n readonly index: number;\n readonly count: number;\n readonly data: string;\n}): string =>\n `{\"_tag\":\"transcript-chunk\",\"frameId\":${input.frameId},\"updateSeq\":${input.updateSeq},` +\n `\"index\":${input.index},\"count\":${input.count},\"data\":${JSON.stringify(input.data)}}`;\n\nconst textEncoder = new TextEncoder();\n\n/** UTF-8 byte length of a string. */\nexport const utf8ByteLength = (text: string): number => textEncoder.encode(text).byteLength;\n\n/** Bytes a chunk frame spends besides its data, with generous room for large numbers. */\nconst chunkFrameOverheadBytes = 160;\n\n/** Control characters JSON writes as a two-byte escape (`\\b`, `\\t`, `\\n`, `\\f`, `\\r`). */\nconst shortEscapes: ReadonlySet<number> = new Set([0x08, 0x09, 0x0a, 0x0c, 0x0d]);\n\n/** UTF-8 bytes one UTF-16 code unit costs inside a JSON string literal. */\nconst jsonStringUnitBytes = (code: number): number => {\n if (code === 0x22 || code === 0x5c) return 2;\n if (code < 0x20) return shortEscapes.has(code) ? 2 : 6;\n if (code < 0x80) return 1;\n if (code < 0x800) return 2;\n // A lone surrogate half is written as a `\\uXXXX` escape; pairs are costed by the caller.\n if (code >= 0xd800 && code <= 0xdfff) return 6;\n return 3;\n};\n\n/**\n * Split an encoded update into chunk data that each fit a frame of `maxFrameBytes`, never\n * splitting a surrogate pair.\n */\nexport const splitEDATranscriptUpdate = (\n encodedUpdate: string,\n maxFrameBytes: number,\n): ReadonlyArray<string> => {\n const budget = Math.max(16, maxFrameBytes - chunkFrameOverheadBytes);\n const chunks: string[] = [];\n let start = 0;\n let bytes = 0;\n for (let index = 0; index < encodedUpdate.length; index += 1) {\n const code = encodedUpdate.charCodeAt(index);\n const pair =\n code >= 0xd800 && code <= 0xdbff && index + 1 < encodedUpdate.length\n ? encodedUpdate.charCodeAt(index + 1)\n : undefined;\n const isPair = pair !== undefined && pair >= 0xdc00 && pair <= 0xdfff;\n const cost = isPair ? 4 : jsonStringUnitBytes(code);\n if (bytes + cost > budget && index > start) {\n chunks.push(encodedUpdate.slice(start, index));\n start = index;\n bytes = 0;\n }\n bytes += cost;\n if (isPair) index += 1;\n }\n if (start < encodedUpdate.length || chunks.length === 0) chunks.push(encodedUpdate.slice(start));\n return chunks;\n};\n","import * as Exit from \"effect/Exit\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport {\n TranscriptOrder,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n type TranscriptVersion,\n} from \"../transcript/records\";\nimport {\n TranscriptUpdate,\n transcriptCoverageOf,\n type TranscriptCoverage,\n} from \"../transcript/subscription\";\nimport type {\n TranscriptActiveContent,\n TranscriptReadiness,\n TranscriptWindow,\n} from \"../transcript/window\";\nimport type { EDAWebSocketWireAckFrame } from \"./protocol\";\nimport {\n EDATranscriptChunkFrame,\n EDATranscriptUpdateFrame,\n negotiateEDATranscript,\n type EDATranscriptNegotiationResult,\n type EDATranscriptPageFrame,\n type EDATranscriptRetainFrame,\n type EDATranscriptSubscribeFrame,\n} from \"./transcript\";\n\n/**\n * The window a client holds: always exactly one complete cut. Top-level records are in\n * transcript order; dependencies are keyed by id and ordered as the server listed them.\n */\nexport interface EDATranscriptClientWindow {\n readonly incarnation: TranscriptLogIncarnation;\n readonly version: TranscriptVersion;\n readonly throughSeq: SequenceNumber;\n readonly coverage: TranscriptCoverage | undefined;\n readonly hasOlder: boolean;\n readonly hasNewer: boolean;\n readonly readiness: TranscriptReadiness;\n readonly records: ReadonlyArray<TranscriptRecordView>;\n readonly dependencies: ReadonlyArray<TranscriptRecordView>;\n readonly activeContent: ReadonlyArray<TranscriptActiveContent>;\n}\n\n/**\n * Reference client state for one transcript socket, independent of any UI framework.\n *\n * Hosts feed every server message to `applyEDATranscriptServerMessage`, send the ACK it returns,\n * and render `window`. Chunked updates are assembled here and applied only when complete, so the\n * rendered window never shows a partial update.\n */\nexport interface EDATranscriptClientState {\n readonly window: EDATranscriptClientWindow | undefined;\n /** Highest frame id received on the current socket. */\n readonly lastFrameId: number;\n /** The last update applied on the current socket. */\n readonly appliedUpdateSeq: number;\n readonly assembling:\n | { readonly updateSeq: number; readonly count: number; readonly data: ReadonlyArray<string> }\n | undefined;\n}\n\n/** A client that has rendered nothing yet. */\nexport const emptyEDATranscriptClientState: EDATranscriptClientState = {\n window: undefined,\n lastFrameId: 0,\n appliedUpdateSeq: 0,\n assembling: undefined,\n};\n\n/** Seed a client from the window its page was server-rendered with. */\nexport const edaTranscriptClientFromWindow = (\n window: TranscriptWindow,\n): EDATranscriptClientState => ({\n ...emptyEDATranscriptClientState,\n window: {\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n coverage: transcriptCoverageOf(window),\n hasOlder: window.hasOlder,\n hasNewer: window.hasNewer,\n readiness: window.readiness,\n records: window.records,\n dependencies: window.dependencies,\n activeContent: window.activeContent ?? [],\n },\n});\n\n/**\n * Prepare for a new socket: per-socket counters restart and any partial transfer is discarded.\n * The applied window is kept; the next `subscribe` asks for changes since it.\n */\nexport const edaTranscriptClientReconnected = (\n state: EDATranscriptClientState,\n): EDATranscriptClientState => ({ ...emptyEDATranscriptClientState, window: state.window });\n\n/** What one server message did. */\nexport type EDATranscriptClientOutcome =\n | { readonly _tag: \"Hello\"; readonly negotiation: EDATranscriptNegotiationResult }\n | { readonly _tag: \"Applied\"; readonly updateSeq: number; readonly requestId?: string }\n | { readonly _tag: \"Partial\" }\n | { readonly _tag: \"Ignored\" }\n /** The stream is unusable (a gap, a bad frame, a protocol close): reconnect and resubscribe. */\n | { readonly _tag: \"Resubscribe\"; readonly reason: string };\n\nexport interface EDATranscriptClientStep {\n readonly state: EDATranscriptClientState;\n readonly outcome: EDATranscriptClientOutcome;\n /** Send this ACK when present: a transport receipt plus the applied cut. */\n readonly ack?: EDAWebSocketWireAckFrame;\n}\n\nconst decodeUpdateFrame = Schema.decodeUnknownExit(EDATranscriptUpdateFrame);\nconst decodeChunkFrame = Schema.decodeUnknownExit(EDATranscriptChunkFrame);\nconst decodeUpdate = Schema.decodeUnknownExit(TranscriptUpdate);\n\nconst peek = (value: unknown): { readonly tag?: string; readonly frameId?: number } => {\n if (typeof value !== \"object\" || value === null) return {};\n const tag = \"_tag\" in value && typeof value._tag === \"string\" ? value._tag : undefined;\n const frameId =\n \"frameId\" in value && typeof value.frameId === \"number\" && Number.isInteger(value.frameId)\n ? value.frameId\n : undefined;\n return {\n ...(tag === undefined ? {} : { tag }),\n ...(frameId === undefined ? {} : { frameId }),\n };\n};\n\n/** Apply one server text message. Frames must arrive in frame-id order without gaps. */\nexport const applyEDATranscriptServerMessage = (\n state: EDATranscriptClientState,\n message: string,\n): EDATranscriptClientStep => {\n let json: unknown;\n try {\n json = JSON.parse(message);\n } catch {\n return resubscribe(state, \"malformed server message\");\n }\n const { tag, frameId } = peek(json);\n switch (tag) {\n case \"hello\":\n return { state, outcome: { _tag: \"Hello\", negotiation: negotiateEDATranscript(json) } };\n case \"pong\":\n return { state, outcome: { _tag: \"Ignored\" } };\n case \"lagged\":\n case \"error\":\n return resubscribe(state, `server sent ${tag}`);\n }\n if (frameId === undefined) return { state, outcome: { _tag: \"Ignored\" } };\n if (frameId !== state.lastFrameId + 1) return resubscribe(state, \"frame gap\");\n const received: EDATranscriptClientState = { ...state, lastFrameId: frameId };\n\n if (tag === \"transcript\") {\n const decoded = decodeUpdateFrame(json);\n if (Exit.isFailure(decoded)) return resubscribe(state, \"undecodable update\");\n if (received.assembling !== undefined)\n return resubscribe(state, \"update interrupted a transfer\");\n return applyUpdate(received, decoded.value.update);\n }\n if (tag === \"transcript-chunk\") {\n const decoded = decodeChunkFrame(json);\n if (Exit.isFailure(decoded)) return resubscribe(state, \"undecodable chunk\");\n const chunk = decoded.value;\n const assembling = received.assembling ?? {\n updateSeq: chunk.updateSeq,\n count: chunk.count,\n data: [],\n };\n if (\n assembling.updateSeq !== chunk.updateSeq ||\n assembling.count !== chunk.count ||\n assembling.data.length !== chunk.index\n ) {\n return resubscribe(state, \"interrupted chunked transfer\");\n }\n const data = [...assembling.data, chunk.data];\n if (data.length < chunk.count) {\n const next = { ...received, assembling: { ...assembling, data } };\n return { state: next, outcome: { _tag: \"Partial\" }, ack: ackOf(next) };\n }\n let updateJson: unknown;\n try {\n updateJson = JSON.parse(data.join(\"\"));\n } catch {\n return resubscribe(state, \"malformed chunked update\");\n }\n const update = decodeUpdate(updateJson);\n if (Exit.isFailure(update) || update.value.updateSeq !== chunk.updateSeq) {\n return resubscribe(state, \"undecodable chunked update\");\n }\n return applyUpdate({ ...received, assembling: undefined }, update.value);\n }\n // A frame kind from a newer server: acknowledge its receipt and ignore it.\n return { state: received, outcome: { _tag: \"Ignored\" }, ack: ackOf(received) };\n};\n\nconst resubscribe = (state: EDATranscriptClientState, reason: string): EDATranscriptClientStep => ({\n state: { ...state, assembling: undefined },\n outcome: { _tag: \"Resubscribe\", reason },\n});\n\nconst ackOf = (state: EDATranscriptClientState): EDAWebSocketWireAckFrame => ({\n _tag: \"ack\",\n frameId: state.lastFrameId,\n durableThroughSeq: state.appliedUpdateSeq === 0 ? 0 : (state.window?.throughSeq ?? 0),\n appliedUpdateSeq: state.appliedUpdateSeq,\n});\n\nconst orderKeyOf = (record: TranscriptRecordView): TranscriptOrderKey | undefined =>\n \"position\" in record && record.position !== undefined\n ? { ...record.position, recordId: record.id }\n : undefined;\n\nconst covered = (\n coverage: TranscriptCoverage | undefined,\n record: TranscriptRecordView,\n): boolean => {\n const key = orderKeyOf(record);\n return (\n coverage !== undefined &&\n key !== undefined &&\n TranscriptOrder(coverage.from, key) <= 0 &&\n TranscriptOrder(key, coverage.to) <= 0\n );\n};\n\nconst applyUpdate = (\n state: EDATranscriptClientState,\n update: TranscriptUpdate,\n): EDATranscriptClientStep => {\n if (update.updateSeq !== state.appliedUpdateSeq + 1) return resubscribe(state, \"update gap\");\n const previous = state.window;\n if (\n update.mode === \"patch\" &&\n (previous === undefined ||\n previous.incarnation !== update.incarnation ||\n previous.version !== update.version)\n ) {\n return resubscribe(state, \"patch without its base\");\n }\n const base = update.mode === \"patch\" ? previous : undefined;\n\n const topLevel = new Map((base?.records ?? []).map((record) => [record.id, record]));\n for (const record of update.records) topLevel.set(record.id, record);\n const records = [...topLevel.values()]\n .filter((record) => covered(update.coverage, record))\n .sort((left, right) => {\n const leftKey = orderKeyOf(left);\n const rightKey = orderKeyOf(right);\n return leftKey === undefined || rightKey === undefined\n ? 0\n : TranscriptOrder(leftKey, rightKey);\n });\n\n const dependencyMap = new Map((base?.dependencies ?? []).map((record) => [record.id, record]));\n for (const record of update.dependencies) dependencyMap.set(record.id, record);\n const dependencies = update.dependencyIds.flatMap((id) => {\n const record = dependencyMap.get(id);\n return record === undefined ? [] : [record];\n });\n if (dependencies.length !== update.dependencyIds.length) {\n return resubscribe(state, \"patch referenced a dependency the client does not hold\");\n }\n\n const window: EDATranscriptClientWindow = {\n incarnation: update.incarnation,\n version: update.version,\n throughSeq: update.throughSeq,\n coverage: update.coverage,\n hasOlder: update.hasOlder,\n hasNewer: update.hasNewer,\n readiness: update.readiness,\n records,\n dependencies,\n activeContent:\n update.readiness._tag !== \"Ready\" ? [] : (update.activeContent ?? base?.activeContent ?? []),\n };\n const next: EDATranscriptClientState = {\n ...state,\n window,\n appliedUpdateSeq: update.updateSeq,\n assembling: undefined,\n };\n return {\n state: next,\n outcome: {\n _tag: \"Applied\",\n updateSeq: update.updateSeq,\n ...(update.requestId === undefined ? {} : { requestId: update.requestId }),\n },\n ack: ackOf(next),\n };\n};\n\n/**\n * The request a client sends first on every socket: changes since the window it holds over the\n * span it holds, or the latest `count` records when it holds none.\n */\nexport const edaTranscriptSubscribeRequest = (\n state: EDATranscriptClientState,\n options?: { readonly count?: number; readonly requestId?: string },\n): EDATranscriptSubscribeFrame => {\n const window = state.window;\n const extra = {\n ...(options?.count === undefined ? {} : { count: options.count }),\n ...(options?.requestId === undefined ? {} : { requestId: options.requestId }),\n };\n return window?.coverage === undefined\n ? { _tag: \"subscribe\", ...extra }\n : {\n _tag: \"subscribe\",\n range: window.coverage,\n tail: !window.hasNewer,\n since: window.throughSeq,\n ...extra,\n };\n};\n\n/** Page from the held coverage's edge, or `undefined` when there is nothing to page from. */\nexport const edaTranscriptPageRequest = (\n state: EDATranscriptClientState,\n direction: \"before\" | \"after\",\n count: number,\n requestId?: string,\n): EDATranscriptPageFrame | undefined => {\n const coverage = state.window?.coverage;\n if (coverage === undefined) return undefined;\n return {\n _tag: \"page\",\n direction,\n cursor: direction === \"before\" ? coverage.from : coverage.to,\n count,\n ...(requestId === undefined ? {} : { requestId }),\n };\n};\n\n/**\n * Keep only the top-level records from `fromIndex` to `toIndex` (inclusive) of the held window;\n * the server confirms with an update whose coverage is the narrowed span.\n */\nexport const edaTranscriptRetainRequest = (\n state: EDATranscriptClientState,\n fromIndex: number,\n toIndex: number,\n requestId?: string,\n): EDATranscriptRetainFrame | undefined => {\n const window = state.window;\n const from = window?.records[fromIndex];\n const to = window?.records[toIndex];\n const fromKey = from === undefined ? undefined : orderKeyOf(from);\n const toKey = to === undefined ? undefined : orderKeyOf(to);\n if (window === undefined || fromKey === undefined || toKey === undefined) return undefined;\n const scope = { incarnation: window.incarnation, version: window.version };\n return {\n _tag: \"retain\",\n from: { ...scope, ...fromKey, anchorSeq: SequenceNumber.make(fromKey.anchorSeq) },\n to: { ...scope, ...toKey, anchorSeq: SequenceNumber.make(toKey.anchorSeq) },\n ...(requestId === undefined ? {} : { requestId }),\n };\n};\n","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { TranscriptSubscriptionBase, type TranscriptUpdate } from \"../transcript/subscription\";\nimport type { EDAWebSocketFlowControl } from \"./messages\";\nimport type { EDAWebSocketWireAckFrame } from \"./protocol\";\nimport {\n EDATranscriptRequestFrame,\n edaTranscriptChunkFrameText,\n edaTranscriptUpdateFrameText,\n splitEDATranscriptUpdate,\n utf8ByteLength,\n} from \"./transcript\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** A chunked update whose frames are not all sent yet; its chunk data is volatile. */\nexport const EDATranscriptTransfer = Schema.Struct({\n updateSeq: PositiveInt,\n throughSeq: SequenceNumber,\n count: PositiveInt,\n nextIndex: NonNegativeInt,\n});\nexport type EDATranscriptTransfer = typeof EDATranscriptTransfer.Type;\n\n/**\n * Everything a transcript socket needs to resume after hibernation, persisted in its attachment\n * before every send and after every applied ACK.\n *\n * Transport receipts (`inFlight`, `lastAckedFrameId`) bound frames in flight exactly as on an\n * event socket. The applied cut (`appliedUpdateSeq`, `appliedThroughSeq`) is the last update the\n * client applied completely. `subscription` is the base the next update is planned against, and\n * `requests` are client requests not yet answered. A persisted `transfer` means chunk data was\n * staged in memory; a socket restored with one cannot finish it and is closed.\n */\nexport const EDATranscriptDeliveryCheckpoint = Schema.Struct({\n lastAckedFrameId: NonNegativeInt,\n nextFrameId: PositiveInt,\n inFlight: Schema.Array(Schema.Struct({ frameId: PositiveInt, sentAtMs: Schema.Number })),\n nextUpdateSeq: PositiveInt,\n completedUpdateSeq: NonNegativeInt,\n completedThroughSeq: SequenceNumber,\n appliedUpdateSeq: NonNegativeInt,\n appliedThroughSeq: SequenceNumber,\n transfer: Schema.optionalKey(EDATranscriptTransfer),\n subscription: Schema.optionalKey(TranscriptSubscriptionBase),\n requests: Schema.Array(EDATranscriptRequestFrame),\n});\nexport type EDATranscriptDeliveryCheckpoint = typeof EDATranscriptDeliveryCheckpoint.Type;\n\n/** Bounds on one transcript socket beyond the shared flow-control policy. */\nexport interface EDATranscriptDeliveryLimits {\n /** Largest encoded update staged for one transfer; a larger one closes the socket. */\n readonly maxStagedBytes: number;\n /** Unanswered client requests held at once; more is a protocol violation. */\n readonly maxPendingRequests: number;\n}\n\nexport const defaultEDATranscriptDeliveryLimits: EDATranscriptDeliveryLimits = {\n maxStagedBytes: 8 * 1_048_576,\n maxPendingRequests: 4,\n};\n\n/** In-memory state of one transcript socket. */\nexport interface EDATranscriptDeliveryState extends EDATranscriptDeliveryCheckpoint {\n readonly policy: EDAWebSocketFlowControl;\n /** Chunk data of `transfer` not yet sent, in order. Never persisted. */\n readonly staged: ReadonlyArray<string>;\n}\n\n/** Delivery state for a newly accepted transcript socket. */\nexport const makeTranscriptDeliveryState = (\n policy: EDAWebSocketFlowControl,\n): EDATranscriptDeliveryState => ({\n policy,\n lastAckedFrameId: 0,\n nextFrameId: 1,\n inFlight: [],\n nextUpdateSeq: 1,\n completedUpdateSeq: 0,\n completedThroughSeq: SequenceNumber.make(0),\n appliedUpdateSeq: 0,\n appliedThroughSeq: SequenceNumber.make(0),\n requests: [],\n staged: [],\n});\n\n/**\n * Restore a hibernated transcript socket. A socket that was mid-transfer lost its staged chunks\n * with the isolate and cannot resume: the caller closes it and the client resubscribes.\n */\nexport const restoreTranscriptDeliveryState = (\n policy: EDAWebSocketFlowControl,\n checkpoint: EDATranscriptDeliveryCheckpoint,\n):\n | { readonly _tag: \"Restored\"; readonly state: EDATranscriptDeliveryState }\n | { readonly _tag: \"TransferLost\" } =>\n checkpoint.transfer === undefined\n ? { _tag: \"Restored\", state: { ...checkpoint, policy, staged: [] } }\n : { _tag: \"TransferLost\" };\n\n/** The attachment-safe part of the state. */\nexport const checkpointTranscriptDelivery = (\n state: EDATranscriptDeliveryState,\n): EDATranscriptDeliveryCheckpoint => ({\n lastAckedFrameId: state.lastAckedFrameId,\n nextFrameId: state.nextFrameId,\n inFlight: state.inFlight,\n nextUpdateSeq: state.nextUpdateSeq,\n completedUpdateSeq: state.completedUpdateSeq,\n completedThroughSeq: state.completedThroughSeq,\n appliedUpdateSeq: state.appliedUpdateSeq,\n appliedThroughSeq: state.appliedThroughSeq,\n ...(state.transfer === undefined ? {} : { transfer: state.transfer }),\n ...(state.subscription === undefined ? {} : { subscription: state.subscription }),\n requests: state.requests,\n});\n\n/** Frames that may be sent before the client's next receipt. */\nexport const transcriptDeliveryCapacity = (state: EDATranscriptDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\n/** Lazily enforced ACK deadline: no resident timer, checked on each transition. */\nexport const transcriptAckTimedOut = (state: EDATranscriptDeliveryState, nowMs: number): boolean =>\n state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs);\n\n/** Result of a transition that may emit frames. */\nexport interface EDATranscriptSendResult {\n readonly state: EDATranscriptDeliveryState;\n /** Encoded frames to send in order, after persisting `state`. */\n readonly frames: ReadonlyArray<string>;\n}\n\n/**\n * Start sending one planned update, captured from its own snapshot.\n *\n * `subscription` becomes the base for the next update immediately: nothing else is sent until\n * this update's last frame is, so the client can only apply later updates on top of it. An\n * update within the frame limit is one frame; a larger one is chunked and as many chunks as\n * flow control allows are sent now, the rest staged.\n */\nexport const startTranscriptUpdate = (\n state: EDATranscriptDeliveryState,\n input: {\n readonly update: TranscriptUpdate;\n readonly encodedUpdate: string;\n readonly subscription: TranscriptSubscriptionBase;\n },\n limits: EDATranscriptDeliveryLimits,\n nowMs: number,\n):\n | ({ readonly _tag: \"Sending\" } & EDATranscriptSendResult)\n | { readonly _tag: \"TooLarge\"; readonly bytes: number } => {\n if (state.transfer !== undefined) {\n throw new Error(\"A transcript update cannot start while another is being transferred\");\n }\n if (input.update.updateSeq !== state.nextUpdateSeq) {\n throw new Error(\"A transcript update must carry the socket's next update seq\");\n }\n const updateSeq = input.update.updateSeq;\n const advanced: EDATranscriptDeliveryState = {\n ...state,\n nextUpdateSeq: updateSeq + 1,\n subscription: input.subscription,\n };\n const single = edaTranscriptUpdateFrameText(state.nextFrameId, input.encodedUpdate);\n if (utf8ByteLength(single) <= state.policy.maxFrameBytes) {\n return {\n _tag: \"Sending\",\n ...sendFrames(\n {\n ...advanced,\n completedUpdateSeq: updateSeq,\n completedThroughSeq: input.update.throughSeq,\n },\n [single],\n nowMs,\n ),\n };\n }\n const bytes = utf8ByteLength(input.encodedUpdate);\n if (bytes > limits.maxStagedBytes) return { _tag: \"TooLarge\", bytes };\n const chunks = splitEDATranscriptUpdate(input.encodedUpdate, state.policy.maxFrameBytes);\n return {\n _tag: \"Sending\",\n ...pumpTranscriptTransfer(\n {\n ...advanced,\n transfer: {\n updateSeq,\n throughSeq: input.update.throughSeq,\n count: chunks.length,\n nextIndex: 0,\n },\n staged: chunks,\n },\n nowMs,\n ),\n };\n};\n\n/** Send staged chunks of the transfer in progress while flow control allows. */\nexport const pumpTranscriptTransfer = (\n state: EDATranscriptDeliveryState,\n nowMs: number,\n): EDATranscriptSendResult => {\n let next = state;\n const frames: string[] = [];\n while (next.transfer !== undefined && transcriptDeliveryCapacity(next) > 0) {\n const transfer: EDATranscriptTransfer = next.transfer;\n const [data, ...rest] = next.staged;\n if (data === undefined) break;\n const text = edaTranscriptChunkFrameText({\n frameId: next.nextFrameId,\n updateSeq: transfer.updateSeq,\n index: transfer.nextIndex,\n count: transfer.count,\n data,\n });\n const nextIndex = transfer.nextIndex + 1;\n const done = nextIndex === transfer.count;\n const { transfer: _sent, ...withoutTransfer } = next;\n const sent = sendFrames(\n done\n ? {\n ...withoutTransfer,\n staged: [],\n completedUpdateSeq: transfer.updateSeq,\n completedThroughSeq: transfer.throughSeq,\n }\n : { ...next, staged: rest, transfer: { ...transfer, nextIndex } },\n [text],\n nowMs,\n );\n next = sent.state;\n frames.push(...sent.frames);\n }\n return { state: next, frames };\n};\n\nconst sendFrames = (\n state: EDATranscriptDeliveryState,\n texts: ReadonlyArray<string>,\n nowMs: number,\n): EDATranscriptSendResult => {\n // Frame texts embed `state.nextFrameId` onwards in order.\n const inFlight = texts.map((_, index) => ({\n frameId: state.nextFrameId + index,\n sentAtMs: nowMs,\n }));\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, ...inFlight],\n nextFrameId: state.nextFrameId + texts.length,\n },\n frames: texts,\n };\n};\n\n/** Outcome of one client ACK on a transcript socket. */\nexport type EDATranscriptAckResult =\n | { readonly _tag: \"Applied\"; readonly state: EDATranscriptDeliveryState }\n | { readonly _tag: \"Ignored\" }\n | { readonly _tag: \"ProtocolError\"; readonly message: string };\n\n/**\n * Apply one ACK. The receipt frees flow-control capacity cumulatively; the applied cut may only\n * name an update whose frames were all sent, and never moves backwards.\n */\nexport const onTranscriptAck = (\n state: EDATranscriptDeliveryState,\n ack: EDAWebSocketWireAckFrame,\n): EDATranscriptAckResult => {\n const appliedUpdateSeq = ack.appliedUpdateSeq ?? state.appliedUpdateSeq;\n const advancesApplied = appliedUpdateSeq > state.appliedUpdateSeq;\n if (ack.frameId <= state.lastAckedFrameId) {\n return advancesApplied\n ? { _tag: \"ProtocolError\", message: \"Duplicate ACK attempted to advance the applied cut\" }\n : { _tag: \"Ignored\" };\n }\n if (ack.frameId >= state.nextFrameId) {\n return { _tag: \"ProtocolError\", message: \"ACK referenced an unsent frame\" };\n }\n if (appliedUpdateSeq < state.appliedUpdateSeq) {\n return { _tag: \"ProtocolError\", message: \"ACK applied cut moved backwards\" };\n }\n if (appliedUpdateSeq > state.completedUpdateSeq) {\n return { _tag: \"ProtocolError\", message: \"ACK applied an incomplete update\" };\n }\n // `throughSeq` may fall between updates (a new incarnation, a building window), so it is not\n // monotonic; it must match the update it names when that update is the last one completed.\n if (\n advancesApplied &&\n appliedUpdateSeq === state.completedUpdateSeq &&\n ack.durableThroughSeq !== state.completedThroughSeq\n ) {\n return { _tag: \"ProtocolError\", message: \"ACK applied cut names another update's seq\" };\n }\n return {\n _tag: \"Applied\",\n state: {\n ...state,\n lastAckedFrameId: ack.frameId,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n appliedUpdateSeq,\n appliedThroughSeq: advancesApplied\n ? SequenceNumber.make(ack.durableThroughSeq)\n : state.appliedThroughSeq,\n },\n };\n};\n\n/** Queue one client request, or report that the client exceeded its request bound. */\nexport const enqueueTranscriptRequest = (\n state: EDATranscriptDeliveryState,\n request: EDATranscriptRequestFrame,\n limits: EDATranscriptDeliveryLimits,\n): EDATranscriptDeliveryState | undefined =>\n state.requests.length >= limits.maxPendingRequests\n ? undefined\n : { ...state, requests: [...state.requests, request] };\n"],"mappings":";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BAC3B,OAAO;EAAE,MAAM;EAAiB,SAAS;CAAkC;CAE7E,IAAI,mBAAmB,MAAM,oBAC3B,OAAO;EAAE,MAAM;EAAiB,SAAS;CAAmC;CAI9E,IACE,mBACA,qBAAqB,MAAM,sBAC3B,IAAI,sBAAsB,MAAM,qBAEhC,OAAO;EAAE,MAAM;EAAiB,SAAS;CAA6C;CAExF,OAAO;EACL,MAAM;EACN,OAAO;GACL,GAAG;GACH,kBAAkB,IAAI;GACtB,UAAU,MAAM,SAAS,QAAQ,UAAU,MAAM,UAAU,IAAI,OAAO;GACtE;GACA,mBAAmB,kBACf,eAAe,KAAK,IAAI,iBAAiB,IACzC,MAAM;EACZ;CACF;AACF;;AAGA,MAAa,4BACX,OACA,SACA,WAEA,MAAM,SAAS,UAAU,OAAO,qBAC5B,KAAA,IACA;CAAE,GAAG;CAAO,UAAU,CAAC,GAAG,MAAM,UAAU,OAAO;AAAE"}
@@ -0,0 +1,113 @@
1
+ import { h as SequenceNumber } from "./core-BcimKMIv.js";
2
+ import { A as TranscriptDefinition, At as TranscriptToolRecord, C as TranscriptVersionMeta, D as TranscriptWindowSelector, E as TranscriptWindowLimits, Ft as TranscriptVersion, H as AssistantRecordId, Nt as TranscriptUserRecord, S as TranscriptReadiness, T as TranscriptWindow, gt as TranscriptOrderKey, jt as TranscriptTopLevelRecord, mt as TranscriptLogIncarnation, t as CommittedDurableEvent, v as TranscriptCursorMismatch, vt as TranscriptRecord, xt as TranscriptRecordId } from "./session-store-CQxg9U82.js";
3
+ import * as Schema from "effect/Schema";
4
+ import * as Result from "effect/Result";
5
+ //#region src/transcript/plan.d.ts
6
+ /**
7
+ * Secondary keys that resolve to a record through an indexed join, never an in-memory map.
8
+ *
9
+ * - `messageId`: every message id a user submission has carried, including replacement ids.
10
+ * - `idempotencyKey`: a submitting command's caller-owned retry key.
11
+ * - `runId`: every run of a run group, so continuations resolve to the root's group.
12
+ * - `runCommand`: commands owned by a run group; a run that reuses them continues the group.
13
+ * - `toolPart`: `<inferenceId>/<providerPartId>`, linking an assistant tool-call part to its tool.
14
+ */
15
+ declare const TranscriptAliasNamespace: Schema.Literals<readonly ["messageId", "idempotencyKey", "runId", "runCommand", "toolPart"]>;
16
+ type TranscriptAliasNamespace = typeof TranscriptAliasNamespace.Type;
17
+ /** One alias row: `(namespace, key)` resolves to `recordId` within one version. */
18
+ interface TranscriptAlias {
19
+ readonly namespace: TranscriptAliasNamespace;
20
+ readonly key: string;
21
+ readonly recordId: TranscriptRecordId;
22
+ }
23
+ /**
24
+ * Synchronous indexed reads of one transcript version, as committed before the batch.
25
+ *
26
+ * Adapters back this with indexed storage reads so the interpreter can run inside a synchronous
27
+ * transaction (Cloudflare `storage.transactionSync`). Reads see no uncommitted plan; the
28
+ * interpreter overlays its own in-batch changes.
29
+ */
30
+ interface TranscriptLookup {
31
+ /** Last seq already projected into this version. Events at or below it are skipped. */
32
+ readonly cursor: SequenceNumber;
33
+ readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;
34
+ readonly alias: (namespace: TranscriptAliasNamespace, key: string) => TranscriptRecordId | undefined;
35
+ /** Next free ordinal among records positioned at `anchorSeq`; 0 when none are. */
36
+ readonly nextOrdinal: (anchorSeq: SequenceNumber) => number;
37
+ }
38
+ /**
39
+ * Deterministic changes for one committed batch: the final state of every record the batch
40
+ * touched, in first-touch order, the aliases it introduced, and the new cursor.
41
+ *
42
+ * There are no deletions. Aliases are inserts only: an alias never moves to another record.
43
+ * Applying the plan and advancing the cursor must commit atomically with each other.
44
+ */
45
+ interface TranscriptChangePlan {
46
+ readonly records: ReadonlyArray<TranscriptRecord>;
47
+ readonly aliases: ReadonlyArray<TranscriptAlias>;
48
+ readonly throughSeq: SequenceNumber;
49
+ }
50
+ /**
51
+ * The interpretation boundary: a pure, synchronous function from a lookup, committed events and
52
+ * a definition to a change plan.
53
+ *
54
+ * It throws `TranscriptProjectionError` when the stored projection is inconsistent with the log.
55
+ * The adapter treats any throw as a recoverable projection failure of that version only.
56
+ */
57
+ type PlanTranscriptBatch = (lookup: TranscriptLookup, committed: ReadonlyArray<CommittedDurableEvent>, definition: TranscriptDefinition) => TranscriptChangePlan;
58
+ declare const TranscriptProjectionError_base: Schema.Class<TranscriptProjectionError, Schema.TaggedStruct<"TranscriptProjectionError", {
59
+ readonly message: Schema.String;
60
+ }>, import("effect/Cause").YieldableError>;
61
+ /** The stored projection cannot be advanced from the given lookup and batch. */
62
+ declare class TranscriptProjectionError extends TranscriptProjectionError_base {}
63
+ //#endregion
64
+ //#region src/transcript/window-read.d.ts
65
+ /**
66
+ * Synchronous indexed reads of the served version at one cut, as a store provides them.
67
+ *
68
+ * Window assembly (paging, dependency collection, byte budgeting and body references) is shared
69
+ * by every store through `readTranscriptWindowFrom`; a store only supplies these reads.
70
+ */
71
+ interface TranscriptWindowSource {
72
+ readonly incarnation: TranscriptLogIncarnation;
73
+ /** Maintenance state of the served (active) version; its cursor is the window's `throughSeq`. */
74
+ readonly meta: TranscriptVersionMeta;
75
+ /** False when this release no longer carries the served version (a missed session). */
76
+ readonly carried: boolean;
77
+ /** Top-level records before `key` (or before the end), newest first. */
78
+ readonly topLevelBefore: (key: TranscriptOrderKey | undefined, limit: number, inclusive: boolean) => ReadonlyArray<TranscriptTopLevelRecord>;
79
+ /** Top-level records after `key` (or after the start), oldest first. */
80
+ readonly topLevelAfter: (key: TranscriptOrderKey | undefined, limit: number, inclusive: boolean) => ReadonlyArray<TranscriptTopLevelRecord>;
81
+ readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;
82
+ readonly alias: (namespace: TranscriptAliasNamespace, key: string) => TranscriptRecordId | undefined;
83
+ /** Tool records of one assistant (the typed dependency lookup). */
84
+ readonly toolsOf: (assistantId: AssistantRecordId) => ReadonlyArray<TranscriptToolRecord>;
85
+ /** Every user record still waiting for the agent (the pending-membership index). */
86
+ readonly pendingUsers: () => ReadonlyArray<TranscriptUserRecord>;
87
+ }
88
+ /** Readiness of a served version: why its cut may be behind the log. */
89
+ declare const transcriptReadiness: (meta: TranscriptVersionMeta, carried: boolean) => TranscriptReadiness;
90
+ /** The empty window served while no version is servable yet. */
91
+ declare const buildingTranscriptWindow: (incarnation: TranscriptLogIncarnation, version: TranscriptVersion) => TranscriptWindow;
92
+ /**
93
+ * The empty window served while no version is active.
94
+ *
95
+ * It reads as `Building` while the build of `currentVersion` can still finish. A build that has
96
+ * frozen as failed is never retried (only a new definition repairs it), so once the build of
97
+ * `currentVersion` has failed the window is `Unreadable` and names that failure, rather than
98
+ * reading as building forever.
99
+ */
100
+ declare const inactiveTranscriptWindow: (incarnation: TranscriptLogIncarnation, currentVersion: TranscriptVersion, build: Pick<TranscriptVersionMeta, "version" | "status"> | undefined) => TranscriptWindow;
101
+ /**
102
+ * Assemble one window from a source at a single cut.
103
+ *
104
+ * The response never contains anything newer than the served version's cursor: a frozen (failed
105
+ * or no longer carried) version's rows, pending users and session context all stop at its last
106
+ * good cut, which is the degraded-read rule. Bodies above the inline limit become references;
107
+ * if the response still exceeds the byte budget, records are dropped from the far end of the
108
+ * selection, keeping at least one so paging always progresses.
109
+ */
110
+ declare const readTranscriptWindowFrom: (source: TranscriptWindowSource, selector: TranscriptWindowSelector, limits: TranscriptWindowLimits) => Result.Result<TranscriptWindow, TranscriptCursorMismatch>;
111
+ //#endregion
112
+ export { transcriptReadiness as a, TranscriptAliasNamespace as c, TranscriptProjectionError as d, readTranscriptWindowFrom as i, TranscriptChangePlan as l, buildingTranscriptWindow as n, PlanTranscriptBatch as o, inactiveTranscriptWindow as r, TranscriptAlias as s, TranscriptWindowSource as t, TranscriptLookup as u };
113
+ //# sourceMappingURL=window-read-CBZEJ84M.d.ts.map
@@ -0,0 +1,264 @@
1
+ import { SequenceNumber } from "./types/core.js";
2
+ import { u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
3
+ import { A as TranscriptRecordFromEnvelope, E as TranscriptOrder, W as isPendingTranscriptUserRecord, Y as transcriptRecordId } from "./records--54mZEBx.js";
4
+ import * as Context from "effect/Context";
5
+ import * as Schema from "effect/Schema";
6
+ import * as Result from "effect/Result";
7
+ //#region src/transcript/store.ts
8
+ /** A cursor minted for another log incarnation or transcript version. The client takes `Latest`. */
9
+ var TranscriptCursorMismatch = class extends Schema.TaggedError()("TranscriptCursorMismatch", { message: Schema.String }) {};
10
+ /** Transcript read port, provided alongside `EDASessionStore` by stores that maintain transcripts. */
11
+ var EDATranscriptStore = class extends Context.Service()("@effect-durable-agent/EDATranscriptStore") {};
12
+ //#endregion
13
+ //#region src/transcript/window-read.ts
14
+ /** Readiness of a served version: why its cut may be behind the log. */
15
+ const transcriptReadiness = (meta, carried) => {
16
+ if (!carried) return { _tag: "UpdatingHistory" };
17
+ switch (meta.status._tag) {
18
+ case "Ok": return { _tag: "Ready" };
19
+ case "Failed": return {
20
+ _tag: "Degraded",
21
+ failedAtSeq: meta.status.failedAtSeq,
22
+ error: meta.status.error
23
+ };
24
+ }
25
+ };
26
+ /** The empty window served while no version is servable yet. */
27
+ const buildingTranscriptWindow = (incarnation, version) => ({
28
+ incarnation,
29
+ version,
30
+ throughSeq: SequenceNumber.make(0),
31
+ records: [],
32
+ dependencies: [],
33
+ hasOlder: false,
34
+ hasNewer: false,
35
+ readiness: { _tag: "Building" }
36
+ });
37
+ /**
38
+ * The empty window served while no version is active.
39
+ *
40
+ * It reads as `Building` while the build of `currentVersion` can still finish. A build that has
41
+ * frozen as failed is never retried (only a new definition repairs it), so once the build of
42
+ * `currentVersion` has failed the window is `Unreadable` and names that failure, rather than
43
+ * reading as building forever.
44
+ */
45
+ const inactiveTranscriptWindow = (incarnation, currentVersion, build) => {
46
+ const building = buildingTranscriptWindow(incarnation, currentVersion);
47
+ if (build?.version !== currentVersion || build.status._tag !== "Failed") return building;
48
+ return {
49
+ ...building,
50
+ readiness: {
51
+ _tag: "Unreadable",
52
+ error: `transcript version ${build.version} failed to build at seq ${build.status.failedAtSeq}: ${build.status.error}`
53
+ }
54
+ };
55
+ };
56
+ const orderKey = (record) => ({
57
+ anchorSeq: record.position?.anchorSeq ?? 0,
58
+ ordinal: record.position?.ordinal ?? 0,
59
+ recordId: record.id
60
+ });
61
+ const cursorKey = (cursor) => ({
62
+ anchorSeq: cursor.anchorSeq,
63
+ ordinal: cursor.ordinal,
64
+ recordId: cursor.recordId
65
+ });
66
+ /**
67
+ * Assemble one window from a source at a single cut.
68
+ *
69
+ * The response never contains anything newer than the served version's cursor: a frozen (failed
70
+ * or no longer carried) version's rows, pending users and session context all stop at its last
71
+ * good cut, which is the degraded-read rule. Bodies above the inline limit become references;
72
+ * if the response still exceeds the byte budget, records are dropped from the far end of the
73
+ * selection, keeping at least one so paging always progresses.
74
+ */
75
+ const readTranscriptWindowFrom = (source, selector, limits) => {
76
+ const version = source.meta.version;
77
+ for (const cursor of selectorCursors(selector)) if (cursor.incarnation !== source.incarnation || cursor.version !== version) return Result.fail(new TranscriptCursorMismatch({ message: `cursor for ${cursor.incarnation}/${cursor.version} read against ${source.incarnation}/${version}` }));
78
+ const selected = selectTopLevel(source, selector, limits.maxRecords);
79
+ const keepNewest = selector._tag === "Latest" || selector._tag === "Page" && selector.direction === "before";
80
+ const kept = trimToBudget(dependencyGroups(source, selected.map((record) => withBodyRefs(record, limits.maxInlineBodyBytes)), limits.maxInlineBodyBytes), limits.maxBytes, keepNewest);
81
+ const top = kept.top;
82
+ const dependencies = flattenDependencies(kept);
83
+ const first = top[0];
84
+ const last = top[top.length - 1];
85
+ const [hasOlder, hasNewer] = first === void 0 || last === void 0 ? emptySelectionNeighbours(source, selector) : [source.topLevelBefore(orderKey(first), 1, false).length > 0, source.topLevelAfter(orderKey(last), 1, false).length > 0];
86
+ return Result.succeed({
87
+ incarnation: source.incarnation,
88
+ version,
89
+ throughSeq: source.meta.cursor,
90
+ records: top,
91
+ dependencies,
92
+ hasOlder,
93
+ hasNewer,
94
+ readiness: transcriptReadiness(source.meta, source.carried)
95
+ });
96
+ };
97
+ const selectorCursors = (selector) => {
98
+ switch (selector._tag) {
99
+ case "Latest": return [];
100
+ case "Page": return [selector.cursor];
101
+ case "Range": return [selector.from, selector.to];
102
+ }
103
+ };
104
+ const selectTopLevel = (source, selector, maxRecords) => {
105
+ switch (selector._tag) {
106
+ case "Latest": return [...source.topLevelBefore(void 0, Math.min(selector.count, maxRecords), false)].reverse();
107
+ case "Page": {
108
+ const count = Math.min(selector.count, maxRecords);
109
+ return selector.direction === "before" ? [...source.topLevelBefore(cursorKey(selector.cursor), count, false)].reverse() : source.topLevelAfter(cursorKey(selector.cursor), count, false);
110
+ }
111
+ case "Range": {
112
+ const to = cursorKey(selector.to);
113
+ return source.topLevelAfter(cursorKey(selector.from), maxRecords, true).filter((record) => TranscriptOrder(orderKey(record), to) <= 0);
114
+ }
115
+ }
116
+ };
117
+ const emptySelectionNeighbours = (source, selector) => {
118
+ switch (selector._tag) {
119
+ case "Latest": return [false, false];
120
+ case "Page": {
121
+ const key = cursorKey(selector.cursor);
122
+ return selector.direction === "before" ? [false, source.topLevelAfter(key, 1, true).length > 0] : [source.topLevelBefore(key, 1, true).length > 0, false];
123
+ }
124
+ case "Range": return [source.topLevelBefore(cursorKey(selector.from), 1, false).length > 0, source.topLevelAfter(cursorKey(selector.to), 1, false).length > 0];
125
+ }
126
+ };
127
+ const dependencyGroups = (source, top, maxInlineBodyBytes) => {
128
+ const referenced = (records) => records.flatMap((record) => record === void 0 ? [] : [withBodyRefs(record, maxInlineBodyBytes)]);
129
+ return {
130
+ top,
131
+ leading: referenced([source.record(transcriptRecordId.session)]),
132
+ perTop: top.map((record) => referenced(recordDependencies(source, record))),
133
+ trailing: referenced([...source.pendingUsers()].filter(isPendingTranscriptUserRecord).sort((left, right) => left.submittedSeq - right.submittedSeq || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)))
134
+ };
135
+ };
136
+ /** One top-level record's run group and tools, in part order. */
137
+ const recordDependencies = (source, record) => {
138
+ switch (record.kind) {
139
+ case "assistant": {
140
+ const partOrder = new Map(record.parts.flatMap((part, index) => part._tag === "ToolCall" && part.toolId !== void 0 ? [[part.toolId, index]] : []));
141
+ const tools = [...source.toolsOf(record.id)].sort((left, right) => (partOrder.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (partOrder.get(right.id) ?? Number.MAX_SAFE_INTEGER) || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
142
+ return [...record.runGroupId === void 0 ? [] : [source.record(record.runGroupId)], ...tools];
143
+ }
144
+ case "user": {
145
+ const runId = record.state._tag === "Consumed" ? record.state.runId : void 0;
146
+ const groupId = (runId === void 0 ? void 0 : source.alias("runId", runId)) ?? source.alias("runCommand", record.commandId);
147
+ return groupId === void 0 ? [] : [source.record(groupId)];
148
+ }
149
+ case "compaction": return [];
150
+ }
151
+ };
152
+ /** Each dependency once, where it first appears. */
153
+ const flattenDependencies = (groups) => {
154
+ const dependencies = /* @__PURE__ */ new Map();
155
+ for (const record of [
156
+ ...groups.leading,
157
+ ...groups.perTop.flat(),
158
+ ...groups.trailing
159
+ ]) if (!dependencies.has(record.id)) dependencies.set(record.id, record);
160
+ return Array.from(dependencies.values());
161
+ };
162
+ /**
163
+ * Drop records from the far end of the selection until the window (records and their
164
+ * dependencies) fits `maxBytes`, keeping at least one.
165
+ *
166
+ * Each record is measured once. A dependency's bytes count while any kept record (or the
167
+ * window itself, for the session context and pending users) needs it, so dropping a record
168
+ * subtracts its own bytes and those of the dependencies only it needed. The result equals
169
+ * re-measuring the whole window after every drop, in time linear in the selection.
170
+ */
171
+ const trimToBudget = (groups, maxBytes, keepNewest) => {
172
+ const { top } = groups;
173
+ if (top.length <= 1) return groups;
174
+ const users = /* @__PURE__ */ new Map();
175
+ const sizes = /* @__PURE__ */ new Map();
176
+ const sizeOf = (record) => {
177
+ const known = sizes.get(record.id);
178
+ if (known !== void 0) return known;
179
+ const bytes = recordBytes(record);
180
+ sizes.set(record.id, bytes);
181
+ return bytes;
182
+ };
183
+ let total = 0;
184
+ const need = (record) => {
185
+ const count = users.get(record.id) ?? 0;
186
+ if (count === 0) total += sizeOf(record);
187
+ users.set(record.id, count + 1);
188
+ };
189
+ const release = (record) => {
190
+ const count = (users.get(record.id) ?? 0) - 1;
191
+ if (count === 0) total -= sizeOf(record);
192
+ users.set(record.id, count);
193
+ };
194
+ const ownDependencies = groups.perTop.map((records) => [...new Map(records.map((record) => [record.id, record])).values()]);
195
+ const topBytes = top.map(recordBytes);
196
+ for (const record of [...groups.leading, ...groups.trailing]) need(record);
197
+ top.forEach((_, index) => {
198
+ total += topBytes[index] ?? 0;
199
+ ownDependencies[index]?.forEach(need);
200
+ });
201
+ let from = 0;
202
+ let to = top.length;
203
+ while (to - from > 1 && total > maxBytes) {
204
+ const dropped = keepNewest ? from++ : --to;
205
+ total -= topBytes[dropped] ?? 0;
206
+ ownDependencies[dropped]?.forEach(release);
207
+ }
208
+ return {
209
+ ...groups,
210
+ top: top.slice(from, to),
211
+ perTop: groups.perTop.slice(from, to)
212
+ };
213
+ };
214
+ const encoder = new TextEncoder();
215
+ const encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);
216
+ const jsonBytes = (value) => {
217
+ const json = JSON.stringify(value);
218
+ return json === void 0 ? 0 : encoder.encode(json).length;
219
+ };
220
+ /** A record's size in the window, as it is encoded on the wire. */
221
+ const recordBytes = (record) => jsonBytes(encodeRecord(record));
222
+ const bodyRef = (body, maxInlineBodyBytes) => {
223
+ if (body._tag === "Ref") return body;
224
+ const byteLength = jsonBytes(body.value);
225
+ return byteLength <= maxInlineBodyBytes ? body : {
226
+ _tag: "Ref",
227
+ source: body.source,
228
+ byteLength: NonNegativeInt.make(byteLength)
229
+ };
230
+ };
231
+ /** Replace inline bodies above the limit with references to their immutable log source. */
232
+ const withBodyRefs = (record, maxInlineBodyBytes) => {
233
+ switch (record.kind) {
234
+ case "tool": {
235
+ const tool = {
236
+ ...record,
237
+ ...record.params === void 0 ? {} : { params: bodyRef(record.params, maxInlineBodyBytes) },
238
+ lifecycle: record.lifecycle._tag === "Completed" ? {
239
+ _tag: "Completed",
240
+ result: bodyRef(record.lifecycle.result, maxInlineBodyBytes)
241
+ } : record.lifecycle
242
+ };
243
+ return {
244
+ ...record,
245
+ ...tool
246
+ };
247
+ }
248
+ case "assistant": {
249
+ const parts = record.parts.map((part) => part._tag === "ToolResult" ? {
250
+ ...part,
251
+ result: bodyRef(part.result, maxInlineBodyBytes)
252
+ } : part);
253
+ return {
254
+ ...record,
255
+ parts
256
+ };
257
+ }
258
+ default: return record;
259
+ }
260
+ };
261
+ //#endregion
262
+ export { EDATranscriptStore as a, transcriptReadiness as i, inactiveTranscriptWindow as n, TranscriptCursorMismatch as o, readTranscriptWindowFrom as r, buildingTranscriptWindow as t };
263
+
264
+ //# sourceMappingURL=window-read-DPFAA1hM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"window-read-DPFAA1hM.js","names":[],"sources":["../src/transcript/store.ts","../src/transcript/window-read.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { EDASessionStoreError } from \"../services/session-store\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport type {\n TranscriptVersionMeta,\n TranscriptWindow,\n TranscriptWindowLimits,\n TranscriptWindowSelector,\n} from \"./window\";\n\n/**\n * The transcript definitions a store maintains, fixed when the store is constructed.\n *\n * `current` is what new sessions start with and every session converges to. `previous` is\n * carried for one release only, so a session not yet rebuilt keeps its active rows maintained.\n * A stored version that matches neither is frozen.\n */\nexport interface TranscriptMaintenanceConfig {\n readonly current: TranscriptDefinition;\n readonly previous?: TranscriptDefinition;\n}\n\n/** A cursor minted for another log incarnation or transcript version. The client takes `Latest`. */\nexport class TranscriptCursorMismatch extends Schema.TaggedError<TranscriptCursorMismatch>()(\n \"TranscriptCursorMismatch\",\n { message: Schema.String },\n) {}\n\n/**\n * Storage-level transcript reads for one session.\n *\n * Maintenance has no method here: the store runs it inside its own append transaction for every\n * carried, healthy version, so `EDASessionStore.append` semantics are unchanged. These reads never\n * construct the model runtime and never include live active content, which only the delivery\n * layer can capture.\n */\nexport interface EDATranscriptStoreShape {\n /** Read one complete window of the served version at a single cut. */\n readonly readTranscriptWindow: (\n selector: TranscriptWindowSelector,\n limits: TranscriptWindowLimits,\n ) => Effect.Effect<TranscriptWindow, EDASessionStoreError | TranscriptCursorMismatch>;\n /** Maintenance state of every version present, for builders, backfill proofs and alerts. */\n readonly readTranscriptMeta: Effect.Effect<\n ReadonlyArray<TranscriptVersionMeta>,\n EDASessionStoreError\n >;\n}\n\n/** Transcript read port, provided alongside `EDASessionStore` by stores that maintain transcripts. */\nexport class EDATranscriptStore extends Context.Service<\n EDATranscriptStore,\n EDATranscriptStoreShape\n>()(\"@effect-durable-agent/EDATranscriptStore\") {}\n","import * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { NonNegativeInt } from \"../types/events/envelope\";\nimport type { TranscriptAliasNamespace } from \"./plan\";\nimport {\n TranscriptOrder,\n TranscriptRecordFromEnvelope,\n isPendingTranscriptUserRecord,\n transcriptRecordId,\n type AssistantRecordId,\n type TranscriptAssistantPart,\n type TranscriptBody,\n type TranscriptCursor,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecord,\n type TranscriptRecordId,\n type TranscriptToolRecord,\n type TranscriptTopLevelRecord,\n type TranscriptUserRecord,\n type TranscriptVersion,\n} from \"./records\";\nimport { TranscriptCursorMismatch } from \"./store\";\nimport type {\n TranscriptReadiness,\n TranscriptVersionMeta,\n TranscriptWindow,\n TranscriptWindowLimits,\n TranscriptWindowSelector,\n} from \"./window\";\n\n/**\n * Synchronous indexed reads of the served version at one cut, as a store provides them.\n *\n * Window assembly (paging, dependency collection, byte budgeting and body references) is shared\n * by every store through `readTranscriptWindowFrom`; a store only supplies these reads.\n */\nexport interface TranscriptWindowSource {\n readonly incarnation: TranscriptLogIncarnation;\n /** Maintenance state of the served (active) version; its cursor is the window's `throughSeq`. */\n readonly meta: TranscriptVersionMeta;\n /** False when this release no longer carries the served version (a missed session). */\n readonly carried: boolean;\n /** Top-level records before `key` (or before the end), newest first. */\n readonly topLevelBefore: (\n key: TranscriptOrderKey | undefined,\n limit: number,\n inclusive: boolean,\n ) => ReadonlyArray<TranscriptTopLevelRecord>;\n /** Top-level records after `key` (or after the start), oldest first. */\n readonly topLevelAfter: (\n key: TranscriptOrderKey | undefined,\n limit: number,\n inclusive: boolean,\n ) => ReadonlyArray<TranscriptTopLevelRecord>;\n readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;\n readonly alias: (\n namespace: TranscriptAliasNamespace,\n key: string,\n ) => TranscriptRecordId | undefined;\n /** Tool records of one assistant (the typed dependency lookup). */\n readonly toolsOf: (assistantId: AssistantRecordId) => ReadonlyArray<TranscriptToolRecord>;\n /** Every user record still waiting for the agent (the pending-membership index). */\n readonly pendingUsers: () => ReadonlyArray<TranscriptUserRecord>;\n}\n\n/** Readiness of a served version: why its cut may be behind the log. */\nexport const transcriptReadiness = (\n meta: TranscriptVersionMeta,\n carried: boolean,\n): TranscriptReadiness => {\n if (!carried) return { _tag: \"UpdatingHistory\" };\n switch (meta.status._tag) {\n case \"Ok\":\n return { _tag: \"Ready\" };\n case \"Failed\":\n return {\n _tag: \"Degraded\",\n failedAtSeq: meta.status.failedAtSeq,\n error: meta.status.error,\n };\n }\n};\n\n/** The empty window served while no version is servable yet. */\nexport const buildingTranscriptWindow = (\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n): TranscriptWindow => ({\n incarnation,\n version,\n throughSeq: SequenceNumber.make(0),\n records: [],\n dependencies: [],\n hasOlder: false,\n hasNewer: false,\n readiness: { _tag: \"Building\" },\n});\n\n/**\n * The empty window served while no version is active.\n *\n * It reads as `Building` while the build of `currentVersion` can still finish. A build that has\n * frozen as failed is never retried (only a new definition repairs it), so once the build of\n * `currentVersion` has failed the window is `Unreadable` and names that failure, rather than\n * reading as building forever.\n */\nexport const inactiveTranscriptWindow = (\n incarnation: TranscriptLogIncarnation,\n currentVersion: TranscriptVersion,\n build: Pick<TranscriptVersionMeta, \"version\" | \"status\"> | undefined,\n): TranscriptWindow => {\n const building = buildingTranscriptWindow(incarnation, currentVersion);\n if (build?.version !== currentVersion || build.status._tag !== \"Failed\") return building;\n return {\n ...building,\n readiness: {\n _tag: \"Unreadable\",\n error: `transcript version ${build.version} failed to build at seq ${build.status.failedAtSeq}: ${build.status.error}`,\n },\n };\n};\n\nconst orderKey = (record: TranscriptTopLevelRecord): TranscriptOrderKey => ({\n anchorSeq: record.position?.anchorSeq ?? 0,\n ordinal: record.position?.ordinal ?? 0,\n recordId: record.id,\n});\n\nconst cursorKey = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\n/**\n * Assemble one window from a source at a single cut.\n *\n * The response never contains anything newer than the served version's cursor: a frozen (failed\n * or no longer carried) version's rows, pending users and session context all stop at its last\n * good cut, which is the degraded-read rule. Bodies above the inline limit become references;\n * if the response still exceeds the byte budget, records are dropped from the far end of the\n * selection, keeping at least one so paging always progresses.\n */\nexport const readTranscriptWindowFrom = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n limits: TranscriptWindowLimits,\n): Result.Result<TranscriptWindow, TranscriptCursorMismatch> => {\n const version = source.meta.version;\n for (const cursor of selectorCursors(selector)) {\n if (cursor.incarnation !== source.incarnation || cursor.version !== version) {\n return Result.fail(\n new TranscriptCursorMismatch({\n message: `cursor for ${cursor.incarnation}/${cursor.version} read against ${source.incarnation}/${version}`,\n }),\n );\n }\n }\n\n const selected = selectTopLevel(source, selector, limits.maxRecords);\n // Latest and Page(before) keep the newest records when trimming; the others keep the oldest.\n const keepNewest =\n selector._tag === \"Latest\" || (selector._tag === \"Page\" && selector.direction === \"before\");\n const kept = trimToBudget(\n dependencyGroups(\n source,\n selected.map((record) => withBodyRefs(record, limits.maxInlineBodyBytes)),\n limits.maxInlineBodyBytes,\n ),\n limits.maxBytes,\n keepNewest,\n );\n const top = kept.top;\n const dependencies = flattenDependencies(kept);\n\n const first = top[0];\n const last = top[top.length - 1];\n const [hasOlder, hasNewer] =\n first === undefined || last === undefined\n ? emptySelectionNeighbours(source, selector)\n : [\n source.topLevelBefore(orderKey(first), 1, false).length > 0,\n source.topLevelAfter(orderKey(last), 1, false).length > 0,\n ];\n\n return Result.succeed({\n incarnation: source.incarnation,\n version,\n throughSeq: source.meta.cursor,\n records: top,\n dependencies,\n hasOlder,\n hasNewer,\n readiness: transcriptReadiness(source.meta, source.carried),\n });\n};\n\nconst selectorCursors = (selector: TranscriptWindowSelector): ReadonlyArray<TranscriptCursor> => {\n switch (selector._tag) {\n case \"Latest\":\n return [];\n case \"Page\":\n return [selector.cursor];\n case \"Range\":\n return [selector.from, selector.to];\n }\n};\n\nconst selectTopLevel = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n maxRecords: number,\n): ReadonlyArray<TranscriptTopLevelRecord> => {\n switch (selector._tag) {\n case \"Latest\":\n return [\n ...source.topLevelBefore(undefined, Math.min(selector.count, maxRecords), false),\n ].reverse();\n case \"Page\": {\n const count = Math.min(selector.count, maxRecords);\n return selector.direction === \"before\"\n ? [...source.topLevelBefore(cursorKey(selector.cursor), count, false)].reverse()\n : source.topLevelAfter(cursorKey(selector.cursor), count, false);\n }\n case \"Range\": {\n const to = cursorKey(selector.to);\n return source\n .topLevelAfter(cursorKey(selector.from), maxRecords, true)\n .filter((record) => TranscriptOrder(orderKey(record), to) <= 0);\n }\n }\n};\n\nconst emptySelectionNeighbours = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n): readonly [boolean, boolean] => {\n switch (selector._tag) {\n case \"Latest\":\n return [false, false];\n case \"Page\": {\n const key = cursorKey(selector.cursor);\n return selector.direction === \"before\"\n ? [false, source.topLevelAfter(key, 1, true).length > 0]\n : [source.topLevelBefore(key, 1, true).length > 0, false];\n }\n case \"Range\":\n return [\n source.topLevelBefore(cursorKey(selector.from), 1, false).length > 0,\n source.topLevelAfter(cursorKey(selector.to), 1, false).length > 0,\n ];\n }\n};\n\n/**\n * A selection with its dependencies grouped by owner: the session context first, each top-level\n * record's run group and tools in part order, then pending users. A record may appear in several\n * groups; the window carries it once, where it first appears.\n */\ninterface DependencyGroups {\n readonly top: ReadonlyArray<TranscriptTopLevelRecord>;\n readonly leading: ReadonlyArray<TranscriptRecord>;\n /** Dependencies of `top[i]`, in order. */\n readonly perTop: ReadonlyArray<ReadonlyArray<TranscriptRecord>>;\n readonly trailing: ReadonlyArray<TranscriptRecord>;\n}\n\nconst dependencyGroups = (\n source: TranscriptWindowSource,\n top: ReadonlyArray<TranscriptTopLevelRecord>,\n maxInlineBodyBytes: number,\n): DependencyGroups => {\n const referenced = (records: ReadonlyArray<TranscriptRecord | undefined>) =>\n records.flatMap((record) =>\n record === undefined ? [] : [withBodyRefs(record, maxInlineBodyBytes)],\n );\n return {\n top,\n leading: referenced([source.record(transcriptRecordId.session)]),\n perTop: top.map((record) => referenced(recordDependencies(source, record))),\n trailing: referenced(\n [...source.pendingUsers()]\n .filter(isPendingTranscriptUserRecord)\n .sort(\n (left, right) =>\n left.submittedSeq - right.submittedSeq ||\n (left.id < right.id ? -1 : left.id > right.id ? 1 : 0),\n ),\n ),\n };\n};\n\n/** One top-level record's run group and tools, in part order. */\nconst recordDependencies = (\n source: TranscriptWindowSource,\n record: TranscriptTopLevelRecord,\n): ReadonlyArray<TranscriptRecord | undefined> => {\n switch (record.kind) {\n case \"assistant\": {\n const partOrder = new Map(\n record.parts.flatMap((part, index) =>\n part._tag === \"ToolCall\" && part.toolId !== undefined ? [[part.toolId, index]] : [],\n ),\n );\n const tools = [...source.toolsOf(record.id)].sort(\n (left, right) =>\n (partOrder.get(left.id) ?? Number.MAX_SAFE_INTEGER) -\n (partOrder.get(right.id) ?? Number.MAX_SAFE_INTEGER) ||\n (left.id < right.id ? -1 : left.id > right.id ? 1 : 0),\n );\n return [\n ...(record.runGroupId === undefined ? [] : [source.record(record.runGroupId)]),\n ...tools,\n ];\n }\n case \"user\": {\n // The consuming run's group, or, for a submission committed at its own run's start (the\n // interrupt path, which records no run on the user), the group that owns its command.\n const runId = record.state._tag === \"Consumed\" ? record.state.runId : undefined;\n const groupId =\n (runId === undefined ? undefined : source.alias(\"runId\", runId)) ??\n source.alias(\"runCommand\", record.commandId);\n return groupId === undefined ? [] : [source.record(groupId)];\n }\n case \"compaction\":\n return [];\n }\n};\n\n/** Each dependency once, where it first appears. */\nconst flattenDependencies = (groups: DependencyGroups): ReadonlyArray<TranscriptRecord> => {\n const dependencies = new Map<string, TranscriptRecord>();\n for (const record of [...groups.leading, ...groups.perTop.flat(), ...groups.trailing]) {\n if (!dependencies.has(record.id)) dependencies.set(record.id, record);\n }\n return Array.from(dependencies.values());\n};\n\n/**\n * Drop records from the far end of the selection until the window (records and their\n * dependencies) fits `maxBytes`, keeping at least one.\n *\n * Each record is measured once. A dependency's bytes count while any kept record (or the\n * window itself, for the session context and pending users) needs it, so dropping a record\n * subtracts its own bytes and those of the dependencies only it needed. The result equals\n * re-measuring the whole window after every drop, in time linear in the selection.\n */\nconst trimToBudget = (\n groups: DependencyGroups,\n maxBytes: number,\n keepNewest: boolean,\n): DependencyGroups => {\n const { top } = groups;\n if (top.length <= 1) return groups;\n const users = new Map<string, number>();\n const sizes = new Map<string, number>();\n const sizeOf = (record: TranscriptRecord) => {\n const known = sizes.get(record.id);\n if (known !== undefined) return known;\n const bytes = recordBytes(record);\n sizes.set(record.id, bytes);\n return bytes;\n };\n let total = 0;\n const need = (record: TranscriptRecord) => {\n const count = users.get(record.id) ?? 0;\n if (count === 0) total += sizeOf(record);\n users.set(record.id, count + 1);\n };\n const release = (record: TranscriptRecord) => {\n const count = (users.get(record.id) ?? 0) - 1;\n if (count === 0) total -= sizeOf(record);\n users.set(record.id, count);\n };\n // Within one record a dependency counts once, as the window carries it once.\n const ownDependencies = groups.perTop.map((records) => [\n ...new Map(records.map((record) => [record.id, record])).values(),\n ]);\n const topBytes = top.map(recordBytes);\n for (const record of [...groups.leading, ...groups.trailing]) need(record);\n top.forEach((_, index) => {\n total += topBytes[index] ?? 0;\n ownDependencies[index]?.forEach(need);\n });\n let from = 0;\n let to = top.length;\n while (to - from > 1 && total > maxBytes) {\n const dropped = keepNewest ? from++ : --to;\n total -= topBytes[dropped] ?? 0;\n ownDependencies[dropped]?.forEach(release);\n }\n return { ...groups, top: top.slice(from, to), perTop: groups.perTop.slice(from, to) };\n};\n\nconst encoder = new TextEncoder();\nconst encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);\n\nconst jsonBytes = (value: unknown): number => {\n const json = JSON.stringify(value);\n return json === undefined ? 0 : encoder.encode(json).length;\n};\n\n/** A record's size in the window, as it is encoded on the wire. */\nconst recordBytes = (record: TranscriptRecord): number => jsonBytes(encodeRecord(record));\n\nconst bodyRef = (body: TranscriptBody, maxInlineBodyBytes: number): TranscriptBody => {\n if (body._tag === \"Ref\") return body;\n const byteLength = jsonBytes(body.value);\n return byteLength <= maxInlineBodyBytes\n ? body\n : { _tag: \"Ref\", source: body.source, byteLength: NonNegativeInt.make(byteLength) };\n};\n\n/** Replace inline bodies above the limit with references to their immutable log source. */\nconst withBodyRefs = <R extends TranscriptRecord>(record: R, maxInlineBodyBytes: number): R => {\n switch (record.kind) {\n case \"tool\": {\n const tool: TranscriptToolRecord = {\n ...record,\n ...(record.params === undefined\n ? {}\n : { params: bodyRef(record.params, maxInlineBodyBytes) }),\n lifecycle:\n record.lifecycle._tag === \"Completed\"\n ? { _tag: \"Completed\", result: bodyRef(record.lifecycle.result, maxInlineBodyBytes) }\n : record.lifecycle,\n };\n return { ...record, ...tool };\n }\n case \"assistant\": {\n const parts = record.parts.map((part): TranscriptAssistantPart =>\n part._tag === \"ToolResult\"\n ? { ...part, result: bodyRef(part.result, maxInlineBodyBytes) }\n : part,\n );\n return { ...record, parts };\n }\n default:\n return record;\n }\n};\n"],"mappings":";;;;;;;;AA0BA,IAAa,2BA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